@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
@@ -0,0 +1,101 @@
1
+ 'use client';
2
+
3
+ import { useCallback } from 'react';
4
+ import { useNotisRuntime } from '../provider';
5
+ import { settledNavigation } from './useNotisNavigation';
6
+
7
+ /** A Settings place a Space may open. Only the Cloud Computer's repository secrets for now. */
8
+ export interface NotisSettingsTarget {
9
+ page: 'cloud-computer';
10
+ section: 'repository-secrets';
11
+ /**
12
+ * The repository the form is prefilled with: its short name (`naturalisation-switzerland`) or `owner/name`, whose
13
+ * short name is kept. Repository secrets are keyed by the short name, in lower case.
14
+ */
15
+ repository?: string;
16
+ /** Open the Add env file (`env_file`) or Add variable (`variable`) form. Without it the section is only shown. */
17
+ add?: 'env_file' | 'variable';
18
+ }
19
+
20
+ export interface UseNotisSettingsResult {
21
+ /** False on a Site, a link, a release preview, a page framed inside another, verify and the vite preview: offer your
22
+ * own fallback there. */
23
+ available: boolean;
24
+ /**
25
+ * Opens Settings on the target, above the Space. Resolves once the host has taken it; rejects on a host that cannot
26
+ * open Settings, on a target it does not know, or when the view is no longer the one on screen. Values are never
27
+ * prefilled: the person types or chooses them in Settings.
28
+ */
29
+ openSettings: (target: NotisSettingsTarget) => Promise<void>;
30
+ }
31
+
32
+ export type NotisSettingsNavigation = {
33
+ kind: 'settings'; page: 'cloud-computer'; section: 'repository-secrets';
34
+ repository?: string; add?: 'env_file' | 'variable';
35
+ };
36
+
37
+ /** The repository-secrets store's rule for a repository (server/lib/database_schema.py SECRET_REPOSITORY_SLUG). */
38
+ const REPOSITORY = /^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/;
39
+ /** A GitHub owner: letters, digits and dashes. */
40
+ const OWNER = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/;
41
+
42
+ /** The short name a repository is kept under (`owner/name` keeps `name`, lower case), or null when it is not one. */
43
+ export function settingsRepositoryName(value: unknown): string | null {
44
+ if (typeof value !== 'string') return null;
45
+ const parts = value.trim().split('/');
46
+ if (parts.length > 2 || (parts.length === 2 && !OWNER.test(parts[0]))) return null;
47
+ const name = parts[parts.length - 1].toLowerCase();
48
+ return REPOSITORY.test(name) ? name : null;
49
+ }
50
+
51
+ const TARGET_KEYS = ['page', 'section', 'repository', 'add'];
52
+
53
+ /** The payload `openSettings` sends the host, or an Error naming what is wrong. Hosts check it again with this. */
54
+ export function settingsNavigation(target: unknown): NotisSettingsNavigation | Error {
55
+ if (!target || typeof target !== 'object' || Array.isArray(target)) return new Error('Name the Settings page to open.');
56
+ const fields = target as Record<string, unknown>;
57
+ if (Object.keys(fields).some(key => fields[key] !== undefined && !TARGET_KEYS.includes(key))) {
58
+ return new Error('openSettings takes page, section, repository and add.');
59
+ }
60
+ if (fields.page !== 'cloud-computer' || fields.section !== 'repository-secrets') {
61
+ return new Error("Spaces open Settings on { page: 'cloud-computer', section: 'repository-secrets' }.");
62
+ }
63
+ if (fields.add !== undefined && fields.add !== 'env_file' && fields.add !== 'variable') {
64
+ return new Error("add is 'env_file' or 'variable'.");
65
+ }
66
+ let repository: string | undefined;
67
+ if (fields.repository !== undefined) {
68
+ const name = settingsRepositoryName(fields.repository);
69
+ if (!name) return new Error('Name the repository by its short name or owner/name.');
70
+ repository = name;
71
+ }
72
+ return { kind: 'settings', page: 'cloud-computer', section: 'repository-secrets',
73
+ ...(repository ? { repository } : {}), ...(fields.add ? { add: fields.add as 'env_file' | 'variable' } : {}) };
74
+ }
75
+
76
+ /**
77
+ * Opens the host's Settings from a Space view, such as the repository secrets form for one repository.
78
+ *
79
+ * ```tsx
80
+ * const settings = useNotisSettings();
81
+ * <button disabled={!settings.available}
82
+ * onClick={() => settings.openSettings({ page: 'cloud-computer', section: 'repository-secrets',
83
+ * repository: 'naturalisation-switzerland', add: 'env_file' })}>Add .env file</button>
84
+ * ```
85
+ *
86
+ * The same place has a plain address a Space or an email can link to:
87
+ * `/manage?settings=cloud&settings_section=repository-secrets&settings_repository=<name>&settings_add=env_file`.
88
+ */
89
+ export function useNotisSettings(): UseNotisSettingsResult {
90
+ const runtime = useNotisRuntime();
91
+ const available = Boolean(runtime?.settingsAvailable && runtime.navigate);
92
+ const openSettings = useCallback(async (target: NotisSettingsTarget) => {
93
+ if (!runtime?.settingsAvailable || !runtime.navigate) {
94
+ throw new Error('Settings open only from a Space page in Notis, signed in.');
95
+ }
96
+ const payload = settingsNavigation(target);
97
+ if (payload instanceof Error) throw payload;
98
+ await settledNavigation(() => runtime.navigate!(payload));
99
+ }, [runtime]);
100
+ return { available, openSettings };
101
+ }
@@ -28,7 +28,7 @@ export type { SpaceViewParam, SpaceViewParamType, SpaceViewFilter, SpaceShows, S
28
28
  export { SPACE_VIEWER_READ_OPERATIONS } from './space';
29
29
  export { SPACE_CLOUD_COMPUTER_OPERATIONS, spaceCloudComputerAllows } from './space';
30
30
  export { spaceCloudComputerAccess } from './space';
31
- export type { SpaceCloudComputerLevel, SpaceCloudComputerOperation, SpaceCloudComputerStatus, SpaceCloudComputerRelease, SpaceCloudComputerRunInput,
31
+ export type { SpaceCloudComputerLevel, SpaceCloudComputerOperation, SpaceCloudComputerStatus, SpaceCloudComputerRelease, SpaceCloudComputerCopy, SpaceCloudComputerRunInput,
32
32
  SpaceCloudComputerRunResult, SpaceCloudComputerUploadInput, SpaceCloudComputerUploadResult, SpaceCloudComputerTransport,
33
33
  SpaceCloudComputerDeclaration, SpaceCloudComputerService, SpaceCloudComputerJobOperation, SpaceCloudComputerJobInput,
34
34
  SpaceCloudComputerJobStatus, SpaceCloudComputerJobLogs, SpaceCloudComputerJobResult, SpaceCloudComputerLeaseInput,
@@ -41,7 +41,10 @@ export type { SpaceViewerReadFamily, SpaceViewerReadOperation, SpaceViewerReadIn
41
41
  export type { SpaceAgentDeclaration, SpaceItemThread, SpaceAgentQueue, SpaceAgentsStatus, SpaceThreadsTransport,
42
42
  SpaceThreadItemText, SpaceThreadItemCondition, SpaceThreadItemState, SpaceThreadItemConfirm, SpaceThreadItemAction,
43
43
  SpaceThreadItemKind, SpaceThreadItem, SpaceThreadItemRun, SpaceThreadItemTransport,
44
- SpaceCommentSource, SpaceCommentsTransport, SpaceCommentViewer, SpaceCommentThreadRef, SpaceCommentThreadPick } from './space';
44
+ SpaceCommentSource, SpaceCommentsTransport, SpaceCommentViewer, SpaceCommentThreadRef, SpaceCommentThreadPick,
45
+ SpaceCommentAnchor, SpaceCommentAttachment, SpaceCommentChange, SpaceCommentFile, SpaceCommentInsert, SpaceCommentMode,
46
+ SpaceCommentNeeds, SpaceCommentPage, SpaceCommentPageKey, SpaceCommentReply, SpaceCommentRow, SpaceCommentStatus,
47
+ SpaceCommentThreadsAnswer, SpaceCommentThreadsInput } from './space';
45
48
  export { SpaceActionError, SpaceNavigationCancelled, isSpaceNavigationCancelled } from './space';
46
49
  export { spaceAudience, spaceMarksEditorsOnly, publicSpaceDescriptor, withoutEditorColumns } from './space';
47
50
  export type { SpaceAudience, SpaceEditorsOnly, SpaceResourceColumns, EditorOnlyColumns, AudienceRow } from './space';
@@ -76,9 +79,18 @@ export { useHandover } from './hooks/useHandover';
76
79
  export type { UseHandoverResult } from './hooks/useHandover';
77
80
  export { useCloudComputer } from './hooks/useCloudComputer';
78
81
  export type { UseCloudComputerResult } from './hooks/useCloudComputer';
82
+ export { useConnection } from './hooks/useConnection';
83
+ export type { UseConnectionResult } from './hooks/useConnection';
84
+ export type { SpaceConnection, SpaceConnectionsTransport } from './space';
79
85
  export { useItemThread } from './hooks/useItemThread';
80
86
  export type { UseItemThreadResult } from './hooks/useItemThread';
81
87
  export { useThreadItem } from './hooks/useThreadItem';
88
+ export { useFunction, useFunctionQuery } from './hooks/useFunction';
89
+ export { threadHookInput, threadIdleInput, threadSettleInput, commentOptionInput } from './functions';
90
+ export type { SpaceFunctionDeclaration, SpaceFunctionHandler, SpaceFunctionContext, SpaceFunctionKind, SpaceFunctionExposure,
91
+ SpaceFunctionRole, SpaceFunctionUses, SpaceThreadOperation, SpaceThreadHookEvent, SpaceThreadHookInput, SpaceThreadIdleInput, SpaceThreadSettleInput,
92
+ SpaceCommentOption, SpaceCommentOptionInput, SpaceFunctionThread, SpaceFunctionThreadItem, SpaceFunctionCloudComputer, SpaceFunctionDescriptor,
93
+ SpaceFunctionCallOptions } from './functions';
82
94
  export type { UseThreadItemResult } from './hooks/useThreadItem';
83
95
  export { useAgentQueue, AGENT_QUEUE_WORDS } from './hooks/useAgentQueue';
84
96
  export type { UseAgentQueueResult, AgentQueueStatus } from './hooks/useAgentQueue';
@@ -90,6 +102,8 @@ export { useCloudComputerJob } from './hooks/useCloudComputerJob';
90
102
  export type { UseCloudComputerJobOptions, UseCloudComputerJobResult } from './hooks/useCloudComputerJob';
91
103
  export { CLOUD_COMPUTER_WORDS, cloudComputerPriceWords, formatHourlyPrice } from './cloudComputerWords';
92
104
  export { useNotisNavigation } from './hooks/useNotisNavigation';
105
+ export { useNotisSettings } from './hooks/useNotisSettings';
106
+ export type { NotisSettingsTarget, UseNotisSettingsResult } from './hooks/useNotisSettings';
93
107
  export { useTopBarSearch } from './hooks/useTopBarSearch';
94
108
  export { useTopBarTitleLeaf } from './hooks/useTopBarTitleLeaf';
95
109
  export { useBackend } from './hooks/useBackend';
@@ -234,7 +248,5 @@ export { isInteractionElementVisible } from './interactions/visibility';
234
248
 
235
249
  export type { AgentContextContent, AgentContextItem, ContextAttachment } from './agentContext';
236
250
  export { useAgentContext } from './hooks/useAgentContext';
237
- export { NotisCommentBoundary, NotisCommentBox } from './components/NotisCommentBoundary';
238
- export type { NotisCommentBoundaryProps, NotisCommentBoxProps } from './components/NotisCommentBoundary';
239
251
  export { VIEW_PERIODS, isViewDate, isViewPeriod, resolveViewPeriod } from './viewPeriod';
240
252
  export { journalViewParams, tasksViewParams, tasksViewFilter } from './standardViewParams';
@@ -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';
@@ -11,7 +11,7 @@ import type { AgentContextContent, AgentContextItem, AgentContextSource } from '
11
11
  import type { ComponentType, ReactNode } from 'react';
12
12
  import type { NotisQueryClient } from './queryCache';
13
13
  import type { NotisSpaceSkeleton } from './skeleton';
14
- import type { SpaceRuntimeDescriptor, SpaceActionOptions, SpaceDocumentBodyRequest, SpaceDocumentBodyResult, SpaceViewerReadOperation, SpaceShownOptions, SpaceCloudComputerTransport, SpaceFilesTransport, SpaceThreadsTransport, SpaceThreadItemTransport, SpaceCommentsTransport } from './space';
14
+ import type { SpaceRuntimeDescriptor, SpaceActionOptions, SpaceDocumentBodyRequest, SpaceDocumentBodyResult, SpaceViewerReadOperation, SpaceShownOptions, SpaceCloudComputerTransport, SpaceConnectionsTransport, SpaceFilesTransport, SpaceThreadsTransport, SpaceThreadItemTransport, SpaceCommentsTransport } from './space';
15
15
 
16
16
  // ---------------------------------------------------------------------------
17
17
  // Database types
@@ -596,6 +596,9 @@ export interface RuntimeResource {
596
596
  export interface NotisRuntime {
597
597
  space?: SpaceRuntimeDescriptor;
598
598
  callAction?<TResult = unknown>(actionId: string, inputs?: Record<string, unknown>, options?: SpaceActionOptions): Promise<TResult>;
599
+ /** Space-only: run one of the Space's functions exposed to its views. Absent on hosts that predate functions. */
600
+ callFunction?<TResult = unknown>(name: string, input?: Record<string, unknown>,
601
+ options?: import('./functions').SpaceFunctionCallOptions): Promise<TResult>;
599
602
  documentBody?(request: SpaceDocumentBodyRequest): Promise<SpaceDocumentBodyResult>;
600
603
  /**
601
604
  * Space-only declared viewer read (`viewerReads`): what the signed-in viewer can open,
@@ -619,6 +622,11 @@ export interface NotisRuntime {
619
622
  * viewer allows it. Absent on Sites, links, verification harnesses and older hosts.
620
623
  */
621
624
  spaceCloudComputer?: SpaceCloudComputerTransport;
625
+ /**
626
+ * Space-only connected apps (`useConnection`): the signed-in viewer's own account in one app, and the Portal's
627
+ * connect flow from the person's click. Absent on Sites, links, verification harnesses and older hosts.
628
+ */
629
+ spaceConnections?: SpaceConnectionsTransport;
622
630
  /**
623
631
  * Space-only files attached from a view to a database's files column (comment pictures): the signed-in Editor's
624
632
  * own upload into Notis's private EU storage. Absent on Sites, previews, verification harnesses and older hosts.
@@ -705,6 +713,13 @@ export interface NotisRuntime {
705
713
  */
706
714
  navigate?: (payload: { kind: string; [key: string]: unknown }) => NotisNavigationAnswer | Promise<NotisNavigationAnswer>;
707
715
 
716
+ /**
717
+ * True when this host opens its own Settings from `navigate({ kind: 'settings', ... })` (`useNotisSettings()`):
718
+ * a signed-in viewer's Space page in the Portal. Absent on a Site, a link, a release preview, verify and the vite
719
+ * preview.
720
+ */
721
+ settingsAvailable?: boolean;
722
+
708
723
  registerTopBarSearch?: (
709
724
  config:
710
725
  | {