@startsimpli/integrations 0.2.82 → 0.2.83

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.82",
3
+ "version": "0.2.83",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -0,0 +1,118 @@
1
+ // @vitest-environment jsdom
2
+ /**
3
+ * bd startsim-ij1lw.12 + startsim-23np6.3: the web Voice page runs on the shared
4
+ * notes controller (the one the iOS Notes tab uses), so search, project filter,
5
+ * order and "Load more" are server queries here too, and the summary is read
6
+ * through `noteSections`.
7
+ */
8
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
9
+ import * as React from 'react';
10
+ import { afterEach, describe, expect, it, vi } from 'vitest';
11
+
12
+ import { VoiceNotesPage } from '../components/pages/VoiceNotesPage';
13
+ import type { VoiceNotesApi } from '../corpus/voice';
14
+ import { createFakeVoiceApi, type FakeVoiceApiOptions } from '../native/voice/fake';
15
+
16
+ afterEach(cleanup);
17
+
18
+ const mount = (options: FakeVoiceApiOptions = {}, wrap: (api: VoiceNotesApi) => VoiceNotesApi = (a) => a) => {
19
+ const base = createFakeVoiceApi(options);
20
+ const api = wrap(base);
21
+ const spy = api.listPage ? vi.spyOn(api, 'listPage') : undefined;
22
+ render(<VoiceNotesPage api={api} pollMs={60_000} searchDebounceMs={0} />);
23
+ return { api, spy };
24
+ };
25
+ const titles = () => screen.queryAllByRole('heading', { level: 3 }).map((h) => h.textContent);
26
+
27
+ describe('VoiceNotesPage on the shared controller', () => {
28
+ it('lists the notes with how many there are', async () => {
29
+ mount();
30
+ expect(await screen.findByText('Snake plant watering')).toBeTruthy();
31
+ expect(screen.getByText('4 notes')).toBeTruthy();
32
+ });
33
+
34
+ it('search is a server query and shows only what the server returned', async () => {
35
+ const { spy } = mount();
36
+ await screen.findByText('Snake plant watering');
37
+ fireEvent.change(screen.getByLabelText('Search notes'), { target: { value: 'dentist' } });
38
+ await waitFor(() => expect(titles()).toEqual(['Hearing prep and a dentist reminder']));
39
+ expect(spy).toHaveBeenCalledWith(expect.objectContaining({ search: 'dentist' }), 1);
40
+ expect(screen.getByText('1 note')).toBeTruthy();
41
+ });
42
+
43
+ it('a search with no hits says so, and Clear brings everything back', async () => {
44
+ mount();
45
+ await screen.findByText('Snake plant watering');
46
+ fireEvent.change(screen.getByLabelText('Search notes'), { target: { value: 'zzzz' } });
47
+ expect(await screen.findByText('No notes match.')).toBeTruthy();
48
+ fireEvent.click(screen.getByText('Clear search and filters'));
49
+ await waitFor(() => expect(titles()).toHaveLength(4));
50
+ expect((screen.getByLabelText('Search notes') as HTMLInputElement).value).toBe('');
51
+ });
52
+
53
+ it('the project filter and the sort are server parameters', async () => {
54
+ const { spy } = mount();
55
+ await screen.findByText('Snake plant watering');
56
+ await waitFor(() => expect((screen.getByLabelText('Filter by project') as HTMLSelectElement).options.length).toBe(4));
57
+ fireEvent.change(screen.getByLabelText('Filter by project'), { target: { value: 'fma' } });
58
+ await waitFor(() => expect(titles().sort()).toEqual(['Hearing prep and a dentist reminder', 'Snake plant watering']));
59
+ expect(spy).toHaveBeenCalledWith(expect.objectContaining({ focusId: 'fma' }), 1);
60
+ fireEvent.change(screen.getByLabelText('Sort notes'), { target: { value: 'oldest' } });
61
+ await waitFor(() => expect(titles()[0]).toBe('Snake plant watering'));
62
+ });
63
+
64
+ it('Load more appends the next page and goes away on the last one', async () => {
65
+ mount({ pageSize: 3 });
66
+ await screen.findByText('Snake plant watering');
67
+ expect(titles()).toHaveLength(3);
68
+ fireEvent.click(screen.getByText('Load more'));
69
+ await waitFor(() => expect(titles()).toHaveLength(4));
70
+ expect(screen.queryByText('Load more')).toBeNull();
71
+ });
72
+
73
+ it('says so when the server did not apply the search', async () => {
74
+ mount({ unsupported: ['search'] });
75
+ await screen.findByText('Snake plant watering');
76
+ fireEvent.change(screen.getByLabelText('Search notes'), { target: { value: 'dentist' } });
77
+ expect(await screen.findByText(/does not search notes yet/)).toBeTruthy();
78
+ });
79
+
80
+ it('a client without listPage has no search, filter or sort (nothing is narrowed locally)', async () => {
81
+ mount({}, (a) => ({ ...a, listPage: undefined }));
82
+ await screen.findByText('Snake plant watering');
83
+ expect(screen.queryByLabelText('Search notes')).toBeNull();
84
+ expect(screen.queryByLabelText('Sort notes')).toBeNull();
85
+ expect(screen.queryByText('Load more')).toBeNull();
86
+ });
87
+
88
+ it('reads each note through its sections: summary and to-dos per section', async () => {
89
+ mount();
90
+ await screen.findByText('Hearing prep and a dentist reminder');
91
+ expect(screen.getByText('Finish the exhibit list before the hearing.')).toBeTruthy();
92
+ expect(screen.getByText('Finish exhibit list')).toBeTruthy();
93
+ expect(screen.getByText('Call Megan about the filing receipt')).toBeTruthy();
94
+ expect(screen.getByText('Book the dentist')).toBeTruthy();
95
+ });
96
+
97
+ it('moves one section through the controller and shows the result', async () => {
98
+ const { api } = mount();
99
+ const fileSection = vi.spyOn(api, 'fileSection');
100
+ const personal = await screen.findByLabelText('Project for Personal') as HTMLSelectElement;
101
+ await waitFor(() => expect(personal.options.length).toBe(4));
102
+ fireEvent.change(personal, { target: { value: 'fdbg' } });
103
+ await waitFor(() => expect(fileSection).toHaveBeenCalledWith('n1', 2, 'fdbg'));
104
+ await waitFor(() => expect(personal.value).toBe('fdbg'));
105
+ });
106
+
107
+ it('a rebuilt api prop does not restart the page (the controller is made once)', async () => {
108
+ const base = createFakeVoiceApi();
109
+ const list = vi.spyOn(base as { listPage: NonNullable<VoiceNotesApi['listPage']> }, 'listPage');
110
+ const { rerender } = render(<VoiceNotesPage api={base} pollMs={60_000} />);
111
+ await screen.findByText('Snake plant watering');
112
+ const calls = list.mock.calls.length;
113
+ rerender(<VoiceNotesPage api={{ ...base }} pollMs={60_000} />);
114
+ rerender(<VoiceNotesPage api={{ ...base }} pollMs={60_000} />);
115
+ await new Promise((r) => setTimeout(r, 30));
116
+ expect(list.mock.calls.length).toBe(calls);
117
+ });
118
+ });
@@ -0,0 +1,72 @@
1
+ /**
2
+ * bd startsim-23np6.3: the notes list is a server query. These pin the spelling of
3
+ * the request and the page it is read back as.
4
+ */
5
+ import { describe, expect, it, vi } from 'vitest';
6
+ import { createVoiceApi } from '../corpus/voice';
7
+ import { voiceNotesParams } from '../corpus/voice-query';
8
+
9
+ const voiceRow = (id: string) => ({ id, name: id, data: { source: 'voice', voice_status: 'ready', summary: `s${id}`, body: `b${id}` } });
10
+
11
+ function world(envelope: Record<string, unknown> = {}) {
12
+ const gets: Array<{ path: string; params: Record<string, unknown> }> = [];
13
+ const http = {
14
+ get: vi.fn(async (path: string, options?: { params?: Record<string, unknown> }) => {
15
+ gets.push({ path, params: options?.params ?? {} });
16
+ if (path.endsWith('entities')) {
17
+ return { count: 3, next: 'http://x/?page=2', results: [voiceRow('a'), voiceRow('b')], applied_filters: ['type', 'source', 'search', 'order', 'related_to', 'related_via', 'related_direction'], ...envelope };
18
+ }
19
+ return { results: [{ source: 'a', target: 'f1' }] };
20
+ }),
21
+ };
22
+ return { gets, api: createVoiceApi({ http: http as never, scope: { orgId: 'o' } as never, upload: vi.fn() }) };
23
+ }
24
+
25
+ describe('voiceNotesParams', () => {
26
+ it('spells search, order, page and the project as the entities API expects', () => {
27
+ expect(voiceNotesParams({ search: ' brackets ', order: 'relevance', focusId: 'f1' }, 2, 25)).toMatchObject({
28
+ type: 'source_document', source: 'voice', search: 'brackets', order: 'relevance', page: 2, page_size: 25,
29
+ related_to: 'f1', related_via: 'about_focus', related_direction: 'out',
30
+ });
31
+ });
32
+ it('sends no project and no search when none is asked for, and never ranks without a term', () => {
33
+ const p = voiceNotesParams({ order: 'relevance' }, 1, 25);
34
+ expect(p).not.toHaveProperty('related_to');
35
+ expect(p).not.toHaveProperty('search');
36
+ expect(p).not.toHaveProperty('order');
37
+ });
38
+ it('re-reads exact ids with id__in', () => {
39
+ expect(voiceNotesParams({ ids: ['a', 'b'] }, 1, 25)).toMatchObject({ id__in: 'a,b' });
40
+ });
41
+ });
42
+
43
+ describe('createVoiceApi.listPage', () => {
44
+ it('asks the server for the page and reads count + nextPage + the project edges of that page only', async () => {
45
+ const { api, gets } = world();
46
+ const page = await api.listPage!({ search: 'x', focusId: 'f1' }, 2);
47
+ expect(gets[0].params).toMatchObject({ page: 2, search: 'x', related_to: 'f1' });
48
+ expect(gets[1].params).toMatchObject({ rel_type: 'about_focus', entity__in: 'a,b' });
49
+ expect(page.notes.map((n) => n.id)).toEqual(['a', 'b']);
50
+ expect(page.notes[0].focusId).toBe('f1');
51
+ expect(page.count).toBe(3);
52
+ expect(page.nextPage).toBe(3);
53
+ expect(page.ignoredFilters).toEqual([]);
54
+ });
55
+
56
+ it('reports a search the server did not apply instead of passing the list off as searched', async () => {
57
+ const { api } = world({ applied_filters: ['type', 'source', 'order'], ignored_filters: ['search'] });
58
+ const page = await api.listPage!({ search: 'x' }, 1);
59
+ expect(page.ignoredFilters).toEqual(['search']);
60
+ });
61
+
62
+ it('keeps the other-source guard', async () => {
63
+ const { api } = world({ results: [voiceRow('a'), { id: 'z', name: 'Z', data: { source: 'fathom' } }] });
64
+ expect((await api.listPage!({}, 1)).notes.map((n) => n.id)).toEqual(['a']);
65
+ });
66
+
67
+ it('list() is the first page of the same query', async () => {
68
+ const { api, gets } = world();
69
+ expect((await api.list()).map((n) => n.id)).toEqual(['a', 'b']);
70
+ expect(gets[0].params).toMatchObject({ type: 'source_document', source: 'voice', order: 'recent', page: 1 });
71
+ });
72
+ });
@@ -13,13 +13,21 @@
13
13
  * POLLING IS EARNED, NOT AMBIENT. The list is re-read on a timer ONLY while a
