cogens 0.2.1 → 0.3.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.
- package/CHANGELOG.md +15 -0
- package/README.md +23 -2
- package/dist/admin/app.d.ts.map +1 -1
- package/dist/admin/app.js +221 -41
- package/dist/admin/app.js.map +1 -1
- package/dist/admin/fields.d.ts +2 -0
- package/dist/admin/fields.d.ts.map +1 -1
- package/dist/admin/fields.js +4 -2
- package/dist/admin/fields.js.map +1 -1
- package/dist/admin/index.d.ts +2 -2
- package/dist/admin/index.d.ts.map +1 -1
- package/dist/admin/index.js +1 -1
- package/dist/admin/index.js.map +1 -1
- package/dist/admin/types.d.ts +64 -1
- package/dist/admin/types.d.ts.map +1 -1
- package/dist/admin/views.d.ts +43 -8
- package/dist/admin/views.d.ts.map +1 -1
- package/dist/admin/views.js +46 -19
- package/dist/admin/views.js.map +1 -1
- package/dist/core/config/field.d.ts +18 -2
- package/dist/core/config/field.d.ts.map +1 -1
- package/dist/core/config/field.js +12 -1
- package/dist/core/config/field.js.map +1 -1
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/admin/app.ts +219 -39
- package/src/admin/fields.ts +5 -2
- package/src/admin/index.ts +3 -2
- package/src/admin/types.ts +65 -1
- package/src/admin/views.ts +111 -23
- package/src/core/config/field.ts +19 -2
- package/src/core/index.ts +1 -1
package/src/admin/app.ts
CHANGED
|
@@ -23,10 +23,10 @@ import { ADMIN_CSS, ADMIN_JS } from './assets.ts';
|
|
|
23
23
|
import type { ResolveRef } from './fields.ts';
|
|
24
24
|
import { parseForm } from './forms.ts';
|
|
25
25
|
import { can, mayWrite, mayWriteColumn, ruleRow, writable, type Writable } from './rules.ts';
|
|
26
|
-
import type { AdminAction, AdminAssets, AdminOptions, ExternalCollection, ExternalRow } from './types.ts';
|
|
26
|
+
import type { AdminAction, AdminAssets, AdminOptions, AdminRelated, ExternalCollection, ExternalRow } from './types.ts';
|
|
27
27
|
import {
|
|
28
|
-
confirmPage, entryListPage, entryPage, externalListPage, externalRowPage, messagePage, noticeText, signInPage,
|
|
29
|
-
type Column, type Row, type Shell
|
|
28
|
+
confirmPage, entryListPage, entryPage, externalListPage, externalRowPage, homePage, messagePage, noticeText, signInPage,
|
|
29
|
+
type Belonging, type Column, type HomeSection, type ListColumn, type Row, type Shell
|
|
30
30
|
} from './views.ts';
|
|
31
31
|
|
|
32
32
|
export const DEFAULT_ASSETS: AdminAssets = {
|
|
@@ -41,6 +41,21 @@ const PAGE = 50;
|
|
|
41
41
|
const FORM = /^(application\/x-www-form-urlencoded|multipart\/form-data)\b/i;
|
|
42
42
|
/** Most rows offered in a target picker. */
|
|
43
43
|
const PICKER_CAP = 2000;
|
|
44
|
+
/** Most children or related rows listed on an entry's page. */
|
|
45
|
+
const BELONGING_CAP = 50;
|
|
46
|
+
/** Most children counted for "and N more". */
|
|
47
|
+
const COUNT_CAP = 1000;
|
|
48
|
+
/** Ids per read when resolving reference names. */
|
|
49
|
+
const NAME_CHUNK = 90;
|
|
50
|
+
/** The built-in columns a list may show, and their headings. */
|
|
51
|
+
const BUILTIN_COLUMNS: Record<string, string> = {
|
|
52
|
+
slug: 'Slug',
|
|
53
|
+
status: 'Status',
|
|
54
|
+
owner_id: 'Owner',
|
|
55
|
+
parent_id: 'Parent',
|
|
56
|
+
created_at: 'Created',
|
|
57
|
+
updated_at: 'Updated'
|
|
58
|
+
};
|
|
44
59
|
|
|
45
60
|
const status = (error: unknown, fallback: number): number => {
|
|
46
61
|
const n = (error as { status?: unknown } | null)?.status;
|
|
@@ -57,6 +72,63 @@ export function createAdmin<H extends HostPrincipal = never>(options: AdminOptio
|
|
|
57
72
|
const shell: Shell = { mount, home: mount || '/', siteName: options.siteName ?? 'Admin', assets, session: Boolean(options.session) };
|
|
58
73
|
const externals = new Map((options.externalCollections ?? []).map(c => [c.id, c]));
|
|
59
74
|
const typeActions = options.typeActions ?? {};
|
|
75
|
+
const typeRelated = options.typeRelated ?? {};
|
|
76
|
+
const typeTitles = options.typeTitles ?? {};
|
|
77
|
+
for (const typeId of Object.keys(typeTitles)) {
|
|
78
|
+
if (!cms.types.has(typeId)) throw new ConfigError(`The admin names entries of "${typeId}", which is no type.`, typeId);
|
|
79
|
+
}
|
|
80
|
+
/** A host action with a built-in control's id takes its place: the control is not drawn and its route is refused. */
|
|
81
|
+
const replaced = (typeId: string, verb: 'publish' | 'unpublish' | 'delete') => (typeActions[typeId] ?? []).some(a => a.id === verb);
|
|
82
|
+
|
|
83
|
+
// The host's arrangement names types, tables and fields; a name that matches nothing is a mistake in the host's config.
|
|
84
|
+
const known = (id: string) => cms.types.has(id) || externals.has(id);
|
|
85
|
+
for (const section of options.sections ?? []) {
|
|
86
|
+
for (const id of section.items) {
|
|
87
|
+
if (!known(id)) throw new ConfigError(`The admin's section "${section.title}" lists "${id}", which is no type or table.`, id);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (options.ownerTable !== undefined && !externals.has(options.ownerTable)) {
|
|
91
|
+
throw new ConfigError(`The admin's owner table "${options.ownerTable}" is no external collection.`, options.ownerTable);
|
|
92
|
+
}
|
|
93
|
+
const ownerMeta = (): FieldMeta | undefined =>
|
|
94
|
+
options.ownerTable ? { label: 'Owner', fieldType: 'reference', refContentType: options.ownerTable, required: false, system: false } : undefined;
|
|
95
|
+
/** The columns of a store type's list, or undefined for the default. */
|
|
96
|
+
const typeColumns = new Map<string, ListColumn[]>();
|
|
97
|
+
for (const [typeId, names] of Object.entries(options.typeColumns ?? {})) {
|
|
98
|
+
const type = cms.types.get(typeId);
|
|
99
|
+
if (!type) throw new ConfigError(`The admin names columns for "${typeId}", which is no type.`, typeId);
|
|
100
|
+
typeColumns.set(
|
|
101
|
+
typeId,
|
|
102
|
+
names.filter(n => n !== type.displayField).map((column): ListColumn => {
|
|
103
|
+
if (typeof column !== 'string') return { name: column.name, label: column.label, value: column.value };
|
|
104
|
+
const name = column;
|
|
105
|
+
const meta = type.fieldMeta[name];
|
|
106
|
+
if (meta) return { name, label: meta.label, meta };
|
|
107
|
+
if (name === 'parent_id' && type.parent) {
|
|
108
|
+
const parent = cms.types.get(type.parent);
|
|
109
|
+
return { name, label: parent?.name ?? 'Parent', meta: { label: parent?.name ?? 'Parent', fieldType: 'reference', refContentType: type.parent, required: false, system: false } };
|
|
110
|
+
}
|
|
111
|
+
if (name === 'owner_id' && type.owned) return { name, label: 'Owner', meta: ownerMeta() };
|
|
112
|
+
if (name in BUILTIN_COLUMNS && name !== 'parent_id' && name !== 'owner_id') return { name, label: BUILTIN_COLUMNS[name]! };
|
|
113
|
+
throw new ConfigError(`The admin's columns for "${typeId}" name "${name}", which is not one of its fields or columns.`, typeId, name);
|
|
114
|
+
})
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
const tableColumns = new Map<string, ListColumn[]>();
|
|
118
|
+
for (const collection of externals.values()) {
|
|
119
|
+
if (!collection.columns) continue;
|
|
120
|
+
tableColumns.set(
|
|
121
|
+
collection.id,
|
|
122
|
+
collection.columns.filter(n => n !== collection.displayField).map((column): ListColumn => {
|
|
123
|
+
if (typeof column !== 'string') return { name: column.name, label: column.label, value: column.value };
|
|
124
|
+
const name = column;
|
|
125
|
+
const meta = collection.fields[name]?.meta;
|
|
126
|
+
if (meta) return { name, label: meta.label, meta };
|
|
127
|
+
if (name === 'owner_id') return { name, label: 'Owner', meta: ownerMeta() };
|
|
128
|
+
throw new ConfigError(`The columns of "${collection.id}" name "${name}", which is not one of its fields.`, collection.id, name);
|
|
129
|
+
})
|
|
130
|
+
);
|
|
131
|
+
}
|
|
60
132
|
|
|
61
133
|
const app = new Hono<{ Variables: { principal: P } }>();
|
|
62
134
|
|
|
@@ -185,45 +257,128 @@ export function createAdmin<H extends HostPrincipal = never>(options: AdminOptio
|
|
|
185
257
|
const notice = (c: Ctx) => noticeText(c.req.query('notice'));
|
|
186
258
|
const label = (type: ContentType<any>, e: Entry) => String(e.data[type.displayField] ?? '') || e.slug || e.id;
|
|
187
259
|
|
|
188
|
-
/**
|
|
189
|
-
|
|
260
|
+
/**
|
|
261
|
+
* The names of entries of one type, by id: the host's `typeTitles` (with each parent's name, one read per page) or the
|
|
262
|
+
* display field.
|
|
263
|
+
*/
|
|
264
|
+
async function titles(c: Ctx, type: ContentType<any>, entries: Entry[]): Promise<Map<string, string>> {
|
|
265
|
+
const out = new Map<string, string>();
|
|
266
|
+
const named: ((entry: Entry, parent: string | undefined) => string) | undefined = typeTitles[type.id];
|
|
267
|
+
const parents = new Map<string, string>();
|
|
268
|
+
const parentType = named !== undefined && type.parent ? readable(c, type.parent) : undefined;
|
|
269
|
+
if (parentType) {
|
|
270
|
+
const ids = [...new Set(entries.map(e => e.parent_id).filter((id): id is string => typeof id === 'string' && id !== ''))];
|
|
271
|
+
for (let i = 0; i < ids.length; i += NAME_CHUNK) {
|
|
272
|
+
const list = ids.slice(i, i + NAME_CHUNK);
|
|
273
|
+
for (const p of await apiOf(c).list(parentType.id, { where: { id: { in: list } }, limit: list.length })) parents.set(p.id, label(parentType, p));
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
for (const e of entries) out.set(e.id, (named?.(e, e.parent_id ? parents.get(e.parent_id) : undefined)) || label(type, e));
|
|
277
|
+
return out;
|
|
278
|
+
}
|
|
279
|
+
const titleOf = async (c: Ctx, type: ContentType<any>, e: Entry) => (await titles(c, type, [e])).get(e.id) ?? label(type, e);
|
|
280
|
+
|
|
281
|
+
/** The name a row of a store type or a table is shown by. */
|
|
282
|
+
const rowLabel = (c: Ctx, tableId: string, row: ExternalRow): string => {
|
|
283
|
+
const type = readable(c, tableId);
|
|
284
|
+
const display = type ? type.displayField : external(c, tableId)?.displayField;
|
|
285
|
+
return (display ? String(row[display] ?? '') : '') || (typeof row.slug === 'string' ? row.slug : '') || row.id;
|
|
286
|
+
};
|
|
287
|
+
const hrefOf = (c: Ctx, tableId: string, id: string): string | null =>
|
|
288
|
+
readable(c, tableId) ? `${mount}/t/${tableId}/${encodeURIComponent(id)}` : external(c, tableId) ? `${mount}/x/${tableId}/${encodeURIComponent(id)}` : null;
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Where each reference field's ids lead and what to call them, for one entry or a whole list of them. Reads only
|
|
292
|
+
* what the caller may read, and one read per referred type for every id named (in chunks of 90).
|
|
293
|
+
*/
|
|
294
|
+
async function resolver(c: Ctx, fields: Record<string, FieldMeta | undefined>, rows: Record<string, unknown>[]): Promise<ResolveRef> {
|
|
190
295
|
const wanted = new Map<string, Set<string>>();
|
|
191
296
|
for (const [name, meta] of Object.entries(fields)) {
|
|
192
|
-
if ((meta.fieldType !== 'reference' && meta.fieldType !== 'references') || !meta.refContentType) continue;
|
|
193
|
-
const value = data[name];
|
|
194
|
-
const ids = Array.isArray(value) ? value : typeof value === 'string' && value ? [value] : [];
|
|
297
|
+
if (!meta || (meta.fieldType !== 'reference' && meta.fieldType !== 'references') || !meta.refContentType) continue;
|
|
195
298
|
const set = wanted.get(meta.refContentType) ?? new Set<string>();
|
|
196
|
-
for (const
|
|
299
|
+
for (const data of rows) {
|
|
300
|
+
const value = data[name];
|
|
301
|
+
const ids = Array.isArray(value) ? value : typeof value === 'string' && value ? [value] : [];
|
|
302
|
+
for (const id of ids) if (typeof id === 'string') set.add(id);
|
|
303
|
+
}
|
|
197
304
|
wanted.set(meta.refContentType, set);
|
|
198
305
|
}
|
|
199
306
|
const names = new Map<string, string>();
|
|
200
307
|
for (const [refType, ids] of wanted) {
|
|
201
|
-
const
|
|
202
|
-
if (
|
|
308
|
+
const all = [...ids];
|
|
309
|
+
if (all.length === 0) continue;
|
|
203
310
|
const type = readable(c, refType);
|
|
204
311
|
const collection = external(c, refType);
|
|
205
312
|
if (type) {
|
|
206
|
-
for (
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
const
|
|
210
|
-
if (row) names.set(`${refType}:${id}`, String(row[collection.displayField] ?? '') || id);
|
|
313
|
+
for (let i = 0; i < all.length; i += NAME_CHUNK) {
|
|
314
|
+
const list = all.slice(i, i + NAME_CHUNK);
|
|
315
|
+
const found = await apiOf(c).list(refType, { where: { id: { in: list } }, limit: list.length });
|
|
316
|
+
for (const [id, name] of await titles(c, type, found)) names.set(`${refType}:${id}`, name);
|
|
211
317
|
}
|
|
318
|
+
} else if (collection) {
|
|
319
|
+
const found = collection.getMany
|
|
320
|
+
? await collection.getMany(c, all)
|
|
321
|
+
: (await Promise.all(all.slice(0, BELONGING_CAP).map(id => collection.get(c, id)))).filter((r): r is ExternalRow => r !== null);
|
|
322
|
+
for (const row of found) names.set(`${refType}:${row.id}`, String(row[collection.displayField] ?? '') || row.id);
|
|
212
323
|
}
|
|
213
324
|
}
|
|
214
|
-
return (refType, id) => {
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
325
|
+
return (refType, id) => ({ href: hrefOf(c, refType, id), label: names.get(`${refType}:${id}`) ?? id });
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** The host's related lists for an entry or row, as the caller may read them. */
|
|
329
|
+
async function relatedLists(c: Ctx, lists: AdminRelated<H>[], id: string, entry: Entry | ExternalRow): Promise<Belonging[]> {
|
|
330
|
+
const out: Belonging[] = [];
|
|
331
|
+
for (const list of lists) {
|
|
332
|
+
if (!readable(c, list.table) && !external(c, list.table)) continue;
|
|
333
|
+
const answer = await list.rows({ c, principal: principalOf(c), id, entry });
|
|
334
|
+
const rows = Array.isArray(answer) ? answer : answer.rows;
|
|
335
|
+
const total = Array.isArray(answer) ? rows.length : Math.max(answer.total, rows.length);
|
|
336
|
+
out.push({
|
|
337
|
+
label: list.label,
|
|
338
|
+
total,
|
|
339
|
+
items: rows.slice(0, BELONGING_CAP).map(row => ({
|
|
340
|
+
href: hrefOf(c, list.table, row.id),
|
|
341
|
+
label: rowLabel(c, list.table, row),
|
|
342
|
+
status: typeof row.state === 'string' ? row.state : typeof row.status === 'string' ? row.status : undefined
|
|
343
|
+
}))
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
return out;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** An entry's children: the entries of every type whose parent is its type and that the caller may read. */
|
|
350
|
+
async function childLists(c: Ctx, type: ContentType<any>, entry: Entry): Promise<Belonging[]> {
|
|
351
|
+
const out: Belonging[] = [];
|
|
352
|
+
for (const child of cms.types.values()) {
|
|
353
|
+
if (child.parent !== type.id || !readable(c, child.id)) continue;
|
|
354
|
+
const found = await apiOf(c).list(child.id, { where: { parent_id: entry.id }, orderBy: 'created_at', direction: 'asc', limit: COUNT_CAP + 1 });
|
|
355
|
+
const names = await titles(c, child, found.slice(0, BELONGING_CAP));
|
|
356
|
+
out.push({
|
|
357
|
+
label: child.name,
|
|
358
|
+
total: found.length,
|
|
359
|
+
more: `${mount}/t/${child.id}?parent=${encodeURIComponent(entry.id)}`,
|
|
360
|
+
items: found.slice(0, BELONGING_CAP).map(e => ({ href: `${mount}/t/${child.id}/${encodeURIComponent(e.id)}`, label: names.get(e.id) ?? label(child, e), status: e.status }))
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
return out;
|
|
218
364
|
}
|
|
219
365
|
|
|
220
366
|
// ── Types ─────────────────────────────────────────────────────────
|
|
221
367
|
|
|
222
368
|
app.get('/', c => {
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
369
|
+
const item = (id: string) => {
|
|
370
|
+
const type = readable(c, id);
|
|
371
|
+
if (type) return { href: `${mount}/t/${type.id}`, name: type.name };
|
|
372
|
+
const collection = external(c, id);
|
|
373
|
+
return collection ? { href: `${mount}/x/${collection.id}`, name: collection.name } : null;
|
|
374
|
+
};
|
|
375
|
+
const sections: HomeSection[] = options.sections
|
|
376
|
+
? options.sections.map(s => ({ title: s.title, line: s.line, items: s.items.map(item).filter(i => i !== null) }))
|
|
377
|
+
: [
|
|
378
|
+
{ title: 'Types', items: [...cms.types.values()].map(t => item(t.id)).filter(i => i !== null) },
|
|
379
|
+
{ title: 'Tables', items: [...externals.keys()].map(item).filter(i => i !== null) }
|
|
380
|
+
];
|
|
381
|
+
return c.html(homePage(shell, sections));
|
|
227
382
|
});
|
|
228
383
|
|
|
229
384
|
// ── Entry lists ───────────────────────────────────────────────────
|
|
@@ -234,12 +389,14 @@ export function createAdmin<H extends HostPrincipal = never>(options: AdminOptio
|
|
|
234
389
|
const q = (c.req.query('q') ?? '').trim();
|
|
235
390
|
const statusFilter = c.req.query('status') === 'published' || c.req.query('status') === 'draft' ? c.req.query('status')! : '';
|
|
236
391
|
const owner = (c.req.query('owner') ?? '').trim();
|
|
392
|
+
const parent = type.parent ? (c.req.query('parent') ?? '').trim() : '';
|
|
237
393
|
const offset = Math.max(Math.trunc(Number(c.req.query('offset') ?? 0)) || 0, 0);
|
|
238
394
|
const conditions: Where[] = [];
|
|
239
395
|
// The store's conditions are equality, so a slug search is exact.
|
|
240
396
|
if (q) conditions.push({ slug: q });
|
|
241
397
|
if (statusFilter) conditions.push({ status: statusFilter });
|
|
242
398
|
if (owner && type.owned) conditions.push({ owner_id: owner });
|
|
399
|
+
if (parent) conditions.push({ parent_id: parent });
|
|
243
400
|
const found = await apiOf(c).list(type.id, {
|
|
244
401
|
...(conditions.length === 0 ? {} : { where: conditions.length === 1 ? conditions[0]! : { and: conditions } }),
|
|
245
402
|
orderBy: 'updated_at',
|
|
@@ -247,10 +404,24 @@ export function createAdmin<H extends HostPrincipal = never>(options: AdminOptio
|
|
|
247
404
|
limit: PAGE + 1,
|
|
248
405
|
offset
|
|
249
406
|
});
|
|
407
|
+
const entries = found.slice(0, PAGE);
|
|
408
|
+
const entryTitles = await titles(c, type, entries);
|
|
409
|
+
const columns = typeColumns.get(type.id);
|
|
410
|
+
const refs = columns
|
|
411
|
+
? await resolver(
|
|
412
|
+
c,
|
|
413
|
+
Object.fromEntries(columns.map(col => [col.name, col.meta])),
|
|
414
|
+
entries.map(e => ({ ...e.data, owner_id: e.owner_id, parent_id: e.parent_id }))
|
|
415
|
+
)
|
|
416
|
+
: await resolver(c, {}, []);
|
|
250
417
|
return c.html(
|
|
251
418
|
entryListPage(shell, {
|
|
252
419
|
type,
|
|
253
|
-
entries
|
|
420
|
+
entries,
|
|
421
|
+
titles: entryTitles,
|
|
422
|
+
columns,
|
|
423
|
+
refs,
|
|
424
|
+
parent,
|
|
254
425
|
q,
|
|
255
426
|
status: statusFilter,
|
|
256
427
|
owner: type.owned ? owner : '',
|
|
@@ -301,7 +472,8 @@ export function createAdmin<H extends HostPrincipal = never>(options: AdminOptio
|
|
|
301
472
|
rows.push({ name, meta, value: shown(name), editable, error: state.fieldErrors?.[name] });
|
|
302
473
|
}
|
|
303
474
|
const data = Object.fromEntries(Object.keys(type.fieldMeta).map(name => [name, shown(name)]));
|
|
304
|
-
const refs = await resolver(c, type.fieldMeta, data);
|
|
475
|
+
const refs = await resolver(c, type.fieldMeta, [data]);
|
|
476
|
+
const lists = entry ? [...(await childLists(c, type, entry)), ...(await relatedLists(c, typeRelated[type.id] ?? [], entry.id, entry))] : [];
|
|
305
477
|
const actions = entry
|
|
306
478
|
? (typeActions[type.id] ?? []).filter(a => (a.requires ? can(rules, type.id, a.requires, row) : true))
|
|
307
479
|
: [];
|
|
@@ -312,11 +484,13 @@ export function createAdmin<H extends HostPrincipal = never>(options: AdminOptio
|
|
|
312
484
|
rows,
|
|
313
485
|
refs,
|
|
314
486
|
canSave: columns.some(col => col.editable) || rows.some(r => r.editable),
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
canUnpublish: !!entry && can(rules, type.id, 'publish', row) && !(
|
|
318
|
-
canDelete: !!entry && can(rules, type.id, 'delete', row) && !(
|
|
487
|
+
// A type's own `publish`, `unpublish` and `delete` actions take the place of the plain controls.
|
|
488
|
+
canPublish: !!entry && can(rules, type.id, 'publish', row) && !replaced(type.id, 'publish'),
|
|
489
|
+
canUnpublish: !!entry && can(rules, type.id, 'publish', row) && !replaced(type.id, 'unpublish'),
|
|
490
|
+
canDelete: !!entry && can(rules, type.id, 'delete', row) && !replaced(type.id, 'delete'),
|
|
319
491
|
actions,
|
|
492
|
+
belongings: lists,
|
|
493
|
+
title: entry ? await titleOf(c, type, entry) : undefined,
|
|
320
494
|
notice: notice(c),
|
|
321
495
|
problems: state.problems
|
|
322
496
|
});
|
|
@@ -407,7 +581,8 @@ export function createAdmin<H extends HostPrincipal = never>(options: AdminOptio
|
|
|
407
581
|
for (const verb of ['publish', 'unpublish'] as const) {
|
|
408
582
|
app.post(`/t/:type/:id/${verb}`, async c => {
|
|
409
583
|
const { type, entry } = await entryOf(c);
|
|
410
|
-
|
|
584
|
+
// A replaced control is refused at its route, the same answer as a control the caller lacks.
|
|
585
|
+
if (!type || !entry || replaced(type.id, verb)) return notFound(c);
|
|
411
586
|
await apiOf(c)[verb](type.id, entry.id);
|
|
412
587
|
return c.redirect(`${mount}/t/${type.id}/${encodeURIComponent(entry.id)}?notice=${verb === 'publish' ? 'published' : 'unpublished'}`, 303);
|
|
413
588
|
});
|
|
@@ -415,9 +590,9 @@ export function createAdmin<H extends HostPrincipal = never>(options: AdminOptio
|
|
|
415
590
|
|
|
416
591
|
app.get('/t/:type/:id/delete', async c => {
|
|
417
592
|
const { type, entry } = await entryOf(c);
|
|
418
|
-
if (!type || !entry) return notFound(c);
|
|
593
|
+
if (!type || !entry || replaced(type.id, 'delete')) return notFound(c);
|
|
419
594
|
if (!can(rulesOf(c), type.id, 'delete', ruleRow(type, entry))) return notFound(c);
|
|
420
|
-
const name =
|
|
595
|
+
const name = await titleOf(c, type, entry);
|
|
421
596
|
return c.html(
|
|
422
597
|
confirmPage(shell, {
|
|
423
598
|
title: `Delete ${name}?`,
|
|
@@ -433,7 +608,7 @@ export function createAdmin<H extends HostPrincipal = never>(options: AdminOptio
|
|
|
433
608
|
|
|
434
609
|
app.post('/t/:type/:id/delete', async c => {
|
|
435
610
|
const { type, entry } = await entryOf(c);
|
|
436
|
-
if (!type || !entry) return notFound(c);
|
|
611
|
+
if (!type || !entry || replaced(type.id, 'delete')) return notFound(c);
|
|
437
612
|
await apiOf(c).remove(type.id, entry.id);
|
|
438
613
|
return c.redirect(`${mount}/t/${type.id}?notice=deleted`, 303);
|
|
439
614
|
});
|
|
@@ -460,7 +635,8 @@ export function createAdmin<H extends HostPrincipal = never>(options: AdminOptio
|
|
|
460
635
|
if (!type) return null;
|
|
461
636
|
for (let offset = 0; offset < PICKER_CAP; offset += 1000) {
|
|
462
637
|
const rows = await apiOf(c).list(type.id, { limit: 1000, offset });
|
|
463
|
-
|
|
638
|
+
const names = await titles(c, type, rows);
|
|
639
|
+
for (const e of rows) if (e.id !== selfId) options.push({ id: e.id, label: names.get(e.id) ?? label(type, e) });
|
|
464
640
|
if (rows.length < 1000) break;
|
|
465
641
|
}
|
|
466
642
|
return { title: type.name, options };
|
|
@@ -525,7 +701,7 @@ export function createAdmin<H extends HostPrincipal = never>(options: AdminOptio
|
|
|
525
701
|
if (!type || !entry) return null;
|
|
526
702
|
const action = (typeActions[type.id] ?? []).find(a => a.id === c.req.param('action'));
|
|
527
703
|
if (!action || (action.requires && !can(rulesOf(c), type.id, action.requires, ruleRow(type, entry)))) return null;
|
|
528
|
-
const name =
|
|
704
|
+
const name = await titleOf(c, type, entry);
|
|
529
705
|
return {
|
|
530
706
|
action,
|
|
531
707
|
id: entry.id,
|
|
@@ -571,15 +747,19 @@ export function createAdmin<H extends HostPrincipal = never>(options: AdminOptio
|
|
|
571
747
|
if (!collection) return notFound(c);
|
|
572
748
|
const offset = Math.max(Math.trunc(Number(c.req.query('offset') ?? 0)) || 0, 0);
|
|
573
749
|
const rows = await collection.list(c, { limit: PAGE + 1, offset });
|
|
574
|
-
|
|
750
|
+
const shown = rows.slice(0, PAGE);
|
|
751
|
+
const columns = tableColumns.get(collection.id);
|
|
752
|
+
const refs = columns ? await resolver(c, Object.fromEntries(columns.map(col => [col.name, col.meta])), shown) : undefined;
|
|
753
|
+
return c.html(externalListPage(shell, collection, shown, offset, PAGE, rows.length > PAGE, columns, refs));
|
|
575
754
|
});
|
|
576
755
|
|
|
577
756
|
app.get('/x/:collection/:id', async c => {
|
|
578
757
|
const collection = external(c, c.req.param('collection'));
|
|
579
758
|
const row: ExternalRow | null | undefined = await collection?.get(c, c.req.param('id'));
|
|
580
759
|
if (!collection || !row) return notFound(c);
|
|
581
|
-
const refs = await resolver(c, Object.fromEntries(Object.entries(collection.fields).map(([n, b]) => [n, b.meta])), row);
|
|
582
|
-
|
|
760
|
+
const refs = await resolver(c, Object.fromEntries(Object.entries(collection.fields).map(([n, b]) => [n, b.meta])), [row]);
|
|
761
|
+
const related = await relatedLists(c, collection.related ?? [], row.id, row);
|
|
762
|
+
return c.html(externalRowPage(shell, collection, row, refs, collection.actions ?? [], notice(c), related));
|
|
583
763
|
});
|
|
584
764
|
|
|
585
765
|
app.get('/x/:collection/:id/do/:action', async c => {
|
package/src/admin/fields.ts
CHANGED
|
@@ -101,11 +101,14 @@ const date: Renderer = {
|
|
|
101
101
|
read: ({ value }) => (present(value) ? html`<time datetime="${asText(value)}">${asText(value)}</time>` : MUTED)
|
|
102
102
|
};
|
|
103
103
|
|
|
104
|
+
/** What a select shows for a stored value: its option's label, or the value itself. */
|
|
105
|
+
export const optionLabel = (meta: FieldMeta, value: string): string => meta.optionLabels?.[value] ?? value;
|
|
106
|
+
|
|
104
107
|
const select: Renderer = {
|
|
105
108
|
edit: ({ name, meta, value }) => html`<select id="${idOf(name)}" name="${name}">${
|
|
106
109
|
meta.required && present(value) ? '' : html`<option value="">—</option>`
|
|
107
|
-
}${(meta.options ?? []).map(option => html`<option value="${option}"${value === option ? ' selected' : ''}>${option}</option>`)}</select>`,
|
|
108
|
-
read: ({ value }) => (present(value) ? html`<span>${asText(value)}</span>` : MUTED)
|
|
110
|
+
}${(meta.options ?? []).map(option => html`<option value="${option}"${value === option ? ' selected' : ''}>${optionLabel(meta, option)}</option>`)}</select>`,
|
|
111
|
+
read: ({ meta, value }) => (present(value) ? html`<span>${optionLabel(meta, asText(value))}</span>` : MUTED)
|
|
109
112
|
};
|
|
110
113
|
|
|
111
114
|
function refLink(meta: FieldMeta, id: string, refs: ResolveRef): Html {
|
package/src/admin/index.ts
CHANGED
|
@@ -9,8 +9,9 @@
|
|
|
9
9
|
*/
|
|
10
10
|
export { createAdmin, mountAdmin, DEFAULT_ASSETS } from './app.ts';
|
|
11
11
|
export { ADMIN_CSS, ADMIN_JS } from './assets.ts';
|
|
12
|
-
export { KIND, RENDERERS, renderField } from './fields.ts';
|
|
12
|
+
export { KIND, RENDERERS, optionLabel, renderField } from './fields.ts';
|
|
13
13
|
export type { Html, Kind, RefTarget, RenderInput, Renderer, ResolveRef } from './fields.ts';
|
|
14
14
|
export type {
|
|
15
|
-
ActionContext, AdminAction, AdminAssets, AdminSession, AdminOptions, ExternalCollection, ExternalRow
|
|
15
|
+
ActionContext, AdminAction, ComputedColumn, AdminAssets, AdminRelated, AdminSection, AdminSession, AdminOptions, ExternalCollection, ExternalRow,
|
|
16
|
+
RelatedContext
|
|
16
17
|
} from './types.ts';
|
package/src/admin/types.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** What a host gives the admin, and what it may add: external collections and actions. */
|
|
2
2
|
import type { Context } from 'hono';
|
|
3
|
-
import type { Cms, FieldBuilder, HostPrincipal, Operation, Principal } from '../core/index.ts';
|
|
3
|
+
import type { Cms, Entry, FieldBuilder, HostPrincipal, Operation, Principal } from '../core/index.ts';
|
|
4
4
|
|
|
5
5
|
/** What an action's `run` is told. */
|
|
6
6
|
export interface ActionContext<H extends HostPrincipal = never> {
|
|
@@ -49,13 +49,55 @@ export interface ExternalCollection<H extends HostPrincipal = never> {
|
|
|
49
49
|
fields: Record<string, FieldBuilder<any, any>>;
|
|
50
50
|
list(c: Context, page: { limit: number; offset: number }): Promise<ExternalRow[]>;
|
|
51
51
|
get(c: Context, id: string): Promise<ExternalRow | null>;
|
|
52
|
+
/** Several rows by id in one read, for the names a list's references show; `get` for each id when absent. */
|
|
53
|
+
getMany?(c: Context, ids: string[]): Promise<ExternalRow[]>;
|
|
52
54
|
actions?: AdminAction<H>[];
|
|
55
|
+
/** The fields its list shows after the display field, in order; the display field and State when absent. */
|
|
56
|
+
columns?: (string | ComputedColumn<ExternalRow>)[];
|
|
57
|
+
/** Lists of rows that belong to a row of this collection, on the row's page. */
|
|
58
|
+
related?: AdminRelated<H>[];
|
|
53
59
|
/** Who may see it: only the admin kind when absent. */
|
|
54
60
|
allow?(principal: Principal<H>): boolean;
|
|
55
61
|
/** Whether a row is offered when this collection is an action's target; every row but the one acted on when absent. */
|
|
56
62
|
pickable?(row: ExternalRow): boolean;
|
|
57
63
|
}
|
|
58
64
|
|
|
65
|
+
/** What a related list's `rows` is told: the entry or row whose page is being drawn. */
|
|
66
|
+
export interface RelatedContext<H extends HostPrincipal = never> {
|
|
67
|
+
c: Context;
|
|
68
|
+
principal: Principal<H>;
|
|
69
|
+
id: string;
|
|
70
|
+
/** The entry (a store type's page) or the row (an external collection's page). */
|
|
71
|
+
entry: Entry | ExternalRow;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* A read-only list on an entry's or row's page of rows that belong to it but are not its children: the
|
|
76
|
+
* revisions of a document, an author's posts. `table` is the store type or external collection the rows are of, and each row
|
|
77
|
+
* links to its page there.
|
|
78
|
+
*/
|
|
79
|
+
export interface AdminRelated<H extends HostPrincipal = never> {
|
|
80
|
+
table: string;
|
|
81
|
+
label: string;
|
|
82
|
+
/** The rows, or the first rows and how many there are in all. At most 50 are shown. */
|
|
83
|
+
rows(context: RelatedContext<H>): Promise<ExternalRow[] | { rows: ExternalRow[]; total: number }>;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A list column whose text the host computes from the entry or row, for what no one field holds. Shown as text. */
|
|
87
|
+
export interface ComputedColumn<R> {
|
|
88
|
+
name: string;
|
|
89
|
+
label: string;
|
|
90
|
+
value(row: R): string | null | undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** One heading of the home page: what the items are for, and the type or table ids under it, in order. */
|
|
94
|
+
export interface AdminSection {
|
|
95
|
+
title: string;
|
|
96
|
+
/** One line saying what the section is for. */
|
|
97
|
+
line?: string;
|
|
98
|
+
items: string[];
|
|
99
|
+
}
|
|
100
|
+
|
|
59
101
|
/** Where the admin's pages find the host's static files. Each is a URL the host serves. */
|
|
60
102
|
export interface AdminAssets {
|
|
61
103
|
largen: string;
|
|
@@ -88,6 +130,28 @@ export interface AdminOptions<H extends HostPrincipal = never> {
|
|
|
88
130
|
* page's own Unpublish or Delete, for a type whose host does more than the store does.
|
|
89
131
|
*/
|
|
90
132
|
typeActions?: Record<string, AdminAction<H>[]>;
|
|
133
|
+
/**
|
|
134
|
+
* The fields a store type's list shows after the display field, in order, by type id. A field, or a built-in
|
|
135
|
+
* column (`slug`, `status`, `owner_id`, `parent_id`, `created_at`, `updated_at`). A type with none shows the
|
|
136
|
+
* display field, slug, status, owner and when it was updated.
|
|
137
|
+
*/
|
|
138
|
+
typeColumns?: Record<string, (string | ComputedColumn<Entry>)[]>;
|
|
139
|
+
/**
|
|
140
|
+
* How an entry of a type is named wherever the admin names it (its list, its page, references, children, pickers),
|
|
141
|
+
* by type id: from the entry and, for a type with a parent, the parent's name. The display field when absent or
|
|
142
|
+
* when the function gives an empty string.
|
|
143
|
+
*/
|
|
144
|
+
typeTitles?: Record<string, (entry: Entry, parent: string | undefined) => string>;
|
|
145
|
+
/** Lists of rows that belong to a store type's entry and are not its children, on the entry's page, by type id. */
|
|
146
|
+
typeRelated?: Record<string, AdminRelated<H>[]>;
|
|
147
|
+
/** An external collection whose rows are the owners `owner_id` names; owners are then shown by name and linked. */
|
|
148
|
+
ownerTable?: string;
|
|
149
|
+
/**
|
|
150
|
+
* The home page, in sections. An item the caller may not read is left out, and a section left with none is not
|
|
151
|
+
* drawn. A type or table in no section keeps its pages. Absent, the home page lists every type the caller may
|
|
152
|
+
* read and every table.
|
|
153
|
+
*/
|
|
154
|
+
sections?: AdminSection[];
|
|
91
155
|
/** The path the host mounts the admin at, with no trailing slash; every link starts with it. */
|
|
92
156
|
mount: string;
|
|
93
157
|
siteName?: string;
|