@startsimpli/integrations 0.2.70 → 0.2.72
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 +3 -3
- package/src/native/components/useControllerState.ts +11 -0
- package/src/native/corpus/fake-data.ts +5 -2
- package/src/native/home/HomeScreen.tsx +67 -0
- package/src/native/home/__tests__/controller.test.ts +66 -0
- package/src/native/home/controller.ts +95 -0
- package/src/native/home/tab.tsx +47 -0
- package/src/native/index.ts +10 -0
- package/src/native/tracker/TrackerDetailScreen.tsx +82 -0
- package/src/native/tracker/TrackerListScreen.tsx +85 -0
- package/src/native/tracker/__tests__/controller.test.ts +129 -0
- package/src/native/tracker/__tests__/detail.test.ts +64 -0
- package/src/native/tracker/__tests__/format.test.ts +42 -0
- package/src/native/tracker/controller.ts +152 -0
- package/src/native/tracker/detail.ts +95 -0
- package/src/native/tracker/format.ts +79 -0
- package/src/native/tracker/tab.tsx +24 -0
package/README.md
CHANGED
|
@@ -212,6 +212,8 @@ Rules every list tab follows: one server request per page (never load a list and
|
|
|
212
212
|
4. **Fake**: extend `sampleTenantEntities()` / `sampleTenantRelationships()` in `native/corpus/fake-data.ts` with rows for your tab. The fake tenant already serves them through the contract, so the simulator (`-tgTab <key>`) and the tests show real mapped data with no sign-in and no tenant.
|
|
213
213
|
5. Export from `native/index.ts`, run `pnpm type-check && pnpm test` in this package.
|
|
214
214
|
|
|
215
|
+
**Shipped tabs.** `trackerTab({ api, notesKey })` (to-dos: Outstanding / Overdue / Changed this week / Closed, project Select, search, swipe or tap to mark done, detail with the source quote and an "Open note" link) and `homeTab({ api, brand, tabs, recordKey })` (the web Home's counts and latest arrivals, a "Record a note" button). Controllers (`createTrackerController`, `createTrackerDetailController`, `createHomeController`) are pure and tested against `createFakeNativeCorpusApi()`.
|
|
216
|
+
|
|
215
217
|
Not wired yet: `mcpTokens` and `connectionsMe` (`src/api/*`) call a module-global `request()` that does not use `authorizedFetch`; the Connections / Connect Claude tabs need a `create*Api(fetch)` factory first.
|
|
216
218
|
|
|
217
219
|
## Verification
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@startsimpli/integrations",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.72",
|
|
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",
|
|
@@ -90,9 +90,9 @@
|
|
|
90
90
|
"vitest": "^3.0.0",
|
|
91
91
|
"react-native": "0.85.3",
|
|
92
92
|
"react-native-safe-area-context": "~5.7.0",
|
|
93
|
-
"@startsimpli/ui": "0.4.167",
|
|
94
93
|
"@startsimpli/llm": "0.4.28",
|
|
95
|
-
"@startsimpli/ui-native": "0.1.
|
|
94
|
+
"@startsimpli/ui-native": "0.1.2",
|
|
95
|
+
"@startsimpli/ui": "0.4.167"
|
|
96
96
|
},
|
|
97
97
|
"scripts": {
|
|
98
98
|
"type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { useSyncExternalStore } from 'react';
|
|
2
|
+
|
|
3
|
+
/** Anything with `getState` + `subscribe` (the tab controllers). */
|
|
4
|
+
export interface Store<S> {
|
|
5
|
+
getState(): S;
|
|
6
|
+
subscribe(listener: () => void): () => void;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function useControllerState<S>(store: Store<S>): S {
|
|
10
|
+
return useSyncExternalStore(store.subscribe, store.getState, store.getState);
|
|
11
|
+
}
|
|
@@ -9,6 +9,9 @@ const at = (iso: string) => iso;
|
|
|
9
9
|
const row = (id: string, type: string, external: string, name: string, createdAt: string, data: Record<string, unknown>): TenantEntity =>
|
|
10
10
|
({ id, entity_type: type, external_id: external, name, created_at: at(createdAt), org_id: 'tandem', data });
|
|
11
11
|
|
|
12
|
+
const mention = (documentId: string, occurredAt: string, quote: string, section?: string) =>
|
|
13
|
+
({ document_id: documentId, origin_key: `${documentId}:1`, occurred_at: occurredAt, quote, extractor: 'rules', ...(section ? { section } : {}) });
|
|
14
|
+
|
|
12
15
|
const commitment = (id: string, title: string, createdAt: string, data: Record<string, unknown>) =>
|
|
13
16
|
row(id, 'commitment', `commit:${id}`, title, createdAt, {
|
|
14
17
|
title, subtype: 'action', source: 'voice', source_label: 'Voice note', mentions: [], extractor_version: 'fake-1',
|
|
@@ -21,9 +24,9 @@ export function sampleTenantEntities(): TenantEntity[] {
|
|
|
21
24
|
row('fma', 'focus', 'focus:marketing-agents', 'Marketing agents', '2026-09-02T00:00:00Z', { title: 'Marketing agents', status: 'on_track', category: 'product', progress: 0.7, sort_order: 2 }),
|
|
22
25
|
row('fdbg', 'focus', 'focus:debug', 'Debug', '2026-09-03T00:00:00Z', { title: 'Debug', status: 'at_risk', category: 'team', progress: 0.2, sort_order: 3 }),
|
|
23
26
|
|
|
24
|
-
commitment('c1', 'Finish exhibit list', '2026-11-03T14:40:00Z', { status: 'open', owner_name: 'Quinn', due_at: '2026-11-05T17:00:00Z', priority: 1, detail: 'Needed before the hearing.' }),
|
|
27
|
+
commitment('c1', 'Finish exhibit list', '2026-11-03T14:40:00Z', { status: 'open', owner_name: 'Quinn', due_at: '2026-11-05T17:00:00Z', priority: 1, detail: 'Needed before the hearing.', mentions: [mention('n1', '2026-11-03T14:38:00Z', 'I still have to finish the exhibit list before the hearing.', 'Hearing prep')] }),
|
|
25
28
|
commitment('c2', 'Call Megan about the filing receipt', '2026-11-03T14:41:00Z', { status: 'open', owner_name: 'Quinn', due_at: '2026-11-04T17:00:00Z', priority: 2 }),
|
|
26
|
-
commitment('c3', 'Move weekly report to Monday', '2026-11-03T14:42:00Z', { status: 'open', owner_name: 'Quinn' }),
|
|
29
|
+
commitment('c3', 'Move weekly report to Monday', '2026-11-03T14:42:00Z', { status: 'open', owner_name: 'Quinn', source: 'granola', source_label: 'Granola', mentions: [mention('d2', '2026-11-02T15:00:00Z', 'Let us move the weekly report to Mondays.')] }),
|
|
27
30
|
commitment('c4', 'Book the dentist', '2026-11-03T14:43:00Z', { status: 'open', owner_name: 'Quinn', due_at: '2026-11-06T09:00:00Z' }),
|
|
28
31
|
commitment('c5', 'Send the revised proposal', '2026-10-28T10:00:00Z', { status: 'done', owner_name: 'Rae', resolved_at: '2026-10-30T10:00:00Z' }),
|
|
29
32
|
commitment('c6', 'Waiting on court clerk reply', '2026-10-29T10:00:00Z', { status: 'blocked', owner_name: 'Quinn', status_reason: 'Clerk has not answered' }),
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { useEffect } from 'react';
|
|
2
|
+
import { FlatList, Pressable, RefreshControl, View } from 'react-native';
|
|
3
|
+
import { Alert, Button, EmptyState, ListRow, Skeleton, StatTile, Text, useTheme } from '@startsimpli/ui-native';
|
|
4
|
+
import { useControllerState } from '../components/useControllerState';
|
|
5
|
+
import { timeAgo, type HomeArrival, type HomeController } from './controller';
|
|
6
|
+
|
|
7
|
+
export interface HomeScreenProps {
|
|
8
|
+
controller: HomeController;
|
|
9
|
+
brand: string;
|
|
10
|
+
tagline?: string;
|
|
11
|
+
/** Record a note (the web Home's quick-record). Omit to hide the button. */
|
|
12
|
+
onRecord?: () => void;
|
|
13
|
+
/** A metric tile was tapped. */
|
|
14
|
+
onOpenType?: (typeKey: string) => void;
|
|
15
|
+
/** An arrival was tapped. */
|
|
16
|
+
onOpenArrival?: (arrival: HomeArrival) => void;
|
|
17
|
+
/** False while another tab is showing; the counts reload each time Home comes back. Default true. */
|
|
18
|
+
active?: boolean;
|
|
19
|
+
now?: () => number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The front door, as the web Home draws it: brand, "What has come in" counts, "Latest arrivals". */
|
|
23
|
+
export function HomeScreen({ controller, brand, tagline, onRecord, onOpenType, onOpenArrival, active = true, now = Date.now }: HomeScreenProps) {
|
|
24
|
+
const theme = useTheme();
|
|
25
|
+
const s = useControllerState(controller);
|
|
26
|
+
useEffect(() => { if (active) void controller.load(); }, [controller, active]);
|
|
27
|
+
return (
|
|
28
|
+
<FlatList
|
|
29
|
+
testID="home-list"
|
|
30
|
+
data={s.arrivals}
|
|
31
|
+
keyExtractor={(a) => `${a.type}-${a.id}`}
|
|
32
|
+
refreshControl={<RefreshControl refreshing={false} onRefresh={() => { void controller.refresh(); }} tintColor={theme.colors.mutedForeground} />}
|
|
33
|
+
contentContainerStyle={{ padding: theme.spacing.lg, paddingBottom: theme.spacing.xl, flexGrow: 1 }}
|
|
34
|
+
ListHeaderComponent={
|
|
35
|
+
<View style={{ gap: theme.spacing.md, paddingBottom: theme.spacing.md }}>
|
|
36
|
+
<View>
|
|
37
|
+
<Text variant="heading">{brand}</Text>
|
|
38
|
+
{tagline ? <Text variant="muted">{tagline}</Text> : null}
|
|
39
|
+
</View>
|
|
40
|
+
{onRecord ? <Button testID="home-record" title="Record a note" onPress={onRecord} /> : null}
|
|
41
|
+
{s.error ? <Alert variant="destructive">{s.error}</Alert> : null}
|
|
42
|
+
<Text variant="caption" style={{ fontWeight: '600' }}>WHAT HAS COME IN</Text>
|
|
43
|
+
<View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: theme.spacing.sm }}>
|
|
44
|
+
{s.metrics.map((m) => (
|
|
45
|
+
<View key={m.key} style={{ flexGrow: 1, flexBasis: '30%' }} testID={`home-metric-${m.key}`}>
|
|
46
|
+
{s.loading ? <Skeleton height={72} /> : (
|
|
47
|
+
<Pressable accessibilityRole="button" disabled={!onOpenType} onPress={() => onOpenType?.(m.key)} testID={`home-metric-open-${m.key}`}>
|
|
48
|
+
<StatTile value={m.count === null ? '–' : String(m.count)} label={m.label} />
|
|
49
|
+
</Pressable>
|
|
50
|
+
)}
|
|
51
|
+
</View>
|
|
52
|
+
))}
|
|
53
|
+
</View>
|
|
54
|
+
<Text variant="caption" style={{ fontWeight: '600' }}>LATEST ARRIVALS</Text>
|
|
55
|
+
</View>
|
|
56
|
+
}
|
|
57
|
+
ListEmptyComponent={s.loading ? null : <EmptyState title="No records yet" description="Record a note to get started." />}
|
|
58
|
+
renderItem={({ item }) => (
|
|
59
|
+
<ListRow
|
|
60
|
+
title={item.title}
|
|
61
|
+
subtitle={[item.typeLabel, timeAgo(item.createdAt, now())].filter(Boolean).join(' · ')}
|
|
62
|
+
onPress={onOpenArrival ? () => onOpenArrival(item) : undefined}
|
|
63
|
+
/>
|
|
64
|
+
)}
|
|
65
|
+
/>
|
|
66
|
+
);
|
|
67
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { createFakeNativeCorpusApi } from '../../corpus/fake';
|
|
3
|
+
import { createHomeController, timeAgo } from '../controller';
|
|
4
|
+
|
|
5
|
+
const NOW = Date.parse('2026-11-04T00:00:00Z');
|
|
6
|
+
const types = [
|
|
7
|
+
{ key: 'commitment', label: 'To-dos' },
|
|
8
|
+
{ key: 'source_document', label: 'Documents' },
|
|
9
|
+
{ key: 'focus', label: 'Projects' },
|
|
10
|
+
];
|
|
11
|
+
|
|
12
|
+
describe('home controller: what has come in', () => {
|
|
13
|
+
it('one count per type, read from the server COUNT of a one-row page', async () => {
|
|
14
|
+
const api = createFakeNativeCorpusApi();
|
|
15
|
+
const c = createHomeController({ api, types, now: () => NOW });
|
|
16
|
+
await c.load();
|
|
17
|
+
const s = c.getState();
|
|
18
|
+
expect(s.metrics.map((m) => [m.label, m.count])).toEqual([['To-dos', 6], ['Documents', 3], ['Projects', 3]]);
|
|
19
|
+
const counts = api.tenant.requests.filter((r) => r.params?.page_size === 1);
|
|
20
|
+
expect(counts).toHaveLength(3);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('latest arrivals: newest first across types, limited, each a bounded server page', async () => {
|
|
24
|
+
const api = createFakeNativeCorpusApi();
|
|
25
|
+
const c = createHomeController({ api, types, limit: 4, now: () => NOW });
|
|
26
|
+
await c.load();
|
|
27
|
+
const s = c.getState();
|
|
28
|
+
expect(s.arrivals).toHaveLength(4);
|
|
29
|
+
expect(s.arrivals[0].title).toBe('Book the dentist');
|
|
30
|
+
const stamps = s.arrivals.map((a) => a.createdAt);
|
|
31
|
+
expect([...stamps].sort().reverse()).toEqual(stamps);
|
|
32
|
+
const pages = api.tenant.requests.filter((r) => r.params?.order === 'recent');
|
|
33
|
+
expect(pages.length).toBe(3);
|
|
34
|
+
expect(pages.every((r) => r.params?.page_size === 4)).toBe(true);
|
|
35
|
+
expect(s.arrivals[0]).toMatchObject({ type: expect.any(String), typeLabel: expect.any(String) });
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('a type that fails shows no count instead of a false zero, and the rest still load', async () => {
|
|
39
|
+
const api = createFakeNativeCorpusApi({ onRequest: (_m, _p, params) => { if (params.type === 'focus') throw new Error('boom'); } });
|
|
40
|
+
const c = createHomeController({ api, types, now: () => NOW });
|
|
41
|
+
await c.load();
|
|
42
|
+
const s = c.getState();
|
|
43
|
+
expect(s.metrics.find((m) => m.key === 'focus')?.count).toBeNull();
|
|
44
|
+
expect(s.metrics.find((m) => m.key === 'commitment')?.count).toBe(6);
|
|
45
|
+
expect(s.loading).toBe(false);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('refresh reloads', async () => {
|
|
49
|
+
const api = createFakeNativeCorpusApi();
|
|
50
|
+
const c = createHomeController({ api, types, now: () => NOW });
|
|
51
|
+
await c.load();
|
|
52
|
+
await c.refresh();
|
|
53
|
+
expect(c.getState().loading).toBe(false);
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe('timeAgo', () => {
|
|
58
|
+
it.each([
|
|
59
|
+
['2026-11-03T23:59:30Z', 'just now'],
|
|
60
|
+
['2026-11-03T23:30:00Z', '30m ago'],
|
|
61
|
+
['2026-11-03T20:00:00Z', '4h ago'],
|
|
62
|
+
['2026-11-01T00:00:00Z', '3d ago'],
|
|
63
|
+
['2026-09-01T00:00:00Z', 'Sep 1'],
|
|
64
|
+
['garbage', ''],
|
|
65
|
+
])('%s -> %s', (iso, text) => expect(timeAgo(iso, NOW)).toBe(text));
|
|
66
|
+
});
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Home tab's data: what the web Home shows ("What has come in" metrics and
|
|
3
|
+
* "Latest arrivals"), as a framework-free controller. Counts are the server's
|
|
4
|
+
* COUNT of a one-row page per type; arrivals are the newest page of each type
|
|
5
|
+
* (server `order=recent`), merged. Nothing here loads a full list.
|
|
6
|
+
*/
|
|
7
|
+
import type { TenantEntity } from '../../corpus/entities';
|
|
8
|
+
import type { NativeCorpusApi } from '../corpus/api';
|
|
9
|
+
|
|
10
|
+
export interface HomeType { key: string; label: string }
|
|
11
|
+
|
|
12
|
+
export interface HomeMetric { key: string; label: string; count: number | null }
|
|
13
|
+
export interface HomeArrival {
|
|
14
|
+
id: string;
|
|
15
|
+
type: string;
|
|
16
|
+
typeLabel: string;
|
|
17
|
+
title: string;
|
|
18
|
+
createdAt: string;
|
|
19
|
+
/** The entity's own data bag, for the app's tap routing (source, subtype ...). */
|
|
20
|
+
entity: TenantEntity;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface HomeState {
|
|
24
|
+
loading: boolean;
|
|
25
|
+
metrics: HomeMetric[];
|
|
26
|
+
arrivals: HomeArrival[];
|
|
27
|
+
error: string | null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface HomeController {
|
|
31
|
+
getState(): HomeState;
|
|
32
|
+
subscribe(listener: () => void): () => void;
|
|
33
|
+
load(): Promise<void>;
|
|
34
|
+
refresh(): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface HomeControllerOptions {
|
|
38
|
+
api: Pick<NativeCorpusApi, 'entities'>;
|
|
39
|
+
/** Which record types the home summarises. */
|
|
40
|
+
types: HomeType[];
|
|
41
|
+
/** How many arrivals to show (web: 8). */
|
|
42
|
+
limit?: number;
|
|
43
|
+
now?: () => number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
47
|
+
|
|
48
|
+
export function timeAgo(iso: string, now: number): string {
|
|
49
|
+
const t = Date.parse(iso);
|
|
50
|
+
if (Number.isNaN(t)) return '';
|
|
51
|
+
const s = Math.max(0, Math.floor((now - t) / 1000));
|
|
52
|
+
if (s < 60) return 'just now';
|
|
53
|
+
if (s < 3600) return `${Math.floor(s / 60)}m ago`;
|
|
54
|
+
if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
|
|
55
|
+
if (s < 30 * 86400) return `${Math.floor(s / 86400)}d ago`;
|
|
56
|
+
const d = new Date(t);
|
|
57
|
+
return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const stamp = (e: TenantEntity) => String(e.created_at ?? e.createdAt ?? '');
|
|
61
|
+
|
|
62
|
+
export function createHomeController({ api, types, limit = 8 }: HomeControllerOptions): HomeController {
|
|
63
|
+
let state: HomeState = { loading: true, metrics: types.map((t) => ({ key: t.key, label: t.label, count: null })), arrivals: [], error: null };
|
|
64
|
+
const listeners = new Set<() => void>();
|
|
65
|
+
const set = (patch: Partial<HomeState>) => { state = { ...state, ...patch }; listeners.forEach((l) => l()); };
|
|
66
|
+
|
|
67
|
+
async function load() {
|
|
68
|
+
const results = await Promise.all(types.map(async (t) => {
|
|
69
|
+
const [count, recent] = await Promise.all([
|
|
70
|
+
api.entities.list({ type: t.key, pageSize: 1 }).then((p) => p.count ?? null).catch(() => null),
|
|
71
|
+
api.entities.list({ type: t.key, order: 'recent', pageSize: limit }).then((p) => p.items).catch(() => [] as TenantEntity[]),
|
|
72
|
+
]);
|
|
73
|
+
return { t, count, recent };
|
|
74
|
+
}));
|
|
75
|
+
const arrivals = results
|
|
76
|
+
.flatMap(({ t, recent }) => recent.map((entity): HomeArrival => ({
|
|
77
|
+
id: String(entity.id), type: t.key, typeLabel: t.label, title: entity.name || entity.external_id || `#${entity.id}`, createdAt: stamp(entity), entity,
|
|
78
|
+
})))
|
|
79
|
+
.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
|
|
80
|
+
.slice(0, limit);
|
|
81
|
+
set({
|
|
82
|
+
loading: false,
|
|
83
|
+
metrics: results.map(({ t, count }) => ({ key: t.key, label: t.label, count })),
|
|
84
|
+
arrivals,
|
|
85
|
+
error: results.every((r) => r.count === null) ? 'Could not load your workspace.' : null,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
getState: () => state,
|
|
91
|
+
subscribe(l) { listeners.add(l); return () => { listeners.delete(l); }; },
|
|
92
|
+
load,
|
|
93
|
+
refresh: load,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { FoundryTab } from '../components/FoundryTabsShell';
|
|
2
|
+
import type { NativeCorpusApi } from '../corpus/api';
|
|
3
|
+
import { createHomeController, type HomeController, type HomeType } from './controller';
|
|
4
|
+
import { HomeScreen } from './HomeScreen';
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_HOME_TYPES: HomeType[] = [
|
|
7
|
+
{ key: 'commitment', label: 'To-dos' },
|
|
8
|
+
{ key: 'source_document', label: 'Documents' },
|
|
9
|
+
{ key: 'focus', label: 'Projects' },
|
|
10
|
+
];
|
|
11
|
+
|
|
12
|
+
export interface HomeTabOptions {
|
|
13
|
+
api: Pick<NativeCorpusApi, 'entities'>;
|
|
14
|
+
brand: string;
|
|
15
|
+
tagline?: string;
|
|
16
|
+
key?: string;
|
|
17
|
+
label?: string;
|
|
18
|
+
types?: HomeType[];
|
|
19
|
+
controller?: HomeController;
|
|
20
|
+
/** Tab keys by record type, e.g. `{ commitment: 'tracker', source_document: 'library' }`. A type with no tab is not tappable. */
|
|
21
|
+
tabs?: Record<string, string>;
|
|
22
|
+
/** Tab key of the record screen (GO); shows "Record a note". */
|
|
23
|
+
recordKey?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The Home tab as one `FoundryTabsShell` entry. */
|
|
27
|
+
export function homeTab({ api, brand, tagline, key = 'home', label = 'Home', types = DEFAULT_HOME_TYPES, controller = createHomeController({ api, types }), tabs = {}, recordKey }: HomeTabOptions): FoundryTab {
|
|
28
|
+
return {
|
|
29
|
+
key, label,
|
|
30
|
+
render: ({ openTab, active }) => (
|
|
31
|
+
<HomeScreen
|
|
32
|
+
controller={controller}
|
|
33
|
+
active={active}
|
|
34
|
+
brand={brand}
|
|
35
|
+
tagline={tagline}
|
|
36
|
+
onRecord={recordKey ? () => openTab(recordKey) : undefined}
|
|
37
|
+
onOpenType={(type) => { if (tabs[type]) openTab(tabs[type]); }}
|
|
38
|
+
onOpenArrival={(a) => {
|
|
39
|
+
const tab = tabs[a.type];
|
|
40
|
+
if (!tab) return;
|
|
41
|
+
// A voice note opens on Notes by its document id; everything else opens its own tab (detail where it has one).
|
|
42
|
+
openTab(tab, a.type === 'commitment' || (a.entity.data as { source?: string } | undefined)?.source === 'voice' ? a.id : undefined);
|
|
43
|
+
}}
|
|
44
|
+
/>
|
|
45
|
+
),
|
|
46
|
+
};
|
|
47
|
+
}
|
package/src/native/index.ts
CHANGED
|
@@ -22,3 +22,13 @@ export * from './corpus/fake';
|
|
|
22
22
|
export * from './corpus/fake-tenant';
|
|
23
23
|
export * from './corpus/fake-data';
|
|
24
24
|
export * from '../corpus/entity-query';
|
|
25
|
+
export * from './components/useControllerState';
|
|
26
|
+
export * from './tracker/format';
|
|
27
|
+
export * from './tracker/controller';
|
|
28
|
+
export * from './tracker/detail';
|
|
29
|
+
export { TrackerListScreen, type TrackerListScreenProps } from './tracker/TrackerListScreen';
|
|
30
|
+
export { TrackerDetailScreen, type TrackerDetailScreenProps } from './tracker/TrackerDetailScreen';
|
|
31
|
+
export { trackerTab, type TrackerTabOptions } from './tracker/tab';
|
|
32
|
+
export * from './home/controller';
|
|
33
|
+
export { HomeScreen, type HomeScreenProps } from './home/HomeScreen';
|
|
34
|
+
export { homeTab, DEFAULT_HOME_TYPES, type HomeTabOptions } from './home/tab';
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { useEffect, useMemo } from 'react';
|
|
2
|
+
import { ScrollView, View } from 'react-native';
|
|
3
|
+
import { Alert, Button, Card, CardContent, Header, Spinner, StatusChip, Text, useTheme } from '@startsimpli/ui-native';
|
|
4
|
+
import type { NativeCorpusApi } from '../corpus/api';
|
|
5
|
+
import { useControllerState } from '../components/useControllerState';
|
|
6
|
+
import { createTrackerDetailController } from './detail';
|
|
7
|
+
import { formatDue, isOverdueAt, priorityText } from './format';
|
|
8
|
+
|
|
9
|
+
export interface TrackerDetailScreenProps {
|
|
10
|
+
api: Pick<NativeCorpusApi, 'entities' | 'corpus' | 'relationships' | 'commitments' | 'scope'>;
|
|
11
|
+
id: string;
|
|
12
|
+
onBack: () => void;
|
|
13
|
+
/** Open the source note on the Notes tab. Offered only for voice-note sources. */
|
|
14
|
+
onOpenNote?: (documentId: string) => void;
|
|
15
|
+
/** Called after a status write succeeds (the list refreshes). */
|
|
16
|
+
onChanged?: () => void;
|
|
17
|
+
now?: () => number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** One to-do: status, due, owner, project, the verbatim source quote(s) and mark done / reopen. */
|
|
21
|
+
export function TrackerDetailScreen({ api, id, onBack, onOpenNote, onChanged, now = Date.now }: TrackerDetailScreenProps) {
|
|
22
|
+
const theme = useTheme();
|
|
23
|
+
const controller = useMemo(() => createTrackerDetailController({ api, id, onChanged }), [api, id, onChanged]);
|
|
24
|
+
useEffect(() => { void controller.load(); }, [controller]);
|
|
25
|
+
const s = useControllerState(controller);
|
|
26
|
+
const item = s.item;
|
|
27
|
+
|
|
28
|
+
if (!item) {
|
|
29
|
+
return (
|
|
30
|
+
<View style={{ flex: 1 }}>
|
|
31
|
+
<Header title="To-do" onBack={onBack} testID="todo-header" />
|
|
32
|
+
<View style={{ padding: theme.spacing.lg }}>
|
|
33
|
+
{s.loading ? <Spinner /> : <Alert variant="destructive">{s.error ?? 'This to-do is no longer available.'}</Alert>}
|
|
34
|
+
</View>
|
|
35
|
+
</View>
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const closed = item.status === 'done' || item.status === 'dropped';
|
|
40
|
+
const due = formatDue(item.dueAt, now());
|
|
41
|
+
const meta = [
|
|
42
|
+
due ? `${isOverdueAt(item, now()) ? 'Overdue · ' : 'Due '}${due}` : null,
|
|
43
|
+
item.ownerName ? `Owner ${item.ownerName}` : null,
|
|
44
|
+
s.projectTitle ? `Project ${s.projectTitle}` : null,
|
|
45
|
+
priorityText(item.priority),
|
|
46
|
+
].filter(Boolean) as string[];
|
|
47
|
+
|
|
48
|
+
return (
|
|
49
|
+
<View style={{ flex: 1 }}>
|
|
50
|
+
<Header title="To-do" onBack={onBack} testID="todo-header" />
|
|
51
|
+
<ScrollView testID="todo-detail" contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.md }}>
|
|
52
|
+
<Text variant="heading">{item.title}</Text>
|
|
53
|
+
<View style={{ flexDirection: 'row', alignItems: 'center', gap: theme.spacing.sm }}>
|
|
54
|
+
<StatusChip status={item.status} />
|
|
55
|
+
</View>
|
|
56
|
+
{meta.map((line) => <Text key={line} variant="muted">{line}</Text>)}
|
|
57
|
+
{item.statusReason ? <Text variant="caption">{item.statusReason}</Text> : null}
|
|
58
|
+
{item.detail ? <Text>{item.detail}</Text> : null}
|
|
59
|
+
{s.error ? <Alert variant="destructive">{s.error}</Alert> : null}
|
|
60
|
+
<Button
|
|
61
|
+
testID="todo-toggle"
|
|
62
|
+
title={closed ? 'Reopen' : 'Mark done'}
|
|
63
|
+
variant={closed ? 'outline' : 'primary'}
|
|
64
|
+
disabled={s.busy}
|
|
65
|
+
onPress={() => { void controller.setStatus(closed ? 'open' : 'done'); }}
|
|
66
|
+
/>
|
|
67
|
+
{s.sources.length ? <Text variant="caption" style={{ fontWeight: '600' }}>WHERE IT CAME FROM</Text> : null}
|
|
68
|
+
{s.sources.map((src) => (
|
|
69
|
+
<Card key={`${src.documentId}-${src.quote.slice(0, 24)}`}>
|
|
70
|
+
<CardContent>
|
|
71
|
+
<Text style={{ fontWeight: '600' }}>{src.title}{src.section ? ` · ${src.section}` : ''}</Text>
|
|
72
|
+
{src.quote ? <Text variant="muted" style={{ fontStyle: 'italic' }}>{`“${src.quote}”`}</Text> : null}
|
|
73
|
+
{src.isVoiceNote && onOpenNote ? (
|
|
74
|
+
<Button testID={`todo-open-note-${src.documentId}`} title="Open note" variant="ghost" size="sm" style={{ alignSelf: 'flex-start' }} onPress={() => onOpenNote(src.documentId)} />
|
|
75
|
+
) : null}
|
|
76
|
+
</CardContent>
|
|
77
|
+
</Card>
|
|
78
|
+
))}
|
|
79
|
+
</ScrollView>
|
|
80
|
+
</View>
|
|
81
|
+
);
|
|
82
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { useEffect, useState } from 'react';
|
|
2
|
+
import { View } from 'react-native';
|
|
3
|
+
import { DataList, ListRow, StatusChip, SwipeRow, Text, useTheme, type FilterGroup } from '@startsimpli/ui-native';
|
|
4
|
+
import type { Commitment } from '../../corpus/types';
|
|
5
|
+
import { useControllerState } from '../components/useControllerState';
|
|
6
|
+
import type { TrackerController, TrackerRow } from './controller';
|
|
7
|
+
import { TRACKER_VIEWS, rowSubtitle, type TrackerView } from './format';
|
|
8
|
+
|
|
9
|
+
export interface TrackerListScreenProps {
|
|
10
|
+
controller: TrackerController;
|
|
11
|
+
onOpen: (item: Commitment) => void;
|
|
12
|
+
/** Injectable clock for the "Overdue" label. */
|
|
13
|
+
now?: () => number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* To-dos: server-driven. View (Outstanding / Overdue / Changed this week /
|
|
18
|
+
* Closed), project and search are all query parameters; swipe a row to mark it
|
|
19
|
+
* done (or reopen it from Closed); pull to refresh; the list pages on scroll.
|
|
20
|
+
*/
|
|
21
|
+
export function TrackerListScreen({ controller, onOpen, now = Date.now }: TrackerListScreenProps) {
|
|
22
|
+
const state = useControllerState(controller);
|
|
23
|
+
const theme = useTheme();
|
|
24
|
+
const [text, setText] = useState(state.filters.search);
|
|
25
|
+
useEffect(() => { void controller.start(); }, [controller]);
|
|
26
|
+
|
|
27
|
+
const titleOf = (focusId: string | null) => state.projects.find((p) => p.id === focusId)?.title;
|
|
28
|
+
const closed = state.filters.view === 'closed';
|
|
29
|
+
const filters: FilterGroup[] = [
|
|
30
|
+
{ key: 'view', label: 'Show', options: TRACKER_VIEWS, value: state.filters.view },
|
|
31
|
+
{ key: 'project', label: 'Project', display: 'select', options: state.projects.map((p) => ({ value: p.id, label: p.title })), value: state.filters.focusId },
|
|
32
|
+
];
|
|
33
|
+
const isFiltered = state.filters.focusId !== null || state.filters.search.trim() !== '';
|
|
34
|
+
|
|
35
|
+
const renderRow = ({ item: row }: { item: TrackerRow }) => (
|
|
36
|
+
<SwipeRow
|
|
37
|
+
testID={`todo-${row.item.id}`}
|
|
38
|
+
actions={closed
|
|
39
|
+
? [{ key: 'reopen', label: 'Reopen', tone: 'neutral', onPress: () => { void controller.setStatus(row.item, 'open'); } }]
|
|
40
|
+
: [{ key: 'done', label: 'Done', tone: 'success', onPress: () => { void controller.setStatus(row.item, 'done'); } }]}
|
|
41
|
+
>
|
|
42
|
+
<ListRow
|
|
43
|
+
title={row.item.title}
|
|
44
|
+
subtitle={rowSubtitle(row.item, titleOf(row.focusId), now()) || undefined}
|
|
45
|
+
trailing={<StatusChip status={row.item.status} />}
|
|
46
|
+
onPress={() => onOpen(row.item)}
|
|
47
|
+
/>
|
|
48
|
+
</SwipeRow>
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
return (
|
|
52
|
+
<DataList<TrackerRow>
|
|
53
|
+
testID="tracker-list"
|
|
54
|
+
data={state.rows}
|
|
55
|
+
keyExtractor={(r) => r.item.id}
|
|
56
|
+
renderItem={renderRow}
|
|
57
|
+
loading={state.loading}
|
|
58
|
+
onRefresh={() => { void controller.refresh(); }}
|
|
59
|
+
error={state.error}
|
|
60
|
+
onRetry={() => { void controller.refresh(); }}
|
|
61
|
+
hasMore={state.hasMore}
|
|
62
|
+
loadingMore={state.loadingMore}
|
|
63
|
+
onLoadMore={() => { void controller.loadMore(); }}
|
|
64
|
+
search={{
|
|
65
|
+
value: text, onChange: setText, onSearch: (t) => { void controller.setSearch(t); }, placeholder: 'Search to-dos',
|
|
66
|
+
}}
|
|
67
|
+
filters={filters}
|
|
68
|
+
onFilterChange={(key, value) => {
|
|
69
|
+
if (key === 'view') void controller.setView((value ?? 'open') as TrackerView);
|
|
70
|
+
else void controller.setFocus(value);
|
|
71
|
+
}}
|
|
72
|
+
onClearFilters={() => { setText(''); void controller.clearFilters(); }}
|
|
73
|
+
emptyTitle={closed ? 'Nothing closed yet' : 'Nothing outstanding'}
|
|
74
|
+
emptyDescription={closed ? 'Finished to-dos show up here.' : 'To-dos from your notes and meetings show up here.'}
|
|
75
|
+
noResultsTitle="No to-dos match"
|
|
76
|
+
ListHeaderComponent={
|
|
77
|
+
<View style={{ gap: theme.spacing.xs, paddingBottom: theme.spacing.sm }}>
|
|
78
|
+
<Text variant="heading">To-dos</Text>
|
|
79
|
+
{state.count !== null ? <Text variant="caption">{state.count} {closed ? 'closed' : 'to go'}{isFiltered ? ' (filtered)' : ''}</Text> : null}
|
|
80
|
+
{state.ignoredFilters.length ? <Text variant="caption" style={{ color: theme.colors.destructive }}>This workspace did not apply: {state.ignoredFilters.join(', ')}. The list is not filtered by it.</Text> : null}
|
|
81
|
+
</View>
|
|
82
|
+
}
|
|
83
|
+
/>
|
|
84
|
+
);
|
|
85
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { createFakeNativeCorpusApi } from '../../corpus/fake';
|
|
3
|
+
import { createTrackerController } from '../controller';
|
|
4
|
+
|
|
5
|
+
const NOW = Date.parse('2026-11-05T00:00:00Z');
|
|
6
|
+
const flush = () => new Promise((r) => setTimeout(r, 0));
|
|
7
|
+
|
|
8
|
+
async function setup(opts: Parameters<typeof createFakeNativeCorpusApi>[0] = {}, pageSize = 25) {
|
|
9
|
+
const api = createFakeNativeCorpusApi(opts);
|
|
10
|
+
const c = createTrackerController({ api, now: () => NOW, pageSize });
|
|
11
|
+
await c.start();
|
|
12
|
+
const gets = () => api.tenant.requests.filter((r) => r.method === 'GET');
|
|
13
|
+
return { api, c, gets };
|
|
14
|
+
}
|
|
15
|
+
const titles = (c: ReturnType<typeof createTrackerController>) => c.getState().rows.map((r) => r.item.title);
|
|
16
|
+
|
|
17
|
+
describe('tracker controller: every list change is a server request', () => {
|
|
18
|
+
it('Outstanding is the default view, ordered by due date on the server, undated last', async () => {
|
|
19
|
+
const { c, api } = await setup();
|
|
20
|
+
expect(titles(c).slice(0, 3)).toEqual(['Call Megan about the filing receipt', 'Finish exhibit list', 'Book the dentist']);
|
|
21
|
+
expect(titles(c)).toHaveLength(5);
|
|
22
|
+
const q = api.tenant.requests.find((r) => r.params?.type === 'commitment');
|
|
23
|
+
expect(q?.params).toMatchObject({ order: 'attr.due_at', 'attr.status__in': 'open,blocked', page_size: 25 });
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('switching view sends the due window / status to the server and swaps the rows', async () => {
|
|
27
|
+
const { c, api } = await setup();
|
|
28
|
+
await c.setView('overdue');
|
|
29
|
+
const sent = api.tenant.requests.filter((r) => r.params?.type === 'commitment').at(-1)!;
|
|
30
|
+
expect(sent.params).toMatchObject({ 'attr.due_at__lte': new Date(NOW).toISOString() });
|
|
31
|
+
expect(titles(c)).toEqual(['Call Megan about the filing receipt']);
|
|
32
|
+
await c.setView('recent');
|
|
33
|
+
expect(api.tenant.requests.filter((r) => r.params?.type === 'commitment').at(-1)!.params).toMatchObject({ 'attr.last_seen_at__gte': '2026-10-29T00:00:00.000Z' });
|
|
34
|
+
await c.setView('closed');
|
|
35
|
+
expect(titles(c)).toEqual(['Send the revised proposal']);
|
|
36
|
+
expect(api.tenant.requests.filter((r) => r.params?.type === 'commitment').at(-1)!.params).toMatchObject({ 'attr.status__in': 'done,dropped' });
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('filters by project through the edge walk, not by comparing locally', async () => {
|
|
40
|
+
const { c, api } = await setup();
|
|
41
|
+
await c.setFocus('fma');
|
|
42
|
+
expect(titles(c)).toEqual(['Move weekly report to Monday']);
|
|
43
|
+
expect(api.tenant.requests.filter((r) => r.params?.type === 'commitment').at(-1)!.params).toMatchObject({ related_to: 'fma', related_via: 'in_focus' });
|
|
44
|
+
await c.setFocus(null);
|
|
45
|
+
expect(titles(c).length).toBe(5);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('search goes to the server', async () => {
|
|
49
|
+
const { c, api } = await setup();
|
|
50
|
+
await c.setSearch('dentist');
|
|
51
|
+
expect(titles(c)).toEqual(['Book the dentist']);
|
|
52
|
+
expect(api.tenant.requests.filter((r) => r.params?.type === 'commitment').at(-1)!.params).toMatchObject({ search: 'dentist' });
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('pages with the server cursor: one request per page, never the whole list', async () => {
|
|
56
|
+
const { c, gets } = await setup({}, 2);
|
|
57
|
+
const before = gets().filter((r) => r.params?.type === 'commitment').length;
|
|
58
|
+
expect(c.getState().rows).toHaveLength(2);
|
|
59
|
+
expect(c.getState().hasMore).toBe(true);
|
|
60
|
+
await c.loadMore();
|
|
61
|
+
expect(c.getState().rows).toHaveLength(4);
|
|
62
|
+
await c.loadMore();
|
|
63
|
+
expect(c.getState().rows).toHaveLength(5);
|
|
64
|
+
expect(c.getState().hasMore).toBe(false);
|
|
65
|
+
expect(gets().filter((r) => r.params?.type === 'commitment').length - before).toBe(2);
|
|
66
|
+
expect(c.getState().count).toBe(5);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('names each row project with ONE edge request per page (sourceIn), not one per row', async () => {
|
|
70
|
+
const { c, gets } = await setup();
|
|
71
|
+
const rows = c.getState().rows;
|
|
72
|
+
expect(rows.find((r) => r.item.id === 'c1')?.focusId).toBe('f287');
|
|
73
|
+
expect(rows.find((r) => r.item.id === 'c4')?.focusId).toBeNull();
|
|
74
|
+
expect(gets().filter((r) => r.params?.rel_type === 'in_focus').length).toBe(1);
|
|
75
|
+
expect(c.getState().projects.map((p) => p.title)).toEqual(['287A', 'Marketing agents', 'Debug']);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('says so when the server ignored a filter instead of showing the list as filtered', async () => {
|
|
79
|
+
const { c } = await setup({ unsupported: ['attr.status', 'attr.status__in'] });
|
|
80
|
+
expect(c.getState().ignoredFilters).toContain('status');
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('surfaces a load failure', async () => {
|
|
84
|
+
let fail = false;
|
|
85
|
+
const { c } = await setup({ onRequest: (m) => { if (fail && m === 'GET') throw Object.assign(new Error('Gateway down'), { status: 502 }); } });
|
|
86
|
+
fail = true;
|
|
87
|
+
await c.setView('closed');
|
|
88
|
+
expect(c.getState().error).toBe('Gateway down');
|
|
89
|
+
expect(c.getState().loading).toBe(false);
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
describe('tracker controller: mark done', () => {
|
|
94
|
+
it('removes the row at once, writes through setStatus, then refreshes from the server', async () => {
|
|
95
|
+
const { c, api } = await setup();
|
|
96
|
+
const row = c.getState().rows.find((r) => r.item.id === 'c1')!;
|
|
97
|
+
const p = c.setStatus(row.item, 'done');
|
|
98
|
+
expect(titles(c)).not.toContain('Finish exhibit list'); // optimistic
|
|
99
|
+
expect(c.getState().pendingIds).toContain('c1');
|
|
100
|
+
await p;
|
|
101
|
+
const post = api.tenant.requests.find((r) => r.method === 'POST');
|
|
102
|
+
expect(post?.params).toMatchObject({ external_id: 'commit:c1', data: { status: 'done' } });
|
|
103
|
+
expect(c.getState().pendingIds).toEqual([]);
|
|
104
|
+
expect(titles(c)).not.toContain('Finish exhibit list');
|
|
105
|
+
await c.setView('closed');
|
|
106
|
+
expect(titles(c)).toContain('Finish exhibit list');
|
|
107
|
+
expect(c.getState().count).toBe(2);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('puts the row back and says why when the write fails', async () => {
|
|
111
|
+
let fail = false;
|
|
112
|
+
const { c } = await setup({ onRequest: (m) => { if (fail && m === 'POST') throw Object.assign(new Error('Server said no'), { status: 500 }); } });
|
|
113
|
+
const row = c.getState().rows.find((r) => r.item.id === 'c1')!;
|
|
114
|
+
fail = true;
|
|
115
|
+
await c.setStatus(row.item, 'done');
|
|
116
|
+
expect(titles(c)).toContain('Finish exhibit list');
|
|
117
|
+
expect(c.getState().error).toMatch(/could not mark.*done.*Server said no/i);
|
|
118
|
+
expect(c.getState().pendingIds).toEqual([]);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('reopening a closed item leaves the Closed view', async () => {
|
|
122
|
+
const { c } = await setup();
|
|
123
|
+
await c.setView('closed');
|
|
124
|
+
await c.setStatus(c.getState().rows[0].item, 'open');
|
|
125
|
+
expect(titles(c)).toEqual([]);
|
|
126
|
+
await c.setView('open');
|
|
127
|
+
expect(titles(c)).toContain('Send the revised proposal');
|
|
128
|
+
});
|
|
129
|
+
});
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { createFakeNativeCorpusApi } from '../../corpus/fake';
|
|
3
|
+
import { createTrackerDetailController } from '../detail';
|
|
4
|
+
|
|
5
|
+
async function open(id: string, opts: Parameters<typeof createFakeNativeCorpusApi>[0] = {}) {
|
|
6
|
+
const api = createFakeNativeCorpusApi(opts);
|
|
7
|
+
let changed = 0;
|
|
8
|
+
const c = createTrackerDetailController({ api, id, onChanged: () => { changed += 1; } });
|
|
9
|
+
await c.load();
|
|
10
|
+
return { api, c, changed: () => changed };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
describe('tracker detail controller', () => {
|
|
14
|
+
it('loads one to-do by id, with its project and the source it came from', async () => {
|
|
15
|
+
const { c, api } = await open('c1');
|
|
16
|
+
const s = c.getState();
|
|
17
|
+
expect(s.item?.title).toBe('Finish exhibit list');
|
|
18
|
+
expect(s.projectTitle).toBe('287A');
|
|
19
|
+
expect(s.sources).toEqual([
|
|
20
|
+
expect.objectContaining({ documentId: 'n1', quote: 'I still have to finish the exhibit list before the hearing.', section: 'Hearing prep', isVoiceNote: true }),
|
|
21
|
+
]);
|
|
22
|
+
// direct reads, never a scan of the list
|
|
23
|
+
expect(api.tenant.requests.filter((r) => r.params?.type === 'commitment')).toHaveLength(0);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('titles a non-voice source from its document and does not offer the Notes link', async () => {
|
|
27
|
+
const { c } = await open('c3');
|
|
28
|
+
const [src] = c.getState().sources;
|
|
29
|
+
expect(src).toMatchObject({ documentId: 'd2', title: 'Weekly sync with Rae', isVoiceNote: false });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('a missing source document does not break the screen', async () => {
|
|
33
|
+
const { c } = await open('c1');
|
|
34
|
+
// n1 is not a corpus document in the fake; the mention still shows with a fallback title
|
|
35
|
+
expect(c.getState().sources[0].title).toBe('Voice note');
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('reports a to-do that no longer exists', async () => {
|
|
39
|
+
const { c } = await open('nope');
|
|
40
|
+
expect(c.getState().item).toBeNull();
|
|
41
|
+
expect(c.getState().error).toMatch(/no record|not found|no longer/i);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('mark done: optimistic, written through setStatus, tells the list', async () => {
|
|
45
|
+
const { c, api, changed } = await open('c1');
|
|
46
|
+
const p = c.setStatus('done');
|
|
47
|
+
expect(c.getState().item?.status).toBe('done');
|
|
48
|
+
await p;
|
|
49
|
+
expect(api.tenant.requests.find((r) => r.method === 'POST')?.params).toMatchObject({ external_id: 'commit:c1', data: { status: 'done' } });
|
|
50
|
+
expect(changed()).toBe(1);
|
|
51
|
+
await c.setStatus('open');
|
|
52
|
+
expect(c.getState().item?.status).toBe('open');
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('rolls the status back and explains when the write fails', async () => {
|
|
56
|
+
let fail = false;
|
|
57
|
+
const { c } = await open('c1', { onRequest: (m) => { if (fail && m === 'POST') throw new Error('Server said no'); } });
|
|
58
|
+
fail = true;
|
|
59
|
+
await c.setStatus('done');
|
|
60
|
+
expect(c.getState().item?.status).toBe('open');
|
|
61
|
+
expect(c.getState().error).toMatch(/Server said no/);
|
|
62
|
+
expect(c.getState().busy).toBe(false);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { DEFAULT_TRACKER_FILTERS, formatDue, isOverdueAt, leavesView, rowSubtitle, trackerQuery } from '../format';
|
|
3
|
+
|
|
4
|
+
const NOW = Date.parse('2026-11-05T00:00:00Z');
|
|
5
|
+
|
|
6
|
+
describe('trackerQuery', () => {
|
|
7
|
+
it('maps each view to server filters', () => {
|
|
8
|
+
expect(trackerQuery(DEFAULT_TRACKER_FILTERS, NOW)).toEqual({ status: ['open', 'blocked'] });
|
|
9
|
+
expect(trackerQuery({ ...DEFAULT_TRACKER_FILTERS, view: 'overdue' }, NOW)).toEqual({ status: ['open', 'blocked'], dueBefore: '2026-11-05T00:00:00.000Z' });
|
|
10
|
+
expect(trackerQuery({ ...DEFAULT_TRACKER_FILTERS, view: 'recent' }, NOW).changedAfter).toBe('2026-10-29T00:00:00.000Z');
|
|
11
|
+
expect(trackerQuery({ ...DEFAULT_TRACKER_FILTERS, view: 'closed' }, NOW).status).toEqual(['done', 'dropped']);
|
|
12
|
+
});
|
|
13
|
+
it('adds project and trimmed search, and omits empty ones', () => {
|
|
14
|
+
expect(trackerQuery({ view: 'open', focusId: 'f1', search: ' exhibit ' }, NOW)).toMatchObject({ focus: 'f1', search: 'exhibit' });
|
|
15
|
+
expect(trackerQuery({ view: 'open', focusId: null, search: ' ' }, NOW)).not.toHaveProperty('search');
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
describe('row text', () => {
|
|
20
|
+
it('leavesView: done leaves Outstanding, reopen leaves Closed, blocked stays', () => {
|
|
21
|
+
expect(leavesView('open', 'done')).toBe(true);
|
|
22
|
+
expect(leavesView('open', 'blocked')).toBe(false);
|
|
23
|
+
expect(leavesView('closed', 'open')).toBe(true);
|
|
24
|
+
expect(leavesView('closed', 'dropped')).toBe(false);
|
|
25
|
+
});
|
|
26
|
+
it('formats due dates, with the year only when it differs', () => {
|
|
27
|
+
expect(formatDue('2026-11-05T17:00:00Z', NOW)).toBe('Nov 5');
|
|
28
|
+
expect(formatDue('2027-01-02T00:00:00Z', NOW)).toBe('Jan 2, 2027');
|
|
29
|
+
expect(formatDue(null, NOW)).toBeNull();
|
|
30
|
+
expect(formatDue('nonsense', NOW)).toBeNull();
|
|
31
|
+
});
|
|
32
|
+
it('overdue only while still owed', () => {
|
|
33
|
+
expect(isOverdueAt({ dueAt: '2026-11-01T00:00:00Z', status: 'open' }, NOW)).toBe(true);
|
|
34
|
+
expect(isOverdueAt({ dueAt: '2026-11-01T00:00:00Z', status: 'done' }, NOW)).toBe(false);
|
|
35
|
+
expect(isOverdueAt({ dueAt: null, status: 'open' }, NOW)).toBe(false);
|
|
36
|
+
});
|
|
37
|
+
it('subtitle joins due, owner and project', () => {
|
|
38
|
+
const item = { dueAt: '2026-11-01T00:00:00Z', status: 'open', ownerName: 'Quinn' } as never;
|
|
39
|
+
expect(rowSubtitle(item, '287A', NOW)).toBe('Overdue · Nov 1 · Quinn · 287A');
|
|
40
|
+
expect(rowSubtitle({ status: 'open' } as never, undefined, NOW)).toBe('');
|
|
41
|
+
});
|
|
42
|
+
});
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The to-do list as a framework-free controller (same pattern as
|
|
3
|
+
* `VoiceNotesController` and `createPagedList`). Every change of view, project or
|
|
4
|
+
* search is ONE server request for ONE page; nothing loads a list and narrows,
|
|
5
|
+
* sorts or pages it on the phone. The only local work is the optimistic hiding
|
|
6
|
+
* of a row a person just changed, which the server's next page confirms.
|
|
7
|
+
*/
|
|
8
|
+
import type { Commitment, CommitmentStatus } from '../../corpus/types';
|
|
9
|
+
import type { NativeCorpusApi } from '../corpus/api';
|
|
10
|
+
import { unappliedFilters } from '../corpus/api';
|
|
11
|
+
import { createPagedList, type PagedList, type PagedListState } from '../corpus/paged';
|
|
12
|
+
import { DEFAULT_TRACKER_FILTERS, leavesView, statusText, trackerQuery, type TrackerFilters, type TrackerView } from './format';
|
|
13
|
+
|
|
14
|
+
export interface TrackerRow {
|
|
15
|
+
item: Commitment;
|
|
16
|
+
/** The project (focus) the to-do is filed under, or null when unfiled. */
|
|
17
|
+
focusId: string | null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface TrackerProject { id: string; title: string }
|
|
21
|
+
|
|
22
|
+
export interface TrackerState {
|
|
23
|
+
rows: TrackerRow[];
|
|
24
|
+
/** Server COUNT for the current filters, minus rows hidden while their write is in flight. */
|
|
25
|
+
count: number | null;
|
|
26
|
+
loading: boolean;
|
|
27
|
+
loadingMore: boolean;
|
|
28
|
+
hasMore: boolean;
|
|
29
|
+
/** Filters the server did not confirm: the list is NOT filtered by these. */
|
|
30
|
+
ignoredFilters: string[];
|
|
31
|
+
error: string | null;
|
|
32
|
+
filters: TrackerFilters;
|
|
33
|
+
projects: TrackerProject[];
|
|
34
|
+
/** To-dos whose status write is in flight. */
|
|
35
|
+
pendingIds: string[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface TrackerControllerOptions {
|
|
39
|
+
api: Pick<NativeCorpusApi, 'corpus' | 'relationships' | 'commitments'>;
|
|
40
|
+
now?: () => number;
|
|
41
|
+
pageSize?: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface TrackerController {
|
|
45
|
+
getState(): TrackerState;
|
|
46
|
+
subscribe(listener: () => void): () => void;
|
|
47
|
+
/** First load: projects (for the filter) and page 1. */
|
|
48
|
+
start(): Promise<void>;
|
|
49
|
+
refresh(): Promise<void>;
|
|
50
|
+
loadMore(): Promise<void>;
|
|
51
|
+
setView(view: TrackerView): Promise<void>;
|
|
52
|
+
setFocus(focusId: string | null): Promise<void>;
|
|
53
|
+
setSearch(search: string): Promise<void>;
|
|
54
|
+
clearFilters(): Promise<void>;
|
|
55
|
+
/** Mark done / reopen / block / drop. The row leaves the view at once; it comes back with the reason if the write fails. */
|
|
56
|
+
setStatus(item: Commitment, status: CommitmentStatus): Promise<void>;
|
|
57
|
+
dismissError(): void;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const IN_FOCUS = 'in_focus';
|
|
61
|
+
const msg = (e: unknown) => (e instanceof Error && e.message ? e.message : 'That did not work.');
|
|
62
|
+
|
|
63
|
+
export function createTrackerController({ api, now = Date.now, pageSize = 25 }: TrackerControllerOptions): TrackerController {
|
|
64
|
+
let filters: TrackerFilters = DEFAULT_TRACKER_FILTERS;
|
|
65
|
+
let projects: TrackerProject[] = [];
|
|
66
|
+
let hidden = new Set<string>();
|
|
67
|
+
let error: string | null = null;
|
|
68
|
+
const listeners = new Set<() => void>();
|
|
69
|
+
|
|
70
|
+
const list: PagedList<TrackerRow, TrackerFilters> = createPagedList<TrackerRow, TrackerFilters>({
|
|
71
|
+
query: filters,
|
|
72
|
+
async fetchPage(page, f) {
|
|
73
|
+
const query = trackerQuery(f, now());
|
|
74
|
+
const res = await api.corpus.listCommitments({ ...query, page, pageSize });
|
|
75
|
+
const edges = new Map<string, string>();
|
|
76
|
+
if (res.results.length) {
|
|
77
|
+
// ONE request for the page's project edges, not one per row. A failure here costs the project names, not the list.
|
|
78
|
+
const found = await api.relationships
|
|
79
|
+
.list({ relType: IN_FOCUS, sourceIn: res.results.map((c) => c.id), pageSize: 200 })
|
|
80
|
+
.catch(() => null);
|
|
81
|
+
for (const e of found?.items ?? []) edges.set(String(e.source), String(e.target));
|
|
82
|
+
}
|
|
83
|
+
return {
|
|
84
|
+
items: res.results.map((item) => ({ item, focusId: edges.get(item.id) ?? null })),
|
|
85
|
+
count: res.count,
|
|
86
|
+
nextPage: res.next ? page + 1 : null,
|
|
87
|
+
ignoredFilters: unappliedFilters(query, res.appliedFilters),
|
|
88
|
+
};
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
let cache: { key: unknown[]; value: TrackerState } | null = null;
|
|
93
|
+
const build = (): TrackerState => {
|
|
94
|
+
const s: PagedListState<TrackerRow> = list.getState();
|
|
95
|
+
const rows = s.items.filter((r) => !hidden.has(r.item.id));
|
|
96
|
+
return {
|
|
97
|
+
rows,
|
|
98
|
+
count: s.count === null ? null : Math.max(0, s.count - (s.items.length - rows.length)),
|
|
99
|
+
loading: s.loading, loadingMore: s.loadingMore, hasMore: s.hasMore,
|
|
100
|
+
ignoredFilters: s.ignoredFilters,
|
|
101
|
+
error: error ?? s.error,
|
|
102
|
+
filters, projects, pendingIds: [...hidden],
|
|
103
|
+
};
|
|
104
|
+
};
|
|
105
|
+
// Stable identity between changes, as useSyncExternalStore requires.
|
|
106
|
+
const getState = () => {
|
|
107
|
+
const k = [list.getState(), filters, projects, hidden, error];
|
|
108
|
+
if (!cache || k.some((v, i) => v !== cache!.key[i])) cache = { key: k, value: build() };
|
|
109
|
+
return cache.value;
|
|
110
|
+
};
|
|
111
|
+
const emit = () => listeners.forEach((l) => l());
|
|
112
|
+
list.subscribe(emit);
|
|
113
|
+
|
|
114
|
+
async function loadProjects() {
|
|
115
|
+
try {
|
|
116
|
+
const page = await api.corpus.listFocuses({ orderBy: 'sortOrder', pageSize: 200 });
|
|
117
|
+
projects = page.results.map((f) => ({ id: f.id, title: f.title }));
|
|
118
|
+
} catch { projects = []; }
|
|
119
|
+
emit();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const requery = (next: TrackerFilters) => { filters = next; error = null; return list.setQuery(next); };
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
getState,
|
|
126
|
+
subscribe(l) { listeners.add(l); return () => { listeners.delete(l); }; },
|
|
127
|
+
async start() { await Promise.all([loadProjects(), list.refresh()]); },
|
|
128
|
+
refresh: () => { error = null; return list.refresh(); },
|
|
129
|
+
loadMore: () => list.loadMore(),
|
|
130
|
+
setView: (view) => requery({ ...filters, view }),
|
|
131
|
+
setFocus: (focusId) => requery({ ...filters, focusId }),
|
|
132
|
+
setSearch: (search) => (search === filters.search ? Promise.resolve() : requery({ ...filters, search })),
|
|
133
|
+
clearFilters: () => requery({ ...DEFAULT_TRACKER_FILTERS, view: filters.view }),
|
|
134
|
+
async setStatus(item, status) {
|
|
135
|
+
if (hidden.has(item.id)) return;
|
|
136
|
+
if (leavesView(filters.view, status)) hidden = new Set(hidden).add(item.id);
|
|
137
|
+
error = null;
|
|
138
|
+
emit();
|
|
139
|
+
try {
|
|
140
|
+
await api.commitments.setStatus(item, status);
|
|
141
|
+
// The server's page is the truth; this also pulls the next row up into the gap.
|
|
142
|
+
await list.refresh();
|
|
143
|
+
} catch (e) {
|
|
144
|
+
error = `Could not mark "${item.title}" ${statusText(status).toLowerCase()}. ${msg(e)}`;
|
|
145
|
+
} finally {
|
|
146
|
+
hidden = new Set([...hidden].filter((id) => id !== item.id));
|
|
147
|
+
emit();
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
dismissError() { error = null; emit(); },
|
|
151
|
+
};
|
|
152
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One to-do, read directly (one entity read, its project edge, and the source
|
|
3
|
+
* documents its mentions point at) - never by scanning the list. Mark done /
|
|
4
|
+
* reopen is optimistic and rolls back with the server's reason.
|
|
5
|
+
*/
|
|
6
|
+
import type { Commitment, CommitmentStatus } from '../../corpus/types';
|
|
7
|
+
import { toCommitment } from '../../corpus/entities';
|
|
8
|
+
import type { NativeCorpusApi } from '../corpus/api';
|
|
9
|
+
import { statusText } from './format';
|
|
10
|
+
|
|
11
|
+
export interface TrackerSource {
|
|
12
|
+
documentId: string;
|
|
13
|
+
/** The document's title; the to-do's source label when the document cannot be read. */
|
|
14
|
+
title: string;
|
|
15
|
+
/** Verbatim span from that source. */
|
|
16
|
+
quote: string;
|
|
17
|
+
occurredAt: string | null;
|
|
18
|
+
section?: string;
|
|
19
|
+
/** True when the Notes tab can open it. */
|
|
20
|
+
isVoiceNote: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface TrackerDetailState {
|
|
24
|
+
loading: boolean;
|
|
25
|
+
item: Commitment | null;
|
|
26
|
+
projectTitle: string | null;
|
|
27
|
+
sources: TrackerSource[];
|
|
28
|
+
busy: boolean;
|
|
29
|
+
error: string | null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface TrackerDetailController {
|
|
33
|
+
getState(): TrackerDetailState;
|
|
34
|
+
subscribe(listener: () => void): () => void;
|
|
35
|
+
load(): Promise<void>;
|
|
36
|
+
setStatus(status: CommitmentStatus): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface TrackerDetailOptions {
|
|
40
|
+
api: Pick<NativeCorpusApi, 'entities' | 'corpus' | 'relationships' | 'commitments' | 'scope'>;
|
|
41
|
+
id: string;
|
|
42
|
+
/** Called after a status write succeeds, so the list can refresh. */
|
|
43
|
+
onChanged?: () => void;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const msg = (e: unknown) => (e instanceof Error && e.message ? e.message : 'That did not work.');
|
|
47
|
+
|
|
48
|
+
export function createTrackerDetailController({ api, id, onChanged }: TrackerDetailOptions): TrackerDetailController {
|
|
49
|
+
let state: TrackerDetailState = { loading: true, item: null, projectTitle: null, sources: [], busy: false, error: null };
|
|
50
|
+
const listeners = new Set<() => void>();
|
|
51
|
+
const set = (patch: Partial<TrackerDetailState>) => { state = { ...state, ...patch }; listeners.forEach((l) => l()); };
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
getState: () => state,
|
|
55
|
+
subscribe(l) { listeners.add(l); return () => { listeners.delete(l); }; },
|
|
56
|
+
async load() {
|
|
57
|
+
set({ loading: true, error: null });
|
|
58
|
+
try {
|
|
59
|
+
const item = toCommitment(await api.entities.get(id), api.scope);
|
|
60
|
+
const edge = await api.relationships.list({ relType: 'in_focus', source: id, pageSize: 1 }).catch(() => null);
|
|
61
|
+
const focusId = edge?.items[0]?.target;
|
|
62
|
+
const [project, sources] = await Promise.all([
|
|
63
|
+
focusId ? api.entities.get(String(focusId)).then((f) => f.name || null).catch(() => null) : Promise.resolve(null),
|
|
64
|
+
Promise.all(item.mentions.map(async (m): Promise<TrackerSource> => {
|
|
65
|
+
const doc = await api.corpus.getDocument?.(m.documentId).catch(() => null);
|
|
66
|
+
return {
|
|
67
|
+
documentId: m.documentId,
|
|
68
|
+
title: doc?.title || item.sourceLabel || 'Source',
|
|
69
|
+
quote: m.quote,
|
|
70
|
+
occurredAt: m.occurredAt ?? doc?.occurredAt ?? null,
|
|
71
|
+
...(m.section ? { section: m.section } : {}),
|
|
72
|
+
isVoiceNote: (doc?.source ?? item.source) === 'voice',
|
|
73
|
+
};
|
|
74
|
+
})),
|
|
75
|
+
]);
|
|
76
|
+
set({ loading: false, item, projectTitle: project, sources });
|
|
77
|
+
} catch (e) {
|
|
78
|
+
set({ loading: false, item: null, error: (e as { status?: number })?.status === 404 ? 'This to-do is no longer available.' : msg(e) });
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
async setStatus(status) {
|
|
82
|
+
const before = state.item;
|
|
83
|
+
if (!before || state.busy) return;
|
|
84
|
+
set({ item: { ...before, status }, busy: true, error: null });
|
|
85
|
+
try {
|
|
86
|
+
const saved = await api.commitments.setStatus(before, status);
|
|
87
|
+
// Keep what we loaded (mentions, source); take the server's status and reason.
|
|
88
|
+
set({ item: { ...before, status: saved.status, statusReason: saved.statusReason }, busy: false });
|
|
89
|
+
onChanged?.();
|
|
90
|
+
} catch (e) {
|
|
91
|
+
set({ item: before, busy: false, error: `Could not mark this ${statusText(status).toLowerCase()}. ${msg(e)}` });
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { Commitment, CommitmentQuery, CommitmentStatus } from '../../corpus/types';
|
|
2
|
+
|
|
3
|
+
/** The four views the web Tracker has: Outstanding, Overdue, Changed this week, Closed. */
|
|
4
|
+
export type TrackerView = 'open' | 'overdue' | 'recent' | 'closed';
|
|
5
|
+
|
|
6
|
+
export const TRACKER_VIEWS: Array<{ value: TrackerView; label: string }> = [
|
|
7
|
+
{ value: 'open', label: 'Outstanding' },
|
|
8
|
+
{ value: 'overdue', label: 'Overdue' },
|
|
9
|
+
{ value: 'recent', label: 'Changed this week' },
|
|
10
|
+
{ value: 'closed', label: 'Closed' },
|
|
11
|
+
];
|
|
12
|
+
|
|
13
|
+
export interface TrackerFilters {
|
|
14
|
+
view: TrackerView;
|
|
15
|
+
/** A focus (project) id, or null for all projects. */
|
|
16
|
+
focusId: string | null;
|
|
17
|
+
search: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export const DEFAULT_TRACKER_FILTERS: TrackerFilters = { view: 'open', focusId: null, search: '' };
|
|
21
|
+
|
|
22
|
+
export const WEEK_MS = 7 * 24 * 3600 * 1000;
|
|
23
|
+
|
|
24
|
+
const OPEN: CommitmentStatus[] = ['open', 'blocked'];
|
|
25
|
+
const CLOSED: CommitmentStatus[] = ['done', 'dropped'];
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* What the screen asks the SERVER for. Every field here goes out as a query
|
|
29
|
+
* parameter (status, due window, changed window, project, search); the list is
|
|
30
|
+
* never narrowed on the phone.
|
|
31
|
+
*/
|
|
32
|
+
export function trackerQuery(filters: TrackerFilters, now: number): Omit<CommitmentQuery, 'page' | 'pageSize'> {
|
|
33
|
+
const search = filters.search.trim();
|
|
34
|
+
return {
|
|
35
|
+
status: filters.view === 'closed' ? CLOSED : OPEN,
|
|
36
|
+
...(filters.view === 'overdue' ? { dueBefore: new Date(now).toISOString() } : {}),
|
|
37
|
+
...(filters.view === 'recent' ? { changedAfter: new Date(now - WEEK_MS).toISOString() } : {}),
|
|
38
|
+
...(filters.focusId ? { focus: filters.focusId } : {}),
|
|
39
|
+
...(search ? { search } : {}),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Does changing an item to `status` take it out of the view it is shown in? */
|
|
44
|
+
export function leavesView(view: TrackerView, status: CommitmentStatus): boolean {
|
|
45
|
+
return view === 'closed' ? !CLOSED.includes(status) : !OPEN.includes(status);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
49
|
+
|
|
50
|
+
/** "Nov 5", with the year when it is not the current one. Never throws on a bad stamp. */
|
|
51
|
+
export function formatDue(iso: string | null | undefined, now: number): string | null {
|
|
52
|
+
if (!iso) return null;
|
|
53
|
+
const d = new Date(iso);
|
|
54
|
+
if (Number.isNaN(d.getTime())) return null;
|
|
55
|
+
const year = d.getUTCFullYear() === new Date(now).getUTCFullYear() ? '' : `, ${d.getUTCFullYear()}`;
|
|
56
|
+
return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}${year}`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function isOverdueAt(item: Pick<Commitment, 'dueAt' | 'status'>, now: number): boolean {
|
|
60
|
+
if (!item.dueAt || item.status === 'done' || item.status === 'dropped') return false;
|
|
61
|
+
return Date.parse(item.dueAt) < now;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const PRIORITY = ['Critical', 'High', 'Medium', 'Low', 'Backlog'];
|
|
65
|
+
export const priorityText = (p?: number): string | null => (p === undefined || p === null ? null : PRIORITY[p] ?? null);
|
|
66
|
+
|
|
67
|
+
export function statusText(status: CommitmentStatus): string {
|
|
68
|
+
return { open: 'Open', blocked: 'Blocked', done: 'Done', dropped: 'Dropped' }[status] ?? status;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** One line under a to-do's title: due date, owner, project. */
|
|
72
|
+
export function rowSubtitle(item: Commitment, projectTitle: string | undefined, now: number): string {
|
|
73
|
+
const due = formatDue(item.dueAt, now);
|
|
74
|
+
return [
|
|
75
|
+
due ? `${isOverdueAt(item, now) ? 'Overdue · ' : 'Due '}${due}` : null,
|
|
76
|
+
item.ownerName || null,
|
|
77
|
+
projectTitle || null,
|
|
78
|
+
].filter(Boolean).join(' · ');
|
|
79
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { FoundryTab } from '../components/FoundryTabsShell';
|
|
2
|
+
import type { NativeCorpusApi } from '../corpus/api';
|
|
3
|
+
import { createTrackerController, type TrackerController } from './controller';
|
|
4
|
+
import { TrackerDetailScreen } from './TrackerDetailScreen';
|
|
5
|
+
import { TrackerListScreen } from './TrackerListScreen';
|
|
6
|
+
|
|
7
|
+
export interface TrackerTabOptions {
|
|
8
|
+
api: Pick<NativeCorpusApi, 'entities' | 'corpus' | 'relationships' | 'commitments' | 'scope'>;
|
|
9
|
+
key?: string;
|
|
10
|
+
label?: string;
|
|
11
|
+
/** The Notes tab's key; a to-do from a voice note offers "Open note" into it. Omit for no link. */
|
|
12
|
+
notesKey?: string;
|
|
13
|
+
controller?: TrackerController;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The to-do tab as one `FoundryTabsShell` entry: list -> detail (with the source note link). */
|
|
17
|
+
export function trackerTab({ api, key = 'tracker', label = 'To-dos', notesKey = 'notes', controller = createTrackerController({ api }) }: TrackerTabOptions): FoundryTab {
|
|
18
|
+
return {
|
|
19
|
+
key, label, resetOnLeave: true,
|
|
20
|
+
render: ({ route, push, back, openTab }) => route
|
|
21
|
+
? <TrackerDetailScreen api={api} id={route.id} onBack={back} onChanged={() => { void controller.refresh(); }} onOpenNote={notesKey ? (docId) => openTab(notesKey, docId) : undefined} />
|
|
22
|
+
: <TrackerListScreen controller={controller} onOpen={(c) => push(c.id)} />,
|
|
23
|
+
};
|
|
24
|
+
}
|