@notis_ai/cli 0.2.28 → 0.2.29

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 +1 @@
1
- {"schema":1,"stamp":1794414114,"commit":"b30c41a5c3e0b065aaf9a0be08c918eea77be86d"}
1
+ {"schema":1,"stamp":1794497594,"commit":"ca87a334f8e4899af09347a9c5362d62856c6e7c"}
@@ -124,7 +124,10 @@ rather than from a copy.
124
124
  picture that opens full screen. Do not build your own lightbox.
125
125
  - **Comments**: `useComments` with `CommentPane` and `CommentPins` give review
126
126
  threads on a Comments database (pins, zones, replies, asks, Resolve, Copy
127
- changes). For comments on a whole record with nothing to pin on, pass no
127
+ changes). A comment is signed with the viewer's first name; when the
128
+ Comments database's Author is a choice list, give it a `Person` option, which
129
+ signs anyone it does not name (without it the comment saves with no author).
130
+ Pass `me` only to sign with a fixed name. For comments on a whole record with nothing to pin on, pass no
128
131
  `anchors` and `columns.anchor: null`: the pane offers New comment itself.
129
132
  To let people attach pictures and files to a comment or a reply
130
133
  (paste, drop or the paperclip), give the Comments database a files column
@@ -205,6 +208,10 @@ said in the Space's language, default Loading content. Its shapes are
205
208
  measured from the view at verify time and drawn from the release; `skeletonKey`
206
209
  (default `main`) names the region when a view has several separately loading
207
210
  parts, and `variant` only draws the fallback before the first measured release.
211
+ A region that only shows on another tab or page is measured when the
212
+ verification fixtures list that tab's params in `context.skeletonParams`. A Space
213
+ with editor-only parts gets the skeleton of its public view, the one visitors
214
+ see: an editors' page that loads differently keeps a plain loading state of its own.
208
215
 
209
216
  For another explicitly idempotent read use `useActionQuery`, or
210
217
  `useQuery(keyArray, readCallback, { readOnly: true })` with every input in the
@@ -1,10 +1,11 @@
1
1
  'use client';
