diff --git a/apps/ui/content/docs/components/composer.mdx b/apps/ui/content/docs/components/composer.mdx index d40cbbbaa..f789f2908 100644 --- a/apps/ui/content/docs/components/composer.mdx +++ b/apps/ui/content/docs/components/composer.mdx @@ -188,7 +188,7 @@ To extend the anatomy above, pass `triggers={triggers}` to `Composer` and insert ``` -Configure only the triggers you need. Queries can contain spaces: `@sam r` finds Sam Rivera. A space immediately after the trigger closes the suggestions. By default, selecting an item inserts a token into the draft; it does not send the message or execute an action. Supply `onAction` to handle items with `type: "action"` as commands: Composer removes the active query and calls your handler without inserting a token or submitting. Your application owns execution. +Configure only the triggers you need. Queries can contain spaces: `@sam r` finds Sam Rivera. A space keeps the suggestions open only while a name continues past the word just typed, so `@sam ` still shows Sam Rivera, while `@sa ` and `@sam rivera ` close them. A space immediately after the trigger closes them too. By default, selecting an item inserts a token into the draft; it does not send the message or execute an action. Supply `onAction` to handle items with `type: "action"` as commands: Composer removes the active query and calls your handler without inserting a token or submitting. Your application owns execution. To open a trigger from a button inside `ComposerActions`, call `useComposerContext().insertTrigger("@")` or `insertTrigger("/")`. The trigger is inserted at the caret and opens the same suggestions as typing it. @@ -215,6 +215,14 @@ The default filter ignores case and accents. Set a trigger's `filter` to customi +### People and tags + +List people and tags apart: team members first, then contacts, then tags. Each person shows their tags next to their name, and a tag row mentions everyone who has that tag. Typing a tag name also lists its people, and once two or more letters start a tag’s name, the tag moves to the top so it is highlighted first. + +To mention several people in a row, the list can stay open. Enter or a click mentions the highlighted row and closes the list; holding Shift while pressing Enter or clicking mentions it and keeps the list open on the same search. Escape then closes the list and removes the leftover query. + + + ### Emoji Give an item `type: "text"` to replace the query with its `text` as ordinary characters, instead of inserting a token. This demo uses it for Slack-style emoji: typing `:thu` suggests 👍, and selecting it replaces `:thu` with the emoji and a space. The emoji is plain draft text, so backspace, copy, undo, and `getComposerText` treat it like any typed character. diff --git a/apps/ui/public/r/composer-document.json b/apps/ui/public/r/composer-document.json index c0aa77dd7..929cad560 100644 --- a/apps/ui/public/r/composer-document.json +++ b/apps/ui/public/r/composer-document.json @@ -7,7 +7,7 @@ "files": [ { "path": "registry/default/lib/composer-document.ts", - "content": "import type { ReactNode } from \"react\";\nimport { getComposerQuery } from \"@/registry/default/lib/composer-query\";\n\ntype ComposerPart =\n | { type: \"text\"; text: string }\n | {\n type: \"mention\" | \"action\";\n id: string;\n label: string;\n trigger: string;\n kind?: string;\n data?: string;\n text?: string;\n };\n\ntype ComposerValue = readonly ComposerPart[];\ntype ComposerTokenPart = Exclude;\n\ntype ComposerItemValue = {\n id: string;\n label: string;\n disabled?: boolean;\n description?: string;\n icon?: ReactNode;\n type?: \"mention\" | \"action\" | \"text\";\n kind?: string;\n data?: string;\n text?: string;\n};\n\ntype ComposerTrigger = {\n character: string;\n items: readonly ComposerItemValue[];\n status?: \"ready\" | \"loading\" | \"error\";\n itemsFor?: string;\n queryKey?: string;\n showEmpty?: boolean;\n maxQueryLength?: number;\n filter?: ((item: ComposerItemValue, query: string) => boolean) | null;\n};\n\ntype ComposerQuery = { character: string; text: string; key: string };\n\nconst queryNodeIds = new WeakMap();\nlet nextQueryNodeId = 0;\n\ntype ActiveQuery = ComposerQuery & {\n node: Text;\n start: number;\n end: number;\n};\n\nfunction pushText(parts: ComposerPart[], text: string): void {\n if (!text) return;\n const previous = parts[parts.length - 1];\n if (previous?.type === \"text\") previous.text += text;\n else parts.push({ type: \"text\", text });\n}\n\nfunction readValue(\n root: HTMLElement,\n ignoreTrailingPlaceholder = true,\n): ComposerValue {\n if (root instanceof HTMLTextAreaElement) {\n return root.value ? [{ type: \"text\", text: root.value }] : [];\n }\n const parts: ComposerPart[] = [];\n function children(parent: HTMLElement): void {\n const nodes = Array.from(parent.childNodes);\n for (const [index, node] of nodes.entries()) {\n if (node instanceof Text) {\n pushText(parts, node.data);\n continue;\n }\n if (!(node instanceof HTMLElement)) continue;\n const tokenType = node.dataset.composerToken;\n if (tokenType === \"mention\" || tokenType === \"action\") {\n parts.push({\n type: tokenType,\n id: node.dataset.id ?? \"\",\n label: node.dataset.label ?? \"\",\n trigger: node.dataset.trigger ?? \"@\",\n ...(node.dataset.kind ? { kind: node.dataset.kind } : {}),\n ...(node.dataset.data !== undefined\n ? { data: node.dataset.data }\n : {}),\n ...(node.dataset.text !== undefined\n ? { text: node.dataset.text }\n : {}),\n });\n } else if (node.tagName === \"BR\") {\n if (node.hasAttribute(\"data-composer-placeholder\")) continue;\n // Browsers end empty lines with a placeholder BR, which is not another newline.\n if (!ignoreTrailingPlaceholder || index !== nodes.length - 1)\n pushText(parts, \"\\n\");\n } else {\n const isBlock = node.tagName === \"DIV\" || node.tagName === \"P\";\n if (\n isBlock &&\n index > 0 &&\n !(nodes[index - 1] instanceof HTMLBRElement)\n )\n pushText(parts, \"\\n\");\n children(node);\n if (isBlock && index < nodes.length - 1) {\n const next = nodes[index + 1];\n if (\n !(\n next instanceof HTMLElement &&\n (next.tagName === \"DIV\" || next.tagName === \"P\")\n )\n )\n pushText(parts, \"\\n\");\n }\n }\n }\n }\n children(root);\n return parts;\n}\n\nfunction normalizeValue(value: ComposerValue): ComposerValue {\n const parts: ComposerPart[] = [];\n for (const part of value) {\n if (part.type === \"text\") pushText(parts, part.text);\n else parts.push(part);\n }\n return parts;\n}\n\nfunction equalValue(left: ComposerValue, right: ComposerValue): boolean {\n const a = normalizeValue(left);\n const b = normalizeValue(right);\n return (\n a.length === b.length &&\n a.every((part, index) => {\n const other = b[index];\n if (part.type === \"text\")\n return other?.type === \"text\" && part.text === other.text;\n return (\n other?.type !== \"text\" &&\n other?.type === part.type &&\n other.id === part.id &&\n other.label === part.label &&\n other.trigger === part.trigger &&\n other.kind === part.kind &&\n other.data === part.data &&\n other.text === part.text\n );\n })\n );\n}\n\nfunction getComposerText(value: ComposerValue): string {\n return value\n .map((part) =>\n part.type === \"text\"\n ? part.text\n : (part.text ?? `${part.trigger}${part.label}`),\n )\n .join(\"\");\n}\n\nfunction createToken(part: ComposerTokenPart): HTMLSpanElement {\n const token = document.createElement(\"span\");\n token.dataset.composerToken = part.type;\n token.dataset.id = part.id;\n token.dataset.label = part.label;\n token.dataset.trigger = part.trigger;\n if (part.kind) token.dataset.kind = part.kind;\n if (part.data !== undefined) token.dataset.data = part.data;\n if (part.text !== undefined) token.dataset.text = part.text;\n token.contentEditable = \"false\";\n const fallback = document.createElement(\"span\");\n fallback.dataset.slot = \"composer-token-fallback\";\n fallback.textContent = part.text ?? `${part.trigger}${part.label}`;\n const renderer = document.createElement(\"span\");\n renderer.dataset.slot = \"composer-token-renderer\";\n token.append(fallback, renderer);\n return token;\n}\n\nfunction writeValue(root: HTMLElement, value: ComposerValue): void {\n if (root instanceof HTMLTextAreaElement) {\n root.value = getComposerText(value);\n return;\n }\n const fragment = document.createDocumentFragment();\n for (const part of value) {\n if (part.type !== \"text\") fragment.append(createToken(part));\n else if (part.text) fragment.append(document.createTextNode(part.text));\n }\n if (getComposerText(value).endsWith(\"\\n\")) {\n const placeholder = document.createElement(\"br\");\n placeholder.dataset.composerPlaceholder = \"\";\n fragment.append(placeholder);\n }\n root.replaceChildren(fragment);\n}\n\nfunction insertPlainText(root: HTMLElement, text: string): void {\n const selection = window.getSelection();\n if (\n !selection?.rangeCount ||\n !root.contains(selection.anchorNode) ||\n !root.contains(selection.focusNode)\n )\n return;\n const range = selection.getRangeAt(0);\n range.deleteContents();\n const node = document.createTextNode(text.replace(/\\r\\n?/g, \"\\n\"));\n range.insertNode(node);\n range.setStart(node, node.length);\n range.collapse(true);\n selection.removeAllRanges();\n selection.addRange(range);\n}\n\nfunction placeCaretAfterToken(\n root: HTMLElement,\n selection: Selection | null,\n): void {\n if (!selection?.rangeCount) return;\n const range = selection.getRangeAt(0);\n if (!range.collapsed) return;\n const anchor = selection.anchorNode;\n const token = (\n anchor instanceof Element ? anchor : anchor?.parentElement\n )?.closest(\"[data-composer-token]\");\n if (token && root.contains(token)) {\n const next = token.nextSibling;\n if (next instanceof Text && /^\\s/u.test(next.data)) {\n selection.collapse(next, 1);\n } else if (token.parentNode) {\n selection.collapse(\n token.parentNode,\n Array.from(token.parentNode.childNodes).indexOf(token) + 1,\n );\n }\n return;\n }\n const { startContainer, startOffset } = range;\n if (startContainer instanceof Text) {\n if (/^\\s/u.test(startContainer.data.slice(startOffset)))\n selection.collapse(startContainer, startOffset + 1);\n } else {\n const next = startContainer.childNodes[startOffset];\n if (next instanceof Text && /^\\s/u.test(next.data))\n selection.collapse(next, 1);\n }\n}\n\nfunction currentQuery(\n root: HTMLElement,\n triggers: readonly ComposerTrigger[],\n): ActiveQuery | null {\n const selection = window.getSelection();\n if (!selection?.isCollapsed || !root.contains(selection.anchorNode))\n return null;\n const node = selection.anchorNode;\n if (\n !(node instanceof Text) ||\n node.parentElement?.closest(\"[data-composer-token]\")\n )\n return null;\n let caret = selection.anchorOffset;\n let merged = false;\n // Paste and token deletion can leave one query split across adjacent text nodes.\n while (node.previousSibling instanceof Text) {\n const previous = node.previousSibling;\n caret += previous.length;\n node.insertData(0, previous.data);\n previous.remove();\n merged = true;\n }\n while (node.nextSibling instanceof Text) {\n const next = node.nextSibling;\n node.appendData(next.data);\n next.remove();\n merged = true;\n }\n if (merged) selection.collapse(node, caret);\n const query = getComposerQuery(\n node.data,\n caret,\n triggers.map((trigger) => trigger.character),\n );\n if (\n !query ||\n query.text.length >\n (triggers.find((trigger) => trigger.character === query.character)\n ?.maxQueryLength ?? Number.POSITIVE_INFINITY)\n )\n return null;\n if (\n query.start === 0 &&\n node.previousSibling?.textContent &&\n !/\\s$/u.test(node.previousSibling.textContent)\n )\n return null;\n if (!queryNodeIds.has(node)) queryNodeIds.set(node, ++nextQueryNodeId);\n return {\n ...query,\n node,\n key: `${queryNodeIds.get(node)}:${query.character}:${query.start}:${caret}:${query.text}`,\n };\n}\n\nfunction getFilteredItems(\n trigger: ComposerTrigger | undefined,\n query: ActiveQuery | null,\n defaultFilter: (text: string, query: string) => boolean,\n): readonly ComposerItemValue[] {\n if (\n !trigger ||\n !query ||\n (trigger.status && trigger.status !== \"ready\") ||\n (trigger.itemsFor !== undefined && trigger.itemsFor !== query.text) ||\n (trigger.queryKey !== undefined && trigger.queryKey !== query.key)\n )\n return [];\n if (trigger.filter === null) return trigger.items;\n return trigger.items.filter((item) =>\n trigger.filter\n ? trigger.filter(item, query.text)\n : defaultFilter(item.label, query.text),\n );\n}\n\nfunction hasVisibleItems(\n trigger: ComposerTrigger | undefined,\n options: readonly ComposerItemValue[],\n): boolean {\n return Boolean(\n trigger &&\n (options.length ||\n trigger.showEmpty ||\n trigger.status === \"loading\" ||\n trigger.status === \"error\"),\n );\n}\n\nfunction insertItem(\n input: HTMLDivElement,\n query: ActiveQuery,\n suggestion: ComposerItemValue,\n): void {\n const range = document.createRange();\n range.setStart(query.node, query.start);\n range.setEnd(query.node, query.end);\n const selection = window.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n input.focus({ preventScroll: true });\n const node =\n suggestion.type === \"text\"\n ? document.createTextNode(suggestion.text ?? suggestion.label)\n : createToken({\n type: suggestion.type ?? \"mention\",\n id: suggestion.id,\n label: suggestion.label,\n trigger: query.character,\n ...(suggestion.kind ? { kind: suggestion.kind } : {}),\n ...(suggestion.data !== undefined ? { data: suggestion.data } : {}),\n ...(suggestion.text !== undefined ? { text: suggestion.text } : {}),\n });\n const hasSeparator = /^\\s/u.test(query.node.data.slice(query.end));\n const trailingSpace = hasSeparator ? \"\" : \" \";\n range.deleteContents();\n const space = trailingSpace ? document.createTextNode(trailingSpace) : null;\n if (space) range.insertNode(space);\n range.insertNode(node);\n if (space) range.setStart(space, 1);\n else range.setStartAfter(node);\n range.collapse(true);\n selection?.removeAllRanges();\n selection?.addRange(range);\n placeCaretAfterToken(input, selection);\n input.focus({ preventScroll: true });\n}\n\ntype ComposerSelection = { anchor: number; focus: number };\n\n// Use canonical text offsets so chip labels and their icons do not move the caret.\nfunction readSelection(input: HTMLElement): ComposerSelection | null {\n if (input instanceof HTMLTextAreaElement) {\n return document.activeElement === input\n ? {\n anchor:\n input.selectionDirection === \"backward\"\n ? input.selectionEnd\n : input.selectionStart,\n focus:\n input.selectionDirection === \"backward\"\n ? input.selectionStart\n : input.selectionEnd,\n }\n : null;\n }\n const selection = window.getSelection();\n if (\n !selection?.anchorNode ||\n !selection.focusNode ||\n !input.contains(selection.anchorNode) ||\n !input.contains(selection.focusNode)\n )\n return null;\n function offset(node: Node, position: number): number {\n const range = document.createRange();\n range.selectNodeContents(input);\n range.setEnd(node, position);\n const fragment = document.createElement(\"div\");\n fragment.append(range.cloneContents());\n return getComposerText(readValue(fragment, false)).length;\n }\n return {\n anchor: offset(selection.anchorNode, selection.anchorOffset),\n focus: offset(selection.focusNode, selection.focusOffset),\n };\n}\n\nfunction restoreSelection(\n input: HTMLElement,\n selection: ComposerSelection | null,\n): void {\n if (!selection) return;\n if (input instanceof HTMLTextAreaElement) {\n input.setSelectionRange(\n Math.min(selection.anchor, selection.focus),\n Math.max(selection.anchor, selection.focus),\n selection.anchor > selection.focus ? \"backward\" : \"forward\",\n );\n return;\n }\n function point(offset: number): [Node, number] {\n let remaining = offset;\n for (const [index, node] of Array.from(input.childNodes).entries()) {\n const length =\n node instanceof HTMLElement && node.dataset.composerToken\n ? (\n node.dataset.text ??\n `${node.dataset.trigger ?? \"\"}${node.dataset.label ?? \"\"}`\n ).length\n : (node.textContent ?? \"\").length;\n if (remaining <= length) {\n if (node instanceof Text) return [node, remaining];\n return [input, index + (remaining > 0 ? 1 : 0)];\n }\n remaining -= length;\n }\n return [input, input.childNodes.length];\n }\n const [anchor, anchorOffset] = point(selection.anchor);\n const [focus, focusOffset] = point(selection.focus);\n window\n .getSelection()\n ?.setBaseAndExtent(anchor, anchorOffset, focus, focusOffset);\n}\n\ntype ComposerSnapshot = {\n value: ComposerValue;\n selection: ComposerSelection | null;\n};\n\nexport {\n type ActiveQuery,\n type ComposerItemValue,\n type ComposerPart,\n type ComposerQuery,\n type ComposerSelection,\n type ComposerSnapshot,\n type ComposerTokenPart,\n type ComposerTrigger,\n type ComposerValue,\n currentQuery,\n equalValue,\n getComposerText,\n getFilteredItems,\n hasVisibleItems,\n insertItem,\n insertPlainText,\n readSelection,\n readValue,\n restoreSelection,\n writeValue,\n};\n", + "content": "import type { ReactNode } from \"react\";\nimport { getComposerQuery } from \"@/registry/default/lib/composer-query\";\n\ntype ComposerPart =\n | { type: \"text\"; text: string }\n | {\n type: \"mention\" | \"action\";\n id: string;\n label: string;\n trigger: string;\n kind?: string;\n data?: string;\n text?: string;\n };\n\ntype ComposerValue = readonly ComposerPart[];\ntype ComposerTokenPart = Exclude;\n\ntype ComposerItemValue = {\n id: string;\n label: string;\n disabled?: boolean;\n description?: string;\n icon?: ReactNode;\n type?: \"mention\" | \"action\" | \"text\";\n kind?: string;\n data?: string;\n text?: string;\n};\n\ntype ComposerTrigger = {\n character: string;\n items: readonly ComposerItemValue[];\n status?: \"ready\" | \"loading\" | \"error\";\n itemsFor?: string;\n queryKey?: string;\n showEmpty?: boolean;\n maxQueryLength?: number;\n filter?: ((item: ComposerItemValue, query: string) => boolean) | null;\n};\n\ntype ComposerQuery = { character: string; text: string; key: string };\n\nconst queryNodeIds = new WeakMap();\nlet nextQueryNodeId = 0;\n\ntype ActiveQuery = ComposerQuery & {\n node: Text;\n start: number;\n end: number;\n spaceAfter: boolean;\n};\n\nfunction pushText(parts: ComposerPart[], text: string): void {\n if (!text) return;\n const previous = parts[parts.length - 1];\n if (previous?.type === \"text\") previous.text += text;\n else parts.push({ type: \"text\", text });\n}\n\nfunction readValue(\n root: HTMLElement,\n ignoreTrailingPlaceholder = true,\n): ComposerValue {\n if (root instanceof HTMLTextAreaElement) {\n return root.value ? [{ type: \"text\", text: root.value }] : [];\n }\n const parts: ComposerPart[] = [];\n function children(parent: HTMLElement): void {\n const nodes = Array.from(parent.childNodes);\n for (const [index, node] of nodes.entries()) {\n if (node instanceof Text) {\n pushText(parts, node.data);\n continue;\n }\n if (!(node instanceof HTMLElement)) continue;\n const tokenType = node.dataset.composerToken;\n if (tokenType === \"mention\" || tokenType === \"action\") {\n parts.push({\n type: tokenType,\n id: node.dataset.id ?? \"\",\n label: node.dataset.label ?? \"\",\n trigger: node.dataset.trigger ?? \"@\",\n ...(node.dataset.kind ? { kind: node.dataset.kind } : {}),\n ...(node.dataset.data !== undefined\n ? { data: node.dataset.data }\n : {}),\n ...(node.dataset.text !== undefined\n ? { text: node.dataset.text }\n : {}),\n });\n } else if (node.tagName === \"BR\") {\n if (node.hasAttribute(\"data-composer-placeholder\")) continue;\n // Browsers end empty lines with a placeholder BR, which is not another newline.\n if (!ignoreTrailingPlaceholder || index !== nodes.length - 1)\n pushText(parts, \"\\n\");\n } else {\n const isBlock = node.tagName === \"DIV\" || node.tagName === \"P\";\n if (\n isBlock &&\n index > 0 &&\n !(nodes[index - 1] instanceof HTMLBRElement)\n )\n pushText(parts, \"\\n\");\n children(node);\n if (isBlock && index < nodes.length - 1) {\n const next = nodes[index + 1];\n if (\n !(\n next instanceof HTMLElement &&\n (next.tagName === \"DIV\" || next.tagName === \"P\")\n )\n )\n pushText(parts, \"\\n\");\n }\n }\n }\n }\n children(root);\n return parts;\n}\n\nfunction normalizeValue(value: ComposerValue): ComposerValue {\n const parts: ComposerPart[] = [];\n for (const part of value) {\n if (part.type === \"text\") pushText(parts, part.text);\n else parts.push(part);\n }\n return parts;\n}\n\nfunction equalValue(left: ComposerValue, right: ComposerValue): boolean {\n const a = normalizeValue(left);\n const b = normalizeValue(right);\n return (\n a.length === b.length &&\n a.every((part, index) => {\n const other = b[index];\n if (part.type === \"text\")\n return other?.type === \"text\" && part.text === other.text;\n return (\n other?.type !== \"text\" &&\n other?.type === part.type &&\n other.id === part.id &&\n other.label === part.label &&\n other.trigger === part.trigger &&\n other.kind === part.kind &&\n other.data === part.data &&\n other.text === part.text\n );\n })\n );\n}\n\nfunction getComposerText(value: ComposerValue): string {\n return value\n .map((part) =>\n part.type === \"text\"\n ? part.text\n : (part.text ?? `${part.trigger}${part.label}`),\n )\n .join(\"\");\n}\n\nfunction createToken(part: ComposerTokenPart): HTMLSpanElement {\n const token = document.createElement(\"span\");\n token.dataset.composerToken = part.type;\n token.dataset.id = part.id;\n token.dataset.label = part.label;\n token.dataset.trigger = part.trigger;\n if (part.kind) token.dataset.kind = part.kind;\n if (part.data !== undefined) token.dataset.data = part.data;\n if (part.text !== undefined) token.dataset.text = part.text;\n token.contentEditable = \"false\";\n const fallback = document.createElement(\"span\");\n fallback.dataset.slot = \"composer-token-fallback\";\n fallback.textContent = part.text ?? `${part.trigger}${part.label}`;\n const renderer = document.createElement(\"span\");\n renderer.dataset.slot = \"composer-token-renderer\";\n token.append(fallback, renderer);\n return token;\n}\n\nfunction writeValue(root: HTMLElement, value: ComposerValue): void {\n if (root instanceof HTMLTextAreaElement) {\n root.value = getComposerText(value);\n return;\n }\n const fragment = document.createDocumentFragment();\n for (const part of value) {\n if (part.type !== \"text\") fragment.append(createToken(part));\n else if (part.text) fragment.append(document.createTextNode(part.text));\n }\n if (getComposerText(value).endsWith(\"\\n\")) {\n const placeholder = document.createElement(\"br\");\n placeholder.dataset.composerPlaceholder = \"\";\n fragment.append(placeholder);\n }\n root.replaceChildren(fragment);\n}\n\nfunction insertPlainText(root: HTMLElement, text: string): void {\n const selection = window.getSelection();\n if (\n !selection?.rangeCount ||\n !root.contains(selection.anchorNode) ||\n !root.contains(selection.focusNode)\n )\n return;\n const range = selection.getRangeAt(0);\n range.deleteContents();\n const node = document.createTextNode(text.replace(/\\r\\n?/g, \"\\n\"));\n range.insertNode(node);\n range.setStart(node, node.length);\n range.collapse(true);\n selection.removeAllRanges();\n selection.addRange(range);\n}\n\nfunction placeCaretAfterToken(\n root: HTMLElement,\n selection: Selection | null,\n): void {\n if (!selection?.rangeCount) return;\n const range = selection.getRangeAt(0);\n if (!range.collapsed) return;\n const anchor = selection.anchorNode;\n const token = (\n anchor instanceof Element ? anchor : anchor?.parentElement\n )?.closest(\"[data-composer-token]\");\n if (token && root.contains(token)) {\n const next = token.nextSibling;\n if (next instanceof Text && /^\\s/u.test(next.data)) {\n selection.collapse(next, 1);\n } else if (token.parentNode) {\n selection.collapse(\n token.parentNode,\n Array.from(token.parentNode.childNodes).indexOf(token) + 1,\n );\n }\n return;\n }\n const { startContainer, startOffset } = range;\n if (startContainer instanceof Text) {\n if (/^\\s/u.test(startContainer.data.slice(startOffset)))\n selection.collapse(startContainer, startOffset + 1);\n } else {\n const next = startContainer.childNodes[startOffset];\n if (next instanceof Text && /^\\s/u.test(next.data))\n selection.collapse(next, 1);\n }\n}\n\nfunction currentQuery(\n root: HTMLElement,\n triggers: readonly ComposerTrigger[],\n): ActiveQuery | null {\n const selection = window.getSelection();\n if (!selection?.isCollapsed || !root.contains(selection.anchorNode))\n return null;\n const node = selection.anchorNode;\n if (\n !(node instanceof Text) ||\n node.parentElement?.closest(\"[data-composer-token]\")\n )\n return null;\n let caret = selection.anchorOffset;\n let merged = false;\n // Paste and token deletion can leave one query split across adjacent text nodes.\n while (node.previousSibling instanceof Text) {\n const previous = node.previousSibling;\n caret += previous.length;\n node.insertData(0, previous.data);\n previous.remove();\n merged = true;\n }\n while (node.nextSibling instanceof Text) {\n const next = node.nextSibling;\n node.appendData(next.data);\n next.remove();\n merged = true;\n }\n if (merged) selection.collapse(node, caret);\n const query = getComposerQuery(\n node.data,\n caret,\n triggers.map((trigger) => trigger.character),\n );\n if (\n !query ||\n query.text.length >\n (triggers.find((trigger) => trigger.character === query.character)\n ?.maxQueryLength ?? Number.POSITIVE_INFINITY)\n )\n return null;\n if (\n query.start === 0 &&\n node.previousSibling?.textContent &&\n !/\\s$/u.test(node.previousSibling.textContent)\n )\n return null;\n if (!queryNodeIds.has(node)) queryNodeIds.set(node, ++nextQueryNodeId);\n return {\n ...query,\n node,\n key: `${queryNodeIds.get(node)}:${query.character}:${query.start}:${caret}:${query.text}`,\n };\n}\n\nfunction getFilteredItems(\n trigger: ComposerTrigger | undefined,\n query: ActiveQuery | null,\n defaultFilter: (text: string, query: string) => boolean,\n): readonly ComposerItemValue[] {\n if (\n !trigger ||\n !query ||\n (trigger.status && trigger.status !== \"ready\") ||\n (trigger.itemsFor !== undefined && trigger.itemsFor !== query.text) ||\n (trigger.queryKey !== undefined && trigger.queryKey !== query.key)\n )\n return [];\n if (trigger.filter === null) return trigger.items;\n return trigger.items.filter((item) =>\n trigger.filter\n ? trigger.filter(item, query.text)\n : defaultFilter(item.label, query.text),\n );\n}\n\nfunction hasVisibleItems(\n trigger: ComposerTrigger | undefined,\n options: readonly ComposerItemValue[],\n): boolean {\n return Boolean(\n trigger &&\n (options.length ||\n trigger.showEmpty ||\n trigger.status === \"loading\" ||\n trigger.status === \"error\"),\n );\n}\n\nfunction insertItem(\n input: HTMLDivElement,\n query: ActiveQuery,\n suggestion: ComposerItemValue,\n): void {\n const range = document.createRange();\n range.setStart(query.node, query.start);\n range.setEnd(query.node, query.end);\n const selection = window.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n input.focus({ preventScroll: true });\n const node =\n suggestion.type === \"text\"\n ? document.createTextNode(suggestion.text ?? suggestion.label)\n : createToken({\n type: suggestion.type ?? \"mention\",\n id: suggestion.id,\n label: suggestion.label,\n trigger: query.character,\n ...(suggestion.kind ? { kind: suggestion.kind } : {}),\n ...(suggestion.data !== undefined ? { data: suggestion.data } : {}),\n ...(suggestion.text !== undefined ? { text: suggestion.text } : {}),\n });\n const hasSeparator = /^\\s/u.test(query.node.data.slice(query.end));\n const trailingSpace = hasSeparator ? \"\" : \" \";\n range.deleteContents();\n const space = trailingSpace ? document.createTextNode(trailingSpace) : null;\n if (space) range.insertNode(space);\n range.insertNode(node);\n if (space) range.setStart(space, 1);\n else range.setStartAfter(node);\n range.collapse(true);\n selection?.removeAllRanges();\n selection?.addRange(range);\n placeCaretAfterToken(input, selection);\n input.focus({ preventScroll: true });\n}\n\ntype ComposerSelection = { anchor: number; focus: number };\n\n// Use canonical text offsets so chip labels and their icons do not move the caret.\nfunction readSelection(input: HTMLElement): ComposerSelection | null {\n if (input instanceof HTMLTextAreaElement) {\n return document.activeElement === input\n ? {\n anchor:\n input.selectionDirection === \"backward\"\n ? input.selectionEnd\n : input.selectionStart,\n focus:\n input.selectionDirection === \"backward\"\n ? input.selectionStart\n : input.selectionEnd,\n }\n : null;\n }\n const selection = window.getSelection();\n if (\n !selection?.anchorNode ||\n !selection.focusNode ||\n !input.contains(selection.anchorNode) ||\n !input.contains(selection.focusNode)\n )\n return null;\n function offset(node: Node, position: number): number {\n const range = document.createRange();\n range.selectNodeContents(input);\n range.setEnd(node, position);\n const fragment = document.createElement(\"div\");\n fragment.append(range.cloneContents());\n return getComposerText(readValue(fragment, false)).length;\n }\n return {\n anchor: offset(selection.anchorNode, selection.anchorOffset),\n focus: offset(selection.focusNode, selection.focusOffset),\n };\n}\n\nfunction restoreSelection(\n input: HTMLElement,\n selection: ComposerSelection | null,\n): void {\n if (!selection) return;\n if (input instanceof HTMLTextAreaElement) {\n input.setSelectionRange(\n Math.min(selection.anchor, selection.focus),\n Math.max(selection.anchor, selection.focus),\n selection.anchor > selection.focus ? \"backward\" : \"forward\",\n );\n return;\n }\n function point(offset: number): [Node, number] {\n let remaining = offset;\n for (const [index, node] of Array.from(input.childNodes).entries()) {\n const length =\n node instanceof HTMLElement && node.dataset.composerToken\n ? (\n node.dataset.text ??\n `${node.dataset.trigger ?? \"\"}${node.dataset.label ?? \"\"}`\n ).length\n : (node.textContent ?? \"\").length;\n if (remaining <= length) {\n if (node instanceof Text) return [node, remaining];\n return [input, index + (remaining > 0 ? 1 : 0)];\n }\n remaining -= length;\n }\n return [input, input.childNodes.length];\n }\n const [anchor, anchorOffset] = point(selection.anchor);\n const [focus, focusOffset] = point(selection.focus);\n window\n .getSelection()\n ?.setBaseAndExtent(anchor, anchorOffset, focus, focusOffset);\n}\n\ntype ComposerSnapshot = {\n value: ComposerValue;\n selection: ComposerSelection | null;\n};\n\nexport {\n type ActiveQuery,\n type ComposerItemValue,\n type ComposerPart,\n type ComposerQuery,\n type ComposerSelection,\n type ComposerSnapshot,\n type ComposerTokenPart,\n type ComposerTrigger,\n type ComposerValue,\n currentQuery,\n equalValue,\n getComposerText,\n getFilteredItems,\n hasVisibleItems,\n insertItem,\n insertPlainText,\n readSelection,\n readValue,\n restoreSelection,\n writeValue,\n};\n", "type": "registry:lib" } ], diff --git a/apps/ui/public/r/composer-query.json b/apps/ui/public/r/composer-query.json index 394a952ab..97b9d21e1 100644 --- a/apps/ui/public/r/composer-query.json +++ b/apps/ui/public/r/composer-query.json @@ -4,7 +4,7 @@ "files": [ { "path": "registry/default/lib/composer-query.ts", - "content": "export function getComposerQuery(\n text: string,\n caret: number,\n triggers: readonly string[],\n): { character: string; text: string; start: number; end: number } | null {\n let start = -1;\n let character = \"\";\n for (const trigger of triggers) {\n if (!trigger || trigger.length > caret) continue;\n const index = text.lastIndexOf(trigger, caret - trigger.length);\n if (index > start) {\n start = index;\n character = trigger;\n }\n }\n if (start < 0 || (start > 0 && !/\\s/u.test(text.charAt(start - 1))))\n return null;\n\n const beforeCaret = text.slice(start + character.length, caret);\n if (/^\\s/u.test(beforeCaret)) return null;\n if (!/^[\\p{L}\\p{M}\\p{N}\\p{Zs}_.’'-]*$/u.test(beforeCaret)) return null;\n\n // Complete the word at the caret without consuming subsequent prose.\n const suffix = /^[\\p{L}\\p{M}\\p{N}_.’'-]*/u.exec(text.slice(caret))?.[0] ?? \"\";\n return {\n character,\n text: (beforeCaret + suffix).replace(/\\p{Zs}+/gu, \" \").trim(),\n start,\n end: caret + suffix.length,\n };\n}\n", + "content": "export function getComposerQuery(\n text: string,\n caret: number,\n triggers: readonly string[],\n): {\n character: string;\n text: string;\n start: number;\n end: number;\n spaceAfter: boolean;\n} | null {\n let start = -1;\n let character = \"\";\n for (const trigger of triggers) {\n if (!trigger || trigger.length > caret) continue;\n const index = text.lastIndexOf(trigger, caret - trigger.length);\n if (index > start) {\n start = index;\n character = trigger;\n }\n }\n if (start < 0 || (start > 0 && !/\\s/u.test(text.charAt(start - 1))))\n return null;\n\n const beforeCaret = text.slice(start + character.length, caret);\n if (/^\\s/u.test(beforeCaret)) return null;\n if (!/^[\\p{L}\\p{M}\\p{N}\\p{Zs}_.’'-]*$/u.test(beforeCaret)) return null;\n\n // Complete the word at the caret without consuming subsequent prose.\n const suffix = /^[\\p{L}\\p{M}\\p{N}_.’'-]*/u.exec(text.slice(caret))?.[0] ?? \"\";\n return {\n character,\n text: (beforeCaret + suffix).replace(/\\p{Zs}+/gu, \" \").trim(),\n start,\n end: caret + suffix.length,\n spaceAfter: !suffix && /\\p{Zs}$/u.test(beforeCaret),\n };\n}\n\nexport function continuesPastQuery(label: string, query: string): boolean {\n const normalize = (text: string) =>\n text\n .normalize(\"NFD\")\n .replace(/\\p{M}/gu, \"\")\n .replace(/\\s+/gu, \" \")\n .toLocaleLowerCase();\n return ` ${normalize(label)}`.includes(` ${normalize(query)} `);\n}\n", "type": "registry:lib" } ], diff --git a/apps/ui/public/r/composer.json b/apps/ui/public/r/composer.json index bac3ae84a..f33590d88 100644 --- a/apps/ui/public/r/composer.json +++ b/apps/ui/public/r/composer.json @@ -11,7 +11,7 @@ "files": [ { "path": "registry/default/ui/composer.tsx", - "content": "\"use client\";\n\nimport { Button as ButtonPrimitive } from \"@base-ui/react/button\";\nimport { mergeProps } from \"@base-ui/react/merge-props\";\nimport { Popover as PopoverPrimitive } from \"@base-ui/react/popover\";\nimport { useRender } from \"@base-ui/react/use-render\";\nimport type {\n ComponentProps,\n MouseEvent,\n ReactElement,\n ReactNode,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n type ComposerEditorOptions,\n ComposerEditorProvider,\n type ComposerItemValue,\n type ComposerTokenPart,\n focusComposerInput,\n getComposerText,\n useComposerAnchorContext,\n useComposerEditorContext,\n useComposerInputLayout,\n useComposerItem,\n useComposerSuggestionsContext,\n} from \"@/registry/default/lib/composer-editor\";\nimport { cn } from \"@/registry/default/lib/utils\";\nimport { ScrollArea } from \"@/registry/default/ui/scroll-area\";\n\ntype ComposerPopupProps = ComponentProps & {\n anchor?: ComponentProps[\"anchor\"];\n side?: ComponentProps[\"side\"];\n align?: ComponentProps[\"align\"];\n sideOffset?: ComponentProps[\"sideOffset\"];\n alignOffset?: ComponentProps<\n typeof PopoverPrimitive.Positioner\n >[\"alignOffset\"];\n positionerClassName?: string;\n portalProps?: ComponentProps;\n};\n\ntype ComposerFormProps = useRender.ComponentProps<\"form\">;\ntype ComposerLayout = \"stacked\" | \"adaptive\";\ntype ComposerTokenVariant = \"default\" | \"chip\";\nconst composerTokenClassName =\n \"wrap-break-word inline cursor-default align-baseline font-normal text-primary data-[variant=default]:font-medium data-[variant=chip]:box-decoration-clone data-[variant=chip]:rounded-md data-[variant=chip]:bg-accent data-[variant=chip]:px-1.5 data-[variant=chip]:py-px data-[variant=chip]:text-accent-foreground [&_[data-slot=composer-token-icon]:empty]:hidden [&_[data-slot=composer-token-icon]>svg]:size-3.5\";\n\nfunction ComposerFrame({\n className,\n layout = \"stacked\",\n render,\n ref,\n name,\n children,\n ...props\n}: ComposerFormProps & { layout?: ComposerLayout }): ReactElement {\n const editor = useComposerEditorContext();\n const anchorRef = useComposerAnchorContext();\n const defaultProps = {\n \"data-slot\": \"composer\",\n \"data-layout\": layout,\n \"data-base-ui-swipe-ignore\": \"\",\n onMouseDown: (event: MouseEvent): void => {\n focusComposerInput(event, true);\n },\n onClick: (event: MouseEvent): void => {\n focusComposerInput(event, false);\n },\n \"data-disabled\": editor?.disabled ? \"\" : undefined,\n \"data-readonly\": editor?.readOnly ? \"\" : undefined,\n children: (\n <>\n {children}\n {name && (\n \n )}\n \n ),\n className: cn(\n \"relative flex min-h-0 min-w-0 cursor-text flex-col data-disabled:cursor-default rounded-(--composer-radius) border border-input bg-background not-dark:bg-clip-padding pb-[calc(var(--composer-padding)-1px)] text-foreground shadow-xs/5 ring-ring/24 transition-shadow [--composer-radius:var(--radius-xl)] [--composer-max-rows:4] [--composer-padding:--spacing(2)] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--composer-radius)-1px)] not-data-disabled:not-has-[[data-slot=composer-input]:focus-visible]:not-has-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] has-[[data-slot=composer-input]:focus-visible]:has-aria-invalid:border-destructive/64 has-[[data-slot=composer-input]:focus-visible]:has-aria-invalid:ring-destructive/16 has-[[data-slot=composer-input]:focus-visible]:border-ring has-aria-invalid:border-destructive/36 has-[[data-slot=composer-input]:focus-visible]:shadow-none has-aria-invalid:shadow-none has-[[data-slot=composer-input]:focus-visible]:ring-[3px] aria-invalid:border-destructive/36 aria-invalid:shadow-none data-disabled:opacity-64 data-disabled:shadow-none dark:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:has-aria-invalid:ring-destructive/24 dark:not-data-disabled:not-has-[[data-slot=composer-input]:focus-visible]:not-has-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)] md:[--composer-max-rows:8]\",\n \"data-[layout=adaptive]:data-multiline:grid-rows-[minmax(0,1fr)_auto] data-[layout=adaptive]:grid data-[layout=adaptive]:grid-cols-[auto_minmax(0,1fr)_auto] data-[layout=adaptive]:items-center data-[layout=adaptive]:not-data-multiline:px-[calc(--spacing(2)-1px)] data-[layout=adaptive]:not-data-multiline:pt-[calc(var(--composer-padding)-1px)]\",\n className,\n ),\n };\n return useRender({\n defaultTagName: \"form\",\n render,\n ref: [anchorRef ?? null, ref ?? null],\n props: mergeProps<\"form\">(defaultProps, editor?.formProps ?? {}, props),\n });\n}\n\nexport type ComposerProps = Omit<\n ComposerFormProps,\n \"defaultValue\" | \"onSubmit\" | \"name\"\n> &\n ComposerEditorOptions & { layout?: ComposerLayout };\n\nexport function Composer({\n layout,\n value,\n defaultValue,\n onValueChange,\n onSubmit,\n onQueryChange,\n onAction,\n submitOnEmptySuggestions,\n triggers,\n disabled,\n readOnly,\n submitDisabled,\n allowEmpty,\n submitOnEnter,\n name,\n getSuggestionsAnnouncement,\n ...frameProps\n}: ComposerProps): ReactElement {\n return (\n \n \n \n );\n}\n\nexport function ComposerInput({\n className,\n placeholder,\n renderToken,\n render,\n ref,\n ...props\n}: useRender.ComponentProps<\"div\"> & {\n placeholder?: string;\n renderToken?: (token: ComposerTokenPart) => ReactNode;\n}): ReactElement {\n const editor = useComposerEditorContext();\n const suggestions = useComposerSuggestionsContext();\n const tokenHosts = editor?.tokenHosts;\n const { scrollRef, inputRef: layoutInputRef } = useComposerInputLayout();\n const textarea = editor?.isTextarea ?? false;\n const { ref: editorRef, ...editorProps } = editor?.inputProps ?? {};\n const defaultProps = {\n \"data-slot\": \"composer-input\",\n ...(render === undefined\n ? {\n contentEditable: true,\n role: \"textbox\" as const,\n \"aria-multiline\": true as const,\n suppressContentEditableWarning: true,\n }\n : {}),\n \"data-empty\":\n !textarea && editor?.isEmpty && !editor.isComposing ? \"\" : undefined,\n ...(textarea ? { placeholder } : {}),\n \"data-placeholder\": placeholder,\n \"aria-placeholder\": editor ? placeholder : undefined,\n className: cn(\n \"field-sizing-content wrap-anywhere relative block min-h-[calc(var(--composer-min-rows,1)*1lh+--spacing(2))] w-full min-w-0 resize-none whitespace-pre-wrap border-0 bg-transparent in-[[data-layout=adaptive]:not([data-multiline])]:px-1 px-[calc(--spacing(3)-1px)] py-1 outline-none placeholder:text-muted-foreground/72 data-empty:before:pointer-events-none data-empty:before:absolute data-empty:before:text-muted-foreground/72 data-empty:before:content-[attr(data-placeholder)] md:in-data-[layout=adaptive]:min-h-[calc(var(--composer-min-rows,1)*1lh+--spacing(2))] md:min-h-[calc(var(--composer-min-rows,2)*1lh+--spacing(2))]\",\n className,\n ),\n };\n const inputBehaviorProps = textarea\n ? {\n contentEditable: undefined,\n disabled: editor?.disabled,\n readOnly: editor?.readOnly,\n }\n : (suggestions?.inputProps ?? {});\n const input = useRender({\n defaultTagName: \"div\",\n render,\n ref: [editorRef ?? null, layoutInputRef, ref ?? null],\n props: mergeProps<\"div\">(\n defaultProps,\n editorProps,\n inputBehaviorProps,\n props,\n ),\n });\n return (\n <>\n {/* The drawer reserves keyboard space; its nested input scroller needs no extra bottom padding. */}\n \n {input}\n \n {tokenHosts?.map((host, index) => {\n const node = host.parentElement;\n if (!node) return null;\n const token: ComposerTokenPart = {\n type: node.dataset.composerToken === \"action\" ? \"action\" : \"mention\",\n id: node.dataset.id ?? \"\",\n label: node.dataset.label ?? \"\",\n trigger: node.dataset.trigger ?? \"@\",\n ...(node.dataset.kind ? { kind: node.dataset.kind } : {}),\n ...(node.dataset.data !== undefined\n ? { data: node.dataset.data }\n : {}),\n ...(node.dataset.text !== undefined\n ? { text: node.dataset.text }\n : {}),\n };\n return createPortal(\n renderToken?.(token) ?? ,\n host,\n String(index),\n );\n })}\n \n );\n}\n\nexport function ComposerToken({\n variant = \"default\",\n token,\n icon,\n children,\n className,\n ...props\n}: Omit, \"contentEditable\"> & {\n variant?: ComposerTokenVariant;\n token: ComposerTokenPart;\n icon?: ReactNode;\n}): ReactElement {\n return (\n \n {variant === \"chip\" && icon && (\n svg]:inline-block [&>svg]:align-[-0.125em]\"\n data-slot=\"composer-token-icon\"\n >\n {icon}\n \n )}\n \n {variant === \"default\" && token.trigger}\n {children ?? token.label}\n \n \n );\n}\n\nexport function ComposerPopup({\n className,\n anchor,\n side = \"top\",\n align = \"start\",\n sideOffset = 4,\n alignOffset,\n positionerClassName,\n portalProps,\n ...props\n}: ComposerPopupProps): ReactElement {\n const anchorRef = useComposerAnchorContext();\n const editor = useComposerEditorContext();\n return (\n \n \n \n \n \n );\n}\n\nexport function ComposerList({\n className,\n children,\n render,\n ref,\n ...props\n}: Omit, \"children\"> & {\n children?:\n | ReactNode\n | ((item: ComposerItemValue, index: number) => ReactNode);\n}): ReactElement {\n const suggestions = useComposerSuggestionsContext();\n const defaultProps = {\n \"data-slot\": \"composer-list\",\n id: suggestions?.listId,\n role: suggestions ? \"listbox\" : undefined,\n \"aria-label\": suggestions ? \"Suggestions\" : undefined,\n children:\n typeof children === \"function\"\n ? (suggestions?.items as readonly ComposerItemValue[] | undefined)?.map(\n children,\n )\n : children,\n className: cn(\n \"not-empty:scroll-py-1 not-empty:p-1 in-data-has-overflow-y:pe-3\",\n className,\n ),\n };\n const list = useRender({\n defaultTagName: \"div\",\n render,\n ref: [suggestions?.registerList ?? null, ref ?? null],\n props: mergeProps<\"div\">(defaultProps, props),\n });\n return (\n \n {list}\n \n );\n}\n\nexport function ComposerItem({\n className,\n value,\n disabled: disabledProp,\n render,\n ref,\n ...props\n}: Omit<\n useRender.ComponentProps<\n \"button\",\n { highlighted: boolean; disabled: boolean }\n >,\n \"value\"\n> & {\n value?: ComposerItemValue;\n}): ReactElement {\n const disabled = Boolean(disabledProp || value?.disabled);\n const item = useComposerItem(value, disabled);\n const { highlighted } = item;\n const defaultProps = {\n ...item.props,\n type: \"button\" as const,\n \"data-slot\": \"composer-item\",\n disabled,\n className: cn(\n \"flex min-h-8 w-full cursor-default select-none items-center gap-2 rounded-sm px-2 py-1 text-start text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm\",\n className,\n ),\n };\n return useRender({\n defaultTagName: \"button\",\n render,\n ref: [item.ref, ref ?? null],\n state: { highlighted, disabled },\n props: mergeProps<\"button\">(defaultProps, props),\n });\n}\n\nexport function ComposerStatus({\n className,\n render,\n ref,\n ...props\n}: useRender.ComponentProps<\"div\">): ReactElement {\n const defaultProps = {\n role: \"status\",\n \"data-slot\": \"composer-status\",\n className: cn(\n \"px-3 py-2 font-medium text-muted-foreground text-xs empty:m-0 empty:p-0\",\n className,\n ),\n };\n return useRender({\n defaultTagName: \"div\",\n render,\n ref,\n props: mergeProps<\"div\">(defaultProps, props),\n });\n}\n\nexport function ComposerActions({\n className,\n ...props\n}: ComponentProps<\"div\">): ReactElement {\n return (\n \n );\n}\n\nexport function ComposerActionGroup({\n className,\n align = \"start\",\n ...props\n}: ComponentProps<\"div\"> & { align?: \"start\" | \"end\" }): ReactElement {\n return (\n \n );\n}\n\nexport function ComposerSubmit({\n disabled,\n className,\n style,\n render,\n ref,\n ...props\n}: Omit, \"type\">): ReactElement {\n const editor = useComposerEditorContext();\n const preserveInputFocus = (event: MouseEvent): void => {\n const input = editor?.rootRef.current?.querySelector(\n '[data-slot=\"composer-input\"]',\n );\n if (\n event.button === 0 &&\n input === event.currentTarget.ownerDocument.activeElement\n ) {\n event.preventDefault();\n }\n };\n const defaultProps = {\n \"data-slot\": \"composer-submit\",\n type: \"button\" as const,\n disabled: disabled ?? !editor?.canSubmit,\n onPointerDown: preserveInputFocus,\n // iOS can still move focus on compatibility mousedown after pointerdown is canceled.\n onMouseDown: preserveInputFocus,\n onClick: (event: MouseEvent): void => {\n if (event.defaultPrevented || disabled) return;\n event.preventDefault();\n editor?.submit();\n },\n };\n return (\n (defaultProps, props)}\n className={className}\n style={style}\n render={render}\n ref={ref}\n />\n );\n}\n\nexport {\n type ComposerChangeDetails,\n type ComposerItemValue,\n type ComposerPart,\n type ComposerQuery,\n type ComposerTokenPart,\n type ComposerTrigger,\n type ComposerValue,\n getComposerText,\n useComposerContext,\n useComposerFilter,\n} from \"@/registry/default/lib/composer-editor\";\nexport type { ComposerPopupProps, ComposerTokenVariant };\n", + "content": "\"use client\";\n\nimport { Button as ButtonPrimitive } from \"@base-ui/react/button\";\nimport { mergeProps } from \"@base-ui/react/merge-props\";\nimport { Popover as PopoverPrimitive } from \"@base-ui/react/popover\";\nimport { useRender } from \"@base-ui/react/use-render\";\nimport type {\n ComponentProps,\n MouseEvent,\n ReactElement,\n ReactNode,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n type ComposerEditorOptions,\n ComposerEditorProvider,\n type ComposerItemValue,\n type ComposerTokenPart,\n focusComposerInput,\n getComposerText,\n useComposerAnchorContext,\n useComposerEditorContext,\n useComposerInputLayout,\n useComposerItem,\n useComposerSuggestionsContext,\n} from \"@/registry/default/lib/composer-editor\";\nimport { cn } from \"@/registry/default/lib/utils\";\nimport { ScrollArea } from \"@/registry/default/ui/scroll-area\";\n\ntype ComposerPopupProps = ComponentProps & {\n anchor?: ComponentProps[\"anchor\"];\n side?: ComponentProps[\"side\"];\n align?: ComponentProps[\"align\"];\n sideOffset?: ComponentProps[\"sideOffset\"];\n alignOffset?: ComponentProps<\n typeof PopoverPrimitive.Positioner\n >[\"alignOffset\"];\n positionerClassName?: string;\n portalProps?: ComponentProps;\n};\n\ntype ComposerFormProps = useRender.ComponentProps<\"form\">;\ntype ComposerLayout = \"stacked\" | \"adaptive\";\ntype ComposerTokenVariant = \"default\" | \"chip\";\nconst composerTokenClassName =\n \"wrap-break-word inline cursor-default align-baseline font-normal text-primary data-[variant=default]:font-medium data-[variant=chip]:box-decoration-clone data-[variant=chip]:rounded-md data-[variant=chip]:bg-accent data-[variant=chip]:px-1.5 data-[variant=chip]:py-px data-[variant=chip]:text-accent-foreground [&_[data-slot=composer-token-icon]:empty]:hidden [&_[data-slot=composer-token-icon]>svg]:size-3.5\";\n\nfunction ComposerFrame({\n className,\n layout = \"stacked\",\n render,\n ref,\n name,\n children,\n ...props\n}: ComposerFormProps & { layout?: ComposerLayout }): ReactElement {\n const editor = useComposerEditorContext();\n const anchorRef = useComposerAnchorContext();\n const defaultProps = {\n \"data-slot\": \"composer\",\n \"data-layout\": layout,\n \"data-base-ui-swipe-ignore\": \"\",\n onMouseDown: (event: MouseEvent): void => {\n focusComposerInput(event, true);\n },\n onClick: (event: MouseEvent): void => {\n focusComposerInput(event, false);\n },\n \"data-disabled\": editor?.disabled ? \"\" : undefined,\n \"data-readonly\": editor?.readOnly ? \"\" : undefined,\n children: (\n <>\n {children}\n {name && (\n \n )}\n \n ),\n className: cn(\n \"relative flex min-h-0 min-w-0 cursor-text flex-col data-disabled:cursor-default rounded-(--composer-radius) border border-input bg-background not-dark:bg-clip-padding pb-[calc(var(--composer-padding)-1px)] text-foreground shadow-xs/5 ring-ring/24 transition-shadow [--composer-radius:var(--radius-xl)] [--composer-max-rows:4] [--composer-padding:--spacing(2)] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--composer-radius)-1px)] not-data-disabled:not-has-[[data-slot=composer-input]:focus-visible]:not-has-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] has-[[data-slot=composer-input]:focus-visible]:has-aria-invalid:border-destructive/64 has-[[data-slot=composer-input]:focus-visible]:has-aria-invalid:ring-destructive/16 has-[[data-slot=composer-input]:focus-visible]:border-ring has-aria-invalid:border-destructive/36 has-[[data-slot=composer-input]:focus-visible]:shadow-none has-aria-invalid:shadow-none has-[[data-slot=composer-input]:focus-visible]:ring-[3px] aria-invalid:border-destructive/36 aria-invalid:shadow-none data-disabled:opacity-64 data-disabled:shadow-none dark:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:has-aria-invalid:ring-destructive/24 dark:not-data-disabled:not-has-[[data-slot=composer-input]:focus-visible]:not-has-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)] md:[--composer-max-rows:8]\",\n \"data-[layout=adaptive]:data-multiline:grid-rows-[minmax(0,1fr)_auto] data-[layout=adaptive]:grid data-[layout=adaptive]:grid-cols-[auto_minmax(0,1fr)_auto] data-[layout=adaptive]:items-center data-[layout=adaptive]:not-data-multiline:px-[calc(--spacing(2)-1px)] data-[layout=adaptive]:not-data-multiline:pt-[calc(var(--composer-padding)-1px)]\",\n className,\n ),\n };\n return useRender({\n defaultTagName: \"form\",\n render,\n ref: [anchorRef ?? null, ref ?? null],\n props: mergeProps<\"form\">(defaultProps, editor?.formProps ?? {}, props),\n });\n}\n\nexport type ComposerProps = Omit<\n ComposerFormProps,\n \"defaultValue\" | \"onSubmit\" | \"name\"\n> &\n ComposerEditorOptions & { layout?: ComposerLayout };\n\nexport function Composer({\n layout,\n value,\n defaultValue,\n onValueChange,\n onSubmit,\n onQueryChange,\n onAction,\n submitOnEmptySuggestions,\n triggers,\n disabled,\n readOnly,\n submitDisabled,\n allowEmpty,\n submitOnEnter,\n name,\n getSuggestionsAnnouncement,\n ...frameProps\n}: ComposerProps): ReactElement {\n return (\n \n \n \n );\n}\n\nexport function ComposerInput({\n className,\n placeholder,\n renderToken,\n render,\n ref,\n ...props\n}: useRender.ComponentProps<\"div\"> & {\n placeholder?: string;\n renderToken?: (token: ComposerTokenPart) => ReactNode;\n}): ReactElement {\n const editor = useComposerEditorContext();\n const suggestions = useComposerSuggestionsContext();\n const tokenHosts = editor?.tokenHosts;\n const { scrollRef, inputRef: layoutInputRef } = useComposerInputLayout();\n const textarea = editor?.isTextarea ?? false;\n const { ref: editorRef, ...editorProps } = editor?.inputProps ?? {};\n const defaultProps = {\n \"data-slot\": \"composer-input\",\n ...(render === undefined\n ? {\n contentEditable: true,\n role: \"textbox\" as const,\n \"aria-multiline\": true as const,\n suppressContentEditableWarning: true,\n }\n : {}),\n \"data-empty\":\n !textarea && editor?.isEmpty && !editor.isComposing ? \"\" : undefined,\n ...(textarea ? { placeholder } : {}),\n \"data-placeholder\": placeholder,\n \"aria-placeholder\": editor ? placeholder : undefined,\n className: cn(\n \"field-sizing-content wrap-anywhere relative block min-h-[calc(var(--composer-min-rows,1)*1lh+--spacing(2))] w-full min-w-0 resize-none whitespace-pre-wrap border-0 bg-transparent in-[[data-layout=adaptive]:not([data-multiline])]:px-1 px-[calc(--spacing(3)-1px)] py-1 outline-none placeholder:text-muted-foreground/72 data-empty:before:pointer-events-none data-empty:before:absolute data-empty:before:text-muted-foreground/72 data-empty:before:content-[attr(data-placeholder)] md:in-data-[layout=adaptive]:min-h-[calc(var(--composer-min-rows,1)*1lh+--spacing(2))] md:min-h-[calc(var(--composer-min-rows,2)*1lh+--spacing(2))]\",\n className,\n ),\n };\n const inputBehaviorProps = textarea\n ? {\n contentEditable: undefined,\n disabled: editor?.disabled,\n readOnly: editor?.readOnly,\n }\n : (suggestions?.inputProps ?? {});\n const input = useRender({\n defaultTagName: \"div\",\n render,\n ref: [editorRef ?? null, layoutInputRef, ref ?? null],\n props: mergeProps<\"div\">(\n defaultProps,\n editorProps,\n inputBehaviorProps,\n props,\n ),\n });\n return (\n <>\n \n {input}\n \n {tokenHosts?.map((host, index) => {\n const node = host.parentElement;\n if (!node) return null;\n const token: ComposerTokenPart = {\n type: node.dataset.composerToken === \"action\" ? \"action\" : \"mention\",\n id: node.dataset.id ?? \"\",\n label: node.dataset.label ?? \"\",\n trigger: node.dataset.trigger ?? \"@\",\n ...(node.dataset.kind ? { kind: node.dataset.kind } : {}),\n ...(node.dataset.data !== undefined\n ? { data: node.dataset.data }\n : {}),\n ...(node.dataset.text !== undefined\n ? { text: node.dataset.text }\n : {}),\n };\n return createPortal(\n renderToken?.(token) ?? ,\n host,\n String(index),\n );\n })}\n \n );\n}\n\nexport function ComposerToken({\n variant = \"default\",\n token,\n icon,\n children,\n className,\n ...props\n}: Omit, \"contentEditable\"> & {\n variant?: ComposerTokenVariant;\n token: ComposerTokenPart;\n icon?: ReactNode;\n}): ReactElement {\n return (\n \n {variant === \"chip\" && icon && (\n svg]:inline-block [&>svg]:align-[-0.125em]\"\n data-slot=\"composer-token-icon\"\n >\n {icon}\n \n )}\n \n {variant === \"default\" && token.trigger}\n {children ?? token.label}\n \n \n );\n}\n\nexport function ComposerPopup({\n className,\n anchor,\n side = \"top\",\n align = \"start\",\n sideOffset = 4,\n alignOffset,\n positionerClassName,\n portalProps,\n ...props\n}: ComposerPopupProps): ReactElement {\n const anchorRef = useComposerAnchorContext();\n const editor = useComposerEditorContext();\n return (\n \n \n \n \n \n );\n}\n\nexport function ComposerList({\n className,\n children,\n render,\n ref,\n ...props\n}: Omit, \"children\"> & {\n children?:\n | ReactNode\n | ((item: ComposerItemValue, index: number) => ReactNode);\n}): ReactElement {\n const suggestions = useComposerSuggestionsContext();\n const defaultProps = {\n \"data-slot\": \"composer-list\",\n id: suggestions?.listId,\n role: suggestions ? \"listbox\" : undefined,\n \"aria-label\": suggestions ? \"Suggestions\" : undefined,\n children:\n typeof children === \"function\"\n ? (suggestions?.items as readonly ComposerItemValue[] | undefined)?.map(\n children,\n )\n : children,\n className: cn(\n \"not-empty:scroll-py-1 not-empty:p-1 in-data-has-overflow-y:pe-3\",\n className,\n ),\n };\n const list = useRender({\n defaultTagName: \"div\",\n render,\n ref: [suggestions?.registerList ?? null, ref ?? null],\n props: mergeProps<\"div\">(defaultProps, props),\n });\n return (\n \n {list}\n \n );\n}\n\nexport function ComposerItem({\n className,\n value,\n disabled: disabledProp,\n render,\n ref,\n ...props\n}: Omit<\n useRender.ComponentProps<\n \"button\",\n { highlighted: boolean; disabled: boolean }\n >,\n \"value\"\n> & {\n value?: ComposerItemValue;\n}): ReactElement {\n const disabled = Boolean(disabledProp || value?.disabled);\n const item = useComposerItem(value, disabled);\n const { highlighted } = item;\n const defaultProps = {\n ...item.props,\n type: \"button\" as const,\n \"data-slot\": \"composer-item\",\n disabled,\n className: cn(\n \"flex min-h-8 w-full cursor-default select-none items-center gap-2 rounded-sm px-2 py-1 text-start text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm\",\n className,\n ),\n };\n return useRender({\n defaultTagName: \"button\",\n render,\n ref: [item.ref, ref ?? null],\n state: { highlighted, disabled },\n props: mergeProps<\"button\">(defaultProps, props),\n });\n}\n\nexport function ComposerStatus({\n className,\n render,\n ref,\n ...props\n}: useRender.ComponentProps<\"div\">): ReactElement {\n const defaultProps = {\n role: \"status\",\n \"data-slot\": \"composer-status\",\n className: cn(\n \"px-3 py-2 font-medium text-muted-foreground text-xs empty:m-0 empty:p-0\",\n className,\n ),\n };\n return useRender({\n defaultTagName: \"div\",\n render,\n ref,\n props: mergeProps<\"div\">(defaultProps, props),\n });\n}\n\nexport function ComposerActions({\n className,\n ...props\n}: ComponentProps<\"div\">): ReactElement {\n return (\n \n );\n}\n\nexport function ComposerActionGroup({\n className,\n align = \"start\",\n ...props\n}: ComponentProps<\"div\"> & { align?: \"start\" | \"end\" }): ReactElement {\n return (\n \n );\n}\n\nexport function ComposerSubmit({\n disabled,\n className,\n style,\n render,\n ref,\n ...props\n}: Omit, \"type\">): ReactElement {\n const editor = useComposerEditorContext();\n const preserveInputFocus = (event: MouseEvent): void => {\n const input = editor?.rootRef.current?.querySelector(\n '[data-slot=\"composer-input\"]',\n );\n if (\n event.button === 0 &&\n input === event.currentTarget.ownerDocument.activeElement\n ) {\n event.preventDefault();\n }\n };\n const defaultProps = {\n \"data-slot\": \"composer-submit\",\n type: \"button\" as const,\n disabled: disabled ?? !editor?.canSubmit,\n onPointerDown: preserveInputFocus,\n onMouseDown: preserveInputFocus,\n onClick: (event: MouseEvent): void => {\n if (event.defaultPrevented || disabled) return;\n event.preventDefault();\n editor?.submit();\n },\n };\n return (\n (defaultProps, props)}\n className={className}\n style={style}\n render={render}\n ref={ref}\n />\n );\n}\n\nexport {\n type ComposerChangeDetails,\n type ComposerItemValue,\n type ComposerPart,\n type ComposerQuery,\n type ComposerTokenPart,\n type ComposerTrigger,\n type ComposerValue,\n getComposerText,\n useComposerContext,\n useComposerFilter,\n} from \"@/registry/default/lib/composer-editor\";\nexport type { ComposerPopupProps, ComposerTokenVariant };\n", "type": "registry:ui" } ], diff --git a/apps/ui/public/r/p-composer-13.json b/apps/ui/public/r/p-composer-13.json new file mode 100644 index 000000000..8af92c2f2 --- /dev/null +++ b/apps/ui/public/r/p-composer-13.json @@ -0,0 +1,33 @@ +{ + "$schema": "https://ui.shadcn.com/schema/registry-item.json", + "name": "p-composer-13", + "description": "Composer mention list that can stay open to mention several people in a row", + "dependencies": [ + "lucide-react" + ], + "registryDependencies": [ + "@coss/avatar", + "@coss/badge", + "@coss/button", + "@coss/composer", + "@coss/kbd" + ], + "files": [ + { + "path": "registry/default/particles/p-composer-13.tsx", + "content": "\"use client\";\n\nimport { ArrowUpIcon } from \"lucide-react\";\nimport {\n type KeyboardEvent,\n type MouseEvent,\n useId,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\";\nimport {\n Avatar,\n AvatarFallback,\n AvatarImage,\n} from \"@/registry/default/ui/avatar\";\nimport { Badge } from \"@/registry/default/ui/badge\";\nimport { Button } from \"@/registry/default/ui/button\";\nimport {\n Composer,\n ComposerActionGroup,\n ComposerActions,\n ComposerInput,\n ComposerItem,\n type ComposerItemValue,\n ComposerList,\n type ComposerPart,\n ComposerPopup,\n ComposerSubmit,\n ComposerToken,\n type ComposerValue,\n getComposerText,\n useComposerFilter,\n} from \"@/registry/default/ui/composer\";\nimport { Kbd } from \"@/registry/default/ui/kbd\";\n\ntype Tag = { id: string; label: string; color: string; people: string[] };\ntype ItemClickEvent = MouseEvent & {\n preventBaseUIHandler?: () => void;\n};\n\nconst slug = (name: string) => name.toLowerCase().replaceAll(\" \", \"-\");\nconst peopleCount = (count: number) =>\n `${count} ${count === 1 ? \"person\" : \"people\"}`;\n\nconst photo = (id: string) =>\n `https://images.unsplash.com/photo-${id}?w=96&h=96&dpr=2&q=80`;\n\nconst memberData = [\n [\"Alex Morgan\", \"Design\", \"1543610892-0b1f7e6d8ac1\"],\n [\"Sam Rivera\", \"Engineering\", \"1507003211169-0a1dd7228f2d\"],\n [\"Taylor Kim\", \"Product\", \"1472099645785-5658abf4ff4e\"],\n [\"Jordan Lee\", \"Marketing\", \"1500648767791-00dcc994a43e\"],\n [\"Casey Chen\", \"Support\", \"1494790108377-be9c29b29330\"],\n [\"Morgan Davis\", \"Operations\", \"1655874819398-c6dfbec68ac7\"],\n [\"Jamie Wilson\", \"Finance\", \"1438761681033-6461ffad8d80\"],\n [\"Riley Patel\", \"Research\", \"1628157588553-5eeea00af15c\"],\n] as const;\n\nconst members: ComposerItemValue[] = memberData.map(([label, description]) => ({\n description,\n id: `member:${slug(label)}`,\n kind: \"member\",\n label,\n}));\n\nconst photos: Record = Object.fromEntries(\n memberData.map(([label, , image]) => [`member:${slug(label)}`, photo(image)]),\n);\n\nconst tags: Tag[] = [\n {\n color: \"bg-sky-500\",\n id: \"tag:clients\",\n label: \"Clients\",\n people: [\n \"Ben Carter\",\n \"Chloe Martin\",\n \"Sarah Lim\",\n \"Tom Okafor\",\n \"Ava Novak\",\n ],\n },\n {\n color: \"bg-amber-500\",\n id: \"tag:newsletter\",\n label: \"Newsletter\",\n people: [\n \"Aiden Brooks\",\n \"Bella Ortiz\",\n \"Caleb Foster\",\n \"Daisy Nguyen\",\n \"Elijah Grant\",\n \"Fiona Walsh\",\n \"Gabriel Silva\",\n \"Hannah Reed\",\n \"Isaac Moreno\",\n \"Julia Hart\",\n \"Kai Thompson\",\n \"Lena Fischer\",\n \"Mason Clarke\",\n \"Nora Bennett\",\n \"Oscar Diaz\",\n \"Priya Shah\",\n \"Quinn Murphy\",\n \"Rosa Alvarez\",\n \"Sarah Lim\",\n \"Tara Quinn\",\n \"Umar Haddad\",\n \"Vera Lindqvist\",\n \"Wes Turner\",\n \"Xena Park\",\n \"Yusuf Demir\",\n ],\n },\n];\n\nconst tagsOf = (name: string) =>\n tags.filter((tag) => tag.people.includes(name));\n\nconst contacts: ComposerItemValue[] = [\n ...new Set(tags.flatMap((tag) => tag.people)),\n]\n .sort((a, b) => a.localeCompare(b))\n .map((label) => ({\n description: `${slug(label).replace(\"-\", \".\")}@example.com`,\n id: `contact:${slug(label)}`,\n kind: \"contact\",\n label,\n }));\n\nconst tagItems: ComposerItemValue[] = tags.map((tag) => ({\n description: peopleCount(tag.people.length),\n id: tag.id,\n kind: \"tag\",\n label: tag.label,\n}));\n\nconst sections = [\n { kind: \"member\", label: \"Team members\" },\n { kind: \"contact\", label: \"Contacts\" },\n { kind: \"tag\", label: \"Tags\" },\n] as const;\n\nfunction getSegments(input: HTMLElement, value: ComposerValue) {\n const chips = value.filter((part) => part.type !== \"text\");\n let offset = 0;\n return Array.from(input.childNodes, (node) => {\n const length =\n node instanceof Text\n ? node.length\n : node instanceof HTMLBRElement\n ? 1\n : getComposerText(chips.splice(0, 1)).length;\n offset += length;\n return { end: offset, node, start: offset - length };\n });\n}\n\nfunction spliceText(\n value: ComposerValue,\n start: number,\n end: number,\n insert: readonly ComposerPart[],\n): ComposerValue {\n let offset = 0;\n return value.flatMap((part): ComposerPart[] => {\n const from = offset;\n offset += getComposerText([part]).length;\n if (part.type !== \"text\" || start < from || start >= offset) return [part];\n const text = (cut: string): ComposerPart[] =>\n cut ? [{ text: cut, type: \"text\" }] : [];\n return [\n ...text(part.text.slice(0, start - from)),\n ...insert,\n ...text(part.text.slice(end - from)),\n ];\n });\n}\n\nfunction PersonAvatar({ item }: { item: ComposerItemValue }) {\n return (\n \n {photos[item.id] && }\n \n {item.label\n .split(\" \")\n .map((word) => word[0])\n .join(\"\")}\n \n \n );\n}\n\nfunction Dot({ color, className }: { color?: string; className: string }) {\n return ;\n}\n\nexport default function Particle() {\n const [value, setValue] = useState([]);\n const [queryText, setQueryText] = useState(\"\");\n const { contains, startsWith } = useComposerFilter();\n const sectionId = useId();\n const inputRef = useRef(null);\n const listRef = useRef(null);\n const caretAfter = useRef(null);\n const keptOpen = useRef(false);\n\n useLayoutEffect(() => {\n const input = inputRef.current;\n const target = caretAfter.current;\n if (!input || target === null) return;\n caretAfter.current = null;\n const segment = getSegments(input, value).find(\n ({ node, start, end }) =>\n node instanceof Text && start <= target && target <= end,\n );\n if (!segment) return;\n window.getSelection()?.collapse(segment.node, target - segment.start);\n document.dispatchEvent(new Event(\"selectionchange\"));\n });\n\n function findQuery() {\n const input = inputRef.current;\n const selection = window.getSelection();\n if (!input || !selection?.isCollapsed) return null;\n const segment = getSegments(input, value).find(\n ({ node }) => node === selection.anchorNode,\n );\n if (!segment) return null;\n const caret = segment.start + selection.anchorOffset;\n const start = getComposerText(value).lastIndexOf(\"@\", caret - 1);\n return start < 0 ? null : { caret, start };\n }\n\n function mentionAndKeepOpen(item: ComposerItemValue) {\n const query = findQuery();\n if (!query) return;\n const chip: ComposerPart = {\n id: item.id,\n kind: item.kind,\n label: item.label,\n trigger: \"@\",\n type: \"mention\",\n };\n const typed = getComposerText(value).slice(query.start, query.caret);\n const insert: ComposerPart[] = [chip, { text: ` ${typed}`, type: \"text\" }];\n keptOpen.current = true;\n caretAfter.current = query.start + getComposerText(insert).length;\n setValue(spliceText(value, query.start, query.caret, insert));\n }\n\n function handleKeyDown(event: KeyboardEvent) {\n if (event.nativeEvent.isComposing) return;\n const highlighted =\n listRef.current?.querySelector(\"[data-highlighted]\");\n if (!highlighted) return;\n if (event.key === \"Enter\" && event.shiftKey) {\n const item = items.find((entry) => entry.id === highlighted.dataset.id);\n if (!item) return;\n event.preventDefault();\n mentionAndKeepOpen(item);\n } else if (event.key === \"Escape\" && keptOpen.current) {\n const query = findQuery();\n if (!query) return;\n caretAfter.current = query.start;\n setValue(spliceText(value, query.start, query.caret, []));\n }\n }\n\n const matches = [...members, ...contacts, ...tagItems].filter(\n (item) =>\n contains(item.label, queryText) ||\n (item.kind === \"member\" && contains(item.description ?? \"\", queryText)) ||\n (item.kind === \"contact\" &&\n tagsOf(item.label).some((tag) => contains(tag.label, queryText))),\n );\n\n const startsTag = (item: ComposerItemValue) =>\n item.kind === \"tag\" && startsWith(item.label, queryText);\n const tagFirst = queryText.length >= 2 && matches.some(startsTag);\n const visibleSections = (\n tagFirst ? [sections[2], sections[0], sections[1]] : sections\n )\n .map((section) => ({\n ...section,\n items: matches\n .filter((item) => item.kind === section.kind)\n .sort((a, b) => Number(startsTag(b)) - Number(startsTag(a))),\n }))\n .filter((section) => section.items.length);\n const items = visibleSections.flatMap((section) => section.items);\n\n return (\n \n `${count} suggestion${count === 1 ? \"\" : \"s\"} available. Use the up and down arrow keys to navigate. Hold Shift while pressing Enter to mention several.`\n }\n onQueryChange={(query) => {\n if (!query) keptOpen.current = false;\n setQueryText(query?.text ?? \"\");\n }}\n onSubmit={() => setValue([])}\n onValueChange={setValue}\n triggers={[{ character: \"@\", filter: null, items }]}\n value={value}\n >\n \n token.kind === \"tag\" ? (\n tag.id === token.id)?.color}\n />\n }\n token={token}\n variant=\"chip\"\n />\n ) : (\n \n {token.trigger}\n {token.label}\n \n )\n }\n />\n \n \n {visibleSections.map(({ items: sectionItems, kind, label }) => {\n const labelId = `${sectionId}-${kind}`;\n return (\n \n \n {label}\n \n {sectionItems.map((item) => {\n const tag = tags.find((entry) => entry.id === item.id);\n const personTags =\n item.kind === \"contact\" ? tagsOf(item.label) : [];\n return (\n {\n if (!event.shiftKey) return;\n event.preventBaseUIHandler?.();\n mentionAndKeepOpen(item);\n }}\n value={item}\n >\n {tag ? (\n \n \n \n ) : (\n \n )}\n \n \n {item.label}\n \n \n {item.description}\n \n \n {personTags.length > 0 && (\n \n {personTags.map((personTag) => (\n \n \n {personTag.label}\n \n ))}\n \n )}\n \n );\n })}\n \n );\n })}\n \n \n Hold Shift to mention several\n \n \n \n \n \n \n \n }\n />\n \n \n \n );\n}\n", + "type": "registry:block" + } + ], + "meta": { + "className": "**:data-[slot=preview]:w-full **:data-[slot=preview]:max-w-xl" + }, + "categories": [ + "composer", + "avatar", + "badge", + "multiselect", + "tag" + ], + "type": "registry:block" +} \ No newline at end of file diff --git a/apps/ui/public/r/registry.json b/apps/ui/public/r/registry.json index 721a476fb..7acf19ec6 100644 --- a/apps/ui/public/r/registry.json +++ b/apps/ui/public/r/registry.json @@ -5551,6 +5551,37 @@ ], "type": "registry:block" }, + { + "categories": [ + "composer", + "avatar", + "badge", + "multiselect", + "tag" + ], + "dependencies": [ + "lucide-react" + ], + "description": "Composer mention list that can stay open to mention several people in a row", + "files": [ + { + "path": "registry/default/particles/p-composer-13.tsx", + "type": "registry:block" + } + ], + "meta": { + "className": "**:data-[slot=preview]:w-full **:data-[slot=preview]:max-w-xl" + }, + "name": "p-composer-13", + "registryDependencies": [ + "@coss/avatar", + "@coss/badge", + "@coss/button", + "@coss/composer", + "@coss/kbd" + ], + "type": "registry:block" + }, { "categories": [ "command", @@ -12828,7 +12859,8 @@ "name": "use-composer-editor", "registryDependencies": [ "@coss/composer-document", - "@coss/composer-clipboard" + "@coss/composer-clipboard", + "@coss/composer-query" ], "type": "registry:hook" }, diff --git a/apps/ui/public/r/use-composer-editor.json b/apps/ui/public/r/use-composer-editor.json index edf952239..70ef4a460 100644 --- a/apps/ui/public/r/use-composer-editor.json +++ b/apps/ui/public/r/use-composer-editor.json @@ -6,12 +6,13 @@ ], "registryDependencies": [ "@coss/composer-document", - "@coss/composer-clipboard" + "@coss/composer-clipboard", + "@coss/composer-query" ], "files": [ { "path": "registry/default/hooks/use-composer-editor.ts", - "content": "\"use client\";\n\nimport { Autocomplete as AutocompletePrimitive } from \"@base-ui/react/autocomplete\";\nimport type {\n ComponentProps,\n FormEvent,\n KeyboardEvent,\n RefObject,\n} from \"react\";\nimport {\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\";\nimport {\n COMPOSER_CLIPBOARD_TYPE,\n parseComposerClipboard,\n} from \"@/registry/default/lib/composer-clipboard\";\nimport {\n type ActiveQuery,\n type ComposerItemValue,\n type ComposerPart,\n type ComposerQuery,\n type ComposerSelection,\n type ComposerSnapshot,\n type ComposerTokenPart,\n type ComposerTrigger,\n type ComposerValue,\n currentQuery,\n equalValue,\n getComposerText,\n getFilteredItems,\n hasVisibleItems,\n insertItem,\n insertPlainText,\n readSelection,\n readValue,\n restoreSelection,\n writeValue,\n} from \"@/registry/default/lib/composer-document\";\n\ntype ComposerChangeDetails = {\n reason: \"input\" | \"selection\" | \"history\" | \"reset\";\n};\ntype UseComposerEditorOptions = {\n value: ComposerValue;\n onValueChange: (value: ComposerValue, details: ComposerChangeDetails) => void;\n onSubmit?: (value: ComposerValue) => void;\n onQueryChange?: (query: ComposerQuery | null) => void;\n onAction?: (item: ComposerItemValue, query: ComposerQuery) => void;\n submitOnEmptySuggestions?: boolean;\n triggers?: readonly ComposerTrigger[];\n disabled?: boolean;\n readOnly?: boolean;\n submitDisabled?: boolean;\n allowEmpty?: boolean;\n submitOnEnter?: \"desktop\" | \"always\" | \"never\";\n};\n\ntype ComposerEditorController = {\n value: ComposerValue;\n inputProps: ComponentProps<\"div\">;\n formProps: Pick, \"onSubmit\">;\n rootRef: RefObject;\n isEmpty: boolean;\n isTextarea: boolean;\n isComposing: boolean;\n canSubmit: boolean;\n disabled: boolean;\n readOnly: boolean;\n submit: () => void;\n insertTrigger: (character: string) => void;\n reset: (value?: ComposerValue) => void;\n status: \"ready\" | \"loading\" | \"error\";\n tokenHosts: readonly HTMLSpanElement[];\n suggestions: {\n enabled: boolean;\n submitOnEmptySuggestions: boolean;\n items: readonly ComposerItemValue[];\n open: boolean;\n onOpenChange: (open: boolean) => void;\n onItemSelect: (item: ComposerItemValue) => void;\n };\n};\n\nexport function useComposerEditor({\n value,\n onValueChange,\n onSubmit,\n onQueryChange,\n onAction,\n submitOnEmptySuggestions = false,\n triggers = [],\n disabled = false,\n readOnly = false,\n submitDisabled = false,\n allowEmpty = false,\n submitOnEnter = \"always\",\n}: UseComposerEditorOptions): ComposerEditorController {\n const inputRef = useRef(null);\n const [inputElement, setInputElement] = useState(null);\n const setInputRef = useCallback((element: HTMLDivElement | null): void => {\n inputRef.current = element;\n setInputElement(element);\n }, []);\n const isTextarea = inputElement?.tagName === \"TEXTAREA\";\n const history = useRef<{\n current: ComposerSnapshot;\n past: ComposerSnapshot[];\n future: ComposerSnapshot[];\n inputType: string;\n timestamp: number;\n }>({\n current: { value, selection: null },\n past: [],\n future: [],\n inputType: \"\",\n timestamp: 0,\n });\n const pendingInput = useRef({\n type: \"\",\n selection: null as ComposerSelection | null,\n });\n const lastSelection = useRef(null);\n const historyAction = useRef<(direction: \"undo\" | \"redo\") => void>(() => {});\n const rootRef = useRef(null);\n const composing = useRef(false);\n const [isComposing, setIsComposing] = useState(false);\n const compositionValue = useRef(value);\n const ignoreCompositionInput = useRef(false);\n const dismissedQuery = useRef(null);\n const queryAction = useRef<() => void>(() => {});\n const [query, setQuery] = useState(null);\n const [tokenHosts, setTokenHosts] = useState([]);\n const [, forceReconcile] = useState(0);\n const trigger = triggers.find((item) => item.character === query?.character);\n const { contains } = useComposerFilter();\n const options = getFilteredItems(trigger, query, contains);\n const open =\n !isTextarea &&\n !isComposing &&\n !disabled &&\n !readOnly &&\n Boolean(query) &&\n hasVisibleItems(trigger, options);\n const isEmpty = !getComposerText(value);\n const canSubmit =\n !isComposing &&\n !disabled &&\n !readOnly &&\n !submitDisabled &&\n (allowEmpty || Boolean(getComposerText(value).trim()));\n const onQueryChangeRef = useRef(onQueryChange);\n onQueryChangeRef.current = onQueryChange;\n const queryCharacter = query?.character;\n const queryText = query?.text;\n const queryKey = query?.key;\n\n const syncTokenHosts = useCallback((input: HTMLDivElement): void => {\n const next = Array.from(\n input.querySelectorAll(\n '[data-slot=\"composer-token-renderer\"]',\n ),\n );\n setTokenHosts((previous) =>\n previous.length === next.length &&\n previous.every((host, index) => host === next[index])\n ? previous\n : next,\n );\n }, []);\n\n useEffect(() => {\n onQueryChangeRef.current?.(\n queryCharacter && queryText !== undefined && queryKey\n ? { character: queryCharacter, text: queryText, key: queryKey }\n : null,\n );\n }, [queryCharacter, queryText, queryKey]);\n\n useEffect(() => {\n if (\n query &&\n (disabled ||\n readOnly ||\n !triggers.some((item) => item.character === query.character))\n )\n setQuery(null);\n }, [disabled, readOnly, query, triggers]);\n\n useLayoutEffect(() => {\n const input = inputElement;\n if (!input || input instanceof HTMLTextAreaElement || disabled || readOnly)\n return;\n const initializeCaret = (): void => {\n if (composing.current || readValue(input).length > 0) return;\n input.ownerDocument.getSelection()?.setBaseAndExtent(input, 0, input, 0);\n };\n // Initialize before focusin, while the drawer's temporary focus geometry is\n // still applied, so Safari doesn't pan to reveal the empty editor's caret.\n input.addEventListener(\"focus\", initializeCaret);\n return () => input.removeEventListener(\"focus\", initializeCaret);\n }, [inputElement, disabled, readOnly]);\n\n useEffect(() => {\n const input = inputElement;\n if (!input || input instanceof HTMLTextAreaElement) return;\n const beforeInput = (event: InputEvent) => {\n if (event.defaultPrevented) return;\n if (disabled || readOnly || event.inputType.startsWith(\"format\")) {\n event.preventDefault();\n return;\n }\n if (\n event.inputType === \"historyUndo\" ||\n event.inputType === \"historyRedo\"\n ) {\n event.preventDefault();\n historyAction.current(\n event.inputType === \"historyUndo\" ? \"undo\" : \"redo\",\n );\n } else if (!composing.current) {\n pendingInput.current = {\n type: event.inputType,\n selection: readSelection(input),\n };\n }\n };\n input.addEventListener(\"beforeinput\", beforeInput);\n return () => input.removeEventListener(\"beforeinput\", beforeInput);\n }, [inputElement, disabled, readOnly]);\n\n useEffect(() => {\n const onSelectionChange = () => {\n const input = inputRef.current;\n if (input && document.activeElement === input && !composing.current) {\n lastSelection.current = readSelection(input);\n queryAction.current();\n }\n };\n document.addEventListener(\"selectionchange\", onSelectionChange);\n return () =>\n document.removeEventListener(\"selectionchange\", onSelectionChange);\n }, []);\n\n // Check each commit, including edits the controlled owner rejects without changing value.\n useLayoutEffect(() => {\n const input = inputRef.current;\n if (!input || composing.current) return;\n const expected: ComposerValue =\n input instanceof HTMLTextAreaElement\n ? getComposerText(value)\n ? [{ type: \"text\", text: getComposerText(value) }]\n : []\n : value;\n if (!equalValue(history.current.current.value, expected)) {\n lastSelection.current = null;\n history.current = {\n current: { value: expected, selection: null },\n past: [],\n future: [],\n inputType: \"\",\n timestamp: 0,\n };\n }\n if (!equalValue(readValue(input), expected)) {\n const selection = readSelection(input);\n writeValue(input, expected);\n restoreSelection(input, selection);\n setQuery(null);\n dismissedQuery.current = null;\n }\n syncTokenHosts(input);\n if (input instanceof HTMLTextAreaElement) {\n input.disabled = disabled;\n input.readOnly = readOnly;\n }\n });\n\n const updateQuery = (): void => {\n const input = inputRef.current;\n const next =\n input &&\n !composing.current &&\n document.activeElement === input &&\n triggers.length > 0 &&\n !disabled &&\n !readOnly &&\n !(input instanceof HTMLTextAreaElement)\n ? currentQuery(input, triggers)\n : null;\n if (!next || next.key !== dismissedQuery.current)\n dismissedQuery.current = null;\n const active = next?.key === dismissedQuery.current ? null : next;\n setQuery((previous) =>\n previous?.key === active?.key && previous?.node === active?.node\n ? previous\n : active,\n );\n };\n\n queryAction.current = updateQuery;\n\n const dismissSuggestions = (): void => {\n dismissedQuery.current = query?.key ?? null;\n setQuery(null);\n };\n\n const publish = (reason: ComposerChangeDetails[\"reason\"] = \"input\"): void => {\n const input = inputRef.current;\n if (!input || composing.current || disabled || readOnly) return;\n const next = readValue(input);\n if (!(input instanceof HTMLTextAreaElement)) {\n const previous = history.current;\n if (!equalValue(previous.current.value, next)) {\n const before = pendingInput.current;\n const now = Date.now();\n const group =\n reason === \"input\" &&\n /^(insertText|deleteContentBackward|deleteContentForward)$/.test(\n before.type,\n ) &&\n previous.inputType === before.type &&\n now - previous.timestamp < 1000 &&\n before.selection?.anchor === previous.current.selection?.anchor &&\n before.selection?.focus === previous.current.selection?.focus;\n if (!group)\n previous.past.push({\n ...previous.current,\n selection: before.selection,\n });\n if (previous.past.length > 100) previous.past.shift();\n previous.future = [];\n previous.current = { value: next, selection: readSelection(input) };\n previous.inputType = before.type;\n previous.timestamp = now;\n }\n pendingInput.current = { type: \"\", selection: null };\n }\n if (!equalValue(next, value)) onValueChange(next, { reason });\n forceReconcile((revision) => revision + 1);\n syncTokenHosts(input);\n dismissedQuery.current = null;\n updateQuery();\n };\n\n const selectItem = (suggestion: ComposerItemValue): void => {\n const input = inputRef.current;\n if (\n disabled ||\n readOnly ||\n composing.current ||\n suggestion.disabled ||\n !query ||\n !input?.contains(query.node)\n )\n return;\n pendingInput.current = {\n type: \"selection\",\n selection: readSelection(input),\n };\n if (suggestion.type === \"action\" && onAction) {\n const range = document.createRange();\n range.setStart(query.node, query.start);\n range.setEnd(query.node, query.end);\n range.deleteContents();\n range.collapse(true);\n const selection = window.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n publish(\"selection\");\n setQuery(null);\n onAction(suggestion, query);\n return;\n }\n insertItem(input, query, suggestion);\n publish(\"selection\");\n setQuery(null);\n };\n\n const insertTrigger = (character: string): void => {\n const input = inputRef.current;\n if (\n !input ||\n input instanceof HTMLTextAreaElement ||\n disabled ||\n readOnly ||\n composing.current ||\n !triggers.some((trigger) => trigger.character === character)\n )\n return;\n const text = getComposerText(readValue(input));\n const selection = readSelection(input) ??\n lastSelection.current ?? {\n anchor: text.length,\n focus: text.length,\n };\n input.focus({ preventScroll: true });\n restoreSelection(input, selection);\n const start = Math.min(selection.anchor, selection.focus);\n const end = Math.max(selection.anchor, selection.focus);\n const preceding = text.slice(0, start);\n const following = text.slice(end);\n const prefix = preceding && !/\\s$/u.test(preceding) ? \" \" : \"\";\n const suffix = following && !/^\\s/u.test(following) ? \" \" : \"\";\n pendingInput.current = { type: \"trigger\", selection: readSelection(input) };\n insertPlainText(input, `${prefix}${character}${suffix}`);\n if (suffix) {\n const caret = start + prefix.length + character.length;\n restoreSelection(input, { anchor: caret, focus: caret });\n }\n publish();\n lastSelection.current = readSelection(input);\n };\n\n historyAction.current = (direction) => {\n const input = inputRef.current;\n if (\n !input ||\n input instanceof HTMLTextAreaElement ||\n disabled ||\n readOnly ||\n composing.current\n )\n return;\n const state = history.current;\n const source = direction === \"undo\" ? state.past : state.future;\n const destination = direction === \"undo\" ? state.future : state.past;\n const snapshot = source.pop();\n if (!snapshot) return;\n destination.push({\n value: readValue(input),\n selection: readSelection(input),\n });\n state.current = snapshot;\n state.inputType = \"\";\n writeValue(input, snapshot.value);\n restoreSelection(input, snapshot.selection);\n onValueChange(snapshot.value, { reason: \"history\" });\n forceReconcile((revision) => revision + 1);\n syncTokenHosts(input);\n dismissSuggestions();\n };\n\n const performSubmit = (): void => {\n if (!canSubmit || composing.current) return;\n dismissSuggestions();\n onSubmit?.(value);\n };\n\n const submit = (): void => {\n if (!canSubmit || composing.current) return;\n const root = rootRef.current;\n if (root instanceof HTMLFormElement) root.requestSubmit();\n else performSubmit();\n };\n\n const onKeyDown = (event: KeyboardEvent): void => {\n if (\n event.defaultPrevented ||\n composing.current ||\n event.nativeEvent.isComposing ||\n event.nativeEvent.keyCode === 229\n )\n return;\n if (\n !(event.currentTarget instanceof HTMLTextAreaElement) &&\n (event.metaKey || event.ctrlKey) &&\n !event.altKey &&\n (event.key.toLowerCase() === \"z\" ||\n (event.ctrlKey && event.key.toLowerCase() === \"y\"))\n ) {\n event.preventDefault();\n historyAction.current(\n event.shiftKey || event.key.toLowerCase() === \"y\" ? \"redo\" : \"undo\",\n );\n return;\n }\n if (\n event.key === \"Enter\" &&\n !event.shiftKey &&\n (submitOnEnter === \"always\" ||\n (submitOnEnter === \"desktop\" &&\n window.matchMedia(\"(pointer: fine)\").matches))\n ) {\n event.preventDefault();\n submit();\n }\n };\n\n return {\n value,\n isEmpty,\n isTextarea,\n isComposing,\n canSubmit,\n disabled,\n readOnly,\n tokenHosts,\n submit,\n insertTrigger,\n rootRef,\n reset: (next = []) => {\n lastSelection.current = null;\n history.current = {\n current: { value: next, selection: null },\n past: [],\n future: [],\n inputType: \"\",\n timestamp: 0,\n };\n dismissSuggestions();\n onValueChange(next, { reason: \"reset\" });\n forceReconcile((revision) => revision + 1);\n },\n formProps: {\n onSubmit: (event: FormEvent) => {\n if (event.defaultPrevented || event.target !== event.currentTarget)\n return;\n event.preventDefault();\n performSubmit();\n },\n },\n inputProps: {\n ref: setInputRef,\n contentEditable: isTextarea ? undefined : !disabled && !readOnly,\n role: \"textbox\",\n tabIndex: disabled ? -1 : 0,\n suppressContentEditableWarning: true,\n \"aria-disabled\": disabled || undefined,\n \"aria-readonly\": readOnly || undefined,\n \"aria-multiline\": true,\n onKeyDown,\n onKeyUp: (event) => {\n if (!event.defaultPrevented && !composing.current) updateQuery();\n },\n onClick: updateQuery,\n onBlur: (event) => {\n lastSelection.current =\n readSelection(event.currentTarget) ?? lastSelection.current;\n dismissSuggestions();\n },\n onInput: () => {\n if (ignoreCompositionInput.current) return;\n publish();\n },\n onCompositionStart: () => {\n pendingInput.current = {\n type: \"composition\",\n selection: inputRef.current ? readSelection(inputRef.current) : null,\n };\n composing.current = true;\n setIsComposing(true);\n compositionValue.current = value;\n setQuery(null);\n },\n onCompositionEnd: () => {\n composing.current = false;\n setIsComposing(false);\n ignoreCompositionInput.current = true;\n queueMicrotask(() => {\n ignoreCompositionInput.current = false;\n });\n if (equalValue(compositionValue.current, value)) publish();\n forceReconcile((revision) => revision + 1);\n },\n onCopy: (event) => {\n if (\n event.defaultPrevented ||\n event.currentTarget instanceof HTMLTextAreaElement\n )\n return;\n const selection = window.getSelection();\n if (\n !selection?.rangeCount ||\n selection.isCollapsed ||\n !event.currentTarget.contains(selection.anchorNode) ||\n !event.currentTarget.contains(selection.focusNode)\n )\n return;\n const fragment = document.createElement(\"div\");\n fragment.append(selection.getRangeAt(0).cloneContents());\n const copiedValue = readValue(fragment, false);\n event.clipboardData.setData(\"text/plain\", getComposerText(copiedValue));\n event.clipboardData.setData(\n COMPOSER_CLIPBOARD_TYPE,\n JSON.stringify(copiedValue),\n );\n event.preventDefault();\n },\n onCut: (event) => {\n if (\n event.defaultPrevented ||\n event.currentTarget instanceof HTMLTextAreaElement\n )\n return;\n const selection = window.getSelection();\n if (\n !selection?.rangeCount ||\n selection.isCollapsed ||\n !event.currentTarget.contains(selection.anchorNode) ||\n !event.currentTarget.contains(selection.focusNode)\n )\n return;\n const fragment = document.createElement(\"div\");\n fragment.append(selection.getRangeAt(0).cloneContents());\n const copiedValue = readValue(fragment, false);\n event.clipboardData.setData(\"text/plain\", getComposerText(copiedValue));\n event.clipboardData.setData(\n COMPOSER_CLIPBOARD_TYPE,\n JSON.stringify(copiedValue),\n );\n event.preventDefault();\n if (disabled || readOnly || composing.current) return;\n pendingInput.current = {\n type: \"cut\",\n selection: readSelection(event.currentTarget),\n };\n selection.getRangeAt(0).deleteContents();\n publish();\n },\n onPaste: (event) => {\n if (\n event.defaultPrevented ||\n event.currentTarget instanceof HTMLTextAreaElement\n )\n return;\n event.preventDefault();\n if (disabled || readOnly || composing.current) return;\n pendingInput.current = {\n type: \"paste\",\n selection: readSelection(event.currentTarget),\n };\n const pastedValue = parseComposerClipboard(\n event.clipboardData.getData(COMPOSER_CLIPBOARD_TYPE),\n );\n if (pastedValue) {\n const selection = window.getSelection();\n if (\n !selection?.rangeCount ||\n !event.currentTarget.contains(selection.anchorNode) ||\n !event.currentTarget.contains(selection.focusNode)\n )\n return;\n const range = selection.getRangeAt(0);\n range.deleteContents();\n const fragment = document.createElement(\"div\");\n writeValue(fragment, pastedValue);\n const nodes = Array.from(fragment.childNodes).filter(\n (node) =>\n !(\n node instanceof HTMLElement &&\n node.hasAttribute(\"data-composer-placeholder\")\n ),\n );\n const last = nodes.at(-1);\n for (const node of nodes.reverse()) range.insertNode(node);\n if (last) range.setStartAfter(last);\n range.collapse(true);\n selection.removeAllRanges();\n selection.addRange(range);\n } else\n insertPlainText(\n event.currentTarget,\n event.clipboardData.getData(\"text/plain\"),\n );\n publish();\n },\n onDrop: (event) => {\n if (\n event.defaultPrevented ||\n event.currentTarget instanceof HTMLTextAreaElement\n )\n return;\n event.preventDefault();\n if (disabled || readOnly || composing.current) return;\n const text = event.dataTransfer.getData(\"text/plain\");\n if (!text) return;\n const documentWithCaret = document as Document & {\n caretPositionFromPoint?: (\n x: number,\n y: number,\n ) => { offsetNode: Node; offset: number } | null;\n caretRangeFromPoint?: (x: number, y: number) => Range | null;\n };\n const position = documentWithCaret.caretPositionFromPoint?.(\n event.clientX,\n event.clientY,\n );\n const range = documentWithCaret.caretRangeFromPoint?.(\n event.clientX,\n event.clientY,\n );\n const node = position?.offsetNode ?? range?.startContainer;\n const offset = position?.offset ?? range?.startOffset;\n if (\n !node ||\n offset === undefined ||\n !event.currentTarget.contains(node)\n )\n return;\n const token = (\n node instanceof Element ? node : node.parentElement\n )?.closest(\"[data-composer-token]\");\n if (token) {\n const afterToken = document.createRange();\n afterToken.setStartAfter(token);\n afterToken.collapse(true);\n const selection = window.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(afterToken);\n } else {\n window.getSelection()?.collapse(node, offset);\n }\n event.currentTarget.focus({ preventScroll: true });\n pendingInput.current = {\n type: \"drop\",\n selection: readSelection(event.currentTarget),\n };\n insertPlainText(event.currentTarget, text);\n publish();\n },\n },\n status: trigger?.status ?? \"ready\",\n suggestions: {\n submitOnEmptySuggestions,\n enabled:\n triggers.length > 0 &&\n !isTextarea &&\n !isComposing &&\n !disabled &&\n !readOnly,\n items: options,\n open,\n onOpenChange: (nextOpen) => {\n if (!nextOpen) dismissSuggestions();\n },\n onItemSelect: selectItem,\n },\n };\n}\n\nexport const useComposerFilter: typeof AutocompletePrimitive.useFilter =\n AutocompletePrimitive.useFilter;\nexport {\n type ComposerChangeDetails,\n type ComposerEditorController,\n type ComposerItemValue,\n type ComposerPart,\n type ComposerQuery,\n type ComposerTokenPart,\n type ComposerTrigger,\n type ComposerValue,\n getComposerText,\n type UseComposerEditorOptions,\n};\n", + "content": "\"use client\";\n\nimport { Autocomplete as AutocompletePrimitive } from \"@base-ui/react/autocomplete\";\nimport type {\n ComponentProps,\n FormEvent,\n KeyboardEvent,\n RefObject,\n} from \"react\";\nimport {\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\";\nimport {\n COMPOSER_CLIPBOARD_TYPE,\n parseComposerClipboard,\n} from \"@/registry/default/lib/composer-clipboard\";\nimport {\n type ActiveQuery,\n type ComposerItemValue,\n type ComposerPart,\n type ComposerQuery,\n type ComposerSelection,\n type ComposerSnapshot,\n type ComposerTokenPart,\n type ComposerTrigger,\n type ComposerValue,\n currentQuery,\n equalValue,\n getComposerText,\n getFilteredItems,\n hasVisibleItems,\n insertItem,\n insertPlainText,\n readSelection,\n readValue,\n restoreSelection,\n writeValue,\n} from \"@/registry/default/lib/composer-document\";\nimport { continuesPastQuery } from \"@/registry/default/lib/composer-query\";\n\ntype ComposerChangeDetails = {\n reason: \"input\" | \"selection\" | \"history\" | \"reset\";\n};\ntype UseComposerEditorOptions = {\n value: ComposerValue;\n onValueChange: (value: ComposerValue, details: ComposerChangeDetails) => void;\n onSubmit?: (value: ComposerValue) => void;\n onQueryChange?: (query: ComposerQuery | null) => void;\n onAction?: (item: ComposerItemValue, query: ComposerQuery) => void;\n submitOnEmptySuggestions?: boolean;\n triggers?: readonly ComposerTrigger[];\n disabled?: boolean;\n readOnly?: boolean;\n submitDisabled?: boolean;\n allowEmpty?: boolean;\n submitOnEnter?: \"desktop\" | \"always\" | \"never\";\n};\n\ntype ComposerEditorController = {\n value: ComposerValue;\n inputProps: ComponentProps<\"div\">;\n formProps: Pick, \"onSubmit\">;\n rootRef: RefObject;\n isEmpty: boolean;\n isTextarea: boolean;\n isComposing: boolean;\n canSubmit: boolean;\n disabled: boolean;\n readOnly: boolean;\n submit: () => void;\n insertTrigger: (character: string) => void;\n reset: (value?: ComposerValue) => void;\n status: \"ready\" | \"loading\" | \"error\";\n tokenHosts: readonly HTMLSpanElement[];\n suggestions: {\n enabled: boolean;\n submitOnEmptySuggestions: boolean;\n items: readonly ComposerItemValue[];\n open: boolean;\n onOpenChange: (open: boolean) => void;\n onItemSelect: (item: ComposerItemValue) => void;\n };\n};\n\nexport function useComposerEditor({\n value,\n onValueChange,\n onSubmit,\n onQueryChange,\n onAction,\n submitOnEmptySuggestions = false,\n triggers = [],\n disabled = false,\n readOnly = false,\n submitDisabled = false,\n allowEmpty = false,\n submitOnEnter = \"always\",\n}: UseComposerEditorOptions): ComposerEditorController {\n const inputRef = useRef(null);\n const [inputElement, setInputElement] = useState(null);\n const setInputRef = useCallback((element: HTMLDivElement | null): void => {\n inputRef.current = element;\n setInputElement(element);\n }, []);\n const isTextarea = inputElement?.tagName === \"TEXTAREA\";\n const history = useRef<{\n current: ComposerSnapshot;\n past: ComposerSnapshot[];\n future: ComposerSnapshot[];\n inputType: string;\n timestamp: number;\n }>({\n current: { value, selection: null },\n past: [],\n future: [],\n inputType: \"\",\n timestamp: 0,\n });\n const pendingInput = useRef({\n type: \"\",\n selection: null as ComposerSelection | null,\n });\n const lastSelection = useRef(null);\n const historyAction = useRef<(direction: \"undo\" | \"redo\") => void>(() => {});\n const rootRef = useRef(null);\n const composing = useRef(false);\n const [isComposing, setIsComposing] = useState(false);\n const compositionValue = useRef(value);\n const ignoreCompositionInput = useRef(false);\n const dismissedQuery = useRef(null);\n const queryAction = useRef<() => void>(() => {});\n const [query, setQuery] = useState(null);\n const [tokenHosts, setTokenHosts] = useState([]);\n const [, forceReconcile] = useState(0);\n const trigger = triggers.find((item) => item.character === query?.character);\n const { contains } = useComposerFilter();\n const options = getFilteredItems(trigger, query, contains);\n const open =\n !isTextarea &&\n !isComposing &&\n !disabled &&\n !readOnly &&\n Boolean(query) &&\n (query?.spaceAfter\n ? options.some((item) => continuesPastQuery(item.label, query.text))\n : hasVisibleItems(trigger, options));\n const isEmpty = !getComposerText(value);\n const canSubmit =\n !isComposing &&\n !disabled &&\n !readOnly &&\n !submitDisabled &&\n (allowEmpty || Boolean(getComposerText(value).trim()));\n const onQueryChangeRef = useRef(onQueryChange);\n onQueryChangeRef.current = onQueryChange;\n const queryCharacter = query?.character;\n const queryText = query?.text;\n const queryKey = query?.key;\n\n const syncTokenHosts = useCallback((input: HTMLDivElement): void => {\n const next = Array.from(\n input.querySelectorAll(\n '[data-slot=\"composer-token-renderer\"]',\n ),\n );\n setTokenHosts((previous) =>\n previous.length === next.length &&\n previous.every((host, index) => host === next[index])\n ? previous\n : next,\n );\n }, []);\n\n useEffect(() => {\n onQueryChangeRef.current?.(\n queryCharacter && queryText !== undefined && queryKey\n ? { character: queryCharacter, text: queryText, key: queryKey }\n : null,\n );\n }, [queryCharacter, queryText, queryKey]);\n\n useEffect(() => {\n if (\n query &&\n (disabled ||\n readOnly ||\n !triggers.some((item) => item.character === query.character))\n )\n setQuery(null);\n }, [disabled, readOnly, query, triggers]);\n\n useLayoutEffect(() => {\n const input = inputElement;\n if (!input || input instanceof HTMLTextAreaElement || disabled || readOnly)\n return;\n const initializeCaret = (): void => {\n if (composing.current || readValue(input).length > 0) return;\n input.ownerDocument.getSelection()?.setBaseAndExtent(input, 0, input, 0);\n };\n // Initialize before focusin, while the drawer's temporary focus geometry is\n // still applied, so Safari doesn't pan to reveal the empty editor's caret.\n input.addEventListener(\"focus\", initializeCaret);\n return () => input.removeEventListener(\"focus\", initializeCaret);\n }, [inputElement, disabled, readOnly]);\n\n useEffect(() => {\n const input = inputElement;\n if (!input || input instanceof HTMLTextAreaElement) return;\n const beforeInput = (event: InputEvent) => {\n if (event.defaultPrevented) return;\n if (disabled || readOnly || event.inputType.startsWith(\"format\")) {\n event.preventDefault();\n return;\n }\n if (\n event.inputType === \"historyUndo\" ||\n event.inputType === \"historyRedo\"\n ) {\n event.preventDefault();\n historyAction.current(\n event.inputType === \"historyUndo\" ? \"undo\" : \"redo\",\n );\n } else if (!composing.current) {\n pendingInput.current = {\n type: event.inputType,\n selection: readSelection(input),\n };\n }\n };\n input.addEventListener(\"beforeinput\", beforeInput);\n return () => input.removeEventListener(\"beforeinput\", beforeInput);\n }, [inputElement, disabled, readOnly]);\n\n useEffect(() => {\n const onSelectionChange = () => {\n const input = inputRef.current;\n if (input && document.activeElement === input && !composing.current) {\n lastSelection.current = readSelection(input);\n queryAction.current();\n }\n };\n document.addEventListener(\"selectionchange\", onSelectionChange);\n return () =>\n document.removeEventListener(\"selectionchange\", onSelectionChange);\n }, []);\n\n // Check each commit, including edits the controlled owner rejects without changing value.\n useLayoutEffect(() => {\n const input = inputRef.current;\n if (!input || composing.current) return;\n const expected: ComposerValue =\n input instanceof HTMLTextAreaElement\n ? getComposerText(value)\n ? [{ type: \"text\", text: getComposerText(value) }]\n : []\n : value;\n if (!equalValue(history.current.current.value, expected)) {\n lastSelection.current = null;\n history.current = {\n current: { value: expected, selection: null },\n past: [],\n future: [],\n inputType: \"\",\n timestamp: 0,\n };\n }\n if (!equalValue(readValue(input), expected)) {\n const selection = readSelection(input);\n writeValue(input, expected);\n restoreSelection(input, selection);\n setQuery(null);\n dismissedQuery.current = null;\n }\n syncTokenHosts(input);\n if (input instanceof HTMLTextAreaElement) {\n input.disabled = disabled;\n input.readOnly = readOnly;\n }\n });\n\n const updateQuery = (): void => {\n const input = inputRef.current;\n const next =\n input &&\n !composing.current &&\n document.activeElement === input &&\n triggers.length > 0 &&\n !disabled &&\n !readOnly &&\n !(input instanceof HTMLTextAreaElement)\n ? currentQuery(input, triggers)\n : null;\n if (!next || next.key !== dismissedQuery.current)\n dismissedQuery.current = null;\n const active = next?.key === dismissedQuery.current ? null : next;\n setQuery((previous) =>\n previous?.key === active?.key && previous?.node === active?.node\n ? previous\n : active,\n );\n };\n\n queryAction.current = updateQuery;\n\n const dismissSuggestions = (): void => {\n dismissedQuery.current = query?.key ?? null;\n setQuery(null);\n };\n\n const publish = (reason: ComposerChangeDetails[\"reason\"] = \"input\"): void => {\n const input = inputRef.current;\n if (!input || composing.current || disabled || readOnly) return;\n const next = readValue(input);\n if (!(input instanceof HTMLTextAreaElement)) {\n const previous = history.current;\n if (!equalValue(previous.current.value, next)) {\n const before = pendingInput.current;\n const now = Date.now();\n const group =\n reason === \"input\" &&\n /^(insertText|deleteContentBackward|deleteContentForward)$/.test(\n before.type,\n ) &&\n previous.inputType === before.type &&\n now - previous.timestamp < 1000 &&\n before.selection?.anchor === previous.current.selection?.anchor &&\n before.selection?.focus === previous.current.selection?.focus;\n if (!group)\n previous.past.push({\n ...previous.current,\n selection: before.selection,\n });\n if (previous.past.length > 100) previous.past.shift();\n previous.future = [];\n previous.current = { value: next, selection: readSelection(input) };\n previous.inputType = before.type;\n previous.timestamp = now;\n }\n pendingInput.current = { type: \"\", selection: null };\n }\n if (!equalValue(next, value)) onValueChange(next, { reason });\n forceReconcile((revision) => revision + 1);\n syncTokenHosts(input);\n dismissedQuery.current = null;\n updateQuery();\n };\n\n const selectItem = (suggestion: ComposerItemValue): void => {\n const input = inputRef.current;\n if (\n disabled ||\n readOnly ||\n composing.current ||\n suggestion.disabled ||\n !query ||\n !input?.contains(query.node)\n )\n return;\n pendingInput.current = {\n type: \"selection\",\n selection: readSelection(input),\n };\n if (suggestion.type === \"action\" && onAction) {\n const range = document.createRange();\n range.setStart(query.node, query.start);\n range.setEnd(query.node, query.end);\n range.deleteContents();\n range.collapse(true);\n const selection = window.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n publish(\"selection\");\n setQuery(null);\n onAction(suggestion, query);\n return;\n }\n insertItem(input, query, suggestion);\n publish(\"selection\");\n setQuery(null);\n };\n\n const insertTrigger = (character: string): void => {\n const input = inputRef.current;\n if (\n !input ||\n input instanceof HTMLTextAreaElement ||\n disabled ||\n readOnly ||\n composing.current ||\n !triggers.some((trigger) => trigger.character === character)\n )\n return;\n const text = getComposerText(readValue(input));\n const selection = readSelection(input) ??\n lastSelection.current ?? {\n anchor: text.length,\n focus: text.length,\n };\n input.focus({ preventScroll: true });\n restoreSelection(input, selection);\n const start = Math.min(selection.anchor, selection.focus);\n const end = Math.max(selection.anchor, selection.focus);\n const preceding = text.slice(0, start);\n const following = text.slice(end);\n const prefix = preceding && !/\\s$/u.test(preceding) ? \" \" : \"\";\n const suffix = following && !/^\\s/u.test(following) ? \" \" : \"\";\n pendingInput.current = { type: \"trigger\", selection: readSelection(input) };\n insertPlainText(input, `${prefix}${character}${suffix}`);\n if (suffix) {\n const caret = start + prefix.length + character.length;\n restoreSelection(input, { anchor: caret, focus: caret });\n }\n publish();\n lastSelection.current = readSelection(input);\n };\n\n historyAction.current = (direction) => {\n const input = inputRef.current;\n if (\n !input ||\n input instanceof HTMLTextAreaElement ||\n disabled ||\n readOnly ||\n composing.current\n )\n return;\n const state = history.current;\n const source = direction === \"undo\" ? state.past : state.future;\n const destination = direction === \"undo\" ? state.future : state.past;\n const snapshot = source.pop();\n if (!snapshot) return;\n destination.push({\n value: readValue(input),\n selection: readSelection(input),\n });\n state.current = snapshot;\n state.inputType = \"\";\n writeValue(input, snapshot.value);\n restoreSelection(input, snapshot.selection);\n onValueChange(snapshot.value, { reason: \"history\" });\n forceReconcile((revision) => revision + 1);\n syncTokenHosts(input);\n dismissSuggestions();\n };\n\n const performSubmit = (): void => {\n if (!canSubmit || composing.current) return;\n dismissSuggestions();\n onSubmit?.(value);\n };\n\n const submit = (): void => {\n if (!canSubmit || composing.current) return;\n const root = rootRef.current;\n if (root instanceof HTMLFormElement) root.requestSubmit();\n else performSubmit();\n };\n\n const onKeyDown = (event: KeyboardEvent): void => {\n if (\n event.defaultPrevented ||\n composing.current ||\n event.nativeEvent.isComposing ||\n event.nativeEvent.keyCode === 229\n )\n return;\n if (\n !(event.currentTarget instanceof HTMLTextAreaElement) &&\n (event.metaKey || event.ctrlKey) &&\n !event.altKey &&\n (event.key.toLowerCase() === \"z\" ||\n (event.ctrlKey && event.key.toLowerCase() === \"y\"))\n ) {\n event.preventDefault();\n historyAction.current(\n event.shiftKey || event.key.toLowerCase() === \"y\" ? \"redo\" : \"undo\",\n );\n return;\n }\n if (\n event.key === \"Enter\" &&\n !event.shiftKey &&\n (submitOnEnter === \"always\" ||\n (submitOnEnter === \"desktop\" &&\n window.matchMedia(\"(pointer: fine)\").matches))\n ) {\n event.preventDefault();\n submit();\n }\n };\n\n return {\n value,\n isEmpty,\n isTextarea,\n isComposing,\n canSubmit,\n disabled,\n readOnly,\n tokenHosts,\n submit,\n insertTrigger,\n rootRef,\n reset: (next = []) => {\n lastSelection.current = null;\n history.current = {\n current: { value: next, selection: null },\n past: [],\n future: [],\n inputType: \"\",\n timestamp: 0,\n };\n dismissSuggestions();\n onValueChange(next, { reason: \"reset\" });\n forceReconcile((revision) => revision + 1);\n },\n formProps: {\n onSubmit: (event: FormEvent) => {\n if (event.defaultPrevented || event.target !== event.currentTarget)\n return;\n event.preventDefault();\n performSubmit();\n },\n },\n inputProps: {\n ref: setInputRef,\n contentEditable: isTextarea ? undefined : !disabled && !readOnly,\n role: \"textbox\",\n tabIndex: disabled ? -1 : 0,\n suppressContentEditableWarning: true,\n \"aria-disabled\": disabled || undefined,\n \"aria-readonly\": readOnly || undefined,\n \"aria-multiline\": true,\n onKeyDown,\n onKeyUp: (event) => {\n if (!event.defaultPrevented && !composing.current) updateQuery();\n },\n onClick: updateQuery,\n onFocus: updateQuery,\n onBlur: (event) => {\n lastSelection.current =\n readSelection(event.currentTarget) ?? lastSelection.current;\n dismissedQuery.current = null;\n setQuery(null);\n },\n onInput: () => {\n if (ignoreCompositionInput.current) return;\n publish();\n },\n onCompositionStart: () => {\n pendingInput.current = {\n type: \"composition\",\n selection: inputRef.current ? readSelection(inputRef.current) : null,\n };\n composing.current = true;\n setIsComposing(true);\n compositionValue.current = value;\n setQuery(null);\n },\n onCompositionEnd: () => {\n composing.current = false;\n setIsComposing(false);\n ignoreCompositionInput.current = true;\n queueMicrotask(() => {\n ignoreCompositionInput.current = false;\n });\n if (equalValue(compositionValue.current, value)) publish();\n forceReconcile((revision) => revision + 1);\n },\n onCopy: (event) => {\n if (\n event.defaultPrevented ||\n event.currentTarget instanceof HTMLTextAreaElement\n )\n return;\n const selection = window.getSelection();\n if (\n !selection?.rangeCount ||\n selection.isCollapsed ||\n !event.currentTarget.contains(selection.anchorNode) ||\n !event.currentTarget.contains(selection.focusNode)\n )\n return;\n const fragment = document.createElement(\"div\");\n fragment.append(selection.getRangeAt(0).cloneContents());\n const copiedValue = readValue(fragment, false);\n event.clipboardData.setData(\"text/plain\", getComposerText(copiedValue));\n event.clipboardData.setData(\n COMPOSER_CLIPBOARD_TYPE,\n JSON.stringify(copiedValue),\n );\n event.preventDefault();\n },\n onCut: (event) => {\n if (\n event.defaultPrevented ||\n event.currentTarget instanceof HTMLTextAreaElement\n )\n return;\n const selection = window.getSelection();\n if (\n !selection?.rangeCount ||\n selection.isCollapsed ||\n !event.currentTarget.contains(selection.anchorNode) ||\n !event.currentTarget.contains(selection.focusNode)\n )\n return;\n const fragment = document.createElement(\"div\");\n fragment.append(selection.getRangeAt(0).cloneContents());\n const copiedValue = readValue(fragment, false);\n event.clipboardData.setData(\"text/plain\", getComposerText(copiedValue));\n event.clipboardData.setData(\n COMPOSER_CLIPBOARD_TYPE,\n JSON.stringify(copiedValue),\n );\n event.preventDefault();\n if (disabled || readOnly || composing.current) return;\n pendingInput.current = {\n type: \"cut\",\n selection: readSelection(event.currentTarget),\n };\n selection.getRangeAt(0).deleteContents();\n publish();\n },\n onPaste: (event) => {\n if (\n event.defaultPrevented ||\n event.currentTarget instanceof HTMLTextAreaElement\n )\n return;\n event.preventDefault();\n if (disabled || readOnly || composing.current) return;\n pendingInput.current = {\n type: \"paste\",\n selection: readSelection(event.currentTarget),\n };\n const pastedValue = parseComposerClipboard(\n event.clipboardData.getData(COMPOSER_CLIPBOARD_TYPE),\n );\n if (pastedValue) {\n const selection = window.getSelection();\n if (\n !selection?.rangeCount ||\n !event.currentTarget.contains(selection.anchorNode) ||\n !event.currentTarget.contains(selection.focusNode)\n )\n return;\n const range = selection.getRangeAt(0);\n range.deleteContents();\n const fragment = document.createElement(\"div\");\n writeValue(fragment, pastedValue);\n const nodes = Array.from(fragment.childNodes).filter(\n (node) =>\n !(\n node instanceof HTMLElement &&\n node.hasAttribute(\"data-composer-placeholder\")\n ),\n );\n const last = nodes.at(-1);\n for (const node of nodes.reverse()) range.insertNode(node);\n if (last) range.setStartAfter(last);\n range.collapse(true);\n selection.removeAllRanges();\n selection.addRange(range);\n } else\n insertPlainText(\n event.currentTarget,\n event.clipboardData.getData(\"text/plain\"),\n );\n publish();\n },\n onDrop: (event) => {\n if (\n event.defaultPrevented ||\n event.currentTarget instanceof HTMLTextAreaElement\n )\n return;\n event.preventDefault();\n if (disabled || readOnly || composing.current) return;\n const text = event.dataTransfer.getData(\"text/plain\");\n if (!text) return;\n const documentWithCaret = document as Document & {\n caretPositionFromPoint?: (\n x: number,\n y: number,\n ) => { offsetNode: Node; offset: number } | null;\n caretRangeFromPoint?: (x: number, y: number) => Range | null;\n };\n const position = documentWithCaret.caretPositionFromPoint?.(\n event.clientX,\n event.clientY,\n );\n const range = documentWithCaret.caretRangeFromPoint?.(\n event.clientX,\n event.clientY,\n );\n const node = position?.offsetNode ?? range?.startContainer;\n const offset = position?.offset ?? range?.startOffset;\n if (\n !node ||\n offset === undefined ||\n !event.currentTarget.contains(node)\n )\n return;\n const token = (\n node instanceof Element ? node : node.parentElement\n )?.closest(\"[data-composer-token]\");\n if (token) {\n const afterToken = document.createRange();\n afterToken.setStartAfter(token);\n afterToken.collapse(true);\n const selection = window.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(afterToken);\n } else {\n window.getSelection()?.collapse(node, offset);\n }\n event.currentTarget.focus({ preventScroll: true });\n pendingInput.current = {\n type: \"drop\",\n selection: readSelection(event.currentTarget),\n };\n insertPlainText(event.currentTarget, text);\n publish();\n },\n },\n status: trigger?.status ?? \"ready\",\n suggestions: {\n submitOnEmptySuggestions,\n enabled:\n triggers.length > 0 &&\n !isTextarea &&\n !isComposing &&\n !disabled &&\n !readOnly,\n items: options,\n open,\n onOpenChange: (nextOpen) => {\n if (!nextOpen) dismissSuggestions();\n },\n onItemSelect: selectItem,\n },\n };\n}\n\nexport const useComposerFilter: typeof AutocompletePrimitive.useFilter =\n AutocompletePrimitive.useFilter;\nexport {\n type ComposerChangeDetails,\n type ComposerEditorController,\n type ComposerItemValue,\n type ComposerPart,\n type ComposerQuery,\n type ComposerTokenPart,\n type ComposerTrigger,\n type ComposerValue,\n getComposerText,\n type UseComposerEditorOptions,\n};\n", "type": "registry:hook" } ], diff --git a/apps/ui/registry.json b/apps/ui/registry.json index 721a476fb..7acf19ec6 100644 --- a/apps/ui/registry.json +++ b/apps/ui/registry.json @@ -5551,6 +5551,37 @@ ], "type": "registry:block" }, + { + "categories": [ + "composer", + "avatar", + "badge", + "multiselect", + "tag" + ], + "dependencies": [ + "lucide-react" + ], + "description": "Composer mention list that can stay open to mention several people in a row", + "files": [ + { + "path": "registry/default/particles/p-composer-13.tsx", + "type": "registry:block" + } + ], + "meta": { + "className": "**:data-[slot=preview]:w-full **:data-[slot=preview]:max-w-xl" + }, + "name": "p-composer-13", + "registryDependencies": [ + "@coss/avatar", + "@coss/badge", + "@coss/button", + "@coss/composer", + "@coss/kbd" + ], + "type": "registry:block" + }, { "categories": [ "command", @@ -12828,7 +12859,8 @@ "name": "use-composer-editor", "registryDependencies": [ "@coss/composer-document", - "@coss/composer-clipboard" + "@coss/composer-clipboard", + "@coss/composer-query" ], "type": "registry:hook" }, diff --git a/apps/ui/registry/__index__.tsx b/apps/ui/registry/__index__.tsx index 13046a3c7..2557101ec 100644 --- a/apps/ui/registry/__index__.tsx +++ b/apps/ui/registry/__index__.tsx @@ -4865,6 +4865,24 @@ export const Index: Record = { categories: ["composer","text editor"], meta: {"className":"**:data-[slot=preview]:w-full **:data-[slot=preview]:max-w-xl"}, }, + "p-composer-13": { + name: "p-composer-13", + description: "Composer mention list that can stay open to mention several people in a row", + type: "registry:block", + registryDependencies: ["@coss/avatar","@coss/badge","@coss/button","@coss/composer","@coss/kbd"], + files: [{ + path: "registry/default/particles/p-composer-13.tsx", + type: "registry:block", + target: "" + }], + component: React.lazy(async () => { + const mod = await import("@/registry/default/particles/p-composer-13.tsx") + const exportName = Object.keys(mod).find(key => typeof mod[key] === 'function' || typeof mod[key] === 'object') || item.name + return { default: mod.default || mod[exportName] } + }), + categories: ["composer","avatar","badge","multiselect","tag"], + meta: {"className":"**:data-[slot=preview]:w-full **:data-[slot=preview]:max-w-xl"}, + }, "p-command-1": { name: "p-command-1", description: "Command palette with dialog", @@ -10891,7 +10909,7 @@ export const Index: Record = { name: "use-composer-editor", description: "", type: "registry:hook", - registryDependencies: ["@coss/composer-document","@coss/composer-clipboard"], + registryDependencies: ["@coss/composer-document","@coss/composer-clipboard","@coss/composer-query"], files: [{ path: "registry/default/hooks/use-composer-editor.ts", type: "registry:hook", diff --git a/apps/ui/registry/default/hooks/use-composer-editor.ts b/apps/ui/registry/default/hooks/use-composer-editor.ts index ab1aa08d4..d1a09dbab 100644 --- a/apps/ui/registry/default/hooks/use-composer-editor.ts +++ b/apps/ui/registry/default/hooks/use-composer-editor.ts @@ -40,6 +40,7 @@ import { restoreSelection, writeValue, } from "@/registry/default/lib/composer-document"; +import { continuesPastQuery } from "@/registry/default/lib/composer-query"; type ComposerChangeDetails = { reason: "input" | "selection" | "history" | "reset"; @@ -144,7 +145,9 @@ export function useComposerEditor({ !disabled && !readOnly && Boolean(query) && - hasVisibleItems(trigger, options); + (query?.spaceAfter + ? options.some((item) => continuesPastQuery(item.label, query.text)) + : hasVisibleItems(trigger, options)); const isEmpty = !getComposerText(value); const canSubmit = !isComposing && @@ -537,10 +540,12 @@ export function useComposerEditor({ if (!event.defaultPrevented && !composing.current) updateQuery(); }, onClick: updateQuery, + onFocus: updateQuery, onBlur: (event) => { lastSelection.current = readSelection(event.currentTarget) ?? lastSelection.current; - dismissSuggestions(); + dismissedQuery.current = null; + setQuery(null); }, onInput: () => { if (ignoreCompositionInput.current) return; diff --git a/apps/ui/registry/default/lib/composer-document.ts b/apps/ui/registry/default/lib/composer-document.ts index 2f0365dbd..6ab1c65ca 100644 --- a/apps/ui/registry/default/lib/composer-document.ts +++ b/apps/ui/registry/default/lib/composer-document.ts @@ -48,6 +48,7 @@ type ActiveQuery = ComposerQuery & { node: Text; start: number; end: number; + spaceAfter: boolean; }; function pushText(parts: ComposerPart[], text: string): void { diff --git a/apps/ui/registry/default/lib/composer-query.ts b/apps/ui/registry/default/lib/composer-query.ts index f79da794a..8d55bd52a 100644 --- a/apps/ui/registry/default/lib/composer-query.ts +++ b/apps/ui/registry/default/lib/composer-query.ts @@ -2,7 +2,13 @@ export function getComposerQuery( text: string, caret: number, triggers: readonly string[], -): { character: string; text: string; start: number; end: number } | null { +): { + character: string; + text: string; + start: number; + end: number; + spaceAfter: boolean; +} | null { let start = -1; let character = ""; for (const trigger of triggers) { @@ -27,5 +33,16 @@ export function getComposerQuery( text: (beforeCaret + suffix).replace(/\p{Zs}+/gu, " ").trim(), start, end: caret + suffix.length, + spaceAfter: !suffix && /\p{Zs}$/u.test(beforeCaret), }; } + +export function continuesPastQuery(label: string, query: string): boolean { + const normalize = (text: string) => + text + .normalize("NFD") + .replace(/\p{M}/gu, "") + .replace(/\s+/gu, " ") + .toLocaleLowerCase(); + return ` ${normalize(label)}`.includes(` ${normalize(query)} `); +} diff --git a/apps/ui/registry/default/particles/p-composer-13.tsx b/apps/ui/registry/default/particles/p-composer-13.tsx new file mode 100644 index 000000000..df49ba157 --- /dev/null +++ b/apps/ui/registry/default/particles/p-composer-13.tsx @@ -0,0 +1,429 @@ +"use client"; + +import { ArrowUpIcon } from "lucide-react"; +import { + type KeyboardEvent, + type MouseEvent, + useId, + useLayoutEffect, + useRef, + useState, +} from "react"; +import { + Avatar, + AvatarFallback, + AvatarImage, +} from "@/registry/default/ui/avatar"; +import { Badge } from "@/registry/default/ui/badge"; +import { Button } from "@/registry/default/ui/button"; +import { + Composer, + ComposerActionGroup, + ComposerActions, + ComposerInput, + ComposerItem, + type ComposerItemValue, + ComposerList, + type ComposerPart, + ComposerPopup, + ComposerSubmit, + ComposerToken, + type ComposerValue, + getComposerText, + useComposerFilter, +} from "@/registry/default/ui/composer"; +import { Kbd } from "@/registry/default/ui/kbd"; + +type Tag = { id: string; label: string; color: string; people: string[] }; +type ItemClickEvent = MouseEvent & { + preventBaseUIHandler?: () => void; +}; + +const slug = (name: string) => name.toLowerCase().replaceAll(" ", "-"); +const peopleCount = (count: number) => + `${count} ${count === 1 ? "person" : "people"}`; + +const photo = (id: string) => + `https://images.unsplash.com/photo-${id}?w=96&h=96&dpr=2&q=80`; + +const memberData = [ + ["Alex Morgan", "Design", "1543610892-0b1f7e6d8ac1"], + ["Sam Rivera", "Engineering", "1507003211169-0a1dd7228f2d"], + ["Taylor Kim", "Product", "1472099645785-5658abf4ff4e"], + ["Jordan Lee", "Marketing", "1500648767791-00dcc994a43e"], + ["Casey Chen", "Support", "1494790108377-be9c29b29330"], + ["Morgan Davis", "Operations", "1655874819398-c6dfbec68ac7"], + ["Jamie Wilson", "Finance", "1438761681033-6461ffad8d80"], + ["Riley Patel", "Research", "1628157588553-5eeea00af15c"], +] as const; + +const members: ComposerItemValue[] = memberData.map(([label, description]) => ({ + description, + id: `member:${slug(label)}`, + kind: "member", + label, +})); + +const photos: Record = Object.fromEntries( + memberData.map(([label, , image]) => [`member:${slug(label)}`, photo(image)]), +); + +const tags: Tag[] = [ + { + color: "bg-sky-500", + id: "tag:clients", + label: "Clients", + people: [ + "Ben Carter", + "Chloe Martin", + "Sarah Lim", + "Tom Okafor", + "Ava Novak", + ], + }, + { + color: "bg-amber-500", + id: "tag:newsletter", + label: "Newsletter", + people: [ + "Aiden Brooks", + "Bella Ortiz", + "Caleb Foster", + "Daisy Nguyen", + "Elijah Grant", + "Fiona Walsh", + "Gabriel Silva", + "Hannah Reed", + "Isaac Moreno", + "Julia Hart", + "Kai Thompson", + "Lena Fischer", + "Mason Clarke", + "Nora Bennett", + "Oscar Diaz", + "Priya Shah", + "Quinn Murphy", + "Rosa Alvarez", + "Sarah Lim", + "Tara Quinn", + "Umar Haddad", + "Vera Lindqvist", + "Wes Turner", + "Xena Park", + "Yusuf Demir", + ], + }, +]; + +const tagsOf = (name: string) => + tags.filter((tag) => tag.people.includes(name)); + +const contacts: ComposerItemValue[] = [ + ...new Set(tags.flatMap((tag) => tag.people)), +] + .sort((a, b) => a.localeCompare(b)) + .map((label) => ({ + description: `${slug(label).replace("-", ".")}@example.com`, + id: `contact:${slug(label)}`, + kind: "contact", + label, + })); + +const tagItems: ComposerItemValue[] = tags.map((tag) => ({ + description: peopleCount(tag.people.length), + id: tag.id, + kind: "tag", + label: tag.label, +})); + +const sections = [ + { kind: "member", label: "Team members" }, + { kind: "contact", label: "Contacts" }, + { kind: "tag", label: "Tags" }, +] as const; + +function getSegments(input: HTMLElement, value: ComposerValue) { + const chips = value.filter((part) => part.type !== "text"); + let offset = 0; + return Array.from(input.childNodes, (node) => { + const length = + node instanceof Text + ? node.length + : node instanceof HTMLBRElement + ? 1 + : getComposerText(chips.splice(0, 1)).length; + offset += length; + return { end: offset, node, start: offset - length }; + }); +} + +function spliceText( + value: ComposerValue, + start: number, + end: number, + insert: readonly ComposerPart[], +): ComposerValue { + let offset = 0; + return value.flatMap((part): ComposerPart[] => { + const from = offset; + offset += getComposerText([part]).length; + if (part.type !== "text" || start < from || start >= offset) return [part]; + const text = (cut: string): ComposerPart[] => + cut ? [{ text: cut, type: "text" }] : []; + return [ + ...text(part.text.slice(0, start - from)), + ...insert, + ...text(part.text.slice(end - from)), + ]; + }); +} + +function PersonAvatar({ item }: { item: ComposerItemValue }) { + return ( + + ); +} + +function Dot({ color, className }: { color?: string; className: string }) { + return ; +} + +export default function Particle() { + const [value, setValue] = useState([]); + const [queryText, setQueryText] = useState(""); + const { contains, startsWith } = useComposerFilter(); + const sectionId = useId(); + const inputRef = useRef(null); + const listRef = useRef(null); + const caretAfter = useRef(null); + const keptOpen = useRef(false); + + useLayoutEffect(() => { + const input = inputRef.current; + const target = caretAfter.current; + if (!input || target === null) return; + caretAfter.current = null; + const segment = getSegments(input, value).find( + ({ node, start, end }) => + node instanceof Text && start <= target && target <= end, + ); + if (!segment) return; + window.getSelection()?.collapse(segment.node, target - segment.start); + document.dispatchEvent(new Event("selectionchange")); + }); + + function findQuery() { + const input = inputRef.current; + const selection = window.getSelection(); + if (!input || !selection?.isCollapsed) return null; + const segment = getSegments(input, value).find( + ({ node }) => node === selection.anchorNode, + ); + if (!segment) return null; + const caret = segment.start + selection.anchorOffset; + const start = getComposerText(value).lastIndexOf("@", caret - 1); + return start < 0 ? null : { caret, start }; + } + + function mentionAndKeepOpen(item: ComposerItemValue) { + const query = findQuery(); + if (!query) return; + const chip: ComposerPart = { + id: item.id, + kind: item.kind, + label: item.label, + trigger: "@", + type: "mention", + }; + const typed = getComposerText(value).slice(query.start, query.caret); + const insert: ComposerPart[] = [chip, { text: ` ${typed}`, type: "text" }]; + keptOpen.current = true; + caretAfter.current = query.start + getComposerText(insert).length; + setValue(spliceText(value, query.start, query.caret, insert)); + } + + function handleKeyDown(event: KeyboardEvent) { + if (event.nativeEvent.isComposing) return; + const highlighted = + listRef.current?.querySelector("[data-highlighted]"); + if (!highlighted) return; + if (event.key === "Enter" && event.shiftKey) { + const item = items.find((entry) => entry.id === highlighted.dataset.id); + if (!item) return; + event.preventDefault(); + mentionAndKeepOpen(item); + } else if (event.key === "Escape" && keptOpen.current) { + const query = findQuery(); + if (!query) return; + caretAfter.current = query.start; + setValue(spliceText(value, query.start, query.caret, [])); + } + } + + const matches = [...members, ...contacts, ...tagItems].filter( + (item) => + contains(item.label, queryText) || + (item.kind === "member" && contains(item.description ?? "", queryText)) || + (item.kind === "contact" && + tagsOf(item.label).some((tag) => contains(tag.label, queryText))), + ); + + const startsTag = (item: ComposerItemValue) => + item.kind === "tag" && startsWith(item.label, queryText); + const tagFirst = queryText.length >= 2 && matches.some(startsTag); + const visibleSections = ( + tagFirst ? [sections[2], sections[0], sections[1]] : sections + ) + .map((section) => ({ + ...section, + items: matches + .filter((item) => item.kind === section.kind) + .sort((a, b) => Number(startsTag(b)) - Number(startsTag(a))), + })) + .filter((section) => section.items.length); + const items = visibleSections.flatMap((section) => section.items); + + return ( + + `${count} suggestion${count === 1 ? "" : "s"} available. Use the up and down arrow keys to navigate. Hold Shift while pressing Enter to mention several.` + } + onQueryChange={(query) => { + if (!query) keptOpen.current = false; + setQueryText(query?.text ?? ""); + }} + onSubmit={() => setValue([])} + onValueChange={setValue} + triggers={[{ character: "@", filter: null, items }]} + value={value} + > + + token.kind === "tag" ? ( + tag.id === token.id)?.color} + /> + } + token={token} + variant="chip" + /> + ) : ( + + {token.trigger} + {token.label} + + ) + } + /> + + + {visibleSections.map(({ items: sectionItems, kind, label }) => { + const labelId = `${sectionId}-${kind}`; + return ( +
+
+ {label} +
+ {sectionItems.map((item) => { + const tag = tags.find((entry) => entry.id === item.id); + const personTags = + item.kind === "contact" ? tagsOf(item.label) : []; + return ( + { + if (!event.shiftKey) return; + event.preventBaseUIHandler?.(); + mentionAndKeepOpen(item); + }} + value={item} + > + {tag ? ( + + ) : ( + + )} + + + {item.label} + + + {item.description} + + + {personTags.length > 0 && ( + + {personTags.map((personTag) => ( + + + {personTag.label} + + ))} + + )} + + ); + })} +
+ ); + })} +
+ +
+ + + + + +
+ ); +} diff --git a/apps/ui/registry/default/ui/composer.tsx b/apps/ui/registry/default/ui/composer.tsx index 8eea3eca6..19158c10b 100644 --- a/apps/ui/registry/default/ui/composer.tsx +++ b/apps/ui/registry/default/ui/composer.tsx @@ -199,7 +199,6 @@ export function ComposerInput({ }); return ( <> - {/* The drawer reserves keyboard space; its nested input scroller needs no extra bottom padding. */} ): void => { if (event.defaultPrevented || disabled) return; diff --git a/apps/ui/registry/registry-hooks.ts b/apps/ui/registry/registry-hooks.ts index 2768327af..d01a118ba 100644 --- a/apps/ui/registry/registry-hooks.ts +++ b/apps/ui/registry/registry-hooks.ts @@ -8,6 +8,7 @@ export const hooks: Registry["items"] = [ registryDependencies: [ "@coss/composer-document", "@coss/composer-clipboard", + "@coss/composer-query", ], type: "registry:hook", }, diff --git a/apps/ui/registry/registry-particles.ts b/apps/ui/registry/registry-particles.ts index 363f137aa..373b8715f 100644 --- a/apps/ui/registry/registry-particles.ts +++ b/apps/ui/registry/registry-particles.ts @@ -2288,6 +2288,26 @@ export const particles: ParticleItem[] = [ registryDependencies: ["@coss/button", "@coss/composer"], type: "registry:block", }, + { + categories: categories("composer", "avatar", "badge", "multiselect", "tag"), + dependencies: ["lucide-react"], + description: + "Composer mention list that can stay open to mention several people in a row", + files: [{ path: "particles/p-composer-13.tsx", type: "registry:block" }], + meta: { + className: + "**:data-[slot=preview]:w-full **:data-[slot=preview]:max-w-xl", + }, + name: "p-composer-13", + registryDependencies: [ + "@coss/avatar", + "@coss/badge", + "@coss/button", + "@coss/composer", + "@coss/kbd", + ], + type: "registry:block", + }, { categories: categories("command", "dialog"), dependencies: ["lucide-react"], diff --git a/packages/ui/src/components/composer.tsx b/packages/ui/src/components/composer.tsx index 4757878ba..2e297a45b 100644 --- a/packages/ui/src/components/composer.tsx +++ b/packages/ui/src/components/composer.tsx @@ -199,7 +199,6 @@ export function ComposerInput({ }); return ( <> - {/* The drawer reserves keyboard space; its nested input scroller needs no extra bottom padding. */} ): void => { if (event.defaultPrevented || disabled) return; diff --git a/packages/ui/src/hooks/use-composer-editor.ts b/packages/ui/src/hooks/use-composer-editor.ts index 113dd94a5..4dd8d31e5 100644 --- a/packages/ui/src/hooks/use-composer-editor.ts +++ b/packages/ui/src/hooks/use-composer-editor.ts @@ -27,6 +27,7 @@ import { restoreSelection, writeValue, } from "@coss/ui/lib/composer-document"; +import { continuesPastQuery } from "@coss/ui/lib/composer-query"; import type { ComponentProps, FormEvent, @@ -144,7 +145,9 @@ export function useComposerEditor({ !disabled && !readOnly && Boolean(query) && - hasVisibleItems(trigger, options); + (query?.spaceAfter + ? options.some((item) => continuesPastQuery(item.label, query.text)) + : hasVisibleItems(trigger, options)); const isEmpty = !getComposerText(value); const canSubmit = !isComposing && @@ -537,10 +540,12 @@ export function useComposerEditor({ if (!event.defaultPrevented && !composing.current) updateQuery(); }, onClick: updateQuery, + onFocus: updateQuery, onBlur: (event) => { lastSelection.current = readSelection(event.currentTarget) ?? lastSelection.current; - dismissSuggestions(); + dismissedQuery.current = null; + setQuery(null); }, onInput: () => { if (ignoreCompositionInput.current) return; diff --git a/packages/ui/src/lib/composer-document.ts b/packages/ui/src/lib/composer-document.ts index 85d5286bf..3512cfa3e 100644 --- a/packages/ui/src/lib/composer-document.ts +++ b/packages/ui/src/lib/composer-document.ts @@ -48,6 +48,7 @@ type ActiveQuery = ComposerQuery & { node: Text; start: number; end: number; + spaceAfter: boolean; }; function pushText(parts: ComposerPart[], text: string): void { diff --git a/packages/ui/src/lib/composer-query.ts b/packages/ui/src/lib/composer-query.ts index f79da794a..8d55bd52a 100644 --- a/packages/ui/src/lib/composer-query.ts +++ b/packages/ui/src/lib/composer-query.ts @@ -2,7 +2,13 @@ export function getComposerQuery( text: string, caret: number, triggers: readonly string[], -): { character: string; text: string; start: number; end: number } | null { +): { + character: string; + text: string; + start: number; + end: number; + spaceAfter: boolean; +} | null { let start = -1; let character = ""; for (const trigger of triggers) { @@ -27,5 +33,16 @@ export function getComposerQuery( text: (beforeCaret + suffix).replace(/\p{Zs}+/gu, " ").trim(), start, end: caret + suffix.length, + spaceAfter: !suffix && /\p{Zs}$/u.test(beforeCaret), }; } + +export function continuesPastQuery(label: string, query: string): boolean { + const normalize = (text: string) => + text + .normalize("NFD") + .replace(/\p{M}/gu, "") + .replace(/\s+/gu, " ") + .toLocaleLowerCase(); + return ` ${normalize(label)}`.includes(` ${normalize(query)} `); +}