Rich Text Editor
The message box behind the chat composer. Enter sends, Shift+Enter adds a line, and headings, lists, links, and code fences work as you type. Put it in a composer InputGroup and hand it a toolbar.
Installation
pnpm dlx shadcn@latest add https://sprout.tulipfarm.ai/r/rich-text-editor.jsonCopies Rich Text Editor and the components it uses (Spinner) into your app, installs the packages, and adds the styles. Then import it from @/components/ui/rich-text-editor. Needs Tailwind CSS 4 and a components.json from shadcn init.
Install the following dependencies:
pnpm add clsx tailwind-merge @hugeicons/core-free-icons @hugeicons/react @tiptap/core @tiptap/extension-placeholder @tiptap/pm @tiptap/react @tiptap/starter-kitAdd Sprout base once per app: the
cn()helper and the design tokens.lib/sprout/classes.ts- Design tokens, for your global CSS
Add the components it uses: Spinner.
Copy and paste the following code into your project.
'use client'; import { useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type ReactNode, type Ref, } from 'react'; import { EditorContent, useEditor } from '@tiptap/react'; import { Extension, InputRule, type Editor, type Extensions, type JSONContent } from '@tiptap/core'; import { Fragment, Slice, type Node as ProseMirrorNode, type Schema } from '@tiptap/pm/model'; import { Plugin, PluginKey, TextSelection, type EditorState } from '@tiptap/pm/state'; import { canSplit } from '@tiptap/pm/transform'; import { Decoration, DecorationSet } from '@tiptap/pm/view'; import StarterKit from '@tiptap/starter-kit'; import Placeholder from '@tiptap/extension-placeholder'; import { CheckIcon } from '@/lib/sprout/icons/check-icon'; import { LinkOffIcon } from '@/lib/sprout/icons/link-off-icon'; import { cn } from '@/lib/sprout/classes'; import { KeywordHintBody } from '@/lib/sprout/keyword-hint'; import { accountLabel, hasHint, keywordPattern, objectReplacement, scanText, type KeywordHit, type KeywordPattern, } from '@/lib/sprout/keywords'; import { Spinner } from '@/components/ui/spinner'; export const richTextEditorSizeNames = ['md', 'sm'] as const; export type RichTextEditorSize = (typeof richTextEditorSizeNames)[number]; export type RichTextValue = JSONContent; export type RichTextEditorHandle = { focus: () => void; editor: () => Editor | null; setContent: (content: RichTextValue) => void; }; export interface RichTextKeywordAccount { id: string; label: string; } export interface RichTextKeyword { id: string; label: string; match?: readonly string[] | undefined; icon?: ReactNode; color?: string | undefined; connected?: boolean | undefined; account?: string | undefined; accounts?: readonly RichTextKeywordAccount[] | undefined; } export interface RichTextEditorProps { ref?: Ref<RichTextEditorHandle> | undefined; size?: RichTextEditorSize | null | undefined; condensed?: boolean | undefined; minRows?: number | undefined; value: RichTextValue; onChange: (value: RichTextValue) => void; onSend: () => void; extensions?: Extensions | undefined; keywords?: readonly RichTextKeyword[] | undefined; onKeywordConnect?: ((keyword: RichTextKeyword) => void) | undefined; onKeywordAccountChange?: ((keyword: RichTextKeyword, accountId: string) => void | Promise<unknown>) | undefined; placeholder?: string | undefined; disabled?: boolean | undefined; ariaLabel?: string | undefined; ariaInvalid?: boolean | undefined; ariaDescribedBy?: string | undefined; ariaExpanded?: boolean | undefined; ariaControls?: string | undefined; ariaActiveDescendant?: string | undefined; toolbarAddon?: ReactNode | undefined; className?: string | undefined; } const fenceLanguage = /^[\w+#.-]{1,32}$/; const typedFence = /```([\w+#.-]{1,32})?\s$/; const fenceOnly = /^```([\w+#.-]{1,32})?$/; const openingFence = /^ {0,3}(?:(`{3,})([^`]*)|(~{3,})(.*))$/; function isFenceLine(state: EditorState) { const { $from, empty } = state.selection; if (!empty || $from.parent.type.name !== 'paragraph' || $from.parentOffset !== $from.parent.content.size) return false; return fenceOnly.test($from.parent.textBetween(0, $from.parentOffset, undefined, '\n').split('\n').at(-1) ?? ''); } function markdownBlocks(schema: Schema, text: string) { const blocks: ProseMirrorNode[] = []; const lines = text.replace(/\r\n?/g, '\n').split('\n'); while (lines.length) { const line = lines.shift()!; const open = openingFence.exec(line); if (!open) { if (line.trim()) blocks.push(schema.nodes.paragraph!.create(null, schema.text(line))); continue; } const fence = open[1] ?? open[3]!; const info = (open[2] ?? open[4]!).trim().split(/\s/)[0]!; const closing = new RegExp(`^ {0,3}${fence[0]}{${fence.length},}\\s*$`); const end = lines.findIndex(candidate => closing.test(candidate)); const code = (end === -1 ? lines.splice(0) : lines.splice(0, end + 1).slice(0, -1)).join('\n'); blocks.push( schema.nodes.codeBlock!.create( { language: fenceLanguage.test(info) ? info : null }, code ? schema.text(code) : null, ), ); } return blocks; } const MarkdownCodeFence = Extension.create({ name: 'markdownCodeFence', priority: 1000, addInputRules() { return [ new InputRule({ find: typedFence, handler: ({ state, range, match }) => { const { tr, schema } = state; const codeBlock = schema.nodes.codeBlock!; const $from = tr.doc.resolve(range.from); if ($from.parent.type.name !== 'paragraph' || range.to !== $from.end()) return null; const before = $from.nodeBefore; const attrs = { language: match[1] ?? null }; if (!before) { if (!$from.node(-1).canReplaceWith($from.index(-1), $from.indexAfter(-1), codeBlock)) return null; tr.delete(range.from, range.to).setBlockType(range.from, range.from, codeBlock, attrs); return; } if (before.type.name !== 'hardBreak') return null; const splitAt = range.from - before.nodeSize; tr.delete(splitAt, range.to); if (!canSplit(tr.doc, splitAt, 1, [{ type: codeBlock, attrs }])) return null; tr.split(splitAt, 1, [{ type: codeBlock, attrs }]); tr.setSelection(TextSelection.create(tr.doc, splitAt + 2)); }, }), ]; }, addProseMirrorPlugins() { return [ new Plugin({ key: new PluginKey('markdownCodeFencePaste'), props: { handlePaste: (view, event) => { const text = event.clipboardData?.getData('text/plain') ?? ''; if ( view.state.selection.$from.parent.type.spec.code || !text.split(/\r\n?|\n/).some(line => openingFence.test(line)) ) return false; const blocks = markdownBlocks(view.state.schema, text); const slice = new Slice( Fragment.from(blocks), blocks[0]?.type.name === 'paragraph' ? 1 : 0, blocks.at(-1)?.type.name === 'paragraph' ? 1 : 0, ); view.dispatch(view.state.tr.replaceSelection(slice).scrollIntoView().setMeta('paste', true)); return true; }, }, }), ]; }, }); const MessageFormatting = Extension.create({ name: 'messageFormatting', extendMarkSchema(extension) { if (extension.name === 'link') return { inclusive: false }; return {}; }, addProseMirrorPlugins() { return [ new Plugin({ key: new PluginKey('clearDeletedLink'), appendTransaction(transactions, oldState, state) { const link = state.schema.marks.link; if ( !link || !transactions.some(transaction => transaction.docChanged) || state.doc.content.size >= oldState.doc.content.size || !state.selection.empty || !state.storedMarks?.some(mark => mark.type === link) ) return null; if ( state.selection.$from.parent.content.size && state.selection.$from.marks().some(mark => mark.type === link) ) return null; return state.tr.removeStoredMark(link); }, }), ]; }, }); function within(state: EditorState, name: string) { const { $from } = state.selection; for (let depth = $from.depth; depth > 0; depth -= 1) if ($from.node(depth).type.name === name) return true; return false; } type KeywordSource = { pattern: KeywordPattern | null; signature: string; revision: number; focused: boolean; glyph: (id: string) => Element | null; connect: (id: string) => void; }; type KeywordState = { all: KeywordHit[]; hits: KeywordHit[]; pending: number | null; decorations: DecorationSet }; const statusTemplate = 'sprout-status'; const keywordKey = new PluginKey<KeywordState>('richTextKeywords'); function docKeywords(doc: ProseMirrorNode, pattern: KeywordPattern | null) { const hits: KeywordHit[] = []; if (!pattern) return hits; doc.descendants((node, pos) => { if (!node.isTextblock) return true; if (node.type.spec.code) return false; let text = ''; node.forEach(child => { text += child.isText && !child.marks.some(mark => mark.type.spec.code || mark.type.name === 'link') ? child.text! : objectReplacement.repeat(child.nodeSize); }); scanText(text, pattern, pos + 1, hits); return false; }); return hits; } export function findKeywords(value: RichTextValue, keywords: readonly RichTextKeyword[]): RichTextKeyword[] { const pattern = keywordPattern(keywords); if (!pattern) return []; const hits: KeywordHit[] = []; const visit = (node: JSONContent) => { if (node.type === 'codeBlock' || !node.content) return; if (!node.content.some(child => child.type === 'text')) return node.content.forEach(visit); const text = node.content .map(child => child.type === 'text' && !child.marks?.some(mark => mark.type === 'code' || mark.type === 'link') ? (child.text ?? '') : objectReplacement, ) .join(''); scanText(text, pattern, 0, hits); }; visit(value); return [...new Set(hits.map(hit => hit.keyword))]; } export function keywordAccounts(value: RichTextValue, keywords: readonly RichTextKeyword[]): Record<string, string> { return Object.fromEntries( findKeywords(value, keywords) .filter(keyword => keyword.connected !== false && keyword.account) .map(keyword => [keyword.id, keyword.account!]), ); } function keywordWidget(kind: 'icon' | 'status', keyword: RichTextKeyword, glyph: Element | null) { const widget = document.createElement('span'); widget.className = `sprout-rich-text-keyword-${kind}`; widget.contentEditable = 'false'; widget.setAttribute('aria-hidden', 'true'); widget.dataset.keyword = keyword.id; widget.dataset.connected = String(keyword.connected !== false); const box = document.createElement('span'); box.className = 'sprout-rich-text-keyword-glyph'; if (glyph) box.append(glyph.cloneNode(true)); widget.append(box); return widget; } function keywordDecorations(doc: ProseMirrorNode, hits: KeywordHit[], source: KeywordSource) { const seen = new Map<string, number>(); const decorations: Decoration[] = []; for (const { keyword, from, to } of hits) { const index = seen.get(keyword.id) ?? 0; seen.set(keyword.id, index + 1); const key = `${keyword.id}:${index}:${source.revision}`; const connected = keyword.connected !== false; const icon = keyword.icon != null ? source.glyph(keyword.id) : null; decorations.push( Decoration.inline(from, to, { class: 'sprout-rich-text-keyword', 'data-keyword': keyword.id, 'data-connected': String(connected), ...(icon && { 'data-icon': '' }), ...(keyword.color && { 'data-tinted': '', style: `--sprout-rich-text-keyword-color: ${keyword.color}` }), }), ); if (icon) decorations.push( Decoration.widget(from, () => keywordWidget('icon', keyword, icon), { side: -1, key: `${key}:icon` }), ); if (!connected) decorations.push( Decoration.widget( to, () => { const widget = keywordWidget('status', keyword, source.glyph(statusTemplate)); widget.addEventListener('mousedown', event => { event.preventDefault(); source.connect(keyword.id); }); return widget; }, { side: 1, key: `${key}:status`, stopEvent: () => true }, ), ); } return DecorationSet.create(doc, decorations); } function stillTyping(state: EditorState, hit: KeywordHit) { const { $from, empty, from } = state.selection; if (!empty || from <= hit.from || $from.start() !== state.doc.resolve(hit.from).start()) return false; return from <= hit.to || /^\S*$/.test(state.doc.textBetween(hit.to, from, '\n', objectReplacement)); } function keywordExtension(source: KeywordSource) { const build = (state: EditorState, all: KeywordHit[], typed: boolean, previous?: KeywordState, settle = false) => { const candidates = settle ? [] : typed ? all : all.filter(hit => hit.from === previous?.pending); const pending = candidates.find(hit => stillTyping(state, hit)); if (previous && previous.all === all && previous.pending === (pending?.from ?? null)) return previous; const hits = pending ? all.filter(hit => hit !== pending) : all; return { all, hits, pending: pending?.from ?? null, decorations: keywordDecorations(state.doc, hits, source) }; }; return Extension.create({ name: 'richTextKeywords', addProseMirrorPlugins() { return [ new Plugin<KeywordState>({ key: keywordKey, state: { init: (_, state): KeywordState => build(state, docKeywords(state.doc, source.pattern), false), apply: (tr, previous, _, state) => { if (tr.getMeta(keywordKey) === 'settle') return build(state, previous.all, false, previous, true); const rescan = tr.docChanged || tr.getMeta(keywordKey); const all = rescan ? docKeywords(state.doc, source.pattern) : previous.all; return build(state, all, tr.docChanged && source.focused, previous); }, }, props: { decorations: state => keywordKey.getState(state)?.decorations }, }), ]; }, }); } type KeywordHint = { keyword: RichTextKeyword; left: number; top: number; bottom: number; below: boolean }; const noKeywords: readonly RichTextKeyword[] = []; const allowedProtocols = ['http:', 'https:', 'mailto:']; const baseExtensions: Extensions = [ StarterKit.configure({ heading: { levels: [1, 2, 3] }, horizontalRule: false, underline: false, link: { openOnClick: false, isAllowedUri: (url, context) => { const protocol = /^[a-z][a-z\d+.-]*:/i.exec(url)?.[0].toLowerCase(); return context.defaultValidate(url) && (!protocol || allowedProtocols.includes(protocol)); }, }, }), MarkdownCodeFence, MessageFormatting, ]; export function RichTextEditor({ ref, size, condensed = false, minRows, value, onChange, onSend, extensions = [], keywords, onKeywordConnect, onKeywordAccountChange, placeholder = 'Ask anything…', disabled = false, ariaLabel = 'Message', ariaInvalid = false, ariaDescribedBy, ariaExpanded, ariaControls, ariaActiveDescendant, toolbarAddon, className, }: RichTextEditorProps) { const scale = size ?? 'md'; const inline = condensed || scale === 'sm'; const rows = minRows === undefined ? undefined : Math.max(1, Math.round(minRows)); const onSendRef = useRef(onSend); const onChangeRef = useRef(onChange); const placeholderRef = useRef(placeholder); const suggestionOpenRef = useRef(ariaExpanded ?? false); onSendRef.current = onSend; onChangeRef.current = onChange; placeholderRef.current = placeholder; suggestionOpenRef.current = ariaExpanded ?? false; const keywordList = keywords ?? noKeywords; const keywordById = useRef(new Map<string, RichTextKeyword>()); keywordById.current = new Map(keywordList.map(keyword => [keyword.id, keyword])); const onKeywordConnectRef = useRef(onKeywordConnect); onKeywordConnectRef.current = onKeywordConnect; const root = useRef<HTMLDivElement>(null); const templates = useRef<HTMLSpanElement>(null); const bubble = useRef<HTMLDivElement>(null); const hovered = useRef<number | null>(null); const bubbleFocused = useRef(false); const [menuOpen, setMenuOpen] = useState(false); const menuId = useId(); const menuOpenRef = useRef(false); menuOpenRef.current = menuOpen; const [menuSide, setMenuSide] = useState<'top' | 'bottom' | null>(null); const [pending, setPending] = useState<string | null>(null); const [failed, setFailed] = useState(false); const pendingToken = useRef<symbol | null>(null); const caretChip = useRef<string | null>(null); const hoverTimer = useRef<ReturnType<typeof setTimeout>>(undefined); const announced = useRef(new Set<string>()); const [hint, setHint] = useState<KeywordHint | null>(null); const [announcement, setAnnouncement] = useState(''); const template = (id: string) => [...(templates.current?.children ?? [])].find(el => (el as HTMLElement).dataset.keywordTemplate === id); const source = useMemo<KeywordSource>( () => ({ pattern: null, signature: '', revision: 0, focused: false, glyph: id => template(id)?.firstElementChild ?? null, connect: id => { const keyword = keywordById.current.get(id); if (keyword) onKeywordConnectRef.current?.(keyword); }, }), [], ); const keywordPlugin = useMemo(() => keywordExtension(source), [source]); const configured = useMemo( () => [ ...baseExtensions, Placeholder.configure({ placeholder: () => placeholderRef.current }), keywordPlugin, ...extensions, ], [extensions, keywordPlugin], ); const editor = useEditor({ immediatelyRender: false, extensions: configured, content: value, editable: !disabled, editorProps: { attributes: { 'data-slot': 'input-group-control', role: 'textbox', 'aria-label': ariaLabel, 'aria-disabled': String(disabled), 'aria-multiline': 'true', 'aria-autocomplete': 'list', 'aria-invalid': ariaInvalid ? 'true' : 'false', ...(ariaDescribedBy && { 'aria-describedby': ariaDescribedBy }), ...(ariaControls && { 'aria-controls': ariaControls }), ...(ariaActiveDescendant && { 'aria-activedescendant': ariaActiveDescendant, }), class: 'sprout-rich-text-editor-content', }, handleKeyDown: (view, event) => { if (event.isComposing) return false; if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') { event.preventDefault(); onSendRef.current(); return true; } if (event.key === 'Enter' && suggestionOpenRef.current) return false; if (event.key === 'Enter' && isFenceLine(view.state)) return false; if ( event.key === 'Enter' && !event.shiftKey && !within(view.state, 'listItem') && !within(view.state, 'codeBlock') ) { event.preventDefault(); onSendRef.current(); return true; } return false; }, }, onUpdate: ({ editor: current }) => onChangeRef.current(current.getJSON()), }); useImperativeHandle( ref, () => ({ focus: () => editor?.commands.focus(), editor: () => editor, setContent: content => editor?.commands.setContent(content, { emitUpdate: true }), }), [editor], ); useLayoutEffect(() => { const signature = JSON.stringify( keywordList.map(keyword => [ keyword.id, keyword.label, keyword.match, keyword.color, keyword.connected !== false, keyword.account, keyword.accounts, template(keyword.id)?.innerHTML ?? '', ]), ); if (signature === source.signature) return; source.signature = signature; source.revision += 1; source.pattern = keywordPattern(keywordList); if (editor && !editor.isDestroyed) editor.view.dispatch(editor.state.tr.setMeta(keywordKey, true)); }); const canSwitch = (keyword: RichTextKeyword) => keyword.connected !== false && (keyword.accounts?.length ?? 0) > 1 && !!onKeywordAccountChange && !disabled; const describeHint = (keyword: RichTextKeyword) => keyword.connected === false ? `${keyword.label} isn't connected.${onKeywordConnect && !disabled ? ' Press Tab to connect it.' : ''}` : `${keyword.label} uses ${accountLabel(keyword)}.${canSwitch(keyword) ? ' Press Tab to change it.' : ''}`; const updateHint = () => { if (!editor || editor.isDestroyed || !root.current) return setHint(null); const hits = keywordKey.getState(editor.state)?.hits ?? []; const { from, empty } = editor.state.selection; const hinted = hits.filter(hit => hasHint(hit.keyword)); const atCaret = (editor.isFocused || bubbleFocused.current) && empty ? hinted.find(hit => from > hit.from && from < hit.to) : undefined; if ((atCaret?.keyword.id ?? null) !== caretChip.current) { caretChip.current = atCaret?.keyword.id ?? null; if (atCaret && editor.isFocused) setAnnouncement(describeHint(atCaret.keyword)); } const pick = (hovered.current !== null && hinted.find(hit => hit.from === hovered.current)) || atCaret; if (!pick) return setHint(null); const view = editor.view; const start = view.coordsAtPos(pick.from, 1); const end = view.coordsAtPos(pick.to, -1); const frame = view.dom.getBoundingClientRect(); if (start.bottom < frame.top || start.top > frame.bottom) return setHint(null); const box = root.current.getBoundingClientRect(); const below = start.top < 48; setHint({ keyword: pick.keyword, left: (start.left + end.right) / 2 - box.left, top: start.top - box.top - 6, bottom: end.bottom - box.top + 6, below, }); }; const updateHintRef = useRef(updateHint); updateHintRef.current = updateHint; useEffect(() => { if (!editor) return; source.focused = editor.isFocused; const onTransaction = ({ transaction }: { transaction: { docChanged: boolean } }) => { if (transaction.docChanged) { hovered.current = null; const hits = keywordKey.getState(editor.state)?.hits ?? []; const offline = [...new Set(hits.filter(hit => hit.keyword.connected === false).map(hit => hit.keyword))]; for (const id of announced.current) if (!offline.some(keyword => keyword.id === id)) announced.current.delete(id); const fresh = offline.filter(keyword => !announced.current.has(keyword.id)); fresh.forEach(keyword => announced.current.add(keyword.id)); if (fresh.length) setAnnouncement( `${fresh.map(keyword => keyword.label).join(', ')} ${fresh.length > 1 ? "aren't" : "isn't"} connected.`, ); } updateHintRef.current(); }; const onBlur = ({ event }: { event: FocusEvent }) => { if (bubble.current?.contains(event.relatedTarget as Node | null)) bubbleFocused.current = true; source.focused = false; if (!editor.isDestroyed) editor.view.dispatch(editor.state.tr.setMeta(keywordKey, 'settle')); updateHintRef.current(); }; const onFocus = () => { source.focused = true; updateHintRef.current(); }; const onScroll = () => updateHintRef.current(); editor.on('transaction', onTransaction); editor.on('focus', onFocus); editor.on('blur', onBlur); const scroller = editor.isDestroyed ? null : editor.view.dom; scroller?.addEventListener('scroll', onScroll); window.addEventListener('resize', onScroll); return () => { editor.off('transaction', onTransaction); editor.off('focus', onFocus); editor.off('blur', onBlur); scroller?.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); }; }, [editor]); useEffect(() => () => clearTimeout(hoverTimer.current), []); useLayoutEffect(() => { const el = bubble.current; const frame = root.current?.getBoundingClientRect(); const width = root.current?.clientWidth; if (!hint || !el || !frame || !width) return; const half = el.offsetWidth / 2; el.style.left = `${Math.min(Math.max(hint.left, half), Math.max(half, width - half))}px`; if (!menuOpen) { el.style.removeProperty('--sprout-rich-text-keyword-menu-height'); if (!hint.below && el.getBoundingClientRect().top < 8) setHint({ ...hint, below: true }); return; } const menu = el.querySelector<HTMLElement>('[role="menu"]'); if (!menu) return; const space = { top: frame.top + hint.top - 8, bottom: window.innerHeight - (frame.top + hint.bottom) - 8, }; if (!menuSide) { const preferred = hint.below ? 'bottom' : 'top'; const other = preferred === 'top' ? 'bottom' : 'top'; setMenuSide(el.offsetHeight > space[preferred] && space[other] > space[preferred] ? other : preferred); return; } const header = el.offsetHeight - menu.offsetHeight; el.style.setProperty('--sprout-rich-text-keyword-menu-height', `${Math.max(80, space[menuSide] - header)}px`); }, [hint, menuOpen, menuSide]); const hintId = hint?.keyword.id; useEffect(() => setMenuOpen(false), [hintId]); useEffect(() => { if (menuOpen) return; pendingToken.current = null; setPending(null); setFailed(false); }, [menuOpen]); useLayoutEffect(() => { if (!menuOpen) return; const items = [...(bubble.current?.querySelectorAll<HTMLElement>('[role="menuitemradio"]') ?? [])]; (items.find(item => item.getAttribute('aria-checked') === 'true') ?? items[0])?.focus({ preventScroll: true }); const close = (event: PointerEvent) => { if (bubble.current?.contains(event.target as Node)) return; setMenuOpen(false); hovered.current = null; updateHintRef.current(); }; document.addEventListener('pointerdown', close); return () => document.removeEventListener('pointerdown', close); }, [menuOpen]); const closeMenu = () => { setMenuOpen(false); bubble.current?.querySelector<HTMLElement>('[aria-haspopup="menu"]')?.focus(); }; const pickAccount = (keyword: RichTextKeyword, accountId: string) => { if (pending) return; if (accountId === keyword.account || !onKeywordAccountChange) return closeMenu(); const result = onKeywordAccountChange(keyword, accountId); if (!result || typeof (result as Promise<unknown>).then !== 'function') return closeMenu(); const token = Symbol(); pendingToken.current = token; setPending(accountId); setFailed(false); Promise.resolve(result).then( () => { if (pendingToken.current === token) closeMenu(); }, () => { if (pendingToken.current !== token) return; pendingToken.current = null; setPending(null); setFailed(true); setAnnouncement(`Couldn't switch the ${keyword.label} account.`); }, ); }; const menuKeys = (event: ReactKeyboardEvent<HTMLDivElement>) => { const items = [...event.currentTarget.querySelectorAll<HTMLElement>('[role="menuitemradio"]')]; const index = items.indexOf(document.activeElement as HTMLElement); const move = (next: number) => { event.preventDefault(); items[(next + items.length) % items.length]?.focus(); }; if (event.key === 'ArrowDown') move(index + 1); else if (event.key === 'ArrowUp') move(index - 1); else if (event.key === 'Home') move(0); else if (event.key === 'End') move(items.length - 1); else if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeMenu(); } else if (event.key === 'Tab') setMenuOpen(false); }; const hover = (target: EventTarget | null) => { if (!editor || editor.isDestroyed) return; const chip = (target as Element | null)?.closest?.( '.sprout-rich-text-keyword, .sprout-rich-text-keyword-icon, .sprout-rich-text-keyword-status', ); clearTimeout(hoverTimer.current); if (chip) { const pos = editor.view.posAtDOM(chip, 0); const hit = keywordKey .getState(editor.state) ?.hits.find(candidate => hasHint(candidate.keyword) && pos >= candidate.from && pos <= candidate.to); hovered.current = hit?.from ?? null; updateHint(); } else if (hovered.current !== null && !menuOpenRef.current) { hoverTimer.current = setTimeout(() => { hovered.current = null; updateHintRef.current(); }, 150); } }; useEffect(() => { editor?.setEditable(!disabled, false); }, [disabled, editor]); useEffect(() => { if (editor && !editor.isDestroyed) editor.view.dispatch(editor.state.tr); }, [editor, placeholder]); useEffect(() => { if (editor && !editor.state.doc.eq(editor.schema.nodeFromJSON(value))) editor.commands.setContent(value, { emitUpdate: false }); }, [editor, value]); return ( <div ref={root} data-slot="rich-text-editor" data-size={scale} data-condensed={condensed || undefined} data-min-rows={rows} data-disabled={disabled || undefined} style={rows === undefined ? undefined : ({ '--sprout-rich-text-editor-min-rows': rows } as CSSProperties)} className={cn( 'sprout-rich-text-editor', `sprout-rich-text-editor-size-${scale}`, condensed && 'sprout-rich-text-editor-condensed', className, )} > <div className="sprout-rich-text-editor-body" onPointerOver={keywordList.length ? event => hover(event.target) : undefined} onPointerLeave={keywordList.length ? () => hover(null) : undefined} > <EditorContent editor={editor} /> </div> {keywordList.length > 0 && ( <> <span ref={templates} hidden> {keywordList.map(keyword => keyword.icon != null ? ( <span key={keyword.id} data-keyword-template={keyword.id}> {keyword.icon} </span> ) : null, )} <span data-keyword-template={statusTemplate}> <LinkOffIcon aria-hidden="true" /> </span> </span> <span className="sprout-rich-text-editor-sr-only" role="status" aria-live="polite"> {announcement} </span> </> )} {hint && ( <div ref={bubble} data-slot="rich-text-keyword-hint" data-side={(menuOpen && menuSide ? menuSide === 'bottom' : hint.below) ? 'bottom' : 'top'} data-menu={menuOpen || undefined} className="sprout-rich-text-keyword-hint" style={{ left: hint.left, top: (menuOpen && menuSide ? menuSide === 'bottom' : hint.below) ? hint.bottom : hint.top, }} onPointerEnter={() => clearTimeout(hoverTimer.current)} onPointerLeave={() => hover(null)} onFocus={() => { bubbleFocused.current = true; }} onBlur={event => { if (event.currentTarget.contains(event.relatedTarget)) return; bubbleFocused.current = false; updateHint(); }} onKeyDown={event => { if (event.key !== 'Escape') return; event.preventDefault(); bubbleFocused.current = false; hovered.current = null; editor?.commands.focus(); }} > <KeywordHintBody keyword={hint.keyword} /> {canSwitch(hint.keyword) && ( <> <button type="button" className="sprout-rich-text-keyword-connect" aria-label={`Switch ${hint.keyword.label} account`} aria-haspopup="menu" aria-expanded={menuOpen} aria-controls={menuOpen ? menuId : undefined} onMouseDown={event => event.preventDefault()} onClick={() => { setMenuSide(null); setMenuOpen(open => !open); }} > Switch </button> {menuOpen && ( <div id={menuId} role="menu" aria-label={`${hint.keyword.label} accounts`} aria-busy={pending !== null || undefined} className="sprout-rich-text-keyword-menu" onKeyDown={menuKeys} > {hint.keyword.accounts!.map(account => { const current = account.id === hint.keyword.account; return ( <button key={account.id} type="button" role="menuitemradio" aria-checked={current} aria-disabled={(pending !== null && pending !== account.id) || undefined} data-pending={pending === account.id || undefined} tabIndex={-1} className="sprout-rich-text-keyword-menu-item" onPointerMove={event => { if (event.pointerType === 'mouse') event.currentTarget.focus(); }} onClick={() => pickAccount(hint.keyword, account.id)} > <span>{account.label}</span> <span className="sprout-rich-text-keyword-menu-mark" aria-hidden="true"> {pending === account.id ? ( <Spinner size="sm" aria-hidden="true" /> ) : ( current && <CheckIcon size="sm" aria-hidden="true" /> )} </span> </button> ); })} {failed && ( <span aria-hidden="true" className="sprout-rich-text-keyword-menu-error"> Couldn't switch. Try again. </span> )} </div> )} </> )} {hint.keyword.connected === false && onKeywordConnect && !disabled && ( <button type="button" className="sprout-rich-text-keyword-connect" aria-label={`Connect ${hint.keyword.label}`} onMouseDown={event => event.preventDefault()} onClick={() => { hovered.current = null; onKeywordConnect(hint.keyword); }} > Connect </button> )} </div> )} {toolbarAddon && ( <div data-slot="rich-text-editor-toolbar" className={cn('sprout-rich-text-editor-toolbar', inline && 'sprout-rich-text-editor-toolbar-inline')} > {toolbarAddon} </div> )} </div> ); }And the files it imports:
lib/sprout/icons/check-icon.tsxlib/sprout/icons/create-icon.tsxlib/sprout/icons/link-off-icon.tsxlib/sprout/keyword-hint.tsxlib/sprout/keywords.ts
Add the styles to your global CSS, after
@import "tailwindcss".@layer components { .sprout-rich-text-editor { box-sizing: border-box; width: 100%; min-width: 0; color: var(--sprout-text); position: relative; } .sprout-rich-text-editor-size-sm, .sprout-rich-text-editor-condensed { align-items: flex-end; display: flex; } .sprout-rich-text-editor[data-disabled] { cursor: not-allowed; opacity: .6; } .sprout-rich-text-editor-body { flex: 1; min-width: 0; min-height: 5rem; } .sprout-rich-text-editor-size-sm > .sprout-rich-text-editor-body, .sprout-rich-text-editor-condensed > .sprout-rich-text-editor-body { min-height: 2.5rem; } .sprout-rich-text-editor-content { box-sizing: border-box; border-radius: var(--sprout-radius-control); min-height: 5rem; max-height: 16rem; color: var(--sprout-text); font-family: inherit; font-size: var(--sprout-text-base); overflow-wrap: anywhere; outline-offset: 0; outline: 0 solid #0000; padding: 8px 12px; line-height: 1.5; overflow-y: auto; } .sprout-rich-text-editor-size-sm .sprout-rich-text-editor-content { min-height: 2.5rem; max-height: 8rem; font-size: var(--sprout-text-sm); line-height: 20px; } .sprout-rich-text-editor-condensed .sprout-rich-text-editor-content { min-height: 2.5rem; max-height: 8rem; } .sprout-rich-text-editor[data-min-rows] > .sprout-rich-text-editor-body { min-height: calc(var(--sprout-rich-text-editor-min-rows) * 1.5 * var(--sprout-text-base) + 16px); } .sprout-rich-text-editor-size-sm[data-min-rows] > .sprout-rich-text-editor-body { min-height: calc(var(--sprout-rich-text-editor-min-rows) * 20px + 16px); } .sprout-rich-text-editor[data-min-rows] .sprout-rich-text-editor-content { min-height: calc(var(--sprout-rich-text-editor-min-rows) * 1lh + 16px); } .sprout-rich-text-editor-content:focus-visible, .sprout-input-group .sprout-rich-text-editor-content:focus-visible { outline: 0 solid #0000; } .sprout-rich-text-editor[data-disabled] .sprout-rich-text-editor-content { cursor: not-allowed; } .sprout-rich-text-editor-content .is-editor-empty:first-child:before { content: attr(data-placeholder); float: left; height: 0; color: var(--sprout-muted); pointer-events: none; } .sprout-rich-text-editor-content :where(p, h1, h2, h3, blockquote, pre, ul, ol) { margin: 0; } .sprout-rich-text-editor-content :where(h1, h2, h3) { font-weight: 600; line-height: 1.4; } .sprout-rich-text-editor-content h1 { font-size: 1.25rem; } .sprout-rich-text-editor-content h2 { font-size: 1.125rem; } .sprout-rich-text-editor-content h3 { font-size: 1rem; } .sprout-rich-text-editor-content :where(ul, ol) { padding-left: 24px; } .sprout-rich-text-editor-content ul { list-style: outside; } .sprout-rich-text-editor-content ol { list-style: decimal; } .sprout-rich-text-editor-content li > p { margin: 0; } .sprout-rich-text-editor-content blockquote { border-left: 2px solid var(--sprout-line); color: var(--sprout-muted); padding-left: 12px; } .sprout-rich-text-editor-content code { background-color: var(--sprout-hover); border-radius: 4px; padding: 0 4px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .875em; } .sprout-rich-text-editor-content pre { border-radius: var(--sprout-radius-control); background-color: var(--sprout-hover); padding: 12px; overflow-x: auto; } .sprout-rich-text-editor-content pre code { white-space: pre; background-color: #0000; padding: 0; } .sprout-rich-text-editor-content a { color: var(--sprout-primary); text-underline-offset: 2px; text-decoration: underline; } .sprout-rich-text-keyword { padding: 0 var(--sprout-rich-text-keyword-pad); border-radius: var(--sprout-radius-control); background-color: color-mix(in oklab, var(--sprout-text) 8%, transparent); color: var(--sprout-text); white-space: nowrap; -webkit-box-decoration-break: clone; box-decoration-break: clone; font-weight: 500; } .sprout-rich-text-keyword[data-icon] { padding-inline-start: calc(var(--sprout-rich-text-keyword-pad) + var(--sprout-rich-text-keyword-icon) + var(--sprout-rich-text-keyword-gap)); } .sprout-rich-text-keyword[data-tinted] { background-color: color-mix(in oklab, var(--sprout-rich-text-keyword-color) 14%, transparent); color: color-mix(in oklab, var(--sprout-rich-text-keyword-color) 62%, var(--sprout-text)); } .sprout-rich-text-keyword[data-connected="false"] { background-color: color-mix(in oklab, var(--sprout-text) 8%, transparent); color: var(--sprout-muted); padding-inline-end: calc(var(--sprout-rich-text-keyword-pad) + var(--sprout-rich-text-keyword-mark) + var(--sprout-rich-text-keyword-gap)); } .sprout-rich-text-keyword-icon, .sprout-rich-text-keyword-status { user-select: none; } .sprout-rich-text-keyword-glyph { position: relative; } .sprout-rich-text-keyword-glyph > * { width: var(--sprout-rich-text-keyword-icon); height: var(--sprout-rich-text-keyword-icon); place-items: center; display: grid; position: absolute; top: 50%; translate: 0 -50%; } .sprout-rich-text-keyword-glyph > * > svg, .sprout-rich-text-keyword-glyph > svg { width: 100%; height: 100%; display: block; } .sprout-rich-text-keyword-icon .sprout-rich-text-keyword-glyph > * { left: var(--sprout-rich-text-keyword-pad); } .sprout-rich-text-editor-content, .sprout-message-rich-text { --sprout-rich-text-keyword-pad: .4375em; --sprout-rich-text-keyword-gap: .5em; --sprout-rich-text-keyword-icon: 1em; --sprout-rich-text-keyword-mark: .875em; } .sprout-rich-text-keyword-status { cursor: pointer; } .sprout-rich-text-keyword-status .sprout-rich-text-keyword-glyph > * { right: var(--sprout-rich-text-keyword-pad); width: var(--sprout-rich-text-keyword-mark); height: var(--sprout-rich-text-keyword-mark); color: var(--sprout-muted); } .sprout-rich-text-keyword-icon[data-connected="false"] .sprout-rich-text-keyword-glyph { filter: grayscale(); opacity: .7; } .sprout-rich-text-keyword-hint { z-index: 5; box-sizing: border-box; border: 1px solid var(--sprout-line); border-radius: var(--sprout-radius-panel); background: var(--sprout-popover); width: max-content; max-width: min(20rem, 100%); color: var(--sprout-text); box-shadow: var(--sprout-shadow-overlay); font-family: var(--sprout-font); font-size: var(--sprout-text-xs); white-space: nowrap; align-items: center; gap: 6px; padding: 4px 4px 4px 10px; font-weight: 400; line-height: 1rem; display: flex; position: absolute; translate: -50% -100%; } .sprout-rich-text-keyword-hint[data-side="bottom"] { translate: -50%; } .sprout-rich-text-keyword-hint:not(:has(button)) { padding-inline-end: 10px; } :is(.sprout-rich-text-keyword-hint, .sprout-message-rich-text-hint) > svg { color: var(--sprout-muted); flex-shrink: 0; } .sprout-rich-text-keyword-hint-icon { flex-shrink: 0; width: 14px; height: 14px; display: grid; } :is(.sprout-rich-text-keyword-hint, .sprout-message-rich-text-hint) .sprout-rich-text-keyword-hint-icon[aria-hidden] > *, :is(.sprout-rich-text-keyword-hint, .sprout-message-rich-text-hint) .sprout-rich-text-keyword-hint-icon[aria-hidden] svg { width: 100%; height: 100%; display: block; } .sprout-rich-text-keyword-hint-label { flex-shrink: 0; font-weight: 500; } .sprout-rich-text-keyword-hint[data-menu] { flex-wrap: wrap; min-width: 14rem; padding: 4px; padding-inline-start: 10px; } .sprout-rich-text-keyword-hint[data-menu] .sprout-rich-text-keyword-hint-account { display: none; } .sprout-rich-text-keyword-hint[data-menu] .sprout-rich-text-keyword-hint-label { flex: 1; } .sprout-rich-text-keyword-menu { max-height: min(16rem, var(--sprout-rich-text-keyword-menu-height, 16rem)); overscroll-behavior: contain; border-top: 1px solid var(--sprout-line); flex-direction: column; flex-basis: 100%; gap: 1px; margin-inline-start: -6px; padding-top: 4px; display: flex; overflow-y: auto; } .sprout-rich-text-keyword-menu-item { border-radius: var(--sprout-radius-control); min-height: 28px; color: var(--sprout-text); font: inherit; text-align: start; cursor: pointer; background: none; border: 0; flex-shrink: 0; justify-content: space-between; align-items: center; gap: 8px; padding: 0 6px; display: flex; position: relative; } .sprout-rich-text-keyword-menu-item > span:first-child { text-overflow: ellipsis; min-width: 0; overflow: hidden; } .sprout-rich-text-keyword-menu-mark { flex-shrink: 0; place-items: center; width: 14px; height: 14px; display: grid; } .sprout-rich-text-keyword-menu-item:focus { background: var(--sprout-hover); outline: 0; } .sprout-rich-text-keyword-menu-item[aria-disabled="true"] { opacity: .5; cursor: default; } .sprout-rich-text-keyword-menu-item[data-pending] { cursor: progress; } .sprout-rich-text-keyword-menu-error { color: var(--sprout-danger); padding: 4px 6px 2px; } @media (pointer: coarse) { .sprout-rich-text-keyword-menu-item { min-height: 44px; } .sprout-rich-text-keyword-connect:after { content: ""; position: absolute; inset: -12px -4px; } } .sprout-rich-text-keyword-hint-account { min-width: 0; color: var(--sprout-muted); text-overflow: ellipsis; overflow: hidden; } .sprout-rich-text-keyword-connect { border-radius: var(--sprout-radius-control); background: var(--sprout-secondary); height: 20px; color: var(--sprout-text); font: inherit; cursor: pointer; border: 0; padding: 0 6px; font-weight: 500; position: relative; } .sprout-rich-text-keyword-connect:active { background: var(--sprout-active); } .sprout-rich-text-keyword-connect:focus-visible { outline: var(--sprout-focus-width) solid var(--sprout-focus-ring); outline-offset: 1px; } @media (hover: hover) and (pointer: fine) { .sprout-rich-text-keyword-connect:hover { background: var(--sprout-hover); } } .sprout-rich-text-editor-sr-only { clip-path: inset(50%); white-space: nowrap; width: 1px; height: 1px; position: absolute; overflow: hidden; } .sprout-rich-text-editor-toolbar { box-sizing: border-box; border-top: 1px solid var(--sprout-line); flex-wrap: wrap; align-items: center; gap: 4px; min-height: 32px; padding: 4px 8px; display: flex; } .sprout-rich-text-editor-toolbar-inline { border-top: 0; flex-wrap: nowrap; flex-shrink: 0; min-height: 0; padding: 4px; } @media (prefers-reduced-motion: no-preference) { .sprout-rich-text-editor { transition: opacity var(--sprout-motion-fast, .12s) ease-out; } .sprout-rich-text-editor-content { transition: outline-color var(--sprout-motion-fast, .12s) ease-out; } .sprout-rich-text-keyword { animation: sprout-rich-text-keyword-fill var(--sprout-motion-fast, .12s) ease-out; } .sprout-rich-text-keyword-glyph > *, .sprout-rich-text-keyword-menu { animation: sprout-rich-text-keyword-fade var(--sprout-motion-fast, .12s) ease-out; } .sprout-rich-text-keyword-hint { transform-origin: bottom; animation: sprout-rich-text-keyword-pop var(--sprout-motion-fast, .12s) var(--sprout-motion-ease, ease-out); } .sprout-rich-text-keyword-hint[data-side="bottom"] { transform-origin: top; } .sprout-status-mark { animation: sprout-status-enter .28s var(--sprout-motion-ease) backwards; transition: transform var(--sprout-motion-normal) var(--sprout-motion-ease); } .sprout-status-glyph { animation: sprout-status-draw .3s var(--sprout-motion-ease) 90ms backwards; } .sprout-status-dot { animation: sprout-status-pop .22s var(--sprout-motion-ease) .16s backwards; } .sprout-status-ring { transition: stroke var(--sprout-motion-normal) ease; } .sprout-status-segment { transition: stroke var(--sprout-motion-normal) var(--sprout-motion-ease); } .sprout-status-segment[data-segment="active"] { animation: 1.4s ease-in-out infinite alternate sprout-status-fade-cycle; } .sprout-status-spin { animation: 1s linear infinite sprout-status-spin; } @media (hover: hover) and (pointer: fine) { .sprout-status:hover .sprout-status-mark { transform: scale(1.15); } .sprout-status:hover .sprout-status-ring { stroke: currentColor; } } } @keyframes sprout-rich-text-keyword-fill { from { background-color: #0000; } } @keyframes sprout-rich-text-keyword-fade { from { opacity: 0; } } @keyframes sprout-rich-text-keyword-pop { from { opacity: 0; scale: .97; } } @media (forced-colors: active) { .sprout-rich-text-editor-content:focus-visible { outline-color: highlight; } .sprout-rich-text-editor-toolbar { border-top-color: canvastext; } .sprout-rich-text-editor-toolbar-inline { border-top: 0; } .sprout-rich-text-keyword { border: 1px solid canvastext; } .sprout-status { --sprout-status-color: CanvasText; } .sprout-status[data-state="running"] { --sprout-status-color: Highlight; } .sprout-status-ring, .sprout-status-track, .sprout-status-segment[data-segment="todo"] { stroke: graytext; } .sprout-status-glyph { stroke: canvas; } .sprout-status-dot { fill: canvas; } } .sprout-status { --sprout-status-color: var(--sprout-muted); width: 16px; height: 16px; color: var(--sprout-status-color); vertical-align: -.1875em; flex-shrink: 0; display: inline-flex; } .sprout-status-size-sm { width: 12px; height: 12px; } .sprout-status-size-lg { width: 20px; height: 20px; } .sprout-status[data-state="running"] { --sprout-status-color: var(--sprout-info); } .sprout-status[data-state="running"][data-determinate], .sprout-status[data-state="success"] { --sprout-status-color: var(--sprout-success); } .sprout-status[data-state="warning"] { --sprout-status-color: var(--sprout-warning); } .sprout-status[data-state="error"] { --sprout-status-color: var(--sprout-danger); } .sprout-status-mark { transform-origin: center; width: 100%; height: 100%; display: block; overflow: visible; } .sprout-status-ring, .sprout-status-track, .sprout-status-arc, .sprout-status-segment { stroke-width: 2px; } .sprout-status-ring { stroke: color-mix(in oklab, currentColor 72%, transparent); } .sprout-status-track { stroke: color-mix(in oklab, currentColor 22%, transparent); } .sprout-status-arc, .sprout-status-segment { stroke: currentColor; stroke-linecap: round; } .sprout-status-segment[data-segment="todo"] { stroke: color-mix(in oklab, var(--sprout-muted) 30%, transparent); } .sprout-status-segments, .sprout-status-spin { transform-box: view-box; transform-origin: 50%; transform: rotate(-90deg); } .sprout-status-fill { fill: currentColor; } .sprout-status-glyph { stroke: var(--sprout-surface); stroke-width: 2px; stroke-linecap: round; stroke-linejoin: round; stroke-dasharray: 1; } .sprout-status-mark[data-mark="paused"] .sprout-status-glyph, .sprout-status-mark[data-mark="skipped"] .sprout-status-glyph { stroke: currentColor; } .sprout-status-dot { fill: var(--sprout-surface); transform-box: fill-box; transform-origin: center; } @media (prefers-reduced-motion: reduce) { .sprout-status-mark { animation: .16s ease-out backwards sprout-status-fade; } .sprout-status-segment[data-segment="active"] { opacity: .55; } } @keyframes sprout-status-enter { from { opacity: 0; transform: scale(.6); } } @keyframes sprout-status-draw { from { stroke-dashoffset: 1px; } } @keyframes sprout-status-pop { from { opacity: 0; transform: scale(.4); } } @keyframes sprout-status-fade { from { opacity: 0; } } @keyframes sprout-status-fade-cycle { from { opacity: .25; } to { opacity: 1; } } @keyframes sprout-status-spin { from { transform: rotate(-90deg); } to { transform: rotate(270deg); } } }Import it from
@/components/ui/rich-text-editor. Update the paths if your@/alias points elsewhere.
pnpm add @tulipfarm/sprout@import "tailwindcss";
@import "@tulipfarm/sprout/styles.css";The package keeps the source and ships fixes with each release. Import from @tulipfarm/sprout/rich-text-editor.
Sizes
Default is an 80px to 256px box with 16px text and a toolbar row below. Compact is a 40px to 128px box with 14px text that keeps its toolbar inline. Enter sends; Shift+Enter adds a line.
default · formatting toolbar · Nothing has been sent.
sm · no toolbar · Cmd or Ctrl+Enter also sends
Formatting and states
Headings 1 to 3, bold, italic, links, lists, quotes, inline code, and fenced code blocks. Type ``` and a language, then Space, to start a code block; pasted fences become code blocks too. Disabled dims the editor and its toolbar.
Enter inside a list or code block adds a line.
disabled · toolbar disabled too
Enter sendShift Enter new line⌘ Enter send from a list or code block⌘ B bold⌘ I italic
Chat composer
Inside a composer InputGroup, the editor drives the group's focus and invalid states, and toolbarAddon becomes the toolbar row. Type @ for saved files or / for skills: Up and Down choose, Enter picks, Escape closes. Over 400 characters shows an error.
- Pull the Q3 numbers for Northwind and Contoso.
- Northwind grew 14% and Contoso held flat. Want a renewal summary for each?
Nothing has been sent.
Compact composer
Side panels use size compact: one 40px row with 14px text and only the send or stop button inline. Saved file chips still render, but @ and / suggestions are off.
Nothing has been sent.
Question composer and read-only
While an agent waits on a question, an empty composer condenses to one row with only send. Focus it and the full toolbar returns. A read-only chat disables the editor and every toolbar control.
The agent asked: Which region should the Q3 report cover?
Nothing has been sent.
This chat is read-only. composer · disabled
Usage
import {
RichTextEditor,
type RichTextEditorHandle,
type RichTextValue,
} from "@tulipfarm/sprout/rich-text-editor";
// A local draft with a formatting toolbar
const editor = useRef<RichTextEditorHandle>(null);
const [value, setValue] = useState<RichTextValue>({ type: "doc", content: [{ type: "paragraph" }] });
<RichTextEditor ref={editor} value={value} onChange={setValue} onSend={send}
placeholder="Write a local draft…"
toolbarAddon={<>
<Button variant="ghost" size="icon-sm" aria-label="Bold"
aria-pressed={editor.current?.editor()?.isActive("bold") ?? false}
onClick={() => editor.current?.editor()?.chain().focus().toggleMark("bold").run()}>
<Bold aria-hidden="true" />
</Button>
<Button variant="outline" size="sm" onClick={send}>Send <Send aria-hidden="true" /></Button>
</>} />
// Compact, without a toolbar
<RichTextEditor size="sm" value={value} onChange={setValue} onSend={send} />
// Inside the chat composer
<InputGroup variant={questionPending ? "question-composer" : "composer"}>
{attachments && <InputGroupAddon align="block-start">{attachments}</InputGroupAddon>}
<RichTextEditor
key={compact ? "compact" : "full"}
ref={inputRef}
size={compact ? "sm" : "md"}
condensed={questionPending && !focused && !attachments && !canSend}
placeholder={questionPending ? "Send a separate message…" : "Ask anything…"}
value={value}
onChange={setValue}
onSend={send}
disabled={disabled || sending}
ariaInvalid={!!validation}
ariaDescribedBy={validation ? errorId : undefined}
ariaExpanded={!!suggestions}
ariaControls={suggestions?.id}
ariaActiveDescendant={suggestions?.activeId}
extensions={compact ? mentionNodes : [...mentionNodes, fileSuggestion, skillSuggestion]}
toolbarAddon={<>
<FileChoices />
<ModelPicker />
<InputGroupButton type="submit" size="icon"
variant={canSend ? "default" : "secondary"} aria-label="Send message">
<ArrowUp aria-hidden="true" />
</InputGroupButton>
</>}
/>
</InputGroup>Props
value is a Tiptap JSON document and onChangegets the new one on every edit. A new value from outside replaces the content without calling onChange.onSend runs on Enter and on Cmd or Ctrl+Enter.
size is md (80px to 256px, 16px text, a toolbar row below) or sm (40px to 128px, 14px text, the toolbar inline at the end). condensed shrinks a default editor to the same single row, such as while an agent question waits. minRows sets how many lines the empty editor shows, such as 1 for a reply box once a conversation has started, so the messages keep the room; it still grows as people type. Past the maximum height the editor scrolls.
toolbarAddon holds buttons and pickers.extensions adds Tiptap extensions, such as mention nodes and@ or / suggestion triggers. Pass a stable array withuseMemo; a new array rebuilds the editor.placeholder defaults to Ask anything… and can change while mounted.
disabled stops editing and dims the editor.ariaLabel (default Message),ariaInvalid, ariaDescribedBy,ariaControls, and ariaActiveDescendant go on the textbox.ariaExpanded tells the editor a suggestion list is open; it isn't written to the DOM, because ARIA doesn't allowaria-expanded on a textbox.
The ref handle has focus(),editor() for Tiptap commands, andsetContent(doc), which replaces the document and callsonChange.
Keywords
keywords shows matching words as chips while people type, such as Slack or ChatGPT. Each keyword has anid, a label, optional match terms (default: the label), anicon such as <BrandIcon brand="slack" size="inline" />, an optionalcolor tint, connected, and the account it uses. The text stays plain text, so the value doesn't change. Read the mentioned keywords with findKeywords(value, keywords), for example when sending. A term counts only as a whole word: inside a URL, path, or name such asgithub.com, slack-bot, or @slack it stays plain, and so does linked text. The word being typed becomes a chip once you type a space, move the caret away, or leave the editor.
const integrations: RichTextKeyword[] = [
{
id: "slack",
label: "Slack",
icon: <BrandIcon brand="slack" size="inline" />,
accounts: [{ id: "tf", label: "tulipfarm.slack.com" }, { id: "acme", label: "acme.slack.com" }],
account: "tf",
},
{ id: "hubspot", label: "HubSpot", icon: <BrandIcon brand="hubspot" size="inline" />, connected: false },
];
<RichTextEditor value={value} onChange={setValue} onSend={() => send(findKeywords(value, integrations))}
keywords={integrations} onKeywordConnect={keyword => connect(keyword.id)}
onKeywordAccountChange={(keyword, accountId) => useAccount(keyword.id, accountId)} />Matches ignore case, need whole words, and prefer the longest term, so Google Drive wins overGoogle. Code and code blocks are skipped. When connected isfalse the chip is muted with a broken-link mark; hovering it, or putting the caret inside it, shows a hint with a Connect button that calls onKeywordConnect. Without that handler the hint only explains the state. A connected chip with an account shows a tooltip the same way, with its icon, name, and account, and a Switch button when it has two or more accounts andonKeywordAccountChange is set. Switch opens a menu of the accounts with the current one checked; arrow keys move, Enter picks, and Escape goes back to Switch. Return a promise from the handler to keep the menu open with a spinner on the picked account until it settles; a rejection shows an error there. When the caret enters a chip, screen readers hear its account or connection state. account is an accounts id, or any label when there's nothing to switch to. Pass a stable keywords array; changing it re-decorates in place.
Behavior
Enter sends unless the caret is in a list item or code block, a suggestion list is open (ariaExpanded), or the line is a bare code fence. Shift+Enter adds a line break; Cmd or Ctrl+Enter always sends. Enter during IME composition never sends.
Headings go up to level 3. Typing ```sql and Space starts a code block, even after a Shift+Enter line break. Pasted text with``` or ~~~ fences becomes code blocks. Links allow only http, https, andmailto, don't open on click, and stop extending once you type past them. There is no underline or horizontal rule.
Accessibility
The editor is a multi-line textbox witharia-autocomplete="list". PointariaControls at a suggestion listbox andariaActiveDescendant at its active option, so screen readers follow arrow keys while focus stays in the text. Name icon-only toolbar buttons witharia-label and show pressed formats with aria-pressed.
On its own the editor shows a 2px focus outline. Inside anInputGroup it is markeddata-slot="input-group-control", so the group draws focus and invalid borders instead. Fades take 120ms and stop when reduced motion is requested. Forced colors mode keeps a system focus outline.
Keyword icons are decorative, so screen readers read the plain word. A polite status message says when a new disconnected keyword appears. From the caret inside a chip with a tooltip, Tab reaches its Connect orSwitch button and Escape returns to the text.
Theme tokens
Text uses --sprout-text, the placeholder and quotes--sprout-muted, code backgrounds--sprout-hover, and links --sprout-primary. The toolbar divider is --sprout-line and focus--sprout-focus. Keyword chips use --sprout-hover, or their color mixed into the surface. Pick a mid-tone color that holds 4.5:1 in light and dark; leave black, white, or pale brands neutral. The opt-in TulipFarm theme tints links and the send button through these tokens.