devnonla-ui 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,35 @@
1
- import { type KeyboardEvent as ReactKeyboardEvent, type ReactNode, useEffect, useLayoutEffect, useRef, useState } from "react";
1
+ import { memo, type ReactNode, type Ref, useCallback, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
2
2
  import { Icon } from "../../icon/Icon";
3
3
  import { cn } from "../../lib/cn";
4
- import { glassSurfaceClass } from "../../lib/surface";
4
+ import { glassOverlayClass, glassSurfaceClass } from "../../lib/surface";
5
+ import { ChatSuggestProvider, type ChatTrigger, chatTokenAt } from "./ChatSuggestions";
6
+ import { type ComposerCaret, type ComposerPart, emptyComposer, insertChipAt, insertCommandAt, insertTextAt, isComposerEmpty, normalizeParts, removeCommandPart, serializeComposer } from "./commandChips";
7
+
8
+ /** A chip the app adds from code, e.g. a text selection used as context. */
9
+ export type ChatChip = {
10
+ /** Text shown inside the chip. Keep it short, e.g. `notes.md:L1-L4`. */
11
+ label: string;
12
+ /** Token sent in the message, e.g. `@selection-1`. No spaces. */
13
+ value: string;
14
+ /** Full text shown in the native tooltip on hover, e.g. the whole selection. */
15
+ title?: string;
16
+ /** Chip background as hex, e.g. `#6366f1`. Defaults to neutral gray `#71717a`. */
17
+ color?: string;
18
+ };
19
+
20
+ /** Imperative handle for `ChatInput`. Pass it with `inputRef`. */
21
+ export type ChatInputHandle = {
22
+ /** Insert a chip at the caret, or where the caret last was. Focuses the composer. */
23
+ insertChip: (chip: ChatChip) => void;
24
+ /** Move focus into the composer. */
25
+ focus: () => void;
26
+ /** Empty the composer. */
27
+ clear: () => void;
28
+ };
5
29
 
6
30
  export type ChatInputProps = {
31
+ /** Imperative handle, e.g. to insert a chip from a text selection. */
32
+ inputRef?: Ref<ChatInputHandle>;
7
33
  generating?: boolean;
8
34
  placeholder?: string;
9
35
  disabled?: boolean;
@@ -13,6 +39,8 @@ export type ChatInputProps = {
13
39
  onClear?: () => void;
14
40
  /** Left-side toolbar (model picker, tools, …). */
15
41
  toolbar?: ReactNode;
42
+ /** Markers that open a menu, e.g. `/` for commands and `@` for mentions. Each menu gets `useChatSuggest` for the live query. */
43
+ triggers?: ChatTrigger[];
16
44
  defaultValue?: string;
17
45
  className?: string;
18
46
  autoFocus?: boolean;
@@ -22,19 +50,6 @@ export type ChatInputProps = {
22
50
  enableTypeToFocus?: boolean;
23
51
  };
24
52
 
25
- function resize(el: HTMLTextAreaElement | null, maxRows = 10) {
26
- if (!el) return;
27
- // Collapse first — `height: auto` can keep a stretched/flex height so scrollHeight
28
- // stays inflated until a later text change remeasures.
29
- el.style.height = "0px";
30
- const styles = getComputedStyle(el);
31
- const line = Number.parseFloat(styles.lineHeight) || 22;
32
- const padY = (Number.parseFloat(styles.paddingTop) || 0) + (Number.parseFloat(styles.paddingBottom) || 0);
33
- const min = line + padY;
34
- const max = line * maxRows + padY;
35
- el.style.height = `${Math.min(Math.max(el.scrollHeight, min), max)}px`;
36
- }
37
-
38
53
  function isEditableTarget(el: EventTarget | null): boolean {
39
54
  if (!(el instanceof HTMLElement)) return false;
40
55
  const tag = el.tagName;
@@ -42,40 +57,228 @@ function isEditableTarget(el: EventTarget | null): boolean {
42
57
  return Boolean(el.closest("input, textarea, select, [contenteditable], [role='dialog'], [role='alertdialog'], [role='listbox'], [role='menu'], .monaco-editor"));
43
58
  }
44
59
 
45
- export function ChatInput({ generating = false, placeholder = "Message…", disabled = false, onSend, onCancel, onClear, toolbar, defaultValue = "", className, autoFocus = false, focusSignal, enableTypeToFocus = false }: ChatInputProps) {
46
- const [text, setText] = useState(defaultValue);
47
- const textareaRef = useRef<HTMLTextAreaElement>(null);
48
- const hasText = text.trim().length > 0;
49
- const canSend = !generating && !disabled && hasText;
60
+ function readComposer(root: HTMLElement): { parts: ComposerPart[]; caret: ComposerCaret } {
61
+ const sel = window.getSelection();
62
+ const drafts: ComposerPart[] = [];
63
+ let caretIndex = 0;
64
+ let caretOffset = 0;
65
+ let sawCaret = false;
50
66
 
51
- useLayoutEffect(() => {
52
- resize(textareaRef.current);
53
- }, [text]);
67
+ const mark = (index: number, offset: number) => {
68
+ if (sawCaret) return;
69
+ caretIndex = index;
70
+ caretOffset = offset;
71
+ sawCaret = true;
72
+ };
54
73
 
55
- // Remeasure when the composer width settles (first paint / panel resize).
56
- useEffect(() => {
57
- const el = textareaRef.current;
58
- const parent = el?.parentElement;
59
- if (!el || !parent) return;
60
- const ro = new ResizeObserver(() => resize(el));
61
- ro.observe(parent);
62
- return () => ro.disconnect();
63
- }, []);
74
+ const appendText = (value: string, node: Node | null) => {
75
+ const text = value.replace(/\u200b/g, "");
76
+ const last = drafts[drafts.length - 1];
77
+ let index: number;
78
+ let base: number;
79
+ if (last?.type === "text") {
80
+ base = last.value.length;
81
+ last.value += text;
82
+ index = drafts.length - 1;
83
+ } else {
84
+ base = 0;
85
+ drafts.push({ type: "text", id: "tmp", value: text });
86
+ index = drafts.length - 1;
87
+ }
88
+ if (node && sel?.anchorNode === node) {
89
+ const raw = (node.textContent ?? "").slice(0, sel.anchorOffset).replace(/\u200b/g, "");
90
+ mark(index, base + raw.length);
91
+ }
92
+ };
93
+
94
+ const walk = (node: Node) => {
95
+ if (node.nodeType === Node.TEXT_NODE) {
96
+ appendText(node.textContent ?? "", node);
97
+ return;
98
+ }
99
+ if (!(node instanceof HTMLElement)) return;
100
+ if (node.dataset.command) {
101
+ drafts.push({
102
+ type: "command",
103
+ id: node.dataset.seg || `cmd-${drafts.length}`,
104
+ label: node.dataset.label || node.dataset.command,
105
+ value: node.dataset.command,
106
+ title: node.dataset.title || undefined,
107
+ color: node.dataset.color || undefined,
108
+ });
109
+ if (sel?.anchorNode && node.contains(sel.anchorNode)) {
110
+ drafts.push({ type: "text", id: "tmp", value: "" });
111
+ mark(drafts.length - 1, 0);
112
+ }
113
+ return;
114
+ }
115
+ if (node.tagName === "BR") {
116
+ appendText("\n", node);
117
+ return;
118
+ }
119
+ if (node.childNodes.length === 0) {
120
+ appendText("", sel?.anchorNode === node ? node : null);
121
+ return;
122
+ }
123
+ for (const child of node.childNodes) walk(child);
124
+ };
125
+
126
+ for (const child of root.childNodes) walk(child);
127
+ if (!sawCaret) {
128
+ const last = drafts[drafts.length - 1];
129
+ if (!last || last.type !== "text") drafts.push({ type: "text", id: "tmp", value: "" });
130
+ const tail = drafts[drafts.length - 1];
131
+ caretIndex = drafts.length - 1;
132
+ caretOffset = tail?.type === "text" ? tail.value.length : 0;
133
+ }
134
+ const normalized = normalizeParts(drafts, { index: caretIndex, offset: caretOffset });
135
+ return { parts: normalized.parts, caret: normalized.caret ?? { index: 0, offset: 0 } };
136
+ }
137
+
138
+ function chipBesideCaret(root: HTMLElement, side: "before" | "after"): string | null {
139
+ const sel = window.getSelection();
140
+ if (!sel?.isCollapsed || !sel.anchorNode || !root.contains(sel.anchorNode)) return null;
141
+ const node = sel.anchorNode;
142
+ const offset = sel.anchorOffset;
143
+ if (node.nodeType === Node.TEXT_NODE) {
144
+ const raw = (node.textContent ?? "").replace(/\u200b/g, "");
145
+ const cut = (node.textContent ?? "").slice(0, offset).replace(/\u200b/g, "").length;
146
+ const blocked = side === "before" ? cut > 0 : cut < raw.length;
147
+ if (blocked) return null;
148
+ const parent = node.parentElement;
149
+ const sibling = side === "before" ? (parent?.dataset.seg ? parent.previousElementSibling : node.previousSibling) : parent?.dataset.seg ? parent.nextElementSibling : node.nextSibling;
150
+ return sibling instanceof HTMLElement && sibling.dataset.command ? (sibling.dataset.seg ?? null) : null;
151
+ }
152
+ if (node instanceof HTMLElement) {
153
+ const sibling = node.childNodes[side === "before" ? offset - 1 : offset];
154
+ return sibling instanceof HTMLElement && sibling.dataset.command ? (sibling.dataset.seg ?? null) : null;
155
+ }
156
+ return null;
157
+ }
158
+
159
+ const DEFAULT_CHIP_COLOR = "#c9841a";
160
+ const NEUTRAL_CHIP_COLOR = "#71717a";
161
+ const HEX_COLOR = /^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
162
+
163
+ const chipClass = "mx-px inline max-w-full truncate rounded-[4px] px-1 align-middle text-xs leading-4 text-white";
164
+
165
+ function paintComposer(root: HTMLElement, parts: readonly ComposerPart[]) {
166
+ const frag = document.createDocumentFragment();
167
+ for (const part of parts) {
168
+ const span = document.createElement("span");
169
+ span.dataset.seg = part.id;
170
+ if (part.type === "text") {
171
+ span.textContent = part.value === "" ? "\u200b" : part.value;
172
+ } else {
173
+ span.dataset.command = part.value;
174
+ span.dataset.label = part.label;
175
+ if (part.title) {
176
+ span.dataset.title = part.title;
177
+ span.title = part.title;
178
+ }
179
+ const color = part.color && HEX_COLOR.test(part.color) ? part.color : DEFAULT_CHIP_COLOR;
180
+ span.dataset.color = color;
181
+ span.contentEditable = "false";
182
+ span.className = chipClass;
183
+ span.style.backgroundColor = color;
184
+ span.textContent = part.label;
185
+ }
186
+ frag.append(span);
187
+ }
188
+ root.replaceChildren(frag);
189
+ }
190
+
191
+ function placeCaret(root: HTMLElement, parts: readonly ComposerPart[], caret: ComposerCaret) {
192
+ const part = parts[caret.index];
193
+ if (!part || part.type !== "text") return;
194
+ const span = root.querySelector(`[data-seg="${part.id}"]`);
195
+ const node = span?.firstChild;
196
+ if (!node || node.nodeType !== Node.TEXT_NODE) return;
197
+ const point = part.value === "" ? 0 : Math.min(caret.offset, node.textContent?.length ?? 0);
198
+ const range = document.createRange();
199
+ range.setStart(node, point);
200
+ range.collapse(true);
201
+ const sel = window.getSelection();
202
+ sel?.removeAllRanges();
203
+ sel?.addRange(range);
204
+ }
205
+
206
+ const ComposerEditor = memo(function ComposerEditor({ editorRef }: { editorRef: { current: HTMLDivElement | null } }) {
207
+ return <div ref={editorRef} data-chat-input contentEditable="true" suppressContentEditableWarning role="combobox" tabIndex={0} aria-expanded="false" aria-autocomplete="list" className="min-h-[22px] whitespace-pre-wrap wrap-break-word text-sm font-normal text-foreground outline-none" />;
208
+ });
209
+
210
+ export function ChatInput({ inputRef, generating = false, placeholder = "Message…", disabled = false, onSend, onCancel, onClear, toolbar, triggers = [], defaultValue = "", className, autoFocus = false, focusSignal, enableTypeToFocus = false }: ChatInputProps) {
211
+ const initial = emptyComposer(defaultValue);
212
+ const [parts, setParts] = useState<ComposerPart[]>(initial.parts);
213
+ const [caret, setCaret] = useState<ComposerCaret>(initial.caret);
214
+ const [focused, setFocused] = useState(false);
215
+ const [activeOptionId, setActiveOptionId] = useState<string | null>(null);
216
+ const [dismissedKey, setDismissedKey] = useState<string | null>(null);
217
+ const optionsRef = useRef<{ id: string; value: string; label?: string }[]>([]);
218
+ const editorRef = useRef<HTMLDivElement>(null);
219
+ const partsRef = useRef(parts);
220
+ const caretRef = useRef(caret);
221
+ const pendingCaret = useRef(false);
222
+ const composing = useRef(false);
223
+ const chipSeq = useRef(0);
224
+ const listId = useId();
225
+ const lockedRef = useRef(false);
226
+ partsRef.current = parts;
227
+ caretRef.current = caret;
228
+ lockedRef.current = generating || disabled;
229
+
230
+ const locked = generating || disabled;
231
+ const canSend = !locked && !isComposerEmpty(parts);
232
+
233
+ const triggerMarkers = useMemo(() => triggers.filter((item) => item.menu != null && item.menu !== false && item.trigger !== "").map((item) => item.trigger), [triggers]);
234
+
235
+ const textPart = parts[caret.index];
236
+ const token = !locked && focused && textPart?.type === "text" ? chatTokenAt(textPart.value, caret.offset, triggerMarkers) : null;
237
+ const tokenKey = token ? `${caret.index}:${token.start}:${token.trigger}:${token.query}` : null;
238
+ const activeTrigger = token ? triggers.find((item) => item.trigger === token.trigger) : undefined;
239
+ const suggestSlot = activeTrigger?.menu ?? null;
240
+ const menuOpen = Boolean(token && suggestSlot != null && suggestSlot !== false && tokenKey !== dismissedKey);
241
+
242
+ const [prevTokenKey, setPrevTokenKey] = useState(tokenKey);
243
+ if (tokenKey !== prevTokenKey) {
244
+ setPrevTokenKey(tokenKey);
245
+ setActiveOptionId(null);
246
+ }
247
+
248
+ const commit = (nextParts: ComposerPart[], nextCaret: ComposerCaret) => {
249
+ pendingCaret.current = true;
250
+ caretRef.current = nextCaret;
251
+ partsRef.current = nextParts;
252
+ setParts(nextParts);
253
+ setCaret(nextCaret);
254
+ };
255
+
256
+ useLayoutEffect(() => {
257
+ const root = editorRef.current;
258
+ if (!root) return;
259
+ paintComposer(root, parts);
260
+ if (!pendingCaret.current) return;
261
+ pendingCaret.current = false;
262
+ root.focus();
263
+ placeCaret(root, parts, caretRef.current);
264
+ }, [parts]);
64
265
 
65
266
  useEffect(() => {
66
267
  const onSignal = focusSignal !== undefined;
67
268
  if (!autoFocus && !onSignal) return;
68
- if (onSignal) setText("");
69
-
269
+ if (onSignal) {
270
+ const cleared = emptyComposer();
271
+ commit(cleared.parts, cleared.caret);
272
+ }
70
273
  let tries = 0;
71
274
  let timer = 0;
72
275
  const tryFocus = () => {
73
- const ta = textareaRef.current;
74
- if (!ta || ta.disabled) {
276
+ const root = editorRef.current;
277
+ if (!root || lockedRef.current) {
75
278
  if (tries++ < 20) timer = window.setTimeout(tryFocus, 40);
76
279
  return;
77
280
  }
78
- ta.focus({ preventScroll: true });
281
+ root.focus({ preventScroll: true });
79
282
  };
80
283
  timer = window.setTimeout(tryFocus, 0);
81
284
  return () => clearTimeout(timer);
@@ -85,89 +288,260 @@ export function ChatInput({ generating = false, placeholder = "Message…", disa
85
288
  if (!enableTypeToFocus) return;
86
289
 
87
290
  const onKeyDown = (e: globalThis.KeyboardEvent) => {
88
- if (e.defaultPrevented || e.isComposing) return;
291
+ if (e.defaultPrevented || e.isComposing || composing.current) return;
89
292
  if (e.metaKey || e.ctrlKey || e.altKey) return;
90
293
  if (e.key.length !== 1) return;
91
294
 
92
- const ta = textareaRef.current;
93
- if (!ta || ta.disabled || document.activeElement === ta) return;
295
+ const root = editorRef.current;
296
+ if (!root || locked || document.activeElement === root || root.contains(document.activeElement)) return;
94
297
  if (isEditableTarget(e.target) || isEditableTarget(document.activeElement)) return;
95
298
 
96
299
  e.preventDefault();
97
- ta.focus();
98
- const start = ta.selectionStart ?? ta.value.length;
99
- const end = ta.selectionEnd ?? ta.value.length;
100
- const next = ta.value.slice(0, start) + e.key + ta.value.slice(end);
101
- setText(next);
102
- requestAnimationFrame(() => {
103
- const nextTa = textareaRef.current;
104
- if (!nextTa) return;
105
- nextTa.selectionStart = nextTa.selectionEnd = start + e.key.length;
106
- });
300
+ const current = partsRef.current;
301
+ const last = current.length - 1;
302
+ const end = current[last];
303
+ const at = end?.type === "text" ? { index: last, offset: end.value.length } : { index: 0, offset: 0 };
304
+ const placed = insertTextAt(current, at, e.key);
305
+ commit(placed.parts, placed.caret);
107
306
  };
108
307
 
109
308
  window.addEventListener("keydown", onKeyDown);
110
309
  return () => window.removeEventListener("keydown", onKeyDown);
111
- }, [enableTypeToFocus]);
310
+ }, [enableTypeToFocus, locked]);
311
+
312
+ const syncFromDom = () => {
313
+ const root = editorRef.current;
314
+ if (!root || composing.current) return;
315
+ const read = readComposer(root);
316
+ commit(read.parts, read.caret);
317
+ };
318
+
319
+ const refreshCaret = () => {
320
+ const root = editorRef.current;
321
+ if (!root || composing.current) return;
322
+ const read = readComposer(root);
323
+ const same = serializeComposer(read.parts) === serializeComposer(partsRef.current) && read.parts.filter((part) => part.type === "command").length === partsRef.current.filter((part) => part.type === "command").length;
324
+ if (!same) {
325
+ commit(read.parts, read.caret);
326
+ return;
327
+ }
328
+ caretRef.current = read.caret;
329
+ setCaret(read.caret);
330
+ };
331
+
332
+ useImperativeHandle(
333
+ inputRef,
334
+ () => ({
335
+ insertChip: (chip) => {
336
+ const value = chip.value.trim();
337
+ if (!value) return;
338
+ const label = chip.label.trim() || value;
339
+ const title = chip.title?.trim() || undefined;
340
+ const color = chip.color ?? NEUTRAL_CHIP_COLOR;
341
+ const placed = insertChipAt(partsRef.current, caretRef.current, { id: `cmd-${++chipSeq.current}`, label, value, title, color });
342
+ commit(placed.parts, placed.caret);
343
+ },
344
+ focus: () => editorRef.current?.focus(),
345
+ clear: () => {
346
+ const cleared = emptyComposer();
347
+ commit(cleared.parts, cleared.caret);
348
+ },
349
+ }),
350
+ [],
351
+ );
112
352
 
113
353
  const handleSend = () => {
114
354
  if (!canSend) return;
115
- onSend(text.trim());
116
- setText("");
355
+ onSend(serializeComposer(parts).trim());
356
+ const cleared = emptyComposer();
357
+ commit(cleared.parts, cleared.caret);
358
+ };
359
+
360
+ const pickSuggestion = (value: string, label?: string) => {
361
+ if (!token || textPart?.type !== "text") return;
362
+ const raw = value.trim();
363
+ if (!raw) return;
364
+ const placed = insertCommandAt(parts, caret, token.start, token.end, {
365
+ id: `cmd-${++chipSeq.current}`,
366
+ label: label?.trim() || raw,
367
+ value: raw,
368
+ color: activeTrigger?.color,
369
+ });
370
+ setDismissedKey(null);
371
+ commit(placed.parts, placed.caret);
117
372
  };
118
373
 
119
- const handleKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => {
120
- if (e.nativeEvent.isComposing) return;
374
+ const registerOption = useCallback((id: string, option: { value: string; label?: string }) => {
375
+ optionsRef.current = [...optionsRef.current.filter((item) => item.id !== id), { id, ...option }];
376
+ setActiveOptionId((current) => (current && optionsRef.current.some((item) => item.id === current) ? current : (optionsRef.current[0]?.id ?? null)));
377
+ return () => {
378
+ optionsRef.current = optionsRef.current.filter((item) => item.id !== id);
379
+ setActiveOptionId((current) => (current === id ? (optionsRef.current[0]?.id ?? null) : current));
380
+ };
381
+ }, []);
382
+
383
+ const suggestValue = token
384
+ ? {
385
+ query: token.query,
386
+ trigger: token.trigger,
387
+ insert: pickSuggestion,
388
+ close: () => setDismissedKey(tokenKey),
389
+ activeId: activeOptionId,
390
+ register: registerOption,
391
+ highlight: setActiveOptionId,
392
+ }
393
+ : null;
394
+
395
+ const handleKeyDown = (e: KeyboardEvent) => {
396
+ if (e.isComposing || composing.current) return;
397
+ if (menuOpen) {
398
+ const options = optionsRef.current;
399
+ const currentIndex = options.findIndex((item) => item.id === activeOptionId);
400
+ if (e.key === "ArrowDown" && options.length > 0) {
401
+ e.preventDefault();
402
+ setActiveOptionId(options[(currentIndex + 1) % options.length]?.id ?? null);
403
+ return;
404
+ }
405
+ if (e.key === "ArrowUp" && options.length > 0) {
406
+ e.preventDefault();
407
+ setActiveOptionId(options[(currentIndex - 1 + options.length) % options.length]?.id ?? null);
408
+ return;
409
+ }
410
+ if (e.key === "Escape") {
411
+ e.preventDefault();
412
+ setDismissedKey(tokenKey);
413
+ return;
414
+ }
415
+ if (((e.key === "Enter" && !e.shiftKey) || e.key === "Tab") && options.length > 0) {
416
+ e.preventDefault();
417
+ const item = options.find((option) => option.id === activeOptionId) ?? options[0];
418
+ if (item) pickSuggestion(item.value, item.label);
419
+ return;
420
+ }
421
+ }
422
+ const root = editorRef.current;
423
+ const chipId = root && (e.key === "Backspace" || e.key === "Delete") ? chipBesideCaret(root, e.key === "Backspace" ? "before" : "after") : null;
424
+ if (chipId) {
425
+ e.preventDefault();
426
+ const placed = removeCommandPart(partsRef.current, chipId);
427
+ commit(placed.parts, placed.caret);
428
+ return;
429
+ }
121
430
  if (e.key === "Enter" && !e.shiftKey) {
122
431
  e.preventDefault();
123
432
  handleSend();
433
+ return;
434
+ }
435
+ if (e.key === "Enter" && e.shiftKey) {
436
+ e.preventDefault();
437
+ const placed = insertTextAt(partsRef.current, caretRef.current, "\n");
438
+ commit(placed.parts, placed.caret);
124
439
  }
125
440
  };
126
441
 
442
+ const activeId = menuOpen ? activeOptionId : undefined;
443
+ const handlers = useRef({ syncFromDom, refreshCaret, handleKeyDown });
444
+ handlers.current = { syncFromDom, refreshCaret, handleKeyDown };
445
+
446
+ useEffect(() => {
447
+ const root = editorRef.current;
448
+ if (!root) return;
449
+ const onKeyDown = (e: KeyboardEvent) => handlers.current.handleKeyDown(e);
450
+ const onInput = () => handlers.current.syncFromDom();
451
+ const onCaret = () => handlers.current.refreshCaret();
452
+ const onPaste = (e: ClipboardEvent) => {
453
+ e.preventDefault();
454
+ const text = e.clipboardData?.getData("text/plain") ?? "";
455
+ if (!text) return;
456
+ const placed = insertTextAt(partsRef.current, caretRef.current, text);
457
+ commit(placed.parts, placed.caret);
458
+ };
459
+ const onCompositionStart = () => {
460
+ composing.current = true;
461
+ };
462
+ const onCompositionEnd = () => {
463
+ composing.current = false;
464
+ handlers.current.syncFromDom();
465
+ };
466
+ const onFocus = () => setFocused(true);
467
+ const onBlur = () => setFocused(false);
468
+ root.addEventListener("keydown", onKeyDown);
469
+ root.addEventListener("input", onInput);
470
+ root.addEventListener("keyup", onCaret);
471
+ root.addEventListener("mouseup", onCaret);
472
+ root.addEventListener("paste", onPaste);
473
+ root.addEventListener("compositionstart", onCompositionStart);
474
+ root.addEventListener("compositionend", onCompositionEnd);
475
+ root.addEventListener("focus", onFocus);
476
+ root.addEventListener("blur", onBlur);
477
+ return () => {
478
+ root.removeEventListener("keydown", onKeyDown);
479
+ root.removeEventListener("input", onInput);
480
+ root.removeEventListener("keyup", onCaret);
481
+ root.removeEventListener("mouseup", onCaret);
482
+ root.removeEventListener("paste", onPaste);
483
+ root.removeEventListener("compositionstart", onCompositionStart);
484
+ root.removeEventListener("compositionend", onCompositionEnd);
485
+ root.removeEventListener("focus", onFocus);
486
+ root.removeEventListener("blur", onBlur);
487
+ };
488
+ }, []);
489
+
490
+ useEffect(() => {
491
+ const root = editorRef.current;
492
+ if (!root) return;
493
+ root.contentEditable = locked ? "false" : "true";
494
+ root.setAttribute("aria-expanded", menuOpen ? "true" : "false");
495
+ if (menuOpen) root.setAttribute("aria-controls", listId);
496
+ else root.removeAttribute("aria-controls");
497
+ if (activeId) root.setAttribute("aria-activedescendant", `chat-suggest-${activeId}`);
498
+ else root.removeAttribute("aria-activedescendant");
499
+ }, [locked, menuOpen, listId, activeId]);
500
+
127
501
  return (
128
- <div className={cn(glassSurfaceClass, "nonla-chat-input relative isolate mx-4 mb-2.5 flex shrink-0 flex-col overflow-hidden rounded-xl border-(--nonla-input) bg-muted-strong pt-1 [.light:not(.dark)_&]:bg-background [.light:not(.dark)_&]:shadow-none [.light_.nonla-ui:not(.dark)_&]:bg-background [.light_.nonla-ui:not(.dark)_&]:shadow-none", disabled && "opacity-70", className)}>
129
- <textarea
130
- ref={textareaRef}
131
- data-chat-input
132
- value={text}
133
- onChange={(e) => setText(e.target.value)}
134
- onKeyDown={handleKeyDown}
135
- disabled={generating || disabled}
136
- placeholder={placeholder}
137
- rows={1}
138
- className={cn(
139
- "w-full resize-none appearance-none border-0 bg-transparent shadow-none outline-none focus:outline-none px-2.5 pt-1 pb-2.5",
140
- "text-sm font-normal",
141
- disabled ? "text-muted-foreground cursor-not-allowed placeholder:text-quaternary-foreground" : "text-foreground placeholder:text-quaternary-foreground",
142
- )}
143
- />
144
-
145
- <div className="flex items-center gap-1.5 pb-2 px-2">
146
- {onClear ? (
147
- <button type="button" onClick={onClear} title="Clear chat" aria-label="Clear chat" className="inline-flex size-6 shrink-0 items-center justify-center rounded-lg border-0 bg-transparent cursor-pointer hover:bg-ink-hover">
148
- <Icon name="eraser" size={14} />
149
- </button>
150
- ) : null}
151
- {toolbar}
152
- <div className="flex-1" />
153
-
154
- {generating ? (
155
- <button type="button" onClick={onCancel} title="Stop" className="w-6 h-6 rounded-full bg-brand text-(--nonla-text-on-solid) flex items-center justify-center shrink-0 cursor-pointer hover:bg-brand/90 active:scale-95 transition-all duration-100 border-0">
156
- <Icon name="stop" size={12} />
157
- <span className="sr-only">Stop</span>
158
- </button>
159
- ) : (
160
- <button
161
- type="button"
162
- disabled={!canSend}
163
- onClick={handleSend}
164
- title="Send (Enter)"
165
- className={cn("w-6 h-6 rounded-full flex items-center justify-center shrink-0 transition-all duration-100 border-0", canSend ? "bg-foreground text-background cursor-pointer" : "bg-border text-muted-foreground cursor-not-allowed opacity-50")}
166
- >
167
- <Icon name="arrow-up" size={14} />
168
- <span className="sr-only">Send</span>
169
- </button>
170
- )}
502
+ <div className={cn("nonla-chat-input relative mx-4 mb-2.5", className)}>
503
+ {menuOpen && token && suggestValue ? (
504
+ <ChatSuggestProvider value={suggestValue}>
505
+ <div id={listId} role="listbox" aria-label="Suggestions" data-state="open" data-side="top" onMouseDown={(e) => e.preventDefault()} className={cn(glassOverlayClass, "absolute bottom-full left-0 right-0 z-20 mb-1.5 max-h-56 overflow-y-auto p-1 empty:hidden")}>
506
+ {suggestSlot}
507
+ </div>
508
+ </ChatSuggestProvider>
509
+ ) : null}
510
+ <div className={cn(glassSurfaceClass, "relative isolate flex shrink-0 flex-col overflow-hidden rounded-xl border-(--nonla-input) bg-muted-strong pt-1 [.light:not(.dark)_&]:bg-background [.light:not(.dark)_&]:shadow-none [.light_.nonla-ui:not(.dark)_&]:bg-background [.light_.nonla-ui:not(.dark)_&]:shadow-none", disabled && "opacity-70")}>
511
+ <div className="relative">
512
+ {isComposerEmpty(parts) ? <span className="pointer-events-none absolute top-1 left-2.5 text-sm text-quaternary-foreground">{placeholder}</span> : null}
513
+ <div className="max-h-[220px] overflow-y-auto px-2.5 pt-1 pb-2.5">
514
+ <ComposerEditor editorRef={editorRef} />
515
+ </div>
516
+ </div>
517
+
518
+ <div className="flex items-center gap-1.5 pb-2 px-2">
519
+ {onClear ? (
520
+ <button type="button" onClick={onClear} title="Clear chat" aria-label="Clear chat" className="inline-flex size-6 shrink-0 items-center justify-center rounded-lg border-0 bg-transparent cursor-pointer hover:bg-ink-hover">
521
+ <Icon name="eraser" size={14} />
522
+ </button>
523
+ ) : null}
524
+ {toolbar}
525
+ <div className="flex-1" />
526
+
527
+ {generating ? (
528
+ <button type="button" onClick={onCancel} title="Stop" className="w-6 h-6 rounded-full bg-brand text-(--nonla-text-on-solid) flex items-center justify-center shrink-0 cursor-pointer hover:bg-brand/90 active:scale-95 transition-all duration-100 border-0">
529
+ <Icon name="stop" size={12} />
530
+ <span className="sr-only">Stop</span>
531
+ </button>
532
+ ) : (
533
+ <button
534
+ type="button"
535
+ disabled={!canSend}
536
+ onClick={handleSend}
537
+ title="Send (Enter)"
538
+ className={cn("w-6 h-6 rounded-full flex items-center justify-center shrink-0 transition-all duration-100 border-0", canSend ? "bg-foreground text-background cursor-pointer" : "bg-border text-muted-foreground cursor-not-allowed opacity-50")}
539
+ >
540
+ <Icon name="arrow-up" size={14} />
541
+ <span className="sr-only">Send</span>
542
+ </button>
543
+ )}
544
+ </div>
171
545
  </div>
172
546
  </div>
173
547
  );