14
14
  * note is still processing, and never from an effect whose dependencies change
15
15
  * every render (the 917-requests-in-ten-minutes trap documented on TrackerPage).
16
+ *
17
+ * ONE CONTROLLER, TWO SURFACES (bd startsim-ij1lw.12). The load / poll / re-file /
18
+ * retry / delete logic is `createVoiceNotesController`, the same one the iOS Notes
19
+ * tab runs; this page only renders its state. Search, project filter, order and
20
+ * "Load more" are SERVER queries on it (bd startsim-23np6.3); a client that cannot
21
+ * page shows the plain list with no query controls rather than narrowing locally.
16
22
  */
17
23
  import * as React from 'react';
18
24
 
19
- import type { VoiceNote, VoiceNotesApi, VoiceFocus } from '../../corpus/voice';
25
+ import type { VoiceNote, VoiceNoteOrder, VoiceNotesApi } from '../../corpus/voice';
26
+ import { createVoiceNotesController, type VoiceNotesController } from '../../native/voice/controller';
27
+ import { noteLead, noteSections } from '../../native/voice/sections';
20
28
  import { VoiceRecordButton, formatDuration } from './VoiceRecordButton';
21
29
 
22
- type Slot = 'root' | 'section' | 'card' | 'button' | 'recording' | 'muted' | 'error' | 'select';
30
+ type Slot = 'root' | 'section' | 'card' | 'button' | 'recording' | 'muted' | 'error' | 'select' | 'input';
23
31
  export type VoiceNotesClassNames = Partial<Record<Slot, string>>;
