@notis_ai/cli 0.2.27 → 0.2.28

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.
Files changed (42) hide show
  1. package/README.md +2 -2
  2. package/config/notis_app_design_rules.json +5 -123
  3. package/dist/agent-hooks/notis-agent-hook.mjs +2 -2
  4. package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
  5. package/dist/base-skills/notis-spaces/SKILL.md +13 -19
  6. package/dist/base-skills/notis-spaces/references/design.md +11 -45
  7. package/dist/base-skills/notis-spaces/references/sdk.md +86 -67
  8. package/dist/base-skills/notis-spaces/references/views.md +12 -1
  9. package/dist/sdk/src/components/NotisCommentBoundary.tsx +43 -16
  10. package/dist/sdk/src/components/NotisSelectionBoundary.tsx +26 -1
  11. package/dist/sdk/src/components/SelectionActionBar.tsx +262 -0
  12. package/dist/sdk/src/hooks/useCollectionInteractions.ts +5 -2
  13. package/dist/sdk/src/space.ts +4 -0
  14. package/dist/sdk/src/ui/icons.tsx +11 -2
  15. package/dist/sdk/src/words/actions.ts +9 -1
  16. package/dist/sdk/src/words/keymap.ts +3 -0
  17. package/dist/space-harness/host.js +172 -134
  18. package/dist/space-sdk/dist/{chunk-BWHAORT4.js → chunk-BFGB6XXC.js} +2 -2
  19. package/dist/space-sdk/dist/index.js +2 -2
  20. package/dist/space-sdk/dist/ui.js +14 -11
  21. package/dist/space-sdk/src/components/NotisSelectionBoundary.d.ts +7 -0
  22. package/dist/space-sdk/src/space.ts +4 -0
  23. package/dist/space-sdk/src/tailwind-candidates.d.ts +117 -13
  24. package/dist/space-sdk/src/ui/blocks/DataTable.d.ts +86 -0
  25. package/dist/space-sdk/src/ui/blocks/InfoTip.d.ts +25 -0
  26. package/dist/space-sdk/src/ui/blocks/Meter.d.ts +39 -0
  27. package/dist/space-sdk/src/ui/blocks/blocks.d.ts +1 -1
  28. package/dist/space-sdk/src/ui/blocks/index.d.ts +6 -0
  29. package/dist/space-sdk/src/ui/charts/Chart.d.ts +15 -2
  30. package/dist/space-sdk/src/ui/charts/StatRow.d.ts +4 -3
  31. package/dist/space-sdk/src/ui/charts/chartData.d.ts +6 -0
  32. package/dist/space-sdk/src/ui/icons.d.ts +1 -1
  33. package/dist/space-sdk/src/ui/index.d.ts +2 -2
  34. package/dist/space-sdk/src/ui/list/Row.d.ts +10 -3
  35. package/dist/space-sdk/src/ui/period/dateFormat.d.ts +14 -0
  36. package/dist/space-sdk/src/words/actions.ts +9 -1
  37. package/dist/space-sdk/src/words/keymap.ts +3 -0
  38. package/dist/view-renderer/dist/host.js +243 -205
  39. package/package.json +3 -3
  40. package/src/command-specs/computer.js +3 -3
  41. package/template/components/ui/button.tsx +1 -1
  42. package/template/components/ui/native-select.tsx +1 -1
@@ -1,8 +1,11 @@
1
1
  'use client';
