@startsimpli/integrations 0.2.82 → 0.2.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,22 @@
1
1
  /**
2
2
  * The state machine behind a notes list + detail, framework-free so a web page
3
- * and a native screen can share it: load, poll while anything is transcribing,
4
- * move a note to another project (optimistic, rolled back on failure), retry a
5
- * failed note, delete.
3
+ * and a native screen can share it: load, search / filter by project / order and
4
+ * page (all SERVER parameters, bd startsim-23np6.3), poll while anything is
5
+ * transcribing, move a note to another project (optimistic, rolled back on
6
+ * failure), retry a failed note, delete.
7
+ *
8
+ * Nothing here loads a list and narrows it locally. A client that cannot page
9
+ * (`api.listPage` absent) still works as a plain `list()`, with `canQuery` false
10
+ * so a screen hides the search / filter / order controls instead of faking them.
6
11
  */
7
- import type { VoiceFocus, VoiceNote, VoiceNotesApi } from '../../corpus/voice';
12
+ import type { VoiceFocus, VoiceNote, VoiceNoteOrder, VoiceNotesApi, VoiceNotesQuery } from '../../corpus/voice';
13
+
14
+ export interface VoiceNotesFilters {
15
+ search: string;
16
+ /** Only notes filed under this project; null = all. */
17
+ focusId: string | null;
18
+ order: VoiceNoteOrder;
19
+ }
8
20
 
