@notis_ai/cli 0.2.33 → 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 (56) hide show
  1. package/README.md +1 -2
  2. package/dist/agent-hooks/notis-agent-hook.mjs +82 -19
  3. package/dist/base-skills/notis-cli/.notis-base-skill.json +1 -1
  4. package/dist/base-skills/notis-cli/SKILL.md +1 -1
  5. package/dist/base-skills/notis-spaces/.notis-base-skill.json +1 -1
  6. package/dist/base-skills/notis-spaces/references/comments.md +11 -3
  7. package/dist/sdk/src/components/NotisSelectionBoundary.tsx +13 -5
  8. package/dist/sdk/src/components/SelectionActionBar.tsx +3 -1
  9. package/dist/sdk/src/components/SpaceTextComments.tsx +13 -4
  10. package/dist/sdk/src/components/selectionRange.ts +65 -0
  11. package/dist/sdk/src/config.ts +1 -1
  12. package/dist/sdk/src/functions.ts +17 -2
  13. package/dist/sdk/src/hooks/useCollectionInteractions.ts +59 -7
  14. package/dist/sdk/src/index.ts +4 -3
  15. package/dist/sdk/src/interactions/shortcuts.tsx +6 -1
  16. package/dist/sdk/src/interactions/swipeDownToDismiss.ts +158 -0
  17. package/dist/sdk/src/interactions/textBoxTwoState.ts +174 -0
  18. package/dist/sdk/src/interactions.ts +17 -0
  19. package/dist/sdk/src/space.ts +73 -5
  20. package/dist/skill-sync/index.js +23 -1
  21. package/dist/skill-sync-worker.mjs +62 -3
  22. package/dist/space-harness/host.js +351 -237
  23. package/dist/space-sdk/dist/chunk-3NPBCE6E.js +3 -0
  24. package/dist/space-sdk/dist/index.js +2 -2
  25. package/dist/space-sdk/dist/ui.js +16 -12
  26. package/dist/space-sdk/src/config.ts +1 -1
  27. package/dist/space-sdk/src/functions.ts +17 -2
  28. package/dist/space-sdk/src/hooks/useCollectionInteractions.d.ts +5 -0
  29. package/dist/space-sdk/src/index.d.ts +3 -3
  30. package/dist/space-sdk/src/interactions/shortcuts.d.ts +5 -0
  31. package/dist/space-sdk/src/space.ts +73 -5
  32. package/dist/space-sdk/src/tailwind-candidates.d.ts +234 -71
  33. package/dist/space-sdk/src/ui/comments/CommentPane.d.ts +86 -14
  34. package/dist/space-sdk/src/ui/comments/PassageComments.d.ts +4 -1
  35. package/dist/space-sdk/src/ui/comments/agentRuntime.d.ts +0 -6
  36. package/dist/space-sdk/src/ui/comments/commentDrafts.d.ts +63 -0
  37. package/dist/space-sdk/src/ui/comments/commentModel.d.ts +4 -0
  38. package/dist/space-sdk/src/ui/comments/commentWords.d.ts +23 -1
  39. package/dist/space-sdk/src/ui/comments/handover.d.ts +34 -0
  40. package/dist/space-sdk/src/ui/comments/hostPanel.d.ts +113 -0
  41. package/dist/space-sdk/src/ui/comments/index.d.ts +6 -1
  42. package/dist/space-sdk/src/ui/comments/paneOutlet.d.ts +33 -0
  43. package/dist/space-sdk/src/ui/comments/paneParts.d.ts +54 -32
  44. package/dist/space-sdk/src/ui/comments/reviewRun.d.ts +190 -0
  45. package/dist/space-sdk/src/ui/comments/useComments.d.ts +52 -3
  46. package/dist/view-renderer/dist/host.js +413 -299
  47. package/package.json +3 -3
  48. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +1 -1
  49. package/src/runtime/agent-identity.js +3 -4
  50. package/src/runtime/app-platform.js +1 -1
  51. package/src/runtime/profiles.js +59 -2
  52. package/src/runtime/skill-sync/cloud-client.ts +33 -3
  53. package/src/runtime/skill-sync/index.ts +1 -1
  54. package/src/runtime/skill-sync/types.ts +4 -1
  55. package/src/runtime/space-functions.js +5 -3
  56. package/dist/space-sdk/dist/chunk-4GWS2IFO.js +0 -3
@@ -31,6 +31,8 @@ import { useLongPressSelection } from './useLongPressSelection';
31
31
  import { useMarqueeSelection, type SelectionMarqueeRect } from './useMarqueeSelection';
32
32
 
33
33
  export const COLLECTION_ITEM_ATTRIBUTE = 'data-notis-collection-item-id';
34
+ /** Frames a revealed item is waited for before its focus is given up (about a third of a second). */
35
+ const REVEAL_FOCUS_FRAMES = 20;
34
36
  const LEGACY_ROW_ATTRIBUTE = 'data-notis-row-id';
35
37
  const INTERACTIVE_SELECTOR = 'button, a, input, textarea, select, [role="button"], [contenteditable]:not([contenteditable="false"])';
36
38
 
@@ -105,6 +107,11 @@ export interface UseCollectionInteractionsOptions<T> {
105
107
  shortcutPriority?: number;
106
108
  resolveNextId?: (context: CollectionNavigationContext<T>) => string | null;
107
109
  onActiveItemChange?: (id: string | null) => void;
110
+ /**
111
+ * For a view that draws only part of its items (the rows on screen): brings an item into view so it is drawn.
112
+ * Called when the item to focus has no element; the controller then focuses it as soon as it is drawn.
113
+ */
114
+ revealItem?: (id: string) => void;
108
115
  actions?: CollectionAction<T>[];
109
116
  }