2
- import React, { useEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react';
2
+ import React, { useRef, useState, type CSSProperties, type ReactNode } from 'react';
3
3
  import type { ContextResource } from '../runtime';
4
4
  import { NotisSelectionBoundary, quoteResourceFor } from './NotisSelectionBoundary';
5
5
  import { useAgentContext } from '../hooks/useAgentContext';
6
6
  import { useNotisRuntime } from '../provider';
7
- import { COMMENT_GLYPH, QUOTE_GLYPH, SELECTION_BAR_WORDS, SelectionActionBar, clearSelectionIn, getSelectionBarPosition } from './SelectionActionBar';
7
+ import { COMMENT_GLYPH, SELECTION_BAR_WORDS, SelectionActionBar, citeSelectionAction, useSelectionAnchor } from './SelectionActionBar';
8
+ import { newSelectionId } from './selectionId';
8
9
  import { useToolkitLocale } from '../ui/engine/hooks';
9
10
 
10
11
  export interface NotisCommentBoxProps {
@@ -51,20 +52,6 @@ export interface NotisCommentBoundaryProps {
51
52
  renderComment?: (props: NotisCommentBoxProps) => ReactNode;
52
53
  }
53
54
 
54
- type SelectionRect = Pick<DOMRect, 'left' | 'right' | 'top' | 'bottom'>;
55
-
56
- /** Place the tile after the final selected line, otherwise below (or above near the viewport bottom). */
57
- export function getCommentActionPosition(rects: SelectionRect[], viewport: { width: number; height: number }, rightBoundary = viewport.width, trailing: SelectionRect[] = []) {
58
- const last = rects[rects.length - 1];
59
- const size = 32, gap = 8;
60
- const clampX = (x: number) => Math.max(gap, Math.min(viewport.width - size - gap, x));
61
- const clampY = (y: number) => Math.max(gap, Math.min(viewport.height - size - gap, y));
62
- const beside = { left: last.right + gap, top: clampY((last.top + last.bottom - size) / 2) };
63
- const overlapsText = trailing.some(rect => rect.left < beside.left + size && rect.right > beside.left && rect.top < beside.top + size && rect.bottom > beside.top);
64
- if (beside.left + size <= Math.min(viewport.width, rightBoundary) - gap && !overlapsText) return beside;
65
- return { left: clampX(last.right - size), top: clampY(last.bottom + gap + size <= viewport.height - gap ? last.bottom + gap : last.top - size - gap) };
66
- }
67
-
68
55
  /** Browser paragraph selection may include an adjacent block's empty starting boundary. */
69
56
  export function getOwnedCommentRange(selected: Range, content: Element): Range | null {
70
57
  const owned = content.ownerDocument.createRange();
@@ -94,105 +81,51 @@ export function NotisCommentBoundary({ resource, children, className, commentCla
94
81
  // A host without a chat (a public Site) offers Comment alone: Cite would have nowhere to go.
95
82
  const canCite = Boolean(useNotisRuntime()?.addContext);
96
83
  const root = useRef<HTMLDivElement>(null);
97
- const [selection, setSelection] = useState<{ id: string; text: string; resource?: ContextResource | null; range: Range; top: number; left: number } | null>(null);
98
84
  const locale = useToolkitLocale();
99
85
  const [barSize, setBarSize] = useState({ width: 176, height: 32 });
100
- const [editing, setEditing] = useState(false);
101
- const editingRef = useRef(false);
86
+ // The quote being commented on, frozen when the editor opens: typing moves the browser selection into the editor.
87
+ const [editing, setEditing] = useState<{ id: string; text: string; resource: ContextResource | null; top: number; left: number } | null>(null);
102
88
  const [comment, setComment] = useState('');
103
89
  const [pending, setPending] = useState(false);
104
90
  const [error, setError] = useState('');
105
- useEffect(() => {
106
- const node = root.current;
107
- if (!node) return;
108
- const document = node.ownerDocument;
109
- const scope = node.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null };
110
- const clearInvalidSelection = () => {
111
- // Opening the editor focuses its input and collapses the browser range.
112
- // Keep the captured quote/editor; only the unopened action follows live selection.
113
- if (editingRef.current) return;
114
- const selected = scope.getSelection?.() || document.defaultView?.getSelection();
115
- const content = node.firstElementChild;
116
- if (!selected?.rangeCount || selected.isCollapsed || !selected.toString().trim()
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
- }
123
- };
124
- document.addEventListener('selectionchange', clearInvalidSelection);
125
- if (scope !== (document as unknown as ShadowRoot)) scope.addEventListener('selectionchange', clearInvalidSelection);
126
- return () => {
127
- document.removeEventListener('selectionchange', clearInvalidSelection);
128
- if (scope !== (document as unknown as ShadowRoot)) scope.removeEventListener('selectionchange', clearInvalidSelection);
129
- };
130
- }, []);
131
- const open = () => { editingRef.current = true; setEditing(true); };
132
- const touchSettle = useRef<number | undefined>(undefined);
133
- const captureRef = useRef<(target: EventTarget | null) => void>(() => {});
134
- const capture = (target: EventTarget | null) => {
135
- // Clicking the action/editor must not unmount it before its click runs.
136
- if (editing || (target instanceof Element && target.closest('[data-notis-comment-ui],[data-notis-selection-ui]'))) return;
137
- const node = root.current;
138
- const scope = node?.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null };
139
- const selected = scope?.getSelection?.() || window.getSelection();
140
- if (!node || !selected?.rangeCount || selected.isCollapsed) { setSelection(null); return; }
141
- const content = node.firstElementChild;
142
- const range = content ? getOwnedCommentRange(selected.getRangeAt(0), content) : null;
143
- if (!range) { setSelection(null); return; }
144
- const start = range.startContainer.nodeType === Node.ELEMENT_NODE ? range.startContainer as Element : range.startContainer.parentElement;
145
- const end = range.endContainer.nodeType === Node.ELEMENT_NODE ? range.endContainer as Element : range.endContainer.parentElement;
146
- if (!node.contains(range.startContainer) || !node.contains(range.endContainer)
147
- || start?.closest('input,textarea,button,[contenteditable],[data-notis-comment-ui]')
148
- || end?.closest('input,textarea,button,[contenteditable],[data-notis-comment-ui]')) { setSelection(null); return; }
149
- const rect = range.getBoundingClientRect();
150
- const lines = Array.from(range.getClientRects?.() || []).filter(line => line.width > 0 && line.height > 0);
151
- const boundary = node.firstElementChild?.getBoundingClientRect();
152
- const trailing: DOMRect[] = [];
153
- const endBlock = end?.closest('p,li,h1,h2,h3,h4,h5,h6,td,th,div');
154
- if (endBlock && node.contains(endBlock)) {
155
- const remainder = range.cloneRange();
156
- remainder.selectNodeContents(endBlock);
157
- remainder.setStart(range.endContainer, range.endOffset);
158
- trailing.push(...Array.from(remainder.getClientRects?.() || []).filter(line => line.width > 0 && line.height > 0));
159
- }
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 });
91
+ // The same bar placement as every quoting surface; a selection spilling over the boundary only by whitespace is
92
+ // clipped to it, and one that takes a neighbour's words is refused.
93
+ const { anchor, dismiss } = useSelectionAnchor(root, {
94
+ enabled: !editing,
95
+ barSize,
96
+ clip: (range, node) => node.firstElementChild ? getOwnedCommentRange(range, node.firstElementChild) : null,
97
+ // A comment boundary never quotes a selection that starts or ends on a button, as before the shared bar.
98
+ exclude: 'button',
99
+ });
100
+ const ownResource = () => resource ? JSON.parse(JSON.stringify(resource)) as ContextResource : null;
101
+ const open = () => {
102
+ if (!anchor) return;
103
+ setEditing({ id: newSelectionId(), text: anchor.text, resource: ownResource(), top: anchor.top, left: anchor.left });
164
104
  };
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]);
168
- const close = () => { editingRef.current = false; setEditing(false); setSelection(null); setComment(''); setError(''); };
105
+ const close = () => { setEditing(null); dismiss(); setComment(''); setError(''); };
169
106
  const submit = async () => {
170
- if (!selection || !comment.trim() || pending) return;
107
+ if (!editing || !comment.trim() || pending) return;
171
108
  setPending(true); setError('');
172
109
  try {
173
- const added = await context.add({ id: selection.id, kind: 'comment', title: selection.resource?.label || 'Comment', icon: 'phosphor:chat-text', text: selection.text, comment, resource: selection.resource });
110
+ const added = await context.add({ id: editing.id, kind: 'comment', title: editing.resource?.label || 'Comment', icon: 'phosphor:chat-text', text: editing.text, comment, resource: editing.resource });
174
111
  if (!added) throw new Error('The comment could not be added to chat.');
175
112
  close();
176
113
  } catch (reason) { setError(reason instanceof Error ? reason.message : 'Could not add this comment.'); }
177
114
  finally { setPending(false); }
178
115
  };
