@latticecms/admin 0.0.0 → 0.1.1

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.
Files changed (134) hide show
  1. package/README.md +166 -2
  2. package/dist/admin.css +2 -0
  3. package/dist/admin.d.ts +18 -0
  4. package/dist/admin.d.ts.map +1 -0
  5. package/dist/admin.js +92 -0
  6. package/dist/admin.js.map +1 -0
  7. package/dist/catalog.d.ts +45 -0
  8. package/dist/catalog.d.ts.map +1 -0
  9. package/dist/catalog.js +147 -0
  10. package/dist/catalog.js.map +1 -0
  11. package/dist/collections.d.ts +54 -0
  12. package/dist/collections.d.ts.map +1 -0
  13. package/dist/collections.js +103 -0
  14. package/dist/collections.js.map +1 -0
  15. package/dist/confirm.d.ts +16 -0
  16. package/dist/confirm.d.ts.map +1 -0
  17. package/dist/confirm.js +10 -0
  18. package/dist/confirm.js.map +1 -0
  19. package/dist/data.d.ts +28 -0
  20. package/dist/data.d.ts.map +1 -0
  21. package/dist/data.js +55 -0
  22. package/dist/data.js.map +1 -0
  23. package/dist/delete-action.d.ts +10 -0
  24. package/dist/delete-action.d.ts.map +1 -0
  25. package/dist/delete-action.js +44 -0
  26. package/dist/delete-action.js.map +1 -0
  27. package/dist/detail-page.d.ts +12 -0
  28. package/dist/detail-page.d.ts.map +1 -0
  29. package/dist/detail-page.js +65 -0
  30. package/dist/detail-page.js.map +1 -0
  31. package/dist/document-table.d.ts +17 -0
  32. package/dist/document-table.d.ts.map +1 -0
  33. package/dist/document-table.js +41 -0
  34. package/dist/document-table.js.map +1 -0
  35. package/dist/filters.d.ts +18 -0
  36. package/dist/filters.d.ts.map +1 -0
  37. package/dist/filters.js +149 -0
  38. package/dist/filters.js.map +1 -0
  39. package/dist/form.d.ts +80 -0
  40. package/dist/form.d.ts.map +1 -0
  41. package/dist/form.js +318 -0
  42. package/dist/form.js.map +1 -0
  43. package/dist/index-page.d.ts +3 -0
  44. package/dist/index-page.d.ts.map +1 -0
  45. package/dist/index-page.js +11 -0
  46. package/dist/index-page.js.map +1 -0
  47. package/dist/index.d.ts +2 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +2 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/labels.d.ts +13 -0
  52. package/dist/labels.d.ts.map +1 -0
  53. package/dist/labels.js +33 -0
  54. package/dist/labels.js.map +1 -0
  55. package/dist/list-page.d.ts +25 -0
  56. package/dist/list-page.d.ts.map +1 -0
  57. package/dist/list-page.js +82 -0
  58. package/dist/list-page.js.map +1 -0
  59. package/dist/list-state.d.ts +17 -0
  60. package/dist/list-state.d.ts.map +1 -0
  61. package/dist/list-state.js +39 -0
  62. package/dist/list-state.js.map +1 -0
  63. package/dist/method-action.d.ts +16 -0
  64. package/dist/method-action.d.ts.map +1 -0
  65. package/dist/method-action.js +78 -0
  66. package/dist/method-action.js.map +1 -0
  67. package/dist/model.d.ts +11 -0
  68. package/dist/model.d.ts.map +1 -0
  69. package/dist/model.js +16 -0
  70. package/dist/model.js.map +1 -0
  71. package/dist/ref-picker.d.ts +24 -0
  72. package/dist/ref-picker.d.ts.map +1 -0
  73. package/dist/ref-picker.js +77 -0
  74. package/dist/ref-picker.js.map +1 -0
  75. package/dist/refusal-alert.d.ts +12 -0
  76. package/dist/refusal-alert.d.ts.map +1 -0
  77. package/dist/refusal-alert.js +87 -0
  78. package/dist/refusal-alert.js.map +1 -0
  79. package/dist/refusal.d.ts +20 -0
  80. package/dist/refusal.d.ts.map +1 -0
  81. package/dist/refusal.js +40 -0
  82. package/dist/refusal.js.map +1 -0
  83. package/dist/relation-tab.d.ts +14 -0
  84. package/dist/relation-tab.d.ts.map +1 -0
  85. package/dist/relation-tab.js +205 -0
  86. package/dist/relation-tab.js.map +1 -0
  87. package/dist/router.d.ts +50 -0
  88. package/dist/router.d.ts.map +1 -0
  89. package/dist/router.js +121 -0
  90. package/dist/router.js.map +1 -0
  91. package/dist/schema.d.ts +39 -0
  92. package/dist/schema.d.ts.map +1 -0
  93. package/dist/schema.js +113 -0
  94. package/dist/schema.js.map +1 -0
  95. package/dist/states.d.ts +18 -0
  96. package/dist/states.d.ts.map +1 -0
  97. package/dist/states.js +21 -0
  98. package/dist/states.js.map +1 -0
  99. package/dist/value.d.ts +33 -0
  100. package/dist/value.d.ts.map +1 -0
  101. package/dist/value.js +96 -0
  102. package/dist/value.js.map +1 -0
  103. package/dist/write-pages.d.ts +15 -0
  104. package/dist/write-pages.d.ts.map +1 -0
  105. package/dist/write-pages.js +70 -0
  106. package/dist/write-pages.js.map +1 -0
  107. package/package.json +77 -2
  108. package/src/admin.css +14 -0
  109. package/src/admin.tsx +171 -0
  110. package/src/catalog.ts +192 -0
  111. package/src/collections.ts +147 -0
  112. package/src/confirm.tsx +57 -0
  113. package/src/data.tsx +94 -0
  114. package/src/delete-action.tsx +65 -0
  115. package/src/detail-page.tsx +189 -0
  116. package/src/document-table.tsx +129 -0
  117. package/src/filters.tsx +348 -0
  118. package/src/form.tsx +605 -0
  119. package/src/index-page.tsx +26 -0
  120. package/src/index.ts +1 -0
  121. package/src/labels.ts +41 -0
  122. package/src/list-page.tsx +191 -0
  123. package/src/list-state.ts +53 -0
  124. package/src/method-action.tsx +162 -0
  125. package/src/model.tsx +29 -0
  126. package/src/ref-picker.tsx +227 -0
  127. package/src/refusal-alert.tsx +146 -0
  128. package/src/refusal.ts +67 -0
  129. package/src/relation-tab.tsx +440 -0
  130. package/src/router.tsx +186 -0
  131. package/src/schema.ts +151 -0
  132. package/src/states.tsx +67 -0
  133. package/src/value.tsx +171 -0
  134. package/src/write-pages.tsx +146 -0