2
2
  import React, { useEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react';
3
3
  import type { ContextResource } from '../runtime';
4
- import { NotisSelectionBoundary } from './NotisSelectionBoundary';
4
+ import { NotisSelectionBoundary, quoteResourceFor } from './NotisSelectionBoundary';
5
5
  import { useAgentContext } from '../hooks/useAgentContext';
6
+ import { useNotisRuntime } from '../provider';
7
+ import { COMMENT_GLYPH, QUOTE_GLYPH, SELECTION_BAR_WORDS, SelectionActionBar, clearSelectionIn, getSelectionBarPosition } from './SelectionActionBar';
8
+ import { useToolkitLocale } from '../ui/engine/hooks';
6
9
 
7
10
  export interface NotisCommentBoxProps {
8
11
  quote?: string;
@@ -22,7 +25,7 @@ export function NotisCommentBox({ quote, value, onChange, onSubmit, onCancel, pe
22
25
  className={`flex min-w-0 flex-col gap-2 rounded-xl border p-2.5 text-sm shadow-lg ${className}`}>
23
26
  <div className="flex min-w-0 items-center gap-2">
24
27
  {quote && <blockquote title={quote} className="min-w-0 flex-1 truncate border-l-2 border-current/40 pl-2 opacity-70">{quote}</blockquote>}
25
- <button type="button" aria-label="Cancel comment" onClick={onCancel} disabled={pending} className="ml-auto flex size-7 shrink-0 items-center justify-center rounded-lg opacity-70 hover:bg-white/10 hover:opacity-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current disabled:opacity-40 [@media(pointer:coarse)]:size-9">
28
+ <button type="button" aria-label="Cancel comment" onClick={onCancel} disabled={pending} className="ml-auto flex size-7 shrink-0 items-center justify-center rounded-lg opacity-70 hover:bg-white/10 hover:opacity-100 disabled:opacity-40 [@media(pointer:coarse)]:size-9">
26
29
  <svg aria-hidden="true" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><path d="m6 6 12 12M18 6 6 18" /></svg>
27
30
  </button>
28
31
  </div>
@@ -34,7 +37,7 @@ export function NotisCommentBox({ quote, value, onChange, onSubmit, onCancel, pe
34
37
  <span className="text-xs opacity-60">⌘ / Ctrl ↵ to add</span>
35
38
  <button type="button" disabled={pending || !value.trim()} onClick={onSubmit}
36
39
  style={{ background: 'hsl(var(--sidebar-foreground, 240 4.8% 95.9%))', color: 'hsl(var(--sidebar-background, 0 0% 7.5%))' }}
37
- className="min-h-8 shrink-0 rounded-lg px-2.5 text-sm font-medium hover:opacity-90 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current disabled:opacity-40 [@media(pointer:coarse)]:min-h-9">{pending ? 'Adding…' : 'Add to chat'}</button>
40
+ className="min-h-8 shrink-0 rounded-lg px-2.5 text-sm font-medium hover:opacity-90 disabled:opacity-40 [@media(pointer:coarse)]:min-h-9">{pending ? 'Adding…' : 'Add to chat'}</button>
38
41
  </div>
39
42
  </div>;
40
43
  }
@@ -88,8 +91,12 @@ export function getOwnedCommentRange(selected: Range, content: Element): Range |
88
91
  /** Selection-to-chat convenience. No annotation database, polling or background attachment. */
89
92
  export function NotisCommentBoundary({ resource, children, className, commentClassName, renderComment }: NotisCommentBoundaryProps) {
90
93
  const context = useAgentContext();
94
+ // A host without a chat (a public Site) offers Comment alone: Cite would have nowhere to go.
95
+ const canCite = Boolean(useNotisRuntime()?.addContext);
91
96
  const root = useRef<HTMLDivElement>(null);
92
- const [selection, setSelection] = useState<{ id: string; text: string; resource?: ContextResource | null; top: number; left: number } | null>(null);
97
+ const [selection, setSelection] = useState<{ id: string; text: string; resource?: ContextResource | null; range: Range; top: number; left: number } | null>(null);
98
+ const locale = useToolkitLocale();
99
+ const [barSize, setBarSize] = useState({ width: 176, height: 32 });
93
100
  const [editing, setEditing] = useState(false);
94
101
  const editingRef = useRef(false);
95
102
  const [comment, setComment] = useState('');
@@ -107,7 +114,12 @@ export function NotisCommentBoundary({ resource, children, className, commentCla
107
114
  const selected = scope.getSelection?.() || document.defaultView?.getSelection();
108
115
  const content = node.firstElementChild;
109
116
  if (!selected?.rangeCount || selected.isCollapsed || !selected.toString().trim()
110
- || !content || !getOwnedCommentRange(selected.getRangeAt(0), content)) setSelection(null);
117
+ || !content || !getOwnedCommentRange(selected.getRangeAt(0), content)) { setSelection(null); return; }
118
+ // A touch selection has no mouse up: show the bar once its handles stop moving (truth PRT-094).
119
+ if (document.defaultView?.matchMedia?.('(pointer: coarse)').matches) {
120
+ document.defaultView.clearTimeout(touchSettle.current);
121
+ touchSettle.current = document.defaultView.setTimeout(() => captureRef.current(null), 450);
122
+ }
111
123
  };
112
124
  document.addEventListener('selectionchange', clearInvalidSelection);
113
125
  if (scope !== (document as unknown as ShadowRoot)) scope.addEventListener('selectionchange', clearInvalidSelection);
@@ -117,9 +129,11 @@ export function NotisCommentBoundary({ resource, children, className, commentCla
117
129
  };
118
130
  }, []);
119
131
  const open = () => { editingRef.current = true; setEditing(true); };
132
+ const touchSettle = useRef<number | undefined>(undefined);
133
+ const captureRef = useRef<(target: EventTarget | null) => void>(() => {});
120
134
  const capture = (target: EventTarget | null) => {
121
135
  // Clicking the action/editor must not unmount it before its click runs.
122
- if (editing || (target instanceof Element && target.closest('[data-notis-comment-ui]'))) return;
136
+ if (editing || (target instanceof Element && target.closest('[data-notis-comment-ui],[data-notis-selection-ui]'))) return;
123
137
  const node = root.current;
124
138
  const scope = node?.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null };
125
139
  const selected = scope?.getSelection?.() || window.getSelection();
@@ -143,9 +157,14 @@ export function NotisCommentBoundary({ resource, children, className, commentCla
143
157
  remainder.setStart(range.endContainer, range.endOffset);
144
158
  trailing.push(...Array.from(remainder.getClientRects?.() || []).filter(line => line.width > 0 && line.height > 0));
145
159
  }
146
- const position = getCommentActionPosition(lines.length ? lines : [rect], { width: window.innerWidth, height: window.innerHeight }, boundary?.width ? boundary.right : window.innerWidth, trailing);
147
- setSelection({ id: crypto.randomUUID(), text: selected.toString().trim(), resource: resource ? JSON.parse(JSON.stringify(resource)) : null, ...position });
160
+ // The bar (Cite, then Comment) sits where the old Comment tile did: after the last line, or below it.
161
+ const position = getSelectionBarPosition(lines.length ? lines : [rect], { width: window.innerWidth, height: window.innerHeight }, barSize,
162
+ { rightBoundary: boundary?.width ? boundary.right : window.innerWidth, trailing, coarse: window.matchMedia?.('(pointer: coarse)').matches });
163
+ setSelection({ id: crypto.randomUUID(), text: selected.toString().trim(), resource: resource ? JSON.parse(JSON.stringify(resource)) : null, range: range.cloneRange(), ...position });
148
164
  };
165
+ captureRef.current = capture;
166
+ // Once the bar measured itself, place it again with its real width.
167
+ useEffect(() => { if (!editingRef.current) captureRef.current(null); }, [barSize.width, barSize.height]);
149
168
  const close = () => { editingRef.current = false; setEditing(false); setSelection(null); setComment(''); setError(''); };
150
169
  const submit = async () => {
151
170
  if (!selection || !comment.trim() || pending) return;
@@ -157,16 +176,24 @@ export function NotisCommentBoundary({ resource, children, className, commentCla
157
176
  } catch (reason) { setError(reason instanceof Error ? reason.message : 'Could not add this comment.'); }
158
177
  finally { setPending(false); }
159
178
  };
179
+ const cite = async () => {
180
+ if (!selection) return;
181
+ const quoted = selection;
182
+ clearSelectionIn(root.current);
183
+ setSelection(null);
184
+ // The quote copy would make: the innermost boundary's resource, else this boundary's.
185
+ const named = quoteResourceFor(quoted.range) ?? quoted.resource ?? null;
186
+ try { await context.add({ id: quoted.id, text: quoted.text, ...(named ? { resource: named } : {}) }); } catch { /* No chat in this host: copy still quotes. */ }
187
+ };
160
188
  const editorProps: NotisCommentBoxProps = { quote: selection?.text, value: comment, onChange: setComment, onSubmit: () => void submit(), onCancel: close, pending, error, className: commentClassName };
161
- return <div ref={root} className="contents" onMouseUp={event => capture(event.target)} onDoubleClick={event => capture(event.target)} onKeyUp={event => { if (!editing && (event.shiftKey || event.key === 'Shift' || ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'a'))) capture(event.target); }}>
189
+ return <div ref={root} className="contents" data-notis-comment-boundary onMouseUp={event => capture(event.target)} onDoubleClick={event => capture(event.target)} onKeyUp={event => { if (!editing && (event.shiftKey || event.key === 'Shift' || ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'a'))) capture(event.target); }}>
162
190
  <NotisSelectionBoundary resource={resource} className={className} style={className ? undefined : { display: 'contents' }}>{children}</NotisSelectionBoundary>
163
- {selection && <div data-notis-comment-ui className="fixed z-50 max-h-[calc(100dvh-1rem)]" style={{ overflow: editing ? 'auto' : 'visible', top: editing ? Math.min(selection.top, Math.max(8, window.innerHeight - 320)) : selection.top, left: `clamp(8px, ${selection.left}px, calc(100vw - ${editing ? 'min(20rem, calc(100vw - 1rem))' : '2rem'} - 8px))`, width: editing ? 'min(20rem, calc(100vw - 1rem))' : undefined } as CSSProperties}>
164
- {editing ? (renderComment ? renderComment(editorProps) : <NotisCommentBox {...editorProps} />) : <button type="button" aria-label="Comment" title="Comment" onMouseDown={event => event.preventDefault()} onClick={open}
165
- style={{ background: 'hsl(var(--sidebar-background, 0 0% 7.5%))', color: 'hsl(var(--sidebar-foreground, 240 4.8% 95.9%))' }}
166
- className="relative flex size-8 items-center justify-center rounded-lg ring-1 ring-white/15 hover:opacity-90 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-current">
167
- <svg aria-hidden="true" width="18" height="18" viewBox="0 0 256 256" fill="currentColor"><path d="M216,48H40A16,16,0,0,0,24,64V224a15.85,15.85,0,0,0,9.24,14.5A16.13,16.13,0,0,0,40,240a15.89,15.89,0,0,0,10.25-3.78l.09-.07L83,208H216a16,16,0,0,0,16-16V64A16,16,0,0,0,216,48ZM40,224h0ZM216,192H80a8,8,0,0,0-5.23,1.95L40,224V64H216ZM88,112a8,8,0,0,1,8-8h64a8,8,0,0,1,0,16H96A8,8,0,0,1,88,112Zm0,32a8,8,0,0,1,8-8h64a8,8,0,1,1,0,16H96A8,8,0,0,1,88,144Z" /></svg>
168
- <span aria-hidden="true" className="absolute left-1/2 top-1/2 hidden size-12 -translate-x-1/2 -translate-y-1/2 [@media(pointer:coarse)]:block" />
169
- </button>}
191
+ {selection && !editing && <SelectionActionBar anchor={selection} onSize={setBarSize} actions={[
192
+ ...(canCite ? [{ key: 'cite', label: SELECTION_BAR_WORDS.cite[locale], title: SELECTION_BAR_WORDS.citeHint[locale], icon: QUOTE_GLYPH, onSelect: () => void cite() }] : []),
193
+ { key: 'comment', label: SELECTION_BAR_WORDS.comment[locale], icon: COMMENT_GLYPH, onSelect: open },
194
+ ]} />}
195
+ {selection && editing && <div data-notis-comment-ui className="fixed z-50 max-h-[calc(100dvh-1rem)]" style={{ overflow: 'auto', top: Math.min(selection.top, Math.max(8, window.innerHeight - 320)), left: `clamp(8px, ${selection.left}px, calc(100vw - min(20rem, calc(100vw - 1rem)) - 8px))`, width: 'min(20rem, calc(100vw - 1rem))' } as CSSProperties}>
196
+ {renderComment ? renderComment(editorProps) : <NotisCommentBox {...editorProps} />}
170
197
  </div>}
171
198
  </div>;
172
199
  }
@@ -109,5 +109,30 @@ export function NotisSelectionBoundary({
109
109
  ...(resource ? { resource: { ...resource, snapshot: undefined } } : {}),
110
110
  }), [resource, runtime]);
111
111
 
112
- return <div className={className} style={style} onCopy={onCopy}>{children}</div>;
112
+ // Cite reads the same resource as copy: the bar looks it up from the selection (`quoteResourceFor`).
113
+ const marker = resource ? JSON.stringify({ ...resource, snapshot: undefined }) : undefined;
114
+ return <div className={className} style={style} onCopy={onCopy} data-notis-quote-resource={marker}>{children}</div>;
115
+ }
116
+
117
+ /** The resource a Space's own boundary names for the text in `range`, as copy would quote it; null outside one. */
118
+ export function quoteResourceFor(range: Range): ContextResource | null {
119
+ const start = range.commonAncestorContainer;
120
+ const element = start.nodeType === Node.ELEMENT_NODE ? start as Element : start.parentElement;
121
+ const marked = element?.closest('[data-notis-quote-resource]')?.getAttribute('data-notis-quote-resource');
122
+ if (!marked) return null;
123
+ try { return JSON.parse(marked) as ContextResource; } catch { return null; }
124
+ }
125
+
126
+ /**
127
+ * Cite for a Space (truth PRT-087): the selected text goes to chat as the quote copy would make, its Space as source
128
+ * and the boundary's resource when one names it. A Site's runtime has no chat, so it cites nothing.
129
+ */
130
+ export function citeSpaceSelection(runtime: Pick<NotisRuntime, 'contextSource' | 'addContext'> | null, range: Range, text: string): Promise<boolean> {
131
+ if (!runtime?.addContext) return Promise.resolve(false);
132
+ const resource = quoteResourceFor(range);
133
+ const source = runtime.contextSource;
134
+ return runtime.addContext({
135
+ id: selectionId(), text,
136
+ ...(resource ? { resource } : source ? { title: source.appName } : {}),
137
+ });
113
138
  }
@@ -0,0 +1,262 @@
1
+ 'use client';
2
+ import React, { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from 'react';
3
+ import type { Words } from '../words/types';
4
+
5
+ /**
6
+ * The floating bar on selected text (truths PRT-087, PRT-090, PRT-094): one dark labelled pill at the end of the
7
+ * selection, with Cite and, where a surface takes comments, Comment. Chat, every Space view, Skills and automations
8
+ * draw the same bar; each surface decides what Cite quotes and where the quote goes.
9
+ */
10
+
11
+ /** Cmd+Shift+C (Ctrl+Shift+C off a Mac) cites the selection: the host dispatches this on the document, and the bar on screen answers. */
12
+ export const CITE_SELECTION_EVENT = 'notis:cite-selection';
13
+
14
+ export const SELECTION_BAR_WORDS = Object.freeze({
15
+ cite: Object.freeze({ en: 'Cite', fr: 'Citer' }),
16
+ citeHint: Object.freeze({ en: 'Cite in chat', fr: 'Citer dans le chat' }),
17
+ comment: Object.freeze({ en: 'Comment', fr: 'Commenter' }),
18
+ }) satisfies Readonly<Record<string, Words>>;
19
+
20
+ export interface SelectionBarAction {
21
+ key: string;
22
+ label: string;
23
+ title?: string;
24
+ icon: ReactNode;
25
+ onSelect(): void;
26
+ }
27
+
28
+ export interface SelectionAnchor {
29
+ top: number;
30
+ left: number;
31
+ /** The selected text, trimmed. */
32
+ text: string;
33
+ /** A copy of the selected range, still valid after the browser collapses the live selection. */
34
+ range: Range;
35
+ }
36
+
37
+ type Rect = Pick<DOMRect, 'left' | 'right' | 'top' | 'bottom'>;
38
+ const GAP = 8;
39
+ const TOUCH_GAP = 14;
40
+
41
+ /**
42
+ * Where the bar goes: after the last selected line when it fits there and no text follows on that line, otherwise
43
+ * just below where the selection ends (above it near the bottom of the viewport). On a touch screen it always goes
44
+ * below, so the system's own Copy menu keeps the space above the selection.
45
+ */
46
+ export function getSelectionBarPosition(
47
+ rects: Rect[],
48
+ viewport: { width: number; height: number },
49
+ bar: { width: number; height: number },
50
+ options: { rightBoundary?: number; trailing?: Rect[]; coarse?: boolean } = {},
51
+ ): { top: number; left: number } {
52
+ const last = rects[rects.length - 1];
53
+ const { width, height } = bar;
54
+ const rightBoundary = options.rightBoundary ?? viewport.width;
55
+ const clampX = (x: number) => Math.max(GAP, Math.min(viewport.width - width - GAP, x));
56
+ const clampY = (y: number) => Math.max(GAP, Math.min(viewport.height - height - GAP, y));
57
+ if (!options.coarse) {
58
+ const beside = { left: last.right + GAP, top: clampY((last.top + last.bottom - height) / 2) };
59
+ const overlapsText = (options.trailing ?? []).some(rect => rect.left < beside.left + width && rect.right > beside.left
60
+ && rect.top < beside.top + height && rect.bottom > beside.top);
61
+ if (beside.left + width <= Math.min(viewport.width, rightBoundary) - GAP && !overlapsText) return beside;
62
+ }
63
+ const gap = options.coarse ? TOUCH_GAP : GAP;
64
+ const below = last.bottom + gap;
65
+ const left = clampX(options.coarse ? (last.left + last.right - width) / 2 : last.right - width);
66
+ return { left, top: clampY(below + height <= viewport.height - GAP ? below : last.top - height - gap) };
67
+ }
68
+
69
+ function isCoarsePointer(view: Window | null): boolean {
70
+ return Boolean(view?.matchMedia?.('(pointer: coarse)').matches);
71
+ }
72
+
73
+ const EDITABLE = 'input,textarea,select,[contenteditable]:not([contenteditable="false"]),[data-notis-selection-ui]';
74
+
75
+ function elementOf(node: Node): Element | null {
76
+ return node.nodeType === Node.ELEMENT_NODE ? node as Element : node.parentElement;
77
+ }
78
+
79
+ export interface UseSelectionAnchorOptions {
80
+ /** Off while the surface has nowhere to send a quote (a public Site, a chat that cannot send). */
81
+ enabled?: boolean;
82
+ /** Refuse a selection the surface does not quote (inside a nested surface with its own bar). */
83
+ accept?(range: Range, root: HTMLElement): boolean;
84
+ /** Clip the selection to the surface instead of refusing one that spills over its edge. */
85
+ clip?(range: Range, root: HTMLElement): Range | null;
86
+ /** The bar's size, measured once it shows; used to keep it inside the viewport. */
87
+ barSize?: { width: number; height: number };
88
+ }
89
+
90
+ /**
91
+ * Follows the text selected inside `root` and returns where the bar shows, or null. A mouse or keyboard selection
92
+ * shows the bar when it ends (mouse up, Shift+arrow up); a touch selection once it has stopped moving.
93
+ */
94
+ export function useSelectionAnchor(root: RefObject<HTMLElement | null>, options: UseSelectionAnchorOptions = {}) {
95
+ const { enabled = true } = options;
96
+ const [anchor, setAnchor] = useState<SelectionAnchor | null>(null);
97
+ const optionsRef = useRef(options);
98
+ optionsRef.current = options;
99
+ const settle = useRef<number | undefined>(undefined);
100
+
101
+ const read = useCallback((): SelectionAnchor | null => {
102
+ const node = root.current;
103
+ if (!node) return null;
104
+ const scope = node.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null };
105
+ const view = node.ownerDocument.defaultView;
106
+ const selection = scope.getSelection?.() || view?.getSelection();
107
+ if (!selection?.rangeCount || selection.isCollapsed || !selection.toString().trim()) return null;
108
+ let range: Range | null = selection.getRangeAt(0).cloneRange();
109
+ if (!node.contains(range.startContainer) || !node.contains(range.endContainer)) {
110
+ range = optionsRef.current.clip?.(range, node) ?? null;
111
+ if (!range) return null;
112
+ }
113
+ const start = elementOf(range.startContainer);
114
+ const end = elementOf(range.endContainer);
115
+ if (start?.closest(EDITABLE) || end?.closest(EDITABLE)) return null;
116
+ if (optionsRef.current.accept && !optionsRef.current.accept(range, node)) return null;
117
+ const text = range.toString().trim();
118
+ if (!text) return null;
119
+ const lines = Array.from(range.getClientRects?.() || []).filter(line => line.width > 0 && line.height > 0);
120
+ const rect = range.getBoundingClientRect();
121
+ const trailing: DOMRect[] = [];
122
+ const endBlock = end?.closest('p,li,h1,h2,h3,h4,h5,h6,td,th,pre,blockquote,div');
123
+ if (endBlock && node.contains(endBlock)) {
124
+ const remainder = range.cloneRange();
125
+ remainder.selectNodeContents(endBlock);
126
+ remainder.setStart(range.endContainer, range.endOffset);
127
+ if (remainder.toString().trim()) trailing.push(...Array.from(remainder.getClientRects?.() || []).filter(line => line.width > 0 && line.height > 0));
128
+ }
129
+ const bounds = node.getBoundingClientRect();
130
+ const position = getSelectionBarPosition(lines.length ? lines : [rect],
131
+ { width: view?.innerWidth ?? 1024, height: view?.innerHeight ?? 768 },
132
+ optionsRef.current.barSize ?? { width: 80, height: 32 },
133
+ { rightBoundary: bounds.width ? bounds.right : undefined, trailing, coarse: isCoarsePointer(view) });
134
+ return { ...position, text, range };
135
+ }, [root]);
136
+
137
+ const dismiss = useCallback(() => setAnchor(null), []);
138
+
139
+ // The bar measured itself: place it again with its real width, so its edge lines up with the selection.
140
+ const barWidth = options.barSize?.width;
141
+ const barHeight = options.barSize?.height;
142
+ useEffect(() => { setAnchor(current => current ? read() : current); }, [barWidth, barHeight, read]);
143
+
144
+ useEffect(() => {
145
+ const node = root.current;
146
+ if (!enabled || !node) { setAnchor(null); return; }
147
+ const document = node.ownerDocument;
148
+ const view = document.defaultView;
149
+ const scope = node.getRootNode() as ShadowRoot | Document;
150
+ const capture = (event: Event) => {
151
+ if (event.target instanceof Element && event.target.closest('[data-notis-selection-ui]')) return;
152
+ // Let the browser finish the selection (a double click selects the word after mouseup).
153
+ view?.setTimeout(() => setAnchor(read()), 0);
154
+ };
155
+ const onKeyUp = (event: KeyboardEvent) => {
156
+ if (event.shiftKey || event.key === 'Shift' || ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'a')) capture(event);
157
+ };
158
+ const onSelectionChange = () => {
159
+ const next = read();
160
+ if (!next) { setAnchor(null); return; }
161
+ // A touch selection has no mouse up: show the bar once its handles stop moving.
162
+ if (isCoarsePointer(view)) {
163
+ view?.clearTimeout(settle.current);
164
+ setAnchor(null);
165
+ settle.current = view?.setTimeout(() => setAnchor(read()), 450);
166
+ }
167
+ };
168
+ const onScroll = () => setAnchor(current => current ? read() : current);
169
+ node.addEventListener('mouseup', capture);
170
+ node.addEventListener('dblclick', capture);
171
+ node.addEventListener('keyup', onKeyUp);
172
+ document.addEventListener('selectionchange', onSelectionChange);
173
+ if (scope !== document) scope.addEventListener('selectionchange', onSelectionChange);
174
+ view?.addEventListener('scroll', onScroll, true);
175
+ view?.addEventListener('resize', onScroll);
176
+ return () => {
177
+ view?.clearTimeout(settle.current);
178
+ node.removeEventListener('mouseup', capture);
179
+ node.removeEventListener('dblclick', capture);
180
+ node.removeEventListener('keyup', onKeyUp);
181
+ document.removeEventListener('selectionchange', onSelectionChange);
182
+ if (scope !== document) scope.removeEventListener('selectionchange', onSelectionChange);
183
+ view?.removeEventListener('scroll', onScroll, true);
184
+ view?.removeEventListener('resize', onScroll);
185
+ };
186
+ }, [enabled, read, root]);
187
+
188
+ return { anchor, dismiss, refresh: () => setAnchor(read()) };
189
+ }
190
+
191
+ /** Clears the page's selection once its text was cited, so the bar does not linger over it. */
192
+ export function clearSelectionIn(node: Node | null | undefined): void {
193
+ if (!node) return;
194
+ const scope = node.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null };
195
+ (scope.getSelection?.() || node.ownerDocument?.defaultView?.getSelection())?.removeAllRanges();
196
+ }
197
+
198
+ export const QUOTE_GLYPH = <svg aria-hidden="true" width="14" height="14" viewBox="0 0 256 256" fill="currentColor"><path d="M100,56H40A16,16,0,0,0,24,72v64a16,16,0,0,0,16,16h60v8a32,32,0,0,1-32,32,8,8,0,0,0,0,16,48.05,48.05,0,0,0,48-48V72A16,16,0,0,0,100,56Zm0,80H40V72h60ZM216,56H156a16,16,0,0,0-16,16v64a16,16,0,0,0,16,16h60v8a32,32,0,0,1-32,32,8,8,0,0,0,0,16,48.05,48.05,0,0,0,48-48V72A16,16,0,0,0,216,56Zm0,80H156V72h60Z" /></svg>;
199
+ export const COMMENT_GLYPH = <svg aria-hidden="true" width="14" height="14" viewBox="0 0 256 256" fill="currentColor"><path d="M216,48H40A16,16,0,0,0,24,64V224a15.85,15.85,0,0,0,9.24,14.5A16.13,16.13,0,0,0,40,240a15.89,15.89,0,0,0,10.25-3.78l.09-.07L83,208H216a16,16,0,0,0,16-16V64A16,16,0,0,0,216,48ZM40,224h0ZM216,192H80a8,8,0,0,0-5.23,1.95L40,224V64H216ZM88,112a8,8,0,0,1,8-8h64a8,8,0,0,1,0,16H96A8,8,0,0,1,88,112Zm0,32a8,8,0,0,1,8-8h64a8,8,0,1,1,0,16H96A8,8,0,0,1,88,144Z" /></svg>;
200
+
201
+ const BAR_STYLE: React.CSSProperties = {
202
+ position: 'fixed', zIndex: 60, display: 'inline-flex', alignItems: 'center', gap: 2, padding: 3, borderRadius: 999,
203
+ background: 'hsl(var(--sidebar-background, 0 0% 7.5%))', color: 'hsl(var(--sidebar-foreground, 240 4.8% 95.9%))',
204
+ boxShadow: '0 0 0 1px rgb(255 255 255 / 0.15), 0 6px 18px rgb(0 0 0 / 0.28)', colorScheme: 'dark',
205
+ fontFamily: 'inherit', fontSize: 13, lineHeight: '18px', fontWeight: 500, whiteSpace: 'nowrap',
206
+ };
207
+
208
+ /**
209
+ * The dark labelled pill itself. It never takes focus or moves the selection (mouse down is cancelled), and it
210
+ * answers the Cite key while it shows: the first action is Cite.
211
+ */
212
+ export function SelectionActionBar({ anchor, actions, onSize }: {
213
+ anchor: Pick<SelectionAnchor, 'top' | 'left'>;
214
+ actions: SelectionBarAction[];
215
+ onSize?(size: { width: number; height: number }): void;
216
+ }) {
217
+ const bar = useRef<HTMLDivElement>(null);
218
+ const first = useRef(actions[0]);
219
+ first.current = actions[0];
220
+ const [left, setLeft] = useState(anchor.left);
221
+ // A finger needs a bigger target than the 26 px a pointer gets.
222
+ const coarse = typeof window !== 'undefined' && isCoarsePointer(window);
223
+ useLayoutEffect(() => {
224
+ const node = bar.current;
225
+ const view = node?.ownerDocument.defaultView;
226
+ if (!node || !view) { setLeft(anchor.left); return; }
227
+ const width = node.offsetWidth;
228
+ onSize?.({ width, height: node.offsetHeight });
229
+ setLeft(Math.max(GAP, Math.min(view.innerWidth - width - GAP, anchor.left)));
230
+ }, [anchor.left, anchor.top, onSize, actions.length]);
231
+ useEffect(() => {
232
+ const document = bar.current?.ownerDocument;
233
+ if (!document) return;
234
+ const onCite = (event: Event) => {
235
+ if ((event as CustomEvent<{ handled?: boolean }>).detail?.handled) return;
236
+ const detail = (event as CustomEvent<{ handled?: boolean }>).detail;
237
+ if (detail) detail.handled = true;
238
+ first.current?.onSelect();
239
+ };
240
+ document.addEventListener(CITE_SELECTION_EVENT, onCite);
241
+ return () => document.removeEventListener(CITE_SELECTION_EVENT, onCite);
242
+ }, []);
243
+ return <div ref={bar} data-notis-selection-ui role="toolbar" style={{ ...BAR_STYLE, top: anchor.top, left }}
244
+ onMouseDown={event => event.preventDefault()} onPointerDown={event => event.stopPropagation()}>
245
+ {actions.map((action, index) => <React.Fragment key={action.key}>
246
+ {index > 0 && <span aria-hidden="true" style={{ width: 1, height: 16, background: 'rgb(255 255 255 / 0.14)', margin: '0 1px' }} />}
247
+ <button type="button" title={action.title ?? action.label} onClick={action.onSelect} data-selection-action={action.key}
248
+ className="notis-selection-action"
249
+ style={{ all: 'unset', boxSizing: 'border-box', display: 'inline-flex', alignItems: 'center', gap: 6, height: coarse ? 36 : 26,
250
+ padding: coarse ? '0 14px 0 12px' : '0 11px 0 9px', borderRadius: 999, cursor: 'pointer', background: index === 0 ? 'rgb(255 255 255 / 0.08)' : undefined }}>
251
+ {action.icon}<span>{action.label}</span>
252
+ </button>
253
+ </React.Fragment>)}
254
+ </div>;
255
+ }
256
+
257
+ /** Fires the Cite key: the bar on screen cites its selection. Returns whether one did. */
258
+ export function dispatchCiteSelection(document: Document): boolean {
259
+ const detail = { handled: false };
260
+ document.dispatchEvent(new CustomEvent(CITE_SELECTION_EVENT, { detail }));
261
+ return detail.handled;
262
+ }
@@ -285,6 +285,9 @@ export function useCollectionInteractions<T>(
285
285
  );
