@kidecms/core 0.1.10 → 0.13.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.
Files changed (182) hide show
  1. package/LICENSE +21 -0
  2. package/admin/components/AssetsGrid.tsx +366 -173
  3. package/admin/components/BlockEditor.tsx +260 -679
  4. package/admin/components/CheckboxField.tsx +2 -2
  5. package/admin/components/CollaborationReviewBar.tsx +384 -0
  6. package/admin/components/ColorField.tsx +87 -0
  7. package/admin/components/CommandPalette.tsx +169 -0
  8. package/admin/components/ContentEditor.tsx +687 -0
  9. package/admin/components/DocumentActions.tsx +4 -2
  10. package/admin/components/DocumentsDataTable.tsx +91 -10
  11. package/admin/components/FieldControl.astro +151 -26
  12. package/admin/components/FocalPointSelector.tsx +27 -1
  13. package/admin/components/InternalLinkPicker.tsx +4 -3
  14. package/admin/components/LinkField.tsx +126 -0
  15. package/admin/components/RelationField.tsx +105 -26
  16. package/admin/components/RepeaterInput.tsx +46 -0
  17. package/admin/components/RichTextEditor.tsx +44 -9
  18. package/admin/components/SharedSectionBlockField.tsx +93 -0
  19. package/admin/components/SidebarUserMenu.tsx +1 -1
  20. package/admin/components/Toast.astro +1 -1
  21. package/admin/components/TreeItemsEditor.tsx +20 -19
  22. package/admin/components/TreeSelect.tsx +2 -2
  23. package/admin/components/YoutubeField.tsx +48 -0
  24. package/admin/components/block-fields.tsx +777 -0
  25. package/admin/components/content-block-spec.ts +114 -0
  26. package/admin/components/slash-command.tsx +242 -0
  27. package/admin/components/tree-utils.ts +14 -2
  28. package/admin/components/ui/badge.tsx +2 -3
  29. package/admin/components/ui/button.tsx +5 -4
  30. package/admin/components/ui/checkbox.tsx +1 -1
  31. package/admin/components/ui/input.tsx +1 -1
  32. package/admin/components/ui/select.tsx +1 -1
  33. package/admin/components/ui/table.tsx +1 -1
  34. package/admin/components/ui/textarea.tsx +1 -1
  35. package/admin/layouts/AdminLayout.astro +323 -123
  36. package/admin/lib/access.ts +54 -0
  37. package/admin/lib/collaboration.ts +178 -0
  38. package/admin/lib/edit-data.ts +448 -0
  39. package/admin/views/AccessDeniedView.astro +8 -0
  40. package/admin/views/EditView.astro +706 -0
  41. package/admin/views/ListView.astro +202 -0
  42. package/admin/views/RecentView.astro +76 -0
  43. package/admin/views/SinglesView.astro +65 -0
  44. package/admin/views/edit/EditScripts.astro +145 -0
  45. package/admin/views/edit/ReverseReferencesList.astro +68 -0
  46. package/core/admin.ts +193 -0
  47. package/core/ai.ts +87 -0
  48. package/core/api.ts +1392 -0
  49. package/core/assets.ts +336 -0
  50. package/core/audit.ts +84 -0
  51. package/core/auth-config.ts +44 -0
  52. package/core/auth.ts +303 -0
  53. package/core/collaboration.ts +276 -0
  54. package/core/content.ts +27 -0
  55. package/core/create-admin.ts +28 -0
  56. package/core/define.ts +625 -0
  57. package/core/field-model.ts +172 -0
  58. package/core/generator.ts +519 -0
  59. package/core/http.ts +42 -0
  60. package/core/image.ts +219 -0
  61. package/core/index.ts +211 -0
  62. package/core/locks.ts +52 -0
  63. package/core/log.ts +37 -0
  64. package/core/migrate.ts +278 -0
  65. package/core/rate-limit.ts +110 -0
  66. package/core/request-scope.ts +33 -0
  67. package/core/richtext.ts +1 -0
  68. package/core/runtime.ts +63 -0
  69. package/core/schema.ts +32 -0
  70. package/core/search.ts +489 -0
  71. package/core/seed.ts +101 -0
  72. package/core/shared-sections.ts +96 -0
  73. package/core/tasks.ts +176 -0
  74. package/core/values.ts +433 -0
  75. package/core/webhooks.ts +85 -0
  76. package/core/youtube.ts +39 -0
  77. package/internals/cli.mjs +34 -0
  78. package/internals/context.ts +67 -0
  79. package/internals/create-admin.ts +40 -0
  80. package/internals/describe.ts +25 -0
  81. package/internals/eject.ts +144 -0
  82. package/internals/generator.ts +11 -0
  83. package/internals/integration.ts +481 -0
  84. package/internals/mcp.ts +397 -0
  85. package/internals/project.ts +26 -0
  86. package/internals/push.ts +160 -0
  87. package/internals/reindex.ts +11 -0
  88. package/internals/restore.ts +257 -0
  89. package/internals/seed.data.ts +7 -0
  90. package/internals/seed.ts +11 -0
  91. package/internals/upgrade.ts +776 -0
  92. package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
  93. package/middleware/auth.ts +130 -17
  94. package/middleware/push.ts +121 -0
  95. package/package.json +55 -67
  96. package/platform/cloudflare/cf-env.ts +60 -0
  97. package/platform/cloudflare/database.ts +28 -0
  98. package/platform/cloudflare/globals.d.ts +5 -0
  99. package/platform/cloudflare/storage.ts +33 -0
  100. package/platform/cloudflare/uploads-route.ts +37 -0
  101. package/platform/node/database.ts +39 -0
  102. package/platform/node/storage.ts +52 -0
  103. package/routes/admin/[...path].astro +71 -0
  104. package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
  105. package/routes/admin/assets/index.astro +90 -0
  106. package/routes/admin/forgot-password.astro +60 -0
  107. package/routes/{pages/admin → admin}/invite.astro +7 -6
  108. package/routes/admin/login.astro +103 -0
  109. package/routes/admin/reset-password.astro +73 -0
  110. package/routes/{pages/admin → admin}/setup.astro +32 -8
  111. package/routes/api/{cms/[collection] → [collection]}/[...path].ts +66 -14
  112. package/routes/api/admin/search.ts +89 -0
  113. package/routes/api/{cms/assets → assets}/[id].ts +24 -14
  114. package/routes/api/{cms/assets → assets}/index.ts +4 -2
  115. package/routes/api/assets/upload.ts +147 -0
  116. package/routes/api/auth/forgot-password.ts +77 -0
  117. package/routes/api/{cms/auth → auth}/invite.ts +41 -9
  118. package/routes/api/auth/login.ts +167 -0
  119. package/routes/api/{cms/auth → auth}/logout.ts +11 -2
  120. package/routes/api/auth/reset-password.ts +85 -0
  121. package/routes/api/auth/setup.ts +110 -0
  122. package/routes/api/auth/sso/[provider]/start.ts +34 -0
  123. package/routes/api/collaboration/index.ts +106 -0
  124. package/routes/api/cron/_authorize.ts +25 -0
  125. package/routes/api/{cms/cron → cron}/publish.ts +3 -9
  126. package/routes/api/cron/tasks.ts +33 -0
  127. package/routes/api/forms/submit/[slug].ts +143 -0
  128. package/routes/api/img/[...path].ts +65 -0
  129. package/routes/api/{cms/preview → preview}/render.ts +8 -3
  130. package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
  131. package/routes/api/webhooks/[provider].ts +54 -0
  132. package/README.md +0 -28
  133. package/dist/admin.d.ts +0 -33
  134. package/dist/admin.js +0 -92
  135. package/dist/ai.d.ts +0 -15
  136. package/dist/ai.js +0 -70
  137. package/dist/api.d.ts +0 -14
  138. package/dist/api.js +0 -833
  139. package/dist/assets.d.ts +0 -51
  140. package/dist/assets.js +0 -163
  141. package/dist/auth.d.ts +0 -30
  142. package/dist/auth.js +0 -132
  143. package/dist/content.d.ts +0 -3
  144. package/dist/content.js +0 -29
  145. package/dist/create-admin.d.ts +0 -5
  146. package/dist/create-admin.js +0 -23
  147. package/dist/define.d.ts +0 -254
  148. package/dist/define.js +0 -36
  149. package/dist/generator.d.ts +0 -9
  150. package/dist/generator.js +0 -370
  151. package/dist/image.d.ts +0 -9
  152. package/dist/image.js +0 -69
  153. package/dist/index.d.ts +0 -28
  154. package/dist/index.js +0 -16
  155. package/dist/integration.d.ts +0 -14
  156. package/dist/integration.js +0 -327
  157. package/dist/locks.d.ts +0 -7
  158. package/dist/locks.js +0 -37
  159. package/dist/richtext.d.ts +0 -1
  160. package/dist/richtext.js +0 -1
  161. package/dist/runtime.d.ts +0 -24
  162. package/dist/runtime.js +0 -26
  163. package/dist/schema.d.ts +0 -17
  164. package/dist/schema.js +0 -13
  165. package/dist/seed.d.ts +0 -2
  166. package/dist/seed.js +0 -84
  167. package/dist/values.d.ts +0 -8
  168. package/dist/values.js +0 -102
  169. package/dist/webhooks.d.ts +0 -2
  170. package/dist/webhooks.js +0 -73
  171. package/routes/api/cms/assets/upload.ts +0 -112
  172. package/routes/api/cms/auth/login.ts +0 -124
  173. package/routes/api/cms/auth/setup.ts +0 -77
  174. package/routes/api/cms/img/[...path].ts +0 -24
  175. package/routes/pages/admin/[...path].astro +0 -1107
  176. package/routes/pages/admin/assets/index.astro +0 -63
  177. package/routes/pages/admin/login.astro +0 -57
  178. /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
  179. /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
  180. /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
  181. /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
  182. /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
