An open source design system that's fully customizable and agent ready
TypeScript
refactor(Chat): extract token logic into useComposerTokens hook (#1287)
Cindy Zhangb0119ff867dd
diff --git a/packages/core/src/Chat/XDSChatComposerInput.tsx b/packages/core/src/Chat/XDSChatComposerInput.tsxindex 5e1af4511b..ed408ff1e6 100644--- a/packages/core/src/Chat/XDSChatComposerInput.tsx+++ b/packages/core/src/Chat/XDSChatComposerInput.tsx@@ -41,6 +41,9 @@ import {} from '../theme/tokens.stylex';import {xdsClassName, mergeProps} from '../utils';import {useTriggerMenu} from './useTriggerMenu';+import {useXDSChatComposerTokens, isCustomToken} from './useXDSChatComposerTokens';+import {XDSChatPastedTextToken} from './XDSChatPastedTextToken';+import {useXDSChatPasteAsToken, type UseXDSChatPasteAsTokenReturn} from './useXDSChatPasteAsToken';import {XDSBadge, type XDSBadgeProps} from '../Badge';import {useXDSChatComposerContext} from './XDSChatContext';@@ -159,8 +162,14 @@ export interface XDSChatComposerInputProps extends Omit<label?: string;/** Disabled state. @default false */isDisabled?: boolean;- /** Paste handler */- onPaste?: (event: ClipboardEvent<HTMLDivElement>, text: string) => void;+ /** Paste handler. Called with the plain text before insertion. Return true to handle the paste yourself (e.g. insert a token instead). */+ onPaste?: (event: ClipboardEvent<HTMLDivElement>, text: string) => boolean | void;+ /**+ * Paste-as-token behavior. Defaults to converting pastes over 200 chars+ * into token chips. Pass a custom useXDSChatPasteAsToken result to override,+ * or false to disable.+ */+ pasteAsToken?: UseXDSChatPasteAsTokenReturn | false;/** File drop/paste handler */onFiles?: (files: File[]) => void;/** Submit handler (Enter without Shift) */@@ -215,13 +224,6 @@ const styles = stylex.create({// Helpers// =============================================================================-/** Type guard: does this token use the custom render path? */-function isCustomToken(- token: XDSChatComposerToken,-): token is XDSChatComposerTokenCustom {- return 'render' in token && typeof token.render === 'function';-}-/** Select all text in a contentEditable element. */function selectAll(el: HTMLElement): void {const selection = window.getSelection();@@ -287,6 +289,7 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {label = 'Message input',isDisabled = composerCtx?.isDisabled ?? false,onPaste: onPasteProp,+ pasteAsToken: pasteAsTokenProp,onFiles,onSubmit = composerCtx?.onSubmit,xstyle,@@ -296,6 +299,7 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {} = props;const editableRef = useRef<HTMLDivElement>(null);+ const selfRef = useRef<XDSChatComposerInputHandle>(null);const [isEmpty, setIsEmpty] = useState(true);const historyRef = useRef<string[]>([]);const historyIndexRef = useRef(-1);@@ -307,13 +311,17 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {);const insertTextRef = useRef<(text: string) => void>(() => {});- useImperativeHandle(ref, () => ({- insertToken: (token: XDSChatComposerToken) => insertTokenRef.current(token),- insertText: (text: string) => insertTextRef.current(text),- focus: () => editableRef.current?.focus(),- getValue: () =>- serialize(editableRef.current ?? document.createElement('div')),- }));+ useImperativeHandle(ref, () => {+ const h: XDSChatComposerInputHandle = {+ insertToken: (token: XDSChatComposerToken) => insertTokenRef.current(token),+ insertText: (text: string) => insertTextRef.current(text),+ focus: () => editableRef.current?.focus(),+ getValue: () =>+ serialize(editableRef.current ?? document.createElement('div')),+ };+ selfRef.current = h;+ return h;+ });useEffect(() => {if (controlledValue !== undefined && editableRef.current) {@@ -332,67 +340,31 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {// which serializes to "\n". Treat whitespace-only as empty.setIsEmpty(text.trim().length === 0);onChange?.(text);- // Clean up portals for tokens no longer in the DOM- setTokenPortals(prev =>- prev.filter(p => editableRef.current?.contains(p.span)),- );+ tokens.cleanupPortals();}, [onChange]);- // --- Token insertion ---- // Track inserted token spans for portal rendering- const [tokenPortals, setTokenPortals] = useState<- Array<{id: string; span: HTMLSpanElement; token: XDSChatComposerToken}>- >([]);-- const insertToken = useCallback((token: XDSChatComposerToken) => {- const editable = editableRef.current;- if (!editable) return;-- const selection = window.getSelection();- if (!selection || selection.rangeCount === 0) return;-- const range = selection.getRangeAt(0);-- // Create a non-editable container — React will portal the Badge into it- const span = document.createElement('span');- const id = `token-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;- span.setAttribute('data-xds-token', '');- span.setAttribute('data-xds-token-value', token.value);- span.setAttribute('data-xds-token-id', id);- span.contentEditable = 'false';- span.style.display = 'inline-flex';- span.style.verticalAlign = 'baseline';-- range.deleteContents();- range.insertNode(span);-- // Add a non-breaking space after the token and move cursor there- const space = document.createTextNode('\u00A0');- span.after(space);-- const newRange = document.createRange();- newRange.setStartAfter(space);- newRange.collapse(true);- selection.removeAllRanges();- selection.addRange(newRange);-- // Register for portal rendering- setTokenPortals(prev => [...prev, {id, span, token}]);- }, []);+ // --- Token management (via hook) ---+ const tokens = useXDSChatComposerTokens({editableRef, onEmitChange: emitChange});++ // --- Paste-as-token (internal default) ---+ const defaultPasteAsToken = useXDSChatPasteAsToken({inputRef: selfRef});+ const pasteAsToken: UseXDSChatPasteAsTokenReturn | null = pasteAsTokenProp === false+ ? null+ : (pasteAsTokenProp ?? defaultPasteAsToken);const insertText = useCallback((text: string) => {insertTextAtCursor(text);}, []);// Keep stable refs in sync for imperative handle- insertTokenRef.current = insertToken;+ insertTokenRef.current = tokens.insertToken;insertTextRef.current = insertText;// --- Trigger menu ---const triggerMenu = useTriggerMenu({triggers,editableRef,- onInsertToken: insertToken,+ onInsertToken: tokens.insertToken,onInsertText: insertText,onEmitChange: emitChange,debounceMs,@@ -511,6 +483,11 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {const handlePaste = useCallback((e: ClipboardEvent<HTMLDivElement>) => {+ // Handle paste near/into tokens first+ if (tokens.handlePaste(e)) {+ return;+ }+const files = Array.from(e.clipboardData.files);if (files.length > 0) {e.preventDefault();@@ -520,12 +497,24 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {e.preventDefault();const text = e.clipboardData.getData('text/plain');- insertTextAtCursor(text);- onPasteProp?.(e, text);+ // Paste-as-token: convert long pastes to token chips+ if (pasteAsToken?.onPaste(e, text)) {+ emitChange();+ return;+ }++ // Consumer onPaste — return true to prevent default text insert+ const handled = onPasteProp?.(e, text);+ if (handled) {+ emitChange();+ return;+ }++ insertTextAtCursor(text);emitChange();},- [onFiles, onPasteProp, emitChange],+ [onFiles, onPasteProp, emitChange, tokens, pasteAsToken],);const maxHeight = maxRows * LINE_HEIGHT_PX;@@ -559,10 +548,16 @@ export function XDSChatComposerInput(props: XDSChatComposerInputProps) {style={{maxHeight: `${maxHeight}px`}}/>{triggerMenu.renderMenu()}- {tokenPortals.map(({id, span, token}) =>+ {tokens.tokenPortals.map(({id, span, token}) =>createPortal(isCustomToken(token) ? (<span key={id}>{token.render()}</span>+ ) : token.value.length > (pasteAsToken === null ? Infinity : 200) ? (+ <XDSChatPastedTextToken+ key={id}+ text={token.value}+ onExpand={() => tokens.expandToken(id)}+ />) : (<XDSBadgekey={id}diff --git a/packages/core/src/Chat/XDSChatPastedTextToken.tsx b/packages/core/src/Chat/XDSChatPastedTextToken.tsxnew file mode 100644index 0000000000..c8ed55784e--- /dev/null+++ b/packages/core/src/Chat/XDSChatPastedTextToken.tsx@@ -0,0 +1,124 @@+'use client';++/**+ * @file XDSChatPastedTextToken.tsx+ * @input Uses React, StyleX, XDSBadge, XDSHoverCard, XDSButton, XDSCodeBlock+ * @output Exports XDSChatPastedTextToken component+ * @position Inline token for pasted text with hover card preview + expand+ *+ * Hover: card with truncated text preview and "Expand" button.+ * Expand replaces the token with the full text in the contentEditable.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Chat/index.ts (exports)+ */++import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ spacingVars,+ typeScaleVars,+ typographyVars,+} from '../theme/tokens.stylex';+import {XDSBadge} from '../Badge';+import {XDSButton} from '../Button';+import {XDSHoverCard} from '../HoverCard';++// =============================================================================+// Types+// =============================================================================++export interface XDSChatPastedTextTokenProps {+ /** The full pasted text. */+ text: string;+ /** Called when the user clicks Expand — dissolves the token into editable text. */+ onExpand?: () => void;+}++// =============================================================================+// Styles+// =============================================================================++const styles = stylex.create({+ preview: {+ display: 'flex',+ flexDirection: 'column',+ gap: spacingVars['--spacing-2'],+ maxWidth: '480px',+ },+ previewText: {+ fontFamily: typographyVars['--font-family-code'],+ fontSize: typeScaleVars['--text-supporting-size'],+ lineHeight: typeScaleVars['--text-supporting-leading'],+ color: colorVars['--color-text-primary'],+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ maxHeight: '240px',+ overflowY: 'auto',+ },+ footer: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: spacingVars['--spacing-2'],+ },+ meta: {+ fontSize: typeScaleVars['--text-supporting-size'],+ color: colorVars['--color-text-secondary'],+ },+});++// =============================================================================+// Helpers+// =============================================================================++function formatLabel(text: string): string {+ const lines = text.split('\n').length;+ const chars = text.length;+ return lines > 1+ ? `${lines} lines, ${chars} chars`+ : `${chars} chars`;+}++++// =============================================================================+// Component+// =============================================================================++export function XDSChatPastedTextToken({+ text,+ onExpand,+}: XDSChatPastedTextTokenProps) {+ const label = formatLabel(text);+++ const cardContent = (+ <div {...stylex.props(styles.preview)}>+ <div {...stylex.props(styles.previewText)}>{text}</div>+ <div {...stylex.props(styles.footer)}>+ <span {...stylex.props(styles.meta)}>{label}</span>+ {onExpand && (+ <XDSButton+ label="Expand"+ variant="ghost"+ size="sm"+ onClick={onExpand}+ />+ )}+ </div>+ </div>+ );++ return (+ <XDSHoverCard+ content={cardContent}+ placement="above"+ alignment="start"+ hasHoverIndication={false}>+ <XDSBadge label={label} variant="neutral" />+ </XDSHoverCard>+ );+}++XDSChatPastedTextToken.displayName = 'XDSChatPastedTextToken';diff --git a/packages/core/src/Chat/index.ts b/packages/core/src/Chat/index.tsindex a59082faac..5df35fd092 100644--- a/packages/core/src/Chat/index.ts+++ b/packages/core/src/Chat/index.ts@@ -61,6 +61,10 @@ export type {UseXDSChatStreamScrollOptions, UseXDSChatStreamScrollReturn} from 'export {useXDSChatNewMessages} from './useXDSChatNewMessages';export type {UseXDSChatNewMessagesOptions, UseXDSChatNewMessagesReturn} from './useXDSChatNewMessages';+export {useXDSChatPasteAsToken} from './useXDSChatPasteAsToken';+export type {UseXDSChatPasteAsTokenOptions, UseXDSChatPasteAsTokenReturn} from './useXDSChatPasteAsToken';+export {useXDSChatComposerTokens} from './useXDSChatComposerTokens';+export type {UseXDSChatComposerTokensOptions, UseXDSChatComposerTokensReturn, TokenPortal} from './useXDSChatComposerTokens';export type {XDSChatMessageSender, XDSChatDensity} from './XDSChatContext';export {useXDSChatLayoutContext} from './XDSChatContext';diff --git a/packages/core/src/Chat/useXDSChatComposerTokens.ts b/packages/core/src/Chat/useXDSChatComposerTokens.tsnew file mode 100644index 0000000000..53629c381a--- /dev/null+++ b/packages/core/src/Chat/useXDSChatComposerTokens.ts@@ -0,0 +1,285 @@+'use client';++/**+ * @file useXDSChatComposerTokens.ts+ * @input Uses React refs, state, DOM APIs+ * @output Exports useXDSChatComposerTokens hook for inline token management+ * @position Utility hook — extracted from XDSChatComposerInput+ *+ * Manages inline token chips in a contentEditable element:+ * - Insert tokens (badge or custom render) at cursor position+ * - Backspace handling near tokens (removes token + trailing NBSP)+ * - Paste handling near tokens (prevents broken state)+ * - Portal tracking for React rendering inside DOM-created spans+ * - Serialization awareness (data-xds-token attributes)+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Chat/index.ts (exports)+ * - /packages/core/src/Chat/XDSChatComposerInput.tsx (consumer)+ */++import {useCallback, useState} from 'react';+import type {XDSChatComposerToken, XDSChatComposerTokenCustom} from './XDSChatComposerInput';++// =============================================================================+// Types+// =============================================================================++export interface TokenPortal {+ id: string;+ span: HTMLSpanElement;+ token: XDSChatComposerToken;+}++export interface UseXDSChatComposerTokensOptions {+ /** Ref to the contentEditable element. */+ editableRef: React.RefObject<HTMLDivElement | null>;+ /** Called after token insertion/removal to sync state. */+ onEmitChange: () => void;+}++export interface UseXDSChatComposerTokensReturn {+ /** Active token portals — render via createPortal in the component. */+ tokenPortals: TokenPortal[];+ /** Expand a token — replace the token span with its text value. */+ expandToken: (id: string) => void;+ /** Insert a token at the current cursor position. */+ insertToken: (token: XDSChatComposerToken) => void;+ /** Handle keydown — intercepts Backspace near tokens. Returns true if handled. */+ handleKeyDown: (e: React.KeyboardEvent) => boolean;+ /** Handle paste — prevents pasting into token spans. Returns true if handled. */+ handlePaste: (e: React.ClipboardEvent) => boolean;+ /** Clean up orphaned portals (call after content changes). */+ cleanupPortals: () => void;+}++// =============================================================================+// Helpers+// =============================================================================++/** Type guard: does this token use the custom render path? */+export function isCustomToken(+ token: XDSChatComposerToken,+): token is XDSChatComposerTokenCustom {+ return 'render' in token && typeof token.render === 'function';+}++/** Insert plain text at the current selection. */+function insertTextAtCursor(text: string): void {+ const selection = window.getSelection();+ if (!selection || selection.rangeCount === 0) return;+ const range = selection.getRangeAt(0);+ range.deleteContents();+ const textNode = document.createTextNode(text);+ range.insertNode(textNode);+ range.setStartAfter(textNode);+ range.collapse(true);+ selection.removeAllRanges();+ selection.addRange(range);+}++/** Check if a node is inside or is a token span. */+function isInsideToken(node: Node): HTMLElement | null {+ let current: Node | null = node;+ while (current) {+ if (+ current instanceof HTMLElement &&+ current.hasAttribute('data-xds-token')+ ) {+ return current;+ }+ current = current.parentNode;+ }+ return null;+}++// =============================================================================+// Hook+// =============================================================================++export function useXDSChatComposerTokens({+ editableRef,+ onEmitChange,+}: UseXDSChatComposerTokensOptions): UseXDSChatComposerTokensReturn {+ const [tokenPortals, setTokenPortals] = useState<TokenPortal[]>([]);++ // --- Insert token at cursor ---+ const insertToken = useCallback(+ (token: XDSChatComposerToken) => {+ const editable = editableRef.current;+ if (!editable) return;++ const selection = window.getSelection();+ if (!selection || selection.rangeCount === 0) return;++ const range = selection.getRangeAt(0);++ // Create a non-editable container — React will portal the Badge into it+ const span = document.createElement('span');+ const id = `token-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;+ span.setAttribute('data-xds-token', '');+ span.setAttribute('data-xds-token-value', token.value);+ span.setAttribute('data-xds-token-id', id);+ span.contentEditable = 'false';+ span.style.display = 'inline-flex';+ span.style.verticalAlign = 'baseline';++ range.deleteContents();+ range.insertNode(span);++ // Add a non-breaking space after the token and move cursor there+ const space = document.createTextNode('\u00A0');+ span.after(space);++ const newRange = document.createRange();+ newRange.setStartAfter(space);+ newRange.collapse(true);+ selection.removeAllRanges();+ selection.addRange(newRange);++ // Register for portal rendering+ setTokenPortals(prev => [...prev, {id, span, token}]);+ },+ [editableRef],+ );++ // --- Backspace near tokens ---+ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent): boolean => {+ if (e.key !== 'Backspace') return false;++ const selection = window.getSelection();+ if (!selection || !selection.isCollapsed || selection.rangeCount === 0) {+ return false;+ }++ const range = selection.getRangeAt(0);+ const {startContainer, startOffset} = range;++ // Case 1: Cursor at start of text node right after a token —+ // let the browser handle it (it will select/delete the token)+ if (+ startContainer.nodeType === Node.TEXT_NODE &&+ startOffset === 0 &&+ startContainer.previousSibling instanceof HTMLElement &&+ startContainer.previousSibling.hasAttribute('data-xds-token')+ ) {+ return false;+ }++ // Case 2: Cursor in or after the trailing NBSP — remove both+ // the NBSP and the token in one action+ if (+ startContainer.nodeType === Node.TEXT_NODE &&+ startContainer.textContent === '\u00A0' &&+ startOffset <= 1 &&+ startContainer.previousSibling instanceof HTMLElement &&+ startContainer.previousSibling.hasAttribute('data-xds-token')+ ) {+ e.preventDefault();+ const tokenSpan = startContainer.previousSibling;+ const parent = startContainer.parentNode;+ if (parent) {+ parent.removeChild(startContainer);+ parent.removeChild(tokenSpan);+ }+ onEmitChange();+ return true;+ }++ return false;+ },+ [onEmitChange],+ );++ // --- Paste near tokens ---+ const handlePaste = useCallback(+ (e: React.ClipboardEvent): boolean => {+ const selection = window.getSelection();+ if (!selection || selection.rangeCount === 0) return false;++ const range = selection.getRangeAt(0);++ // If selection overlaps a token, collapse to after the token+ // and insert there instead of breaking the token+ const tokenEl = isInsideToken(range.startContainer);+ if (tokenEl) {+ e.preventDefault();+ const text = e.clipboardData.getData('text/plain');++ // Move cursor after the token's trailing space+ const space = tokenEl.nextSibling;+ const newRange = document.createRange();+ if (space && space.nodeType === Node.TEXT_NODE) {+ newRange.setStartAfter(space);+ } else {+ newRange.setStartAfter(tokenEl);+ }+ newRange.collapse(true);+ selection.removeAllRanges();+ selection.addRange(newRange);++ insertTextAtCursor(text);+ onEmitChange();+ return true;+ }++ return false;+ },+ [onEmitChange],+ );++ // --- Expand token (replace with text) ---+ const expandToken = useCallback(+ (id: string) => {+ const editable = editableRef.current;+ if (!editable) return;++ const portal = tokenPortals.find(p => p.id === id);+ if (!portal) return;++ const {span} = portal;+ const value = span.getAttribute('data-xds-token-value') ?? '';+ const textNode = document.createTextNode(value);++ // Remove the trailing NBSP if present+ const next = span.nextSibling;+ if (next?.nodeType === Node.TEXT_NODE && next.textContent === '\u00A0') {+ next.remove();+ }++ span.replaceWith(textNode);++ // Place cursor at end of inserted text+ const selection = window.getSelection();+ if (selection) {+ const range = document.createRange();+ range.setStartAfter(textNode);+ range.collapse(true);+ selection.removeAllRanges();+ selection.addRange(range);+ }++ // Remove from portals+ setTokenPortals(prev => prev.filter(p => p.id !== id));+ onEmitChange();+ },+ [editableRef, tokenPortals, onEmitChange],+ );++ // --- Cleanup orphaned portals ---+ const cleanupPortals = useCallback(() => {+ setTokenPortals(prev =>+ prev.filter(p => editableRef.current?.contains(p.span)),+ );+ }, [editableRef]);++ return {+ tokenPortals,+ expandToken,+ insertToken,+ handleKeyDown,+ handlePaste,+ cleanupPortals,+ };+}diff --git a/packages/core/src/Chat/useXDSChatPasteAsToken.ts b/packages/core/src/Chat/useXDSChatPasteAsToken.tsnew file mode 100644index 0000000000..2f930446ed--- /dev/null+++ b/packages/core/src/Chat/useXDSChatPasteAsToken.ts@@ -0,0 +1,91 @@+'use client';++/**+ * @file useXDSChatPasteAsToken.ts+ * @input Uses React refs, callbacks+ * @output Exports useXDSChatPasteAsToken hook+ * @position Utility hook — composable paste behavior for XDSChatComposerInput+ *+ * Intercepts paste events and converts long text into a token chip+ * instead of inserting raw text into the contentEditable. Short+ * pastes pass through normally.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Chat/index.ts (exports)+ */++import {useCallback} from 'react';+import type {ClipboardEvent} from 'react';+import type {+ XDSChatComposerInputHandle,+ XDSChatComposerToken,+} from './XDSChatComposerInput';++// =============================================================================+// Types+// =============================================================================++export interface UseXDSChatPasteAsTokenOptions {+ /** Ref to the composer input handle for inserting tokens. */+ inputRef: React.RefObject<XDSChatComposerInputHandle | null>;++ /**+ * Character count threshold — pastes longer than this become tokens.+ * @default 200+ */+ threshold?: number;++ /**+ * Convert pasted text into a token. Return the token to insert.+ * @default Creates a neutral badge with character count label.+ */+ toToken?: (text: string) => XDSChatComposerToken;+}++export interface UseXDSChatPasteAsTokenReturn {+ /**+ * Pass as the onPaste prop on XDSChatComposerInput.+ * Returns true when the paste was converted to a token.+ */+ onPaste: (event: ClipboardEvent<HTMLDivElement>, text: string) => boolean;+}++// =============================================================================+// Default token factory+// =============================================================================++function defaultToToken(text: string): XDSChatComposerToken {+ const lines = text.split('\n').length;+ const chars = text.length;+ const label = lines > 1+ ? `${lines} lines, ${chars} chars`+ : `${chars} chars`;+ return {+ value: text,+ label,+ variant: 'neutral' as const,+ };+}++// =============================================================================+// Hook+// =============================================================================++export function useXDSChatPasteAsToken({+ inputRef,+ threshold = 200,+ toToken = defaultToToken,+}: UseXDSChatPasteAsTokenOptions): UseXDSChatPasteAsTokenReturn {+ const onPaste = useCallback(+ (_event: ClipboardEvent<HTMLDivElement>, text: string): boolean => {+ if (text.length <= threshold) return false;++ const token = toToken(text);+ inputRef.current?.insertToken(token);+ return true;+ },+ [inputRef, threshold, toToken],+ );++ return {onPaste};+}