package/src/admin.tsx ADDED
@@ -0,0 +1,171 @@
1
+ import { type ReactNode, useMemo } from 'react';
2
+ import useSWR, { SWRConfig } from 'swr';
3
+ import { readCatalog } from './catalog.js';
4
+ import { collectionsOf } from './collections.js';
5
+ import { LinkProvider } from './data.js';
6
+ import { DetailPage } from './detail-page.js';
7
+ import { IndexPage } from './index-page.js';
8
+ import { ListPage } from './list-page.js';
9
+ import { CollectionsProvider, useCollection } from './model.js';
10
+ import { refusalOf } from './refusal.js';
11
+ import { Link, RouterProvider, useRouter } from './router.js';
12
+ import { ErrorAlert, Loading, NotFound } from './states.js';
13
+ import { CreatePage, EditPage } from './write-pages.js';
14
+
15
+ /** The catalog at `url`, read with the app's fetch, or a throw saying why not. */
16
+ async function loadCatalog(fetch: typeof globalThis.fetch, url: string) {
17
+ const response = await fetch(url);
18
+ if (!response.ok) {
19
+ throw new Error(`The catalog at ${url} answered ${response.status}.`);
20
+ }
21
+ const read = readCatalog(await response.json());
22
+ if (!read.ok) {
23
+ throw new Error(`The catalog at ${url} cannot be read. ${read.reason}`);
24
+ }
25
+ return read.catalog;
26
+ }
27
+
28
+ /** The page the route names. */
29
+ function Page() {
30
+ const { route } = useRouter();
31
+ const collection = useCollection(
32
+ route.page === 'index' || route.page === 'not-found'
33
+ ? undefined
34
+ : route.collection,
35
+ );
36
+ if (route.page === 'index') return <IndexPage />;
37
+ if (route.page === 'not-found') return <NotFound what="No page here." />;
38
+ if (collection === undefined) {
39
+ return <NotFound what={`No collection "${route.collection}".`} />;
40
+ }
41
+ if (route.page === 'list') {
42
+ return (
43
+ <ListPage
44
+ key={collection.slug}
45
+ collection={collection}
46
+ query={route.query}
47
+ />
48
+ );
49
+ }
50
+ if (route.page === 'create') {
51
+ return <CreatePage key={collection.slug} collection={collection} />;
52
+ }
53
+ if (route.page === 'edit') {
54
+ return (
55
+ <EditPage
56
+ key={`${collection.slug}/${route.id}`}
57
+ collection={collection}
58
+ id={route.id}
59
+ />
60
+ );
61
+ }
62
+ return (
63
+ <DetailPage
64
+ key={`${collection.slug}/${route.id}`}
65
+ collection={collection}
66
+ id={route.id}
67
+ tab={route.tab}
68
+ query={route.query}
69
+ />
70
+ );
71
+ }
72
+
73
+ /** The pages, once the catalog has loaded. */
74
+ function Catalog({
75
+ fetch,
76
+ catalogUrl,
77
+ }: {
78
+ readonly fetch: typeof globalThis.fetch;
79
+ readonly catalogUrl: string;
80
+ }) {
81
+ // The catalog changes only with a deploy, so it is read once per mount.
82
+ const { data, error } = useSWR(
83
+ ['lattice-admin:catalog', catalogUrl],
84
+ ([, url]) => loadCatalog(fetch, url),
85
+ {
86
+ revalidateOnFocus: false,
87
+ revalidateIfStale: false,
88
+ revalidateOnReconnect: false,
89
+ },
90
+ );
91
+ // Once per catalog, not per render: pages keep the same field objects.
92
+ const collections = useMemo(
93
+ () => (data === undefined ? [] : collectionsOf(data)),
94
+ [data],
95
+ );
96
+ if (error !== undefined) {
97
+ return (
98
+ <ErrorAlert
99
+ title="The admin cannot start"
100
+ message={refusalOf(error).message}
101
+ />
102
+ );
103
+ }
104
+ if (data === undefined) return <Loading />;
105
+ return (
106
+ <CollectionsProvider collections={collections}>
107
+ <LinkProvider prefix={data.prefix} fetch={fetch}>
108
+ <Page />
109
+ </LinkProvider>
110
+ </CollectionsProvider>
111
+ );
112
+ }
113
+
114
+ function TopBar({ header }: { readonly header: ReactNode }) {
115
+ const { href } = useRouter();
116
+ return (
117
+ <header className="flex items-center justify-between border-b px-6 py-3">
118
+ <Link className="font-semibold" href={href()}>
119
+ Admin
120
+ </Link>
121
+ <div>{header}</div>
122
+ </header>
123
+ );
124
+ }
125
+
126
+ /**
127
+ * Each mount has its own cache. Data refetches when the window regains
128
+ * focus; a refusal is not retried, since it would answer the same again.
129
+ * A list keeps its rows on screen while the next page or sort loads.
130
+ */
131
+ const swrConfig = {
132
+ provider: () => new Map(),
133
+ revalidateOnFocus: true,
134
+ shouldRetryOnError: false,
135
+ keepPreviousData: true,
136
+ };
137
+
138
+ /**
139
+ * An admin for a Lattice app, rendered from the catalog the app serves.
140
+ * The app supplies `fetch`, which adds its session and organization to each
141
+ * request, and mounts it on a catch-all route under `basePath`. Key it by
142
+ * organization, so a switch remounts it with an empty cache.
143
+ */
144
+ export function Admin({
145
+ fetch,
146
+ catalogUrl,
147
+ basePath,
148
+ header,
149
+ }: {
150
+ /** Calls the app's server as the signed-in user: the catalog and every procedure. */
151
+ readonly fetch: typeof globalThis.fetch;
152
+ /** Where the app serves `catalog(contract)` as JSON. */
153
+ readonly catalogUrl: string;
154
+ /** The path the admin is mounted under, such as `/admin`. */
155
+ readonly basePath: string;
156
+ /** The app's part of the top bar, such as an organization switcher. */
157
+ readonly header?: ReactNode;
158
+ }) {
159
+ return (
160
+ <SWRConfig value={swrConfig}>
161
+ <RouterProvider basePath={basePath}>
162
+ <div className="min-h-screen bg-background text-foreground">
163
+ <TopBar header={header} />
164
+ <main className="mx-auto max-w-6xl p-6">
165
+ <Catalog fetch={fetch} catalogUrl={catalogUrl} />
166
+ </main>
167
+ </div>
168
+ </RouterProvider>
169
+ </SWRConfig>
170
+ );
171
+ }
package/src/catalog.ts ADDED
@@ -0,0 +1,192 @@
1
+ import type { LatticeMeta } from '@latticecms/core';
2
+ import type { JsonSchema } from '@ts-pf/docs';
3
+
4
+ /** What a procedure does to data, from its `mcp` meta. */
5
+ export type Effect = 'read' | 'write' | 'destructive';
6
+
7
+ const effects: readonly Effect[] = ['read', 'write', 'destructive'];
8
+
9
+ function effectOf(mcp: unknown): Effect | undefined {
10
+ if (!isRecord(mcp)) return undefined;
11
+ return effects.find((effect) => effect === mcp.effect);
12
+ }
13
+
14
+ /** A procedure's docs, as far as the admin reads them. */
15
+ export type Docs = {
16
+ readonly summary: string | undefined;
17
+ readonly description: string | undefined;
18
+ };
19
+
20
+ /** A Lattice procedure, as the admin reads it from the served catalog. */
21
+ export type Procedure = {
22
+ readonly path: readonly string[];
23
+ readonly lattice: LatticeMeta;
24
+ readonly docs: Docs | undefined;
25
+ /** Its MCP effect: whether it reads, writes, or destroys. */
26
+ readonly effect: Effect | undefined;
27
+ readonly input: JsonSchema | undefined;
28
+ readonly output: JsonSchema | undefined;
29
+ /** The fields `populate` may name, when the procedure populates. */
30
+ readonly expand: readonly string[];
31
+ readonly errors: readonly { readonly code: string }[];
32
+ };
33
+
34
+ /** The catalog the app serves, narrowed to what the admin reads. */
35
+ export type Catalog = {
36
+ /** Where procedures are served, such as `/rpc`. */
37
+ readonly prefix: string;
38
+ readonly procedures: readonly Procedure[];
39
+ };
40
+
41
+ /** A catalog, or what made it unreadable. */
42
+ export type CatalogRead =
43
+ | { readonly ok: true; readonly catalog: Catalog }
44
+ | { readonly ok: false; readonly reason: string };
45
+
46
+ export function isRecord(value: unknown): value is Record<string, unknown> {
47
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
48
+ }
49
+
50
+ function isStringArray(value: unknown): value is string[] {
51
+ return (
52
+ Array.isArray(value) && value.every((item) => typeof item === 'string')
53
+ );
54
+ }
55
+
56
+ const operations = ['find', 'count', 'get', 'create', 'update', 'delete'];
57
+
58
+ function isLabel(value: unknown): value is LatticeMeta['label'] {
59
+ return (
60
+ isRecord(value) &&
61
+ typeof value.singular === 'string' &&
62
+ typeof value.plural === 'string'
63
+ );
64
+ }
65
+
66
+ function isLatticeMeta(value: unknown): value is LatticeMeta {
67
+ if (
68
+ !isRecord(value) ||
69
+ typeof value.collection !== 'string' ||
70
+ !isLabel(value.label)
71
+ ) {
72
+ return false;
73
+ }
74
+ const { operation } = value;
75
+ if (typeof operation !== 'string') return false;
76
+ if (operation === 'list' || operation === 'set') {
77
+ return (
78
+ typeof value.relation === 'string' && typeof value.target === 'string'
79
+ );
80
+ }
81
+ if (operation === 'method') return typeof value.method === 'string';
82
+ return operations.includes(operation);
83
+ }
84
+
85
+ function optionalString(value: unknown): string | undefined | null {
86
+ if (value === undefined || typeof value === 'string') return value;
87
+ return null;
88
+ }
89
+
90
+ /** The summary and description of a docs entry, or null when unreadable. */
91
+ function docsOf(value: unknown): Docs | null {
92
+ if (!isRecord(value)) return null;
93
+ const summary = optionalString(value.summary);
94
+ const description = optionalString(value.description);
95
+ if (summary === null || description === null) return null;
96
+ return { summary, description };
97
+ }
98
+
99
+ /** The JSON Schema of a catalog schema entry, when it has one. */
100
+ function jsonSchemaOf(value: unknown): JsonSchema | undefined {
101
+ if (!isRecord(value) || value.kind !== 'json') return undefined;
102
+ return isRecord(value.jsonSchema) ? value.jsonSchema : undefined;
103
+ }
104
+
105
+ function expandOf(value: unknown): readonly string[] | undefined {
106
+ if (value === undefined) return [];
107
+ if (!isRecord(value) || !isRecord(value.fields)) return undefined;
108
+ return Object.keys(value.fields);
109
+ }
110
+
111
+ function errorsOf(value: unknown): readonly { code: string }[] | undefined {
112
+ if (!Array.isArray(value)) return undefined;
113
+ const errors: { code: string }[] = [];
114
+ for (const error of value) {
115
+ if (!isRecord(error) || typeof error.code !== 'string') return undefined;
116
+ errors.push({ code: error.code });
117
+ }
118
+ return errors;
119
+ }
120
+
121
+ /**
122
+ * A procedure entry, or why it cannot be read. An entry without a `lattice`
123
+ * meta key is not a Lattice procedure, and is skipped.
124
+ */
125
+ function procedureOf(
126
+ value: unknown,
127
+ at: string,
128
+ ): Procedure | null | { reason: string } {
129
+ const named = `The catalog's ${at}`;
130
+ if (!isRecord(value)) return { reason: `${named} is not an object.` };
131
+ if (!isStringArray(value.path)) return { reason: `${named} has no path.` };
132
+ if (!isRecord(value.meta)) return { reason: `${named} has no meta.` };
133
+ const { lattice } = value.meta;
134
+ if (lattice === undefined) return null;
135
+ if (!isLatticeMeta(lattice)) {
136
+ return { reason: `${named}.meta.lattice is not Lattice's procedure meta.` };
137
+ }
138
+ const docs =
139
+ value.meta.docs === undefined ? undefined : docsOf(value.meta.docs);
140
+ if (docs === null) {
141
+ return {
142
+ reason: `${named}.meta.docs has a summary or description that is not text.`,
143
+ };
144
+ }
145
+ const expand = expandOf(value.expand);
146
+ if (expand === undefined) {
147
+ return { reason: `${named}.expand has no fields.` };
148
+ }
149
+ const errors = errorsOf(value.errors);
150
+ if (errors === undefined) {
151
+ return { reason: `${named}.errors is not a list of errors with codes.` };
152
+ }
153
+ return {
154
+ path: value.path,
155
+ lattice,
156
+ docs,
157
+ effect: effectOf(value.meta.mcp),
158
+ input: jsonSchemaOf(value.input),
159
+ output: jsonSchemaOf(value.output),
160
+ expand,
161
+ errors,
162
+ };
163
+ }
164
+
165
+ /**
166
+ * Narrows the JSON the app serves to the catalog the admin reads. It checks
167
+ * only what the admin uses, and says why the first unreadable part fails.
168
+ */
169
+ export function readCatalog(value: unknown): CatalogRead {
170
+ if (!isRecord(value))
171
+ return { ok: false, reason: 'It is not a JSON object.' };
172
+ if (value.catalogVersion !== 1) {
173
+ return { ok: false, reason: 'Its catalogVersion is not 1.' };
174
+ }
175
+ if (typeof value.prefix !== 'string') {
176
+ return { ok: false, reason: 'It has no prefix.' };
177
+ }
178
+ if (!Array.isArray(value.procedures)) {
179
+ return { ok: false, reason: 'It has no procedures.' };
180
+ }
181
+ const procedures: Procedure[] = [];
182
+ for (const [index, entry] of value.procedures.entries()) {
183
+ const read = procedureOf(entry, `procedures[${index}]`);
184
+ if (read === null) continue;
185
+ if ('reason' in read) return { ok: false, reason: read.reason };
186
+ procedures.push(read);
187
+ }
188
+ if (procedures.length === 0) {
189
+ return { ok: false, reason: 'None of its procedures has Lattice meta.' };
190
+ }
191
+ return { ok: true, catalog: { prefix: value.prefix, procedures } };
192
+ }
@@ -0,0 +1,147 @@
1
+ import type { LatticeMeta } from '@latticecms/core';
2
+ import type { JsonSchema } from '@ts-pf/docs';
3
+ import type { Catalog, Procedure } from './catalog.js';
4
+ import { type Field, fieldsOf, propertiesOf, resolve } from './schema.js';
5
+
6
+ /** A generated operation: find, count, get, create, update or delete. */
7
+ type Operation = Exclude<LatticeMeta['operation'], 'list' | 'set' | 'method'>;
8
+
9
+ /** A `many()` relation: its procedures, and the collection its links point to. */
10
+ export type Relation = {
11
+ readonly name: string;
12
+ readonly target: string;
13
+ readonly list: Procedure | undefined;
14
+ readonly set: Procedure | undefined;
15
+ };
16
+
17
+ /** A method: its name, and its procedure. */
18
+ export type Method = { readonly name: string; readonly procedure: Procedure };
19
+
20
+ /** One collection, from the procedures whose `lattice` meta names it. */
21
+ export type Collection = {
22
+ readonly slug: string;
23
+ readonly label: LatticeMeta['label'];
24
+ readonly operations: Partial<Record<Operation, Procedure>>;
25
+ readonly relations: readonly Relation[];
26
+ /** Its methods: the procedures its use cases declare, by name. */
27
+ readonly methods: readonly Method[];
28
+ /** Every procedure of the collection, so a write can refresh them all. */
29
+ readonly procedures: readonly Procedure[];
30
+ /** Its documents' fields, in schema order. Relations are not fields. */
31
+ readonly fields: readonly Field[];
32
+ };
33
+
34
+ /** The document schema of a page's output, `find`'s or `list`'s: the items of its `docs`. */
35
+ export function documentOf(page: Procedure | undefined): JsonSchema {
36
+ const output = page?.output;
37
+ if (output === undefined) return {};
38
+ const docs = propertiesOf(output).find(([name]) => name === 'docs');
39
+ return docs === undefined ? {} : resolve(docs[1].items, output);
40
+ }
41
+
42
+ /**
43
+ * The catalog's collections, in the order their procedures appear. Each
44
+ * procedure joins the collection its meta names; nothing is read from paths.
45
+ */
46
+ export function collectionsOf(catalog: Catalog): Collection[] {
47
+ const grouped = new Map<string, Procedure[]>();
48
+ for (const procedure of catalog.procedures) {
49
+ const { collection } = procedure.lattice;
50
+ grouped.set(collection, [...(grouped.get(collection) ?? []), procedure]);
51
+ }
52
+ return [...grouped.entries()].flatMap(([slug, procedures]) => {
53
+ const [first] = procedures;
54
+ if (first === undefined) return [];
55
+ const operations: Partial<Record<Operation, Procedure>> = {};
56
+ const relations = new Map<string, Relation>();
57
+ const methods: Method[] = [];
58
+ for (const procedure of procedures) {
59
+ const meta = procedure.lattice;
60
+ if (meta.operation === 'list' || meta.operation === 'set') {
61
+ const known = relations.get(meta.relation);
62
+ relations.set(meta.relation, {
63
+ name: meta.relation,
64
+ target: meta.target,
65
+ list: meta.operation === 'list' ? procedure : known?.list,
66
+ set: meta.operation === 'set' ? procedure : known?.set,
67
+ });
68
+ } else if (meta.operation === 'method') {
69
+ methods.push({ name: meta.method, procedure });
70
+ } else {
71
+ operations[meta.operation] = procedure;
72
+ }
73
+ }
74
+ const fields = fieldsOf(documentOf(operations.find)).filter(
75
+ (field) => !relations.has(field.name),
76
+ );
77
+ return [
78
+ {
79
+ slug,
80
+ label: first.lattice.label,
81
+ operations,
82
+ relations: [...relations.values()],
83
+ methods,
84
+ procedures,
85
+ fields,
86
+ },
87
+ ];
88
+ });
89
+ }
90
+
91
+ /**
92
+ * The field a document is named by, such as in a link to it: the first
93
+ * required string among `name`, `title`, `label` and `email`, never a
94
+ * maskable one.
95
+ */
96
+ export function titleFieldOf(collection: Collection): Field | undefined {
97
+ for (const name of ['name', 'title', 'label', 'email']) {
98
+ const field = collection.fields.find(
99
+ (candidate) => candidate.name === name,
100
+ );
101
+ if (field?.required && field.kind === 'string' && !field.maskable) {
102
+ return field;
103
+ }
104
+ }
105
+ return undefined;
106
+ }
107
+
108
+ const scalars = new Set([
109
+ 'string',
110
+ 'number',
111
+ 'boolean',
112
+ 'enum',
113
+ 'datetime',
114
+ 'ref',
115
+ ]);
116
+
117
+ /** The most columns a list shows before `updatedAt`. */
118
+ const maxColumns = 6;
119
+
120
+ /**
121
+ * A list's columns: the title field, then the required scalar fields in
122
+ * schema order, up to six in all, then `updatedAt`. A maskable field counts
123
+ * as required, since only its client schema makes it optional, unless no
124
+ * loaded document carries it: a field rule is per caller, not per document
125
+ * (0031), so the caller may not read it, and the column is left out.
126
+ */
127
+ export function columnsOf(
128
+ collection: Collection,
129
+ docs: readonly Record<string, unknown>[],
130
+ ): Field[] {
131
+ const title = titleFieldOf(collection);
132
+ const rest = collection.fields.filter(
133
+ (field) =>
134
+ field !== title &&
135
+ !field.system &&
136
+ scalars.has(field.kind) &&
137
+ (field.maskable
138
+ ? docs.some((doc) => doc[field.name] !== undefined)
139
+ : field.required),
140
+ );
141
+ const updatedAt = collection.fields.find(
142
+ (field) => field.name === 'updatedAt',
143
+ );
144
+ return [...(title === undefined ? [] : [title]), ...rest]
145
+ .slice(0, maxColumns)
146
+ .concat(updatedAt === undefined ? [] : [updatedAt]);
147
+ }
@@ -0,0 +1,57 @@
1
+ import {
2
+ AlertDialog,
3
+ AlertDialogAction,
4
+ AlertDialogCancel,
5
+ AlertDialogContent,
6
+ AlertDialogDescription,
7
+ AlertDialogFooter,
8
+ AlertDialogHeader,
9
+ AlertDialogTitle,
10
+ } from '@shadalaya/react/alert-dialog';
11
+
12
+ /** What a confirmation asks: a question, what follows, and the action. */
13
+ export type Confirmation = {
14
+ readonly title: string;
15
+ readonly description: string;
16
+ readonly action: string;
17
+ /** The action destroys data, so its button says so. */
18
+ readonly destructive: boolean;
19
+ };
20
+
21
+ /** Asks before a call that changes data. Cancel closes it and does nothing. */
22
+ export function ConfirmDialog({
23
+ confirmation,
24
+ open,
25
+ onOpenChange,
26
+ onConfirm,
27
+ }: {
28
+ readonly confirmation: Confirmation;
29
+ readonly open: boolean;
30
+ readonly onOpenChange: (open: boolean) => void;
31
+ readonly onConfirm: () => void;
32
+ }) {
33
+ return (
34
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
35
+ <AlertDialogContent>
36
+ <AlertDialogHeader>
37
+ <AlertDialogTitle>{confirmation.title}</AlertDialogTitle>
38
+ <AlertDialogDescription>
39
+ {confirmation.description}
40
+ </AlertDialogDescription>
41
+ </AlertDialogHeader>
42
+ <AlertDialogFooter>
43
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
44
+ <AlertDialogAction
45
+ variant={confirmation.destructive ? 'destructive' : 'default'}
46
+ onClick={() => {
47
+ onOpenChange(false);
48
+ onConfirm();
49
+ }}
50
+ >
51
+ {confirmation.action}
52
+ </AlertDialogAction>
53
+ </AlertDialogFooter>
54
+ </AlertDialogContent>
55
+ </AlertDialog>
56
+ );
57
+ }
package/src/data.tsx ADDED
@@ -0,0 +1,94 @@
1
+ import type { Link } from '@ts-pf/client';
2
+ import { FetchLink } from '@ts-pf/client-http';
3
+ import {
4
+ createContext,
5
+ type ReactNode,
6
+ useCallback,
7
+ useContext,
8
+ useMemo,
9
+ } from 'react';
10
+ import useSWR, { useSWRConfig } from 'swr';
11
+ import type { Procedure } from './catalog.js';
12
+ import type { Collection } from './collections.js';
13
+
14
+ const LinkContext = createContext<Link | undefined>(undefined);
15
+
16
+ /** Calls go to the catalog's prefix, through the app's fetch. */
17
+ export function LinkProvider({
18
+ prefix,
19
+ fetch,
20
+ children,
21
+ }: {
22
+ readonly prefix: string;
23
+ readonly fetch: typeof globalThis.fetch;
24
+ readonly children: ReactNode;
25
+ }) {
26
+ const link = useMemo(
27
+ () => new FetchLink({ url: prefix, fetch }),
28
+ [prefix, fetch],
29
+ );
30
+ return <LinkContext value={link}>{children}</LinkContext>;
31
+ }
32
+
33
+ function useLink(): Link {
34
+ const link = useContext(LinkContext);
35
+ if (link === undefined) {
36
+ throw new Error('Lattice admin: a call outside <Admin>');
37
+ }
38
+ return link;
39
+ }
40
+
41
+ /** An swr key: the procedure's path and its input. */
42
+ type Call = readonly [path: readonly string[], input: unknown];
43
+
44
+ /**
45
+ * Calls `procedure` with `input` through swr, keyed by both, so the same
46
+ * call is shared and refetched on focus. No procedure, no call.
47
+ */
48
+ export function useCall(procedure: Procedure | undefined, input: unknown) {
49
+ const link = useLink();
50
+ const key: Call | null =
51
+ procedure === undefined ? null : [procedure.path, input];
52
+ return useSWR(key, ([path, body]: Call) => link.call([...path], body));
53
+ }
54
+
55
+ /** Calls a procedure once, outside swr: a write, or a load the user asked for. */
56
+ export function useCaller(): (
57
+ procedure: Procedure,
58
+ input: unknown,
59
+ ) => Promise<unknown> {
60
+ const link = useLink();
61
+ return useCallback(
62
+ (procedure, input) => link.call([...procedure.path], input),
63
+ [link],
64
+ );
65
+ }
66
+
67
+ /**
68
+ * After a write: the swr entries of the collections it touched, by their
69
+ * procedures' paths, such as a document, its lists and counts, and a
70
+ * relation's target. `refresh` refetches them where they stand, so a
71
+ * mounted document never blinks. `drop` empties them and refetches, for a
72
+ * delete that leaves the page: a list mounts empty and fetches fresh, so it
73
+ * never shows the deleted row. Emptying alone is not enough: swr would
74
+ * dedupe the list's next fetch against the one before the delete, then
75
+ * discard that answer as older than the change.
76
+ */
77
+ export function useRevalidate(
78
+ mode: 'refresh' | 'drop',
79
+ ): (...collections: readonly Collection[]) => Promise<void> {
80
+ const { mutate } = useSWRConfig();
81
+ return async (...collections) => {
82
+ const paths = new Set(
83
+ collections.flatMap(({ procedures }) =>
84
+ procedures.map(({ path }) => path.join('/')),
85
+ ),
86
+ );
87
+ const touched = (key: unknown) =>
88
+ Array.isArray(key) &&
89
+ Array.isArray(key[0]) &&
90
+ paths.has(key[0].join('/'));
91
+ if (mode === 'drop') await mutate(touched, undefined);
92
+ else await mutate(touched);
93
+ };
94
+ }