Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

feat(app): CMP-47 add inline composer context

grim57336abc2cc5
diff --git a/apps/app/components/agent-builder/agent-composer.tsx b/apps/app/components/agent-builder/agent-composer.tsx
index d7a6bc04..df161292 100644
--- a/apps/app/components/agent-builder/agent-composer.tsx
+++ b/apps/app/components/agent-builder/agent-composer.tsx
@@ -16,7 +16,11 @@ import {
} from "@crm/ui/components/async-action";
import { Button } from "@crm/ui/components/button";
import { type CarbonIcon, Icon } from "@crm/ui/components/icon";
-import { Input } from "@crm/ui/components/input";
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+} from "@crm/ui/components/input-group";
import {
Popover,
PopoverContent,
@@ -24,10 +28,11 @@ import {
} from "@crm/ui/components/popover";
import { Skeleton } from "@crm/ui/components/skeleton";
import { SkeletonSwap } from "@crm/ui/components/skeleton-swap";
-import { Textarea } from "@crm/ui/components/textarea";
+import { TokenField } from "@crm/ui/components/token-field";
import { cn } from "@crm/ui/lib/utils";
import { useQuery } from "@tanstack/react-query";
import { useReducer, useRef } from "react";
+import { flushSync } from "react-dom";
import { toast } from "sonner";
import {
type BuilderCommandType,
@@ -82,50 +87,134 @@ const CREATE_AGENT_COMMAND = {
commandType: "CREATE_AGENT" as const,
invocation: "/Create agent",
label: "Create agent",
- description: "Build a durable team automation",
};
type ComposerCommand = typeof CREATE_AGENT_COMMAND;
+type ComposerAnchor = {
+ key: string;
+ offset: number;
+ order: number;
+};
+
type ComposerState = {
draft: string;
command: ComposerCommand | null;
detectedCommandLabel: string | null;
commandOpen: boolean;
+ resourceOpen: boolean;
resourceQuery: string;
resources: BuilderResource[];
attachments: BuilderUploadAttachment[];
attachmentsReading: boolean;
+ anchors: ComposerAnchor[];
+ nextAnchorOrder: number;
};
type ComposerAction =
- | { type: "draft.changed"; value: string }
- | { type: "command.selected" }
- | { type: "command.removed" }
+ | { type: "editor.changed"; value: string; anchors: ComposerAnchor[] }
+ | { type: "command.selected"; offset: number }
+ | { type: "context.removed"; key: string }
| { type: "command.open.changed"; open: boolean }
+ | { type: "resource.open.changed"; open: boolean }
| { type: "resource.query.changed"; value: string }
- | { type: "resource.added"; resource: BuilderResource }
- | { type: "resource.removed"; resource: BuilderResource }
- | { type: "attachments.added"; attachments: BuilderUploadAttachment[] }
- | { type: "attachment.removed"; attachment: BuilderUploadAttachment }
+ | { type: "resource.added"; resource: BuilderResource; offset: number }
+ | {
+ type: "attachments.added";
+ attachments: BuilderUploadAttachment[];
+ offset: number;
+ }
| { type: "attachments.reading.started" }
| { type: "attachments.reading.finished" }
| { type: "submitted" };
+const COMMAND_CONTEXT_KEY = "command:create-agent";
+const EDITOR_SENTINEL = "\u200B";
+
+function resourceContextKey(resource: BuilderResource): string {
+ return `resource:${resource.kind}:${resource.id}`;
+}
+
+function attachmentContextKey(attachment: ChatChipAttachment): string {
+ return `attachment:${attachmentKey(attachment)}`;
+}
+
+function clampAnchor(anchor: ComposerAnchor, length: number): ComposerAnchor {
+ return { ...anchor, offset: Math.max(0, Math.min(anchor.offset, length)) };
+}
+
+function withAnchor(
+ state: ComposerState,
+ key: string,
+ offset: number,
+): Pick<ComposerState, "anchors" | "nextAnchorOrder"> {
+ if (state.anchors.some((anchor) => anchor.key === key)) {
+ return {
+ anchors: state.anchors,
+ nextAnchorOrder: state.nextAnchorOrder,
+ };
+ }
+ return {
+ anchors: [
+ ...state.anchors,
+ clampAnchor(
+ { key, offset, order: state.nextAnchorOrder },
+ state.draft.length,
+ ),
+ ],
+ nextAnchorOrder: state.nextAnchorOrder + 1,
+ };
+}
+
+function withoutContext(state: ComposerState, key: string): ComposerState {
+ return {
+ ...state,
+ command: key === COMMAND_CONTEXT_KEY ? null : state.command,
+ detectedCommandLabel:
+ key === COMMAND_CONTEXT_KEY ? null : state.detectedCommandLabel,
+ resources: state.resources.filter(
+ (resource) => resourceContextKey(resource) !== key,
+ ),
+ attachments: state.attachments.filter(
+ (attachment) => attachmentContextKey(attachment) !== key,
+ ),
+ anchors: state.anchors.filter((anchor) => anchor.key !== key),
+ };
+}
+
function initialComposerState(initialPrompt: string): ComposerState {
const explicitCommand = consumeBuilderCommand(initialPrompt);
const detectedIntent = explicitCommand
? null
: consumeBuilderIntent(initialPrompt);
+ const draft = explicitCommand?.body ?? initialPrompt;
+ const commandOffset = explicitCommand
+ ? 0
+ : detectedIntent
+ ? initialPrompt.indexOf(detectedIntent.invocation) +
+ detectedIntent.invocation.length
+ : null;
return {
- draft: explicitCommand?.body ?? initialPrompt,
+ draft,
command: explicitCommand || detectedIntent ? CREATE_AGENT_COMMAND : null,
detectedCommandLabel: detectedIntent?.invocation ?? null,
commandOpen: false,
+ resourceOpen: false,
resourceQuery: "",
resources: [],
attachments: [],
attachmentsReading: false,
+ anchors:
+ commandOffset === null
+ ? []
+ : [
+ {
+ key: COMMAND_CONTEXT_KEY,
+ offset: Math.max(0, commandOffset),
+ order: 0,
+ },
+ ],
+ nextAnchorOrder: commandOffset === null ? 0 : 1,
};
}
@@ -134,69 +223,128 @@ function composerReducer(
action: ComposerAction,
): ComposerState {
switch (action.type) {
- case "draft.changed": {
+ case "editor.changed": {
+ const presentKeys = new Set(action.anchors.map((anchor) => anchor.key));
+ const retainedCommand =
+ state.command && presentKeys.has(COMMAND_CONTEXT_KEY)
+ ? state.command
+ : null;
+ const retainedResources = state.resources.filter((resource) =>
+ presentKeys.has(resourceContextKey(resource)),
+ );
+ const retainedAttachments = state.attachments.filter((attachment) =>
+ presentKeys.has(attachmentContextKey(attachment)),
+ );
+ const anchors = action.anchors.map((anchor) =>
+ clampAnchor(anchor, action.value.length),
+ );
const explicitCommand = consumeBuilderCommand(action.value);
- if (explicitCommand) {
+ if (!retainedCommand && explicitCommand) {
+ const bodyStart = action.value.length - explicitCommand.body.length;
+ const shiftedAnchors = anchors.map((anchor) =>
+ clampAnchor(
+ { ...anchor, offset: anchor.offset - bodyStart },
+ explicitCommand.body.length,
+ ),
+ );
return {
...state,
draft: explicitCommand.body,
command: CREATE_AGENT_COMMAND,
detectedCommandLabel: null,
commandOpen: false,
+ resources: retainedResources,
+ attachments: retainedAttachments,
+ anchors: [
+ ...shiftedAnchors,
+ {
+ key: COMMAND_CONTEXT_KEY,
+ offset: 0,
+ order: state.nextAnchorOrder,
+ },
+ ],
+ nextAnchorOrder: state.nextAnchorOrder + 1,
};
}
- const detectedIntent = state.command
+ const detectedIntent = retainedCommand
? null
: consumeBuilderIntent(action.value);
if (detectedIntent) {
+ const intentStart = action.value.indexOf(detectedIntent.invocation);
return {
...state,
draft: action.value,
command: CREATE_AGENT_COMMAND,
detectedCommandLabel: detectedIntent.invocation,
commandOpen: false,
+ resources: retainedResources,
+ attachments: retainedAttachments,
+ anchors: [
+ ...anchors,
+ {
+ key: COMMAND_CONTEXT_KEY,
+ offset: Math.max(
+ 0,
+ intentStart + detectedIntent.invocation.length,
+ ),
+ order: state.nextAnchorOrder,
+ },
+ ],
+ nextAnchorOrder: state.nextAnchorOrder + 1,
};
}
return {
...state,
draft: action.value,
- commandOpen: !state.command && action.value.trimStart().startsWith("/"),
+ command: retainedCommand,
+ detectedCommandLabel: retainedCommand
+ ? state.detectedCommandLabel
+ : null,
+ commandOpen:
+ !retainedCommand && action.value.trimStart().startsWith("/"),
+ resources: retainedResources,
+ attachments: retainedAttachments,
+ anchors,
};
}
- case "command.selected":
+ case "command.selected": {
+ const clearsSlash = state.draft.trimStart().startsWith("/");
+ const draft = clearsSlash ? "" : state.draft;
+ const anchorState = withAnchor(
+ { ...state, draft },
+ COMMAND_CONTEXT_KEY,
+ clearsSlash ? 0 : action.offset,
+ );
return {
...state,
+ ...anchorState,
command: CREATE_AGENT_COMMAND,
detectedCommandLabel: null,
commandOpen: false,
- draft: state.draft.trimStart().startsWith("/") ? "" : state.draft,
- };
- case "command.removed":
- return {
- ...state,
- command: null,
- detectedCommandLabel: null,
+ draft,
};
+ }
+ case "context.removed":
+ return withoutContext(state, action.key);
case "command.open.changed":
return { ...state, commandOpen: action.open };
+ case "resource.open.changed":
+ return { ...state, resourceOpen: action.open };
case "resource.query.changed":
return { ...state, resourceQuery: action.value };
- case "resource.added":
+ case "resource.added": {
+ const key = resourceContextKey(action.resource);
return state.resources.some(
(item) =>
item.kind === action.resource.kind && item.id === action.resource.id,
)
? state
- : { ...state, resources: [...state.resources, action.resource] };
- case "resource.removed":
- return {
- ...state,
- resources: state.resources.filter(
- (item) =>
- item.kind !== action.resource.kind ||
- item.id !== action.resource.id,
- ),
- };
+ : {
+ ...state,
+ ...withAnchor(state, key, action.offset),
+ resources: [...state.resources, action.resource],
+ };
+ }
case "attachments.added": {
const keys = new Set(state.attachments.map(attachmentKey));
const added = action.attachments.filter((attachment) => {
@@ -206,18 +354,19 @@ function composerReducer(
return true;
});
if (added.length === 0) return state;
+ const accepted = added.slice(0, 5 - state.attachments.length);
+ const addedAnchors = accepted.map((attachment, index) => ({
+ key: attachmentContextKey(attachment),
+ offset: Math.max(0, Math.min(action.offset, state.draft.length)),
+ order: state.nextAnchorOrder + index,
+ }));
return {
...state,
- attachments: [...state.attachments, ...added].slice(0, 5),
+ attachments: [...state.attachments, ...accepted],
+ anchors: [...state.anchors, ...addedAnchors],
+ nextAnchorOrder: state.nextAnchorOrder + accepted.length,
};
}
- case "attachment.removed":
- return {
- ...state,
- attachments: state.attachments.filter(
- (item) => item !== action.attachment,
- ),
- };
case "attachments.reading.started":
return { ...state, attachmentsReading: true };
case "attachments.reading.finished":
@@ -229,9 +378,13 @@ function composerReducer(
command: null,
detectedCommandLabel: null,
commandOpen: false,
+ resourceOpen: false,
+ resourceQuery: "",
resources: [],
attachments: [],
attachmentsReading: false,
+ anchors: [],
+ nextAnchorOrder: 0,
};
}
}
@@ -263,6 +416,9 @@ export function AgentComposer({
}) {
const trpc = useTRPC();
const pendingSubmission = useRef<PendingSubmission | null>(null);
+ const editor = useRef<HTMLDivElement>(null);
+ const selectionOffset = useRef(initialPrompt.length);
+ const composing = useRef(false);
const [state, dispatch] = useReducer(
composerReducer,
initialPrompt,
@@ -309,6 +465,34 @@ export function AgentComposer({
const connectedGoogle = (google.data?.sources ?? []).filter(
(source) => source.connected,
);
+ const focusAfterContext = (key: string) => {
+ let attempts = 0;
+ const focus = () => {
+ const offset = focusEditorAfterContext(editor.current, key);
+ if (offset !== null) {
+ selectionOffset.current = offset;
+ return;
+ }
+ attempts += 1;
+ if (attempts < 3) requestAnimationFrame(focus);
+ };
+ requestAnimationFrame(focus);
+ };
+ const updateEditor = (snapshot: ComposerEditorSnapshot) => {
+ flushSync(() => {
+ dispatch({
+ type: "editor.changed",
+ value: snapshot.value,
+ anchors: snapshot.anchors,
+ });
+ });
+ selectionOffset.current = snapshot.selectionOffset;
+ focusEditorAtOffset(editor.current, snapshot.selectionOffset);
+ };
+ const removeContext = (key: string) => {
+ flushSync(() => dispatch({ type: "context.removed", key }));
+ focusEditorAtOffset(editor.current, selectionOffset.current);
+ };
return (
<div
@@ -317,20 +501,17 @@ export function AgentComposer({
mode === "home" ? "min-h-24" : "min-h-[78px]",
)}
>
- <ComposerContext
- command={state.command}
- resources={state.resources}
- attachments={state.attachments}
- disabled={locked}
- dispatch={dispatch}
- />
-
- <ComposerTextarea
+ <ComposerEditor
+ editorRef={editor}
+ composingRef={composing}
mode={mode}
- value={state.draft}
- detectedIntent={state.detectedCommandLabel}
- onChange={(value) => dispatch({ type: "draft.changed", value })}
+ state={state}
disabled={locked}
+ onChanged={updateEditor}
+ onSelectionChanged={(offset) => {
+ selectionOffset.current = offset;
+ }}
+ onRemoveContext={removeContext}
onSubmit={submit}
/>
@@ -344,6 +525,8 @@ export function AgentComposer({
disabled={locked}
attachmentsReading={state.attachmentsReading}
dispatch={dispatch}
+ getInsertionOffset={() => selectionOffset.current}
+ onContextAdded={focusAfterContext}
/>
<Button
@@ -375,130 +558,598 @@ export function AgentComposer({
);
}
-function ComposerTextarea({
+type ComposerEditorSnapshot = {
+ value: string;
+ anchors: ComposerAnchor[];
+ selectionOffset: number;
+};
+
+type ComposerEditorPart =
+ | { type: "text"; key: string; start: number; value: string }
+ | { type: "context"; anchor: ComposerAnchor };
+
+function ComposerEditor({
+ editorRef,
+ composingRef,
mode,
- value,
- detectedIntent,
+ state,
disabled,
- onChange,
+ onChanged,
+ onSelectionChanged,
+ onRemoveContext,
onSubmit,
}: {
+ editorRef: React.RefObject<HTMLDivElement | null>;
+ composingRef: React.RefObject<boolean>;
mode: "home" | "chat";
- value: string;
- detectedIntent: string | null;
+ state: ComposerState;
disabled: boolean;
- onChange: (value: string) => void;
+ onChanged: (snapshot: ComposerEditorSnapshot) => void;
+ onSelectionChanged: (offset: number) => void;
+ onRemoveContext: (key: string) => void;
onSubmit: () => void;
}) {
- const emphasis = useRef<HTMLDivElement>(null);
- const intentStart = detectedIntent ? value.indexOf(detectedIntent) : -1;
- const showEmphasis = detectedIntent !== null && intentStart >= 0;
+ const parts = composerEditorParts(state);
+ const placeholder =
+ mode === "home"
+ ? "Ask about your CRM or automate a task…"
+ : "Send a message";
+ const commit = () => {
+ const root = editorRef.current;
+ if (!root || composingRef.current) return;
+ onChanged(readComposerEditor(root, state.draft.length));
+ };
+ const captureSelection = () => {
+ const root = editorRef.current;
+ if (!root) return;
+ onSelectionChanged(composerEditorOffset(root, state.draft.length));
+ };
return (
- <div className="relative grid">
- {showEmphasis ? (
- <div
- ref={emphasis}
- data-intent-overlay
- aria-hidden
- className="pointer-events-none absolute inset-0 overflow-hidden whitespace-pre-wrap break-words border border-transparent px-1 py-0 text-base leading-6 sm:text-[15px] md:text-xs"
- >
- <span>{value.slice(0, intentStart)}</span>
+ <TokenField
+ ref={editorRef}
+ role="textbox"
+ tabIndex={disabled ? -1 : 0}
+ aria-label="Message the agent builder"
+ aria-multiline="true"
+ aria-disabled={disabled}
+ data-empty={state.draft.length === 0 && state.anchors.length === 0}
+ data-placeholder={placeholder}
+ spellCheck
+ onFocus={(event) => {
+ if (event.target !== event.currentTarget) return;
+ focusEditorAtOffset(event.currentTarget, state.draft.length);
+ }}
+ onPointerDown={(event) => {
+ if (event.target !== event.currentTarget) return;
+ event.preventDefault();
+ onSelectionChanged(state.draft.length);
+ focusEditorAtOffset(event.currentTarget, state.draft.length);
+ }}
+ onBeforeInput={(event) =>
+ ensureComposerEditorSelection(event.currentTarget, state.draft.length)
+ }
+ onInput={commit}
+ onBlur={captureSelection}
+ onKeyUp={captureSelection}
+ onPointerUp={captureSelection}
+ onCompositionStart={() => {
+ composingRef.current = true;
+ }}
+ onCompositionEnd={() => {
+ composingRef.current = false;
+ commit();
+ }}
+ onPaste={(event) => {
+ event.preventDefault();
+ insertEditorText(
+ event.currentTarget,
+ event.clipboardData.getData("text/plain"),
+ );
+ commit();
+ }}
+ onDrop={(event) => event.preventDefault()}
+ onKeyDown={(event) => {
+ if (event.nativeEvent.isComposing || composingRef.current) return;
+ if (event.key === "Enter") {
+ event.preventDefault();
+ if (event.shiftKey) {
+ insertEditorText(event.currentTarget, "\n");
+ commit();
+ } else {
+ onSubmit();
+ }
+ return;
+ }
+ if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
+ const offset = moveComposerCaretAcrossContext(
+ event.currentTarget,
+ event.key === "ArrowLeft" ? "previous" : "next",
+ );
+ if (offset !== null) {
+ event.preventDefault();
+ onSelectionChanged(offset);
+ }
+ return;
+ }
+ if (event.key === "Backspace") {
+ const key = previousComposerContextKey(event.currentTarget);
+ if (!key) return;
+ event.preventDefault();
+ onSelectionChanged(
+ composerEditorOffset(event.currentTarget, state.draft.length),
+ );
+ onRemoveContext(key);
+ }
+ }}
+ >
+ {parts.map((part) =>
+ part.type === "text" ? (
+ <ComposerEditorText
+ key={part.key}
+ start={part.start}
+ value={part.value}
+ disabled={disabled}
+ detectedIntent={state.detectedCommandLabel}
+ intentStart={
+ state.detectedCommandLabel
+ ? state.draft.indexOf(state.detectedCommandLabel)
+ : -1
+ }
+ />
+ ) : (
+ <ComposerContextToken
+ key={part.anchor.key}
+ anchor={part.anchor}
+ state={state}
+ disabled={disabled}
+ onRemove={onRemoveContext}
+ />
+ ),
+ )}
+ </TokenField>
+ );
+}
+
+function ComposerEditorText({
+ start,
+ value,
+ disabled,
+ detectedIntent,
+ intentStart,
+}: {
+ start: number;
+ value: string;
+ disabled: boolean;
+ detectedIntent: string | null;
+ intentStart: number;
+}) {
+ const localIntentStart = intentStart - start;
+ const showsIntent =
+ detectedIntent !== null &&
+ localIntentStart >= 0 &&
+ localIntentStart + detectedIntent.length <= value.length;
+
+ return (
+ <span
+ contentEditable={!disabled}
+ suppressContentEditableWarning
+ tabIndex={-1}
+ role="none"
+ data-composer-text
+ data-composer-text-start={start}
+ >
+ {showsIntent ? (
+ <>
+ {value.slice(0, localIntentStart)}
<span data-intent-trigger className="relative">
{detectedIntent}
<span
+ contentEditable={false}
data-intent-accent
className="absolute inset-x-0 bottom-0 h-px origin-left animate-in bg-primary duration-200 ease-out zoom-in-0 motion-reduce:animate-none"
/>
</span>
- <span>{value.slice(intentStart + detectedIntent.length)}</span>
- </div>
- ) : null}
- <Textarea
- value={value}
- onChange={(event) => onChange(event.target.value)}
- onScroll={(event) => {
- if (!emphasis.current) return;
- emphasis.current.style.translate = `${-event.currentTarget.scrollLeft}px ${-event.currentTarget.scrollTop}px`;
- }}
- onKeyDown={(event) => {
- if (event.key === "Enter" && !event.shiftKey) {
- event.preventDefault();
- onSubmit();
- }
- }}
- disabled={disabled}
- rows={mode === "home" ? 2 : 1}
- variant="composer"
- size="composer"
- placeholder={
- mode === "home"
- ? "Ask about your CRM or automate a task…"
- : "Send a message"
- }
- aria-label="Message the agent builder"
- className={cn(
- "relative",
- showEmphasis && "text-transparent caret-foreground",
- )}
- />
- </div>
+ {value.slice(localIntentStart + detectedIntent.length)}
+ </>
+ ) : (
+ value || EDITOR_SENTINEL
+ )}
+ </span>
);
}
-function ComposerContext({
- command,
- resources,
- attachments,
+function ComposerContextToken({
+ anchor,
+ state,
disabled,
- dispatch,
+ onRemove,
}: {
- command: ComposerCommand | null;
- resources: BuilderResource[];
- attachments: BuilderUploadAttachment[];
+ anchor: ComposerAnchor;
+ state: ComposerState;
disabled: boolean;
- dispatch: React.Dispatch<ComposerAction>;
+ onRemove: (key: string) => void;
}) {
- if (!command && resources.length === 0 && attachments.length === 0) {
- return null;
- }
-
- return (
- <div className="flex flex-wrap gap-1 px-1 pb-1">
- {command ? (
- <ChatCommandChip
- label={command.label}
- icon={Application}
- onRemove={
- disabled ? undefined : () => dispatch({ type: "command.removed" })
- }
- />
- ) : null}
- {resources.map((resource) => (
+ const remove = disabled ? undefined : () => onRemove(anchor.key);
+ let content: React.ReactNode = null;
+ if (anchor.key === COMMAND_CONTEXT_KEY && state.command) {
+ content = (
+ <ChatCommandChip
+ label={state.command.label}
+ icon={Application}
+ variant="composer"
+ onRemove={remove}
+ />
+ );
+ } else {
+ const resource = state.resources.find(
+ (item) => resourceContextKey(item) === anchor.key,
+ );
+ if (resource) {
+ content = (
<ChatReferenceChip
- key={`${resource.kind}:${resource.id}`}
resource={resource}
icon={RESOURCE_ICONS[resource.kind]}
- onRemove={
- disabled
- ? undefined
- : () => dispatch({ type: "resource.removed", resource })
- }
+ variant="composer"
+ onRemove={remove}
/>
- ))}
- {attachments.map((attachment) => (
- <ChatAttachmentChip
- key={attachmentKey(attachment)}
- attachment={attachment}
- onRemove={
- disabled
- ? undefined
- : () => dispatch({ type: "attachment.removed", attachment })
- }
- />
- ))}
- </div>
+ );
+ } else {
+ const attachment = state.attachments.find(
+ (item) => attachmentContextKey(item) === anchor.key,
+ );
+ if (attachment) {
+ content = (
+ <ChatAttachmentChip
+ attachment={attachment}
+ variant="composer"
+ onRemove={remove}
+ />
+ );
+ }
+ }
+ }
+ if (!content) return null;
+
+ return (
+ <span
+ contentEditable={false}
+ data-composer-token-key={anchor.key}
+ data-composer-token-order={anchor.order}
+ className="inline-flex align-middle"
+ >
+ {content}
+ </span>
+ );
+}
+
+function composerEditorParts(state: ComposerState): ComposerEditorPart[] {
+ const activeKeys = new Set<string>();
+ if (state.command) activeKeys.add(COMMAND_CONTEXT_KEY);
+ for (const resource of state.resources) {
+ activeKeys.add(resourceContextKey(resource));
+ }
+ for (const attachment of state.attachments) {
+ activeKeys.add(attachmentContextKey(attachment));
+ }
+ const anchors = state.anchors
+ .filter((anchor) => activeKeys.has(anchor.key))
+ .map((anchor) => clampAnchor(anchor, state.draft.length))
+ .sort(
+ (left, right) => left.offset - right.offset || left.order - right.order,
+ );
+ const parts: ComposerEditorPart[] = [];
+ let cursor = 0;
+ let previousKey = "start";
+ for (const anchor of anchors) {
+ parts.push({
+ type: "text",
+ key: `text-after:${previousKey}`,
+ start: cursor,
+ value: state.draft.slice(cursor, anchor.offset),
+ });
+ parts.push({ type: "context", anchor });
+ cursor = anchor.offset;
+ previousKey = anchor.key;
+ }
+ parts.push({
+ type: "text",
+ key: `text-after:${previousKey}`,
+ start: cursor,
+ value: state.draft.slice(cursor),
+ });
+ return parts;
+}
+
+function readComposerEditor(
+ root: HTMLDivElement,
+ fallbackOffset: number,
+): ComposerEditorSnapshot {
+ const selectionOffset = composerEditorOffset(root, fallbackOffset);
+ const anchors: ComposerAnchor[] = [];
+ let value = "";
+ for (const node of Array.from(root.childNodes)) {
+ if (node instanceof HTMLElement && node.dataset.composerTokenKey) {
+ anchors.push({
+ key: node.dataset.composerTokenKey,
+ offset: value.length,
+ order: Number(node.dataset.composerTokenOrder ?? anchors.length),
+ });
+ continue;
+ }
+ value += composerEditableText(node);
+ }
+ return { value, anchors, selectionOffset };
+}
+
+function composerEditorOffset(
+ root: HTMLDivElement,
+ fallbackOffset: number,
+): number {
+ const selection = root.ownerDocument.defaultView?.getSelection();
+ const focusNode = selection?.focusNode;
+ if (!selection || !focusNode || !root.contains(focusNode)) {
+ return Math.max(
+ 0,
+ Math.min(fallbackOffset, composerEditableText(root).length),
+ );
+ }
+ if (focusNode === root) {
+ let offset = 0;
+ for (const node of Array.from(root.childNodes).slice(
+ 0,
+ selection.focusOffset,
+ )) {
+ offset += composerEditableText(node).length;
+ }
+ return offset;
+ }
+
+ let offset = 0;
+ for (const node of Array.from(root.childNodes)) {
+ if (node === focusNode || node.contains?.(focusNode)) {
+ return (
+ offset + composerOffsetWithin(node, focusNode, selection.focusOffset)
+ );
+ }
+ offset += composerEditableText(node).length;
+ }
+ return Math.max(0, Math.min(fallbackOffset, offset));
+}
+
+function composerOffsetWithin(
+ container: Node,
+ target: Node,
+ targetOffset: number,
+): number {
+ const range = container.ownerDocument?.createRange();
+ if (!range) return 0;
+ try {
+ range.selectNodeContents(container);
+ range.setEnd(target, targetOffset);
+ return composerEditableText(range.cloneContents()).length;
+ } catch {
+ return 0;
+ }
+}
+
+function composerEditableText(node: Node): string {
+ if (node.nodeType === Node.TEXT_NODE) {
+ return (node.textContent ?? "").replaceAll(EDITOR_SENTINEL, "");
+ }
+ if (node instanceof HTMLElement) {
+ if (
+ node.dataset.composerTokenKey ||
+ node.dataset.intentAccent !== undefined
+ ) {
+ return "";
+ }
+ if (
+ node.dataset.composerText !== undefined &&
+ node.childNodes.length === 1 &&
+ node.firstChild instanceof HTMLBRElement
+ ) {
+ return "";
+ }
+ if (node.tagName === "BR") return "\n";
+ }
+ let value = "";
+ for (const child of Array.from(node.childNodes)) {
+ value += composerEditableText(child);
+ }
+ return value;
+}
+
+function previousComposerContextKey(root: HTMLDivElement): string | null {
+ const selection = root.ownerDocument.defaultView?.getSelection();
+ const focusNode = selection?.focusNode;
+ if (!selection?.isCollapsed || !focusNode || !root.contains(focusNode)) {
+ return null;
+ }
+ const parent =
+ focusNode instanceof HTMLElement ? focusNode : focusNode.parentElement;
+ const text = parent?.closest<HTMLElement>("[data-composer-text]");
+ if (text && root.contains(text)) {
+ if (composerOffsetWithin(text, focusNode, selection.focusOffset) !== 0) {
+ return null;
+ }
+ return text.previousElementSibling instanceof HTMLElement
+ ? (text.previousElementSibling.dataset.composerTokenKey ?? null)
+ : null;
+ }
+ if (focusNode === root && selection.focusOffset > 0) {
+ const previous = root.childNodes.item(selection.focusOffset - 1);
+ return previous instanceof HTMLElement
+ ? (previous.dataset.composerTokenKey ?? null)
+ : null;
+ }
+ return null;
+}
+
+function moveComposerCaretAcrossContext(
+ root: HTMLDivElement,
+ direction: "previous" | "next",
+): number | null {
+ const selection = root.ownerDocument.defaultView?.getSelection();
+ const focusNode = selection?.focusNode;
+ if (!selection?.isCollapsed || !focusNode || !root.contains(focusNode)) {
+ return null;
+ }
+ const parent =
+ focusNode instanceof HTMLElement ? focusNode : focusNode.parentElement;
+ const text = parent?.closest<HTMLElement>("[data-composer-text]");
+ if (!text) return null;
+ const localOffset = composerOffsetWithin(
+ text,
+ focusNode,
+ selection.focusOffset,
+ );
+ const textLength = composerEditableText(text).length;
+ if (direction === "previous" && localOffset === 0) {
+ const token = text.previousElementSibling;
+ const previous = token?.previousElementSibling;
+ if (
+ !(token instanceof HTMLElement) ||
+ !token.dataset.composerTokenKey ||
+ !(previous instanceof HTMLElement) ||
+ previous.dataset.composerText === undefined
+ ) {
+ return null;
+ }
+ setComposerCaret(previous, composerEditableText(previous).length);
+ return Number(text.dataset.composerTextStart ?? 0);
+ }
+ if (direction === "next" && localOffset === textLength) {
+ const token = text.nextElementSibling;
+ const next = token?.nextElementSibling;
+ if (
+ !(token instanceof HTMLElement) ||
+ !token.dataset.composerTokenKey ||
+ !(next instanceof HTMLElement) ||
+ next.dataset.composerText === undefined
+ ) {
+ return null;
+ }
+ setComposerCaret(next, 0);
+ return Number(next.dataset.composerTextStart ?? 0);
+ }
+ return null;
+}
+
+function insertEditorText(root: HTMLDivElement, value: string): void {
+ let selection = root.ownerDocument.defaultView?.getSelection();
+ if (
+ !selection?.rangeCount ||
+ !selection.focusNode ||
+ !root.contains(selection.focusNode)
+ ) {
+ focusEditorAtOffset(root, composerEditableText(root).length);
+ selection = root.ownerDocument.defaultView?.getSelection();
+ }
+ if (!selection?.rangeCount) return;
+ const range = selection.getRangeAt(0);
+ range.deleteContents();
+ const text = root.ownerDocument.createTextNode(value);
+ range.insertNode(text);
+ range.setStartAfter(text);
+ range.collapse(true);
+ selection.removeAllRanges();
+ selection.addRange(range);
+}
+
+function ensureComposerEditorSelection(
+ root: HTMLDivElement,
+ fallbackOffset: number,
+): void {
+ const selection = root.ownerDocument.defaultView?.getSelection();
+ const focusNode = selection?.focusNode;
+ const parent =
+ focusNode instanceof HTMLElement ? focusNode : focusNode?.parentElement;
+ if (parent?.closest("[data-composer-text]")) return;
+ focusEditorAtOffset(root, composerEditorOffset(root, fallbackOffset));
+}
+
+function focusEditorAtOffset(
+ root: HTMLDivElement | null,
+ offset: number,
+): void {
+ if (!root) return;
+ const textParts = Array.from(
+ root.querySelectorAll<HTMLElement>("[data-composer-text]"),
);
+ let target = textParts.at(-1) ?? null;
+ for (const part of textParts) {
+ const start = Number(part.dataset.composerTextStart ?? 0);
+ const end = start + composerEditableText(part).length;
+ if (start <= offset && offset <= end) target = part;
+ }
+ if (!target) return;
+ const start = Number(target.dataset.composerTextStart ?? 0);
+ setComposerCaret(target, Math.max(0, offset - start));
+}
+
+function focusEditorAfterContext(
+ root: HTMLDivElement | null,
+ key: string,
+): number | null {
+ if (!root) return null;
+ const token = Array.from(
+ root.querySelectorAll<HTMLElement>("[data-composer-token-key]"),
+ ).find((item) => item.dataset.composerTokenKey === key);
+ const text = token?.nextElementSibling;
+ if (!(text instanceof HTMLElement) || !text.dataset.composerText) return null;
+ setComposerCaret(text, 0);
+ return Number(text.dataset.composerTextStart ?? 0);
+}
+
+function setComposerCaret(container: HTMLElement, offset: number): void {
+ container.focus();
+ const textNodes: Text[] = [];
+ const collect = (node: Node) => {
+ if (node.nodeType === Node.TEXT_NODE) {
+ textNodes.push(node as Text);
+ return;
+ }
+ if (
+ node instanceof HTMLElement &&
+ (node.contentEditable === "false" ||
+ node.dataset.composerTokenKey ||
+ node.dataset.intentAccent !== undefined)
+ ) {
+ return;
+ }
+ for (const child of Array.from(node.childNodes)) collect(child);
+ };
+ collect(container);
+ const range = container.ownerDocument.createRange();
+ let remaining = offset;
+ for (const text of textNodes) {
+ const logicalLength = text.data.replaceAll(EDITOR_SENTINEL, "").length;
+ if (remaining <= logicalLength) {
+ range.setStart(text, composerDomOffset(text.data, remaining));
+ range.collapse(true);
+ const selection = container.ownerDocument.defaultView?.getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+ return;
+ }
+ remaining -= logicalLength;
+ }
+ range.selectNodeContents(container);
+ range.collapse(false);
+ const selection = container.ownerDocument.defaultView?.getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+}
+
+function composerDomOffset(value: string, logicalOffset: number): number {
+ if (logicalOffset === 0) return 0;
+ let logical = 0;
+ for (let index = 0; index < value.length; index += 1) {
+ if (value[index] !== EDITOR_SENTINEL) logical += 1;
+ if (logical === logicalOffset) return index + 1;
+ }
+ return value.length;
}
function ComposerTools({
@@ -510,6 +1161,8 @@ function ComposerTools({
disabled,
attachmentsReading,
dispatch,
+ getInsertionOffset,
+ onContextAdded,
}: {
state: ComposerState;
resources: BuilderResource[];
@@ -519,10 +1172,13 @@ function ComposerTools({
disabled: boolean;
attachmentsReading: boolean;
dispatch: React.Dispatch<ComposerAction>;
+ getInsertionOffset: () => number;
+ onContextAdded: (key: string) => void;
}) {
return (
<div className="flex items-center gap-0.5">
<ResourcePicker
+ open={state.resourceOpen}
query={state.resourceQuery}
resources={resources}
loading={resourcesLoading}
@@ -530,21 +1186,31 @@ function ComposerTools({
connectedGoogle={connectedGoogle}
disabled={disabled}
dispatch={dispatch}
+ getInsertionOffset={getInsertionOffset}
+ onPicked={onContextAdded}
/>
<AttachmentPicker
- disabled={disabled || attachmentsReading}
+ disabled={
+ disabled || attachmentsReading || state.attachments.length >= 5
+ }
+ remaining={Math.max(0, 5 - state.attachments.length)}
dispatch={dispatch}
+ getInsertionOffset={getInsertionOffset}
+ onPicked={onContextAdded}
/>
<CommandPicker
open={state.commandOpen}
disabled={disabled}
dispatch={dispatch}
+ getInsertionOffset={getInsertionOffset}
+ onPicked={onContextAdded}
/>
</div>
);
}
function ResourcePicker({
+ open,
query,
resources,
loading,
@@ -552,7 +1218,10 @@ function ResourcePicker({
connectedGoogle,
disabled,
dispatch,
+ getInsertionOffset,
+ onPicked,
}: {
+ open: boolean;
query: string;
resources: BuilderResource[];
loading: boolean;
@@ -560,12 +1229,26 @@ function ResourcePicker({
connectedGoogle: Array<{ source: string }>;
disabled: boolean;
dispatch: React.Dispatch<ComposerAction>;
+ getInsertionOffset: () => number;
+ onPicked: (key: string) => void;
}) {
- const add = (resource: BuilderResource) =>
- dispatch({ type: "resource.added", resource });
+ const add = (resource: BuilderResource) => {
+ dispatch({
+ type: "resource.added",
+ resource,
+ offset: getInsertionOffset(),
+ });
+ dispatch({ type: "resource.open.changed", open: false });
+ onPicked(resourceContextKey(resource));
+ };
return (
- <Popover>
+ <Popover
+ open={disabled ? false : open}
+ onOpenChange={(next) =>
+ dispatch({ type: "resource.open.changed", open: next })
+ }
+ >
<PopoverTrigger asChild>
<Button
variant="ghost"
@@ -578,12 +1261,8 @@ function ResourcePicker({
</PopoverTrigger>
<PopoverContent size="fit" align="start" side="top" className="w-80">
<div className="border-b p-2">
- <div className="relative">
- <Icon
- icon={Search}
- className="absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground"
- />
- <Input
+ <InputGroup>
+ <InputGroupInput
value={query}
onChange={(event) =>
dispatch({
@@ -591,12 +1270,14 @@ function ResourcePicker({
value: event.target.value,
})
}
- placeholder="Search CRM records"
- aria-label="Search CRM records"
+ placeholder="Search CRM"
+ aria-label="Search CRM"
disabled={disabled}
- className="pl-8"
/>
- </div>
+ <InputGroupAddon>
+ <Icon icon={Search} className="size-3.5" />
+ </InputGroupAddon>
+ </InputGroup>
</div>
<div className="max-h-72 overflow-y-auto p-1">
{connectedGoogle.map((source) => {
@@ -607,14 +1288,13 @@ function ResourcePicker({
key={source.source}
icon={calendar ? Calendar : Email}
label={label}
- detail="Connected integration"
disabled={disabled}
onSelect={() =>
add({
kind: "integration",
id: `google:${source.source}`,
label,
- detail: "Connected integration",
+ detail: null,
imageUrl: null,
})
}
@@ -631,7 +1311,6 @@ function ResourcePicker({
key={`${resource.kind}:${resource.id}`}
icon={RESOURCE_ICONS[resource.kind]}
label={resource.label}
- detail={resource.detail ?? RESOURCE_LABELS[resource.kind]}
disabled={disabled}
imageUrl={resource.imageUrl}
onSelect={() => add(resource)}
@@ -651,10 +1330,16 @@ function ResourcePicker({
function AttachmentPicker({
disabled,
+ remaining,
dispatch,
+ getInsertionOffset,
+ onPicked,
}: {
disabled: boolean;
+ remaining: number;
dispatch: React.Dispatch<ComposerAction>;
+ getInsertionOffset: () => number;
+ onPicked: (key: string) => void;
}) {
const input = useRef<HTMLInputElement>(null);
const addFiles = async (files: FileList | null) => {
@@ -662,7 +1347,16 @@ function AttachmentPicker({
dispatch({ type: "attachments.reading.started" });
try {
const attachments = await readFiles(files);
- dispatch({ type: "attachments.added", attachments });
+ const accepted = attachments.slice(0, remaining);
+ const lastAccepted = accepted.at(-1);
+ if (lastAccepted) {
+ dispatch({
+ type: "attachments.added",
+ attachments: accepted,
+ offset: getInsertionOffset(),
+ });
+ onPicked(attachmentContextKey(lastAccepted));
+ }
} catch {
toast.error("Those files could not be attached. Try again.");
} finally {
@@ -700,10 +1394,14 @@ function CommandPicker({
open,
disabled,
dispatch,
+ getInsertionOffset,
+ onPicked,
}: {
open: boolean;
disabled: boolean;
dispatch: React.Dispatch<ComposerAction>;
+ getInsertionOffset: () => number;
+ onPicked: (key: string) => void;
}) {
return (
<Popover
@@ -726,18 +1424,19 @@ function CommandPicker({
<PopoverContent size="fit" align="start" side="top" className="w-64 p-1">
<button
type="button"
- onClick={() => dispatch({ type: "command.selected" })}
- className="flex w-full items-center gap-3 rounded-sm px-3 py-2 text-left outline-none hover:bg-muted focus-visible:bg-muted"
+ onClick={() => {
+ dispatch({
+ type: "command.selected",
+ offset: getInsertionOffset(),
+ });
+ onPicked(COMMAND_CONTEXT_KEY);
+ }}
+ className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left outline-none hover:bg-muted focus-visible:bg-muted"
disabled={disabled}
>
<Icon icon={Application} className="size-4 text-muted-foreground" />
- <span>
- <span className="block font-medium text-xs">
- /{CREATE_AGENT_COMMAND.label}
- </span>
- <span className="block text-muted-foreground text-xs">
- {CREATE_AGENT_COMMAND.description}
- </span>
+ <span className="font-medium text-xs">
+ /{CREATE_AGENT_COMMAND.label}
</span>
</button>
</PopoverContent>
@@ -749,12 +1448,9 @@ function ResourceResultsSkeleton() {
return (
<div className="flex flex-col gap-1 px-3 py-2">
{["first", "second", "third"].map((item) => (
- <div key={item} className="flex h-10 items-center gap-3">
+ <div key={item} className="flex h-8 items-center gap-2">
<Skeleton className="size-6 shrink-0" />
- <div className="flex min-w-0 flex-1 flex-col gap-1.5">
- <Skeleton className="h-3 w-2/3" />
- <Skeleton className="h-2.5 w-1/3" />
- </div>
+ <Skeleton className="h-3 w-2/3" />
</div>
))}
</div>
@@ -768,24 +1464,15 @@ const RESOURCE_ICONS: Record<BuilderResource["kind"], CarbonIcon> = {
deal: Partnership,
};
-const RESOURCE_LABELS: Record<BuilderResource["kind"], string> = {
- integration: "Integration",
- company: "Company",
- contact: "Contact",
- deal: "Deal",
-};
-
function ResourceButton({
icon,
label,
- detail,
imageUrl,
disabled,
onSelect,
}: {
icon: CarbonIcon;
label: string;
- detail: string | null;
imageUrl?: string | null;
disabled: boolean;
onSelect: () => void;
@@ -795,17 +1482,18 @@ function ResourceButton({
type="button"
onClick={onSelect}
disabled={disabled}
- className="flex w-full items-center gap-3 rounded-sm px-3 py-2 text-left outline-none hover:bg-muted focus-visible:bg-muted"
+ className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left outline-none hover:bg-muted focus-visible:bg-muted"
>
<ChatReferenceIdentity
resource={{
kind: "integration",
id: label,
label,
- detail,
+ detail: null,
imageUrl,
}}
icon={icon}
+ showDetail={false}
/>
</button>
);
diff --git a/apps/app/components/agent-builder/chat-chips.tsx b/apps/app/components/agent-builder/chat-chips.tsx
index 8e7a1ba5..e583f120 100644
--- a/apps/app/components/agent-builder/chat-chips.tsx
+++ b/apps/app/components/agent-builder/chat-chips.tsx
@@ -10,8 +10,15 @@ import {
} from "@crm/ui/components/attachment";
import { Avatar, AvatarFallback, AvatarImage } from "@crm/ui/components/avatar";
import { type CarbonIcon, Icon } from "@crm/ui/components/icon";
+import {
+ TokenFieldAction,
+ TokenFieldItem,
+} from "@crm/ui/components/token-field";
+import { cn } from "@crm/ui/lib/utils";
import Image from "next/image";
+type ChatChipVariant = "default" | "composer";
+
export type ChatChipResource = {
kind: "integration" | "company" | "contact" | "deal";
id: string;
@@ -33,18 +40,41 @@ export function ChatReferenceChip({
resource,
icon,
onRemove,
+ variant = "default",
}: {
resource: ChatChipResource;
icon: CarbonIcon;
onRemove?: () => void;
+ variant?: ChatChipVariant;
}) {
+ const identity = (
+ <ChatReferenceIdentity
+ resource={resource}
+ icon={icon}
+ showDetail={false}
+ compact={variant === "composer"}
+ />
+ );
+
+ if (variant === "composer") {
+ return (
+ <TokenFieldItem>
+ {identity}
+ {onRemove ? (
+ <TokenFieldAction
+ aria-label={`Remove ${resource.label}`}
+ onClick={onRemove}
+ >
+ <Icon icon={Close} className="size-3" />
+ </TokenFieldAction>
+ ) : null}
+ </TokenFieldItem>
+ );
+ }
+
return (
<span className="flex min-w-0 max-w-full items-center gap-1 rounded-sm border bg-background py-0.5 pr-1 pl-0.5 text-left">
- <ChatReferenceIdentity
- resource={resource}
- icon={icon}
- showDetail={false}
- />
+ {identity}
{onRemove ? (
<button
type="button"
@@ -63,14 +93,16 @@ export function ChatReferenceIdentity({
resource,
icon,
showDetail = true,
+ compact = false,
}: {
resource: ChatChipResource;
icon: CarbonIcon;
showDetail?: boolean;
+ compact?: boolean;
}) {
return (
<>
- <Avatar size="sm">
+ <Avatar size={compact ? "xs" : "sm"}>
{resource.imageUrl ? (
<AvatarImage src={resource.imageUrl} alt="" />
) : null}
@@ -78,7 +110,7 @@ export function ChatReferenceIdentity({
<Icon icon={icon} className="size-3" />
</AvatarFallback>
</Avatar>
- <span className="min-w-0 max-w-48">
+ <span className={cn("min-w-0 max-w-48", compact && "max-w-40")}>
<span className="block truncate font-medium text-xs">
{resource.label}
</span>
@@ -95,9 +127,11 @@ export function ChatReferenceIdentity({
export function ChatAttachmentChip({
attachment,
onRemove,
+ variant = "default",
}: {
attachment: ChatChipAttachment;
onRemove?: () => void;
+ variant?: ChatChipVariant;
}) {
const label = `${attachment.name} · ${formatBytes(attachment.size)}`;
const image = isPreviewableImage(attachment.type)
@@ -108,7 +142,10 @@ export function ChatAttachmentChip({
: null;
return (
- <Attachment size="compact" state="done">
+ <Attachment
+ size={variant === "composer" ? "token" : "compact"}
+ state="done"
+ >
<AttachmentMedia variant={image ? "image" : "icon"}>
{image ? (
<Image
@@ -145,11 +182,27 @@ export function ChatCommandChip({
label,
icon,
onRemove,
+ variant = "default",
}: {
label: string;
icon: CarbonIcon;
onRemove?: () => void;
+ variant?: ChatChipVariant;
}) {
+ if (variant === "composer") {
+ return (
+ <TokenFieldItem className="pl-1.5">
+ <Icon icon={icon} className="size-3.5" />
+ <span className="font-medium">{label}</span>
+ {onRemove ? (
+ <TokenFieldAction aria-label={`Remove ${label}`} onClick={onRemove}>
+ <Icon icon={Close} className="size-3" />
+ </TokenFieldAction>
+ ) : null}
+ </TokenFieldItem>
+ );
+ }
+
return (
<span className="flex h-7 items-center gap-1.5 rounded-md bg-primary px-2 text-primary-foreground text-xs">
<Icon icon={icon} className="size-3.5" />
diff --git a/packages/ui/src/components/attachment.tsx b/packages/ui/src/components/attachment.tsx
index ca592560..fd7edbcf 100644
--- a/packages/ui/src/components/attachment.tsx
+++ b/packages/ui/src/components/attachment.tsx
@@ -16,6 +16,8 @@ const attachmentVariants = cva(
xs: "gap-1.5 rounded-sm text-xs has-data-[slot=attachment-content]:px-1.5 has-data-[slot=attachment-content]:py-1 has-data-[slot=attachment-media]:p-1",
compact:
"gap-1 rounded-sm text-xs has-data-[slot=attachment-content]:px-1.5 has-data-[slot=attachment-content]:py-0.5 has-data-[slot=attachment-media]:p-0.5",
+ token:
+ "gap-1 rounded-lg border-0 bg-tag text-tag-foreground text-xs has-data-[slot=attachment-content]:px-1 has-data-[slot=attachment-content]:py-0.5 has-data-[slot=attachment-media]:p-0.5",
},
orientation: {
horizontal: "min-w-40 items-center",
@@ -28,6 +30,11 @@ const attachmentVariants = cva(
orientation: "horizontal",
className: "min-w-0",
},
+ {
+ size: "token",
+ orientation: "horizontal",
+ className: "min-w-0",
+ },
],
}
)
@@ -55,7 +62,7 @@ function Attachment({
}
const attachmentMediaVariants = cva(
- "relative flex aspect-square w-10 shrink-0 items-center justify-center overflow-hidden rounded-none bg-muted text-foreground group-data-[orientation=vertical]/attachment:w-full group-data-[size=sm]/attachment:w-8 group-data-[size=xs]/attachment:w-7 group-data-[size=compact]/attachment:w-5 group-data-[size=xs]/attachment:rounded-none group-data-[size=compact]/attachment:rounded-none group-data-[state=error]/attachment:bg-destructive/10 group-data-[state=error]/attachment:text-destructive group-data-[orientation=vertical]/attachment:*:data-[slot=spinner]:size-6! [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 group-data-[orientation=vertical]/attachment:[&_svg:not([class*='size-'])]:size-6 group-data-[size=xs]/attachment:[&_svg:not([class*='size-'])]:size-3.5 group-data-[size=compact]/attachment:[&_svg:not([class*='size-'])]:size-3",
+ "relative flex aspect-square w-10 shrink-0 items-center justify-center overflow-hidden rounded-none bg-muted text-foreground group-data-[orientation=vertical]/attachment:w-full group-data-[size=sm]/attachment:w-8 group-data-[size=xs]/attachment:w-7 group-data-[size=compact]/attachment:w-5 group-data-[size=token]/attachment:w-5 group-data-[size=xs]/attachment:rounded-none group-data-[size=compact]/attachment:rounded-none group-data-[size=token]/attachment:rounded-md group-data-[state=error]/attachment:bg-destructive/10 group-data-[state=error]/attachment:text-destructive group-data-[orientation=vertical]/attachment:*:data-[slot=spinner]:size-6! [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 group-data-[orientation=vertical]/attachment:[&_svg:not([class*='size-'])]:size-6 group-data-[size=xs]/attachment:[&_svg:not([class*='size-'])]:size-3.5 group-data-[size=compact]/attachment:[&_svg:not([class*='size-'])]:size-3 group-data-[size=token]/attachment:[&_svg:not([class*='size-'])]:size-3",
{
variants: {
variant: {
@@ -161,7 +168,10 @@ function AttachmentAction({
data-slot="attachment-action"
variant={variant ?? "ghost"}
size={size}
- className={cn(className)}
+ className={cn(
+ "group-data-[size=token]/attachment:size-5 group-data-[size=token]/attachment:rounded-lg",
+ className
+ )}
{...props}
/>
)
diff --git a/packages/ui/src/components/avatar.tsx b/packages/ui/src/components/avatar.tsx
index eaa0ca85..31f89d71 100644
--- a/packages/ui/src/components/avatar.tsx
+++ b/packages/ui/src/components/avatar.tsx
@@ -9,14 +9,14 @@ function Avatar({
size = "default",
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
- size?: "default" | "sm" | "lg";
+ size?: "default" | "xs" | "sm" | "lg";
}) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
data-size={size}
className={cn(
- "group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
+ "group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 data-[size=xs]:size-5 dark:after:mix-blend-lighten",
className,
)}
{...props}
@@ -50,7 +50,7 @@ function AvatarFallback({
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
- "flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
+ "flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs group-data-[size=xs]/avatar:text-[10px]",
className,
)}
{...props}
diff --git a/packages/ui/src/components/token-field.tsx b/packages/ui/src/components/token-field.tsx
new file mode 100644
index 00000000..34b2c74e
--- /dev/null
+++ b/packages/ui/src/components/token-field.tsx
@@ -0,0 +1,50 @@
+import { Button } from "@crm/ui/components/button";
+import { cn } from "@crm/ui/lib/utils";
+import type * as React from "react";
+
+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)] aria-disabled:cursor-not-allowed aria-disabled:opacity-60 sm:text-[15px] md:text-xs [&>[contenteditable]]:outline-none",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function TokenFieldItem({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="token-field-item"
+ 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,
+ )}
+ {...props}
+ />
+ );
+}
+
+function TokenFieldAction({
+ className,
+ ...props
+}: React.ComponentProps<typeof Button>) {
+ return (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className={cn("size-5 rounded-lg", className)}
+ {...props}
+ />
+ );
+}
+
+export { TokenField, TokenFieldAction, TokenFieldItem };
diff --git a/packages/ui/src/styles/globals.css b/packages/ui/src/styles/globals.css
index ddfd85b8..173dc527 100644
--- a/packages/ui/src/styles/globals.css
+++ b/packages/ui/src/styles/globals.css
@@ -21,6 +21,8 @@
--muted-foreground: #6b6b6b;
--accent: #f4f4f4;
--accent-foreground: #171717;
+ --tag: #ffffff;
+ --tag-foreground: #171717;
--destructive: #ae2e24;
--destructive-foreground: #ffffff;
--success: oklch(0.55 0.13 150);
@@ -88,6 +90,8 @@
--muted-foreground: #a0a0a0;
--accent: #292929;
--accent-foreground: #f5f5f5;
+ --tag: #292929;
+ --tag-foreground: #f5f5f5;
--destructive: #ae2e24;
--destructive-foreground: #ffffff;
--success: oklch(0.72 0.16 155);
@@ -153,6 +157,8 @@
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
+ --color-tag: var(--tag);
+ --color-tag-foreground: var(--tag-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-success: var(--success);