@kidecms/core 0.19.1 → 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.
Files changed (39) hide show
  1. package/admin/components/AssetsGrid.tsx +1 -1
  2. package/admin/components/BlockEditor.tsx +3 -12
  3. package/admin/components/CollaborationReviewBar.tsx +245 -61
  4. package/admin/components/CommandPalette.tsx +19 -72
  5. package/admin/components/ContentEditor.tsx +4 -10
  6. package/admin/components/DocumentCombobox.tsx +171 -0
  7. package/admin/components/FieldControl.astro +16 -32
  8. package/admin/components/InternalLinkPicker.tsx +30 -62
  9. package/admin/components/LinkField.tsx +6 -5
  10. package/admin/components/RelationField.tsx +32 -58
  11. package/admin/components/RepeaterInput.tsx +3 -6
  12. package/admin/components/SharedSectionBlockField.tsx +2 -6
  13. package/admin/components/TreeItemsEditor.tsx +4 -4
  14. package/admin/components/TreeSelect.tsx +33 -19
  15. package/admin/components/block-fields.tsx +21 -50
  16. package/admin/components/content-block-spec.ts +5 -6
  17. package/admin/layouts/AdminLayout.astro +41 -2
  18. package/admin/lib/collaboration.ts +91 -0
  19. package/admin/lib/edit-data.ts +84 -129
  20. package/admin/lib/use-document-search.ts +107 -0
  21. package/admin/views/EditView.astro +19 -28
  22. package/admin/views/ListView.astro +3 -1
  23. package/admin/views/NeedsYouView.astro +100 -0
  24. package/admin/views/RecentView.astro +32 -9
  25. package/admin/views/edit/EditScripts.astro +90 -15
  26. package/core/admin.ts +2 -0
  27. package/core/api.ts +31 -2
  28. package/core/collaboration.ts +73 -0
  29. package/core/generator.ts +25 -2
  30. package/core/index.ts +8 -2
  31. package/middleware/auth.ts +7 -1
  32. package/package.json +1 -1
  33. package/routes/admin/[...path].astro +19 -6
  34. package/routes/admin/setup.astro +3 -2
  35. package/routes/api/[collection]/[...path].ts +12 -5
  36. package/routes/api/admin/search.ts +102 -45
  37. package/routes/api/auth/setup.ts +7 -5
  38. package/routes/api/collaboration/index.ts +15 -0
  39. package/admin/components/Untitled +0 -1
@@ -6,35 +6,111 @@ import { getLabelField } from "../../../core";
6
6
 
7
7
  export const prerender = false;
8
8
 
9
+ /**
10
+ * Document lookup for the admin. Serves three callers with one shape:
11
+ *
12
+ * ?q=term command palette — every collection, a few hits each
13
+ * ?q=term&collection=a,b&limit=20 relation / internal-link pickers — the target collections only
14
+ * ?collection=a&ids=x,y label resolution for already-selected values
15
+ * ?collection=a no query yet — the most recently updated documents
16
+ *
17
+ * Every read goes through `find()` with the caller's user, so collection and
18
+ * per-document access rules apply exactly as in the admin lists.
19
+ */
9
20
  const HIDDEN_FROM_SEARCH = new Set(["form-submissions"]);
10
- const PER_COLLECTION = 5;
11
- const TOTAL_CAP = 30;
21
+ const MIN_QUERY_LENGTH = 2;
22
+ const PALETTE_PER_COLLECTION = 5;
23
+ const PALETTE_TOTAL_CAP = 30;
24
+ const PICKER_DEFAULT_LIMIT = 20;
25
+ const PICKER_MAX_LIMIT = 50;
26
+ const MAX_IDS = 200;
12
27
 