@@ -0,0 +1,202 @@
1
+ ---
2
+ import { Plus } from "lucide-react";
3
+
4
+ import DocumentsDataTable, { PAGE_SIZE } from "../components/DocumentsDataTable";
5
+ import { buttonVariants } from "../components/ui/button";
6
+ import config from "virtual:kide/config";
7
+ import { cms } from "virtual:kide/api";
8
+ import { collaboration } from "virtual:kide/runtime";
9
+ import { REVIEW_STATE_META } from "../lib/collaboration";
10
+ import {
11
+ formatDate,
12
+ formatFieldValue,
13
+ getLabelField,
14
+ getListColumns,
15
+ humanize,
16
+ resolveCollaboration,
17
+ } from "../../core";
18
+ import { canWrite, getVisualStatus } from "../lib/access";
19
+ import { loadRelationOptionList, loadSharedSectionUsageCounts } from "../lib/edit-data";
20
+
21
+ type CollectionLike = {
22
+ slug: string;
23
+ labels: { singular: string; plural: string };
24
+ drafts?: boolean;
25
+ fields: Record<string, any>;
26
+ views?: Record<string, any>;
27
+ };
28
+
29
+ const { collection } = Astro.props as { collection: CollectionLike };
30
+ const user = Astro.locals.user;
31
+ const runtimeContext = user ? { user: { id: user.id, role: user.role, email: user.email } } : {};
32
+ const cmsRuntime = cms as Record<string, any>;
33
+ const defaultLocale = config.locales?.default ?? "en";
34
+ const locales = config.locales?.supported ?? [];
35
+
36
+ const viewConfig = collection.views ?? {};
37
+ const defaultSort = viewConfig.list?.defaultSort ?? { field: "_updatedAt", direction: "desc" };
38
+ const sortParam = Astro.url.searchParams.get("sort");
39
+ const sortDirParam = Astro.url.searchParams.get("dir");
40
+ const currentSort = sortParam
41
+ ? { field: sortParam, direction: (sortDirParam === "asc" ? "asc" : "desc") as "asc" | "desc" }
42
+ : defaultSort;
43
+ const currentPage = Math.max(1, Number(Astro.url.searchParams.get("page") ?? "1"));
44
+ const searchParam = Astro.url.searchParams.get("q") ?? "";
45
+ const offset = (currentPage - 1) * PAGE_SIZE;
46
+
47
+ const collectionApi = cmsRuntime[collection.slug];
48
+ const [docs, totalDocs] = await Promise.all([
49
+ collectionApi.find(
50
+ {
51
+ status: "any",
52
+ locale: defaultLocale,
53
+ sort: currentSort,
54
+ limit: PAGE_SIZE,
55
+ offset,
56
+ search: searchParam || undefined,
57
+ },
58
+ runtimeContext,
59
+ ),
60
+ collectionApi.count({ status: "any", locale: defaultLocale, search: searchParam || undefined }, runtimeContext),
61
+ ]);
62
+ const totalPages = Math.max(1, Math.ceil(totalDocs / PAGE_SIZE));
63
+
64
+ const listColumns = getListColumns(collection, viewConfig.list);
65
+
66
+ // Resolve relation columns to their related document labels (id → label) so the
67
+ // table shows e.g. the form title instead of the raw relation id.
68
+ const relationLabels: Record<string, string> = {};
69
+ for (const column of listColumns) {
70
+ const field = collection.fields[column];
71
+ if (field?.type !== "relation") continue;
72
+ const options = await loadRelationOptionList(
73
+ field.collection,
74
+ config,
75
+ cmsRuntime as any,
76
+ defaultLocale,
77
+ runtimeContext,
78
+ );
79
+ for (const option of options) relationLabels[option.value] = option.label;
80
+ }
81
+
82
+ // Collaboration columns (review state + editor) — only for collections in the
83
+ // collaboration list that also support drafts. Not sortable (non-DB columns).
84
+ const collabListColumns =
85
+ resolveCollaboration(config, collection.slug).enabled && collection.drafts ? ["__review", "__editor"] : [];
86
+ const displayColumns = [...listColumns, ...collabListColumns];
87
+
88
+ // Batch-load review state + editor for the listed documents.
89
+ let collabStates: Record<string, { reviewState: string; editor: string | null }> = {};
90
+ const collabUserNames: Record<string, string> = {};
91
+ if (collabListColumns.length > 0) {
92
+ collabStates = await collaboration.getStatesForDocs(
93
+ collection.slug,
94
+ docs.map((entry: Record<string, unknown>) => String(entry._id)),
95
+ );
96
+ const editorIds = [
97
+ ...new Set(
98
+ Object.values(collabStates)
99
+ .map((s) => s.editor)
100
+ .filter((id): id is string => Boolean(id)),
101
+ ),
102
+ ];
103
+ if (editorIds.length > 0) {
104
+ const users = await cmsRuntime.users?.find({ status: "any", limit: 100 }, runtimeContext).catch(() => []);
105
+ for (const u of users ?? []) collabUserNames[String(u._id)] = String(u.name ?? u.email ?? u._id);
106
+ }
107
+ }
108
+
109
+ const sharedSectionUsageCounts =
110
+ collection.slug === "shared-sections"
111
+ ? await loadSharedSectionUsageCounts(
112
+ docs.map((entry: Record<string, unknown>) => String(entry._id)),
113
+ config,
114
+ user,
115
+ cmsRuntime as any,
116
+ defaultLocale,
117
+ runtimeContext,
118
+ )
119
+ : {};
120
+ const tableRows = docs.map((entry: Record<string, unknown>) => ({
121
+ id: String(entry._id),
122
+ editHref: `/admin/${collection.slug}/${entry._id}`,
123
+ status: getVisualStatus(entry),
124
+ locales: [
125
+ defaultLocale,
126
+ ...(Array.isArray(entry._availableLocales)
127
+ ? entry._availableLocales.map((l) => String(l)).filter((l) => l !== defaultLocale)
128
+ : []),
129
+ ],
130
+ searchText: String(entry[getLabelField(collection)] ?? entry.slug ?? entry._id ?? ""),
131
+ values: Object.fromEntries(
132
+ displayColumns.map((column) => [
133
+ column,
134
+ column === "__review"
135
+ ? REVIEW_STATE_META[
136
+ (collabStates[String(entry._id)]?.reviewState ?? "in_progress") as keyof typeof REVIEW_STATE_META
137
+ ].label
138
+ : column === "__editor"
139
+ ? collabStates[String(entry._id)]?.editor
140
+ ? (collabUserNames[collabStates[String(entry._id)]!.editor!] ?? "—")
141
+ : "Unassigned"
142
+ : column === "_status"
143
+ ? getVisualStatus(entry)
144
+ : column === "__usage"
145
+ ? `${sharedSectionUsageCounts[String(entry._id)] ?? 0} places`
146
+ : column === "_updatedAt" || column === "_createdAt"
147
+ ? formatDate(entry[column])
148
+ : column.startsWith("_")
149
+ ? String(entry[column] ?? "—")
150
+ : formatFieldValue(collection.fields[column], entry[column], relationLabels),
151
+ ]),
152
+ ),
153
+ }));
154
+ ---
155
+
156
+ <section class="space-y-6 px-4 py-6 lg:py-8 lg:pr-8 lg:pl-12">
157
+ <div class="flex items-start justify-between gap-4">
158
+ <div>
159
+ <h1 class="text-2xl font-semibold tracking-tight">{collection.labels.plural}</h1>
160
+ </div>
161
+ <div class="flex flex-wrap items-center gap-2">
162
+ {
163
+ canWrite(config, user, collection.slug) && (
164
+ <a href={`/admin/${collection.slug}/new`} class={buttonVariants({})}>
165
+ <Plus className="size-4" />
166
+ {collection.slug === "users" ? "Invite user" : `New ${collection.labels.singular}`}
167
+ </a>
168
+ )
169
+ }
170
+ </div>
171
+ </div>
172
+ <DocumentsDataTable
173
+ client:load
174
+ collectionSlug={collection.slug}
175
+ draftsEnabled={collection.drafts}
176
+ defaultLocale={locales.length > 1 ? defaultLocale : undefined}
177
+ labelField={getLabelField(collection)}
178
+ newHref={`/admin/${collection.slug}/new`}
179
+ title={collection.labels.plural}
180
+ columns={displayColumns.map((column) => ({
181
+ key: column,
182
+ label:
183
+ column === "__usage"
184
+ ? "Used in"
185
+ : column === "__review"
186
+ ? "Review"
187
+ : column === "__editor"
188
+ ? "Editor"
189
+ : humanize(column),
190
+ sortable: !column.startsWith("__"),
191
+ }))}
192
+ data={tableRows}
193
+ searchPlaceholder={`Filter ${collection.labels.plural.toLowerCase()}...`}
194
+ serverPagination={{
195
+ totalDocs,
196
+ totalPages,
197
+ currentPage,
198
+ currentSort,
199
+ currentSearch: searchParam,
200
+ }}
201
+ />
202
+ </section>
@@ -0,0 +1,76 @@
1
+ ---
2
+ import DocumentsDataTable from "../components/DocumentsDataTable";
3
+ import config from "virtual:kide/config";
4
+ import { cms } from "virtual:kide/api";
5
+ import { formatDate, getLabelField } from "../../core";
6
+ import { canRead, getVisualStatus } from "../lib/access";
7
+
8
+ const user = Astro.locals.user;
9
+ const runtimeContext = user ? { user: { id: user.id, role: user.role, email: user.email } } : {};
10
+ const cmsRuntime = cms as Record<string, any>;
11
+ const defaultLocale = config.locales?.default ?? "en";
12
+
13
+ const pinnedSlugs = new Set(["taxonomies", "menus", "authors", "users"]);
14
+ const contentCollections = config.collections.filter(
15
+ (c) => !c.auth && !pinnedSlugs.has(c.slug) && canRead(config, user, c.slug),
16
+ );
17
+
18
+ const allEntries: Array<{ doc: Record<string, unknown>; collection: (typeof contentCollections)[0] }> = [];
19
+ for (const cc of contentCollections) {
20
+ const api = cmsRuntime[cc.slug];
21
+ const docs = await api.find(
22
+ { status: "any", locale: defaultLocale, sort: { field: "_updatedAt", direction: "desc" }, limit: 50 },
23
+ runtimeContext,
24
+ );
25
+ for (const doc of docs) allEntries.push({ doc, collection: cc });
26
+ }
27
+ allEntries.sort((a, b) => String(b.doc._updatedAt ?? "").localeCompare(String(a.doc._updatedAt ?? "")));
28
+
29
+ const recentRows = allEntries.slice(0, 50).map(({ doc, collection: cc }) => {
30
+ const displayTitle = cc.singleton
31
+ ? cc.labels.singular
32
+ : String(doc[getLabelField(cc)] ?? doc.slug ?? cc.labels.singular);
33
+ // Only compute status for collections that opt into drafts. Otherwise it defaults
34
+ // to "draft" and the recent list shows a misleading badge for non-draftable docs.
35
+ const status = cc.drafts ? getVisualStatus(doc) : "";
36
+ return {
37
+ id: String(doc._id),
38
+ editHref: `/admin/${cc.slug}/${doc._id}`,
39
+ status,
40
+ singleton: cc.singleton,
41
+ locales: [
42
+ defaultLocale,
43
+ ...(Array.isArray(doc._availableLocales)
44
+ ? doc._availableLocales.map((l) => String(l)).filter((l) => l !== defaultLocale)
45
+ : []),
46
+ ],
47
+ searchText: displayTitle,
48
+ values: {
49
+ title: displayTitle,
50
+ collection: cc.labels.singular,
51
+ _status: status,
52
+ _updatedAt: formatDate(doc._updatedAt),
53
+ },
54
+ };
55
+ });
56
+ ---
57
+
58
+ <section class="space-y-6 px-4 py-6 lg:py-8 lg:pr-8 lg:pl-12">
59
+ <div class="flex items-start justify-between gap-4">
60
+ <h1 class="text-2xl font-semibold tracking-tight">Recent</h1>
61
+ </div>
62
+ <DocumentsDataTable
63
+ client:load
64
+ collectionSlug="recent"
65
+ draftsEnabled={true}
66
+ title="Recent"
67
+ columns={[
68
+ { key: "title", label: "Title" },
69
+ { key: "collection", label: "Collection" },
70
+ { key: "_status", label: "Status" },
71
+ { key: "_updatedAt", label: "Updated" },
72
+ ]}
73
+ data={recentRows}
74
+ searchPlaceholder="Filter recent entries..."
75
+ />
76
+ </section>
@@ -0,0 +1,65 @@
1
+ ---
2
+ import DocumentsDataTable from "../components/DocumentsDataTable";
3
+ import config from "virtual:kide/config";
4
+ import { cms } from "virtual:kide/api";
5
+ import { formatDate } from "../../core";
6
+ import { canRead } from "../lib/access";
7
+
8
+ const user = Astro.locals.user;
9
+ const runtimeContext = user ? { user: { id: user.id, role: user.role, email: user.email } } : {};
10
+ const cmsRuntime = cms as Record<string, any>;
11
+ const defaultLocale = config.locales?.default ?? "en";
12
+
13
+ const singletonCollections = config.collections.filter((c) => c.singleton && canRead(config, user, c.slug));
14
+ const singletonsData = await Promise.all(
15
+ singletonCollections.map(async (sc) => {
16
+ const api = cmsRuntime[sc.slug];
17
+ const singleDocs = await api.find({ status: "any", limit: 1, locale: defaultLocale }, runtimeContext);
18
+ const singleDoc = singleDocs[0] ?? null;
19
+ return {
20
+ id: singleDoc ? String(singleDoc._id) : "",
21
+ collectionSlug: sc.slug,
22
+ label: sc.labels.singular,
23
+ status: singleDoc && sc.drafts ? String(singleDoc._status ?? "draft") : "",
24
+ locales: singleDoc
25
+ ? [
26
+ defaultLocale,
27
+ ...(Array.isArray(singleDoc._availableLocales)
28
+ ? singleDoc._availableLocales.filter((l: string) => l !== defaultLocale)
29
+ : []),
30
+ ]
31
+ : [],
32
+ updatedAt: singleDoc ? formatDate(singleDoc._updatedAt) : "—",
33
+ editHref: `/admin/${sc.slug}`,
34
+ };
35
+ }),
36
+ );
37
+ ---
38
+
39
+ <section class="space-y-6 px-4 py-6 lg:py-8 lg:pr-8 lg:pl-12">
40
+ <div class="flex items-start justify-between gap-4">
41
+ <h1 class="text-2xl font-semibold tracking-tight">Singles</h1>
42
+ </div>
43
+ <DocumentsDataTable
44
+ client:load
45
+ collectionSlug="singles"
46
+ draftsEnabled={true}
47
+ duplicateEnabled={false}
48
+ title="Singles"
49
+ columns={[
50
+ { key: "name", label: "Name" },
51
+ { key: "slug", label: "API slug" },
52
+ ...(singletonCollections.some((c) => c.drafts) ? [{ key: "_status", label: "Status" }] : []),
53
+ { key: "updatedAt", label: "Last updated" },
54
+ ]}
55
+ data={singletonsData.map((s) => ({
56
+ id: s.id,
57
+ collectionSlug: s.collectionSlug,
58
+ editHref: s.editHref,
59
+ locales: s.locales,
60
+ searchText: `${s.label} ${s.collectionSlug}`,
61
+ values: { name: s.label, slug: s.collectionSlug, _status: s.status, updatedAt: s.updatedAt },
62
+ }))}
63
+ searchPlaceholder="Filter singles..."
64
+ />
65
+ </section>
@@ -0,0 +1,145 @@
1
+ ---
2
+ // Client-side glue for the edit form: conditional field visibility, autofocus on new,
3
+ // AJAX form submit (so validation errors surface as toasts without losing form state),
4
+ // and collapsible field-group state persistence.
5
+ ---
6
+
7
+ <script is:inline>
8
+ // Collapsible field groups remember their open/closed state per collection
9
+ // and group in localStorage, so a folded section stays folded across visits.
10
+ (function () {
11
+ document.querySelectorAll("details[data-fieldset-key]").forEach(function (el) {
12
+ var key = "kide:fieldset:" + el.getAttribute("data-fieldset-key");
13
+ try {
14
+ var saved = localStorage.getItem(key);
15
+ if (saved === "open") el.open = true;
16
+ else if (saved === "closed") el.open = false;
17
+ } catch (e) {
18
+ /* no localStorage — schema default stays */
19
+ }
20
+ el.addEventListener("toggle", function () {
21
+ try {
22
+ localStorage.setItem(key, el.open ? "open" : "closed");
23
+ } catch (e) {
24
+ /* ignore */
25
+ }
26
+ });
27
+ });
28
+ })();
29
+ </script>
30
+
31
+ <script is:inline>
32
+ (function () {
33
+ // --- Conditional fields ---
34
+ var conditionals = document.querySelectorAll("[data-condition-field]");
35
+ if (conditionals.length > 0) {
36
+ var matchesCondition = function (currentValue, expected) {
37
+ if (Array.isArray(expected)) {
38
+ return expected.some(function (v) {
39
+ return String(v) === String(currentValue);
40
+ });
41
+ }
42
+ if (typeof expected === "boolean") {
43
+ return expected
44
+ ? currentValue === "true" || currentValue === true
45
+ : currentValue === "false" || currentValue === false || currentValue === "";
46
+ }
47
+ return String(expected) === String(currentValue);
48
+ };
49
+
50
+ var getFieldValue = function (fieldName) {
51
+ var radio = document.querySelector('input[type="radio"][name="' + fieldName + '"]:checked');
52
+ if (radio) return radio.value;
53
+ if (document.querySelector('input[type="radio"][name="' + fieldName + '"]')) return "";
54
+ var checkbox = document.querySelector('input[type="checkbox"][name="' + fieldName + '"]');
55
+ if (checkbox) return checkbox.checked ? "true" : "false";
56
+ var hidden = document.querySelector('input[type="hidden"][name="' + fieldName + '"]');
57
+ if (hidden) return hidden.value;
58
+ var input = document.querySelector('[name="' + fieldName + '"]');
59
+ if (input) return input.value;
60
+ return "";
61
+ };
62
+
63
+ var updateVisibility = function () {
64
+ conditionals.forEach(function (el) {
65
+ var depField = el.getAttribute("data-condition-field");
66
+ var expected = JSON.parse(el.getAttribute("data-condition-value"));
67
+ var currentValue = getFieldValue(depField);
68
+ var visible = matchesCondition(currentValue, expected);
69
+ var target = el.parentElement && el.parentElement.childElementCount === 1 ? el.parentElement : el;
70
+ target.style.display = visible ? "" : "none";
71
+ el.querySelectorAll("input, textarea, select").forEach(function (input) {
72
+ input.disabled = !visible;
73
+ });
74
+ });
75
+ };
76
+
77
+ updateVisibility();
78
+ var form = document.getElementById("document-form");
79
+ if (form) {
80
+ form.addEventListener("input", updateVisibility);
81
+ form.addEventListener("change", updateVisibility);
82
+ }
83
+ }
84
+ })();
85
+ </script>
86
+
87
+ <script is:inline>
88
+ (function () {
89
+ var form = document.getElementById("document-form");
90
+ if (!form) return;
91
+ if (location.pathname.endsWith("/new")) {
92
+ var first = form.querySelector('input[type="text"], textarea');
93
+ if (first) first.focus();
94
+ }
95
+ form.addEventListener("submit", function (e) {
96
+ e.preventDefault();
97
+ var f = e.target;
98
+ var sub = e.submitter;
99
+ var fd = new FormData(f);
100
+ if (sub && sub.name && sub.value) fd.set(sub.name, sub.value);
101
+ fetch(f.action, {
102
+ method: f.method || "POST",
103
+ body: new URLSearchParams(fd),
104
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
105
+ })
106
+ .then(function (res) {
107
+ var u = new URL(res.url);
108
+ if (u.searchParams.get("_toast") === "error") {
109
+ var existing = document.getElementById("admin-toast");
110
+ if (existing) existing.parentElement.remove();
111
+ var msg = decodeURIComponent(u.searchParams.get("_msg") || "Something went wrong");
112
+ var w = document.createElement("div");
113
+ w.className = "fixed top-4 left-1/2 z-50 w-full max-w-sm -translate-x-1/2";
114
+ w.innerHTML =
115
+ '<div id="admin-toast" role="alert" class="bg-card flex items-center gap-2 rounded-lg border border-red-500/30 px-5 py-3 text-sm shadow-lg" style="animation:toast-in .25s ease-out,toast-out .3s ease-in 4.7s forwards">' +
116
+ '<svg class="size-4 shrink-0 text-red-600 dark:text-red-400" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>' +
117
+ '<span class="text-red-700 dark:text-red-400"></span></div>';
118
+ // Carries document data (hook errors quote field values) — never innerHTML.
119
+ w.querySelector("span").textContent = msg;
120
+ document.body.appendChild(w);
121
+ setTimeout(function () {
122
+ w.remove();
123
+ }, 5200);
124
+ return;
125
+ }
126
+ if (u.searchParams.get("_toast") === "success") {
127
+ try {
128
+ new BroadcastChannel("cms-preview").postMessage({ type: "reload" });
129
+ } catch (e) {}
130
+ }
131
+ if (window.parent !== window && u.searchParams.get("_toast") === "success") {
132
+ var idMatch = u.pathname.match(/\/admin\/[^/]+\/([^/]+)/);
133
+ if (idMatch) {
134
+ window.parent.postMessage({ type: "cms:created", id: idMatch[1] }, "*");
135
+ return;
136
+ }
137
+ }
138
+ window.location.assign(res.url);
139
+ })
140
+ .catch(function () {
141
+ f.submit();
142
+ });
143
+ });
144
+ })();
145
+ </script>
@@ -0,0 +1,68 @@
1
+ ---
2
+ import AdminCard from "../../components/AdminCard.astro";
3
+ import type { ReverseRef } from "../../lib/edit-data";
4
+
5
+ const { reverseRefs, variant = "editorial" } = Astro.props as {
6
+ reverseRefs: ReverseRef[];
7
+ variant?: "editorial" | "record";
8
+ };
9
+
10
+ const allDocs = reverseRefs.flatMap((ref) =>
11
+ ref.docs.map((d) => ({ ...d, collectionSlug: ref.collectionSlug, collectionLabel: ref.collectionLabel })),
12
+ );
13
+ const visible = allDocs.slice(0, 30);
14
+ const hidden = allDocs.slice(30);
15
+ ---
16
+
17
+ {
18
+ allDocs.length > 0 &&
19
+ (() => {
20
+ const list = (
21
+ <>
22
+ <ul class="grid gap-1">
23
+ {visible.map((d) => (
24
+ <li class="flex min-w-0 items-baseline justify-between gap-2">
25
+ <a
26
+ href={`/admin/${d.collectionSlug}/${d._id}`}
27
+ target="_blank"
28
+ class="text-foreground/70 hover:text-foreground truncate text-sm transition-colors hover:underline"
29
+ >
30
+ {d.label}
31
+ </a>
32
+ <span class="text-muted-foreground shrink-0 text-xs">{d.collectionLabel}</span>
33
+ </li>
34
+ ))}
35
+ </ul>
36
+ {hidden.length > 0 && (
37
+ <details class="mt-2">
38
+ <summary class="text-muted-foreground hover:text-foreground cursor-pointer text-xs transition-colors">
39
+ Show {hidden.length} more
40
+ </summary>
41
+ <ul class="mt-1 grid gap-1">
42
+ {hidden.map((d) => (
43
+ <li class="flex min-w-0 items-baseline justify-between gap-2">
44
+ <a
45
+ href={`/admin/${d.collectionSlug}/${d._id}`}
46
+ class="text-foreground/70 hover:text-foreground truncate text-sm transition-colors hover:underline"
47
+ >
48
+ {d.label}
49
+ </a>
50
+ <span class="text-muted-foreground shrink-0 text-xs">{d.collectionLabel}</span>
51
+ </li>
52
+ ))}
53
+ </ul>
54
+ </details>
55
+ )}
56
+ </>
57
+ );
58
+
59
+ return variant === "record" ? (
60
+ <AdminCard title="Referenced by">{list}</AdminCard>
61
+ ) : (
62
+ <div class="grid gap-2">
63
+ <span class="text-foreground/80 text-sm leading-none font-medium">Referenced by</span>
64
+ {list}
65
+ </div>
66
+ );
67
+ })()
68
+ }