@easy-cms/plugin-nested-docs 0.21.0
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/LICENSE +21 -0
- package/README.md +23 -0
- package/dist/admin.js +10 -0
- package/dist/index.d.ts +97 -0
- package/dist/index.js +505 -0
- package/package.json +51 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kanawoot K.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# @easy-cms/plugin-nested-docs
|
|
2
|
+
|
|
3
|
+
Nested pages for [Easy CMS](https://maritonx.github.io/easy-cms/): a parent for each page, its
|
|
4
|
+
breadcrumbs and full path (`/about/team`) kept up to date when a page above it moves, and a tree
|
|
5
|
+
in the admin's list.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { nestedDocsPlugin } from '@easy-cms/plugin-nested-docs'
|
|
9
|
+
|
|
10
|
+
export default defineConfig({
|
|
11
|
+
// …
|
|
12
|
+
plugins: [nestedDocsPlugin({ collections: ['pages'] })],
|
|
13
|
+
})
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { findByPath, getTree } from '@easy-cms/plugin-nested-docs'
|
|
18
|
+
|
|
19
|
+
const page = await findByPath(cms, 'pages', '/about/team')
|
|
20
|
+
const menu = await getTree(cms, 'pages', { depth: 2 })
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
See [Nested pages](https://maritonx.github.io/easy-cms/guide/nested-docs).
|
package/dist/admin.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
var c={en:{top:"A top-level page",unsaved:"Save the page to see where it sits.",children:"{n} pages under it",child:"1 page under it",none:"No pages under it",view:"View them",trail:"Where this page sits"},th:{top:"\u0E2B\u0E19\u0E49\u0E32\u0E23\u0E30\u0E14\u0E31\u0E1A\u0E1A\u0E19\u0E2A\u0E38\u0E14",unsaved:"\u0E1A\u0E31\u0E19\u0E17\u0E36\u0E01\u0E2B\u0E19\u0E49\u0E32\u0E01\u0E48\u0E2D\u0E19\u0E40\u0E1E\u0E37\u0E48\u0E2D\u0E14\u0E39\u0E15\u0E33\u0E41\u0E2B\u0E19\u0E48\u0E07\u0E02\u0E2D\u0E07\u0E2B\u0E19\u0E49\u0E32\u0E19\u0E35\u0E49",children:"\u0E21\u0E35\u0E2B\u0E19\u0E49\u0E32\u0E22\u0E48\u0E2D\u0E22 {n} \u0E2B\u0E19\u0E49\u0E32",child:"\u0E21\u0E35\u0E2B\u0E19\u0E49\u0E32\u0E22\u0E48\u0E2D\u0E22 1 \u0E2B\u0E19\u0E49\u0E32",none:"\u0E22\u0E31\u0E07\u0E44\u0E21\u0E48\u0E21\u0E35\u0E2B\u0E19\u0E49\u0E32\u0E22\u0E48\u0E2D\u0E22",view:"\u0E14\u0E39\u0E2B\u0E19\u0E49\u0E32\u0E22\u0E48\u0E2D\u0E22",trail:"\u0E15\u0E33\u0E41\u0E2B\u0E19\u0E48\u0E07\u0E02\u0E2D\u0E07\u0E2B\u0E19\u0E49\u0E32\u0E19\u0E35\u0E49"}},o=r=>r.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]),m=`
|
|
2
|
+
:host { display: block; font: inherit; color: var(--text); }
|
|
3
|
+
ol { display: flex; flex-wrap: wrap; gap: 0.25rem; margin: 0 0 0.5rem; padding: 0; list-style: none; font-size: 0.875rem; }
|
|
4
|
+
li { display: inline-flex; align-items: center; gap: 0.25rem; }
|
|
5
|
+
li + li::before { content: '\u203A'; color: var(--faint); }
|
|
6
|
+
li[aria-current] { font-weight: 600; }
|
|
7
|
+
p { margin: 0 0 0.4rem; font-size: 0.8rem; color: var(--text-muted); }
|
|
8
|
+
a { color: var(--accent-ink, var(--text)); font-size: 0.8rem; font-weight: 500; }
|
|
9
|
+
a:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
|
|
10
|
+
`,a=class r extends HTMLElement{props={};total=null;loadedFor;static{for(let t of["doc","id","uiLocale","options","api","collection","value","path","global","locale","readOnly","field","label"])Object.defineProperty(r.prototype,t,{get(){return this.props[t]},set(e){this.props[t]=e,this.render()}})}constructor(){super(),this.attachShadow({mode:"open"})}connectedCallback(){this.render()}t(t,e){return(this.props.uiLocale==="th"?c.th:c.en)[t].replace("{n}",String(e??""))}async count(t,e){let n=this.props.api,i=this.props.collection;if(!(!n||typeof i!="string"||t===this.loadedFor)){this.loadedFor=t;try{let s=await n("GET",`/${i}?where[${e.parentField}][equals]=${encodeURIComponent(String(t))}&limit=1&depth=0&draft=true`);this.total=s.totalDocs??0}catch{this.total=null}this.render()}}render(){let t=this.shadowRoot;if(!t)return;let e=this.props.options??{},n=this.props.id,i=Array.isArray(this.props.value)?this.props.value:[],s;if(n==null)s=`<p>${o(this.t("unsaved"))}</p>`;else{this.count(n,e);let h=i.length<=1?`<p>${o(this.t("top"))}</p>`:`<ol aria-label="${o(this.t("trail"))}">${i.map((l,g)=>{let p=o(String(l.label||l.url||"\u2014"));return g===i.length-1?`<li aria-current="page">${p}</li>`:`<li>${p}</li>`}).join("")}</ol>`,d=`${e.adminPath}/collections/${String(this.props.collection)}?f_${e.parentField}=${encodeURIComponent(String(n))}`,u=this.total===null?"":this.total===0?`<p>${o(this.t("none"))}</p>`:`<p>${o(this.total===1?this.t("child"):this.t("children",this.total))} \xB7 <a href="${o(d)}">${o(this.t("view"))}</a></p>`;s=h+u}t.innerHTML=`<style>${m}</style>${s}`}};customElements.get("ecms-nested-breadcrumbs")||customElements.define("ecms-nested-breadcrumbs",a);
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { AccessOptions, Plugin } from '@easy-cms/core';
|
|
2
|
+
|
|
3
|
+
type ID = string | number;
|
|
4
|
+
type Doc = Record<string, unknown>;
|
|
5
|
+
/** One step of a page's trail, from the top-level page down to the page itself. */
|
|
6
|
+
interface Breadcrumb {
|
|
7
|
+
/** The page's id; `null` on the page's own step while it is being created. */
|
|
8
|
+
readonly doc: ID | null;
|
|
9
|
+
readonly label: string;
|
|
10
|
+
/** The page's path, e.g. `/about/team`. */
|
|
11
|
+
readonly url: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* What the helpers use of `EasyCMS`: an instance typed with your config fits (its methods take
|
|
15
|
+
* your collection slugs, not any string).
|
|
16
|
+
*/
|
|
17
|
+
interface NestedCMS {
|
|
18
|
+
readonly config: {
|
|
19
|
+
readonly endpoints: readonly {
|
|
20
|
+
readonly handler: unknown;
|
|
21
|
+
}[];
|
|
22
|
+
};
|
|
23
|
+
find(collection: string, options?: Record<string, unknown>): Promise<unknown>;
|
|
24
|
+
}
|
|
25
|
+
/** `/about/team` from what a visitor's URL or an editor typed: one leading slash, none at the end. */
|
|
26
|
+
declare function normalizePath(path: string): string;
|
|
27
|
+
|
|
28
|
+
interface FindByPathOptions extends AccessOptions {
|
|
29
|
+
/** The content locale of the path. Default: the default locale. */
|
|
30
|
+
readonly locale?: string;
|
|
31
|
+
/** Include drafts (for previews). Default false: published pages only. */
|
|
32
|
+
readonly draft?: boolean;
|
|
33
|
+
/** Relationship levels to populate. Default 1. */
|
|
34
|
+
readonly depth?: number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The page at a path, e.g. `findByPath(cms, 'pages', '/about/team')`, or `null`. The path is
|
|
38
|
+
* the page's own: take the locale prefix or other routing off first.
|
|
39
|
+
*/
|
|
40
|
+
declare function findByPath(instance: NestedCMS, collection: string, path: string, options?: FindByPathOptions): Promise<Doc | null>;
|
|
41
|
+
/** A page in `getTree()`: what a menu or sidebar needs, and the pages under it. */
|
|
42
|
+
interface TreeNode {
|
|
43
|
+
readonly id: ID;
|
|
44
|
+
readonly title: string;
|
|
45
|
+
readonly slug: string;
|
|
46
|
+
readonly path: string | null;
|
|
47
|
+
readonly children: TreeNode[];
|
|
48
|
+
}
|
|
49
|
+
interface GetTreeOptions extends AccessOptions {
|
|
50
|
+
readonly locale?: string;
|
|
51
|
+
/** Levels to include, e.g. 2 for a menu with one level of submenus. Default: all. */
|
|
52
|
+
readonly depth?: number;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Published pages as a tree, top-level pages first, in the list's order (`admin.list.sort`,
|
|
56
|
+
* else by title). Pages under an unpublished page are left out with it.
|
|
57
|
+
*/
|
|
58
|
+
declare function getTree(instance: NestedCMS, collection: string, options?: GetTreeOptions): Promise<TreeNode[]>;
|
|
59
|
+
/**
|
|
60
|
+
* Works out every page's breadcrumbs and path again, from the top level down, and saves the
|
|
61
|
+
* pages whose values changed. For pages that existed before the plugin, or to repair them.
|
|
62
|
+
* Pages whose parent was deleted move to the top level.
|
|
63
|
+
*/
|
|
64
|
+
declare function rebuildNestedDocs(instance: NestedCMS, collection: string): Promise<{
|
|
65
|
+
checked: number;
|
|
66
|
+
updated: number;
|
|
67
|
+
}>;
|
|
68
|
+
|
|
69
|
+
interface NestedDocsPluginOptions {
|
|
70
|
+
/** Collections whose documents can have a parent in the same collection, e.g. `['pages']`. */
|
|
71
|
+
readonly collections: readonly string[];
|
|
72
|
+
/** The slug field each page adds to its parent's path. Default `slug`. */
|
|
73
|
+
readonly slugField?: string;
|
|
74
|
+
/** The field shown in breadcrumbs. Default the collection's `useAsTitle`, else the slug. */
|
|
75
|
+
readonly titleField?: string;
|
|
76
|
+
/** Names of the fields the plugin adds. Default `parent`, `breadcrumbs` and `path`. */
|
|
77
|
+
readonly fields?: {
|
|
78
|
+
readonly parent?: string;
|
|
79
|
+
readonly breadcrumbs?: string;
|
|
80
|
+
readonly path?: string;
|
|
81
|
+
};
|
|
82
|
+
/** Levels of pages, top level included. Default 10. */
|
|
83
|
+
readonly maxDepth?: number;
|
|
84
|
+
/**
|
|
85
|
+
* Deleting a page that has pages under it: `restrict` refuses (move or delete them first),
|
|
86
|
+
* `orphan` moves them to the top level (their addresses change). Default `restrict`.
|
|
87
|
+
*/
|
|
88
|
+
readonly onDeleteParent?: 'restrict' | 'orphan';
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Pages inside pages: a parent for each document, its breadcrumbs and its full path
|
|
92
|
+
* (`/about/team`), kept up to date when a page above it moves or changes its slug, and a tree
|
|
93
|
+
* in the admin's list.
|
|
94
|
+
*/
|
|
95
|
+
declare function nestedDocsPlugin(options: NestedDocsPluginOptions): Plugin;
|
|
96
|
+
|
|
97
|
+
export { type Breadcrumb, type FindByPathOptions, type GetTreeOptions, type NestedCMS, type NestedDocsPluginOptions, type TreeNode, findByPath, getTree, nestedDocsPlugin, normalizePath, rebuildNestedDocs };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
// src/shared.ts
|
|
2
|
+
var NESTED_SOURCE = /* @__PURE__ */ Symbol.for("easy-cms.plugin-nested-docs.source");
|
|
3
|
+
var localApi = (cms) => cms;
|
|
4
|
+
function nestedOf(cms, collection) {
|
|
5
|
+
for (const endpoint of cms.config.endpoints) {
|
|
6
|
+
const source = endpoint.handler[NESTED_SOURCE];
|
|
7
|
+
const nested = source?.collections.get(collection);
|
|
8
|
+
if (source && nested) return { source, nested };
|
|
9
|
+
}
|
|
10
|
+
throw new Error(
|
|
11
|
+
`nestedDocsPlugin: "${collection}" is not nested; add it to nestedDocsPlugin({ collections })`
|
|
12
|
+
);
|
|
13
|
+
}
|
|
14
|
+
function idOf(value) {
|
|
15
|
+
if (value && typeof value === "object" && "id" in value) return idOf(value.id);
|
|
16
|
+
return typeof value === "number" || typeof value === "string" && value !== "" ? value : null;
|
|
17
|
+
}
|
|
18
|
+
function normalizePath(path) {
|
|
19
|
+
const parts = path.split(/[?#]/)[0]?.split("/").filter(Boolean).map((part) => {
|
|
20
|
+
try {
|
|
21
|
+
return decodeURIComponent(part);
|
|
22
|
+
} catch {
|
|
23
|
+
return part;
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
return `/${(parts ?? []).join("/")}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// src/tree.ts
|
|
30
|
+
import { randomUUID } from "crypto";
|
|
31
|
+
var all = (source) => source.locales.length > 0 ? { locale: "all" } : {};
|
|
32
|
+
function textIn(value, locale, source) {
|
|
33
|
+
if (value && typeof value === "object") {
|
|
34
|
+
const map = value;
|
|
35
|
+
const found = (locale !== null ? map[locale] : void 0) ?? map[source.defaultLocale ?? ""];
|
|
36
|
+
return typeof found === "string" ? found : "";
|
|
37
|
+
}
|
|
38
|
+
return typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
|
|
39
|
+
}
|
|
40
|
+
function rowsIn(value, locale, source) {
|
|
41
|
+
if (Array.isArray(value)) return value;
|
|
42
|
+
if (value && typeof value === "object") {
|
|
43
|
+
const map = value;
|
|
44
|
+
const found = (locale !== null ? map[locale] : void 0) ?? map[source.defaultLocale ?? ""];
|
|
45
|
+
return Array.isArray(found) ? found : [];
|
|
46
|
+
}
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
var localesOf = (nested, source) => nested.localized ? [...source.locales] : [null];
|
|
50
|
+
async function liveDoc(cms, source, nested, id) {
|
|
51
|
+
const options = { depth: 0, ...all(source) };
|
|
52
|
+
const live = await cms.findById(nested.slug, id, options);
|
|
53
|
+
if (live || !nested.drafts) return live;
|
|
54
|
+
return cms.findById(nested.slug, id, { ...options, draft: true });
|
|
55
|
+
}
|
|
56
|
+
async function liveChildren(cms, source, nested, id) {
|
|
57
|
+
const where = id === void 0 ? {} : { [nested.parentField]: { equals: id } };
|
|
58
|
+
const options = { limit: 0, depth: 0, sort: nested.sort, ...all(source) };
|
|
59
|
+
const live = await cms.find(nested.slug, { ...options, where });
|
|
60
|
+
if (!nested.drafts) return live.docs;
|
|
61
|
+
const unpublished = await cms.find(nested.slug, {
|
|
62
|
+
...options,
|
|
63
|
+
where: { and: [where, { status: { equals: "draft" } }] },
|
|
64
|
+
draft: true
|
|
65
|
+
});
|
|
66
|
+
return [...live.docs, ...unpublished.docs];
|
|
67
|
+
}
|
|
68
|
+
async function descendants(cms, nested, id) {
|
|
69
|
+
const found = [];
|
|
70
|
+
const seen = /* @__PURE__ */ new Set([String(id)]);
|
|
71
|
+
let level = [id];
|
|
72
|
+
for (let depth = 0; level.length > 0 && depth <= nested.maxDepth; depth++) {
|
|
73
|
+
const children = await cms.find(nested.slug, {
|
|
74
|
+
where: { [nested.parentField]: { in: level } },
|
|
75
|
+
limit: 0,
|
|
76
|
+
depth: 0,
|
|
77
|
+
draft: true
|
|
78
|
+
});
|
|
79
|
+
level = [];
|
|
80
|
+
for (const child of children.docs) {
|
|
81
|
+
const childId = child.id;
|
|
82
|
+
if (seen.has(String(childId))) continue;
|
|
83
|
+
seen.add(String(childId));
|
|
84
|
+
found.push(childId);
|
|
85
|
+
level.push(childId);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return found;
|
|
89
|
+
}
|
|
90
|
+
async function trailOf(cms, source, nested, data, selfId, parent) {
|
|
91
|
+
const parentId = idOf(data[nested.parentField]);
|
|
92
|
+
const parentDoc = parent !== void 0 ? parent : parentId === null ? null : await liveDoc(cms, source, nested, parentId);
|
|
93
|
+
const breadcrumbs = /* @__PURE__ */ new Map();
|
|
94
|
+
const path = /* @__PURE__ */ new Map();
|
|
95
|
+
for (const locale of localesOf(nested, source)) {
|
|
96
|
+
const above = parentDoc ? rowsIn(parentDoc[nested.breadcrumbsField], locale, source) : [];
|
|
97
|
+
const parentPath = parentDoc ? textIn(parentDoc[nested.pathField], locale, source) : "";
|
|
98
|
+
const slug = textIn(data[nested.slugField], locale, source);
|
|
99
|
+
const own = slug && (parentDoc === null || parentPath) ? `${parentPath}/${slug}` : null;
|
|
100
|
+
const label = textIn(data[nested.titleField], locale, source) || slug;
|
|
101
|
+
breadcrumbs.set(locale, [
|
|
102
|
+
...above.map((row) => ({
|
|
103
|
+
id: randomUUID(),
|
|
104
|
+
doc: idOf(row.doc),
|
|
105
|
+
label: typeof row.label === "string" ? row.label : "",
|
|
106
|
+
url: typeof row.url === "string" ? row.url : ""
|
|
107
|
+
})),
|
|
108
|
+
{ id: randomUUID(), doc: selfId, label, url: own ?? "" }
|
|
109
|
+
]);
|
|
110
|
+
path.set(locale, own);
|
|
111
|
+
}
|
|
112
|
+
return { breadcrumbs, path };
|
|
113
|
+
}
|
|
114
|
+
function trailData(nested, trail) {
|
|
115
|
+
const value = (map) => nested.localized ? Object.fromEntries(map) : map.get(null);
|
|
116
|
+
return {
|
|
117
|
+
[nested.breadcrumbsField]: value(trail.breadcrumbs),
|
|
118
|
+
[nested.pathField]: value(trail.path)
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
function hasTrail(source, nested, doc, trail) {
|
|
122
|
+
for (const locale of localesOf(nested, source)) {
|
|
123
|
+
const stored = rowsIn(doc[nested.breadcrumbsField], locale, source).map((row) => [
|
|
124
|
+
idOf(row.doc),
|
|
125
|
+
row.label ?? "",
|
|
126
|
+
row.url ?? ""
|
|
127
|
+
]);
|
|
128
|
+
const wanted = (trail.breadcrumbs.get(locale) ?? []).map((row) => [row.doc, row.label, row.url]);
|
|
129
|
+
if (JSON.stringify(stored) !== JSON.stringify(wanted)) return false;
|
|
130
|
+
const storedPath = textIn(doc[nested.pathField], locale, source) || null;
|
|
131
|
+
if (storedPath !== (trail.path.get(locale) ?? null)) return false;
|
|
132
|
+
}
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
async function syncChildren(cms, source, nested, id) {
|
|
136
|
+
const parent = await liveDoc(cms, source, nested, id);
|
|
137
|
+
if (!parent) return 0;
|
|
138
|
+
let saved = 0;
|
|
139
|
+
for (const child of await liveChildren(cms, source, nested, id)) {
|
|
140
|
+
const trail = await trailOf(cms, source, nested, child, child.id, parent);
|
|
141
|
+
if (hasTrail(source, nested, child, trail)) continue;
|
|
142
|
+
await cms.update(nested.slug, child.id, {}, { live: true });
|
|
143
|
+
saved++;
|
|
144
|
+
}
|
|
145
|
+
return saved;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// src/helpers.ts
|
|
149
|
+
async function findByPath(instance, collection, path, options = {}) {
|
|
150
|
+
const cms = localApi(instance);
|
|
151
|
+
const { nested } = nestedOf(cms, collection);
|
|
152
|
+
const found = await cms.find(collection, {
|
|
153
|
+
...options,
|
|
154
|
+
where: { [nested.pathField]: { equals: normalizePath(path) } },
|
|
155
|
+
limit: 1
|
|
156
|
+
});
|
|
157
|
+
return found.docs[0] ?? null;
|
|
158
|
+
}
|
|
159
|
+
async function getTree(instance, collection, options = {}) {
|
|
160
|
+
const cms = localApi(instance);
|
|
161
|
+
const { nested } = nestedOf(cms, collection);
|
|
162
|
+
const { docs } = await cms.find(collection, {
|
|
163
|
+
...options,
|
|
164
|
+
limit: 0,
|
|
165
|
+
depth: 0,
|
|
166
|
+
sort: nested.sort
|
|
167
|
+
});
|
|
168
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
169
|
+
for (const doc of docs) {
|
|
170
|
+
const text = (value) => typeof value === "string" ? value : "";
|
|
171
|
+
nodes.set(String(doc.id), {
|
|
172
|
+
id: doc.id,
|
|
173
|
+
title: text(doc[nested.titleField]) || text(doc[nested.slugField]),
|
|
174
|
+
slug: text(doc[nested.slugField]),
|
|
175
|
+
path: text(doc[nested.pathField]) || null,
|
|
176
|
+
children: []
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
const roots = [];
|
|
180
|
+
for (const doc of docs) {
|
|
181
|
+
const node = nodes.get(String(doc.id));
|
|
182
|
+
const parentId = idOf(doc[nested.parentField]);
|
|
183
|
+
if (parentId === null) roots.push(node);
|
|
184
|
+
else nodes.get(String(parentId))?.children.push(node);
|
|
185
|
+
}
|
|
186
|
+
const max = options.depth ?? Number.POSITIVE_INFINITY;
|
|
187
|
+
const cut = (list, level) => list.map((node) => ({ ...node, children: level < max ? cut(node.children, level + 1) : [] }));
|
|
188
|
+
return cut(roots, 1);
|
|
189
|
+
}
|
|
190
|
+
async function rebuildNestedDocs(instance, collection) {
|
|
191
|
+
const cms = localApi(instance);
|
|
192
|
+
const { source, nested } = nestedOf(cms, collection);
|
|
193
|
+
const snapshot = async () => {
|
|
194
|
+
const docs = await liveChildren(cms, source, nested, void 0);
|
|
195
|
+
return new Map(
|
|
196
|
+
docs.map((d) => [
|
|
197
|
+
String(d.id),
|
|
198
|
+
JSON.stringify([d[nested.pathField], stripIds(d[nested.breadcrumbsField])])
|
|
199
|
+
])
|
|
200
|
+
);
|
|
201
|
+
};
|
|
202
|
+
const before = await snapshot();
|
|
203
|
+
const seen = /* @__PURE__ */ new Set();
|
|
204
|
+
const visit = async (docs, parent) => {
|
|
205
|
+
for (const listed of docs) {
|
|
206
|
+
const id = listed.id;
|
|
207
|
+
if (seen.has(String(id))) continue;
|
|
208
|
+
seen.add(String(id));
|
|
209
|
+
const trail = await trailOf(cms, source, nested, listed, id, parent);
|
|
210
|
+
let doc = listed;
|
|
211
|
+
if (!hasTrail(source, nested, listed, trail)) {
|
|
212
|
+
await cms.update(collection, id, {}, { live: true });
|
|
213
|
+
doc = await liveDoc(cms, source, nested, id) ?? listed;
|
|
214
|
+
}
|
|
215
|
+
await visit(await liveChildren(cms, source, nested, id), doc);
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
await visit(await liveChildren(cms, source, nested, null), null);
|
|
219
|
+
for (const doc of await liveChildren(cms, source, nested, void 0)) {
|
|
220
|
+
if (seen.has(String(doc.id))) continue;
|
|
221
|
+
const parentId = idOf(doc[nested.parentField]);
|
|
222
|
+
if (parentId !== null && await liveDoc(cms, source, nested, parentId)) continue;
|
|
223
|
+
await cms.update(collection, doc.id, { [nested.parentField]: null }, { live: true });
|
|
224
|
+
}
|
|
225
|
+
const after = await snapshot();
|
|
226
|
+
let updated = 0;
|
|
227
|
+
for (const [id, value] of after) if (before.get(id) !== value) updated++;
|
|
228
|
+
return { checked: after.size, updated };
|
|
229
|
+
}
|
|
230
|
+
function stripIds(value) {
|
|
231
|
+
if (Array.isArray(value))
|
|
232
|
+
return value.map((row) => {
|
|
233
|
+
const { id: _id, ...rest } = row;
|
|
234
|
+
return rest;
|
|
235
|
+
});
|
|
236
|
+
if (value && typeof value === "object")
|
|
237
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, stripIds(v)]));
|
|
238
|
+
return value;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// src/plugin.ts
|
|
242
|
+
import {
|
|
243
|
+
NotFoundError,
|
|
244
|
+
ValidationError
|
|
245
|
+
} from "@easy-cms/core";
|
|
246
|
+
var ADMIN_MODULE = "@easy-cms/plugin-nested-docs/admin";
|
|
247
|
+
function nestedDocsPlugin(options) {
|
|
248
|
+
return (config) => {
|
|
249
|
+
const slugs = options.collections ?? [];
|
|
250
|
+
if (!Array.isArray(slugs) || slugs.length === 0)
|
|
251
|
+
throw new Error("nestedDocsPlugin: list the collections, e.g. { collections: ['pages'] }");
|
|
252
|
+
const missing = slugs.filter((s) => !config.collections?.some((c) => c.slug === s));
|
|
253
|
+
if (missing.length > 0)
|
|
254
|
+
throw new Error(
|
|
255
|
+
`nestedDocsPlugin: unknown collection ${missing.map((s) => `"${s}"`).join(", ")}`
|
|
256
|
+
);
|
|
257
|
+
const maxDepth = options.maxDepth ?? 10;
|
|
258
|
+
if (!Number.isInteger(maxDepth) || maxDepth < 1)
|
|
259
|
+
throw new Error("nestedDocsPlugin: maxDepth must be a whole number of at least 1");
|
|
260
|
+
const onDeleteParent = options.onDeleteParent ?? "restrict";
|
|
261
|
+
if (onDeleteParent !== "restrict" && onDeleteParent !== "orphan")
|
|
262
|
+
throw new Error("nestedDocsPlugin: onDeleteParent must be 'restrict' or 'orphan'");
|
|
263
|
+
const localization = config.localization;
|
|
264
|
+
const source = {
|
|
265
|
+
collections: /* @__PURE__ */ new Map(),
|
|
266
|
+
locales: localization?.locales ?? [],
|
|
267
|
+
defaultLocale: localization?.defaultLocale ?? null
|
|
268
|
+
};
|
|
269
|
+
const withNesting = (collection) => {
|
|
270
|
+
if (!slugs.includes(collection.slug)) return collection;
|
|
271
|
+
const where = `nestedDocsPlugin: "${collection.slug}"`;
|
|
272
|
+
const slugField = options.slugField ?? "slug";
|
|
273
|
+
const slug = collection.fields.find((f) => f.name === slugField);
|
|
274
|
+
if (!slug || slug.type !== "slug" && slug.type !== "text")
|
|
275
|
+
throw new Error(`${where} needs a slug field "${slugField}" (or set \`slugField\`)`);
|
|
276
|
+
const titleField = options.titleField ?? collection.useAsTitle ?? slugField;
|
|
277
|
+
if (!collection.fields.some((f) => f.name === titleField))
|
|
278
|
+
throw new Error(`${where} has no field "${titleField}" for breadcrumbs`);
|
|
279
|
+
const names = {
|
|
280
|
+
parent: options.fields?.parent ?? "parent",
|
|
281
|
+
breadcrumbs: options.fields?.breadcrumbs ?? "breadcrumbs",
|
|
282
|
+
path: options.fields?.path ?? "path"
|
|
283
|
+
};
|
|
284
|
+
const ownParent = collection.fields.find((f) => f.name === names.parent);
|
|
285
|
+
if (ownParent && !(ownParent.type === "relationship" && ownParent.to === collection.slug && !ownParent.hasMany))
|
|
286
|
+
throw new Error(
|
|
287
|
+
`${where} has a field "${names.parent}" that is not a relationship to "${collection.slug}"; set \`fields\``
|
|
288
|
+
);
|
|
289
|
+
for (const name of [names.breadcrumbs, names.path])
|
|
290
|
+
if (collection.fields.some((f) => f.name === name))
|
|
291
|
+
throw new Error(`${where} already has a field "${name}"; set \`fields\``);
|
|
292
|
+
const localized = !!localization && slug.localized === true;
|
|
293
|
+
const nested = {
|
|
294
|
+
slug: collection.slug,
|
|
295
|
+
parentField: names.parent,
|
|
296
|
+
breadcrumbsField: names.breadcrumbs,
|
|
297
|
+
pathField: names.path,
|
|
298
|
+
slugField,
|
|
299
|
+
titleField,
|
|
300
|
+
localized,
|
|
301
|
+
drafts: collection.drafts === true,
|
|
302
|
+
maxDepth,
|
|
303
|
+
onDeleteParent,
|
|
304
|
+
sort: collection.admin?.list?.sort ?? titleField
|
|
305
|
+
};
|
|
306
|
+
source.collections.set(collection.slug, nested);
|
|
307
|
+
const notBelowItself = async ({ id, cms }) => id === void 0 ? true : { id: { not_in: [id, ...await descendants(cms, nested, id)] } };
|
|
308
|
+
const readOnly = { update: () => false };
|
|
309
|
+
const parentField = {
|
|
310
|
+
label: { en: "Parent page", th: "\u0E2B\u0E19\u0E49\u0E32\u0E41\u0E21\u0E48" },
|
|
311
|
+
position: "sidebar",
|
|
312
|
+
...ownParent,
|
|
313
|
+
name: names.parent,
|
|
314
|
+
type: "relationship",
|
|
315
|
+
to: collection.slug,
|
|
316
|
+
filterOptions: notBelowItself
|
|
317
|
+
};
|
|
318
|
+
const added = [
|
|
319
|
+
...ownParent ? [] : [parentField],
|
|
320
|
+
{
|
|
321
|
+
name: names.path,
|
|
322
|
+
type: "text",
|
|
323
|
+
label: { en: "Path", th: "\u0E40\u0E2A\u0E49\u0E19\u0E17\u0E32\u0E07 (path)" },
|
|
324
|
+
index: true,
|
|
325
|
+
localized,
|
|
326
|
+
position: "sidebar",
|
|
327
|
+
access: readOnly
|
|
328
|
+
},
|
|
329
|
+
{
|
|
330
|
+
name: names.breadcrumbs,
|
|
331
|
+
type: "array",
|
|
332
|
+
label: { en: "Breadcrumbs", th: "\u0E40\u0E2A\u0E49\u0E19\u0E17\u0E32\u0E07\u0E19\u0E33\u0E17\u0E32\u0E07" },
|
|
333
|
+
localized,
|
|
334
|
+
position: "sidebar",
|
|
335
|
+
access: readOnly,
|
|
336
|
+
admin: {
|
|
337
|
+
component: {
|
|
338
|
+
tag: "ecms-nested-breadcrumbs",
|
|
339
|
+
props: {
|
|
340
|
+
adminPath: `/${(config.admin?.path ?? "/admin").replace(/^\/+|\/+$/g, "")}`,
|
|
341
|
+
parentField: names.parent
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
},
|
|
345
|
+
fields: [
|
|
346
|
+
{ name: "doc", type: "relationship", to: collection.slug },
|
|
347
|
+
{ name: "label", type: "text" },
|
|
348
|
+
{ name: "url", type: "text" }
|
|
349
|
+
]
|
|
350
|
+
}
|
|
351
|
+
];
|
|
352
|
+
const clearTrail = ({ data }) => ({
|
|
353
|
+
...data,
|
|
354
|
+
[names.breadcrumbs]: localized ? Object.fromEntries(source.locales.map((l) => [l, []])) : []
|
|
355
|
+
});
|
|
356
|
+
const computeTrail = async ({ data, originalDoc, cms }) => {
|
|
357
|
+
const selfId = idOf(originalDoc?.id);
|
|
358
|
+
const parentId = idOf(data[names.parent]);
|
|
359
|
+
if (parentId !== null && selfId !== null && parentId !== idOf(originalDoc?.[names.parent]) && (String(parentId) === String(selfId) || (await descendants(cms, nested, selfId)).some((d) => String(d) === String(parentId)))) {
|
|
360
|
+
throw new ValidationError(collection.slug, [
|
|
361
|
+
{ field: names.parent, message: "cannot be this page or a page under it" }
|
|
362
|
+
]);
|
|
363
|
+
}
|
|
364
|
+
const trail = await trailOf(cms, source, nested, data, selfId);
|
|
365
|
+
const depth = Math.max(...[...trail.breadcrumbs.values()].map((rows) => rows.length));
|
|
366
|
+
if (depth > maxDepth) {
|
|
367
|
+
throw new ValidationError(collection.slug, [
|
|
368
|
+
{ field: names.parent, message: `is too deep: pages go at most ${maxDepth} levels` }
|
|
369
|
+
]);
|
|
370
|
+
}
|
|
371
|
+
for (const [locale, path] of trail.path) {
|
|
372
|
+
if (!path) continue;
|
|
373
|
+
const taken = await cms.find(collection.slug, {
|
|
374
|
+
where: {
|
|
375
|
+
and: [
|
|
376
|
+
{ [names.path]: { equals: path } },
|
|
377
|
+
...selfId === null ? [] : [{ id: { not_equals: selfId } }]
|
|
378
|
+
]
|
|
379
|
+
},
|
|
380
|
+
limit: 1,
|
|
381
|
+
depth: 0,
|
|
382
|
+
draft: true,
|
|
383
|
+
...locale ? { locale } : {}
|
|
384
|
+
});
|
|
385
|
+
if (taken.totalDocs > 0) {
|
|
386
|
+
throw new ValidationError(collection.slug, [
|
|
387
|
+
{ field: slugField, message: `another page already has the path ${path}` }
|
|
388
|
+
]);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return { ...data, ...trailData(nested, trail) };
|
|
392
|
+
};
|
|
393
|
+
const updateChildren = async ({ doc, operation, cms }) => {
|
|
394
|
+
const id = idOf(doc.id);
|
|
395
|
+
if (id === null) return;
|
|
396
|
+
if (operation === "create") {
|
|
397
|
+
await cms.update(collection.slug, id, {}, { live: true });
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
await syncChildren(cms, source, nested, id);
|
|
401
|
+
};
|
|
402
|
+
const guardChildren = async ({ id, cms }) => {
|
|
403
|
+
if (onDeleteParent !== "restrict") return;
|
|
404
|
+
const children = await liveChildren(cms, source, nested, id);
|
|
405
|
+
if (children.length > 0) {
|
|
406
|
+
throw new ValidationError(collection.slug, [
|
|
407
|
+
{
|
|
408
|
+
field: names.parent,
|
|
409
|
+
message: `this page has ${children.length} page${children.length === 1 ? "" : "s"} under it: move or delete ${children.length === 1 ? "it" : "them"} first`
|
|
410
|
+
}
|
|
411
|
+
]);
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
const orphanChildren = async ({ id, cms }) => {
|
|
415
|
+
if (onDeleteParent !== "orphan") return;
|
|
416
|
+
for (const child of await liveChildren(cms, source, nested, id))
|
|
417
|
+
await cms.update(
|
|
418
|
+
collection.slug,
|
|
419
|
+
child.id,
|
|
420
|
+
{ [names.parent]: null },
|
|
421
|
+
{ live: true }
|
|
422
|
+
);
|
|
423
|
+
};
|
|
424
|
+
const fields = collection.fields.map(
|
|
425
|
+
(f) => f === slug && f.type === "slug" && f.uniqueWithin === void 0 ? { ...f, uniqueWithin: names.parent } : f === ownParent ? parentField : f
|
|
426
|
+
);
|
|
427
|
+
const hooks = { ...collection.hooks };
|
|
428
|
+
hooks.beforeValidate = [...hooks.beforeValidate ?? [], clearTrail];
|
|
429
|
+
hooks.beforeChange = [...hooks.beforeChange ?? [], computeTrail];
|
|
430
|
+
hooks.afterChange = [...hooks.afterChange ?? [], updateChildren];
|
|
431
|
+
hooks.beforeDelete = [...hooks.beforeDelete ?? [], guardChildren];
|
|
432
|
+
hooks.afterDelete = [...hooks.afterDelete ?? [], orphanChildren];
|
|
433
|
+
return {
|
|
434
|
+
...collection,
|
|
435
|
+
fields: [...fields, ...added],
|
|
436
|
+
hooks,
|
|
437
|
+
admin: {
|
|
438
|
+
...collection.admin,
|
|
439
|
+
list: { ...collection.admin?.list, tree: collection.admin?.list?.tree ?? names.parent }
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
};
|
|
443
|
+
const collections = (config.collections ?? []).map(withNesting);
|
|
444
|
+
const tree = {
|
|
445
|
+
path: "/tree/:collection",
|
|
446
|
+
method: "get",
|
|
447
|
+
// Lets the helpers find these options from the resolved config.
|
|
448
|
+
handler: Object.assign(
|
|
449
|
+
async ({ params, url, user, cms }) => {
|
|
450
|
+
const collection = params.collection;
|
|
451
|
+
if (!source.collections.has(collection)) throw new NotFoundError("tree", collection);
|
|
452
|
+
const locale = url.searchParams.get("locale");
|
|
453
|
+
const depth = Number(url.searchParams.get("depth"));
|
|
454
|
+
const nodes = await getTree(cms, collection, {
|
|
455
|
+
...locale ? { locale } : {},
|
|
456
|
+
...Number.isInteger(depth) && depth > 0 ? { depth } : {},
|
|
457
|
+
user,
|
|
458
|
+
overrideAccess: false
|
|
459
|
+
});
|
|
460
|
+
return Response.json(nodes, { headers: { "cache-control": "public, max-age=60" } });
|
|
461
|
+
},
|
|
462
|
+
{ [NESTED_SOURCE]: source }
|
|
463
|
+
)
|
|
464
|
+
};
|
|
465
|
+
const rebuild = {
|
|
466
|
+
name: "nested:rebuild",
|
|
467
|
+
description: "Work out the breadcrumbs and paths of nested pages again",
|
|
468
|
+
help: `Usage: easy-cms nested:rebuild [collection\u2026] [options]
|
|
469
|
+
|
|
470
|
+
Works out every page's breadcrumbs and path again, top-level pages first, and saves the pages
|
|
471
|
+
whose values changed: after adding the plugin to a collection that has pages, or to repair
|
|
472
|
+
pages after an error. Default: every collection of nestedDocsPlugin (${slugs.join(", ")}).
|
|
473
|
+
`,
|
|
474
|
+
run: async ({ cms, args, log }) => {
|
|
475
|
+
const unknown = args.filter((a) => !slugs.includes(a));
|
|
476
|
+
if (unknown.length > 0) {
|
|
477
|
+
log(`Not nested: ${unknown.join(", ")} (nested: ${slugs.join(", ")})`);
|
|
478
|
+
return 1;
|
|
479
|
+
}
|
|
480
|
+
for (const collection of args.length > 0 ? args : slugs) {
|
|
481
|
+
const result = await rebuildNestedDocs(cms, collection);
|
|
482
|
+
log(`${collection}: checked ${result.checked}, updated ${result.updated}`);
|
|
483
|
+
}
|
|
484
|
+
return 0;
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
return {
|
|
488
|
+
...config,
|
|
489
|
+
collections,
|
|
490
|
+
endpoints: [...config.endpoints ?? [], tree],
|
|
491
|
+
commands: [...config.commands ?? [], rebuild],
|
|
492
|
+
admin: {
|
|
493
|
+
...config.admin,
|
|
494
|
+
modules: [.../* @__PURE__ */ new Set([...config.admin?.modules ?? [], ADMIN_MODULE])]
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
export {
|
|
500
|
+
findByPath,
|
|
501
|
+
getTree,
|
|
502
|
+
nestedDocsPlugin,
|
|
503
|
+
normalizePath,
|
|
504
|
+
rebuildNestedDocs
|
|
505
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@easy-cms/plugin-nested-docs",
|
|
3
|
+
"version": "0.21.0",
|
|
4
|
+
"description": "Nested pages for Easy CMS: a parent for each page, breadcrumbs and full paths kept up to date, and a tree in the admin",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./admin": "./dist/admin.js",
|
|
14
|
+
"./package.json": "./package.json"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"peerDependencies": {
|
|
20
|
+
"@easy-cms/core": "^0.21.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@easy-cms/core": "^0.21.0",
|
|
24
|
+
"@easy-cms/plugin-redirects": "^0.21.0",
|
|
25
|
+
"@easy-cms/db-sqlite": "^0.21.0"
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=22.12"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/maritonx/easy-cms.git",
|
|
36
|
+
"directory": "packages/plugin-nested-docs"
|
|
37
|
+
},
|
|
38
|
+
"keywords": [
|
|
39
|
+
"easy-cms",
|
|
40
|
+
"easy-cms-plugin",
|
|
41
|
+
"nested-docs",
|
|
42
|
+
"breadcrumbs",
|
|
43
|
+
"hierarchy",
|
|
44
|
+
"pages"
|
|
45
|
+
],
|
|
46
|
+
"scripts": {
|
|
47
|
+
"build": "tsup",
|
|
48
|
+
"typecheck": "tsc --noEmit",
|
|
49
|
+
"test": "vitest run"
|
|
50
|
+
}
|
|
51
|
+
}
|