@notis_ai/cli 0.2.7 → 0.2.8

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 (177) hide show
  1. package/README.md +15 -0
  2. package/dist/scaffolds/notis-database/app/page.tsx +38 -41
  3. package/dist/scaffolds/notis-database/lib/types.ts +5 -7
  4. package/dist/scaffolds/notis-database/metadata/screenshot-1.png +0 -0
  5. package/dist/scaffolds/notis-database/metadata/screenshot-2.png +0 -0
  6. package/dist/scaffolds/notis-database/metadata/screenshot-3.png +0 -0
  7. package/dist/scaffolds/notis-database/metadata/screenshot-4.png +0 -0
  8. package/dist/scaffolds/notis-database/metadata/screenshot-5.png +0 -0
  9. package/dist/scaffolds/notis-database/metadata/screenshot-fixtures.json +1839 -0
  10. package/dist/scaffolds/notis-database/notis.config.ts +48 -1
  11. package/dist/scaffolds/notis-database/package-lock.json +3935 -0
  12. package/dist/scaffolds/notis-database/package.json +2 -1
  13. package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/package.json +4 -0
  14. package/dist/scaffolds/notis-database/packages/sdk/src/components/DocumentEditor.tsx +93 -0
  15. package/dist/scaffolds/notis-database/packages/sdk/src/components/Markdown.tsx +60 -0
  16. package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/components/MultiSelectActionBar.tsx +7 -2
  17. package/dist/scaffolds/notis-database/packages/sdk/src/config.ts +196 -0
  18. package/dist/scaffolds/notis-database/packages/sdk/src/documents.ts +229 -0
  19. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useDatabaseSchema.ts +85 -0
  20. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useDocument.ts +78 -0
  21. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useDocuments.ts +121 -0
  22. package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/hooks/useMultiSelect.ts +38 -2
  23. package/dist/scaffolds/notis-database/packages/sdk/src/hooks/useUpsertDocument.ts +95 -0
  24. package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/index.ts +30 -1
  25. package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/runtime.ts +76 -17
  26. package/dist/scaffolds/notis-database/packages/sdk/src/styles.css +186 -0
  27. package/dist/scaffolds/notis-database/src/mock-runtime.ts +4 -1
  28. package/dist/scaffolds/notis-journal/CHANGELOG.md +4 -0
  29. package/dist/scaffolds/notis-journal/app/page.tsx +1 -0
  30. package/dist/scaffolds/notis-journal/package-lock.json +4615 -0
  31. package/dist/scaffolds/notis-journal/package.json +2 -2
  32. package/dist/scaffolds/notis-journal/packages/sdk/src/config.ts +52 -1
  33. package/dist/scaffolds/notis-notes/app/page.tsx +39 -46
  34. package/dist/scaffolds/notis-notes/app/phosphor-icons.ts +596 -0
  35. package/dist/scaffolds/notis-notes/lib/visible-properties.ts +144 -0
  36. package/dist/scaffolds/notis-notes/metadata/screenshot-1.png +0 -0
  37. package/dist/scaffolds/notis-notes/metadata/screenshot-2.png +0 -0
  38. package/dist/scaffolds/notis-notes/metadata/screenshot-3.png +0 -0
  39. package/dist/scaffolds/notis-notes/metadata/screenshot-4.png +0 -0
  40. package/dist/scaffolds/notis-notes/metadata/screenshot-5.png +0 -0
  41. package/dist/scaffolds/notis-notes/metadata/screenshot-fixtures.json +752 -0
  42. package/dist/scaffolds/notis-notes/notis.config.ts +48 -3
  43. package/dist/scaffolds/notis-notes/package-lock.json +4636 -0
  44. package/dist/scaffolds/notis-notes/package.json +7 -3
  45. package/dist/scaffolds/notis-notes/packages/sdk/package.json +36 -0
  46. package/dist/scaffolds/notis-notes/packages/sdk/src/components/DocumentEditor.tsx +93 -0
  47. package/dist/scaffolds/notis-notes/packages/sdk/src/components/Markdown.tsx +60 -0
  48. package/dist/scaffolds/notis-notes/packages/sdk/src/components/MultiSelectActionBar.tsx +278 -0
  49. package/dist/scaffolds/notis-notes/packages/sdk/src/components/MultiSelectCheckbox.tsx +91 -0
  50. package/dist/scaffolds/notis-notes/packages/sdk/src/components/MultiSelectDragOverlay.tsx +39 -0
  51. package/dist/scaffolds/notis-notes/packages/sdk/src/config.ts +196 -0
  52. package/dist/scaffolds/notis-notes/packages/sdk/src/documents.ts +229 -0
  53. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useBackend.ts +41 -0
  54. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useDatabaseSchema.ts +85 -0
  55. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useDocument.ts +78 -0
  56. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useDocuments.ts +121 -0
  57. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useMultiSelect.ts +539 -0
  58. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useNotis.ts +34 -0
  59. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useNotisNavigation.ts +49 -0
  60. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useTool.ts +64 -0
  61. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useTools.ts +56 -0
  62. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useTopBarSearch.ts +73 -0
  63. package/dist/scaffolds/notis-notes/packages/sdk/src/hooks/useUpsertDocument.ts +95 -0
  64. package/dist/scaffolds/notis-notes/packages/sdk/src/index.ts +83 -0
  65. package/dist/scaffolds/notis-notes/packages/sdk/src/provider.tsx +43 -0
  66. package/dist/scaffolds/notis-notes/packages/sdk/src/runtime.ts +220 -0
  67. package/dist/scaffolds/notis-notes/packages/sdk/src/styles.css +186 -0
  68. package/dist/scaffolds/notis-notes/packages/sdk/src/ui.ts +15 -0
  69. package/dist/scaffolds/notis-notes/packages/sdk/src/vite.ts +56 -0
  70. package/dist/scaffolds/notis-notes/packages/sdk/tsconfig.json +15 -0
  71. package/dist/scaffolds/notis-random/CHANGELOG.md +12 -2
  72. package/dist/scaffolds/notis-random/app/history/page.tsx +5 -4
  73. package/dist/scaffolds/notis-random/app/page.tsx +141 -74
  74. package/dist/scaffolds/notis-random/components/ui/button.tsx +50 -0
  75. package/dist/scaffolds/notis-random/components/ui/card.tsx +16 -0
  76. package/dist/scaffolds/notis-random/components/ui/input.tsx +23 -0
  77. package/dist/scaffolds/notis-random/lib/notis-tools.ts +26 -7
  78. package/dist/scaffolds/notis-random/lib/rng.ts +179 -19
  79. package/dist/scaffolds/notis-random/lib/roll-record.ts +103 -16
  80. package/dist/scaffolds/notis-random/metadata/screenshot-1.png +0 -0
  81. package/dist/scaffolds/notis-random/metadata/screenshot-2.png +0 -0
  82. package/dist/scaffolds/notis-random/metadata/screenshot-3.png +0 -0
  83. package/dist/scaffolds/notis-random/metadata/screenshot-4.png +0 -0
  84. package/dist/scaffolds/notis-random/metadata/screenshot-5.png +0 -0
  85. package/dist/scaffolds/notis-random/metadata/screenshot-fixtures.json +753 -0
  86. package/dist/scaffolds/notis-random/notis.config.ts +47 -3
  87. package/dist/scaffolds/notis-random/package-lock.json +4513 -0
  88. package/dist/scaffolds/notis-random/package.json +6 -2
  89. package/dist/scaffolds/notis-random/packages/sdk/package.json +36 -0
  90. package/dist/scaffolds/notis-random/packages/sdk/src/components/DocumentEditor.tsx +93 -0
  91. package/dist/scaffolds/notis-random/packages/sdk/src/components/Markdown.tsx +60 -0
  92. package/dist/scaffolds/notis-random/packages/sdk/src/components/MultiSelectActionBar.tsx +278 -0
  93. package/dist/scaffolds/notis-random/packages/sdk/src/components/MultiSelectCheckbox.tsx +91 -0
  94. package/dist/scaffolds/notis-random/packages/sdk/src/components/MultiSelectDragOverlay.tsx +39 -0
  95. package/dist/scaffolds/notis-random/packages/sdk/src/config.ts +196 -0
  96. package/dist/scaffolds/notis-random/packages/sdk/src/documents.ts +229 -0
  97. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useBackend.ts +41 -0
  98. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useDatabaseSchema.ts +85 -0
  99. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useDocument.ts +78 -0
  100. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useDocuments.ts +121 -0
  101. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useMultiSelect.ts +539 -0
  102. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useNotis.ts +34 -0
  103. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useNotisNavigation.ts +49 -0
  104. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useTool.ts +64 -0
  105. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useTools.ts +56 -0
  106. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useTopBarSearch.ts +73 -0
  107. package/dist/scaffolds/notis-random/packages/sdk/src/hooks/useUpsertDocument.ts +95 -0
  108. package/dist/scaffolds/notis-random/packages/sdk/src/index.ts +83 -0
  109. package/dist/scaffolds/notis-random/packages/sdk/src/provider.tsx +43 -0
  110. package/dist/scaffolds/notis-random/packages/sdk/src/runtime.ts +220 -0
  111. package/dist/scaffolds/notis-random/packages/sdk/src/styles.css +186 -0
  112. package/dist/scaffolds/notis-random/packages/sdk/src/ui.ts +15 -0
  113. package/dist/scaffolds/notis-random/packages/sdk/src/vite.ts +56 -0
  114. package/dist/scaffolds/notis-random/packages/sdk/tsconfig.json +15 -0
  115. package/dist/scaffolds/notis-random/tailwind.config.ts +8 -1
  116. package/dist/scaffolds.json +8 -17
  117. package/package.json +2 -1
  118. package/skills/notis-apps/SKILL.md +449 -144
  119. package/skills/notis-apps/cli.md +15 -0
  120. package/skills/notis-cli/SKILL.md +8 -4
  121. package/skills/notis-onboarding/BRIEF.md +93 -0
  122. package/src/cli.js +50 -12
  123. package/src/command-specs/apps.js +154 -21
  124. package/src/command-specs/index.js +2 -0
  125. package/src/command-specs/onboarding.js +216 -0
  126. package/src/command-specs/tools.js +8 -4
  127. package/src/runtime/app-platform.js +65 -4
  128. package/src/runtime/desktop-auth.js +66 -17
  129. package/src/runtime/errors.js +1 -0
  130. package/src/runtime/output.js +9 -2
  131. package/src/runtime/profiles.js +179 -17
  132. package/src/runtime/telemetry.js +92 -0
  133. package/src/runtime/transport.js +26 -1
  134. package/template/.harness/index.html.tmpl +30 -2
  135. package/template/packages/sdk/src/config.ts +38 -1
  136. package/dist/scaffolds/notis-affiliate-prospects/CHANGELOG.md +0 -7
  137. package/dist/scaffolds/notis-affiliate-prospects/README.md +0 -20
  138. package/dist/scaffolds/notis-affiliate-prospects/app/globals.css +0 -42
  139. package/dist/scaffolds/notis-affiliate-prospects/app/layout.tsx +0 -7
  140. package/dist/scaffolds/notis-affiliate-prospects/app/page.tsx +0 -248
  141. package/dist/scaffolds/notis-affiliate-prospects/app/prospects/page.tsx +0 -134
  142. package/dist/scaffolds/notis-affiliate-prospects/app/segments/page.tsx +0 -108
  143. package/dist/scaffolds/notis-affiliate-prospects/components/ui/card.tsx +0 -35
  144. package/dist/scaffolds/notis-affiliate-prospects/index.html +0 -12
  145. package/dist/scaffolds/notis-affiliate-prospects/lib/affiliate-data.ts +0 -218
  146. package/dist/scaffolds/notis-affiliate-prospects/lib/demo-prospects.ts +0 -52
  147. package/dist/scaffolds/notis-affiliate-prospects/lib/notis-tools.ts +0 -100
  148. package/dist/scaffolds/notis-affiliate-prospects/lib/utils.ts +0 -25
  149. package/dist/scaffolds/notis-affiliate-prospects/metadata/screenshot-1.png +0 -0
  150. package/dist/scaffolds/notis-affiliate-prospects/metadata/screenshot-2.png +0 -0
  151. package/dist/scaffolds/notis-affiliate-prospects/metadata/screenshot-3.png +0 -0
  152. package/dist/scaffolds/notis-affiliate-prospects/metadata/screenshot-fixtures.json +0 -187
  153. package/dist/scaffolds/notis-affiliate-prospects/notis.config.ts +0 -65
  154. package/dist/scaffolds/notis-affiliate-prospects/package.json +0 -32
  155. package/dist/scaffolds/notis-affiliate-prospects/packages/sdk/src/config.ts +0 -90
  156. package/dist/scaffolds/notis-affiliate-prospects/packages/sdk/src/hooks/useDatabase.ts +0 -76
  157. package/dist/scaffolds/notis-affiliate-prospects/packages/sdk/src/hooks/useUpsertDocument.ts +0 -50
  158. package/dist/scaffolds/notis-affiliate-prospects/packages/sdk/src/styles.css +0 -38
  159. package/dist/scaffolds/notis-affiliate-prospects/postcss.config.mjs +0 -6
  160. package/dist/scaffolds/notis-affiliate-prospects/src/dev-main.tsx +0 -72
  161. package/dist/scaffolds/notis-affiliate-prospects/src/mock-runtime.ts +0 -242
  162. package/dist/scaffolds/notis-affiliate-prospects/tailwind.config.ts +0 -51
  163. package/dist/scaffolds/notis-affiliate-prospects/tsconfig.json +0 -23
  164. package/dist/scaffolds/notis-affiliate-prospects/vite.config.ts +0 -11
  165. /package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/components/MultiSelectCheckbox.tsx +0 -0
  166. /package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/components/MultiSelectDragOverlay.tsx +0 -0
  167. /package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/hooks/useBackend.ts +0 -0
  168. /package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/hooks/useNotis.ts +0 -0
  169. /package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/hooks/useNotisNavigation.ts +0 -0
  170. /package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/hooks/useTool.ts +0 -0
  171. /package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/hooks/useTools.ts +0 -0
  172. /package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/hooks/useTopBarSearch.ts +0 -0
  173. /package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/provider.tsx +0 -0
  174. /package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/ui.ts +0 -0
  175. /package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/src/vite.ts +0 -0
  176. /package/dist/scaffolds/{notis-affiliate-prospects → notis-database}/packages/sdk/tsconfig.json +0 -0
  177. /package/dist/scaffolds/{notis-affiliate-prospects → notis-random}/components.json +0 -0
