@notis_ai/cli 0.2.32 → 0.2.34

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 (95) hide show
  1. package/README.md +75 -11
  2. package/dist/agent-hooks/notis-agent-hook.mjs +4407 -905
  3. package/dist/base-skills/notis-cli/.notis-base-skill.json +1 -1
  4. package/dist/base-skills/notis-cli/SKILL.md +7 -3
  5. package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
  6. package/dist/base-skills/notis-spaces/SKILL.md +5 -3
  7. package/dist/base-skills/notis-spaces/references/comments.md +102 -0
  8. package/dist/base-skills/notis-spaces/references/context.md +20 -19
  9. package/dist/base-skills/notis-spaces/references/design.md +3 -2
  10. package/dist/base-skills/notis-spaces/references/sdk.md +135 -83
  11. package/dist/base-skills/notis-spaces/references/store.md +24 -1
  12. package/dist/sdk/src/components/NotisSelectionBoundary.tsx +13 -5
  13. package/dist/sdk/src/components/SelectionActionBar.tsx +45 -8
  14. package/dist/sdk/src/components/SpaceTextComments.tsx +293 -0
  15. package/dist/sdk/src/components/selectionRange.ts +65 -0
  16. package/dist/sdk/src/config.ts +3 -1
  17. package/dist/sdk/src/functions.ts +218 -0
  18. package/dist/sdk/src/hooks/useAgentQueue.ts +17 -28
  19. package/dist/sdk/src/hooks/useCollectionInteractions.ts +66 -9
  20. package/dist/sdk/src/hooks/useConnection.ts +102 -0
  21. package/dist/sdk/src/hooks/useFunction.ts +42 -0
  22. package/dist/sdk/src/hooks/useNotisSettings.ts +101 -0
  23. package/dist/sdk/src/index.ts +16 -4
  24. package/dist/sdk/src/interactions/shortcuts.tsx +6 -1
  25. package/dist/sdk/src/interactions/swipeDownToDismiss.ts +158 -0
  26. package/dist/sdk/src/interactions/textBoxTwoState.ts +174 -0
  27. package/dist/sdk/src/interactions.ts +17 -0
  28. package/dist/sdk/src/runtime.ts +16 -1
  29. package/dist/sdk/src/space.ts +401 -33
  30. package/dist/sdk/src/ui/comments/passageModel.ts +99 -0
  31. package/dist/sdk/src/ui/comments/textHighlights.ts +33 -0
  32. package/dist/skill-sync/index.js +262 -31
  33. package/dist/skill-sync-worker.mjs +515 -127
  34. package/dist/space-harness/host.js +389 -154
  35. package/dist/space-sdk/dist/chunk-3NPBCE6E.js +3 -0
  36. package/dist/space-sdk/dist/index.js +3 -3
  37. package/dist/space-sdk/dist/ui.js +16 -11
  38. package/dist/space-sdk/src/config.ts +3 -1
  39. package/dist/space-sdk/src/functions.ts +218 -0
  40. package/dist/space-sdk/src/hooks/useAgentQueue.d.ts +2 -13
  41. package/dist/space-sdk/src/hooks/useCollectionInteractions.d.ts +7 -0
  42. package/dist/space-sdk/src/hooks/useConnection.d.ts +42 -0
  43. package/dist/space-sdk/src/hooks/useFunction.d.ts +20 -0
  44. package/dist/space-sdk/src/hooks/useNotisSettings.d.ts +48 -0
  45. package/dist/space-sdk/src/index.d.ts +10 -4
  46. package/dist/space-sdk/src/interactions/shortcuts.d.ts +5 -0
  47. package/dist/space-sdk/src/runtime.d.ts +14 -1
  48. package/dist/space-sdk/src/space.ts +401 -33
  49. package/dist/space-sdk/src/tailwind-candidates.d.ts +400 -204
  50. package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +90 -15
  51. package/dist/space-sdk/src/ui/comments/PassageComments.d.ts +4 -1
  52. package/dist/space-sdk/src/ui/comments/agentRuntime.d.ts +4 -2
  53. package/dist/space-sdk/src/ui/comments/commentDrafts.d.ts +63 -0
  54. package/dist/space-sdk/src/ui/comments/commentModel.d.ts +59 -88
  55. package/dist/space-sdk/src/ui/comments/commentWords.d.ts +32 -1
  56. package/dist/space-sdk/src/ui/comments/handover.d.ts +34 -0
  57. package/dist/space-sdk/src/ui/comments/hostComments.d.ts +13 -9
  58. package/dist/space-sdk/src/ui/comments/hostPanel.d.ts +113 -0
  59. package/dist/space-sdk/src/ui/comments/index.d.ts +7 -2
  60. package/dist/space-sdk/src/ui/comments/paneOutlet.d.ts +33 -0
  61. package/dist/space-sdk/src/ui/comments/paneParts.d.ts +71 -27
  62. package/dist/space-sdk/src/ui/comments/passageModel.d.ts +12 -36
  63. package/dist/space-sdk/src/ui/comments/reviewRun.d.ts +190 -0
  64. package/dist/space-sdk/src/ui/comments/useCommentRouting.d.ts +26 -4
  65. package/dist/space-sdk/src/ui/comments/useComments.d.ts +116 -77
  66. package/dist/space-sdk/src/ui/comments/usePassageComments.d.ts +8 -4
  67. package/dist/space-sdk/src/ui/index.d.ts +1 -1
  68. package/dist/space-sdk/src/ui/layout/SidePane.d.ts +3 -4
  69. package/dist/space-sdk/src/ui/period/dateFormat.d.ts +27 -8
  70. package/dist/view-renderer/dist/host.js +450 -215
  71. package/package.json +3 -3
  72. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +2 -2
  73. package/skills/notis-spaces/cli.md +3 -3
  74. package/src/cli.js +2 -1
  75. package/src/command-specs/index.js +3 -0
  76. package/src/command-specs/repository-secrets.js +171 -0
  77. package/src/command-specs/spaces.js +3 -3
  78. package/src/runtime/agent-credential.js +175 -0
  79. package/src/runtime/agent-identity.js +95 -19
  80. package/src/runtime/app-platform.js +8 -0
  81. package/src/runtime/auth-recovery.js +14 -0
  82. package/src/runtime/profiles.js +74 -2
  83. package/src/runtime/skill-sync/cloud-client.ts +33 -3
  84. package/src/runtime/skill-sync/index.ts +4 -3
  85. package/src/runtime/skill-sync/symlink-manager.ts +354 -35
  86. package/src/runtime/skill-sync/types.ts +14 -2
  87. package/src/runtime/space-functions.js +213 -0
  88. package/src/runtime/space-platform.js +12 -3
  89. package/src/runtime/space-source.js +116 -13
  90. package/src/runtime/space-test-server.js +22 -4
  91. package/src/runtime/space-verification.js +3 -1
  92. package/src/runtime/transport.js +15 -0
  93. package/dist/sdk/src/components/NotisCommentBoundary.tsx +0 -132
  94. package/dist/space-sdk/dist/chunk-I4Z4UFGB.js +0 -3
  95. package/dist/space-sdk/src/components/NotisCommentBoundary.d.ts +0 -26
