@startsimpli/integrations 0.2.72 → 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.
- package/README.md +2 -0
- package/package.json +1 -1
- package/src/__tests__/view-text.test.ts +31 -0
- package/src/components/Markdown.tsx +1 -15
- package/src/components/pages/AskPage.tsx +12 -59
- package/src/components/pages/LibraryPage.tsx +1 -45
- package/src/corpus/client.ts +8 -4
- package/src/corpus/entities.ts +1 -0
- package/src/corpus/types.ts +4 -0
- package/src/corpus/view-text.ts +113 -0
- package/src/native/components/NotesShell.tsx +9 -4
- package/src/native/corpus/fake-tenant.ts +6 -0
- package/src/native/index.ts +9 -0
- package/src/native/screens/__tests__/ask-controller.test.ts +135 -0
- package/src/native/screens/__tests__/ask-screen.test.tsx +96 -0
- package/src/native/screens/__tests__/library-controller.test.ts +185 -0
- package/src/native/screens/__tests__/library-screens.test.tsx +134 -0
- package/src/native/screens/__tests__/tabs.test.tsx +46 -0
- package/src/native/screens/ask/AskScreen.tsx +118 -0
- package/src/native/screens/ask/answer-view.ts +53 -0
- package/src/native/screens/ask/controller.ts +100 -0
- package/src/native/screens/library/LibraryDetailScreen.tsx +93 -0
- package/src/native/screens/library/LibraryListScreen.tsx +99 -0
- package/src/native/screens/library/controller.ts +196 -0
- package/src/native/screens/library/fake-library.ts +38 -0
- package/src/native/screens/store.ts +19 -0
- package/src/native/screens/tabs.tsx +41 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shared tenant fake plus the extra documents the Library and Ask screens
|
|
3
|
+
* need to look like a real corpus: a Markdown summary, an unfiled document and a
|
|
4
|
+
* second page worth of rows. The base rows (`sampleTenantEntities`) stay as the
|
|
5
|
+
* other tabs expect them; these are added on top, for this tab's simulator proof
|
|
6
|
+
* and tests only.
|
|
7
|
+
*/
|
|
8
|
+
import type { TenantEntity, TenantRelationship } from '../../../corpus/entities';
|
|
9
|
+
import { createFakeNativeCorpusApi, type FakeNativeCorpusApi } from '../../corpus/fake';
|
|
10
|
+
import { sampleTenantEntities, sampleTenantRelationships } from '../../corpus/fake-data';
|
|
11
|
+
import type { FakeTenantOptions } from '../../corpus/fake-tenant';
|
|
12
|
+
|
|
13
|
+
const doc = (id: string, source: string, subtype: string, title: string, createdAt: string, summary: string, extra: Record<string, unknown> = {}): TenantEntity => ({
|
|
14
|
+
id, entity_type: 'source_document', external_id: `${source}:${id}`, name: title, created_at: createdAt, org_id: 'tandem',
|
|
15
|
+
data: { title, source, subtype, occurred_at: createdAt, summary, ...extra },
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
export function libraryExtraEntities(): TenantEntity[] {
|
|
19
|
+
return [
|
|
20
|
+
doc('d4', 'granola', 'meeting', 'Pricing call with Acme', '2026-10-20T13:00:00Z',
|
|
21
|
+
'## Decisions\n\nAcme renews at **$4,800 per month** for 12 months.\n\n## Next steps\n\n- Send the order form\n- Confirm the start date'),
|
|
22
|
+
doc('d5', 'drive', 'document', 'Office move notes', '2026-10-12T09:30:00Z',
|
|
23
|
+
'Movers booked for the 14th. Keys go back to the landlord on the 15th.', { path: '/Admin' }),
|
|
24
|
+
];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function libraryExtraRelationships(): TenantRelationship[] {
|
|
28
|
+
return [{ id: 'e8', rel_type: 'about_focus', source: 'd4', target: 'fma' }];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** `createFakeNativeCorpusApi` over the base corpus plus the Library extras. */
|
|
32
|
+
export function createFakeLibraryApi(options: FakeTenantOptions = {}): FakeNativeCorpusApi {
|
|
33
|
+
return createFakeNativeCorpusApi({
|
|
34
|
+
entities: [...sampleTenantEntities(), ...libraryExtraEntities()],
|
|
35
|
+
relationships: [...sampleTenantRelationships(), ...libraryExtraRelationships()],
|
|
36
|
+
...options,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tiny store both tab controllers are built on: an immutable state value, a
|
|
3
|
+
* subscribe, and `set(patch)`. Screens read it with `useControllerState`.
|
|
4
|
+
*/
|
|
5
|
+
import type { Store } from '../components/useControllerState';
|
|
6
|
+
|
|
7
|
+
export function createStore<S extends object>(initial: S) {
|
|
8
|
+
let state = initial;
|
|
9
|
+
const listeners = new Set<() => void>();
|
|
10
|
+
return {
|
|
11
|
+
getState: () => state,
|
|
12
|
+
subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
13
|
+
set(patch: Partial<S>) { state = { ...state, ...patch }; listeners.forEach((l) => l()); },
|
|
14
|
+
update(fn: (s: S) => Partial<S>) { state = { ...state, ...fn(state) }; listeners.forEach((l) => l()); },
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const errorMessage = (e: unknown, fallback = 'That did not work.'): string =>
|
|
19
|
+
e instanceof Error && e.message ? e.message : fallback;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { useMemo } from 'react';
|
|
2
|
+
import type { FoundryTab, TabContext } from '../components/FoundryTabsShell';
|
|
3
|
+
import type { NativeCorpusApi } from '../corpus/api';
|
|
4
|
+
import { AskScreen } from './ask/AskScreen';
|
|
5
|
+
import { createAskController } from './ask/controller';
|
|
6
|
+
import { LibraryDetailScreen } from './library/LibraryDetailScreen';
|
|
7
|
+
import { LibraryListScreen } from './library/LibraryListScreen';
|
|
8
|
+
import { createLibraryController } from './library/controller';
|
|
9
|
+
|
|
10
|
+
export const LIBRARY_TAB = 'library';
|
|
11
|
+
export const ASK_TAB = 'ask';
|
|
12
|
+
|
|
13
|
+
function LibraryTabBody({ api, ctx }: { api: NativeCorpusApi; ctx: TabContext }) {
|
|
14
|
+
const controller = useMemo(() => createLibraryController(api), [api]);
|
|
15
|
+
return ctx.route
|
|
16
|
+
? <LibraryDetailScreen controller={controller} documentId={ctx.route.id} onBack={ctx.back} />
|
|
17
|
+
: <LibraryListScreen controller={controller} onOpen={(id) => ctx.push(id)} />;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function AskTabBody({ api, ctx }: { api: NativeCorpusApi; ctx: TabContext }) {
|
|
21
|
+
const controller = useMemo(() => createAskController({
|
|
22
|
+
api: api.ask,
|
|
23
|
+
scope: api.scope,
|
|
24
|
+
listProjects: async () => (await api.corpus.listFocusChoices?.()) ?? [],
|
|
25
|
+
}), [api]);
|
|
26
|
+
// A citation opens the cited record in the Library tab; Back there returns to its list.
|
|
27
|
+
return <AskScreen controller={controller} onOpenDocument={(id) => ctx.openTab(LIBRARY_TAB, id)} />;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The Library tab: documents list -> one document. */
|
|
31
|
+
export function libraryTab(api: NativeCorpusApi, over: Partial<Pick<FoundryTab, 'key' | 'label'>> = {}): FoundryTab {
|
|
32
|
+
return { key: LIBRARY_TAB, label: 'Library', ...over, render: (ctx) => <LibraryTabBody api={api} ctx={ctx} /> };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The Ask tab: project-scoped questions over the documents. Citations jump to the Library tab. */
|
|
36
|
+
export function askTab(api: NativeCorpusApi, over: Partial<Pick<FoundryTab, 'key' | 'label'>> = {}): FoundryTab {
|
|
37
|
+
return { key: ASK_TAB, label: 'Ask', ...over, render: (ctx) => <AskTabBody api={api} ctx={ctx} /> };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Both tabs, for an app that wants Library and Ask in one go. */
|
|
41
|
+
export const libraryAskTabs = (api: NativeCorpusApi): FoundryTab[] => [libraryTab(api), askTab(api)];
|