9
21
  export interface VoiceNotesState {
10
22
  /** null until the first load finishes. */
@@ -12,21 +24,44 @@ export interface VoiceNotesState {
12
24
  focuses: VoiceFocus[];
13
25
  refreshing: boolean;
14
26
  error: string | null;
27
+ query: VoiceNotesFilters;
28
+ /** Total notes matching the query, from the server's count (null until known). */
29
+ count: number | null;
30
+ hasMore: boolean;
31
+ loadingMore: boolean;
32
+ /** Query parts the server did not apply: `search`, `order`, `related_to`. */
33
+ ignoredFilters: string[];
34
+ /** A note opened by id that is not in the loaded pages (a deep link, or one moved out of the filter). */
35
+ opened: VoiceNote | null;
36
+ opening: boolean;
15
37
  }
16
38
 
17
39
  export interface VoiceNotesController {
18
40
  getState(): VoiceNotesState;
19
41
  subscribe(listener: () => void): () => void;
42
+ /** Re-read from page 1 with the current query. */
20
43
  refresh(): Promise<void>;
21
44
  /** Load once and keep polling while any note is processing. */
22
45
  start(): void;
23
46
  stop(): void;
47
+ setSearch(text: string): Promise<void>;
48
+ setFocusFilter(focusId: string | null): Promise<void>;
49
+ setOrder(order: VoiceNoteOrder): Promise<void>;
50
+ clearFilters(): Promise<void>;
51
+ /** Append the next page (no-op when there is none or one is already loading). */
52
+ loadMore(): Promise<void>;
53
+ /** Make a note available to a detail screen even when it is not on a loaded page. */
54
+ open(noteId: string): Promise<void>;
24
55
  file(noteId: string, focusId: string | null): Promise<void>;
56
+ fileSection(noteId: string, sectionIndex: number, focusId: string | null): Promise<void>;
25
57
  retry(noteId: string): Promise<void>;
26
58
  remove(noteId: string): Promise<void>;
27
59
  clearError(): void;
28
60
  readonly canRetry: boolean;
29
61
  readonly canRemove: boolean;
62
+ readonly canFileSection: boolean;
63
+ /** True when the api can search / filter / order / page on the server. */
64
+ readonly canQuery: boolean;
30
65
  }
31
66
 
32
67
  export interface VoiceNotesControllerOptions {
@@ -35,66 +70,199 @@ export interface VoiceNotesControllerOptions {
35
70
  pollMs?: number;
36
71
  }
37
72
 
73
+ export const EMPTY_NOTES_QUERY: VoiceNotesFilters = { search: '', focusId: null, order: 'recent' };
74
+
38
75
  const message = (e: unknown) => (e instanceof Error && e.message ? e.message : 'That did not work.');
39
76
 
77
+ export function toApiQuery(f: VoiceNotesFilters): VoiceNotesQuery {
78
+ const search = f.search.trim();
79
+ return { ...(search ? { search } : {}), ...(f.focusId ? { focusId: f.focusId } : {}), order: f.order };
80
+ }
81
+
40
82
  export function createVoiceNotesController(options: VoiceNotesControllerOptions): VoiceNotesController {
41
83
  const { api } = options;
42
84
  const pollMs = options.pollMs ?? 3000;
43
- let state: VoiceNotesState = { notes: null, focuses: [], refreshing: false, error: null };
85
+ let state: VoiceNotesState = {
86
+ notes: null, focuses: [], refreshing: false, error: null,
87
+ query: EMPTY_NOTES_QUERY, count: null, hasMore: false, loadingMore: false, ignoredFilters: [],
88
+ opened: null, opening: false,
89
+ };
44
90
  const listeners = new Set<() => void>();
45
91
  let timer: ReturnType<typeof setTimeout> | null = null;
46
92
  let running = false;
47
93
  let focusesLoaded = false;
94
+ let nextPage: number | null = null;
95
+ /** Bumped by every restart from page 1; a response from an older one is dropped. */
96
+ let generation = 0;
97
+ let openRequest: string | null = null;
48
98
 
49
99
  const set = (patch: Partial<VoiceNotesState>) => {
50
100
  state = { ...state, ...patch };
51
101
  listeners.forEach((l) => l());
52
102
  };
103
+ /** Change one note wherever it is held: the loaded pages and the opened slot. */
53
104
  const mapNote = (id: string, fn: (n: VoiceNote) => VoiceNote) =>
54
- set({ notes: state.notes?.map((n) => (n.id === id ? fn(n) : n)) ?? state.notes });
105
+ set({
106
+ notes: state.notes?.map((n) => (n.id === id ? fn(n) : n)) ?? state.notes,
107
+ opened: state.opened?.id === id ? fn(state.opened) : state.opened,
108
+ });
109
+ const findNote = (id: string) => state.notes?.find((n) => n.id === id) ?? (state.opened?.id === id ? state.opened : undefined);
110
+ const processingIds = () => {
111
+ const ids = new Set((state.notes ?? []).filter((n) => n.status === 'processing').map((n) => n.id));
112
+ if (state.opened?.status === 'processing') ids.add(state.opened.id);
113
+ return [...ids];
114
+ };
55
115
 
56
116
  function schedule() {
57
117
  if (timer) { clearTimeout(timer); timer = null; }
58
- if (!running || !state.notes?.some((n) => n.status === 'processing')) return;
59
- timer = setTimeout(() => { timer = null; void refresh(); }, pollMs);
118
+ if (!running || processingIds().length === 0) return;
119
+ timer = setTimeout(() => { timer = null; void poll(); }, pollMs);
120
+ }
121
+
122
+ function loadFocuses() {
123
+ if (focusesLoaded) return;
124
+ focusesLoaded = true;
125
+ api.listFocuses().then((focuses) => set({ focuses })).catch(() => { focusesLoaded = false; });
60
126
  }
61
127
 
62
128
  async function refresh() {
129
+ const mine = ++generation;
63
130
  set({ refreshing: true });
64
131
  try {
65
- const notes = await api.list();
66
- set({ notes, error: null });
67
- if (!focusesLoaded) {
68
- focusesLoaded = true;
69
- api.listFocuses().then((focuses) => set({ focuses })).catch(() => { focusesLoaded = false; });
132
+ if (api.listPage) {
133
+ const page = await api.listPage(toApiQuery(state.query), 1);
134
+ if (mine !== generation) return;
135
+ nextPage = page.nextPage;
136
+ set({ notes: page.notes, count: page.count, hasMore: page.nextPage !== null, loadingMore: false, ignoredFilters: page.ignoredFilters, error: null });
137
+ } else {
138
+ const notes = await api.list();
139
+ if (mine !== generation) return;
140
+ nextPage = null;
141
+ set({ notes, count: notes.length, hasMore: false, loadingMore: false, ignoredFilters: [], error: null });
70
142
  }
143
+ loadFocuses();
144
+ } catch (e) {
145
+ if (mine === generation) set({ error: message(e) });
146
+ } finally {
147
+ if (mine === generation) { set({ refreshing: false }); schedule(); }
148
+ }
149
+ }
150
+
151
+ /**
152
+ * The poll re-reads ONLY the notes still processing and patches them in place.
153
+ * Re-running page 1 would throw away every page the user has scrolled to.
154
+ */
155
+ async function poll() {
156
+ if (!api.listPage) { await refresh(); return; }
157
+ const mine = generation;
158
+ const ids = processingIds();
159
+ try {
160
+ const page = await api.listPage({ ids }, 1);
161
+ if (mine !== generation) return;
162
+ const fresh = new Map(page.notes.map((n) => [n.id, n]));
163
+ set({
164
+ notes: state.notes?.map((n) => fresh.get(n.id) ?? n) ?? state.notes,
165
+ opened: state.opened ? fresh.get(state.opened.id) ?? state.opened : null,
166
+ });
71
167
  } catch (e) {
72
- set({ error: message(e) });
168
+ if (mine === generation) set({ error: message(e) });
73
169
  } finally {
74
- set({ refreshing: false });
75
- schedule();
170
+ if (mine === generation) schedule();
76
171
  }
77
172
  }
78
173
 
174
+ async function applyQuery(next: VoiceNotesFilters) {
175
+ if (!api.listPage) return;
176
+ set({ query: next });
177
+ await refresh();
178
+ }
179
+
79
180
  return {
80
181
  getState: () => state,
81
182
  subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
82
183
  refresh,
83
184
  start() { running = true; void refresh(); },
84
185
  stop() { running = false; if (timer) { clearTimeout(timer); timer = null; } },
186
+
187
+ async setSearch(text) {
188
+ if (!api.listPage) return;
189
+ // "Best match" ranks a search; with no term there is nothing to be relevant TO.
190
+ const order = !text.trim() && state.query.order === 'relevance' ? 'recent' : state.query.order;
191
+ const next = { ...state.query, search: text, order };
192
+ if (text.trim() === state.query.search.trim() && order === state.query.order) { set({ query: next }); return; }
193
+ await applyQuery(next);
194
+ },
195
+ setFocusFilter: (focusId) => applyQuery({ ...state.query, focusId }),
196
+ setOrder: (order) => applyQuery({ ...state.query, order }),
197
+ clearFilters: () => applyQuery(EMPTY_NOTES_QUERY),
198
+
199
+ async loadMore() {
200
+ if (!api.listPage || nextPage === null || state.loadingMore || state.refreshing) return;
201
+ const mine = generation;
202
+ const page = nextPage;
203
+ set({ loadingMore: true });
204
+ try {
205
+ const result = await api.listPage(toApiQuery(state.query), page);
206
+ if (mine !== generation) return;
207
+ const have = new Set((state.notes ?? []).map((n) => n.id));
208
+ nextPage = result.nextPage;
209
+ set({
210
+ notes: [...(state.notes ?? []), ...result.notes.filter((n) => !have.has(n.id))],
211
+ count: result.count, hasMore: result.nextPage !== null, loadingMore: false, error: null,
212
+ });
213
+ } catch (e) {
214
+ if (mine === generation) set({ loadingMore: false, error: message(e) });
215
+ }
216
+ },
217
+
218
+ async open(noteId) {
219
+ openRequest = noteId;
220
+ const loaded = state.notes?.find((n) => n.id === noteId);
221
+ if (loaded) { set({ opened: null, opening: false }); return; }
222
+ if (state.opened?.id === noteId || !api.listPage) return;
223
+ set({ opening: true });
224
+ try {
225
+ const page = await api.listPage({ ids: [noteId] }, 1);
226
+ if (openRequest !== noteId) return;
227
+ set({ opened: page.notes[0] ?? null, opening: false });
228
+ schedule();
229
+ } catch {
230
+ if (openRequest === noteId) set({ opening: false });
231
+ }
232
+ },
233
+
85
234
  async file(noteId, focusId) {
86
- const previous = state.notes?.find((n) => n.id === noteId)?.focusId ?? null;
235
+ const previous = findNote(noteId)?.focusId ?? null;
87
236
  mapNote(noteId, (n) => ({ ...n, focusId }));
88
237
  try {
89
238
  await api.file(noteId, focusId);
90
239
  } catch (e) {
91
240
  mapNote(noteId, (n) => ({ ...n, focusId: previous }));
92
241
  set({ error: message(e) });
242
+ return;
243
+ }
244
+ // A project filter is a server query: a note moved out of it leaves it on the next read.
245
+ if (state.query.focusId) await refresh();
246
+ },
247
+
248
+ async fileSection(noteId, sectionIndex, focusId) {
249
+ if (!api.fileSection) return;
250
+ const before = findNote(noteId)?.sections;
251
+ const apply = (sections: NonNullable<VoiceNote['sections']>) => mapNote(noteId, (n) => ({ ...n, sections }));
252
+ if (before) apply(before.map((s, i) => (i === sectionIndex ? { ...s, focusId } : s)));
253
+ try {
254
+ await api.fileSection(noteId, sectionIndex, focusId);
255
+ } catch (e) {
256
+ if (before) apply(before);
257
+ set({ error: message(e) });
258
+ return;
93
259
  }
260
+ if (state.query.focusId) await refresh();
94
261
  },
262
+
95
263
  async retry(noteId) {
96
264
  if (!api.retry) return;
97
- const before = state.notes?.find((n) => n.id === noteId);
265
+ const before = findNote(noteId);
98
266
  mapNote(noteId, (n) => ({ ...n, status: 'processing', error: undefined }));
99
267
  try {
100
268
  await api.retry(noteId);
@@ -105,18 +273,26 @@ export function createVoiceNotesController(options: VoiceNotesControllerOptions)
105
273
  }
106
274
  await refresh();
107
275
  },
276
+
108
277
  async remove(noteId) {
109
278
  if (!api.remove) return;
110
- const before = state.notes;
111
- set({ notes: before?.filter((n) => n.id !== noteId) ?? before });
279
+ const before = { notes: state.notes, count: state.count, opened: state.opened };
280
+ set({
281
+ notes: before.notes?.filter((n) => n.id !== noteId) ?? before.notes,
282
+ count: before.count !== null && before.notes?.some((n) => n.id === noteId) ? before.count - 1 : before.count,
283
+ opened: before.opened?.id === noteId ? null : before.opened,
284
+ });
112
285
  try {
113
286
  await api.remove(noteId);
114
287
  } catch (e) {
115
- set({ notes: before, error: message(e) });
288
+ set({ ...before, error: message(e) });
116
289
  }
117
290
  },
291
+
118
292
  clearError() { set({ error: null }); },
119
293
  get canRetry() { return Boolean(api.retry); },
120
294
  get canRemove() { return Boolean(api.remove); },
295
+ get canFileSection() { return Boolean(api.fileSection); },
296
+ get canQuery() { return Boolean(api.listPage); },
121
297
  };
122
298
  }
@@ -29,25 +29,72 @@ export function sampleVoiceFocuses(): VoiceFocus[] {
29
29
  return [{ id: 'f287', title: '287A' }, { id: 'fma', title: 'Marketing agents' }, { id: 'fdbg', title: 'Debug' }];
30
30
  }
31
31
 
32
- export function createFakeVoiceApi(options: { notes?: VoiceNote[]; focuses?: VoiceFocus[]; processingPolls?: number } = {}): VoiceNotesApi {
32
+ export interface FakeVoiceApiOptions {
33
+ notes?: VoiceNote[];
34
+ focuses?: VoiceFocus[];
35
+ processingPolls?: number;
36
+ /** Notes per page for `listPage`. Default 25. */
37
+ pageSize?: number;
38
+ /** Query parts to behave like an older server: not applied, and reported ignored. */
39
+ unsupported?: Array<'search' | 'order' | 'related_to'>;
40
+ }
41
+
42
+ const hay = (n: VoiceNote) => `${n.title} ${n.summary} ${n.transcript}`.toLowerCase();
43
+ const filedUnder = (n: VoiceNote, focusId: string) =>
44
+ n.focusId === focusId || (n.focusIds ?? []).includes(focusId) || (n.sections ?? []).some((s) => s.focusId === focusId);
45
+
46
+ export function createFakeVoiceApi(options: FakeVoiceApiOptions = {}): VoiceNotesApi {
33
47
  let notes = options.notes ?? sampleVoiceNotes();
34
48
  const focuses = options.focuses ?? sampleVoiceFocuses();
35
49
  const polls = options.processingPolls ?? 2;
50
+ const pageSize = options.pageSize ?? 25;
51
+ const unsupported = new Set(options.unsupported ?? []);
36
52
  const waiting = new Map<string, number>();
37
53
  const finish = (n: VoiceNote): VoiceNote => ({ ...n, status: 'ready', error: undefined, title: n.title.startsWith('Voice note') ? 'Garage shelves' : n.title, summary: n.summary || 'Buy brackets and build the garage shelves this weekend.', transcript: n.transcript || 'Buy brackets and build the garage shelves this weekend.' });
54
+ /** Every read moves a processing note one step closer to ready. */
55
+ const advance = () => {
56
+ notes = notes.map((n) => {
57
+ if (n.status !== 'processing') return n;
58
+ const seen = (waiting.get(n.id) ?? 0) + 1;
59
+ waiting.set(n.id, seen);
60
+ return seen > polls ? finish(n) : n;
61
+ });
62
+ };
63
+ const at = (n: VoiceNote) => (n.occurredAt ? Date.parse(n.occurredAt) : 0);
38
64
  return {
39
65
  async submit() { throw new Error('The fake api does not record.'); },
40
66
  async list() {
41
- notes = notes.map((n) => {
42
- if (n.status !== 'processing') return n;
43
- const seen = (waiting.get(n.id) ?? 0) + 1;
44
- waiting.set(n.id, seen);
45
- return seen > polls ? finish(n) : n;
46
- });
67
+ advance();
47
68
  return notes.map((n) => ({ ...n }));
48
69
  },
70
+ // Same semantics as the entities API: a filter is applied by the "server" (here, this function), and reported
71
+ // ignored when `unsupported` says this server predates it.
72
+ async listPage(query, page) {
73
+ advance();
74
+ const term = unsupported.has('search') ? '' : (query.search ?? '').trim().toLowerCase();
75
+ let rows = notes.filter((n) => !query.ids?.length || query.ids.includes(n.id));
76
+ if (query.focusId && !unsupported.has('related_to')) rows = rows.filter((n) => filedUnder(n, query.focusId!));
77
+ if (term) rows = rows.filter((n) => hay(n).includes(term));
78
+ const order = unsupported.has('order') ? 'recent' : query.order ?? 'recent';
79
+ const hits = (n: VoiceNote) => hay(n).split(term).length - 1;
80
+ rows = [...rows].sort((a, b) => (order === 'oldest' ? at(a) - at(b) : order === 'relevance' && term ? hits(b) - hits(a) || at(b) - at(a) : at(b) - at(a)));
81
+ const start = (page - 1) * pageSize;
82
+ return {
83
+ notes: rows.slice(start, start + pageSize).map((n) => ({ ...n })),
84
+ count: rows.length,
85
+ nextPage: start + pageSize < rows.length ? page + 1 : null,
86
+ ignoredFilters: [
87
+ ...(query.search?.trim() && unsupported.has('search') ? ['search'] : []),
88
+ ...(query.focusId && unsupported.has('related_to') ? ['related_to'] : []),
89
+ ...(query.order && query.order !== 'recent' && unsupported.has('order') ? ['order'] : []),
90
+ ],
91
+ };
92
+ },
49
93
  async listFocuses() { return focuses; },
50
94
  async file(id, focusId) { notes = notes.map((n) => (n.id === id ? { ...n, focusId } : n)); },
95
+ async fileSection(id, index, focusId) {
96
+ notes = notes.map((n) => (n.id === id ? { ...n, sections: n.sections?.map((s, i) => (i === index ? { ...s, focusId } : s)) } : n));
97
+ },
51
98
  async retry(id) { waiting.delete(id); notes = notes.map((n) => (n.id === id ? { ...n, status: 'processing', error: undefined } : n)); },
52
99
  async remove(id) { notes = notes.filter((n) => n.id !== id); },
53
100
  };