286
286
  const selectableIdsRef = useRef(selectableIds);
287
287
  selectableIdsRef.current = selectableIds;
288
+ const selectableIdSet = useMemo(() => new Set(selectableIds), [selectableIds]);
289
+ const selectableIdSetRef = useRef(selectableIdSet);
290
+ selectableIdSetRef.current = selectableIdSet;
288
291
  // The list as it was when it last held the active item: J/K from an item that left the list go on from its place.
289
292
  const activePlaceRef = useRef<{ id: string; ids: string[] } | null>(null);
290
293
  const droppedActiveIdRef = useRef<string | null>(null);
@@ -647,7 +650,7 @@ export function useCollectionInteractions<T>(
647
650
  [LEGACY_ROW_ATTRIBUTE]: id,
648
651
  tabIndex: activeIdRef.current === id || (!activeIdRef.current && selectableIdsRef.current[0] === id) ? 0 : -1,
649
652
  'aria-selected': selectedIdsRef.current.has(id),
650
- 'aria-disabled': !selectableIdsRef.current.includes(id),
653
+ 'aria-disabled': !selectableIdSetRef.current.has(id),
651
654
  'data-notis-active': (activeIdRef.current === id ? 'true' : 'false') as 'true' | 'false',
652
655
  onFocus: () => {
653
656
  activateCollectionShortcuts();
@@ -680,7 +683,7 @@ export function useCollectionInteractions<T>(
680
683
 
681
684
  const getCheckboxProps = useCallback((id: string) => ({
682
685
  isSelected: selectedIdsRef.current.has(id),
683
- disabled: !enabled || !selectableIdsRef.current.includes(id),
686
+ disabled: !enabled || !selectableIdSetRef.current.has(id),
684
687
  onClick: onCheckboxClick(id),
685
688
  }), [enabled, onCheckboxClick]);
686
689
 
@@ -537,6 +537,10 @@ export interface SpaceDefinition {
537
537
  * moment, once that person allowed this Space's agents. Agents' own writes never wake anything.
538
538
  */
539
539
  agents?: SpaceAgentDeclaration[];
540
+ /**
541
+ * Lists the database's records as sidebar rows under this Space. Only for a short list people navigate
542
+ * like pages (folders, chapters); a database that keeps growing belongs in the view's `shows` instead.
543
+ */
540
544
  collection?: { database: string; titleProperty: string; parentProperty?: string; allowCreate?: boolean };
541
545
  /** Reproducible source dependencies not discovered by the module graph. */
542
546
  sourceIncludes?: string[];
@@ -74,10 +74,19 @@ export function hasIcon(name: string): boolean {
74
74
  return Object.prototype.hasOwnProperty.call(SHAPES, name);
75
75
  }
76
76
 
77
- /** A built-in icon by name; an unknown name renders nothing. Decorative: the control carries the label. */
77
+ const warned = new Set<string>();
78
+
79
+ /** Names the set lacks, warned once each: an unknown name renders nothing, so a typo would otherwise go unseen. */
80
+ function warnUnknown(name: string): void {
81
+ if (warned.has(name) || typeof console === 'undefined') return;
82
+ warned.add(name);
83
+ console.warn(`[notis/ui] Unknown icon "${name}": it renders nothing. Use a name from the toolkit set (${Object.keys(SHAPES).length} icons, listed in the design system) or pass a Phosphor component.`);
84
+ }
85
+
86
+ /** A built-in icon by name; an unknown name renders nothing and warns once. Decorative: the control carries the label. */
78
87
  export function Icon({ name, className }: { name: string; className?: string }) {
79
88
  const shape = SHAPES[name];
80
- if (!shape) return null;
89
+ if (!shape) { warnUnknown(name); return null; }
81
90
  return (
82
91
  <svg className={className ? `nui-icon ${className}` : 'nui-icon'} viewBox="0 0 16 16" aria-hidden="true" focusable="false">
83
92
  {shape}
@@ -67,7 +67,15 @@ export class ActionError extends Error {
67
67
  /** The reason an ActionError carries, else null. A Space bundles its own copy of the words, so this reads the shape. */
68
68
  export function actionErrorReason(error: unknown): Words | string | null {
69
69
  if (!error || typeof error !== 'object') return null;
70
- const { name, code, reason } = error as { name?: unknown; code?: unknown; reason?: unknown };
70
+ const { name, code, reason, status } = error as { name?: unknown; code?: unknown; reason?: unknown; status?: unknown };
71
+ // A confirmed host refusal can explain how to unblock the action. These words are
72
+ // ours: never display an arbitrary Space/server error's message as a toast reason.
73
+ if (name === 'SpaceActionError' && code === 'document_has_spaces' && status === 'refused') {
74
+ return {
75
+ en: 'This document is used by a Space. Move or trash its linked Spaces first.',
76
+ fr: 'Ce document est utilisé par un Space. Déplace ou mets à la corbeille ses Spaces liés d’abord.',
77
+ };
78
+ }
71
79
  if (name !== 'ActionError' || code !== 'notis_action_error') return null;
72
80
  return typeof reason === 'string' || isWords(reason) ? reason : null;
73
81
  }
@@ -52,6 +52,9 @@ export const DEFAULT_KEYMAP = Object.freeze({
52
52
  'host.search': entry('host.search', ['/'], 'app', 'Search', 'Rechercher', { host: true }),
53
53
  'host.newChat': entry('host.newChat', ['c'], 'app', 'New conversation', 'Nouvelle conversation', { host: true }),
54
54
  'host.call': entry('host.call', ['shift+c'], 'app', 'Open voice call', 'Ouvrir l’appel vocal', { host: true }),
55
+ // Cites the selected text in chat, like the Cite button on the selection (truth PRT-089).
56
+ 'host.cite': entry('host.cite', ['mod+shift+c'], 'app', 'Cite selected text in chat', 'Citer le texte sélectionné dans le chat',
57
+ { host: true }),
55
58
  'host.toggleSidebar': entry('host.toggleSidebar', ['mod+s'], 'app', 'Toggle sidebar',
56
59
  'Afficher ou masquer la barre latérale', { host: true }),
57
60
  'host.voiceMessage': entry('host.voiceMessage', ['mod+d'], 'app', 'Voice message', 'Message vocal', { host: true }),