@@ -0,0 +1,121 @@
1
+ 'use client';
2
+
3
+ import { useCallback, useEffect, useState } from 'react';
4
+ import { useNotisRuntime } from '../provider';
5
+ import { normalizeDocumentRecord } from '../documents';
6
+ import type { DocumentRecord, QueryFilter } from '../runtime';
7
+
8
+ interface QueryDatabaseResult {
9
+ documents?: unknown[];
10
+ has_more?: boolean;
11
+ next_offset?: number | null;
12
+ message?: string;
13
+ error?: string;
14
+ }
15
+
16
+ export interface UseDocumentsOptions {
17
+ filter?: QueryFilter;
18
+ pageSize?: number;
19
+ offset?: number;
20
+ /** Fetch every page, starting at offset, instead of returning only one page. */
21
+ fetchAll?: boolean;
22
+ enabled?: boolean;
23
+ }
24
+
25
+ export interface UseDocumentsResult {
26
+ documents: DocumentRecord[];
27
+ loading: boolean;
28
+ error: Error | null;
29
+ refetch: () => void;
30
+ }
31
+
32
+ /**
33
+ * Query a Notis database and get normalized `DocumentRecord`s.
34
+ *
35
+ * ```tsx
36
+ * const { documents, loading, refetch } = useDocuments('notes', {
37
+ * filter: { filters: [{ property: 'Folder', operator: 'contains', type: 'relation', value: folderId }] },
38
+ * pageSize: 250,
39
+ * });
40
+ * ```
41
+ */
42
+ export function useDocuments(
43
+ databaseSlug: string,
44
+ options: UseDocumentsOptions = {},
45
+ ): UseDocumentsResult {
46
+ const runtime = useNotisRuntime();
47
+ const [documents, setDocuments] = useState<DocumentRecord[]>([]);
48
+ const [loading, setLoading] = useState(true);
49
+ const [error, setError] = useState<Error | null>(null);
50
+ const [fetchKey, setFetchKey] = useState(0);
51
+
52
+ const enabled = options.enabled !== false;
53
+ const filterKey = JSON.stringify(options.filter ?? null);
54
+
55
+ const refetch = useCallback(() => {
56
+ setFetchKey((key) => key + 1);
57
+ }, []);
58
+
59
+ useEffect(() => {
60
+ if (!runtime || !enabled) {
61
+ setLoading(false);
62
+ return;
63
+ }
64
+
65
+ let cancelled = false;
66
+ setLoading(true);
67
+ setError(null);
68
+
69
+ const filter = filterKey === 'null' ? null : (JSON.parse(filterKey) as QueryFilter);
70
+
71
+ const fetchDocuments = async (): Promise<unknown[]> => {
72
+ const allDocuments: unknown[] = [];
73
+ let offset = options.offset ?? 0;
74
+
75
+ while (true) {
76
+ const result = await runtime.callTool<QueryDatabaseResult>('LOCAL_NOTIS_DATABASE_QUERY', {
77
+ database_slug: databaseSlug,
78
+ query: {
79
+ ...(filter ?? {}),
80
+ ...(options.pageSize !== undefined ? { page_size: options.pageSize } : {}),
81
+ },
82
+ ...(offset > 0 ? { offset } : {}),
83
+ });
84
+ const message = result.error ?? result.message;
85
+ if (!result.documents && message) {
86
+ throw new Error(message);
87
+ }
88
+ allDocuments.push(...(result.documents ?? []));
89
+ if (!options.fetchAll || !result.has_more) return allDocuments;
90
+
91
+ const nextOffset = result.next_offset;
92
+ if (typeof nextOffset !== 'number' || nextOffset <= offset) {
93
+ throw new Error('Database query returned an invalid pagination offset');
94
+ }
95
+ offset = nextOffset;
96
+ }
97
+ };
98
+
99
+ fetchDocuments()
100
+ .then((result) => {
101
+ if (cancelled) return;
102
+ setDocuments(
103
+ result
104
+ .map(normalizeDocumentRecord)
105
+ .filter((document) => document.id),
106
+ );
107
+ setLoading(false);
108
+ })
109
+ .catch((err) => {
110
+ if (cancelled) return;
111
+ setError(err instanceof Error ? err : new Error(String(err)));
112
+ setLoading(false);
113
+ });
114
+
115
+ return () => {
116
+ cancelled = true;
117
+ };
118
+ }, [runtime, databaseSlug, enabled, fetchKey, filterKey, options.fetchAll, options.offset, options.pageSize]);
119
+
120
+ return { documents, loading, error, refetch };
121
+ }
@@ -0,0 +1,539 @@
1
+ 'use client';
2
+
3
+ import {
4
+ useCallback,
5
+ useEffect,
6
+ useMemo,
7
+ useRef,
8
+ useState,
9
+ type MouseEvent as ReactMouseEvent,
10
+ } from 'react';
11
+
12
+ const ROW_ATTR = 'data-notis-row-id';
13
+ const INTERACTIVE_SELECTOR = 'button, a, input, textarea, select, [role="button"]';
14
+
15
+ export interface DragRect {
16
+ left: number;
17
+ top: number;
18
+ width: number;
19
+ height: number;
20
+ }
21
+
22
+ export interface UseMultiSelectOptions<T> {
23
+ items: T[];
24
+ getId: (item: T) => string;
25
+ /** When false, suppresses the global Esc / Cmd+A / X / Shift+Arrow listeners. Default true. */
26
+ bindKeyboardShortcuts?: boolean;
27
+ /** When false, disables the rubber-band drag-select rectangle. Default true. */
28
+ enableDragSelect?: boolean;
29
+ /** Distance (px) the cursor must move past mousedown before a drag begins. Default 5. */
30
+ dragThreshold?: number;
31
+ /** Initial head id (the row that Shift+Arrow extends from). */
32
+ initialHeadId?: string | null;
33
+ /** Fires when the head moves via Shift+Arrow so the consumer can scroll the row into view. */
34
+ onHeadChange?: (id: string | null) => void;
35
+ }
36
+
37
+ export interface MultiSelectController<T> {
38
+ selectedIds: ReadonlySet<string>;
39
+ selectedCount: number;
40
+ lastClickedId: string | null;
41
+ headId: string | null;
42
+ /** Viewport-fixed drag rectangle, or null when no drag is active. */
43
+ dragRect: DragRect | null;
44
+
45
+ isSelected: (id: string) => boolean;
46
+ getSelectedItems: () => T[];
47
+
48
+ toggle: (id: string) => void;
49
+ select: (ids: string[]) => void;
50
+ clear: () => void;
51
+ selectAll: () => void;
52
+ selectRange: (anchorId: string, targetId: string) => void;
53
+ setHead: (id: string | null) => void;
54
+
55
+ /** Click handler for a row's hover checkbox. Toggles, with shift-click range from lastClickedId. */
56
+ onCheckboxClick: (id: string) => (event: ReactMouseEvent) => void;
57
+ /** mousedown on a row body — handles Cmd/Ctrl+click toggle without opening detail. */
58
+ onRowMouseDown: (id: string) => (event: ReactMouseEvent) => void;
59
+
60
+ /** Spread on each selectable row so drag-select can find them. */
61
+ getRowProps: (id: string) => { [ROW_ATTR]: string };
62
+ /**
63
+ * Spread on each selectable row/card — bundles `getRowProps` (the drag-select
64
+ * attribute) with the Cmd/Ctrl+click `onMouseDown` handler in one spread.
65
+ */
66
+ getItemProps: (id: string) => {
67
+ [ROW_ATTR]: string;
68
+ onMouseDown: (event: ReactMouseEvent) => void;
69
+ };
70
+ /** Spread onto `<MultiSelectCheckbox {...getCheckboxProps(id)} />`. */
71
+ getCheckboxProps: (id: string) => {
72
+ isSelected: boolean;
73
+ onClick: (event: ReactMouseEvent) => void;
74
+ };
75
+ /** Spread on the list container — owns the drag-select mousedown/move/up + click-empty-to-clear. */
76
+ getContainerProps: () => {
77
+ ref: (node: HTMLElement | null) => void;
78
+ onMouseDown: (event: ReactMouseEvent) => void;
79
+ onClickCapture: (event: ReactMouseEvent) => void;
80
+ style: { userSelect: 'none' };
81
+ };
82
+ }
83
+
84
+ function isEditableEvent(event: Event): boolean {
85
+ // Notis apps mount inside a Shadow DOM, so a document-level listener sees
86
+ // `event.target` retargeted to the shadow host rather than the real focused
87
+ // element. `composedPath()[0]` pierces the shadow boundary to the actual
88
+ // target, so typing in an app input doesn't trigger selection shortcuts.
89
+ const target = event.composedPath?.()[0] ?? event.target;
90
+ if (!(target instanceof HTMLElement)) return false;
91
+ if (target.isContentEditable) return true;
92
+ const tag = target.tagName;
93
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
94
+ }
95
+
96
+ function rectsIntersect(
97
+ a: { left: number; top: number; right: number; bottom: number },
98
+ b: { left: number; top: number; right: number; bottom: number },
99
+ ): boolean {
100
+ return a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top;
101
+ }
102
+
103
+ export function useMultiSelect<T>(opts: UseMultiSelectOptions<T>): MultiSelectController<T> {
104
+ const {
105
+ items,
106
+ getId,
107
+ bindKeyboardShortcuts = true,
108
+ enableDragSelect = true,
109
+ dragThreshold = 5,
110
+ initialHeadId = null,
111
+ onHeadChange,
112
+ } = opts;
113
+
114
+ const [selectedIds, setSelectedIds] = useState<Set<string>>(() => new Set());
115
+ const [lastClickedId, setLastClickedId] = useState<string | null>(null);
116
+ const [headId, setHeadIdState] = useState<string | null>(initialHeadId);
117
+ const [dragRect, setDragRect] = useState<DragRect | null>(null);
118
+
119
+ // Latest-state refs so document listeners and stable callbacks read fresh
120
+ // values without retriggering the effect.
121
+ const itemsRef = useRef(items);
122
+ const getIdRef = useRef(getId);
123
+ const selectedIdsRef = useRef(selectedIds);
124
+ const lastClickedIdRef = useRef(lastClickedId);
125
+ const headIdRef = useRef(headId);
126
+ const onHeadChangeRef = useRef(onHeadChange);
127
+ const containerRef = useRef<HTMLElement | null>(null);
128
+
129
+ itemsRef.current = items;
130
+ getIdRef.current = getId;
131
+ selectedIdsRef.current = selectedIds;
132
+ lastClickedIdRef.current = lastClickedId;
133
+ headIdRef.current = headId;
134
+ onHeadChangeRef.current = onHeadChange;
135
+
136
+ const orderedIds = useMemo(() => items.map((item) => getId(item)), [items, getId]);
137
+ const orderedIdsRef = useRef(orderedIds);
138
+ orderedIdsRef.current = orderedIds;
139
+
140
+ const isSelected = useCallback((id: string) => selectedIds.has(id), [selectedIds]);
141
+
142
+ const getSelectedItems = useCallback(() => {
143
+ const set = selectedIdsRef.current;
144
+ return itemsRef.current.filter((item) => set.has(getIdRef.current(item)));
145
+ }, []);
146
+
147
+ const setHead = useCallback((id: string | null) => {
148
+ setHeadIdState((prev) => {
149
+ if (prev === id) return prev;
150
+ onHeadChangeRef.current?.(id);
151
+ return id;
152
+ });
153
+ }, []);
154
+
155
+ const toggle = useCallback((id: string) => {
156
+ setSelectedIds((prev) => {
157
+ const next = new Set(prev);
158
+ if (next.has(id)) {
159
+ next.delete(id);
160
+ } else {
161
+ next.add(id);
162
+ }
163
+ return next;
164
+ });
165
+ setLastClickedId(id);
166
+ }, []);
167
+
168
+ const select = useCallback((ids: string[]) => {
169
+ setSelectedIds(new Set(ids));
170
+ setLastClickedId(ids.length > 0 ? ids[ids.length - 1] ?? null : null);
171
+ }, []);
172
+
173
+ const clear = useCallback(() => {
174
+ setSelectedIds((prev) => (prev.size === 0 ? prev : new Set()));
175
+ }, []);
176
+
177
+ const selectAll = useCallback(() => {
178
+ const all = orderedIdsRef.current;
179
+ setSelectedIds(new Set(all));
180
+ setLastClickedId(all.length > 0 ? all[all.length - 1] ?? null : null);
181
+ }, []);
182
+
183
+ const selectRange = useCallback((anchorId: string, targetId: string) => {
184
+ const all = orderedIdsRef.current;
185
+ const anchorIdx = all.indexOf(anchorId);
186
+ const targetIdx = all.indexOf(targetId);
187
+ if (anchorIdx === -1 || targetIdx === -1) {
188
+ setSelectedIds(new Set([targetId]));
189
+ setLastClickedId(targetId);
190
+ return;
191
+ }
192
+ const start = Math.min(anchorIdx, targetIdx);
193
+ const end = Math.max(anchorIdx, targetIdx);
194
+ const range = all.slice(start, end + 1);
195
+ setSelectedIds((prev) => {
196
+ const next = new Set(prev);
197
+ for (const id of range) next.add(id);
198
+ return next;
199
+ });
200
+ setLastClickedId(targetId);
201
+ }, []);
202
+
203
+ const onCheckboxClick = useCallback(
204
+ (id: string) =>
205
+ (event: ReactMouseEvent) => {
206
+ event.stopPropagation();
207
+ if (event.shiftKey && lastClickedIdRef.current && lastClickedIdRef.current !== id) {
208
+ selectRange(lastClickedIdRef.current, id);
209
+ return;
210
+ }
211
+ toggle(id);
212
+ },
213
+ [selectRange, toggle],
214
+ );
215
+
216
+ const onRowMouseDown = useCallback(
217
+ (id: string) =>
218
+ (event: ReactMouseEvent) => {
219
+ if (event.button !== 0) return;
220
+ if (!(event.metaKey || event.ctrlKey)) return;
221
+ const target = event.target as HTMLElement | null;
222
+ if (target && target.closest(INTERACTIVE_SELECTOR)) return;
223
+ event.preventDefault();
224
+ event.stopPropagation();
225
+ toggle(id);
226
+ // The trailing click on the row should NOT open it.
227
+ armSuppressNextClick();
228
+ },
229
+ [toggle],
230
+ );
231
+
232
+ const getRowProps = useCallback(
233
+ (id: string) => ({
234
+ [ROW_ATTR]: id,
235
+ }),
236
+ [],
237
+ );
238
+
239
+ const getItemProps = useCallback(
240
+ (id: string) => ({
241
+ [ROW_ATTR]: id,
242
+ onMouseDown: onRowMouseDown(id),
243
+ }),
244
+ [onRowMouseDown],
245
+ );
246
+
247
+ const getCheckboxProps = useCallback(
248
+ (id: string) => ({
249
+ isSelected: selectedIdsRef.current.has(id),
250
+ onClick: onCheckboxClick(id),
251
+ }),
252
+ [onCheckboxClick],
253
+ );
254
+
255
+ // ---------------------------------------------------------------------------
256
+ // Drag-select
257
+ // ---------------------------------------------------------------------------
258
+
259
+ const dragPendingRef = useRef(false);
260
+ const dragActiveRef = useRef(false);
261
+ const dragStartRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
262
+ const dragCurrentRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
263
+ // Tracks whether the most recent mousedown originated outside any row, which
264
+ // means a bare click should clear the selection.
265
+ const clickShouldClearRef = useRef(false);
266
+ // Set true after a gesture that should NOT trigger the row's onClick: an
267
+ // active drag-select, or a cmd/ctrl-click toggle. The container's
268
+ // onClickCapture consumes the next click before it reaches the row.
269
+ const suppressNextClickRef = useRef(false);
270
+
271
+ const armSuppressNextClick = () => {
272
+ suppressNextClickRef.current = true;
273
+ setTimeout(() => {
274
+ suppressNextClickRef.current = false;
275
+ }, 0);
276
+ };
277
+
278
+ const computeDragRect = useCallback((): DragRect => {
279
+ const start = dragStartRef.current;
280
+ const current = dragCurrentRef.current;
281
+ return {
282
+ left: Math.min(start.x, current.x),
283
+ top: Math.min(start.y, current.y),
284
+ width: Math.abs(current.x - start.x),
285
+ height: Math.abs(current.y - start.y),
286
+ };
287
+ }, []);
288
+
289
+ const computeIntersectingIds = useCallback(
290
+ (rect: { left: number; top: number; right: number; bottom: number }): string[] => {
291
+ const container = containerRef.current;
292
+ if (!container) return [];
293
+ const nodes = container.querySelectorAll<HTMLElement>(`[${ROW_ATTR}]`);
294
+ const ids: string[] = [];
295
+ nodes.forEach((node) => {
296
+ const rowRect = node.getBoundingClientRect();
297
+ if (rectsIntersect(rect, rowRect)) {
298
+ const id = node.getAttribute(ROW_ATTR);
299
+ if (id) ids.push(id);
300
+ }
301
+ });
302
+ return ids;
303
+ },
304
+ [],
305
+ );
306
+
307
+ const setContainerRef = useCallback(
308
+ (node: HTMLElement | null) => {
309
+ containerRef.current = node;
310
+ },
311
+ [],
312
+ );
313
+
314
+ const handleContainerMouseDown = useCallback(
315
+ (event: ReactMouseEvent) => {
316
+ if (event.button !== 0) return;
317
+ const target = event.target as HTMLElement | null;
318
+ if (!target) return;
319
+ // Cmd/Ctrl-click on a row is handled by `onRowMouseDown` (which calls
320
+ // stopPropagation), so we never reach here for that case. Skip if the
321
+ // mousedown lands on an interactive element so its native focus/text
322
+ // behavior is preserved.
323
+ if (target.closest(INTERACTIVE_SELECTOR)) {
324
+ clickShouldClearRef.current = false;
325
+ return;
326
+ }
327
+ const isOnRow = Boolean(target.closest(`[${ROW_ATTR}]`));
328
+ // A click on empty space (not on a row) should clear the selection.
329
+ clickShouldClearRef.current = !isOnRow;
330
+ if (!enableDragSelect) return;
331
+ // Arm a possible drag from anywhere in the container — including row
332
+ // bodies. If the user moves past the threshold we activate a rubber-band
333
+ // selection AND suppress the trailing click on the row.
334
+ dragPendingRef.current = true;
335
+ dragStartRef.current = { x: event.clientX, y: event.clientY };
336
+ dragCurrentRef.current = { x: event.clientX, y: event.clientY };
337
+ },
338
+ [enableDragSelect],
339
+ );
340
+
341
+ // Capture-phase click handler intercepts the trailing click after a drag so
342
+ // the row's bubble-phase onClick (which would open the row) never fires.
343
+ const handleContainerClickCapture = useCallback(
344
+ (event: ReactMouseEvent) => {
345
+ if (suppressNextClickRef.current) {
346
+ suppressNextClickRef.current = false;
347
+ event.stopPropagation();
348
+ event.preventDefault();
349
+ }
350
+ },
351
+ [],
352
+ );
353
+
354
+ // Attach document mousemove/mouseup while a drag is pending or active.
355
+ useEffect(() => {
356
+ if (!enableDragSelect) return;
357
+
358
+ const handleMouseMove = (event: MouseEvent) => {
359
+ if (dragPendingRef.current) {
360
+ const dx = event.clientX - dragStartRef.current.x;
361
+ const dy = event.clientY - dragStartRef.current.y;
362
+ if (Math.abs(dx) > dragThreshold || Math.abs(dy) > dragThreshold) {
363
+ dragPendingRef.current = false;
364
+ dragActiveRef.current = true;
365
+ window.getSelection()?.removeAllRanges();
366
+ dragCurrentRef.current = { x: event.clientX, y: event.clientY };
367
+ setDragRect(computeDragRect());
368
+ }
369
+ return;
370
+ }
371
+ if (!dragActiveRef.current) return;
372
+ event.preventDefault();
373
+ dragCurrentRef.current = { x: event.clientX, y: event.clientY };
374
+ const rect = computeDragRect();
375
+ setDragRect(rect);
376
+ const ids = computeIntersectingIds({
377
+ left: rect.left,
378
+ top: rect.top,
379
+ right: rect.left + rect.width,
380
+ bottom: rect.top + rect.height,
381
+ });
382
+ setSelectedIds(new Set(ids));
383
+ setLastClickedId(ids.length > 0 ? ids[ids.length - 1] ?? null : null);
384
+ };
385
+
386
+ const handleMouseUp = () => {
387
+ const wasPending = dragPendingRef.current;
388
+ const wasActive = dragActiveRef.current;
389
+ dragPendingRef.current = false;
390
+ dragActiveRef.current = false;
391
+ if (wasActive) {
392
+ setDragRect(null);
393
+ clickShouldClearRef.current = false;
394
+ // The trailing click on the row should not open it.
395
+ armSuppressNextClick();
396
+ return;
397
+ }
398
+ if (wasPending && clickShouldClearRef.current) {
399
+ // Bare click on empty space — clear the selection.
400
+ clickShouldClearRef.current = false;
401
+ if (selectedIdsRef.current.size > 0) {
402
+ setSelectedIds(new Set());
403
+ }
404
+ }
405
+ };
406
+
407
+ document.addEventListener('mousemove', handleMouseMove);
408
+ document.addEventListener('mouseup', handleMouseUp);
409
+ return () => {
410
+ document.removeEventListener('mousemove', handleMouseMove);
411
+ document.removeEventListener('mouseup', handleMouseUp);
412
+ };
413
+ }, [computeDragRect, computeIntersectingIds, dragThreshold, enableDragSelect]);
414
+
415
+ // ---------------------------------------------------------------------------
416
+ // Keyboard shortcuts
417
+ // ---------------------------------------------------------------------------
418
+
419
+ useEffect(() => {
420
+ if (!bindKeyboardShortcuts) return;
421
+
422
+ const handleKeyDown = (event: KeyboardEvent) => {
423
+ if (isEditableEvent(event)) return;
424
+
425
+ // Esc — clear selection
426
+ if (event.key === 'Escape') {
427
+ if (selectedIdsRef.current.size > 0) {
428
+ event.preventDefault();
429
+ setSelectedIds(new Set());
430
+ }
431
+ return;
432
+ }
433
+
434
+ // Cmd/Ctrl + A — select all
435
+ if ((event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey) {
436
+ const key = event.key.toLowerCase();
437
+ if (key === 'a') {
438
+ if (orderedIdsRef.current.length === 0) return;
439
+ event.preventDefault();
440
+ const all = orderedIdsRef.current;
441
+ setSelectedIds(new Set(all));
442
+ setLastClickedId(all[all.length - 1] ?? null);
443
+ return;
444
+ }
445
+ }
446
+
447
+ // X — toggle the focused/head row
448
+ if (
449
+ event.key === 'x' &&
450
+ !event.shiftKey &&
451
+ !event.metaKey &&
452
+ !event.ctrlKey &&
453
+ !event.altKey
454
+ ) {
455
+ const targetId = headIdRef.current ?? lastClickedIdRef.current;
456
+ if (!targetId) return;
457
+ event.preventDefault();
458
+ toggle(targetId);
459
+ return;
460
+ }
461
+
462
+ // Shift + ArrowUp / ArrowDown — extend range from anchor
463
+ if (
464
+ (event.key === 'ArrowDown' || event.key === 'ArrowUp') &&
465
+ event.shiftKey &&
466
+ !event.metaKey &&
467
+ !event.ctrlKey &&
468
+ !event.altKey
469
+ ) {
470
+ const all = orderedIdsRef.current;
471
+ if (all.length === 0) return;
472
+ event.preventDefault();
473
+ const direction = event.key === 'ArrowDown' ? 1 : -1;
474
+ const currentHead = headIdRef.current;
475
+ const currentIdx = currentHead ? all.indexOf(currentHead) : -1;
476
+ const newIdx =
477
+ currentIdx === -1
478
+ ? direction === 1
479
+ ? 0
480
+ : all.length - 1
481
+ : Math.min(all.length - 1, Math.max(0, currentIdx + direction));
482
+ if (newIdx === currentIdx) return;
483
+ const newHead = all[newIdx];
484
+ if (!newHead) return;
485
+ const anchorId = lastClickedIdRef.current ?? currentHead ?? newHead;
486
+ const anchorIdx = all.indexOf(anchorId);
487
+ if (anchorIdx === -1) {
488
+ setSelectedIds(new Set([newHead]));
489
+ } else {
490
+ const start = Math.min(anchorIdx, newIdx);
491
+ const end = Math.max(anchorIdx, newIdx);
492
+ setSelectedIds(new Set(all.slice(start, end + 1)));
493
+ }
494
+ if (lastClickedIdRef.current === null) {
495
+ setLastClickedId(anchorId);
496
+ }
497
+ setHead(newHead);
498
+ return;
499
+ }
500
+ };
501
+
502
+ document.addEventListener('keydown', handleKeyDown);
503
+ return () => {
504
+ document.removeEventListener('keydown', handleKeyDown);
505
+ };
506
+ }, [bindKeyboardShortcuts, setHead, toggle]);
507
+
508
+ const getContainerProps = useCallback(
509
+ () => ({
510
+ ref: setContainerRef,
511
+ onMouseDown: handleContainerMouseDown,
512
+ onClickCapture: handleContainerClickCapture,
513
+ style: { userSelect: 'none' as const },
514
+ }),
515
+ [handleContainerClickCapture, handleContainerMouseDown, setContainerRef],
516
+ );
517
+
518
+ return {
519
+ selectedIds,
520
+ selectedCount: selectedIds.size,
521
+ lastClickedId,
522
+ headId,
523
+ dragRect,
524
+ isSelected,
525
+ getSelectedItems,
526
+ toggle,
527
+ select,
528
+ clear,
529
+ selectAll,
530
+ selectRange,
531
+ setHead,
532
+ onCheckboxClick,
533
+ onRowMouseDown,
534
+ getRowProps,
535
+ getItemProps,
536
+ getCheckboxProps,
537
+ getContainerProps,
538
+ };
539
+ }
@@ -0,0 +1,34 @@
1
+ 'use client';
2
+
3
+ import { useNotisRuntime } from '../provider';
4
+ import type { AppDescriptor, CollectionItemDetail, DatabaseDescriptor, RouteDescriptor } from '../runtime';
5
+
6
+ interface NotisContext {
7
+ /** App metadata (id, name, icon, description). Null before runtime loads. */
8
+ app: AppDescriptor | null;
9
+ /** Current route descriptor. Null before runtime loads. */
10
+ route: RouteDescriptor | null;
11
+ /** Databases declared by this app. Empty before runtime loads. */
12
+ databases: DatabaseDescriptor[];
13
+ /** Selected collection item for the current route, when applicable. */
14
+ collectionItem: CollectionItemDetail | null;
15
+ /** Whether the runtime is loaded and available. */
16
+ ready: boolean;
17
+ }
18
+
19
+ /**
20
+ * Access app-level metadata, the current route, declared databases, and the
21
+ * selected collection item. Returns safe defaults when the portal runtime is
22
+ * not available.
23
+ */
24
+ export function useNotis(): NotisContext {
25
+ const runtime = useNotisRuntime();
26
+
27
+ return {
28
+ app: runtime?.app ?? null,
29
+ route: runtime?.route ?? null,
30
+ databases: runtime?.databases ?? [],
31
+ collectionItem: runtime?.context?.collectionItem ?? null,
32
+ ready: runtime !== null,
33
+ };
34
+ }