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/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.1
|
|
4
|
+
|
|
5
|
+
- A list column may be computed: `{ name, label, value(entry) }` in `typeColumns`, or `value(row)` in a table's `columns`, for text no one field holds. It is shown as text.
|
|
6
|
+
- `typeTitles` on `createAdmin`: how an entry of a type is named, from the entry and its parent's name, wherever the admin names it (its list, its page and confirmations, references to it, its parent's list of children, and target pickers). A page's parent names cost one read. Absent, or when the function gives an empty string, the display field.
|
|
7
|
+
|
|
8
|
+
## 0.3.0
|
|
9
|
+
|
|
10
|
+
- **Changed:** when a type action's id is `publish`, `unpublish` or `delete`, that control's own route (`POST /t/:type/:id/publish`, `/unpublish`, `GET` and `POST /t/:type/:id/delete`) answers 404 for the type, as a control the caller lacks does. Before, the button was hidden but the route still ran the store's operation. A type action with the id `publish` now also hides the Publish button.
|
|
11
|
+
- `sections` on `createAdmin`: the home page in sections, each with a title, a line and its items (type or table ids) in order. An item the caller may not read is skipped, and an empty section is not drawn. Without it the home page is as before. A section naming no type or table is a `ConfigError`.
|
|
12
|
+
- The home page's title is the site's name, not "Content".
|
|
13
|
+
- `typeColumns` (by type id) and `columns` on an external collection: the fields a list shows after the display field. A reference shows the referred entry's name, resolved in one read per referred type for the whole page; a select shows its label; `parent_id` and `owner_id` may be columns. `ownerTable` names the external collection owners are shown through. An external collection may give `getMany` for one read of several rows.
|
|
14
|
+
- An entry's page lists its children of every type whose `parent` is its type and that the caller may read, up to 50, then "and N more" linking to the child list filtered by the new `?parent=` filter.
|
|
15
|
+
- `typeRelated` (by type id) and `related` on an external collection: read-only lists on an entry's or row's page of rows that belong to it, each linked to its page.
|
|
16
|
+
- `field.select` options may be `{ value, label }`. The admin shows and offers the label and stores the value; `FieldMeta.optionLabels` holds the labels. The value is still what the schema checks, so a posted label is refused.
|
|
17
|
+
|
|
3
18
|
## 0.2.1
|
|
4
19
|
|
|
5
20
|
- The package now ships compiled JavaScript (ES modules) with `.d.ts` declarations, declaration maps and source maps in `dist/`. `exports` point there, so Node 20 or later, Vitest and Node scripts can import it; Node refuses `.ts` files under `node_modules`. Wrangler and Bun are unaffected.
|
package/README.md
CHANGED
|
@@ -123,7 +123,7 @@ contentType({
|
|
|
123
123
|
});
|
|
124
124
|
```
|
|
125
125
|
|
|
126
|
-
Field builders: `text`, `longText`, `markdown`, `url`, `email`, `boolean`, `number`, `date`, `select(label, { options })
|
|
126
|
+
Field builders: `text`, `longText`, `markdown`, `url`, `email`, `boolean`, `number`, `date`, `select(label, { options })` (an option is its value, or `{ value, label }`: the admin shows the label and stores the value), `ref(type, label)`, `refs(type, label)`, `files`, `json`. A field may be `.required()`, `.default(v)`, `.min(n)`, `.max(n)` and `.system()` (written only by a grant that lists it). Values are checked with `@cfworker/json-schema`; a bad value is a `ValidationError`.
|
|
127
127
|
|
|
128
128
|
An entry has the type's fields in `data` and these built-in columns: `id`, `owner_id`, `slug`, `status` (`draft` or `published`), `parent_id`, `sort_key`, `parent_status`, `created_at`, `updated_at`. Their names are reserved as field names.
|
|
129
129
|
|
|
@@ -248,7 +248,28 @@ const host = new Hono().route('/admin', createAdmin({
|
|
|
248
248
|
|
|
249
249
|
The pages (type list, entry list, entry view and edit, delete confirmation, external collection list and row) are Hono routes rendered with `hono/html`. The admin is an ordinary client of `content.as(principal)` for the principal you resolve, so it can do nothing the type's rules refuse that caller; it offers a button only if `cms.access.rulesFor` says the caller may press it. Writes are forms that POST and redirect with 303, refused unless they come from the admin's own origin (`hono/csrf`), under a content security policy (`hono/secure-headers`).
|
|
250
250
|
|
|
251
|
-
Options: `externalCollections` (read-only views over your own tables, with `list`, `get`, `actions` and `allow`), `typeActions` (extra buttons on a type's entries; an action with the id `unpublish` or `delete` replaces the page's own), `session` (`{ signIn, signOut, signOutEverywhere }` as functions that answer a `Response`), `unauthorized` (what to answer when there is no principal and no `session`), and `assets`.
|
|
251
|
+
Options: `externalCollections` (read-only views over your own tables, with `list`, `get`, optional `getMany`, `actions`, `columns`, `related` and `allow`), `typeActions` (extra buttons on a type's entries; an action with the id `publish`, `unpublish` or `delete` replaces the page's own, and that control's own route then answers 404 for the type), `sections`, `typeColumns`, `typeRelated`, `typeTitles`, `ownerTable` (below), `session` (`{ signIn, signOut, signOutEverywhere }` as functions that answer a `Response`), `unauthorized` (what to answer when there is no principal and no `session`), and `assets`.
|
|
252
|
+
|
|
253
|
+
The home page lists every type the caller may read and every table, unless you arrange it in sections. A type or table left out of every section keeps its pages, and references still link to it:
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
createAdmin({
|
|
257
|
+
// ...
|
|
258
|
+
sections: [
|
|
259
|
+
{ title: 'Writing', line: 'What authors publish.', items: ['article', 'series'] },
|
|
260
|
+
{ title: 'People', line: 'Accounts and their handles.', items: ['accounts'] } // a table
|
|
261
|
+
],
|
|
262
|
+
typeColumns: { article: ['parent_id', 'visibility', 'owner_id'] }, // after the display field
|
|
263
|
+
typeRelated: {
|
|
264
|
+
article: [{ table: 'revisions', label: 'Revisions', rows: async ({ c, id }) => /* ExternalRow[] or { rows, total } */ }]
|
|
265
|
+
},
|
|
266
|
+
ownerTable: 'accounts', // owner_id shown by the account's name, linked
|
|
267
|
+
// An entry's name wherever the admin names it, from the entry and its parent's name:
|
|
268
|
+
typeTitles: { chapter: (e, series) => (series ? `${series}: ${e.data.title}` : '') }
|
|
269
|
+
});
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
A list with `columns` (a type's in `typeColumns`, a table's on the collection) shows the display field and those fields (or a computed column, `{ name, label, value(entry) }`, for text no one field holds): a reference by the referred entry's name (one read per referred type for the page), a select by its label, `parent_id` by the parent's name. An entry's page lists its children of every type whose `parent` is its type and that the caller may read (up to 50, then "and N more" linking to the child list filtered by `?parent=`), and each `related` list the host gives it.
|
|
252
273
|
|
|
253
274
|
Static files the admin links, which your Worker serves (default URLs in `DEFAULT_ASSETS`): Largen's `largen.css` and `largen-theme-dark.css` (the `largen` package; without them the pages are plain HTML), and the markdown editor: `admin-editor.js`, `admin-editor.css` and `admin-editor-dark.css`. The admin's own script and style are served by the admin itself at `<mount>/assets/`. If the editor does not load, a markdown field is a plain textarea.
|
|
254
275
|
|
package/dist/admin/app.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../../src/admin/app.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,IAAI,EAAgB,MAAM,MAAM,CAAC;AAI1C,OAAO,EAEyC,KAAK,aAAa,EACjE,MAAM,kBAAkB,CAAC;AAK1B,OAAO,KAAK,EAAe,WAAW,EAAE,YAAY,
|
|
1
|
+
{"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../../src/admin/app.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,IAAI,EAAgB,MAAM,MAAM,CAAC;AAI1C,OAAO,EAEyC,KAAK,aAAa,EACjE,MAAM,kBAAkB,CAAC;AAK1B,OAAO,KAAK,EAAe,WAAW,EAAE,YAAY,EAAiD,MAAM,YAAY,CAAC;AAMxH,eAAO,MAAM,cAAc,EAAE,WAM5B,CAAC;AA2BF,wBAAgB,WAAW,CAAC,CAAC,SAAS,aAAa,GAAG,KAAK,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CA8sBhG;AAED,6EAA6E;AAC7E,wBAAgB,UAAU,CAAC,CAAC,SAAS,aAAa,GAAG,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,IAAI,CAExI"}
|
package/dist/admin/app.js
CHANGED
|
@@ -19,7 +19,7 @@ import { ConfigError, Conflict, Forbidden, ValidationError, WriteRefused } from
|
|
|
19
19
|
import { ADMIN_CSS, ADMIN_JS } from "./assets.js";
|
|
20
20
|
import { parseForm } from "./forms.js";
|
|
21
21
|
import { can, mayWrite, mayWriteColumn, ruleRow, writable } from "./rules.js";
|
|
22
|
-
import { confirmPage, entryListPage, entryPage, externalListPage, externalRowPage, messagePage, noticeText, signInPage
|
|
22
|
+
import { confirmPage, entryListPage, entryPage, externalListPage, externalRowPage, homePage, messagePage, noticeText, signInPage } from "./views.js";
|
|
23
23
|
export const DEFAULT_ASSETS = {
|
|
24
24
|
largen: '/largen.css',
|
|
25
25
|
largenDark: '/largen-theme-dark.css',
|
|
@@ -31,6 +31,21 @@ const PAGE = 50;
|
|
|
31
31
|
const FORM = /^(application\/x-www-form-urlencoded|multipart\/form-data)\b/i;
|
|
32
32
|
/** Most rows offered in a target picker. */
|
|
33
33
|
const PICKER_CAP = 2000;
|
|
34
|
+
/** Most children or related rows listed on an entry's page. */
|
|
35
|
+
const BELONGING_CAP = 50;
|
|
36
|
+
/** Most children counted for "and N more". */
|
|
37
|
+
const COUNT_CAP = 1000;
|
|
38
|
+
/** Ids per read when resolving reference names. */
|
|
39
|
+
const NAME_CHUNK = 90;
|
|
40
|
+
/** The built-in columns a list may show, and their headings. */
|
|
41
|
+
const BUILTIN_COLUMNS = {
|
|
42
|
+
slug: 'Slug',
|
|
43
|
+
status: 'Status',
|
|
44
|
+
owner_id: 'Owner',
|
|
45
|
+
parent_id: 'Parent',
|
|
46
|
+
created_at: 'Created',
|
|
47
|
+
updated_at: 'Updated'
|
|
48
|
+
};
|
|
34
49
|
const status = (error, fallback) => {
|
|
35
50
|
const n = error?.status;
|
|
36
51
|
return typeof n === 'number' && n >= 400 && n < 600 ? n : fallback;
|
|
@@ -42,6 +57,66 @@ export function createAdmin(options) {
|
|
|
42
57
|
const shell = { mount, home: mount || '/', siteName: options.siteName ?? 'Admin', assets, session: Boolean(options.session) };
|
|
43
58
|
const externals = new Map((options.externalCollections ?? []).map(c => [c.id, c]));
|
|
44
59
|
const typeActions = options.typeActions ?? {};
|
|
60
|
+
const typeRelated = options.typeRelated ?? {};
|
|
61
|
+
const typeTitles = options.typeTitles ?? {};
|
|
62
|
+
for (const typeId of Object.keys(typeTitles)) {
|
|
63
|
+
if (!cms.types.has(typeId))
|
|
64
|
+
throw new ConfigError(`The admin names entries of "${typeId}", which is no type.`, typeId);
|
|
65
|
+
}
|
|
66
|
+
/** A host action with a built-in control's id takes its place: the control is not drawn and its route is refused. */
|
|
67
|
+
const replaced = (typeId, verb) => (typeActions[typeId] ?? []).some(a => a.id === verb);
|
|
68
|
+
// The host's arrangement names types, tables and fields; a name that matches nothing is a mistake in the host's config.
|
|
69
|
+
const known = (id) => cms.types.has(id) || externals.has(id);
|
|
70
|
+
for (const section of options.sections ?? []) {
|
|
71
|
+
for (const id of section.items) {
|
|
72
|
+
if (!known(id))
|
|
73
|
+
throw new ConfigError(`The admin's section "${section.title}" lists "${id}", which is no type or table.`, id);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (options.ownerTable !== undefined && !externals.has(options.ownerTable)) {
|
|
77
|
+
throw new ConfigError(`The admin's owner table "${options.ownerTable}" is no external collection.`, options.ownerTable);
|
|
78
|
+
}
|
|
79
|
+
const ownerMeta = () => options.ownerTable ? { label: 'Owner', fieldType: 'reference', refContentType: options.ownerTable, required: false, system: false } : undefined;
|
|
80
|
+
/** The columns of a store type's list, or undefined for the default. */
|
|
81
|
+
const typeColumns = new Map();
|
|
82
|
+
for (const [typeId, names] of Object.entries(options.typeColumns ?? {})) {
|
|
83
|
+
const type = cms.types.get(typeId);
|
|
84
|
+
if (!type)
|
|
85
|
+
throw new ConfigError(`The admin names columns for "${typeId}", which is no type.`, typeId);
|
|
86
|
+
typeColumns.set(typeId, names.filter(n => n !== type.displayField).map((column) => {
|
|
87
|
+
if (typeof column !== 'string')
|
|
88
|
+
return { name: column.name, label: column.label, value: column.value };
|
|
89
|
+
const name = column;
|
|
90
|
+
const meta = type.fieldMeta[name];
|
|
91
|
+
if (meta)
|
|
92
|
+
return { name, label: meta.label, meta };
|
|
93
|
+
if (name === 'parent_id' && type.parent) {
|
|
94
|
+
const parent = cms.types.get(type.parent);
|
|
95
|
+
return { name, label: parent?.name ?? 'Parent', meta: { label: parent?.name ?? 'Parent', fieldType: 'reference', refContentType: type.parent, required: false, system: false } };
|
|
96
|
+
}
|
|
97
|
+
if (name === 'owner_id' && type.owned)
|
|
98
|
+
return { name, label: 'Owner', meta: ownerMeta() };
|
|
99
|
+
if (name in BUILTIN_COLUMNS && name !== 'parent_id' && name !== 'owner_id')
|
|
100
|
+
return { name, label: BUILTIN_COLUMNS[name] };
|
|
101
|
+
throw new ConfigError(`The admin's columns for "${typeId}" name "${name}", which is not one of its fields or columns.`, typeId, name);
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
104
|
+
const tableColumns = new Map();
|
|
105
|
+
for (const collection of externals.values()) {
|
|
106
|
+
if (!collection.columns)
|
|
107
|
+
continue;
|
|
108
|
+
tableColumns.set(collection.id, collection.columns.filter(n => n !== collection.displayField).map((column) => {
|
|
109
|
+
if (typeof column !== 'string')
|
|
110
|
+
return { name: column.name, label: column.label, value: column.value };
|
|
111
|
+
const name = column;
|
|
112
|
+
const meta = collection.fields[name]?.meta;
|
|
113
|
+
if (meta)
|
|
114
|
+
return { name, label: meta.label, meta };
|
|
115
|
+
if (name === 'owner_id')
|
|
116
|
+
return { name, label: 'Owner', meta: ownerMeta() };
|
|
117
|
+
throw new ConfigError(`The columns of "${collection.id}" name "${name}", which is not one of its fields.`, collection.id, name);
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
45
120
|
const app = new Hono();
|
|
46
121
|
// ── Headers, assets, write checks, caller ─────────────────────────
|
|
47
122
|
const absolute = (c, url) => (/^https?:\/\//i.test(url) ? url : new URL(url, c.req.url).href);
|
|
@@ -157,50 +232,133 @@ export function createAdmin(options) {
|
|
|
157
232
|
const allowed = (collection, principal) => collection.allow ? collection.allow(principal) : principal.kind === 'admin';
|
|
158
233
|
const notice = (c) => noticeText(c.req.query('notice'));
|
|
159
234
|
const label = (type, e) => String(e.data[type.displayField] ?? '') || e.slug || e.id;
|
|
160
|
-
/**
|
|
161
|
-
|
|
235
|
+
/**
|
|
236
|
+
* The names of entries of one type, by id: the host's `typeTitles` (with each parent's name, one read per page) or the
|
|
237
|
+
* display field.
|
|
238
|
+
*/
|
|
239
|
+
async function titles(c, type, entries) {
|
|
240
|
+
const out = new Map();
|
|
241
|
+
const named = typeTitles[type.id];
|
|
242
|
+
const parents = new Map();
|
|
243
|
+
const parentType = named !== undefined && type.parent ? readable(c, type.parent) : undefined;
|
|
244
|
+
if (parentType) {
|
|
245
|
+
const ids = [...new Set(entries.map(e => e.parent_id).filter((id) => typeof id === 'string' && id !== ''))];
|
|
246
|
+
for (let i = 0; i < ids.length; i += NAME_CHUNK) {
|
|
247
|
+
const list = ids.slice(i, i + NAME_CHUNK);
|
|
248
|
+
for (const p of await apiOf(c).list(parentType.id, { where: { id: { in: list } }, limit: list.length }))
|
|
249
|
+
parents.set(p.id, label(parentType, p));
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
for (const e of entries)
|
|
253
|
+
out.set(e.id, (named?.(e, e.parent_id ? parents.get(e.parent_id) : undefined)) || label(type, e));
|
|
254
|
+
return out;
|
|
255
|
+
}
|
|
256
|
+
const titleOf = async (c, type, e) => (await titles(c, type, [e])).get(e.id) ?? label(type, e);
|
|
257
|
+
/** The name a row of a store type or a table is shown by. */
|
|
258
|
+
const rowLabel = (c, tableId, row) => {
|
|
259
|
+
const type = readable(c, tableId);
|
|
260
|
+
const display = type ? type.displayField : external(c, tableId)?.displayField;
|
|
261
|
+
return (display ? String(row[display] ?? '') : '') || (typeof row.slug === 'string' ? row.slug : '') || row.id;
|
|
262
|
+
};
|
|
263
|
+
const hrefOf = (c, tableId, id) => readable(c, tableId) ? `${mount}/t/${tableId}/${encodeURIComponent(id)}` : external(c, tableId) ? `${mount}/x/${tableId}/${encodeURIComponent(id)}` : null;
|
|
264
|
+
/**
|
|
265
|
+
* Where each reference field's ids lead and what to call them, for one entry or a whole list of them. Reads only
|
|
266
|
+
* what the caller may read, and one read per referred type for every id named (in chunks of 90).
|
|
267
|
+
*/
|
|
268
|
+
async function resolver(c, fields, rows) {
|
|
162
269
|
const wanted = new Map();
|
|
163
270
|
for (const [name, meta] of Object.entries(fields)) {
|
|
164
|
-
if ((meta.fieldType !== 'reference' && meta.fieldType !== 'references') || !meta.refContentType)
|
|
271
|
+
if (!meta || (meta.fieldType !== 'reference' && meta.fieldType !== 'references') || !meta.refContentType)
|
|
165
272
|
continue;
|
|
166
|
-
const value = data[name];
|
|
167
|
-
const ids = Array.isArray(value) ? value : typeof value === 'string' && value ? [value] : [];
|
|
168
273
|
const set = wanted.get(meta.refContentType) ?? new Set();
|
|
169
|
-
for (const
|
|
170
|
-
|
|
171
|
-
|
|
274
|
+
for (const data of rows) {
|
|
275
|
+
const value = data[name];
|
|
276
|
+
const ids = Array.isArray(value) ? value : typeof value === 'string' && value ? [value] : [];
|
|
277
|
+
for (const id of ids)
|
|
278
|
+
if (typeof id === 'string')
|
|
279
|
+
set.add(id);
|
|
280
|
+
}
|
|
172
281
|
wanted.set(meta.refContentType, set);
|
|
173
282
|
}
|
|
174
283
|
const names = new Map();
|
|
175
284
|
for (const [refType, ids] of wanted) {
|
|
176
|
-
const
|
|
177
|
-
if (
|
|
285
|
+
const all = [...ids];
|
|
286
|
+
if (all.length === 0)
|
|
178
287
|
continue;
|
|
179
288
|
const type = readable(c, refType);
|
|
180
289
|
const collection = external(c, refType);
|
|
181
290
|
if (type) {
|
|
182
|
-
for (
|
|
183
|
-
|
|
291
|
+
for (let i = 0; i < all.length; i += NAME_CHUNK) {
|
|
292
|
+
const list = all.slice(i, i + NAME_CHUNK);
|
|
293
|
+
const found = await apiOf(c).list(refType, { where: { id: { in: list } }, limit: list.length });
|
|
294
|
+
for (const [id, name] of await titles(c, type, found))
|
|
295
|
+
names.set(`${refType}:${id}`, name);
|
|
296
|
+
}
|
|
184
297
|
}
|
|
185
298
|
else if (collection) {
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
299
|
+
const found = collection.getMany
|
|
300
|
+
? await collection.getMany(c, all)
|
|
301
|
+
: (await Promise.all(all.slice(0, BELONGING_CAP).map(id => collection.get(c, id)))).filter((r) => r !== null);
|
|
302
|
+
for (const row of found)
|
|
303
|
+
names.set(`${refType}:${row.id}`, String(row[collection.displayField] ?? '') || row.id);
|
|
191
304
|
}
|
|
192
305
|
}
|
|
193
|
-
return (refType, id) => {
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
306
|
+
return (refType, id) => ({ href: hrefOf(c, refType, id), label: names.get(`${refType}:${id}`) ?? id });
|
|
307
|
+
}
|
|
308
|
+
/** The host's related lists for an entry or row, as the caller may read them. */
|
|
309
|
+
async function relatedLists(c, lists, id, entry) {
|
|
310
|
+
const out = [];
|
|
311
|
+
for (const list of lists) {
|
|
312
|
+
if (!readable(c, list.table) && !external(c, list.table))
|
|
313
|
+
continue;
|
|
314
|
+
const answer = await list.rows({ c, principal: principalOf(c), id, entry });
|
|
315
|
+
const rows = Array.isArray(answer) ? answer : answer.rows;
|
|
316
|
+
const total = Array.isArray(answer) ? rows.length : Math.max(answer.total, rows.length);
|
|
317
|
+
out.push({
|
|
318
|
+
label: list.label,
|
|
319
|
+
total,
|
|
320
|
+
items: rows.slice(0, BELONGING_CAP).map(row => ({
|
|
321
|
+
href: hrefOf(c, list.table, row.id),
|
|
322
|
+
label: rowLabel(c, list.table, row),
|
|
323
|
+
status: typeof row.state === 'string' ? row.state : typeof row.status === 'string' ? row.status : undefined
|
|
324
|
+
}))
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
return out;
|
|
328
|
+
}
|
|
329
|
+
/** An entry's children: the entries of every type whose parent is its type and that the caller may read. */
|
|
330
|
+
async function childLists(c, type, entry) {
|
|
331
|
+
const out = [];
|
|
332
|
+
for (const child of cms.types.values()) {
|
|
333
|
+
if (child.parent !== type.id || !readable(c, child.id))
|
|
334
|
+
continue;
|
|
335
|
+
const found = await apiOf(c).list(child.id, { where: { parent_id: entry.id }, orderBy: 'created_at', direction: 'asc', limit: COUNT_CAP + 1 });
|
|
336
|
+
const names = await titles(c, child, found.slice(0, BELONGING_CAP));
|
|
337
|
+
out.push({
|
|
338
|
+
label: child.name,
|
|
339
|
+
total: found.length,
|
|
340
|
+
more: `${mount}/t/${child.id}?parent=${encodeURIComponent(entry.id)}`,
|
|
341
|
+
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 }))
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
return out;
|
|
197
345
|
}
|
|
198
346
|
// ── Types ─────────────────────────────────────────────────────────
|
|
199
347
|
app.get('/', c => {
|
|
200
|
-
const
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
348
|
+
const item = (id) => {
|
|
349
|
+
const type = readable(c, id);
|
|
350
|
+
if (type)
|
|
351
|
+
return { href: `${mount}/t/${type.id}`, name: type.name };
|
|
352
|
+
const collection = external(c, id);
|
|
353
|
+
return collection ? { href: `${mount}/x/${collection.id}`, name: collection.name } : null;
|
|
354
|
+
};
|
|
355
|
+
const sections = options.sections
|
|
356
|
+
? options.sections.map(s => ({ title: s.title, line: s.line, items: s.items.map(item).filter(i => i !== null) }))
|
|
357
|
+
: [
|
|
358
|
+
{ title: 'Types', items: [...cms.types.values()].map(t => item(t.id)).filter(i => i !== null) },
|
|
359
|
+
{ title: 'Tables', items: [...externals.keys()].map(item).filter(i => i !== null) }
|
|
360
|
+
];
|
|
361
|
+
return c.html(homePage(shell, sections));
|
|
204
362
|
});
|
|
205
363
|
// ── Entry lists ───────────────────────────────────────────────────
|
|
206
364
|
app.get('/t/:type', async (c) => {
|
|
@@ -210,6 +368,7 @@ export function createAdmin(options) {
|
|
|
210
368
|
const q = (c.req.query('q') ?? '').trim();
|
|
211
369
|
const statusFilter = c.req.query('status') === 'published' || c.req.query('status') === 'draft' ? c.req.query('status') : '';
|
|
212
370
|
const owner = (c.req.query('owner') ?? '').trim();
|
|
371
|
+
const parent = type.parent ? (c.req.query('parent') ?? '').trim() : '';
|
|
213
372
|
const offset = Math.max(Math.trunc(Number(c.req.query('offset') ?? 0)) || 0, 0);
|
|
214
373
|
const conditions = [];
|
|
215
374
|
// The store's conditions are equality, so a slug search is exact.
|
|
@@ -219,6 +378,8 @@ export function createAdmin(options) {
|
|
|
219
378
|
conditions.push({ status: statusFilter });
|
|
220
379
|
if (owner && type.owned)
|
|
221
380
|
conditions.push({ owner_id: owner });
|
|
381
|
+
if (parent)
|
|
382
|
+
conditions.push({ parent_id: parent });
|
|
222
383
|
const found = await apiOf(c).list(type.id, {
|
|
223
384
|
...(conditions.length === 0 ? {} : { where: conditions.length === 1 ? conditions[0] : { and: conditions } }),
|
|
224
385
|
orderBy: 'updated_at',
|
|
@@ -226,9 +387,19 @@ export function createAdmin(options) {
|
|
|
226
387
|
limit: PAGE + 1,
|
|
227
388
|
offset
|
|
228
389
|
});
|
|
390
|
+
const entries = found.slice(0, PAGE);
|
|
391
|
+
const entryTitles = await titles(c, type, entries);
|
|
392
|
+
const columns = typeColumns.get(type.id);
|
|
393
|
+
const refs = columns
|
|
394
|
+
? await resolver(c, Object.fromEntries(columns.map(col => [col.name, col.meta])), entries.map(e => ({ ...e.data, owner_id: e.owner_id, parent_id: e.parent_id })))
|
|
395
|
+
: await resolver(c, {}, []);
|
|
229
396
|
return c.html(entryListPage(shell, {
|
|
230
397
|
type,
|
|
231
|
-
entries
|
|
398
|
+
entries,
|
|
399
|
+
titles: entryTitles,
|
|
400
|
+
columns,
|
|
401
|
+
refs,
|
|
402
|
+
parent,
|
|
232
403
|
q,
|
|
233
404
|
status: statusFilter,
|
|
234
405
|
owner: type.owned ? owner : '',
|
|
@@ -270,7 +441,8 @@ export function createAdmin(options) {
|
|
|
270
441
|
rows.push({ name, meta, value: shown(name), editable, error: state.fieldErrors?.[name] });
|
|
271
442
|
}
|
|
272
443
|
const data = Object.fromEntries(Object.keys(type.fieldMeta).map(name => [name, shown(name)]));
|
|
273
|
-
const refs = await resolver(c, type.fieldMeta, data);
|
|
444
|
+
const refs = await resolver(c, type.fieldMeta, [data]);
|
|
445
|
+
const lists = entry ? [...(await childLists(c, type, entry)), ...(await relatedLists(c, typeRelated[type.id] ?? [], entry.id, entry))] : [];
|
|
274
446
|
const actions = entry
|
|
275
447
|
? (typeActions[type.id] ?? []).filter(a => (a.requires ? can(rules, type.id, a.requires, row) : true))
|
|
276
448
|
: [];
|
|
@@ -281,11 +453,13 @@ export function createAdmin(options) {
|
|
|
281
453
|
rows,
|
|
282
454
|
refs,
|
|
283
455
|
canSave: columns.some(col => col.editable) || rows.some(r => r.editable),
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
canUnpublish: !!entry && can(rules, type.id, 'publish', row) && !(
|
|
287
|
-
canDelete: !!entry && can(rules, type.id, 'delete', row) && !(
|
|
456
|
+
// A type's own `publish`, `unpublish` and `delete` actions take the place of the plain controls.
|
|
457
|
+
canPublish: !!entry && can(rules, type.id, 'publish', row) && !replaced(type.id, 'publish'),
|
|
458
|
+
canUnpublish: !!entry && can(rules, type.id, 'publish', row) && !replaced(type.id, 'unpublish'),
|
|
459
|
+
canDelete: !!entry && can(rules, type.id, 'delete', row) && !replaced(type.id, 'delete'),
|
|
288
460
|
actions,
|
|
461
|
+
belongings: lists,
|
|
462
|
+
title: entry ? await titleOf(c, type, entry) : undefined,
|
|
289
463
|
notice: notice(c),
|
|
290
464
|
problems: state.problems
|
|
291
465
|
});
|
|
@@ -374,7 +548,8 @@ export function createAdmin(options) {
|
|
|
374
548
|
for (const verb of ['publish', 'unpublish']) {
|
|
375
549
|
app.post(`/t/:type/:id/${verb}`, async (c) => {
|
|
376
550
|
const { type, entry } = await entryOf(c);
|
|
377
|
-
|
|
551
|
+
// A replaced control is refused at its route, the same answer as a control the caller lacks.
|
|
552
|
+
if (!type || !entry || replaced(type.id, verb))
|
|
378
553
|
return notFound(c);
|
|
379
554
|
await apiOf(c)[verb](type.id, entry.id);
|
|
380
555
|
return c.redirect(`${mount}/t/${type.id}/${encodeURIComponent(entry.id)}?notice=${verb === 'publish' ? 'published' : 'unpublished'}`, 303);
|
|
@@ -382,11 +557,11 @@ export function createAdmin(options) {
|
|
|
382
557
|
}
|
|
383
558
|
app.get('/t/:type/:id/delete', async (c) => {
|
|
384
559
|
const { type, entry } = await entryOf(c);
|
|
385
|
-
if (!type || !entry)
|
|
560
|
+
if (!type || !entry || replaced(type.id, 'delete'))
|
|
386
561
|
return notFound(c);
|
|
387
562
|
if (!can(rulesOf(c), type.id, 'delete', ruleRow(type, entry)))
|
|
388
563
|
return notFound(c);
|
|
389
|
-
const name =
|
|
564
|
+
const name = await titleOf(c, type, entry);
|
|
390
565
|
return c.html(confirmPage(shell, {
|
|
391
566
|
title: `Delete ${name}?`,
|
|
392
567
|
question: `Delete “${name}”? This cannot be undone.`,
|
|
@@ -399,7 +574,7 @@ export function createAdmin(options) {
|
|
|
399
574
|
});
|
|
400
575
|
app.post('/t/:type/:id/delete', async (c) => {
|
|
401
576
|
const { type, entry } = await entryOf(c);
|
|
402
|
-
if (!type || !entry)
|
|
577
|
+
if (!type || !entry || replaced(type.id, 'delete'))
|
|
403
578
|
return notFound(c);
|
|
404
579
|
await apiOf(c).remove(type.id, entry.id);
|
|
405
580
|
return c.redirect(`${mount}/t/${type.id}?notice=deleted`, 303);
|
|
@@ -427,9 +602,10 @@ export function createAdmin(options) {
|
|
|
427
602
|
return null;
|
|
428
603
|
for (let offset = 0; offset < PICKER_CAP; offset += 1000) {
|
|
429
604
|
const rows = await apiOf(c).list(type.id, { limit: 1000, offset });
|
|
605
|
+
const names = await titles(c, type, rows);
|
|
430
606
|
for (const e of rows)
|
|
431
607
|
if (e.id !== selfId)
|
|
432
|
-
options.push({ id: e.id, label: label(type, e) });
|
|
608
|
+
options.push({ id: e.id, label: names.get(e.id) ?? label(type, e) });
|
|
433
609
|
if (rows.length < 1000)
|
|
434
610
|
break;
|
|
435
611
|
}
|
|
@@ -484,7 +660,7 @@ export function createAdmin(options) {
|
|
|
484
660
|
const action = (typeActions[type.id] ?? []).find(a => a.id === c.req.param('action'));
|
|
485
661
|
if (!action || (action.requires && !can(rulesOf(c), type.id, action.requires, ruleRow(type, entry))))
|
|
486
662
|
return null;
|
|
487
|
-
const name =
|
|
663
|
+
const name = await titleOf(c, type, entry);
|
|
488
664
|
return {
|
|
489
665
|
action,
|
|
490
666
|
id: entry.id,
|
|
@@ -529,15 +705,19 @@ export function createAdmin(options) {
|
|
|
529
705
|
return notFound(c);
|
|
530
706
|
const offset = Math.max(Math.trunc(Number(c.req.query('offset') ?? 0)) || 0, 0);
|
|
531
707
|
const rows = await collection.list(c, { limit: PAGE + 1, offset });
|
|
532
|
-
|
|
708
|
+
const shown = rows.slice(0, PAGE);
|
|
709
|
+
const columns = tableColumns.get(collection.id);
|
|
710
|
+
const refs = columns ? await resolver(c, Object.fromEntries(columns.map(col => [col.name, col.meta])), shown) : undefined;
|
|
711
|
+
return c.html(externalListPage(shell, collection, shown, offset, PAGE, rows.length > PAGE, columns, refs));
|
|
533
712
|
});
|
|
534
713
|
app.get('/x/:collection/:id', async (c) => {
|
|
535
714
|
const collection = external(c, c.req.param('collection'));
|
|
536
715
|
const row = await collection?.get(c, c.req.param('id'));
|
|
537
716
|
if (!collection || !row)
|
|
538
717
|
return notFound(c);
|
|
539
|
-
const refs = await resolver(c, Object.fromEntries(Object.entries(collection.fields).map(([n, b]) => [n, b.meta])), row);
|
|
540
|
-
|
|
718
|
+
const refs = await resolver(c, Object.fromEntries(Object.entries(collection.fields).map(([n, b]) => [n, b.meta])), [row]);
|
|
719
|
+
const related = await relatedLists(c, collection.related ?? [], row.id, row);
|
|
720
|
+
return c.html(externalRowPage(shell, collection, row, refs, collection.actions ?? [], notice(c), related));
|
|
541
721
|
});
|
|
542
722
|
app.get('/x/:collection/:id/do/:action', async (c) => {
|
|
543
723
|
const site = await externalSite(c);
|