Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
fix(ui): complete token field states (#256)
grim50f53bcb74b8
diff --git a/apps/app/components/agent-builder/agent-composer.tsx b/apps/app/components/agent-builder/agent-composer.tsxindex acaf1f3f..bb4b289a 100644--- a/apps/app/components/agent-builder/agent-composer.tsx+++ b/apps/app/components/agent-builder/agent-composer.tsx@@ -30,7 +30,7 @@ import {} from "@crm/ui/components/popover";import { Skeleton } from "@crm/ui/components/skeleton";import { SkeletonSwap } from "@crm/ui/components/skeleton-swap";-import { TokenField } from "@crm/ui/components/token-field";+import { TokenField, TokenFieldEditable } from "@crm/ui/components/token-field";import { cn } from "@crm/ui/lib/utils";import { useQuery } from "@tanstack/react-query";import { type ReactNode, useReducer, useRef } from "react";@@ -518,7 +518,8 @@ export function AgentComposer({composingRef={composing}mode={mode}state={state}- disabled={locked}+ disabled={disabled}+ loading={submitAction.pending}onChanged={updateEditor}onSelectionChanged={(offset) => {selectionOffset.current = offset;@@ -616,6 +617,7 @@ function ComposerEditor({mode,state,disabled,+ loading,onChanged,onSelectionChanged,onRemoveContext,@@ -626,11 +628,13 @@ function ComposerEditor({mode: "home" | "chat";state: ComposerState;disabled: boolean;+ loading: boolean;onChanged: (snapshot: ComposerEditorSnapshot) => void;onSelectionChanged: (offset: number) => void;onRemoveContext: (key: string) => void;onSubmit: () => void;}) {+ const inactive = disabled || loading;const parts = composerEditorParts(state);const placeholder =mode === "home"@@ -651,10 +655,12 @@ function ComposerEditor({<TokenFieldref={editorRef}role="textbox"- tabIndex={disabled ? -1 : 0}+ tabIndex={0}aria-label="Message the agent builder"aria-multiline="true"- aria-disabled={disabled}+ disabled={disabled}+ loading={loading}+ loadingLabel="Sending message"data-empty={state.draft.length === 0 && state.anchors.length === 0}data-placeholder={placeholder}spellCheck@@ -731,7 +737,6 @@ function ComposerEditor({key={part.key}start={part.start}value={part.value}- disabled={disabled}detectedIntent={state.detectedCommandLabel}intentStart={state.detectedCommandLabel@@ -744,7 +749,7 @@ function ComposerEditor({key={part.anchor.key}anchor={part.anchor}state={state}- disabled={disabled}+ disabled={inactive}onRemove={onRemoveContext}/>),@@ -756,13 +761,11 @@ function ComposerEditor({function ComposerEditorText({start,value,- disabled,detectedIntent,intentStart,}: {start: number;value: string;- disabled: boolean;detectedIntent: string | null;intentStart: number;}) {@@ -773,10 +776,7 @@ function ComposerEditorText({localIntentStart + detectedIntent.length <= value.length;return (- <span- contentEditable={!disabled}- suppressContentEditableWarning- tabIndex={-1}+ <TokenFieldEditablerole="none"data-composer-textdata-composer-text-start={start}@@ -797,7 +797,7 @@ function ComposerEditorText({) : (value || EDITOR_SENTINEL)}- </span>+ </TokenFieldEditable>);}@@ -980,6 +980,7 @@ function composerEditableText(node: Node): string {return (node.textContent ?? "").replaceAll(EDITOR_SENTINEL, "");}if (node instanceof HTMLElement) {+ if (node.contentEditable === "false") return "";if (node.dataset.composerTokenKey ||node.dataset.intentAccent !== undefineddiff --git a/bun.lock b/bun.lockindex f02e078e..81579ea8 100644--- a/bun.lock+++ b/bun.lock@@ -243,6 +243,7 @@"@types/node": "^24.10.1","@types/react": "^19.2.18","@types/react-dom": "^19",+ "happy-dom": "^21.0.4","next": "16.4.2","react": "19.2.4","react-dom": "19.2.4",@@ -1179,6 +1180,10 @@"@types/validator": ["@types/[email protected]", "", {}, "sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA=="],+ "@types/whatwg-mimetype": ["@types/[email protected]", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="],++ "@types/ws": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w=="],+"@ungap/structured-clone": ["@ungap/[email protected]", "", {}, "sha512-60YRaenCQcVjYEKOcG824+DRGGIQ3VKErcBoAEDJZz5bKIs2ZG+X/H9Nk+Q6EVkwJk5QNApxbrc5QtBSwtrXAg=="],"@vercel/blob": ["@vercel/[email protected]", "", { "dependencies": { "@vercel/oidc": "^3.6.1", "async-retry": "^1.3.3", "is-buffer": "^2.0.5", "is-node-process": "^1.2.0", "throttleit": "^2.1.0", "undici": "^6.23.0" } }, "sha512-KTJytw85j1XQBxjN5d6UXI7fIWNQe1jotn4nWN+0hePqLs+Qi1B3jHdQcSKFGF0m2rsy9uhPT6GOXMtHe3qNzg=="],@@ -1327,6 +1332,8 @@"browserslist": ["[email protected]", "", { "dependencies": { "baseline-browser-mapping": "^2.10.44", "caniuse-lite": "^1.0.30001806", "electron-to-chromium": "^1.5.393", "node-releases": "^2.0.51", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-JxV13hNrFxqjOc8alRbq9dK1MM79NEXYpma2B2J4wAtpWS5zIEIKqWPGCl7N4o7Uc7B7itylh7SuDujATRyyTw=="],+ "buffer-image-size": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ=="],+"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],@@ -1515,7 +1522,7 @@"enhanced-resolve": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A=="],- "entities": ["[email protected]", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],+ "entities": ["[email protected]", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],"env-paths": ["[email protected]", "", {}, "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A=="],@@ -1653,6 +1660,8 @@"h3": ["[email protected]", "", { "dependencies": { "cookie-es": "^1.2.3", "crossws": "^0.3.5", "defu": "^6.1.6", "destr": "^2.0.5", "iron-webcrypto": "^1.2.1", "node-mock-http": "^1.0.4", "radix3": "^1.1.2", "ufo": "^1.6.3", "uncrypto": "^0.1.3" } }, "sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg=="],+ "happy-dom": ["[email protected]", "", { "dependencies": { "@types/node": ">=20.0.0", "@types/whatwg-mimetype": "^3.0.2", "@types/ws": "^8.18.1", "buffer-image-size": "^0.6.4", "entities": "^7.0.1", "whatwg-mimetype": "^3.0.0", "ws": "^8.21.0" } }, "sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw=="],+"has-symbols": ["[email protected]", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],"has-tostringtag": ["[email protected]", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="],@@ -2395,6 +2404,8 @@"web-vitals-soft-navs": ["[email protected]", "", {}, "sha512-rLcLXA2sx6+9dE88NHFubwTtGxpK4yYBLj6qHPdFoCaLr0cXGb4efOqtKLlm4loGA4OEKHIQKMKzZkKyOh5ctw=="],+ "whatwg-mimetype": ["[email protected]", "", {}, "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q=="],+"which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],"why-is-node-running": ["[email protected]", "", { "bin": { "why-is-node-running": "cli.js" } }, "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ=="],@@ -2699,6 +2710,8 @@"parse-entities/@types/unist": ["@types/[email protected]", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],+ "parse5/entities": ["[email protected]", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="],+"pg-types/postgres-array": ["[email protected]", "", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="],"posthog-js/@posthog/core": ["@posthog/[email protected]", "", { "dependencies": { "@posthog/types": "^1.416.0" } }, "sha512-2e44KMrhboQyK7OrQFnWwNopa8ZLK6hQoni8Bxm258+lLERoRAUKOFC4jt+zp0RxVsYQAb9SqPMdH+jguVqdKQ=="],diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 5ea24580..a6151791 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -52,6 +52,7 @@"@types/node": "^24.10.1","@types/react": "^19.2.18","@types/react-dom": "^19",+ "happy-dom": "^21.0.4","next": "16.4.2","react": "19.2.4","react-dom": "19.2.4",diff --git a/packages/ui/src/components/token-field.tsx b/packages/ui/src/components/token-field.tsxindex 6b7dbea8..7216415d 100644--- a/packages/ui/src/components/token-field.tsx+++ b/packages/ui/src/components/token-field.tsx@@ -1,16 +1,129 @@+"use client";+import { Button } from "@crm/ui/components/button";+import { Spinner } from "@crm/ui/components/spinner";import { cn } from "@crm/ui/lib/utils";-import type * as React from "react";+import * as React from "react";++type TokenFieldState = {+ disabled: boolean;+ loading: boolean;+};++const TokenFieldContext = React.createContext<TokenFieldState>({+ disabled: false,+ loading: false,+});++function TokenField({+ className,+ children,+ disabled = false,+ loading = false,+ loadingLabel = "Loading",+ tabIndex,+ "aria-busy": ariaBusy,+ "aria-disabled": ariaDisabled,+ onBeforeInputCapture,+ onClickCapture,+ onCompositionEndCapture,+ onCompositionStartCapture,+ onCutCapture,+ onDropCapture,+ onInputCapture,+ onKeyDownCapture,+ onPasteCapture,+ onPointerDownCapture,+ ...props+}: React.ComponentProps<"div"> & {+ disabled?: boolean;+ loading?: boolean;+ loadingLabel?: string;+}) {+ const disabledState =+ disabled || ariaDisabled === true || ariaDisabled === "true";+ const inactive = disabledState || loading;+ const guard = <T extends React.SyntheticEvent>(+ handler: ((event: T) => void) | undefined,+ ) =>+ (event: T) => {+ if (inactive) {+ event.preventDefault();+ event.stopPropagation();+ return;+ }+ handler?.(event);+ };+ const guardKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {+ if (inactive && event.key !== "Tab") {+ event.preventDefault();+ event.stopPropagation();+ return;+ }+ onKeyDownCapture?.(event);+ };-function TokenField({ className, ...props }: React.ComponentProps<"div">) {return (- <div- data-slot="token-field"- role="group"- className={cn(- "max-h-40 min-h-6 w-full min-w-0 cursor-text overflow-y-auto whitespace-pre-wrap break-words px-1 text-base leading-6 outline-none data-[empty=true]:before:pointer-events-none data-[empty=true]:before:text-muted-foreground data-[empty=true]:before:content-[attr(data-placeholder)] focus-within:before:hidden aria-disabled:cursor-not-allowed aria-disabled:opacity-60 sm:text-[15px] md:text-xs [&>[contenteditable]]:outline-none",- className,- )}+ <TokenFieldContext.Provider value={{ disabled: disabledState, loading }}>+ <div+ data-slot="token-field"+ data-loading={loading}+ role="group"+ aria-busy={ariaBusy ?? loading}+ aria-disabled={inactive || undefined}+ tabIndex={inactive ? -1 : tabIndex}+ className={cn(+ "max-h-40 min-h-6 w-full min-w-0 cursor-text overflow-y-auto whitespace-pre-wrap break-words px-1 text-base leading-6 outline-none data-[empty=true]:before:pointer-events-none data-[empty=true]:before:text-muted-foreground data-[empty=true]:before:content-[attr(data-placeholder)] data-[loading=true]:cursor-wait focus-within:before:hidden aria-disabled:cursor-not-allowed aria-disabled:opacity-60 sm:text-[15px] md:text-xs [&>[contenteditable]]:outline-none",+ className,+ )}+ {...props}+ onBeforeInputCapture={guard(onBeforeInputCapture)}+ onClickCapture={guard(onClickCapture)}+ onCompositionEndCapture={guard(onCompositionEndCapture)}+ onCompositionStartCapture={guard(onCompositionStartCapture)}+ onCutCapture={guard(onCutCapture)}+ onDropCapture={guard(onDropCapture)}+ onInputCapture={guard(onInputCapture)}+ onKeyDownCapture={guardKeyDown}+ onPasteCapture={guard(onPasteCapture)}+ onPointerDownCapture={guard(onPointerDownCapture)}+ >+ {children}+ <span+ data-slot="token-field-status"+ role="status"+ contentEditable={false}+ className={cn(+ "ml-1 inline-flex align-middle text-muted-foreground",+ !loading && "sr-only",+ )}+ >+ {loading ? (+ <>+ <Spinner aria-hidden="true" role="presentation" />+ <span className="sr-only">{loadingLabel}</span>+ </>+ ) : null}+ </span>+ </div>+ </TokenFieldContext.Provider>+ );+}++function TokenFieldEditable({+ contentEditable = true,+ tabIndex,+ ...props+}: React.ComponentProps<"span">) {+ const state = React.useContext(TokenFieldContext);+ const inactive = state.disabled || state.loading;++ return (+ <span+ data-slot="token-field-editable"+ contentEditable={inactive ? false : contentEditable}+ suppressContentEditableWarning+ tabIndex={inactive ? -1 : (tabIndex ?? -1)}{...props}/>);@@ -20,9 +133,13 @@ function TokenFieldItem({className,...props}: React.ComponentProps<"span">) {+ const state = React.useContext(TokenFieldContext);+ const inactive = state.disabled || state.loading;+return (<spandata-slot="token-field-item"+ aria-disabled={inactive}className={cn("inline-flex h-6 min-w-0 max-w-full shrink-0 items-center gap-1 rounded-lg bg-tag py-0 pr-0.5 pl-0.5 align-middle text-left text-tag-foreground text-xs",className,@@ -34,17 +151,23 @@ function TokenFieldItem({function TokenFieldAction({className,+ disabled,...props}: React.ComponentProps<typeof Button>) {+ const state = React.useContext(TokenFieldContext);+ const inactive = state.disabled || state.loading;+return (<Button+ data-slot="token-field-action"type="button"variant="ghost"size="icon-xs"+ disabled={inactive || disabled}className={cn("size-5 rounded-lg", className)}{...props}/>);}-export { TokenField, TokenFieldAction, TokenFieldItem };+export { TokenField, TokenFieldAction, TokenFieldEditable, TokenFieldItem };diff --git a/packages/ui/test/token-field.spec.ts b/packages/ui/test/token-field.spec.tsindex 7ccc372f..cf884d75 100644--- a/packages/ui/test/token-field.spec.ts+++ b/packages/ui/test/token-field.spec.ts@@ -1,8 +1,20 @@-import { expect, test } from "bun:test";-import { TokenField } from "@crm/ui/components/token-field";-import { createElement } from "react";+import { afterEach, expect, test } from "bun:test";+import {+ TokenField,+ TokenFieldAction,+ TokenFieldEditable,+} from "@crm/ui/components/token-field";+import { Window } from "happy-dom";+import { createElement, type ReactNode } from "react";+import { createRoot } from "react-dom/client";import { renderToStaticMarkup } from "react-dom/server";+const roots: Array<ReturnType<typeof createRoot>> = [];++afterEach(() => {+ for (const root of roots.splice(0)) root.unmount();+});+test("hides an empty placeholder while the field contains focus", () => {const markup = renderToStaticMarkup(createElement(TokenField, {@@ -13,3 +25,149 @@ test("hides an empty placeholder while the field contains focus", () => {expect(markup).toContain("focus-within:before:hidden");});++test("disabled fields block editing and token actions", async () => {+ const { container, render, window } = renderField();+ let actionCount = 0;+ let pointerCount = 0;++ await render(+ createElement(+ TokenField,+ {+ disabled: true,+ tabIndex: 0,+ onPointerDown: () => {+ pointerCount += 1;+ },+ },+ createElement(TokenFieldEditable, { contentEditable: true }, "Draft"),+ createElement(+ TokenFieldAction,+ {+ "aria-label": "Remove item",+ onClick: () => {+ actionCount += 1;+ },+ },+ "Remove",+ ),+ ),+ );++ const field = container.querySelector<HTMLElement>("[data-slot=token-field]");+ const editable = container.querySelector<HTMLElement>(+ "[data-slot=token-field-editable]",+ );+ const action = container.querySelector<HTMLButtonElement>(+ "[data-slot=token-field-action]",+ );++ expect(field?.getAttribute("aria-disabled")).toBe("true");+ expect(field?.tabIndex).toBe(-1);+ expect(editable?.getAttribute("contenteditable")).toBe("false");+ expect(action?.disabled).toBe(true);+ field?.dispatchEvent(+ new window.PointerEvent("pointerdown", {+ bubbles: true,+ cancelable: true,+ }),+ );+ action?.click();+ expect(pointerCount).toBe(0);+ expect(actionCount).toBe(0);+});++test("loading fields show and announce progress while blocking interaction", async () => {+ const { container, render } = renderField();+ let actionCount = 0;++ await render(+ createElement(+ TokenField,+ { loading: true, loadingLabel: "Sending message", tabIndex: 0 },+ createElement(TokenFieldEditable, { contentEditable: true }, "Draft"),+ createElement(TokenFieldAction, {+ "aria-label": "Remove item",+ onClick: () => {+ actionCount += 1;+ },+ }),+ ),+ );++ const field = container.querySelector<HTMLElement>("[data-slot=token-field]");+ const editable = container.querySelector<HTMLElement>(+ "[data-slot=token-field-editable]",+ );+ const action = container.querySelector<HTMLButtonElement>(+ "[data-slot=token-field-action]",+ );+ const status = container.querySelector<HTMLElement>(+ "[data-slot=token-field-status]",+ );++ expect(field?.getAttribute("aria-busy")).toBe("true");+ expect(field?.getAttribute("aria-disabled")).toBe("true");+ expect(editable?.getAttribute("contenteditable")).toBe("false");+ expect(action?.disabled).toBe(true);+ expect(status?.getAttribute("role")).toBe("status");+ expect(status?.textContent).toBe("Sending message");+ expect(status?.querySelector("[data-slot=spinner]")).not.toBeNull();+ expect(status?.classList.contains("sr-only")).toBe(false);+ action?.click();+ expect(actionCount).toBe(0);+});++test("enabled fields permit editing and token actions", async () => {+ const { container, render } = renderField();+ let actionCount = 0;++ await render(+ createElement(+ TokenField,+ null,+ createElement(TokenFieldEditable, null, "Draft"),+ createElement(TokenFieldAction, {+ "aria-label": "Remove item",+ onClick: () => {+ actionCount += 1;+ },+ }),+ ),+ );++ const editable = container.querySelector<HTMLElement>(+ "[data-slot=token-field-editable]",+ );+ const action = container.querySelector<HTMLButtonElement>(+ "[data-slot=token-field-action]",+ );++ expect(editable?.getAttribute("contenteditable")).toBe("true");+ expect(action?.disabled).toBe(false);+ action?.click();+ expect(actionCount).toBe(1);+});++function renderField() {+ const window = new Window();+ Object.assign(globalThis, {+ window,+ document: window.document,+ HTMLElement: window.HTMLElement,+ Node: window.Node,+ });+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ roots.push(root);+ return {+ container,+ window,+ render: async (element: ReactNode) => {+ root.render(element);+ await new Promise((resolve) => setTimeout(resolve, 0));+ },+ };+}