179
- const cite = async () => {
180
- if (!selection) return;
181
- const quoted = selection;
182
- clearSelectionIn(root.current);
183
- setSelection(null);
116
+ const cite = async (range: Range, text: string) => {
184
117
  // 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. */ }
118
+ const named = quoteResourceFor(range) ?? ownResource();
119
+ try { await context.add({ id: newSelectionId(), text, ...(named ? { resource: named } : {}) }); } catch { /* No chat in this host: copy still quotes. */ }
187
120
  };
188
- const editorProps: NotisCommentBoxProps = { quote: selection?.text, value: comment, onChange: setComment, onSubmit: () => void submit(), onCancel: close, pending, error, className: commentClassName };
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); }}>
121
+ const editorProps: NotisCommentBoxProps = { quote: editing?.text, value: comment, onChange: setComment, onSubmit: () => void submit(), onCancel: close, pending, error, className: commentClassName };
122
+ return <div ref={root} className="contents" data-notis-comment-boundary>
190
123
  <NotisSelectionBoundary resource={resource} className={className} style={className ? undefined : { display: 'contents' }}>{children}</NotisSelectionBoundary>
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() }] : []),
124
+ {anchor && !editing && <SelectionActionBar anchor={anchor} onSize={setBarSize} actions={[
125
+ ...(canCite ? [citeSelectionAction(locale, anchor, root, dismiss, (range, text) => void cite(range, text))] : []),
193
126
  { key: 'comment', label: SELECTION_BAR_WORDS.comment[locale], icon: COMMENT_GLYPH, onSelect: open },
194
127
  ]} />}
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}>
128
+ {editing && <div data-notis-comment-ui className="fixed z-50 max-h-[calc(100dvh-1rem)]" style={{ overflow: 'auto', top: Math.min(editing.top, Math.max(8, window.innerHeight - 320)), left: `clamp(8px, ${editing.left}px, calc(100vw - min(20rem, calc(100vw - 1rem)) - 8px))`, width: 'min(20rem, calc(100vw - 1rem))' } as CSSProperties}>
196
129
  {renderComment ? renderComment(editorProps) : <NotisCommentBox {...editorProps} />}
197
130
  </div>}