24
32
 
25
33
  const FALLBACK: Record<Slot, string> = {
@@ -31,6 +39,7 @@ const FALLBACK: Record<Slot, string> = {
31
39
  muted: 'text-sm opacity-70',
32
40
  error: 'rounded-md border p-3 text-sm',
33
41
  select: 'rounded-md border px-2 py-1 text-sm',
42
+ input: 'rounded-md border px-3 py-1 text-sm',
34
43
  };
35
44
 
36
45
  export { formatDuration, pickMimeType } from './VoiceRecordButton';
@@ -38,100 +47,83 @@ export { formatDuration, pickMimeType } from './VoiceRecordButton';
38
47
  export interface VoiceNotesPageProps {
39
48
  api: VoiceNotesApi;
40
49
  classNames?: VoiceNotesClassNames;
41
- /** How often to re-read while something is processing. */
50
+ /** How often to re-read while something is processing. Read once, when the page mounts. */
42
51
  pollMs?: number;
52
+ /** How long typing pauses before the search is sent. Default 300. */
53
+ searchDebounceMs?: number;
43
54
  /** Injectable for tests; defaults to the browser's. */
44
55
  mediaDevices?: Pick<MediaDevices, 'getUserMedia'>;
45
56
  recorderFactory?: (stream: MediaStream, mimeType: string) => MediaRecorder;
46
57
  }
47
58
 
59
+ const IGNORED_NAMES: Record<string, string> = { search: 'search notes', related_to: 'filter by project', order: 'sort notes' };
60
+
61
+ /** The controller is made once; this lets it keep calling whatever `api` the parent passes now. */
62
+ function liveApi(ref: React.MutableRefObject<VoiceNotesApi>): VoiceNotesApi {
63
+ const optional = <A extends unknown[], R>(pick: (a: VoiceNotesApi) => ((...args: A) => R) | undefined) =>
64
+ pick(ref.current) ? (...args: A): R => pick(ref.current)!(...args) : undefined;
65
+ return {
66
+ submit: (audio, meta) => ref.current.submit(audio, meta),
67
+ list: () => ref.current.list(),
68
+ listFocuses: () => ref.current.listFocuses(),
69
+ file: (id, focusId) => ref.current.file(id, focusId),
70
+ get listPage() { return optional((a) => a.listPage?.bind(a)); },
71
+ get fileSection() { return optional((a) => a.fileSection?.bind(a)); },
72
+ get retry() { return optional((a) => a.retry?.bind(a)); },
73
+ get remove() { return optional((a) => a.remove?.bind(a)); },
74
+ };
75
+ }
76
+
77
+ function useNotes(controller: VoiceNotesController) {
78
+ React.useEffect(() => {
79
+ controller.start();
80
+ return () => controller.stop();
81
+ }, [controller]);
82
+ return React.useSyncExternalStore(controller.subscribe, controller.getState, controller.getState);
83
+ }
84
+
48
85
  export function VoiceNotesPage({
49
- api, classNames, pollMs = 3000, mediaDevices, recorderFactory,
86
+ api, classNames, pollMs = 3000, searchDebounceMs = 300, mediaDevices, recorderFactory,
50
87
  }: VoiceNotesPageProps) {
51
88
  const cx = (slot: Slot) => classNames?.[slot] ?? FALLBACK[slot];
52
89
 
53
- const [notes, setNotes] = React.useState<VoiceNote[] | null>(null);
54
- const [focuses, setFocuses] = React.useState<VoiceFocus[]>([]);
55
- const [error, setError] = React.useState<string | null>(null);
56
- const [busy, setBusy] = React.useState<Set<string>>(new Set());
57
- const [audio, setAudio] = React.useState<Record<string, string>>({});
58
-
59
- // The api may be rebuilt by the parent; the effects below must not re-fire.
90
+ // The api may be rebuilt by the parent; the controller (and its timers) must not be.
60
91
  const apiRef = React.useRef(api);
61
92
  apiRef.current = api;
93
+ const [controller] = React.useState(() => createVoiceNotesController({ api: liveApi(apiRef), pollMs }));
94
+ const state = useNotes(controller);
95
+ const { notes, focuses, query } = state;
62
96
 
63
- const refresh = React.useCallback(async () => {
64
- try {
65
- setNotes(await apiRef.current.list());
66
- } catch (e) {
67
- setError(e instanceof Error ? e.message : 'Could not load voice notes.');
68
- }
69
- }, []);
70
-
71
- React.useEffect(() => {
72
- void refresh();
73
- apiRef.current.listFocuses().then(setFocuses).catch(() => setFocuses([]));
74
- }, [refresh]);
97
+ const [localError, setLocalError] = React.useState<string | null>(null);
98
+ const [busy, setBusy] = React.useState<Set<string>>(new Set());
99
+ const [audio, setAudio] = React.useState<Record<string, string>>({});
100
+ const [draft, setDraft] = React.useState('');
75
101
 
76
- const processing = notes?.some((n) => n.status === 'processing') ?? false;
102
+ // Typing is sent to the server once it pauses; Enter sends it now.
77
103
  React.useEffect(() => {
78
- if (!processing) return undefined;
79
- const timer = setTimeout(() => void refresh(), pollMs);
104
+ if (draft.trim() === query.search.trim()) return undefined;
105
+ const timer = setTimeout(() => void controller.setSearch(draft), searchDebounceMs);
80
106
  return () => clearTimeout(timer);
81
- }, [processing, notes, pollMs, refresh]);
107
+ }, [draft, query.search, controller, searchDebounceMs]);
82
108
 