13
- type SearchResult = {
28
+ export type SearchResult = {
14
29
  collection: string;
15
30
  collectionLabel: string;
16
31
  docId: string;
17
32
  title: string;
18
33
  editUrl: string;
34
+ /** Public route of the document (internal-link pickers store this). */
35
+ href: string | null;
19
36
  status: string | null;
20
37
  };
21
38
 
39
+ type CollectionLike = { slug: string; singleton?: boolean; labels: { singular: string; plural: string } };
40
+
41
+ const csv = (value: string | null) =>
42
+ (value ?? "")
43
+ .split(",")
44
+ .map((s) => s.trim())
45
+ .filter(Boolean);
46
+
22
47
  export const GET: APIRoute = async ({ url, locals }) => {
23
48
  if (!locals.user) {
24
49
  return Response.json({ error: "Unauthorized" }, { status: 401 });
25
50
  }
26
51
 
52
+ const cmsAny = cms as Record<string, any>;
53
+ const context = { user: locals.user };
27
54
  const q = (url.searchParams.get("q") ?? "").trim();
28
- if (q.length < 2) return Response.json({ results: [] });
55
+ const requested = csv(url.searchParams.get("collection"));
56
+ const ids = csv(url.searchParams.get("ids")).slice(0, MAX_IDS);
57
+ const limit = Math.min(Math.max(Number(url.searchParams.get("limit")) || PICKER_DEFAULT_LIMIT, 1), PICKER_MAX_LIMIT);
29
58
 
30
- const cmsAny = cms as Record<string, any>;
31
- const results: SearchResult[] = [];
59
+ const toResult = (collection: CollectionLike, doc: Record<string, unknown>): SearchResult => ({
60
+ collection: collection.slug,
61
+ collectionLabel: collection.singleton ? "Single" : collection.labels.singular,
62
+ docId: String(doc._id),
63
+ title: collection.singleton
64
+ ? collection.labels.singular
65
+ : String(doc[getLabelField(collection as any)] ?? doc.slug ?? doc._id),
66
+ editUrl: `/admin/${collection.slug}/${doc._id}`,
67
+ href: cmsAny.meta?.getRouteForDocument?.(collection.slug, doc) ?? null,
68
+ status: typeof doc._status === "string" ? doc._status : null,
69
+ });
70
+
71
+ // Picker mode: explicit target collections.
72
+ if (requested.length > 0) {
73
+ const collections = (config.collections as CollectionLike[]).filter(
74
+ (c) => requested.includes(c.slug) && !HIDDEN_FROM_SEARCH.has(c.slug),
75
+ );
76
+ const results: SearchResult[] = [];
77
+
78
+ for (const collection of collections) {
79
+ const api = cmsAny[collection.slug];
80
+ if (!api?.find) continue;
81
+
82
+ // access denied or runtime error — skip this collection silently, like the palette
83
+ const docs: Array<Record<string, unknown>> | null = await (async () => {
84
+ if (ids.length > 0) {
85
+ const found = await Promise.all(
86
+ ids.map((id) =>
87
+ api.find({ where: { _id: id }, status: "any", limit: 1 }, context).then((d: any[]) => d[0]),
88
+ ),
89
+ );
90
+ return found.filter(Boolean);
91
+ }
92
+ // Recently-updated first in both modes — without a sort, LIMIT keeps an
93
+ // arbitrary subset of the matches.
94
+ const sort = { field: "_updatedAt", direction: "desc" } as const;
95
+ if (q.length >= MIN_QUERY_LENGTH) return api.find({ search: q, status: "any", sort, limit }, context);
96
+ return api.find({ status: "any", sort, limit }, context);
97
+ })().catch(() => null);
98
+
99
+ if (!docs) continue;
100
+ for (const doc of docs) results.push(toResult(collection, doc));
101
+ }
102
+
103
+ return Response.json({ results });
104
+ }
32
105
 
106
+ // Palette mode: everything, a few hits per collection.
107
+ if (q.length < MIN_QUERY_LENGTH) return Response.json({ results: [] });
108
+
109
+ const results: SearchResult[] = [];
33
110
  const qLower = q.toLowerCase();
34
111
 
35
- for (const collection of config.collections) {
112
+ for (const collection of config.collections as CollectionLike[]) {
36
113
  if (HIDDEN_FROM_SEARCH.has(collection.slug)) continue;
37
-
38
114
  const api = cmsAny[collection.slug];
39
115
  if (!api?.find) continue;
40
116
 
@@ -42,47 +118,28 @@ export const GET: APIRoute = async ({ url, locals }) => {
42
118
  // on the collection's singular label (which is what gets shown to admins). Body-search
43
119
  // would fight UX: e.g. searching "front" for the "Front page" singleton must find it
44
120
  // even if the singleton's body text says nothing about "front".
45
- if (collection.singleton) {
46
- if (!collection.labels.singular.toLowerCase().includes(qLower)) continue;
47
- const docs = await api
48
- .find({ status: "any", limit: 1 }, { user: locals.user })
49
- .catch(() => null as Array<Record<string, unknown>> | null);
50
- if (!docs || docs.length === 0) continue;
51
- const doc = docs[0];
52
- results.push({
53
- collection: collection.slug,
54
- // Match the sidebar grouping: every singleton lives under one "Singles" header.
55
- collectionLabel: "Single",
56
- docId: String(doc._id),
57
- title: collection.labels.singular,
58
- editUrl: `/admin/${collection.slug}/${doc._id}`,
59
- status: typeof doc._status === "string" ? doc._status : null,
60
- });
61
- if (results.length >= TOTAL_CAP) break;
62
- continue;
63
- }
121
+ const docs: Array<Record<string, unknown>> | null = collection.singleton
122
+ ? collection.labels.singular.toLowerCase().includes(qLower)
123
+ ? await api.find({ status: "any", limit: 1 }, context).catch(() => null)
124
+ : []
125
+ : await api
126
+ .find(
127
+ {
128
+ search: q,
129
+ status: "any",
130
+ sort: { field: "_updatedAt", direction: "desc" },
131
+ limit: PALETTE_PER_COLLECTION,
132
+ },
133
+ context,
134
+ )
135
+ .catch(() => null);
64
136
 
65
- const docs = await api
66
- .find({ search: q, status: "any", limit: PER_COLLECTION }, { user: locals.user })
67
- .catch(() => null as Array<Record<string, unknown>> | null);
68
-
69
- // access denied or runtime error — skip this collection silently
70
137
  if (!docs) continue;
71
-
72
- const labelField = getLabelField(collection);
73
138
  for (const doc of docs) {
74
- const title = String(doc[labelField] ?? doc.slug ?? doc._id);
75
- results.push({
76
- collection: collection.slug,
77
- collectionLabel: collection.labels.singular,
78
- docId: String(doc._id),
79
- title,
80
- editUrl: `/admin/${collection.slug}/${doc._id}`,
81
- status: typeof doc._status === "string" ? doc._status : null,
82
- });
83
- if (results.length >= TOTAL_CAP) break;
139
+ results.push(toResult(collection, doc));
140
+ if (results.length >= PALETTE_TOTAL_CAP) break;
84
141
  }
85
- if (results.length >= TOTAL_CAP) break;
142
+ if (results.length >= PALETTE_TOTAL_CAP) break;
86
143
  }
87
144
 
88
145
  return Response.json({ results });
@@ -60,8 +60,10 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
60
60
  return Response.json({ error: "Users collection not configured." }, { status: 500 });
61
61
  }
62
62
 
63
- // Prevent setup if users already exist (fast path / friendly redirect).
64
- const existing = await db.select().from(tables.users.main).limit(1);
63
+ // Prevent setup if an admin already exists (fast path / friendly redirect).
64
+ // Deliberately admin-scoped: seeded demo editors, or an invite that created an
65
+ // editor first, must not strand a project with no way to make its first admin.
66
+ const existing = await db.select().from(tables.users.main).where(eq(tables.users.main.role, "admin")).limit(1);
65
67
  if (existing.length > 0) {
66
68
  return new Response(null, {
67
69
  status: 303,
@@ -74,12 +76,12 @@ export const POST: APIRoute = async ({ request, clientAddress }) => {
74
76
  const hashedPassword = await hashPassword(password);
75
77
 
76
78
  // Atomic winner election that leaves no orphan state: a single conditional insert creates
77
- // the first admin only if the table is still empty. Self-recovering — if anything fails
78
- // there's no marker to strand setup, and a retry just runs the same guarded insert.
79
+ // the first admin only if none exists yet. Self-recovering — if anything fails there's no
80
+ // marker to strand setup, and a retry just runs the same guarded insert.
79
81
  await db.run(sql`
80
82
  INSERT INTO cms_users (_id, name, email, role, password, _created_at, _updated_at)
81
83
  SELECT ${id}, ${name}, ${email}, 'admin', ${hashedPassword}, ${now}, ${now}
82
- WHERE NOT EXISTS (SELECT 1 FROM cms_users)
84
+ WHERE NOT EXISTS (SELECT 1 FROM cms_users WHERE role = 'admin')
83
85
  `);
84
86
 
85
87
  // Confirm we won the race (our row exists). If not, another concurrent setup created the
@@ -45,6 +45,15 @@ export const GET: APIRoute = async ({ url }) => {
45
45
  return Response.json({ state, comments, activity });
46
46
  };
47
47
 
48
+ // Editing is author-only, deliberately narrower than resolve/delete: removing a
49
+ // comment is moderation, but rewriting the words under someone else's name and
50
+ // avatar is not something an approver should be able to do.
51
+ const authorizeCommentEdit = async (commentId: string, actor: { id: string }) => {
52
+ const comment = await collaboration.getComment(commentId);
53
+ if (!comment || !isEnabled(comment.collection)) return null;
54
+ return comment.authorId === actor.id ? comment : null;
55
+ };
56
+
48
57
  // POST /api/cms/collaboration { collection, id, action, ...payload }
49
58
  export const POST: APIRoute = async ({ request, locals }) => {
50
59
  const actor = getActor(locals);
@@ -85,6 +94,12 @@ export const POST: APIRoute = async ({ request, locals }) => {
85
94
  );
86
95
  return Response.json({ comment });
87
96
  }
97
+ case "updateComment": {
98
+ const comment = await authorizeCommentEdit(String((body as any).commentId), actor);
99
+ if (!comment) return forbidden();
100
+ const updated = await collaboration.updateComment(comment._id, String((body as any).body ?? ""), actor);
101
+ return Response.json({ comment: updated });
102
+ }
88
103
  case "resolveComment": {
89
104
  const comment = await authorizeComment(String((body as any).commentId), actor);
90
105
  if (!comment) return forbidden();
@@ -1 +0,0 @@
1
- deleting