110
117
 
@@ -226,6 +233,7 @@ export function useCollectionInteractions<T>(
226
233
  shortcutPriority = 0,
227
234
  resolveNextId,
228
235
  onActiveItemChange,
236
+ revealItem,
229
237
  actions: actionDefinitions = [],
230
238
  } = options;
231
239
 
@@ -254,6 +262,7 @@ export function useCollectionInteractions<T>(
254
262
  const onActiveItemChangeRef = useRef(onActiveItemChange);
255
263
  const onActivateRef = useRef(onActivate);
256
264
  const resolveNextIdRef = useRef(resolveNextId);
265
+ const revealItemRef = useRef(revealItem);
257
266
  const containerRef = useRef<HTMLElement | null>(null);
258
267
  const [containerElement, setContainerElement] = useState<HTMLElement | null>(null);
259
268
  const setContainerRef = useCallback((node: HTMLElement | null) => {
@@ -279,6 +288,7 @@ export function useCollectionInteractions<T>(
279
288
  onActiveItemChangeRef.current = onActiveItemChange;
280
289
  onActivateRef.current = onActivate;
281
290
  resolveNextIdRef.current = resolveNextId;
291
+ revealItemRef.current = revealItem;
282
292
 
283
293
  const itemById = useMemo(() => new Map(items.map((item) => [getId(item), item])), [getId, items]);
284
294
  const selectableIds = useMemo(
@@ -449,13 +459,52 @@ export function useCollectionInteractions<T>(
449
459
  }
450
460
  }, [commitSelection, selectableIds, setActive, setAnchor]);
451
461
 
462
+ const pendingRevealRef = useRef<number | null>(null);
463
+ useEffect(() => () => {
464
+ if (pendingRevealRef.current !== null) cancelAnimationFrame(pendingRevealRef.current);
465
+ }, []);
452
466
  const focusItem = useCallback((id: string) => {
453
- const nodes = containerRef.current?.querySelectorAll<HTMLElement>(`[${COLLECTION_ITEM_ATTRIBUTE}]`);
454
- const node = nodes ? Array.from(nodes).find(
455
- (candidate) => candidate.getAttribute(COLLECTION_ITEM_ATTRIBUTE) === id && isInteractionElementVisible(candidate),
456
- ) : null;
457
- node?.focus({ preventScroll: true });
458
- node?.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
467
+ if (pendingRevealRef.current !== null) {
468
+ cancelAnimationFrame(pendingRevealRef.current);
469
+ pendingRevealRef.current = null;
470
+ }
471
+ const find = () => {
472
+ const nodes = containerRef.current?.querySelectorAll<HTMLElement>(`[${COLLECTION_ITEM_ATTRIBUTE}]`);
473
+ return nodes ? Array.from(nodes).find(
474
+ (candidate) => candidate.getAttribute(COLLECTION_ITEM_ATTRIBUTE) === id && isInteractionElementVisible(candidate),
475
+ ) ?? null : null;
476
+ };
477
+ const focus = (node: HTMLElement) => {
478
+ node.focus({ preventScroll: true });
479
+ node.scrollIntoView?.({ block: 'nearest', inline: 'nearest' });
480
+ };
481
+ const node = find();
482
+ if (node) { focus(node); return; }
483
+ // A view that draws only the items on screen: ask it to draw this one, then focus it once it is there.
484
+ // Another focus, the active item moving on, or the person putting focus somewhere else (a field, another
485
+ // surface) drops the wait.
486
+ if (!revealItemRef.current || typeof requestAnimationFrame !== 'function') return;
487
+ // Focus is read in the page and, for a view drawn in a shadow root, inside that root too: the page only sees
488
+ // the root's host there.
489
+ const ownerDocument = containerRef.current?.ownerDocument;
490
+ const root = containerRef.current?.getRootNode();
491
+ const focusPlace = () => [
492
+ ownerDocument?.activeElement ?? null,
493
+ root && root !== ownerDocument && 'activeElement' in root ? (root as ShadowRoot).activeElement : null,
494
+ ] as const;
495
+ const before = focusPlace();
496
+ revealItemRef.current(id);
497
+ let frames = REVEAL_FOCUS_FRAMES;
498
+ const retry = () => {
499
+ pendingRevealRef.current = null;
500
+ if (activeIdRef.current !== id) return;
501
+ const now = focusPlace();
502
+ if ((now[0] && now[0] !== before[0] && now[0] !== ownerDocument?.body) || (now[1] && now[1] !== before[1])) return;
503
+ const revealed = find();
504
+ if (revealed) { focus(revealed); return; }
505
+ if (--frames > 0) pendingRevealRef.current = requestAnimationFrame(retry);
506
+ };
507
+ pendingRevealRef.current = requestAnimationFrame(retry);
459
508
  }, []);
460
509
 
461
510
  const focusPointerItem = useCallback((id: string) => {
@@ -545,7 +594,10 @@ export function useCollectionInteractions<T>(
545
594
  const extendUp = filterShortcutKeys(keyboard.extendPrevious, (key) => !key.toLowerCase().endsWith('arrowleft'));
546
595
  // An empty collection has nothing to dismiss. Let the enclosing surface
547
596
  // own Escape (for example Desktop's final Inbox navigation layer).
548
- add('collection.clear', 'Clear selection', selectedIds.size > 0 ? keyboard.clear : false, clear);
597
+ // Bound only while something is selected, so the engine clears it whether or not a selected item is drawn.
598
+ if (selectedIds.size > 0 && keyboard.clear) {
599
+ definitions.push({ id: 'collection.clear', label: 'Clear selection', keys: keyboard.clear, onTrigger: clear, whileSelected: true });
600
+ }
549
601
  add('collection.select-all', 'Select all visible items', selectionMode === 'none' ? false : keyboard.selectAll, selectAll);
550
602
  add('collection.toggle', 'Toggle active item', selectionMode === 'none' ? false : keyboard.toggle, () => {
551
603
  const id = activeIdRef.current ?? anchorIdRef.current;
@@ -43,7 +43,8 @@ export type { SpaceAgentDeclaration, SpaceItemThread, SpaceAgentQueue, SpaceAgen
43
43
  SpaceThreadItemKind, SpaceThreadItem, SpaceThreadItemRun, SpaceThreadItemTransport,
44
44
  SpaceCommentSource, SpaceCommentsTransport, SpaceCommentViewer, SpaceCommentThreadRef, SpaceCommentThreadPick,
45
45
  SpaceCommentAnchor, SpaceCommentAttachment, SpaceCommentChange, SpaceCommentFile, SpaceCommentInsert, SpaceCommentMode,
46
- SpaceCommentNeeds, SpaceCommentPage, SpaceCommentPageKey, SpaceCommentReply, SpaceCommentRow, SpaceCommentStatus } from './space';
46
+ SpaceCommentNeeds, SpaceCommentPage, SpaceCommentPageKey, SpaceCommentReply, SpaceCommentRow, SpaceCommentStatus,
47
+ SpaceCommentThreadsAnswer, SpaceCommentThreadsInput } from './space';
47
48
  export { SpaceActionError, SpaceNavigationCancelled, isSpaceNavigationCancelled } from './space';
48
49
  export { spaceAudience, spaceMarksEditorsOnly, publicSpaceDescriptor, withoutEditorColumns } from './space';
49
50
  export type { SpaceAudience, SpaceEditorsOnly, SpaceResourceColumns, EditorOnlyColumns, AudienceRow } from './space';
@@ -85,9 +86,9 @@ export { useItemThread } from './hooks/useItemThread';
85
86
  export type { UseItemThreadResult } from './hooks/useItemThread';
86
87
  export { useThreadItem } from './hooks/useThreadItem';
87
88
  export { useFunction, useFunctionQuery } from './hooks/useFunction';
88
- export { threadHookInput, threadSettleInput, commentOptionInput } from './functions';
89
+ export { threadHookInput, threadIdleInput, threadSettleInput, commentOptionInput } from './functions';
89
90
  export type { SpaceFunctionDeclaration, SpaceFunctionHandler, SpaceFunctionContext, SpaceFunctionKind, SpaceFunctionExposure,
90
- SpaceFunctionRole, SpaceFunctionUses, SpaceThreadOperation, SpaceThreadHookEvent, SpaceThreadHookInput, SpaceThreadSettleInput,
91
+ SpaceFunctionRole, SpaceFunctionUses, SpaceThreadOperation, SpaceThreadHookEvent, SpaceThreadHookInput, SpaceThreadIdleInput, SpaceThreadSettleInput,
91
92
  SpaceCommentOption, SpaceCommentOptionInput, SpaceFunctionThread, SpaceFunctionThreadItem, SpaceFunctionCloudComputer, SpaceFunctionDescriptor,
92
93
  SpaceFunctionCallOptions } from './functions';
93
94
  export type { UseThreadItemResult } from './hooks/useThreadItem';
@@ -33,6 +33,11 @@ export interface ShortcutDefinition {
33
33
  allowRepeat?: boolean;
34
34
  preventDefault?: boolean;
35
35
  stopPropagation?: boolean;
36
+ /**
37
+ * Set by a collection that binds its clear key only while something is selected: the binding itself says the
38
+ * selection is not empty, whichever items are drawn (a windowed list draws only the rows on screen).
39
+ */
40
+ whileSelected?: boolean;
36
41
  onTrigger: (event: KeyboardEvent) => void | Promise<void>;
37
42
  }
38
43
 
@@ -223,7 +228,7 @@ function consumeShortcut(event: KeyboardEvent, definition: ShortcutDefinition):
223
228
  // rendered and none selected, leave Escape to the enclosing surface (the Portal
224
229
  // closes its frontmost layer, then returns to Inbox).
225
230
  function isEmptyCollectionClear(shortcut: ShortcutDefinition, ownerDocument: Document, event: KeyboardEvent): boolean {
226
- if (event.key !== 'Escape' || shortcut.id !== 'collection.clear') return false;
231
+ if (event.key !== 'Escape' || shortcut.id !== 'collection.clear' || shortcut.whileSelected) return false;
227
232
  const items = collectionItems(ownerDocument).filter((item) => isInteractionElementVisible(item as HTMLElement));
228
233
  return items.length > 0 && !items.some((item) => item.getAttribute('aria-selected') === 'true');
229
234
  }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Swipe down in a text box to put the keyboard away, as phone chat apps do. A swipe that starts inside an area marked
3
+ * `data-swipe-dismiss` (a chat composer, a comment's reply box) while its field has the keyboard first scrolls the
4
+ * field's own text, as the browser does. Once the text is at its top, the rest of the swipe stops scrolling anything
5
+ * behind it, and past {@link SWIPE_DISMISS_DISTANCE} the field loses focus, so the keyboard closes. A swipe up, a
6
+ * sideways swipe, a second finger or a field without the keyboard leave everything to the browser.
7
+ *
8
+ * One listener per document, whoever asks for it (the Portal, a comment pane), through {@link useSwipeDownToDismiss}
9
+ * or {@link installSwipeDownToDismiss}. Areas inside a shadow root (the comment panes) are found through the event's
10
+ * composed path, and the focused field through each shadow root's own active element.
11
+ */
12
+
13
+ import { useEffect } from 'react';
14
+
15
+ /** Marks an area where a swipe down puts the keyboard away. */
16
+ export const SWIPE_DISMISS_ATTRIBUTE = 'data-swipe-dismiss';
17
+ /** How far the finger travels down, once the text is at its top, before the keyboard closes, in pixels. */
18
+ export const SWIPE_DISMISS_DISTANCE = 32;
19
+ /** Travel before a swipe counts as vertical or sideways, in pixels. */
20
+ const SLOP = 6;
21
+
22
+ type Gesture = {
23
+ id: number;
24
+ field: HTMLElement;
25
+ startX: number;
26
+ startY: number;
27
+ lastY: number;
28
+ /** Where the finger was when the text reached its top during a downward move; null while the text still scrolls. */
29
+ topY: number | null;
30
+ vertical: boolean | null;
31
+ };
32
+
33
+ /** The element that has the focus, looking inside open shadow roots. */
34
+ export function deepActiveElement(doc: Document): Element | null {
35
+ let active: Element | null = doc.activeElement;
36
+ while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
37
+ return active;
38
+ }
39
+
40
+ function isTextField(element: Element | null): element is HTMLElement {
41
+ if (!element) return false;
42
+ if (element instanceof HTMLTextAreaElement) return !element.readOnly && !element.disabled;
43
+ if (element instanceof HTMLInputElement) {
44
+ return !element.readOnly && !element.disabled && !['button', 'checkbox', 'radio', 'range', 'submit', 'reset', 'file', 'color', 'image'].includes(element.type);
45
+ }
46
+ return element instanceof HTMLElement && element.isContentEditable;
47
+ }
48
+
49
+ /** The marked area on the touch's composed path, so areas inside a shadow root count too. */
50
+ function areaOf(event: TouchEvent): HTMLElement | null {
51
+ for (const node of event.composedPath()) {
52
+ if (node instanceof HTMLElement && node.hasAttribute(SWIPE_DISMISS_ATTRIBUTE)) return node;
53
+ }
54
+ return null;
55
+ }
56
+
57
+ /** The field the text scrolls in: the focused element, or its nearest scrolling editable ancestor (a contentEditable). */
58
+ function scrollerOf(field: HTMLElement): HTMLElement {
59
+ let node: HTMLElement | null = field;
60
+ while (node) {
61
+ if (node.scrollHeight > node.clientHeight + 1) return node;
62
+ if (node.parentElement && !node.parentElement.isContentEditable) break;
63
+ node = node.parentElement;
64
+ }
65
+ return field;
66
+ }
67
+
68
+ const installs = new WeakMap<Document, { count: number; remove: () => void }>();
69
+
70
+ function listen(doc: Document): () => void {
71
+ let gesture: Gesture | null = null;
72
+
73
+ const start = (event: TouchEvent) => {
74
+ gesture = null;
75
+ if (event.touches.length !== 1) return;
76
+ const area = areaOf(event);
77
+ if (!area) return;
78
+ const active = deepActiveElement(doc);
79
+ if (!isTextField(active)) return;
80
+ // The focused field must be in this area (or be the area): touching another composer leaves this one alone.
81
+ let inside = false;
82
+ for (let node: Node | null = active; node; node = node.parentNode ?? (node instanceof ShadowRoot ? node.host : null)) {
83
+ if (node === area) { inside = true; break; }
84
+ }
85
+ if (!inside) return;
86
+ const touch = event.touches[0];
87
+ const field = scrollerOf(active);
88
+ gesture = {
89
+ id: touch.identifier, field, startX: touch.clientX, startY: touch.clientY, lastY: touch.clientY,
90
+ topY: field.scrollTop <= 0 ? touch.clientY : null, vertical: null,
91
+ };
92
+ };
93
+
94
+ const move = (event: TouchEvent) => {
95
+ const current = gesture;
96
+ if (!current) return;
97
+ if (event.touches.length !== 1) { gesture = null; return; }
98
+ const touch = Array.from(event.touches).find((t) => t.identifier === current.id);
99
+ if (!touch) return;
100
+ if (current.vertical === null) {
101
+ const dx = Math.abs(touch.clientX - current.startX);
102
+ const dy = Math.abs(touch.clientY - current.startY);
103
+ if (dx < SLOP && dy < SLOP) return;
104
+ current.vertical = dy > dx;
105
+ if (!current.vertical) { gesture = null; return; }
106
+ }
107
+ const goingUp = touch.clientY < current.lastY;
108
+ current.lastY = touch.clientY;
109
+ // Moving up, or text still above the top: the browser scrolls the field, and the count starts again.
110
+ if (goingUp || current.field.scrollTop > 0) { current.topY = null; return; }
111
+ if (current.topY === null) current.topY = touch.clientY;
112
+ // The text is at its top: nothing behind the field scrolls for the rest of this swipe.
113
+ if (event.cancelable) event.preventDefault();
114
+ if (touch.clientY - current.topY >= SWIPE_DISMISS_DISTANCE) {
115
+ gesture = null;
116
+ current.field.blur();
117
+ const active = deepActiveElement(doc);
118
+ if (active instanceof HTMLElement && active !== current.field && isTextField(active)) active.blur();
119
+ }
120
+ };
121
+
122
+ const end = () => { gesture = null; };
123
+
124
+ doc.addEventListener('touchstart', start, { passive: true, capture: true });
125
+ doc.addEventListener('touchmove', move, { passive: false, capture: true });
126
+ doc.addEventListener('touchend', end, { capture: true });
127
+ doc.addEventListener('touchcancel', end, { capture: true });
128
+ return () => {
129
+ doc.removeEventListener('touchstart', start, { capture: true });
130
+ doc.removeEventListener('touchmove', move, { capture: true });
131
+ doc.removeEventListener('touchend', end, { capture: true });
132
+ doc.removeEventListener('touchcancel', end, { capture: true });
133
+ };
134
+ }
135
+
136
+ /** Turns the swipe on for a document; each call returns its own undo, and the listener stays while any caller needs it. */
137
+ export function installSwipeDownToDismiss(doc: Document = document): () => void {
138
+ const existing = installs.get(doc);
139
+ if (existing) existing.count += 1;
140
+ else installs.set(doc, { count: 1, remove: listen(doc) });
141
+ let done = false;
142
+ return () => {
143
+ if (done) return;
144
+ done = true;
145
+ const install = installs.get(doc);
146
+ if (!install) return;
147
+ install.count -= 1;
148
+ if (install.count <= 0) { install.remove(); installs.delete(doc); }
149
+ };
150
+ }
151
+
152
+ /** Turns the swipe on for this document while the component is mounted. */
153
+ export function useSwipeDownToDismiss(enabled = true): void {
154
+ useEffect(() => {
155
+ if (!enabled || typeof document === 'undefined') return;
156
+ return installSwipeDownToDismiss(document);
157
+ }, [enabled]);
158
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * The two states of a text box (docs/portal-design-system.md, "Two states of a text box"), for every box a person
3
+ * writes a message or a comment in: the Portal's chat box, quick box and comment box (through its
4
+ * `composerTwoState.ts`) and the comment pane's own fields, where the host draws none.
5
+ *
6
+ * - At rest (no focus; on a phone, the keyboard closed): one line, the placeholder or the first line of a draft.
7
+ * - Open (the focus is in the box): the text takes the full width on top and the buttons a line of their own under it.
8
+ *
9
+ * This file holds what every box shares, so they open and fold the same way: when a box is open
10
+ * ({@link textBoxOpen}), how long a blur waits before it folds ({@link TEXT_BOX_FOLD_DELAY_MS}), how its height moves
11
+ * between the two states ({@link useHeightFollowsState}) and the hook that ties them to an element
12
+ * ({@link useTextBoxTwoState}). The element gets `data-composer-state="rest" | "open"`; each stylesheet draws the two
13
+ * states from that attribute (`globals.css` in the Portal, `toolkit.css` in a comment pane's shadow root).
14
+ */
15
+
16
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState, type RefObject } from 'react';
17
+ import { deepActiveElement } from './swipeDownToDismiss';
18
+
19
+ const LG_QUERY = '(min-width: 1024px)';
20
+ /** How long a blur waits before the box folds: a press on one of its own menus or buttons is no blur. */
21
+ export const TEXT_BOX_FOLD_DELAY_MS = 160;
22
+ /** How long the box takes to change height between its two states. */
23
+ export const TEXT_BOX_STATE_MS = 200;
24
+ /** Something of a box drawn outside it (the thread picker, a menu, the @ list): the focus there keeps the box open. */
25
+ export const TEXT_BOX_OUTSIDE_PARTS = '[data-notis-thread-picker], [role="menu"], [data-mention-dropdown]';
26
+
27
+ const useIsoLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
28
+
29
+ /** True from 1024px up (a computer's layout); true before the first effect, as the server draws it. */
30
+ export function useWideScreen(): boolean {
31
+ const [wide, setWide] = useState(true);
32
+ useEffect(() => {
33
+ const query = window.matchMedia?.(LG_QUERY);
34
+ if (!query) return undefined;
35
+ const sync = () => setWide(query.matches);
36
+ sync();
37
+ query.addEventListener?.('change', sync);
38
+ return () => query.removeEventListener?.('change', sync);
39
+ }, []);
40
+ return wide;
41
+ }
42
+
43
+ /**
44
+ * Whether a box is open: it has the focus, or is busy (recording, sending); on a computer a draft keeps it open too.
45
+ * On a phone a draft at rest is one line.
46
+ */
47
+ export function textBoxOpen(input: { focused: boolean; busy: boolean; hasDraft: boolean; wide: boolean }): boolean {
48
+ return input.focused || input.busy || (input.wide && input.hasDraft);
49
+ }
50
+
51
+ /**
52
+ * The box's surface changes height between its two states over TEXT_BOX_STATE_MS, from the height it had to the one
53
+ * its new layout takes (nothing moves for reduced motion, or where the browser cannot animate). The surface is the
54
+ * holder's first element, or what `surfaceOf` picks in it.
55
+ */
56
+ export function useHeightFollowsState(holder: RefObject<HTMLElement | null>, state: string | null,
57
+ surfaceOf?: (holder: HTMLElement) => HTMLElement | null): void {
58
+ const last = useRef<{ state: string | null; height: number } | null>(null);
59
+ const pick = useRef(surfaceOf);
60
+ pick.current = surfaceOf;
61
+ useIsoLayoutEffect(() => {
62
+ // One state only (the Desktop overlay, a computer's quick box): nothing is read from the page.
63
+ if (!state) { last.current = null; return; }
64
+ const element = holder.current;
65
+ const surface = element ? (pick.current ? pick.current(element) : element.firstElementChild as HTMLElement | null) : null;
66
+ if (!surface) return;
67
+ const height = surface.getBoundingClientRect().height;
68
+ const before = last.current;
69
+ last.current = { state, height };
70
+ if (!before || before.state === state || !state || !before.state || Math.abs(before.height - height) < 1) return;
71
+ const view = surface.ownerDocument.defaultView;
72
+ if (typeof surface.animate !== 'function' || view?.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
73
+ surface.animate([{ height: `${before.height}px`, overflow: 'hidden' }, { height: `${height}px`, overflow: 'hidden' }],
74
+ { duration: TEXT_BOX_STATE_MS, easing: 'ease-out' });
75
+ });
76
+ }
77
+
78
+ /**
79
+ * Runs `fold` once the focus has left `box` for good, TEXT_BOX_FOLD_DELAY_MS after a blur. While something of the box
80
+ * drawn outside it is open (`TEXT_BOX_OUTSIDE_PARTS`, or `keep`), it waits and looks again, so a box whose menu or
81
+ * picker closed without giving it the focus back still folds. `timer` holds the pending look; a focus that returns
82
+ * clears it. The focus is read through shadow roots, so a box inside a comment pane counts its own field.
83
+ */
84
+ export function foldOnceFocusLeft(timer: { current: ReturnType<typeof setTimeout> | null }, box: () => HTMLElement | null,
85
+ fold: () => void, keep?: () => boolean): void {
86
+ if (timer.current) clearTimeout(timer.current);
87
+ const look = () => {
88
+ timer.current = null;
89
+ const element = box();
90
+ if (element && element.contains(deepActiveElement(element.ownerDocument))) return;
91
+ if (keep?.() || document.querySelector(TEXT_BOX_OUTSIDE_PARTS)) { timer.current = setTimeout(look, TEXT_BOX_FOLD_DELAY_MS); return; }
92
+ fold();
93
+ };
94
+ timer.current = setTimeout(look, TEXT_BOX_FOLD_DELAY_MS);
95
+ }
96
+
97
+ export interface TextBoxTwoStateOptions {
98
+ /** The box takes the two states here. False: one state, no attribute, and nothing is read from the page. */
99
+ enabled: boolean;
100
+ /** The two states on a phone only: from 1024px up the box keeps its one state. */
101
+ phoneOnly?: boolean;
102
+ hasDraft: boolean;
103
+ /** Something keeps the box open without the focus (a voice message being recorded). */
104
+ busy?: boolean;
105
+ /** A message is being sent, or the box says why it could not: it stays in the state it was in. */
106
+ hold?: boolean;
107
+ /** Something of the box drawn outside it is open (a dialog it started): a blur toward it is no blur. */
108
+ keepOpen?: () => boolean;
109
+ /** The element whose height follows the state, when it is not the holder's first element. */
110
+ surfaceOf?: (holder: HTMLElement) => HTMLElement | null;
111
+ /**
112
+ * The box can lose the focus without hearing of it: a browser sends no blur when the focused field or button is
113
+ * switched off or taken away (Send once the message is sent, the field while a voice message is recorded). With
114
+ * this on, the box looks again each time what holds it changes, and folds when the focus is no longer in it.
115
+ */
116
+ looksAgain?: boolean;
117
+ }
118
+
119
+ export interface TextBoxTwoState<T extends HTMLElement = HTMLDivElement> {
120
+ /** False where the box has one state: no attribute is set. */
121
+ on: boolean;
122
+ open: boolean;
123
+ state: 'rest' | 'open' | null;
124
+ /** Spread on the element that wraps the box's surface. */
125
+ bind: {
126
+ ref: RefObject<T | null>;
127
+ onFocusCapture(): void;
128
+ onBlurCapture(): void;
129
+ 'data-composer-state'?: 'rest' | 'open';
130
+ };
131
+ }
132
+
133
+ /** The two states of one box: open with the focus, folded TEXT_BOX_FOLD_DELAY_MS after it left, its height following. */
134
+ export function useTextBoxTwoState<T extends HTMLElement = HTMLDivElement>({ enabled: asked, phoneOnly = false, hasDraft,
135
+ busy = false, hold = false, keepOpen, surfaceOf, looksAgain = false }: TextBoxTwoStateOptions): TextBoxTwoState<T> {
136
+ const [focused, setFocused] = useState(false);
137
+ const wide = useWideScreen();
138
+ const enabled = asked && !(phoneOnly && wide);
139
+ const ref = useRef<T | null>(null);
140
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
141
+ const keep = useRef(keepOpen);
142
+ keep.current = keepOpen;
143
+ useEffect(() => () => { if (timer.current) clearTimeout(timer.current); }, []);
144
+ // A box that comes and goes (the quick box closes; a window crosses 1024px) reads where the focus is each time it
145
+ // takes the two states: a field taken off the page never said it lost the focus.
146
+ useEffect(() => {
147
+ if (timer.current) { clearTimeout(timer.current); timer.current = null; }
148
+ const element = ref.current;
149
+ setFocused(Boolean(enabled && element && element.contains(deepActiveElement(element.ownerDocument))));
150
+ }, [enabled]);
151
+ const onFocusCapture = useCallback(() => {
152
+ if (timer.current) clearTimeout(timer.current);
153
+ setFocused(true);
154
+ }, []);
155
+ const onBlurCapture = useCallback(() => {
156
+ foldOnceFocusLeft(timer, () => ref.current, () => setFocused(false), () => Boolean(keep.current?.()));
157
+ }, []);
158
+ // `looksAgain`: each time what holds the box changes, it looks once more, TEXT_BOX_FOLD_DELAY_MS later, and folds
159
+ // when the focus is no longer in it (no blur said so).
160
+ useEffect(() => {
161
+ if (!looksAgain || !enabled || !focused || hold) return;
162
+ foldOnceFocusLeft(timer, () => ref.current, () => setFocused(false), () => Boolean(keep.current?.()));
163
+ }, [looksAgain, enabled, focused, hold, busy, hasDraft]);
164
+ const natural = textBoxOpen({ focused, busy, hasDraft, wide });
165
+ const kept = useRef(natural);
166
+ if (!hold) kept.current = natural;
167
+ const open = enabled && (hold ? kept.current : natural);
168
+ const state = enabled ? (open ? 'open' : 'rest') : null;
169
+ useHeightFollowsState(ref, state, surfaceOf);
170
+ return {
171
+ on: enabled, open, state,
172
+ bind: { ref, onFocusCapture, onBlurCapture, ...(state ? { 'data-composer-state': state } : {}) },
173
+ };
174
+ }
@@ -45,3 +45,20 @@ export type { ShortcutHint, ShortcutHintsProps } from './components/ShortcutHint
45
45
 
46
46
  export { useLongPressSelection } from './hooks/useLongPressSelection';
47
47
  export { isInteractionElementVisible } from './interactions/visibility';
48
+ export {
49
+ SWIPE_DISMISS_ATTRIBUTE,
50
+ SWIPE_DISMISS_DISTANCE,
51
+ installSwipeDownToDismiss,
52
+ useSwipeDownToDismiss,
53
+ } from './interactions/swipeDownToDismiss';
54
+ export {
55
+ TEXT_BOX_FOLD_DELAY_MS,
56
+ TEXT_BOX_OUTSIDE_PARTS,
57
+ TEXT_BOX_STATE_MS,
58
+ foldOnceFocusLeft,
59
+ textBoxOpen,
60
+ useHeightFollowsState,
61
+ useTextBoxTwoState,
62
+ useWideScreen,
63
+ } from './interactions/textBoxTwoState';
64
+ export type { TextBoxTwoState, TextBoxTwoStateOptions } from './interactions/textBoxTwoState';
@@ -318,6 +318,10 @@ export interface SpaceCommentRow {
318
318
  status: SpaceCommentStatus;
319
319
  needs: SpaceCommentNeeds;
320
320
  options: string[];
321
+ /** A choice question's option its asker recommends (one of `options`). Absent or null: none. */
322
+ recommended?: string | null;
323
+ /** A choice question's line under an option, by option. Absent: none. */
324
+ option_details?: Readonly<Record<string, string>>;
321
325
  answer: string | null;
322
326
  answered_at: string | null;
323
327
  answer_to: string | null;
@@ -342,6 +346,46 @@ export interface SpaceCommentRow {
342
346
  */
343
347
  export type SpaceCommentPageKey = string | null | 'all';
344
348
 
349
+ /**
350
+ * Which comment threads of the Space a pane reads (`SpaceCommentsTransport.threads`). The open threads always come,
351
+ * whole. Deleted threads never come.
352
+ */
353
+ export interface SpaceCommentThreadsInput {
354
+ /**
355
+ * How many Done threads the pane wants too, newest first (0 or absent: none). The host reads them a page at a time
356
+ * and answers every one it holds; `moreDone` says whether older ones are left.
357
+ */
358
+ done?: number;
359
+ /**
360
+ * Only these threads (the ids of their first comments), whatever their status: nothing else of the Space is read.
361
+ * For a host that shows a part of a Space's comments (those linked to one conversation).
362
+ */
363
+ only?: readonly string[] | null;
364
+ /** Comments whose threads come too, whatever their status and their place in the list (a link to one comment). */
365
+ include?: readonly string[];
366
+ }
367
+
368
+ /** What a bounded read answers. */
369
+ export interface SpaceCommentThreadsAnswer {
370
+ /** The comments of the threads read, in no particular order: every thread whole. */
371
+ comments: SpaceCommentRow[];
372
+ revision: number;
373
+ /**
374
+ * How many threads the Space holds by status, counted by the server (deleted ones left out), so a pane that holds a
375
+ * part of the Space still knows the totals. Null with `only`, and while the server has not said.
376
+ */
377
+ counts: { open: number; done: number } | null;
378
+ /**
379
+ * The pin number of the first comments that sit on a point or a zone, by comment id, counted by the server among
380
+ * every first comment of their page (deleted ones keep theirs).
381
+ */
382
+ numbers: Readonly<Record<string, number>>;
383
+ /** How many comments Copy changes would report with no checkpoint, counted by the server. Null when not known. */
384
+ changes: number | null;
385
+ /** True while Done threads older than the ones answered are left to read. */
386
+ moreDone: boolean;
387
+ }
388
+
345
389
  /** The page the host shows: its record (null on the Space home), the view slug, and its name when known. */
346
390
  export interface SpaceCommentPage { recordKey: string | null; view?: string | null; name?: string | null }
347
391
 
@@ -352,6 +396,9 @@ export interface SpaceCommentInsert extends SpaceCommentAnchor {
352
396
  body: string;
353
397
  needs?: SpaceCommentNeeds;
354
398
  options?: readonly string[];
399
+ /** With `needs: 'choice'`: the option recommended, and a line under an option (by option). */
400
+ recommended?: string | null;
401
+ option_details?: Readonly<Record<string, string>>;
355
402
  attachments?: readonly SpaceCommentFile[];
356
403
  id?: string;
357
404
  request_id: string;
@@ -367,6 +414,8 @@ export interface SpaceCommentReply {
367
414
  answer_to?: string | null;
368
415
  needs?: SpaceCommentNeeds;
369
416
  options?: readonly string[];
417
+ recommended?: string | null;
418
+ option_details?: Readonly<Record<string, string>>;
370
419
  attachments?: readonly SpaceCommentFile[];
371
420
  id?: string;
372
421
  request_id: string;
@@ -375,12 +424,11 @@ export interface SpaceCommentReply {
375
424
  /**
376
425
  * Space-only host Comments panel and comment store: the comment threads of the page sit in the host's right panel,
377
426
  * beside the chat, instead of a pane inside the Space, and every read and write goes through the host to the Space's
378
- * one comment store (`portal_comments`). Absent while comments are off for the viewer (`unified_comments`), on Sites,
379
- * links, previews and older hosts: a Space then shows no comments at all (no pane, no pins, no highlights, no Comment
380
- * on a selection; Cite stays).
427
+ * one comment store (`portal_comments`). Absent on Sites, links, previews and older hosts: a Space then shows no
428
+ * comments at all (no pane, no pins, no highlights, no Comment on a selection; Cite stays).
381
429
  *
382
430
  * Every write resolves with the stored row (the server stamps author, dates, `change` and `revision`) or rejects with
383
- * an Error whose `code` is the server's (`feature_disabled`, `revision_conflict`, `comment_not_found`, ...).
431
+ * an Error whose `code` is the server's (`comment_forbidden`, `revision_conflict`, `comment_not_found`, ...).
384
432
  */
385
433
  export interface SpaceCommentsTransport {
386
434
  /** Lists a source in the Comments panel until the returned call-back runs. */
@@ -402,6 +450,14 @@ export interface SpaceCommentsTransport {
402
450
  * asks the server for changes only merges them into its copy and answers with the whole page.
403
451
  */
404
452
  list(input: { page: SpaceCommentPageKey; since_revision?: number }): Promise<{ comments: SpaceCommentRow[]; revision: number }>;
453
+ /**
454
+ * A bounded read of the Space's comment threads, for a pane that shows the whole Space: only the threads it lists,
455
+ * each whole (its first comment and its replies), instead of every comment of the Space (`list` with 'all'). See
456
+ * `SpaceCommentThreadsInput`. The host keeps its own copy and asks the server only for what the copy lacks and for
457
+ * what changed since. Resolves null when the server cannot answer this read: the reader then uses `list`. Absent
458
+ * on older hosts: `list` is used. `subscribe` with 'all' says when to read again.
459
+ */
460
+ threads?(input: SpaceCommentThreadsInput): Promise<SpaceCommentThreadsAnswer | null>;
405
461
  /**
406
462
  * Calls `listener` whenever the comments of `page` may have changed (a write here or elsewhere, the window coming
407
463
  * back into focus, the host's poll): the reader lists them again. Returns the call-back that stops it.
@@ -463,6 +519,12 @@ export interface SpaceCommentsTransport {
463
519
  link?(input: { rootId: string; pick: SpaceCommentThreadPick; primary?: boolean }): Promise<SpaceCommentThreadRef | null>;
464
520
  /** Opens a manager thread in the chat (the panel switches to Chat). */
465
521
  openThread?(threadId: string): void;
522
+ /**
523
+ * Opens the page of one comment thread with that thread shown on it, for a host that draws the comments where their
524
+ * page is not open (every Space's open comments, a conversation's comments): each card's "..." then offers Show on
525
+ * page. Absent beside the page itself, where a tap on the card already shows its place.
526
+ */
527
+ showOnPage?(input: { rootId: string }): void;
466
528
  /**
467
529
  * The link that opens the Space page of one comment thread with it revealed (`comment=<root id>`, the link a push
468
530
  * or a chat pill opens), as a full address another person can open: Copy link on a thread card copies it. The host
@@ -477,6 +539,12 @@ export interface SpaceCommentsTransport {
477
539
  * does not cover the page ignores it.
478
540
  */
479
541
  showPage?(): void;
542
+ /**
543
+ * Names the mounted view this transport serves, the same object for its whole life. When a newer version of the
544
+ * view takes its place, the host hands what the comments show (the selected thread, the filters, a new comment
545
+ * being placed) from the old view's token to the new one's (`handOverCommentState`). Absent: nothing is handed.
546
+ */
547
+ viewToken?: object;
480
548
  }
481
549
  /**
482
550
  * The viewer as comments see them. `id` (their user id), when the host gives it, tells their comments by the row's
@@ -1020,7 +1088,7 @@ export interface SpaceDefinition {
1020
1088
  /**
1021
1089
  * The function that runs after a built-in thread action (archive, read, star, Later, delete and their opposites)
1022
1090
  * on a thread one of this Space's items is attached to. The action itself never waits for it. Its `input` is
1023
- * `threadHookInput`.
1091
+ * `threadHookInput`, or `threadIdleInput` for the idle hook.
1024
1092
  */
1025
1093
  threadHooks?: Partial<Record<import('./functions').SpaceThreadHookEvent, string>>;
1026
1094
  /**