@kidecms/core 0.15.0 → 0.16.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.
@@ -806,7 +806,7 @@ export default function AssetsGrid({
806
806
 
807
807
  {/* Selection toolbar */}
808
808
  {selectedIds.size > 0 && (
809
- <div className="bg-muted/40 flex items-center justify-between gap-3 rounded-lg border px-3 py-2">
809
+ <div className="bg-background sticky top-4 z-20 flex items-center justify-between gap-3 rounded-lg border px-3 py-2 shadow-sm">
810
810
  <span className="text-sm font-medium">{selectedIds.size} selected</span>
811
811
  <div className="flex items-center gap-2">
812
812
  <Button
@@ -20,7 +20,7 @@ const buttonVariants = cva(
20
20
  ghost:
21
21
  "border-transparent hover:bg-foreground/8 hover:text-foreground aria-expanded:bg-foreground/8 aria-expanded:text-foreground dark:hover:bg-foreground/15 dark:aria-expanded:bg-foreground/15",
22
22
  destructive:
23
- "border-transparent bg-destructive/10 text-destructive hover:bg-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30",
23
+ "bg-red-100 hover:bg-red-200/70 text-red-800 border-red-300 dark:bg-red-500/20 dark:hover:bg-red-500/30 dark:border-red-900 dark:text-red-200",
24
24
  link: "border-transparent text-primary underline-offset-4 hover:underline",
25
25
  },
26
26
  size: {
@@ -11,6 +11,7 @@ import {
11
11
  formatDate,
12
12
  formatFieldValue,
13
13
  formatPagePath,
14
+ getPageHref,
14
15
  getLabelField,
15
16
  getListColumns,
16
17
  getTranslatableFieldNames,
@@ -175,7 +176,7 @@ const tableRows = docs.map((entry: Record<string, unknown>) => {
175
176
  : []),
176
177
  ],
177
178
  searchText: String(entry[getLabelField(collection)] ?? entry.slug ?? entry._id ?? ""),
178
- pageHref: pagePath ? `${pagePath}?preview=true` : undefined,
179
+ pageHref: pagePath ? getPageHref(pagePath, !collection.drafts || entry._status === "published") : undefined,
179
180
  values: Object.fromEntries(displayColumns.map((column) => [column, formatColumnValue(column, entry, pagePath)])),
180
181
  };
181
182
  });
@@ -2,7 +2,7 @@
2
2
  import DocumentsDataTable from "../components/DocumentsDataTable";
3
3
  import config from "virtual:kide/config";
4
4
  import { cms } from "virtual:kide/api";
5
- import { formatDate, formatPagePath, getTranslatableFieldNames } from "../../core";
5
+ import { formatDate, formatPagePath, getPageHref, getTranslatableFieldNames } from "../../core";
6
6
  import { canRead } from "../lib/access";
7
7
 
8
8
  const user = Astro.locals.user;
@@ -46,7 +46,9 @@ const singletonsData = await Promise.all(
46
46
  updatedAt: singleDoc ? formatDate(singleDoc._updatedAt) : "—",
47
47
  editHref: `/admin/${sc.slug}`,
48
48
  page: pagePath,
49
- pageHref: pagePath ? `${pagePath}?preview=true` : null,
49
+ pageHref: pagePath
50
+ ? getPageHref(pagePath, !!singleDoc && (!sc.drafts || singleDoc._status === "published"))
51
+ : null,
50
52
  };
51
53
  }),
52
54
  );
package/client/preview.ts CHANGED
@@ -33,3 +33,58 @@ if (new URLSearchParams(location.search).has("preview")) {
33
33
  }
34
34
  };
35
35
  }
