@startsimpli/integrations 0.2.71 → 0.2.73

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.
@@ -0,0 +1,118 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import { FlatList, Pressable, View } from 'react-native';
3
+ import { Alert, Badge, Button, ChatComposer, EmptyState, Header, MessageBubble, Select, Text, useTheme } from '@startsimpli/ui-native';
4
+ import { useControllerState as useStore } from '../../components/useControllerState';
5
+ import type { AnswerView } from './answer-view';
6
+ import type { AskController, AskMessage } from './controller';
7
+
8
+ export interface AskScreenProps {
9
+ controller: AskController;
10
+ /** A citation was tapped: open that document (normally the Library tab). */
11
+ onOpenDocument: (documentId: string) => void;
12
+ }
13
+
14
+ /** Ask your documents: pick a project to scope, ask, read a Markdown answer, tap a citation to open the record. */
15
+ export function AskScreen({ controller, onOpenDocument }: AskScreenProps) {
16
+ const s = useStore(controller);
17
+ const theme = useTheme();
18
+ const list = useRef<FlatList<AskMessage>>(null);
19
+ useEffect(() => { void controller.start(); }, [controller]);
20
+ const scope = s.projects.find((p) => p.id === s.projectId)?.title;
21
+
22
+ return (
23
+ <View style={{ flex: 1 }}>
24
+ <Header testID="ask-header" title="Ask" subtitle={scope ? `Scoped to ${scope}` : 'All projects'} />
25
+ {s.projects.length ? (
26
+ <View style={{ paddingHorizontal: theme.spacing.lg, paddingBottom: theme.spacing.sm, flexDirection: 'row' }}>
27
+ <Select
28
+ compact
29
+ testID="ask-project"
30
+ label="All projects"
31
+ title="Scope to a project"
32
+ options={s.projects.map((p) => ({ value: p.id, label: p.title }))}
33
+ value={s.projectId}
34
+ clearLabel="All projects"
35
+ onChange={(id) => controller.setProject(id)}
36
+ />
37
+ </View>
38
+ ) : null}
39
+ <FlatList
40
+ ref={list}
41
+ testID="ask-messages"
42
+ data={s.messages}
43
+ keyExtractor={(m) => m.id}
44
+ keyboardShouldPersistTaps="handled"
45
+ keyboardDismissMode="on-drag"
46
+ onContentSizeChange={() => list.current?.scrollToEnd?.({ animated: true })}
47
+ contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.md, flexGrow: 1 }}
48
+ ListEmptyComponent={
49
+ <EmptyState icon="💬" title="Ask your documents" description="Answers come from your notes, meetings and files, with the records they used." />
50
+ }
51
+ renderItem={({ item }) => <Message message={item} onRetry={() => { void controller.retry(item.id); }} onOpenDocument={onOpenDocument} />}
52
+ />
53
+ <ChatComposer testID="ask-composer" placeholder="Ask about your documents" sending={s.busy} onSend={(text) => { void controller.send(text); }} />
54
+ </View>
55
+ );
56
+ }
57
+
58
+ function Message({ message, onRetry, onOpenDocument }: { message: AskMessage; onRetry: () => void; onOpenDocument: (id: string) => void }) {
59
+ const theme = useTheme();
60
+ if (message.role === 'user') return <MessageBubble role="user" text={message.text} testID={`ask-msg-${message.id}`} />;
61
+ if (message.status === 'pending') return <MessageBubble role="assistant" text="" pending testID="ask-pending" />;
62
+ if (message.status === 'error') {
63
+ return (
64
+ <View style={{ gap: theme.spacing.sm, alignItems: 'flex-start' }} testID={`ask-msg-${message.id}`}>
65
+ <Alert variant="destructive">{message.error ?? 'That question could not be answered right now.'}</Alert>
66
+ <Button testID={`ask-msg-${message.id}-retry`} title="Retry" variant="outline" size="sm" onPress={onRetry} />
67
+ </View>
68
+ );
69
+ }
70
+ return (
71
+ <View style={{ gap: theme.spacing.sm }} testID={`ask-msg-${message.id}`}>
72
+ {message.view?.notices.map((n, i) => <Alert key={i} variant={n.tone === 'error' ? 'destructive' : 'default'}>{n.text}</Alert>)}
73
+ <MessageBubble role="assistant" text={message.text} />
74
+ {message.view ? <Sources view={message.view} onOpenDocument={onOpenDocument} /> : null}
75
+ </View>
76
+ );
77
+ }
78
+
79
+ function Sources({ view, onOpenDocument }: { view: AnswerView; onOpenDocument: (id: string) => void }) {
80
+ const theme = useTheme();
81
+ const [showUncited, setShowUncited] = useState(false);
82
+ const n = view.citations.length;
83
+ return (
84
+ <View style={{ gap: theme.spacing.sm }}>
85
+ {view.status !== 'no_evidence' ? <Text variant="caption">{`${n} source${n === 1 ? '' : 's'}`}</Text> : null}
86
+ {view.citations.map((c) => (
87
+ <Pressable
88
+ key={c.documentId}
89
+ testID={`ask-citation-${c.documentId}`}
90
+ accessibilityRole="button"
91
+ accessibilityLabel={`Open ${c.title}`}
92
+ onPress={() => onOpenDocument(c.documentId)}
93
+ style={({ pressed }) => ({ gap: 2, paddingVertical: theme.spacing.xs, opacity: pressed ? 0.6 : 1 })}
94
+ >
95
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: theme.spacing.sm }}>
96
+ <Badge label={c.sourceLabel} variant="outline" />
97
+ <Text variant="caption">{c.dateLabel}</Text>
98
+ </View>
99
+ <Text style={{ color: theme.colors.primary, fontWeight: '600' }}>{c.title}</Text>
100
+ {c.quote ? <Text variant="muted" style={{ fontStyle: 'italic' }} numberOfLines={3}>{`“${c.quote}”`}</Text> : null}
101
+ </Pressable>
102
+ ))}
103
+ {view.uncited.length ? (
104
+ <View style={{ gap: theme.spacing.xs }}>
105
+ <Pressable accessibilityRole="button" testID="ask-uncited-toggle" onPress={() => setShowUncited((v) => !v)}>
106
+ <Text variant="caption">{`${view.uncited.length} more record${view.uncited.length === 1 ? ' was' : 's were'} searched but not cited`}</Text>
107
+ </Pressable>
108
+ {showUncited ? view.uncited.map((u) => (
109
+ <Pressable key={u.documentId} accessibilityRole="button" onPress={() => onOpenDocument(u.documentId)}>
110
+ <Text variant="muted">{`${u.sourceLabel} · ${u.title}`}</Text>
111
+ </Pressable>
112
+ )) : null}
113
+ </View>
114
+ ) : null}
115
+ <Text variant="caption">{view.provider}</Text>
116
+ </View>
117
+ );
118
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * An `AskResult` as a phone shows it: the answer, the caveats it owes, the
3
+ * records it cites and the one-sentence provenance. Pure; the strings come from
4
+ * `corpus/view-text.ts`, the same ones the web `AskPage` renders, so an answer
5
+ * says the same thing on both. Citations are not optional: an answer with no
6
+ * resolvable citation carries the unsourced warning first.
7
+ */
8
+ import { formatDate } from '../../../components/documentText';
9
+ import type { AskResult, AskStatus } from '../../../corpus/types';
10
+ import {
11
+ UNCITED_NOTICE, droppedNotice, freshnessNotice, providerSentence, stripMarkdown, unresolvedNotice, withheldNotice,
12
+ } from '../../../corpus/view-text';
13
+
14
+ export interface AnswerNotice { tone: 'warning' | 'error'; text: string }
15
+ export interface AnswerCitation { documentId: string; title: string; sourceLabel: string; dateLabel: string; quote: string }
16
+ export interface AnswerView {
17
+ status: AskStatus;
18
+ text: string;
19
+ notices: AnswerNotice[];
20
+ citations: AnswerCitation[];
21
+ /** Searched, offered to the model, but not cited - so "why not the contract?" is answerable. */
22
+ uncited: Array<{ documentId: string; title: string; sourceLabel: string }>;
23
+ provider: string;
24
+ }
25
+
26
+ export function answerView(result: AskResult): AnswerView {
27
+ const notices: AnswerNotice[] = [];
28
+ const add = (tone: AnswerNotice['tone'], text: string) => { if (text) notices.push({ tone, text }); };
29
+ if (result.status === 'uncited') add('warning', UNCITED_NOTICE);
30
+ if (result.status !== 'no_evidence') {
31
+ add('warning', freshnessNotice(result));
32
+ add('warning', withheldNotice(result));
33
+ add('warning', unresolvedNotice(result));
34
+ }
35
+ add('error', droppedNotice(result));
36
+ const cited = new Set(result.citations.map((c) => c.documentId));
37
+ return {
38
+ status: result.status,
39
+ text: result.answer,
40
+ notices,
41
+ citations: result.citations.map((c) => ({
42
+ documentId: c.documentId,
43
+ title: c.document.title,
44
+ sourceLabel: c.document.sourceLabel || c.document.source,
45
+ dateLabel: formatDate(c.document.occurredAt),
46
+ quote: stripMarkdown(c.quote ?? ''),
47
+ })),
48
+ uncited: result.considered.filter((r) => !cited.has(r.document.id)).map((r) => ({
49
+ documentId: r.document.id, title: r.document.title, sourceLabel: r.document.sourceLabel || r.document.source,
50
+ })),
51
+ provider: providerSentence(result.provider),
52
+ };
53
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The Ask tab's logic, framework-free: the web `AskPage` as a conversation. Each
3
+ * question is answered on its own, server-side (the model call and its key live
4
+ * behind `api.ask`), optionally scoped to one project - the choice goes out as
5
+ * `filters.focus`, so retrieval is narrowed by the SERVER to the documents filed
6
+ * under that project. Earlier turns are not sent: Ask is question -> cited answer,
7
+ * not a remembered chat.
8
+ */
9
+ import type { AskRequest, CorpusAskApi, CorpusScope } from '../../../corpus/types';
10
+ import { askFailureMessage } from '../../../corpus/view-text';
11
+ import type { Store } from '../../components/useControllerState';
12
+ import { createStore } from '../store';
13
+ import { answerView, type AnswerView } from './answer-view';
14
+
15
+ export interface AskMessage {
16
+ id: string;
17
+ role: 'user' | 'assistant';
18
+ text: string;
19
+ /** Assistant only: pending until the server answers. */
20
+ status?: 'pending' | 'done' | 'error';
21
+ error?: string;
22
+ view?: AnswerView;
23
+ /** Assistant only: what was asked, so it can be asked again. */
24
+ question?: string;
25
+ projectId?: string | null;
26
+ }
27
+
28
+ export interface AskState {
29
+ messages: AskMessage[];
30
+ projects: Array<{ id: string; title: string }>;
31
+ projectId: string | null;
32
+ busy: boolean;
33
+ }
34
+
35
+ export interface AskController extends Store<AskState> {
36
+ start(): Promise<void>;
37
+ setProject(id: string | null): void;
38
+ send(text: string): Promise<void>;
39
+ retry(assistantMessageId: string): Promise<void>;
40
+ clear(): void;
41
+ }
42
+
43
+ export interface AskControllerOptions {
44
+ api: CorpusAskApi;
45
+ scope: CorpusScope;
46
+ /** The projects a question can be scoped to. Without it there is no picker. */
47
+ listProjects?: () => Promise<Array<{ id: string; title: string }>>;
48
+ }
49
+
50
+ export function createAskController({ api, scope, listProjects }: AskControllerOptions): AskController {
51
+ const store = createStore<AskState>({ messages: [], projects: [], projectId: null, busy: false });
52
+ let seq = 0;
53
+ const nextId = (prefix: string) => `${prefix}${++seq}`;
54
+ const patchMessage = (id: string, patch: Partial<AskMessage>) =>
55
+ store.update((s) => ({ messages: s.messages.map((m) => (m.id === id ? { ...m, ...patch } : m)) }));
56
+
57
+ async function run(assistantId: string, question: string, projectId: string | null) {
58
+ store.set({ busy: true });
59
+ patchMessage(assistantId, { status: 'pending', error: undefined });
60
+ try {
61
+ const request: AskRequest = { question, mode: 'ask', scope, ...(projectId ? { filters: { focus: projectId } } : {}) };
62
+ const result = await api.ask(request);
63
+ patchMessage(assistantId, { status: 'done', text: result.answer, view: answerView(result) });
64
+ } catch (e) {
65
+ patchMessage(assistantId, { status: 'error', error: askFailureMessage(e), text: '' });
66
+ } finally {
67
+ store.set({ busy: false });
68
+ }
69
+ }
70
+
71
+ return {
72
+ getState: store.getState,
73
+ subscribe: store.subscribe,
74
+ async start() {
75
+ if (!listProjects) return;
76
+ try { store.set({ projects: await listProjects() }); } catch { /* Ask still works across everything */ }
77
+ },
78
+ setProject: (id) => store.set({ projectId: id }),
79
+ async send(text) {
80
+ const question = text.trim();
81
+ if (!question || store.getState().busy) return;
82
+ const projectId = store.getState().projectId;
83
+ const assistantId = nextId('a');
84
+ store.update((s) => ({
85
+ messages: [
86
+ ...s.messages,
87
+ { id: nextId('u'), role: 'user', text: question },
88
+ { id: assistantId, role: 'assistant', text: '', status: 'pending', question, projectId },
89
+ ],
90
+ }));
91
+ await run(assistantId, question, projectId);
92
+ },
93
+ async retry(id) {
94
+ const message = store.getState().messages.find((m) => m.id === id);
95
+ if (!message?.question || store.getState().busy) return;
96
+ await run(id, message.question, message.projectId ?? null);
97
+ },
98
+ clear: () => store.set({ messages: [] }),
99
+ };
100
+ }
@@ -0,0 +1,93 @@
1
+ import { useEffect } from 'react';
2
+ import { ScrollView, View } from 'react-native';
3
+ import { Alert, Badge, Header, Markdown, Select, Separator, Spinner, Text, useTheme } from '@startsimpli/ui-native';
4
+ import { formatDate, fullTextOf, summaryOf } from '../../../components/documentText';
5
+ import { useControllerState as useStore } from '../../components/useControllerState';
6
+ import type { LibraryController } from './controller';
7
+
8
+ export interface LibraryDetailScreenProps {
9
+ controller: LibraryController;
10
+ documentId: string;
11
+ onBack: () => void;
12
+ }
13
+
14
+ /** One document: its Markdown summary and text, where it came from, and the project it is filed under (changeable). */
15
+ export function LibraryDetailScreen({ controller, documentId, onBack }: LibraryDetailScreenProps) {
16
+ const s = useStore(controller);
17
+ const theme = useTheme();
18
+ // Opened from a link or a citation the list may never have been shown: load what the screen needs itself.
19
+ useEffect(() => { void controller.start(); void controller.open(documentId); }, [controller, documentId]);
20
+ const open = s.selected?.id === documentId ? s.selected : null;
21
+ const document = open?.document ?? null;
22
+
23
+ if (!document) {
24
+ return (
25
+ <View style={{ flex: 1 }}>
26
+ <Header testID="library-detail" title="Document" onBack={onBack} />
27
+ <View style={{ padding: theme.spacing.lg, gap: theme.spacing.md }}>
28
+ {open?.error ? <Alert variant="destructive">{open.error}</Alert> : <Spinner />}
29
+ </View>
30
+ </View>
31
+ );
32
+ }
33
+
34
+ const filings = s.filings[document.id] ?? [];
35
+ const summary = summaryOf(document);
36
+ const fullText = fullTextOf(document);
37
+ const meta = [formatDate(document.occurredAt), document.participants.map((p) => p.name).join(', ')].filter(Boolean).join(' · ');
38
+ const gap = { gap: theme.spacing.sm } as const;
39
+
40
+ return (
41
+ <View style={{ flex: 1 }}>
42
+ <Header testID="library-detail" title={document.title} subtitle={document.sourceLabel || document.source} onBack={onBack} />
43
+ <ScrollView contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.lg }} keyboardShouldPersistTaps="handled">
44
+ <View style={gap}>
45
+ <Text variant="heading">{document.title}</Text>
46
+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', alignItems: 'center', gap: theme.spacing.sm }}>
47
+ <Badge label={document.sourceLabel || document.source} variant="outline" />
48
+ {document.subtype ? <Badge label={document.subtype.replace(/[_-]+/g, ' ')} variant="secondary" /> : null}
49
+ </View>
50
+ {meta ? <Text variant="caption">{meta}</Text> : null}
51
+ </View>
52
+
53
+ <View style={gap}>
54
+ <Text variant="caption">Filed under</Text>
55
+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: theme.spacing.xs }}>
56
+ {filings.length === 0
57
+ ? <Badge testID="library-detail-filed-none" label="Unfiled" variant="secondary" />
58
+ : filings.map((f) => <Badge key={f.id} label={f.title} variant="secondary" />)}
59
+ </View>
60
+ {s.projects.length ? (
61
+ <Select
62
+ testID="library-detail-project"
63
+ label="Change project"
64
+ title="Change project"
65
+ placeholder="Choose a project"
66
+ options={s.projects}
67
+ value={filings[0]?.id ?? null}
68
+ clearLabel="Unfiled"
69
+ disabled={s.filingBusy}
70
+ onChange={(id) => { void controller.fileUnder(document.id, id); }}
71
+ />
72
+ ) : null}
73
+ {s.filingError ? <Alert variant="destructive">{s.filingError}</Alert> : null}
74
+ </View>
75
+
76
+ <Separator />
77
+ {summary ? <Markdown testID="library-detail-summary">{summary}</Markdown> : <Text variant="muted">No summary was captured for this document.</Text>}
78
+ {document.sections.map((section) => (
79
+ <View key={section.key} style={gap}>
80
+ <Text style={{ fontWeight: '600' }}>{section.label}</Text>
81
+ <Markdown>{section.text}</Markdown>
82
+ </View>
83
+ ))}
84
+ {fullText ? (
85
+ <View style={gap}>
86
+ <Text style={{ fontWeight: '600' }}>Full text</Text>
87
+ <Markdown>{fullText}</Markdown>
88
+ </View>
89
+ ) : null}
90
+ </ScrollView>
91
+ </View>
92
+ );
93
+ }
@@ -0,0 +1,99 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { Pressable, View } from 'react-native';
3
+ import { Alert, Badge, DataList, Text, useTheme, type FilterGroup } from '@startsimpli/ui-native';
4
+ import { documentPreview } from '../../../corpus/view-text';
5
+ import { formatDate } from '../../../components/documentText';
6
+ import type { SourceDocument } from '../../../corpus/types';
7
+ import { useControllerState as useStore } from '../../components/useControllerState';
8
+ import type { FilterKey, LibraryController, LibraryOrder, Option } from './controller';
9
+
10
+ export interface LibraryListScreenProps {
11
+ controller: LibraryController;
12
+ onOpen: (documentId: string) => void;
13
+ }
14
+
15
+ const group = (key: FilterKey, label: string, options: Option[], value: string | null): FilterGroup => ({ key, label, options, value, display: 'select' });
16
+ const FILTER_NAMES: Record<string, string> = { search: 'search', source: 'source', subtype: 'type', focus: 'project', order: 'order' };
17
+
18
+ /** Documents, newest first: server-side search, source / type / project filters and order; tap a row to read it. */
19
+ export function LibraryListScreen({ controller, onOpen }: LibraryListScreenProps) {
20
+ const s = useStore(controller);
21
+ const theme = useTheme();
22
+ const [draft, setDraft] = useState(s.filters.search);
23
+ useEffect(() => { void controller.start(); }, [controller]);
24
+
25
+ const filters = [
26
+ group('source', 'Source', s.sources, s.filters.source),
27
+ group('subtype', 'Type', s.types, s.filters.subtype),
28
+ group('project', 'Project', s.projects, s.filters.project),
29
+ ].filter((g) => g.options.length > 0);
30
+ const ignored = s.list.ignoredFilters.map((k) => FILTER_NAMES[k] ?? k);
31
+ const count = s.list.count;
32
+
33
+ return (
34
+ <DataList<SourceDocument>
35
+ testID="library-list"
36
+ data={s.list.items}
37
+ keyExtractor={(d) => d.id}
38
+ loading={s.list.loading}
39
+ refreshing={false}
40
+ onRefresh={() => { void controller.refresh(); }}
41
+ error={s.list.error}
42
+ onRetry={() => { void controller.refresh(); }}
43
+ hasMore={s.list.hasMore}
44
+ loadingMore={s.list.loadingMore}
45
+ onLoadMore={() => { void controller.loadMore(); }}
46
+ search={{
47
+ value: draft, onChange: setDraft, placeholder: 'Search your documents',
48
+ onSearch: (text) => { void controller.setSearch(text); },
49
+ }}
50
+ filters={filters}
51
+ onFilterChange={(key, value) => { void controller.setFilter(key as FilterKey, value); }}
52
+ onClearFilters={() => { setDraft(''); void controller.clearFilters(); }}
53
+ sort={{
54
+ value: s.filters.order,
55
+ options: [{ value: 'recent', label: 'Newest' }, { value: 'oldest', label: 'Oldest' }],
56
+ onChange: (v) => { void controller.setOrder(v as LibraryOrder); },
57
+ }}
58
+ emptyTitle="No documents yet"
59
+ emptyDescription="Notes, meetings and files you connect appear here."
60
+ noResultsTitle="Nothing matches"
61
+ ListHeaderComponent={
62
+ <View style={{ gap: theme.spacing.sm, paddingBottom: theme.spacing.sm }}>
63
+ <Text variant="heading">Library</Text>
64
+ {count !== null ? <Text variant="caption">{`${count} document${count === 1 ? '' : 's'}`}</Text> : null}
65
+ {ignored.length ? (
66
+ <Alert>{`This workspace does not filter by ${ignored.join(', ')} yet, so the list below is not narrowed by ${ignored.length > 1 ? 'those' : 'that'}.`}</Alert>
67
+ ) : null}
68
+ </View>
69
+ }
70
+ renderItem={({ item }) => <DocumentRow document={item} filings={s.filings[item.id]} onPress={() => onOpen(item.id)} />}
71
+ />
72
+ );
73
+ }
74
+
75
+ function DocumentRow({ document, filings, onPress }: { document: SourceDocument; filings: Array<{ id: string; title: string }> | undefined; onPress: () => void }) {
76
+ const theme = useTheme();
77
+ const preview = documentPreview(document, 140);
78
+ return (
79
+ <Pressable
80
+ testID={`library-row-${document.id}`}
81
+ accessibilityRole="button"
82
+ onPress={onPress}
83
+ style={({ pressed }) => ({ paddingVertical: theme.spacing.md, gap: theme.spacing.xs, borderBottomWidth: 1, borderBottomColor: theme.colors.border, opacity: pressed ? 0.6 : 1 })}
84
+ >
85
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: theme.spacing.sm }}>
86
+ <Badge label={document.sourceLabel || document.source} variant="outline" />
87
+ <Text variant="caption">{formatDate(document.occurredAt)}</Text>
88
+ </View>
89
+ <Text style={{ fontWeight: '600' }} numberOfLines={2}>{document.title}</Text>
90
+ {preview ? <Text variant="muted" numberOfLines={2}>{preview}</Text> : null}
91
+ <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: theme.spacing.xs }}>
92
+ {filings === undefined ? null : filings.length === 0 ? (
93
+ <Badge testID={`library-chip-${document.id}-none`} label="Unfiled" variant="secondary" />
94
+ ) : filings.map((f) => <Badge key={f.id} testID={`library-chip-${document.id}-${f.id}`} label={f.title} variant="secondary" />)}
95
+ </View>
96
+ </Pressable>
97
+ );
98
+ }
99
+
@@ -0,0 +1,196 @@
1
+ /**
2
+ * The Library tab's logic, framework-free (same pattern as `VoiceNotesController`):
3
+ * the web `LibraryPage` as a phone would run it. Search, source, type, project and
4
+ * order are SERVER parameters on one paged documents list - nothing here loads a
5
+ * list and narrows it locally. Filing a document under a project goes through the
6
+ * existing filing code (`corpus/filing.ts`) via `api.corpus.fileDocument`.
7
+ */
8
+ import { ABOUT_FOCUS, type DocumentFiling } from '../../../corpus/filing';
9
+ import type { DocumentQuery, SourceDocument } from '../../../corpus/types';
10
+ import { openFailureMessage } from '../../../corpus/view-text';
11
+ import type { NativeCorpusApi } from '../../corpus/api';
12
+ import type { PagedList, PagedListState } from '../../corpus/paged';
13
+ import type { Store } from '../../components/useControllerState';
14
+ import { createStore, errorMessage } from '../store';
15
+
16
+ export interface Option { value: string; label: string }
17
+ export type LibraryOrder = 'recent' | 'oldest';
18
+ export interface LibraryFilters {
19
+ search: string;
20
+ source: string | null;
21
+ subtype: string | null;
22
+ project: string | null;
23
+ order: LibraryOrder;
24
+ }
25
+ export type FilterKey = 'source' | 'subtype' | 'project';
26
+
27
+ export interface LibraryState {
28
+ /** True once the filter options and the first page have been asked for. */
29
+ ready: boolean;
30
+ list: PagedListState<SourceDocument>;
31
+ filters: LibraryFilters;
32
+ sources: Option[];
33
+ types: Option[];
34
+ projects: Option[];
35
+ /** The projects each loaded document is filed under, by document id. */
36
+ filings: Record<string, DocumentFiling[]>;
37
+ selected: { id: string; document: SourceDocument | null; loading: boolean; error: string | null } | null;
38
+ filingBusy: boolean;
39
+ filingError: string | null;
40
+ }
41
+
42
+ export interface LibraryController extends Store<LibraryState> {
43
+ start(): Promise<void>;
44
+ setSearch(text: string): Promise<void>;
45
+ setFilter(key: FilterKey, value: string | null): Promise<void>;
46
+ setOrder(order: LibraryOrder): Promise<void>;
47
+ clearFilters(): Promise<void>;
48
+ refresh(): Promise<void>;
49
+ loadMore(): Promise<void>;
50
+ open(id: string): Promise<void>;
51
+ close(): void;
52
+ /** Move a document to another project (`null` = unfiled). */
53
+ fileUnder(documentId: string, projectId: string | null): Promise<void>;
54
+ }
55
+
56
+ export const EMPTY_FILTERS: LibraryFilters = { search: '', source: null, subtype: null, project: null, order: 'recent' };
57
+ const UNREADABLE_PROJECT = 'A project you cannot open';
58
+
59
+ const humanize = (value: string) => {
60
+ const spaced = value.replace(/[_-]+/g, ' ').trim();
61
+ return spaced ? spaced[0].toUpperCase() + spaced.slice(1) : value;
62
+ };
63
+
64
+ export function toQuery(f: LibraryFilters): Omit<DocumentQuery, 'page' | 'pageSize'> {
65
+ return {
66
+ ...(f.search.trim() ? { search: f.search.trim() } : {}),
67
+ ...(f.source ? { source: f.source } : {}),
68
+ ...(f.subtype ? { subtype: f.subtype } : {}),
69
+ ...(f.project ? { focus: f.project } : {}),
70
+ order: f.order,
71
+ };
72
+ }
73
+
74
+ export function createLibraryController(api: NativeCorpusApi, options: { pageSize?: number } = {}): LibraryController {
75
+ const paged: PagedList<SourceDocument, Omit<DocumentQuery, 'page' | 'pageSize'>> = api.lists.documents(toQuery(EMPTY_FILTERS), options.pageSize ?? 25);
76
+ const store = createStore<LibraryState>({
77
+ ready: false, list: paged.getState(), filters: EMPTY_FILTERS,
78
+ sources: [], types: [], projects: [], filings: {}, selected: null, filingBusy: false, filingError: null,
79
+ });
80
+ const requested = new Set<string>();
81
+ let started: Promise<void> | null = null;
82
+ let optionsReady: Promise<void> | null = null;
83
+
84
+ paged.subscribe(() => store.set({ list: paged.getState() }));
85
+
86
+ const projectTitle = (id: string) => store.getState().projects.find((p) => p.value === id)?.label ?? UNREADABLE_PROJECT;
87
+
88
+ async function loadOptions(): Promise<void> {
89
+ const labels = new Map<string, string>();
90
+ await api.corpus.listSources().then((rows) => rows.forEach((r) => labels.set(r.source, r.label))).catch(() => undefined);
91
+ const facet = (attr: string) => api.entities.facets({ type: 'source_document', facetAttr: attr, pageSize: 100 })
92
+ .then((page) => page.items.map((row) => String(row.value ?? '')).filter(Boolean))
93
+ .catch(() => [] as string[]);
94
+ const [sources, types, projects] = await Promise.all([
95
+ facet('source'),
96
+ facet('subtype'),
97
+ (api.corpus.listFocusChoices?.() ?? Promise.resolve([])).catch(() => []),
98
+ ]);
99
+ store.set({
100
+ sources: sources.map((value) => ({ value, label: labels.get(value) ?? humanize(value) })),
101
+ types: types.map((value) => ({ value, label: humanize(value) })),
102
+ projects: projects.map((p) => ({ value: p.id, label: p.title })),
103
+ });
104
+ }
105
+
106
+ /** The filter options and the project names, asked for once, whichever screen needs them first. */
107
+ const ensureOptions = () => (optionsReady ??= loadOptions());
108
+
109
+ /** One request for the projects of every loaded row not asked about yet. */
110
+ async function loadFilings(ids: string[] = paged.getState().items.map((d) => d.id)) {
111
+ const missing = ids.filter((id) => !requested.has(id));
112
+ if (!missing.length) return;
113
+ await ensureOptions();
114
+ missing.forEach((id) => requested.add(id));
115
+ try {
116
+ const edges = await api.relationships.list({ relType: ABOUT_FOCUS, sourceIn: missing, pageSize: 200 });
117
+ const found: Record<string, DocumentFiling[]> = Object.fromEntries(missing.map((id) => [id, [] as DocumentFiling[]]));
118
+ for (const edge of edges.items) {
119
+ const list = found[String(edge.source)];
120
+ const id = String(edge.target);
121
+ if (list && !list.some((f) => f.id === id)) list.push({ id, title: projectTitle(id) });
122
+ }
123
+ store.update((s) => ({ filings: { ...s.filings, ...found } }));
124
+ } catch {
125
+ missing.forEach((id) => requested.delete(id));
126
+ }
127
+ }
128
+
129
+ const afterList = async () => { await loadFilings(); };
130
+
131
+ async function applyFilters(next: LibraryFilters) {
132
+ store.set({ filters: next });
133
+ await paged.setQuery(toQuery(next));
134
+ await afterList();
135
+ }
136
+
137
+ const controller: LibraryController = {
138
+ getState: store.getState,
139
+ subscribe: store.subscribe,
140
+ start() {
141
+ started ??= (async () => {
142
+ await ensureOptions();
143
+ await paged.refresh();
144
+ store.set({ ready: true });
145
+ await afterList();
146
+ })();
147
+ return started;
148
+ },
149
+ setSearch: (text) => applyFilters({ ...store.getState().filters, search: text }),
150
+ setFilter: (key, value) => applyFilters({ ...store.getState().filters, [key]: value }),
151
+ setOrder: (order) => applyFilters({ ...store.getState().filters, order }),
152
+ clearFilters: () => applyFilters(EMPTY_FILTERS),
153
+ async refresh() { await paged.refresh(); await afterList(); },
154
+ async loadMore() { await paged.loadMore(); await afterList(); },
155
+
156
+ async open(id) {
157
+ const onPage = paged.getState().items.find((d) => d.id === id);
158
+ if (onPage) { store.set({ selected: { id, document: onPage, loading: false, error: null } }); void loadFilings([id]); return; }
159
+ store.set({ selected: { id, document: null, loading: true, error: null } });
160
+ try {
161
+ const document = await api.corpus.getDocument(id);
162
+ if (store.getState().selected?.id !== id) return;
163
+ store.set({ selected: { id, document, loading: false, error: null } });
164
+ await loadFilings([id]);
165
+ } catch (e) {
166
+ if (store.getState().selected?.id !== id) return;
167
+ store.set({ selected: { id, document: null, loading: false, error: openFailureMessage(e, id) } });
168
+ }
169
+ },
170
+ close() { store.set({ selected: null }); },
171
+
172
+ async fileUnder(documentId, projectId) {
173
+ if (!api.corpus.fileDocument) { store.set({ filingError: 'This workspace cannot move documents.' }); return; }
174
+ const before = store.getState().filings[documentId] ?? [];
175
+ store.update((s) => ({
176
+ filingBusy: true, filingError: null,
177
+ filings: { ...s.filings, [documentId]: projectId ? [{ id: projectId, title: projectTitle(projectId) }] : [] },
178
+ }));
179
+ try {
180
+ await api.corpus.fileDocument(documentId, projectId);
181
+ // A project filter is a server query: a row that moved out of it leaves it on the next read.
182
+ if (store.getState().filters.project) await paged.refresh();
183
+ } catch (e) {
184
+ store.set({ filingError: errorMessage(e, 'Could not change the project.') });
185
+ // The write is delete-then-add, so a failure can leave the document half moved:
186
+ // show what the server says now, not a guess.
187
+ requested.delete(documentId);
188
+ store.update((s) => ({ filings: { ...s.filings, [documentId]: before } }));
189
+ await loadFilings([documentId]);
190
+ } finally {
191
+ store.set({ filingBusy: false });
192
+ }
193
+ },
194
+ };
195
+ return controller;
196
+ }