@@ -2,6 +2,7 @@
2
2
  import React, { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from 'react';
3
3
  import { useToolkitLocale } from '../ui/engine/hooks';
4
4
  import type { Words } from '../words/types';
5
+ import { trimRange } from './selectionRange';
5
6
 
6
7
  /**
7
8
  * The floating bar on selected text (truths PRT-087, PRT-090, PRT-094): one dark labelled pill at the end of the
@@ -149,7 +150,8 @@ export function useSelectionAnchor(root: RefObject<HTMLElement | null>, options:
149
150
  const selection = selectionIn(node);
150
151
  if (!selection?.rangeCount || selection.isCollapsed || !selection.toString().trim()) return null;
151
152
  const live = selection.getRangeAt(0);
152
- let range: Range | null = live.cloneRange();
153
+ // A paragraph selection ends at the next block's start, often outside the surface: read it up to its last word.
154
+ let range: Range | null = trimRange(live.cloneRange());
153
155
  const clipped = !node.contains(range.startContainer) || !node.contains(range.endContainer);
154
156
  if (clipped) {
155
157
  // A selection in another tree (the page around a Space's shadow root) cannot be compared with this one.
@@ -293,6 +295,15 @@ export interface CiteSelectionBarProps {
293
295
  root: RefObject<HTMLElement | null>;
294
296
  /** Receives the cited text once the bar has cleared the selection. */
295
297
  onCite(range: Range, text: string): void;
298
+ /** False hides Cite (a surface with nowhere to send a quote). Default true. */
299
+ cite?: boolean;
300
+ /**
301
+ * Adds Comment after Cite (a Space page while the host takes comments): receives the selected range and text once
302
+ * the bar has cleared the selection.
303
+ */
304
+ onComment?(range: Range, text: string): void;
305
+ /** Whether this selection may be commented on with the bar's Comment (default: any it shows for). */
306
+ canComment?(range: Range): boolean;
296
307
  enabled?: boolean;
297
308
  accept?: UseSelectionAnchorOptions['accept'];
298
309
  /**
@@ -304,15 +315,39 @@ export interface CiteSelectionBarProps {
304
315
  }
305
316
 
306
317
  /**
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`.
318
+ * The Comment action of a selection bar: the same words and glyph everywhere; it clears the selection and hides the
319
+ * bar before handing over the selected range and text.
320
+ */
321
+ export function commentSelectionAction(locale: keyof typeof SELECTION_BAR_WORDS.comment, anchor: SelectionAnchor,
322
+ root: RefObject<HTMLElement | null>, dismiss: () => void, onComment: (range: Range, text: string) => void): SelectionBarAction {
323
+ return {
324
+ key: 'comment', label: SELECTION_BAR_WORDS.comment[locale], icon: COMMENT_GLYPH,
325
+ onSelect: () => {
326
+ const { range, text } = anchor;
327
+ clearSelectionIn(root.current);
328
+ dismiss();
329
+ onComment(range, text);
330
+ },
331
+ };
332
+ }
333
+
334
+ /**
335
+ * The bar every quoting surface shows (chat, Space views, Skills and automations; truth PRT-087): it follows the
336
+ * selection in `root`, measures itself, and hands the cited text to `onCite`. With `onComment` (a Space page while the
337
+ * host takes comments) it also offers Comment.
309
338
  */
310
- export function CiteSelectionBar({ root, onCite, enabled = true, accept, portal }: CiteSelectionBarProps) {
339
+ export function CiteSelectionBar({ root, onCite, cite = true, onComment, canComment, enabled = true, accept, portal }: CiteSelectionBarProps) {
311
340
  const locale = useToolkitLocale();
312
341
  const [barSize, setBarSize] = useState({ width: 72, height: 32 });
313
- const { anchor, dismiss } = useSelectionAnchor(root, { enabled, accept, barSize });
342
+ const { anchor, dismiss } = useSelectionAnchor(root, { enabled: enabled && (cite || Boolean(onComment)), accept, barSize });
314
343
  if (!anchor) return null;
315
- const bar = <SelectionActionBar anchor={anchor} onSize={setBarSize} actions={[citeSelectionAction(locale, anchor, root, dismiss, onCite)]} />;
344
+ const actions: SelectionBarAction[] = [];
345
+ if (cite) actions.push(citeSelectionAction(locale, anchor, root, dismiss, onCite));
346
+ if (onComment && (!canComment || canComment(anchor.range))) {
347
+ actions.push(commentSelectionAction(locale, anchor, root, dismiss, onComment));
348
+ }
349
+ if (!actions.length) return null;
350
+ const bar = <SelectionActionBar anchor={anchor} onSize={setBarSize} actions={actions} />;
316
351
  return portal ? portal(bar) : bar;
317
352
  }
318
353
 
@@ -336,8 +371,10 @@ export function SelectionActionBar({ anchor, actions, onSize }: {
336
371
  onSize?(size: { width: number; height: number }): void;
337
372
  }) {
338
373
  const bar = useRef<HTMLDivElement>(null);
339
- const first = useRef(actions[0]);
340
- first.current = actions[0];
374
+ // The Cite key cites: never another action (a bar without Cite ignores it).
375
+ const citeAction = actions.find(action => action.key === 'cite') ?? (actions[0]?.key === 'comment' ? undefined : actions[0]);
376
+ const first = useRef(citeAction);
377
+ first.current = citeAction;
341
378
  const [left, setLeft] = useState(anchor.left);
342
379
  // A finger needs a bigger target than the 26 px a pointer gets.
343
380
  const coarse = typeof window !== 'undefined' && isCoarsePointer(window);
@@ -0,0 +1,293 @@
1
+ 'use client';
2
+ /**
3
+ * Text comments on every Space page (SPC-118 text mode): Comment on selected words (the shared selection bar, next to
4
+ * Cite) and the highlights of the page's open text comments. Both need the host comment store
5
+ * (`runtime.spaceComments`); without it the page shows Cite alone and no highlights.
6
+ *
7
+ * A text comment keeps its words with up to 40 characters before and after them. The highlights find those words
8
+ * again in the page as it is now (white space ignored, the surrounding words telling apart several matches); words
9
+ * that are gone are reported to the host (`passagesChanged`) and the thread card reads Passage changed. A thread is
10
+ * never closed for it. A click on a highlight opens its thread in the host Comments panel (`revealComment`).
11
+ *
12
+ * Words inside a Space's own commentable text (`CommentableText`, `CommentableRichText`) keep their own Comment button
13
+ * and their own highlights: the page bar offers Cite alone there, and comments on a named field are not drawn here.
14
+ */
15
+
16
+ import { useEffect, useId, useMemo, useRef, useState, type RefObject } from 'react';
17
+ import type { NotisRuntime } from '../runtime';
18
+ import type { SpaceCommentAnchor, SpaceCommentRow, SpaceCommentsTransport } from '../space';
19
+ import { PASSAGE_COMMENT_EVENT, locatePassage, passageAt } from '../ui/comments/passageModel';
20
+ import { setChangedPassages } from '../ui/comments/textHighlights';
21
+
22
+ /** Text a passage is never read from: styles, scripts and the selection bar. */
23
+ const SKIP_TEXT = 'style, script, noscript, template, [data-notis-selection-ui], [data-notis-comment-skip]';
24
+ /** A Space's own commentable text: it has its own Comment button and highlights. */
25
+ export const OWN_PASSAGE_TEXT = '.nui-passage-text-field, .nui-passage-rich-text';
26
+ /** A Space's own commentable rich text: the page's selection bar offers Comment on it (SPC-487). */
27
+ const OWN_RICH_TEXT = '.nui-passage-rich-text';
28
+
29
+ export interface PageText { text: string; nodes: Array<{ node: Text; start: number }> }
30
+
31
+ /** The text of a page, in reading order, with where each text node starts in it. */
32
+ export function pageTextOf(root: Node): PageText {
33
+ const owner = root.ownerDocument ?? (root as Document);
34
+ const walker = owner.createTreeWalker(root, 4 /* NodeFilter.SHOW_TEXT */);
35
+ const nodes: PageText['nodes'] = [];
36
+ let text = '';
37
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
38
+ const parent = (node as Text).parentElement;
39
+ if (parent?.closest(SKIP_TEXT)) continue;
40
+ nodes.push({ node: node as Text, start: text.length });
41
+ text += (node as Text).data;
42
+ }
43
+ return { text, nodes };
44
+ }
45
+
46
+ /** Where a range boundary falls in the page text. */
47
+ function offsetOf(page: PageText, container: Node, offset: number): number {
48
+ if (container.nodeType === 3) {
49
+ const hit = page.nodes.find(item => item.node === container);
50
+ if (hit) return hit.start + Math.min(offset, hit.node.data.length);
51
+ }
52
+ const owner = container.ownerDocument ?? (container as Document);
53
+ const point = owner.createRange();
54
+ try {
55
+ point.setStart(container, offset);
56
+ point.collapse(true);
57
+ } catch {
58
+ return page.text.length;
59
+ }
60
+ // The first text node at or after the boundary starts there; none: the end of the text.
61
+ for (const item of page.nodes) {
62
+ try {
63
+ if (point.comparePoint(item.node, 0) >= 0) return item.start;
64
+ } catch { /* another tree */ }
65
+ }
66
+ return page.text.length;
67
+ }
68
+
69
+ /**
70
+ * A text comment's place for the selected `range` of `root`: the selected words (white space collapsed, at most 1000
71
+ * characters) with up to 40 characters before and after them. Null when only white space is selected.
72
+ */
73
+ export function textCommentAnchor(root: Node, range: Range): SpaceCommentAnchor | null {
74
+ const page = pageTextOf(root);
75
+ const start = offsetOf(page, range.startContainer, range.startOffset);
76
+ const end = offsetOf(page, range.endContainer, range.endOffset);
77
+ if (end <= start) return null;
78
+ const passage = passageAt(page.text, start, end);
79
+ return passage ? { mode: 'text', quote: passage.quote, prefix: passage.prefix, suffix: passage.suffix } : null;
80
+ }
81
+
82
+ /** The page's open text comments drawn here: first comments in text mode on no named field, of this view. */
83
+ export function openTextComments(rows: readonly SpaceCommentRow[], view: string | null): SpaceCommentRow[] {
84
+ return rows.filter(row => row && !row.thread_root_id && row.mode === 'text' && row.status === 'open' && !row.field
85
+ && Boolean(row.quote?.trim()) && (!row.view || !view || row.view === view));
86
+ }
87
+
88
+ function lastNode(page: PageText, test: (item: PageText['nodes'][number]) => boolean): PageText['nodes'][number] | undefined {
89
+ for (let index = page.nodes.length - 1; index >= 0; index -= 1) if (test(page.nodes[index]!)) return page.nodes[index];
90
+ return undefined;
91
+ }
92
+
93
+ /** The ranges of each comment's words in the page, and the comments whose words are gone. */
94
+ export function locateTextComments(root: Node, rows: readonly SpaceCommentRow[]): { found: Map<string, Range>; missing: string[] } {
95
+ const page = pageTextOf(root);
96
+ const found = new Map<string, Range>();
97
+ const missing: string[] = [];
98
+ const owner = root.ownerDocument ?? (root as Document);
99
+ for (const row of rows) {
100
+ const hit = locatePassage(page.text, { quote: row.quote ?? '', prefix: row.prefix ?? '', suffix: row.suffix ?? '' });
101
+ if (!hit) { missing.push(row.id); continue; }
102
+ const from = lastNode(page, item => item.start <= hit.start);
103
+ const to = lastNode(page, item => item.start < hit.end);
104
+ if (!from || !to) { missing.push(row.id); continue; }
105
+ const range = owner.createRange();
106
+ try {
107
+ range.setStart(from.node, Math.min(hit.start - from.start, from.node.data.length));
108
+ range.setEnd(to.node, Math.min(hit.end - to.start, to.node.data.length));
109
+ found.set(row.id, range);
110
+ } catch {
111
+ missing.push(row.id);
112
+ }
113
+ }
114
+ return { found, missing };
115
+ }
116
+
117
+ /** The CSS Custom Highlight registry, where the browser has one. */
118
+ type HighlightRegistry = { set(name: string, value: unknown): void; delete(name: string): boolean };
119
+ function highlightApi(view: Window | null | undefined): { registry: HighlightRegistry; Highlight: new (...ranges: Range[]) => unknown } | null {
120
+ const css = (view as unknown as { CSS?: { highlights?: HighlightRegistry } } | null)?.CSS;
121
+ const Highlight = (view as unknown as { Highlight?: new (...ranges: Range[]) => unknown } | null)?.Highlight;
122
+ return css?.highlights && Highlight ? { registry: css.highlights, Highlight } : null;
123
+ }
124
+
125
+ /**
126
+ * The open text comments of the page the host shows, read through the comment store and listed again whenever the
127
+ * host says they may have changed.
128
+ */
129
+ function usePageTextComments(transport: SpaceCommentsTransport | undefined): SpaceCommentRow[] {
130
+ const page = transport?.page?.recordKey ?? null;
131
+ const view = transport?.page?.view ?? null;
132
+ const [rows, setRows] = useState<SpaceCommentRow[]>([]);
133
+ const transportRef = useRef(transport);
134
+ transportRef.current = transport;
135
+ const hasTransport = Boolean(transport);
136
+ useEffect(() => {
137
+ const store = transportRef.current;
138
+ if (!store) { setRows([]); return undefined; }
139
+ let live = true;
140
+ let seq = 0;
141
+ // The Space home: its open comments are among the Space's open threads, which the home's pane reads by thread
142
+ // (`threads`). The highlights read that same copy, never every comment of the home (Done and deleted ones too).
143
+ // A host without that read, or whose server cannot answer it (null), lists the home as before.
144
+ let byThread = page === null && typeof store.threads === 'function';
145
+ const list = (mine: number) => store.list({ page }).then(answer => {
146
+ if (live && mine === seq) setRows(Array.isArray(answer?.comments) ? answer.comments : []);
147
+ }, () => undefined);
148
+ const read = () => {
149
+ const mine = ++seq;
150
+ if (!byThread || !store.threads) { void list(mine); return; }
151
+ store.threads({}).then(answer => {
152
+ if (!answer) { byThread = false; void list(mine); return; }
153
+ if (live && mine === seq) setRows((Array.isArray(answer.comments) ? answer.comments : []).filter(row => row.page_key == null));
154
+ }, () => undefined);
155
+ };
156
+ // The first read waits for the page to go idle: a Space open never contends with the highlights' read and drawing
157
+ // (SPC-859). A change the host announces reads at once.
158
+ const idleWindow = typeof window !== 'undefined' && typeof window.requestIdleCallback === 'function'
159
+ && typeof window.cancelIdleCallback === 'function' ? window : null;
160
+ const cancelIdle = idleWindow?.cancelIdleCallback;
161
+ const idleRead = idleWindow ? idleWindow.requestIdleCallback(read, { timeout: 1500 }) : null;
162
+ const timer = idleWindow ? null : setTimeout(read, 0);
163
+ let stop: (() => void) | undefined;
164
+ try { stop = store.subscribe({ page: byThread ? 'all' : page }, read); } catch { /* no live feed */ }
165
+ return () => {
166
+ live = false;
167
+ if (idleRead !== null) cancelIdle?.call(idleWindow, idleRead);
168
+ if (timer !== null) clearTimeout(timer);
169
+ stop?.();
170
+ };
171
+ }, [hasTransport, page]);
172
+ return useMemo(() => openTextComments(rows, view), [rows, view]);
173
+ }
174
+
175
+ /**
176
+ * Draws the page's open text comments as highlights in `root`, reports the ones whose words are gone, and opens a
177
+ * thread when its highlight is clicked. Renders only its highlight style.
178
+ */
179
+ export function SpaceTextComments({ root, runtime }: { root: RefObject<HTMLElement | null>; runtime: NotisRuntime }) {
180
+ const transport = runtime.spaceComments;
181
+ const rows = usePageTextComments(transport);
182
+ const name = `notis-comment-${useId().replace(/[^a-zA-Z0-9_-]/g, '')}`;
183
+ const located = useRef<Map<string, Range>>(new Map());
184
+ const transportRef = useRef(transport);
185
+ transportRef.current = transport;
186
+ const page = transport?.page?.recordKey ?? null;
187
+
188
+ useEffect(() => {
189
+ const element = root.current;
190
+ if (!element || !transport) return undefined;
191
+ const view = element.ownerDocument.defaultView;
192
+ const api = highlightApi(view);
193
+ let frame = 0;
194
+ let reported = '';
195
+ const draw = () => {
196
+ frame = 0;
197
+ const { found, missing } = locateTextComments(element, rows);
198
+ located.current = found;
199
+ if (api) {
200
+ if (found.size) api.registry.set(name, new api.Highlight(...found.values()));
201
+ else api.registry.delete(name);
202
+ }
203
+ setChangedPassages(missing);
204
+ const key = [...missing].sort().join('|');
205
+ if (key !== reported) {
206
+ reported = key;
207
+ try { transportRef.current?.passagesChanged?.({ page, ids: missing }); } catch { /* the host may not listen */ }
208
+ }
209
+ };
210
+ draw();
211
+ // The page changes under the comments (an edit, a page of results): find the words again once per frame.
212
+ const Observer = view?.MutationObserver;
213
+ const observer = Observer ? new Observer(() => {
214
+ if (!frame) frame = view?.requestAnimationFrame?.(draw) ?? 0;
215
+ if (!frame) draw();
216
+ }) : null;
217
+ observer?.observe(element, { childList: true, subtree: true, characterData: true });
218
+ return () => {
219
+ observer?.disconnect();
220
+ if (frame) view?.cancelAnimationFrame?.(frame);
221
+ api?.registry.delete(name);
222
+ located.current = new Map();
223
+ };
224
+ }, [root, transport, rows, name, page]);
225
+
226
+ // A click on highlighted words (not the end of a selection) opens their thread in the host Comments panel.
227
+ useEffect(() => {
228
+ const element = root.current;
229
+ if (!element || !transport?.revealComment) return undefined;
230
+ const onClick = (event: MouseEvent) => {
231
+ if (event.button !== 0 || event.defaultPrevented) return;
232
+ const selection = element.ownerDocument.getSelection?.();
233
+ if (selection && !selection.isCollapsed) return;
234
+ for (const [id, range] of located.current) {
235
+ const hit = Array.from(range.getClientRects?.() ?? []).some(rect => event.clientX >= rect.left
236
+ && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom);
237
+ if (hit) { transportRef.current?.revealComment?.(id); return; }
238
+ }
239
+ };
240
+ element.addEventListener('click', onClick);
241
+ return () => element.removeEventListener('click', onClick);
242
+ }, [root, transport]);
243
+
244
+ if (!transport || !rows.length) return null;
245
+ // Theme tokens only: the page's primary color, see-through.
246
+ return <style data-notis-comment-highlights>{`::highlight(${name}) { background-color: hsl(var(--primary) / .18); }`}</style>;
247
+ }
248
+
249
+ /** The Space's own commentable text a selection lies in, if any. */
250
+ function ownTextOf(range: Range): Element | null {
251
+ const container = range.commonAncestorContainer;
252
+ const element = container.nodeType === 1 ? container as Element : container.parentElement;
253
+ return element?.closest(OWN_PASSAGE_TEXT) ?? null;
254
+ }
255
+
256
+ /**
257
+ * Whether the bar's Comment may start a comment on this selection: page text, and a Space's own commentable rich text
258
+ * (the bar hands it the selection, SPC-487), never a text field (its own Comment button stays).
259
+ */
260
+ export function canCommentOnPage(range: Range): boolean {
261
+ const own = ownTextOf(range);
262
+ return !own || own.matches(OWN_RICH_TEXT);
263
+ }
264
+
265
+ /**
266
+ * The bar's Comment on a selection: inside a Space's own commentable rich text that text starts its own new comment
267
+ * on the words; elsewhere the host's new text comment opens on them. False when nothing took it.
268
+ */
269
+ export function commentOnSelection(runtime: NotisRuntime, root: Node | null, range: Range): boolean {
270
+ const own = ownTextOf(range);
271
+ if (own) {
272
+ if (!own.matches(OWN_RICH_TEXT)) return false;
273
+ const view = own.ownerDocument?.defaultView;
274
+ const Custom = view?.CustomEvent ?? CustomEvent;
275
+ // Cancelled by the text once it opened the comment.
276
+ return !own.dispatchEvent(new Custom(PASSAGE_COMMENT_EVENT, { detail: { range }, cancelable: true }));
277
+ }
278
+ return startTextComment(runtime, root, range);
279
+ }
280
+
281
+ /** Hands a selection to the host's new text comment. False when there is nothing to comment on or no host for it. */
282
+ export function startTextComment(runtime: NotisRuntime, root: Node | null, range: Range): boolean {
283
+ const transport = runtime.spaceComments;
284
+ if (!transport?.startComment || !root) return false;
285
+ const anchor = textCommentAnchor(root, range);
286
+ if (!anchor) return false;
287
+ transport.startComment({
288
+ ...anchor,
289
+ page_key: transport.page?.recordKey ?? null,
290
+ view: transport.page?.view ?? null,
291
+ });
292
+ return true;
293
+ }
@@ -0,0 +1,65 @@
1
+ // Node and NodeFilter constants, without their globals (absent from some test and frame realms).
2
+ const TEXT_NODE = 3;
3
+ const SHOW_TEXT = 0x4;
4
+ // Text nobody reads as selected words: code, styles and the selection bar's own labels.
5
+ const UNREAD = 'script,style,noscript,template,[data-notis-selection-ui]';
6
+
7
+ function isText(node: Node): node is Text {
8
+ return node.nodeType === TEXT_NODE;
9
+ }
10
+
11
+ function blankBefore(text: string, end: number): number {
12
+ let index = end;
13
+ while (index > 0 && /\s/.test(text[index - 1]!)) index -= 1;
14
+ return index;
15
+ }
16
+
17
+ function blankAfter(text: string, start: number): number {
18
+ let index = start;
19
+ while (index < text.length && /\s/.test(text[index]!)) index += 1;
20
+ return index;
21
+ }
22
+
23
+ /**
24
+ * A copy of `range` reduced to its selected words. Selecting a whole sentence or paragraph by clicking ends the
25
+ * browser's range at the start of the next block (Chrome, Safari) or starts it before the block (Firefox), which may
26
+ * lie outside the surface or be the selection bar itself: the words are the same, so the surface reads them and its
27
+ * bar stays. Returns `range` itself when both its ends already sit on selected words.
28
+ */
29
+ export function trimRange(range: Range): Range {
30
+ const { startContainer, startOffset, endContainer, endOffset, commonAncestorContainer } = range;
31
+ const startsOnWords = isText(startContainer) && startContainer.data.slice(startOffset,
32
+ startContainer === endContainer ? endOffset : undefined).trim();
33
+ const endsOnWords = isText(endContainer) && endContainer.data.slice(
34
+ endContainer === startContainer ? startOffset : 0, endOffset).trim();
35
+ if ((startsOnWords && endsOnWords) || isText(commonAncestorContainer)) return range;
36
+ const document = commonAncestorContainer.ownerDocument;
37
+ if (!document) return range;
38
+ const walker = document.createTreeWalker(commonAncestorContainer, SHOW_TEXT);
39
+ // Start at the range's start, not at the top of a container that may hold the whole page.
40
+ let node: Node | null = null;
41
+ const child = isText(startContainer) ? startContainer : startContainer.childNodes[startOffset];
42
+ if (child && isText(child)) node = child;
43
+ else {
44
+ walker.currentNode = child ?? commonAncestorContainer;
45
+ node = walker.nextNode();
46
+ }
47
+ let first: { node: Text; offset: number } | null = null;
48
+ let last: { node: Text; offset: number } | null = null;
49
+ for (; node; walker.currentNode = node, node = walker.nextNode()) {
50
+ if (range.comparePoint(node, 0) > 0) break;
51
+ if (!isText(node) || !range.intersectsNode(node) || node.parentElement?.closest(UNREAD)) continue;
52
+ const from = node === startContainer ? startOffset : 0;
53
+ const to = node === endContainer ? endOffset : node.data.length;
54
+ const words = node.data.slice(from, to);
55
+ if (!words.trim()) continue;
56
+ if (!first) first = { node, offset: blankAfter(node.data, from) };
57
+ last = { node, offset: blankBefore(node.data, to) };
58
+ if (node === endContainer) break;
59
+ }
60
+ if (!first || !last) return range;
61
+ const trimmed = range.cloneRange();
62
+ if (!startsOnWords) trimmed.setStart(first.node, first.offset);
63
+ if (!endsOnWords) trimmed.setEnd(last.node, last.offset);
64
+ return trimmed;
65
+ }
@@ -1,6 +1,8 @@
1
1
  export { defineSpace, defineSpaces } from './space';
2
- export type { SpaceDefinition, SpacesWorkspace, SpaceActionTemplate, SpaceResourceReference, SpaceDatabaseCreate } from './space';
2
+ export type { SpaceDefinition, SpacesWorkspace, SpaceActionTemplate, SpaceResourceReference, SpaceDatabaseCreate, SpaceStore } from './space';
3
3
  export type { SpaceViewParam, SpaceViewParamType, SpaceShows, SpaceMemoryPolicy, SpaceMemorySnapshot, SpaceChrome, SpaceMarkdownInput } from './space';
4
+ export { threadHookInput, threadIdleInput, threadSettleInput, commentOptionInput } from './functions';
5
+ export type { SpaceFunctionDeclaration, SpaceFunctionHandler, SpaceFunctionContext } from './functions';
4
6
 
5
7
  /**
6
8
  * Configuration utilities for notis.config.ts and Space definitions.