36
+
37
+ // --- Edit bar: "Edit this page" chip on public pages for logged-in editors ---
38
+ // Zero-cost for anonymous visitors: only acts when the non-httpOnly `kide-editor`
39
+ // hint cookie (set by the auth middleware on admin visits) is present, and only
40
+ // then verifies the real session via the edit-bar endpoint. Renders into a shadow
41
+ // root so site CSS can't leak in. Skipped in preview mode (the editor is already
42
+ // editing in another tab) and on admin pages.
43
+ if (
44
+ !new URLSearchParams(location.search).has("preview") &&
45
+ !location.pathname.startsWith("/admin") &&
46
+ document.cookie.split("; ").includes("kide-editor=1")
47
+ ) {
48
+ const marker = document.querySelector("[data-cms-doc]");
49
+ const ref = marker?.getAttribute("data-cms-doc");
50
+ if (ref) {
51
+ fetch(`/api/cms/edit-bar?doc=${encodeURIComponent(ref)}`)
52
+ .then((r) => {
53
+ if (r.status === 401) {
54
+ // Session gone — drop the hint so future page views stay request-free.
55
+ document.cookie = "kide-editor=; Path=/; Max-Age=0";
56
+ return null;
57
+ }
58
+ return r.ok ? r.json() : null;
59
+ })
60
+ .then((data: { editUrl: string; status: string | null } | null) => {
61
+ if (!data) return;
62
+ const host = document.createElement("div");
63
+ const shadow = host.attachShadow({ mode: "open" });
64
+ // Static markup only — editUrl embeds a caller-suppliable document id, so
65
+ // it goes through setAttribute, never into an HTML string.
66
+ shadow.innerHTML = `
67
+ <style>
68
+ a {
69
+ position: fixed; right: 16px; bottom: 16px; z-index: 2147483647;
70
+ display: inline-flex; align-items: center; gap: 8px;
71
+ padding: 8px 14px; border-radius: 999px;
72
+ background: #18181b; color: #fafafa;
73
+ font: 500 13px/1 system-ui, sans-serif; text-decoration: none;
74
+ box-shadow: 0 2px 12px rgba(0, 0, 0, 0.25);
75
+ }
76
+ a:hover { background: #303036; }
77
+ svg { width: 13px; height: 13px; }
78
+ </style>
79
+ <a>
80
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
81
+ <path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
82
+ </svg>
83
+ Edit this page
84
+ </a>`;
85
+ shadow.querySelector("a")!.setAttribute("href", data.editUrl);
86
+ document.body.appendChild(host);
87
+ })
88
+ .catch(() => {});
89
+ }
90
+ }
package/core/admin.ts CHANGED
@@ -106,6 +106,9 @@ export const resolveAdminRoute = (path: string | undefined): AdminRoute => {
106
106
  /** Display text for a document's public URL in list tables — the bare root path reads as "Homepage" instead of "/". */
107
107
  export const formatPagePath = (path: string | null | undefined) => (path === "/" ? "Homepage" : (path ?? "—"));
108
108
 
109
+ /** Link target for the URL column: live documents open the real page; never-published drafts only exist behind ?preview. */
110
+ export const getPageHref = (pagePath: string, isLive: boolean) => (isLive ? pagePath : `${pagePath}?preview=true`);
111
+
109
112
  export const humanize = (value: string) =>
110
113
  value
111
114
  .replace(/^_+/, "")
package/core/define.ts CHANGED
@@ -382,6 +382,8 @@ export type AdminConfig = {
382
382
  */
383
383
  dateTimePattern?: string;
384
384
  nav?: AdminNavItem[];
385
+ /** "Edit this page" chip on public pages for logged-in editors (default: true). */
386
+ editBar?: boolean;
385
387
  uploads?: AdminUploadConfig;
386
388
  rateLimit?: AdminRateLimitConfig;
387
389
  auth?: AdminAuthConfig;
package/core/index.ts CHANGED
@@ -180,6 +180,7 @@ export {
180
180
  humanize,
181
181
  formatFieldValue,
182
182
  formatPagePath,
183
+ getPageHref,
183
184
  getListColumns,
184
185
  getFieldGroups,
185
186
  getFieldSets,
@@ -312,6 +312,10 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
312
312
  pattern: "/api/cms/collaboration",
313
313
  entrypoint: new URL("../routes/api/collaboration/index.ts", import.meta.url),
314
314
  });
315
+ injectRoute({
316
+ pattern: "/api/cms/edit-bar",
317
+ entrypoint: new URL("../routes/api/edit-bar.ts", import.meta.url),
318
+ });
315
319
  injectRoute({
316
320
  pattern: "/api/cms/ai/alt-text",
317
321
  entrypoint: new URL("../routes/api/ai/alt-text.ts", import.meta.url),
@@ -200,6 +200,22 @@ const handle = async (context: APIContext, next: MiddlewareNext) => {
200
200
  ? normalizeCustomUser(await customProvider.getSession(context.request))
201
201
  : await getSessionUser(context.request);
202
202
 
203
+ // Non-httpOnly hint for the public-site edit bar: lets the injected client skip
204
+ // the session check entirely for anonymous visitors. Carries no auth value — the
205
+ // edit-bar endpoint verifies the real session. Only ever set/cleared on /admin
206
+ // responses, which are never cached, so it can't poison the shared cache.
207
+ const hasEditorHint = (context.request.headers.get("cookie") ?? "").split(/;\s*/).includes("kide-editor=1");
208
+ const editBarEnabled = config.admin?.editBar !== false;
209
+ const secure = process.env.NODE_ENV === "production" ? "; Secure" : "";
210
+ const withEditorHint = (response: Response, loggedIn: boolean) => {
211
+ if (loggedIn && editBarEnabled && !hasEditorHint) {
212
+ response.headers.append("Set-Cookie", `kide-editor=1; Path=/; SameSite=Strict${secure}; Max-Age=2592000`);
213
+ } else if (hasEditorHint && (!loggedIn || !editBarEnabled)) {
214
+ response.headers.append("Set-Cookie", `kide-editor=; Path=/; SameSite=Strict${secure}; Max-Age=0`);
215
+ }
216
+ return response;
217
+ };
218
+
203
219
  if (!user) {
204
220
  // API routes → 401
205
221
  if (isAdminApiRoute) {
@@ -209,11 +225,11 @@ const handle = async (context: APIContext, next: MiddlewareNext) => {
209
225
  });
210
226
  }
211
227
  // Admin pages → redirect to login
212
- return context.redirect("/admin/login");
228
+ return withEditorHint(context.redirect("/admin/login"), false);
213
229
  }
214
230
 
215
231
  // Attach user to locals for downstream use
216
232
  context.locals.user = user;
217
233
 
218
- return serve();
234
+ return withEditorHint(await serve(), true);
219
235
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "Kide CMS runtime — core library, admin UI, routes, and middleware for Astro. Shipped as TypeScript source.",
5
5
  "keywords": [
6
6
  "cms",
@@ -3,7 +3,7 @@ import type { APIRoute } from "astro";
3
3
  import config from "virtual:kide/config";
4
4
  import { cms } from "virtual:kide/api";
5
5
  import { collaboration } from "virtual:kide/runtime";
6
- import { formatPagePath, isApprover, resolveCollaboration } from "../../../core";
6
+ import { formatPagePath, getPageHref, isApprover, resolveCollaboration } from "../../../core";
7
7
  import { loadSharedSectionUsageCounts } from "../../../admin/lib/edit-data";
8
8
 
9
9
  export const prerender = false;
@@ -295,7 +295,9 @@ export const GET: APIRoute = async ({ params, url, locals }) => {
295
295
  ? collection.preview
296
296
  : cmsRuntime.meta.getRouteForDocument(collectionSlug, entry)
297
297
  : null;
298
- if (pagePath) entry._pageHref = `${pagePath}?preview=true`;
298
+ if (pagePath) {
299
+ entry._pageHref = getPageHref(pagePath, !collection.drafts || entry._status === "published");
300
+ }
299
301
  entry.__page = formatPagePath(pagePath);
300
302
  }
301
303
  }
@@ -0,0 +1,46 @@
1
+ import type { APIRoute } from "astro";
2
+ import config from "virtual:kide/config";
3
+ import { cms } from "virtual:kide/api";
4
+ import { canRead, getVisualStatus } from "../../admin/lib/access";
5
+
6
+ export const prerender = false;
7
+
8
+ const cmsRuntime = cms as Record<string, any>;
9
+
10
+ // Resolves a public page's `data-cms-doc="<collection>:<id>"` marker into an admin
11
+ // edit URL for the edit-bar chip. Auth is enforced by the middleware (401 without a
12
+ // session); this only decides whether THIS user may see a link to THIS document.
13
+ export const GET: APIRoute = async ({ url, locals }) => {
14
+ if (config.admin?.editBar === false) {
15
+ return Response.json({ error: "Not found" }, { status: 404 });
16
+ }
17
+
18
+ const ref = url.searchParams.get("doc") ?? "";
19
+ const separator = ref.indexOf(":");
20
+ const collectionSlug = separator === -1 ? ref : ref.slice(0, separator);
21
+ const documentId = separator === -1 ? "" : ref.slice(separator + 1);
22
+
23
+ const collection = config.collections.find((c) => c.slug === collectionSlug);
24
+ const user = locals.user;
25
+ if (!collection || collection.auth || !documentId || !user || !canRead(config, user, collectionSlug)) {
26
+ return Response.json({ error: "Not found" }, { status: 404, headers: { "Cache-Control": "no-store" } });
27
+ }
28
+
29
+ let doc: Record<string, unknown> | null;
30
+ try {
31
+ doc = await cmsRuntime[collectionSlug].findById(documentId, { status: "any" }, { user });
32
+ } catch {
33
+ doc = null;
34
+ }
35
+ if (!doc) {
36
+ return Response.json({ error: "Not found" }, { status: 404, headers: { "Cache-Control": "no-store" } });
37
+ }
38
+
39
+ return Response.json(
40
+ {
41
+ editUrl: collection.singleton ? `/admin/${collectionSlug}` : `/admin/${collectionSlug}/${documentId}`,
42
+ status: collection.drafts ? getVisualStatus(doc) : null,
43
+ },
44
+ { headers: { "Cache-Control": "no-store" } },
45
+ );
46
+ };