198
131
  </div>;
@@ -2,6 +2,7 @@ import type { CSSProperties, ClipboardEvent, ReactNode } from 'react';
2
2
  import React, { useCallback } from 'react';
3
3
  import { useNotisRuntime } from '../provider';
4
4
  import type { ContextResource, ContextSelection, NotisRuntime } from '../runtime';
5
+ import { newSelectionId } from './selectionId';
5
6
 
6
7
  export const NOTIS_CONTEXT_CLIPBOARD_TYPE = 'application/x-notis-context+json';
7
8
 
@@ -12,12 +13,6 @@ export interface NotisSelectionBoundaryProps {
12
13
  style?: CSSProperties;
13
14
  }
14
15
 
15
- function selectionId(): string {
16
- return typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
17
- ? crypto.randomUUID()
18
- : `selection-${Date.now()}-${Math.random().toString(36).slice(2)}`;
19
- }
20
-
21
16
  /** The selection's markup for other paste targets: hidden parts dropped, links made absolute. */
22
17
  function selectionHtml(selection: Selection): string {
23
18
  if (typeof document === 'undefined') return '';
@@ -61,7 +56,7 @@ export function addCopiedSelectionToClipboard(
61
56
  const text = wrotePlain || selection.toString();
62
57
  if (!text.trim()) return null;
63
58
 
64
- const payload: ContextSelection = { ...context, id: selectionId(), text };
59
+ const payload: ContextSelection = { ...context, id: newSelectionId(), text };
65
60
  if (!editorWrote) {
66
61
  // Keep the copied formatting (links, bold, tables) for every other paste target.
67
62
  const html = selectionHtml(selection);
@@ -132,7 +127,7 @@ export function citeSpaceSelection(runtime: Pick<NotisRuntime, 'contextSource' |
132
127
  const resource = quoteResourceFor(range);
133
128
  const source = runtime.contextSource;
134
129
  return runtime.addContext({
135
- id: selectionId(), text,
130
+ id: newSelectionId(), text,
136
131
  ...(resource ? { resource } : source ? { title: source.appName } : {}),
137
132
  });
138
133
  }
@@ -1,5 +1,6 @@
1
1
  'use client';
2
2
  import React, { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from 'react';
3
+ import { useToolkitLocale } from '../ui/engine/hooks';
3
4
  import type { Words } from '../words/types';
4
5
 
5
6
  /**
@@ -70,12 +71,48 @@ function isCoarsePointer(view: Window | null): boolean {
70
71
  return Boolean(view?.matchMedia?.('(pointer: coarse)').matches);
71
72
  }
72
73
 
74
+ // Where a selection may not start or end: fields, editable text and the bar itself.
73
75
  const EDITABLE = 'input,textarea,select,[contenteditable]:not([contenteditable="false"]),[data-notis-selection-ui]';
74
76
 
77
+ /** The live selection's ends, to tell when it moved away from what the bar shows. */
78
+ type Ends = { startContainer: Node; startOffset: number; endContainer: Node; endOffset: number };
79
+ function endsOf(range: Range): Ends {
80
+ return { startContainer: range.startContainer, startOffset: range.startOffset, endContainer: range.endContainer, endOffset: range.endOffset };
81
+ }
82
+ function sameEnds(a: Ends, b: Ends): boolean {
83
+ return a.startContainer === b.startContainer && a.startOffset === b.startOffset
84
+ && a.endContainer === b.endContainer && a.endOffset === b.endOffset;
85
+ }
86
+
75
87
  function elementOf(node: Node): Element | null {
76
88
  return node.nodeType === Node.ELEMENT_NODE ? node as Element : node.parentElement;
77
89
  }
78
90
 
91
+ function selectionIn(node: Node): Selection | null {
92
+ const scope = node.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null };
93
+ return scope.getSelection?.() || node.ownerDocument?.defaultView?.getSelection() || null;
94
+ }
95
+
96
+ /**
97
+ * The surface's box. A `display: contents` element draws none: its content's own box stands in when it draws one
98
+ * (a boundary given a className), else the nearest ancestor that does.
99
+ */
100
+ function boundsOf(node: HTMLElement): DOMRect {
101
+ let element: Element = node;
102
+ let box = element.getBoundingClientRect();
103
+ for (let depth = 0; !box.width && element.firstElementChild && depth < 8; depth += 1) {
104
+ const child = element.firstElementChild.getBoundingClientRect();
105
+ if (child.width) return child;
106
+ element = element.firstElementChild;
107
+ }
108
+ element = node;
109
+ while (!box.width && element.parentElement) {
110
+ element = element.parentElement;
111
+ box = element.getBoundingClientRect();
112
+ }
113
+ return box;
114
+ }
115
+
79
116
  export interface UseSelectionAnchorOptions {
80
117
  /** Off while the surface has nowhere to send a quote (a public Site, a chat that cannot send). */
81
118
  enabled?: boolean;
@@ -85,6 +122,8 @@ export interface UseSelectionAnchorOptions {
85
122
  clip?(range: Range, root: HTMLElement): Range | null;
86
123
  /** The bar's size, measured once it shows; used to keep it inside the viewport. */
87
124
  barSize?: { width: number; height: number };
125
+ /** More places a selection may not start or end in, on top of inputs and editable text (a CSS selector). */
126
+ exclude?: string;
88
127
  }
89
128
 
90
129
  /**
@@ -94,26 +133,35 @@ export interface UseSelectionAnchorOptions {
94
133
  export function useSelectionAnchor(root: RefObject<HTMLElement | null>, options: UseSelectionAnchorOptions = {}) {
95
134
  const { enabled = true } = options;
96
135
  const [anchor, setAnchor] = useState<SelectionAnchor | null>(null);
136
+ const anchorRef = useRef<SelectionAnchor | null>(null);
137
+ anchorRef.current = anchor;
97
138
  const optionsRef = useRef(options);
98
139
  optionsRef.current = options;
99
140
  const settle = useRef<number | undefined>(undefined);
141
+ const pending = useRef<number | undefined>(undefined);
142
+ // The live selection the shown bar was read from: a different one hides the bar until it is read again.
143
+ const shownEnds = useRef<Ends | null>(null);
100
144
 
101
145
  const read = useCallback((): SelectionAnchor | null => {
102
146
  const node = root.current;
103
147
  if (!node) return null;
104
- const scope = node.getRootNode() as ShadowRoot & { getSelection?: () => Selection | null };
105
148
  const view = node.ownerDocument.defaultView;
106
- const selection = scope.getSelection?.() || view?.getSelection();
149
+ const selection = selectionIn(node);
107
150
  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;
151
+ const live = selection.getRangeAt(0);
152
+ let range: Range | null = live.cloneRange();
153
+ const clipped = !node.contains(range.startContainer) || !node.contains(range.endContainer);
154
+ if (clipped) {
155
+ // A selection in another tree (the page around a Space's shadow root) cannot be compared with this one.
156
+ try { range = optionsRef.current.clip?.(range, node) ?? null; } catch { range = null; }
111
157
  if (!range) return null;
112
158
  }
113
159
  const start = elementOf(range.startContainer);
114
160
  const end = elementOf(range.endContainer);
115
- if (start?.closest(EDITABLE) || end?.closest(EDITABLE)) return null;
161
+ const excluded = optionsRef.current.exclude ? `${EDITABLE},${optionsRef.current.exclude}` : EDITABLE;
162
+ if (start?.closest(excluded) || end?.closest(excluded)) return null;
116
163
  if (optionsRef.current.accept && !optionsRef.current.accept(range, node)) return null;
164
+ // The range's own text: it is what the chat finds again when a quote link highlights the words.
117
165
  const text = range.toString().trim();
118
166
  if (!text) return null;
119
167
  const lines = Array.from(range.getClientRects?.() || []).filter(line => line.width > 0 && line.height > 0);
@@ -126,11 +174,12 @@ export function useSelectionAnchor(root: RefObject<HTMLElement | null>, options:
126
174
  remainder.setStart(range.endContainer, range.endOffset);
127
175
  if (remainder.toString().trim()) trailing.push(...Array.from(remainder.getClientRects?.() || []).filter(line => line.width > 0 && line.height > 0));
128
176
  }
129
- const bounds = node.getBoundingClientRect();
177
+ const bounds = boundsOf(node);
130
178
  const position = getSelectionBarPosition(lines.length ? lines : [rect],
131
179
  { width: view?.innerWidth ?? 1024, height: view?.innerHeight ?? 768 },
132
180
  optionsRef.current.barSize ?? { width: 80, height: 32 },
133
181
  { rightBoundary: bounds.width ? bounds.right : undefined, trailing, coarse: isCoarsePointer(view) });
182
+ shownEnds.current = endsOf(live);
134
183
  return { ...position, text, range };
135
184
  }, [root]);
136
185
 
@@ -139,7 +188,12 @@ export function useSelectionAnchor(root: RefObject<HTMLElement | null>, options:
139
188
  // The bar measured itself: place it again with its real width, so its edge lines up with the selection.
140
189
  const barWidth = options.barSize?.width;
141
190
  const barHeight = options.barSize?.height;
142
- useEffect(() => { setAnchor(current => current ? read() : current); }, [barWidth, barHeight, read]);
191
+ useEffect(() => {
192
+ // Read here, not inside the state updater: React may run an updater lazily or twice.
193
+ if (!anchorRef.current) return;
194
+ const next = read();
195
+ setAnchor(current => current ? next : current);
196
+ }, [barWidth, barHeight, read]);
143
197
 
144
198
  useEffect(() => {
145
199
  const node = root.current;
@@ -147,37 +201,61 @@ export function useSelectionAnchor(root: RefObject<HTMLElement | null>, options:
147
201
  const document = node.ownerDocument;
148
202
  const view = document.defaultView;
149
203
  const scope = node.getRootNode() as ShadowRoot | Document;
204
+ // Cheap checks only while the selection moves: no layout until it is read again.
205
+ const liveSelection = () => {
206
+ const selection = selectionIn(node);
207
+ const inside = (point: Node | null | undefined) => Boolean(point && node.contains(point));
208
+ if (!selection?.rangeCount || selection.isCollapsed || !(inside(selection.anchorNode) || inside(selection.focusNode))) return null;
209
+ return selection;
210
+ };
150
211
  const capture = (event: Event) => {
151
212
  if (event.target instanceof Element && event.target.closest('[data-notis-selection-ui]')) return;
152
213
  // Let the browser finish the selection (a double click selects the word after mouseup).
153
- view?.setTimeout(() => setAnchor(read()), 0);
214
+ view?.clearTimeout(pending.current);
215
+ pending.current = view?.setTimeout(() => setAnchor(read()), 0);
154
216
  };
217
+ // Keys go to the focused element (often the page body), so a keyboard selection is followed on the document.
155
218
  const onKeyUp = (event: KeyboardEvent) => {
156
- if (event.shiftKey || event.key === 'Shift' || ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'a')) capture(event);
219
+ if (!(event.shiftKey || event.key === 'Shift' || ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'a'))) return;
220
+ // Only a selection touching this surface (or a bar it shows) is worth reading: typing capitals elsewhere is not.
221
+ if (!liveSelection() && !anchorRef.current) return;
222
+ capture(event);
157
223
  };
158
224
  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);
225
+ if (!isCoarsePointer(view)) {
226
+ // A mouse or keyboard selection shows the bar when it ends (mouse up, key up). While it moves, the bar hides
227
+ // as soon as the selection is gone or is no longer the one the bar was read from (a clipped one included).
228
+ const current = selectionIn(node);
229
+ const moved = !current?.rangeCount || current.isCollapsed || !shownEnds.current
230
+ || !sameEnds(endsOf(current.getRangeAt(0)), shownEnds.current);
231
+ if (moved) setAnchor(shown => shown ? null : shown);
232
+ return;
166
233
  }
234
+ const selection = liveSelection();
235
+ // A touch selection has no mouse up: show the bar once its handles stop moving.
236
+ view?.clearTimeout(settle.current);
237
+ setAnchor(current => current ? null : current);
238
+ if (!selection) return;
239
+ settle.current = view?.setTimeout(() => setAnchor(read()), 450);
240
+ };
241
+ const onScroll = () => {
242
+ if (!anchorRef.current) return;
243
+ const next = read();
244
+ setAnchor(current => current ? next : current);
167
245
  };
168
- const onScroll = () => setAnchor(current => current ? read() : current);
169
246
  node.addEventListener('mouseup', capture);
170
247
  node.addEventListener('dblclick', capture);
171
- node.addEventListener('keyup', onKeyUp);
248
+ document.addEventListener('keyup', onKeyUp);
172
249
  document.addEventListener('selectionchange', onSelectionChange);
173
250
  if (scope !== document) scope.addEventListener('selectionchange', onSelectionChange);
174
251
  view?.addEventListener('scroll', onScroll, true);
175
252
  view?.addEventListener('resize', onScroll);
176
253
  return () => {
177
254
  view?.clearTimeout(settle.current);
255
+ view?.clearTimeout(pending.current);
178
256
  node.removeEventListener('mouseup', capture);
179
257
  node.removeEventListener('dblclick', capture);
180
- node.removeEventListener('keyup', onKeyUp);
258
+ document.removeEventListener('keyup', onKeyUp);
181
259
  document.removeEventListener('selectionchange', onSelectionChange);
182
260
  if (scope !== document) scope.removeEventListener('selectionchange', onSelectionChange);
183
261
  view?.removeEventListener('scroll', onScroll, true);
@@ -190,9 +268,52 @@ export function useSelectionAnchor(root: RefObject<HTMLElement | null>, options:
190
268
 
191
269
  /** Clears the page's selection once its text was cited, so the bar does not linger over it. */
192
270
  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();
271
+ if (node) selectionIn(node)?.removeAllRanges();
272
+ }
273
+
274
+ /**
275
+ * The Cite action of a selection bar: the same words and glyph everywhere; it clears the selection and hides the bar
276
+ * before handing over the cited text.
277
+ */
278
+ export function citeSelectionAction(locale: keyof typeof SELECTION_BAR_WORDS.cite, anchor: SelectionAnchor,
279
+ root: RefObject<HTMLElement | null>, dismiss: () => void, onCite: (range: Range, text: string) => void): SelectionBarAction {
280
+ return {
281
+ key: 'cite', label: SELECTION_BAR_WORDS.cite[locale], title: SELECTION_BAR_WORDS.citeHint[locale], icon: QUOTE_GLYPH,
282
+ onSelect: () => {
283
+ const { range, text } = anchor;
284
+ clearSelectionIn(root.current);
285
+ dismiss();
286
+ onCite(range, text);
287
+ },
288
+ };
289
+ }
290
+
291
+ export interface CiteSelectionBarProps {
292
+ /** The surface whose selected text Cite quotes. */
293
+ root: RefObject<HTMLElement | null>;
294
+ /** Receives the cited text once the bar has cleared the selection. */
295
+ onCite(range: Range, text: string): void;
296
+ enabled?: boolean;
297
+ accept?: UseSelectionAnchorOptions['accept'];
298
+ /**
299
+ * Draws the bar somewhere other than beside the surface. The Portal's own pages hand the bar to a React portal on
300
+ * the page body, out of a container that clips or transforms it. A Space view never gives one: a Notis app stays
301
+ * inside its app surface, so its bar is drawn there, fixed to the viewport.
302
+ */
303
+ portal?(bar: ReactNode): ReactNode;
304
+ }
305
+
306
+ /**
307
+ * The Cite-only bar every quoting surface shows (chat, Space views, Skills and automations; truth PRT-087): it follows
308
+ * the selection in `root`, measures itself, and hands the cited text to `onCite`.
309
+ */
310
+ export function CiteSelectionBar({ root, onCite, enabled = true, accept, portal }: CiteSelectionBarProps) {
311
+ const locale = useToolkitLocale();
312
+ const [barSize, setBarSize] = useState({ width: 72, height: 32 });
313
+ const { anchor, dismiss } = useSelectionAnchor(root, { enabled, accept, barSize });
314
+ if (!anchor) return null;
315
+ const bar = <SelectionActionBar anchor={anchor} onSize={setBarSize} actions={[citeSelectionAction(locale, anchor, root, dismiss, onCite)]} />;
316
+ return portal ? portal(bar) : bar;
196
317
  }
197
318
 
198
319
  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>;
@@ -0,0 +1,6 @@
1
+ /** A fresh id for a quote or a comment taken from the selection. */
2
+ export function newSelectionId(): string {
3
+ return typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
4
+ ? crypto.randomUUID()
5
+ : `selection-${Date.now()}-${Math.random().toString(36).slice(2)}`;
6
+ }
@@ -205,6 +205,11 @@ export interface NotisRuntimeContext {
205
205
  resourceId?: string | null;
206
206
  /** Loading bones measured from this release at build time; `ViewSkeleton` draws them. Absent until the host has them. */
207
207
  readonly skeleton?: NotisSpaceSkeleton;
208
+ /**
209
+ * The signed-in viewer's first name, for signing what they write (comments). Display only, never an identity
210
+ * or a permission. Absent for visitors of a Site or a link, and on hosts that predate it.
211
+ */
212
+ readonly viewerName?: string | null;
208
213
  }
209
214
 
210
215
  // ---------------------------------------------------------------------------