83
109
  async function act(note: VoiceNote, run: () => Promise<void>, failure: string) {
84
110
  setBusy((current) => new Set(current).add(note.id));
85
111
  try {
86
112
  await run();
87
113
  } catch (e) {
88
- setError(e instanceof Error ? e.message : failure);
114
+ setLocalError(e instanceof Error ? e.message : failure);
89
115
  } finally {
90
116
  setBusy((current) => { const next = new Set(current); next.delete(note.id); return next; });
91
117
  }
92
118
  }
93
119
 
94
- const retry = (note: VoiceNote) => act(note, async () => {
95
- await apiRef.current.retry?.(note.id);
96
- await refresh();
97
- }, 'Could not retry that note.');
98
-
99
- const remove = (note: VoiceNote) => act(note, async () => {
100
- await apiRef.current.remove?.(note.id);
101
- setNotes((current) => current?.filter((n) => n.id !== note.id) ?? current);
102
- }, 'Could not delete that note.');
103
-
120
+ const retry = (note: VoiceNote) => act(note, () => controller.retry(note.id), 'Could not retry that note.');
121
+ const remove = (note: VoiceNote) => act(note, () => controller.remove(note.id), 'Could not delete that note.');
104
122
  const play = (note: VoiceNote) => act(note, async () => {
105
123
  const url = await apiRef.current.audioUrl?.(note.id);
106
124
  if (url) setAudio((current) => ({ ...current, [note.id]: url }));
107
125
  }, 'Could not load the recording.');
108
126
 
109
- async function move(note: VoiceNote, focusId: string) {
110
- const next = focusId || null;
111
- const previous = note.focusId;
112
- setNotes((current) => current?.map((n) => (n.id === note.id ? { ...n, focusId: next } : n)) ?? current);
113
- try {
114
- await apiRef.current.file(note.id, next);
115
- } catch (e) {
116
- setNotes((current) => current?.map((n) => (n.id === note.id ? { ...n, focusId: previous } : n)) ?? current);
117
- setError(e instanceof Error ? e.message : 'Could not move that note.');
118
- }
119
- }
120
-
121
- async function moveSection(note: VoiceNote, index: number, focusId: string) {
122
- const next = focusId || null;
123
- const previous = note.sections ?? [];
124
- const apply = (sections: NonNullable<VoiceNote['sections']>) =>
125
- setNotes((current) => current?.map((n) => (n.id === note.id ? { ...n, sections } : n)) ?? current);
126
- apply(previous.map((section, i) => (i === index ? { ...section, focusId: next } : section)));
127
- try {
128
- await apiRef.current.fileSection!(note.id, index, next);
129
- } catch (e) {
130
- apply(previous);
131
- setError(e instanceof Error ? e.message : 'Could not move that section.');
132
- }
133
- }
134
-
135
127
  const projectSelect = (label: string, value: string, onChange: (focusId: string) => void) => (
136
128
  <select
137
129
  className={cx('select')}
@@ -146,12 +138,19 @@ export function VoiceNotesPage({
146
138
  </select>
147
139
  );
148
140
 
141
+ const canQuery = controller.canQuery;
142
+ const filtering = Boolean(query.search.trim() || query.focusId);
143
+ const count = state.count;
144
+ const error = state.error ?? localError;
145
+ const clearAll = () => { setDraft(''); setLocalError(null); controller.clearError(); void controller.clearFilters(); };
146
+ const ignored = state.ignoredFilters.map((k) => IGNORED_NAMES[k] ?? k);
147
+
149
148
  return (
150
149
  <div className={cx('root')}>
151
150
  <section className={cx('section')}>
152
151
  <VoiceRecordButton
153
152
  api={api}
154
- onSaved={refresh}
153
+ onSaved={controller.refresh}
155
154
  mediaDevices={mediaDevices}
156
155
  recorderFactory={recorderFactory}
157
156
  classNames={{ button: cx('button'), recording: cx('recording'), muted: cx('muted'), error: cx('error') }}
@@ -165,63 +164,125 @@ export function VoiceNotesPage({
165
164
  </section>
166
165
 
167
166
  <section className={cx('section')} aria-label="Voice notes">
168
- {notes === null ? <p className={cx('muted')}>Loading…</p> : null}
169
- {notes?.length === 0 ? <p className={cx('muted')}>No voice notes yet.</p> : null}
170
- {notes?.map((note) => (
171
- <article key={note.id} className={cx('card')}>
172
- <header>
173
- <h3>{note.title}</h3>
174
- <p className={cx('muted')}>
175
- {note.occurredAt ? new Date(note.occurredAt).toLocaleString() : ''}
176
- {note.durationMs ? ` · ${formatDuration(note.durationMs)}` : ''}
177
- </p>
178
- </header>
179
-
180
- {note.status === 'processing' ? <p className={cx('muted')}>Transcribing…</p> : null}
181
- {note.status === 'failed' ? (
182
- <p role="alert" className={cx('error')}>Could not process this note{note.error ? `: ${note.error}` : '.'}</p>
183
- ) : null}
184
- {note.status === 'failed' && (api.retry || api.remove) ? (
185
- <p>
186
- {api.retry ? (
187
- <button type="button" className={cx('button')} disabled={busy.has(note.id)} onClick={() => void retry(note)}>Retry</button>
188
- ) : null}{' '}
189
- {api.remove ? (
190
- <button type="button" className={cx('button')} disabled={busy.has(note.id)} onClick={() => void remove(note)}>Delete</button>
191
- ) : null}
192
- </p>
193
- ) : null}
194
- {note.status === 'ready' && note.audioRef && api.audioUrl ? (
195
- audio[note.id] ? (
196
- <audio controls autoPlay src={audio[note.id]} aria-label={`Recording of ${note.title}`} />
197
- ) : (
198
- <button type="button" className={cx('button')} disabled={busy.has(note.id)} onClick={() => void play(note)}>Play recording</button>
199
- )
200
- ) : null}
201
- {note.summary ? <p style={{ whiteSpace: 'pre-line' }}>{note.summary}</p> : null}
202
- {note.transcript ? (
203
- <details>
204
- <summary>Transcript</summary>
205
- <p style={{ whiteSpace: 'pre-wrap' }}>{note.transcript}</p>
206
- </details>
167
+ {canQuery ? (
168
+ <form
169
+ className="flex flex-wrap items-center gap-2"
170
+ role="search"
171
+ onSubmit={(event) => { event.preventDefault(); void controller.setSearch(draft); }}
172
+ >
173
+ <input
174
+ type="search"
175
+ className={cx('input')}
176
+ aria-label="Search notes"
177
+ placeholder="Search your notes"
178
+ value={draft}
179
+ onChange={(event) => setDraft(event.target.value)}
180
+ />
181
+ <select
182
+ className={cx('select')}
183
+ aria-label="Filter by project"
184
+ value={query.focusId ?? ''}
185
+ onChange={(event) => void controller.setFocusFilter(event.target.value || null)}
186
+ >
187
+ <option value="">All projects</option>
188
+ {focuses.map((focus) => (
189
+ <option key={focus.id} value={focus.id}>{focus.title}</option>
190
+ ))}
191
+ </select>
192
+ <select
193
+ className={cx('select')}
194
+ aria-label="Sort notes"
195
+ value={query.order}
196
+ onChange={(event) => void controller.setOrder(event.target.value as VoiceNoteOrder)}
197
+ >
198
+ <option value="recent">Newest</option>
199
+ <option value="oldest">Oldest</option>
200
+ {query.search.trim() ? <option value="relevance">Best match</option> : null}
201
+ </select>
202
+ {filtering ? (
203
+ <button type="button" className={cx('button')} onClick={clearAll}>Clear search and filters</button>
207
204
  ) : null}
205
+ {count !== null ? <span className={cx('muted')}>{`${count} note${count === 1 ? '' : 's'}`}</span> : null}
206
+ </form>
207
+ ) : null}
208
+ {ignored.length ? (
209
+ <p role="status" className={cx('muted')}>
210
+ {`This workspace does not ${ignored.join(', ')} yet, so the list below is not narrowed by ${ignored.length > 1 ? 'those' : 'that'}.`}
211
+ </p>
212
+ ) : null}
208
213
 
209
- {note.sections?.length && api.fileSection ? (
210
- // One project per topic of the note: a recording can cover several.
211
- note.sections.map((section, index) => (
212
- <label key={`${index}-${section.label}`} className={cx('muted')} style={{ display: 'block' }}>
213
- {section.label}{section.kind === 'personal' ? ' (personal)' : ''}{' '}
214
- {projectSelect(section.label, section.focusId ?? '', (focusId) => void moveSection(note, index, focusId))}
214
+ {notes === null ? <p className={cx('muted')}>Loading…</p> : null}
215
+ {notes?.length === 0 ? <p className={cx('muted')}>{filtering ? 'No notes match.' : 'No voice notes yet.'}</p> : null}
216
+ {notes?.map((note) => {
217
+ const lead = noteLead(note);
218
+ return (
219
+ <article key={note.id} className={cx('card')}>
220
+ <header>
221
+ <h3>{note.title}</h3>
222
+ <p className={cx('muted')}>
223
+ {note.occurredAt ? new Date(note.occurredAt).toLocaleString() : ''}
224
+ {note.durationMs ? ` · ${formatDuration(note.durationMs)}` : ''}
225
+ </p>
226
+ </header>
227
+
228
+ {note.status === 'processing' ? <p className={cx('muted')}>Transcribing…</p> : null}
229
+ {note.status === 'failed' ? (
230
+ <p role="alert" className={cx('error')}>Could not process this note{note.error ? `: ${note.error}` : '.'}</p>
231
+ ) : null}
232
+ {note.status === 'failed' && (controller.canRetry || controller.canRemove) ? (
233
+ <p>
234
+ {controller.canRetry ? (
235
+ <button type="button" className={cx('button')} disabled={busy.has(note.id)} onClick={() => void retry(note)}>Retry</button>
236
+ ) : null}{' '}
237
+ {controller.canRemove ? (
238
+ <button type="button" className={cx('button')} disabled={busy.has(note.id)} onClick={() => void remove(note)}>Delete</button>
239
+ ) : null}
240
+ </p>
241
+ ) : null}
242
+ {note.status === 'ready' && note.audioRef && api.audioUrl ? (
243
+ audio[note.id] ? (
244
+ <audio controls autoPlay src={audio[note.id]} aria-label={`Recording of ${note.title}`} />
245
+ ) : (
246
+ <button type="button" className={cx('button')} disabled={busy.has(note.id)} onClick={() => void play(note)}>Play recording</button>
247
+ )
248
+ ) : null}
249
+ {lead ? <p style={{ whiteSpace: 'pre-line' }}>{lead}</p> : null}
250
+ {noteSections(note).map((section, index) => (
251
+ <div key={`${index}-${section.label}`}>
252
+ {section.label ? <h4>{section.label}{section.kind === 'personal' ? ' (personal)' : ''}</h4> : null}
253
+ {section.summary ? <p style={{ whiteSpace: 'pre-line' }}>{section.summary}</p> : null}
254
+ {section.items.length ? <ul>{section.items.map((item, i) => <li key={i}>{item}</li>)}</ul> : null}
255
+ </div>
256
+ ))}
257
+ {note.transcript ? (
258
+ <details>
259
+ <summary>Transcript</summary>
260
+ <p style={{ whiteSpace: 'pre-wrap' }}>{note.transcript}</p>
261
+ </details>
262
+ ) : null}
263
+
264
+ {note.sections?.length && controller.canFileSection ? (
265
+ // One project per topic of the note: a recording can cover several.
266
+ note.sections.map((section, index) => (
267
+ <label key={`${index}-${section.label}`} className={cx('muted')} style={{ display: 'block' }}>
268
+ {section.label}{section.kind === 'personal' ? ' (personal)' : ''}{' '}
269
+ {projectSelect(section.label, section.focusId ?? '', (focusId) => void controller.fileSection(note.id, index, focusId || null))}
270
+ </label>
271
+ ))
272
+ ) : (
273
+ <label className={cx('muted')}>
274
+ Project{' '}
275
+ {projectSelect(note.title, note.focusId ?? '', (focusId) => void controller.file(note.id, focusId || null))}
215
276
  </label>
216
- ))
217
- ) : (
218
- <label className={cx('muted')}>
219
- Project{' '}
220
- {projectSelect(note.title, note.focusId ?? '', (focusId) => void move(note, focusId))}
221
- </label>
222
- )}
223
- </article>
224
- ))}
277
+ )}
278
+ </article>
279
+ );
280
+ })}
281
+ {state.hasMore ? (
282
+ <button type="button" className={cx('button')} disabled={state.loadingMore} onClick={() => void controller.loadMore()}>
283
+ {state.loadingMore ? 'Loading…' : 'Load more'}
284
+ </button>
285
+ ) : null}
225
286
  </section>
226
287
  </div>
227
288
  );
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The notes list's query vocabulary (bd startsim-23np6.3): search, project filter
3
+ * and order are SERVER parameters of `GET api/v1/entities/`, never a local narrow
4
+ * of a loaded list. Pure: the spelling lives in `entity-query`, this only says
5
+ * what a voice note is asking for.
6
+ */
7
+ import { ABOUT_FOCUS } from './filing';
8
+ import { entityParams } from './entity-query';
9
+ import type { VoiceNote } from './voice';
10
+
11
+ export type VoiceNoteOrder = 'recent' | 'oldest' | 'relevance';
12
+
13
+ export interface VoiceNotesQuery {
14
+ /** Ranked full-text search over the title, summary and transcript. */
15
+ search?: string;
16
+ /** Only notes filed under this project (an `about_focus` edge to it). */
17
+ focusId?: string | null;
18
+ order?: VoiceNoteOrder;
19
+ /** Re-read exactly these notes (the poll while they transcribe). */
20
+ ids?: string[];
21
+ }
22
+
23
+ export interface VoiceNotesPage {
24
+ notes: VoiceNote[];
25
+ /** Total notes matching, from the server's own count. */
26
+ count: number;
27
+ /** The next page to ask for, or null on the last page. */
28
+ nextPage: number | null;
29
+ /** Query parts (`search`, `order`, `related_to`) the server did not apply. */
30
+ ignoredFilters: string[];
31
+ }
32
+
33
+ /** The parts of a query a screen can say "not applied" about. */
34
+ export const QUERY_FILTER_KEYS = ['search', 'order', 'related_to', 'related_via', 'related_direction'];
35
+
36
+ export function voiceNotesParams(query: VoiceNotesQuery, page: number, pageSize: number): Record<string, unknown> {
37
+ return entityParams({
38
+ type: 'source_document',
39
+ page,
40
+ pageSize,
41
+ search: query.search,
42
+ order: query.order ?? 'recent',
43
+ filters: {
44
+ source: 'voice',
45
+ ...(query.ids?.length ? { idIn: query.ids } : {}),
46
+ ...(query.focusId ? { relatedTo: query.focusId, relatedVia: ABOUT_FOCUS, relatedDirection: 'out' as const } : {}),
47
+ },
48
+ });
49
+ }