@kidecms/core 0.27.0 → 0.27.2

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.
@@ -3,6 +3,7 @@
3
3
  import { useState, useCallback, useEffect, useRef } from "react";
4
4
  import { ArrowUpRight, GripVertical, ChevronRight, Link2, Plus, Save, Trash2, Unlink } from "lucide-react";
5
5
  import { cn } from "../lib/utils";
6
+ import { openPreviewChannel } from "../lib/preview-channel";
6
7
  import {
7
8
  DndContext,
8
9
  closestCenter,
@@ -300,8 +301,9 @@ export default function BlockEditor({
300
301
  // Live preview: broadcast block data for server-side rendering. Also replay the
301
302
  // current value when a preview tab opened after edits announces itself.
302
303
  useEffect(() => {
303
- if (!previewChannelRef.current) previewChannelRef.current = new BroadcastChannel("cms-preview");
304
+ if (!previewChannelRef.current) previewChannelRef.current = openPreviewChannel();
304
305
  const channel = previewChannelRef.current;
306
+ if (!channel) return;
305
307
  const broadcast = () => channel.postMessage({ field: name, value: serializeBlocks(blocks), render: "blocks" });
306
308
  broadcast();
307
309
  channel.onmessage = (e: MessageEvent) => {
@@ -27,6 +27,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, D
27
27
  import { Input } from "./ui/input";
28
28
  import { cn } from "../lib/utils";
29
29
  import { toggleHeading } from "../lib/editor-commands";
30
+ import { openPreviewChannel } from "../lib/preview-channel";
30
31
  import {
31
32
  LinkDialog,
32
33
  fetchLinkGroups,
@@ -457,8 +458,9 @@ export default function ContentEditor({
457
458
 
458
459
  // Replay the current value when a preview tab opened after edits announces itself
459
460
  useEffect(() => {
460
- if (!previewChannelRef.current) previewChannelRef.current = new BroadcastChannel("cms-preview");
461
+ if (!previewChannelRef.current) previewChannelRef.current = openPreviewChannel();
461
462
  const channel = previewChannelRef.current;
463
+ if (!channel) return;
462
464
  channel.onmessage = (e: MessageEvent) => {
463
465
  if (e.data?.type === "preview-ready") {
464
466
  channel.postMessage({ field: name, value: cmsJson, render: "content" });
@@ -495,8 +497,8 @@ export default function ContentEditor({
495
497
  const json = JSON.stringify(cmsDoc);
496
498
  setCmsJson(json);
497
499
  // Live preview: broadcast for server-side rendering
498
- if (!previewChannelRef.current) previewChannelRef.current = new BroadcastChannel("cms-preview");
499
- previewChannelRef.current.postMessage({ field: name, value: json, render: "content" });
500
+ if (!previewChannelRef.current) previewChannelRef.current = openPreviewChannel();
501
+ previewChannelRef.current?.postMessage({ field: name, value: json, render: "content" });
500
502
  },
501
503
  onSelectionUpdate: forceTick,
502
504
  onTransaction: forceTick,
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
 
3
- import { useEffect, useRef, useState } from "react";
3
+ import { useEffect, useRef, useState, type RefObject } from "react";
4
4
  import type { Editor } from "@tiptap/core";
5
5
  import Image from "@tiptap/extension-image";
6
6
  import { NodeViewWrapper, ReactNodeViewRenderer, type NodeViewProps } from "@tiptap/react";
@@ -10,19 +10,29 @@ import { Input } from "./ui/input";
10
10
  import ImageBrowseDialog from "./ImageBrowseDialog";
11
11
  import { cn, thumbnail } from "../lib/utils";
12
12
 
13
- /** Node views only re-render on node/selection changes, so track editor focus ourselves. */
14
- function useEditorFocus(editor: Editor) {
13
+ /**
14
+ * Node views only re-render on node/selection changes, so track editor focus
15
+ * ourselves. A blur whose focus lands inside `within` (the node's own toolbar)
16
+ * is ignored: in Chrome a mousedown on a button moves focus there before the
17
+ * click fires, and dropping `focused` at that point would unmount the toolbar
18
+ * under the pointer, so the click never happens.
19
+ */
20
+ function useEditorFocus(editor: Editor, within: RefObject<HTMLElement | null>) {
15
21
  const [focused, setFocused] = useState(editor.isFocused);
16
22
  useEffect(() => {
17
23
  const on = () => setFocused(true);
18
- const off = () => setFocused(false);
24
+ const off = ({ event }: { event: FocusEvent }) => {
25
+ const next = event.relatedTarget as Node | null;
26
+ if (next && within.current?.contains(next)) return;
27
+ setFocused(false);
28
+ };
19
29
  editor.on("focus", on);
20
30
  editor.on("blur", off);
21
31
  return () => {
22
32
  editor.off("focus", on);
23
33
  editor.off("blur", off);
24
34
  };
25
- }, [editor]);
35
+ }, [editor, within]);
26
36
  return focused;
27
37
  }
28
38
 
@@ -34,7 +44,8 @@ function useEditorFocus(editor: Editor) {
34
44
  function ImageNodeView({ node, selected, editor, getPos, updateAttributes, deleteNode }: NodeViewProps) {
35
45
  const [browseOpen, setBrowseOpen] = useState(false);
36
46
  const [focusWithin, setFocusWithin] = useState(false);
37
- const focused = useEditorFocus(editor);
47
+ const wrapperRef = useRef<HTMLDivElement>(null);
48
+ const focused = useEditorFocus(editor, wrapperRef);
38
49
  const src = String(node.attrs.src ?? "");
39
50
  const alt = String(node.attrs.alt ?? "");
40
51
 
@@ -56,7 +67,6 @@ function ImageNodeView({ node, selected, editor, getPos, updateAttributes, delet
56
67
  // draws a bare <img> at natural size, so the ghost is a sized div. A real drag
57
68
  // starts on Tiptap's outer node element (the wrapper's parent), and Tiptap
58
69
  // sets its own ghost from React's root listener — override from the document.
59
- const wrapperRef = useRef<HTMLDivElement>(null);
60
70
  const ghostRef = useRef<HTMLDivElement>(null);
61
71
  useEffect(() => {
62
72
  const onDragStart = (e: DragEvent) => {
@@ -27,6 +27,7 @@ import { Label } from "./ui/label";
27
27
  import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
28
28
  import { cn } from "../lib/utils";
29
29
  import { toggleHeading } from "../lib/editor-commands";
30
+ import { openPreviewChannel } from "../lib/preview-channel";
30
31
  import ImageBrowseDialog from "./ImageBrowseDialog";
31
32
 
32
33
  // -----------------------------------------------
@@ -441,8 +442,9 @@ export default function RichTextEditor({ name, initialValue, rows = 10, onChange
441
442
 
442
443
  // Replay the current value when a preview tab opened after edits announces itself
443
444
  useEffect(() => {
444
- if (!previewChannelRef.current) previewChannelRef.current = new BroadcastChannel("cms-preview");
445
+ if (!previewChannelRef.current) previewChannelRef.current = openPreviewChannel();
445
446
  const channel = previewChannelRef.current;
447
+ if (!channel) return;
446
448
  channel.onmessage = (e: MessageEvent) => {
447
449
  if (e.data?.type === "preview-ready") {
448
450
  channel.postMessage({ field: name, value: cmsJson, render: "richText" });
@@ -475,8 +477,8 @@ export default function RichTextEditor({ name, initialValue, rows = 10, onChange
475
477
  setCmsJson(json);
476
478
  onChange?.(json);
477
479
  // Live preview: broadcast for server-side rendering
478
- if (!previewChannelRef.current) previewChannelRef.current = new BroadcastChannel("cms-preview");
479
- previewChannelRef.current.postMessage({ field: name, value: json, render: "richText" });
480
+ if (!previewChannelRef.current) previewChannelRef.current = openPreviewChannel();
481
+ previewChannelRef.current?.postMessage({ field: name, value: json, render: "richText" });
480
482
  },
481
483
  onSelectionUpdate: forceTick,
482
484
  onTransaction: forceTick,
@@ -11,6 +11,7 @@ import {
11
11
  AlertDialogHeader,
12
12
  AlertDialogTitle,
13
13
  } from "./ui/alert-dialog";
14
+ import { openPreviewChannel } from "../lib/preview-channel";
14
15
  import { Button } from "./ui/button";
15
16
 
16
17
  /**
@@ -68,26 +69,27 @@ export default function UnsavedGuard({
68
69
  };
69
70
 
70
71
  // Live preview: broadcast field changes to any open preview tab
71
- const previewChannel = new BroadcastChannel("cms-preview");
72
+ const previewChannel = openPreviewChannel();
72
73
  const broadcastField = (e: Event) => {
73
74
  const target = e.target as HTMLInputElement;
74
75
  if (!target.name || target.name.startsWith("_") || target.name === "redirectTo") return;
75
76
  // Skip hidden inputs — complex fields (rich text, blocks) handle their own broadcasting
76
77
  if (target.type === "hidden") return;
77
- previewChannel.postMessage({ field: target.name, value: target.value });
78
+ previewChannel?.postMessage({ field: target.name, value: target.value });
78
79
  };
79
80
 
80
81
  // A preview tab opened after edits were made announces itself; replay the
81
82
  // current value of every simple field so it doesn't miss unsaved changes.
82
- previewChannel.onmessage = (e: MessageEvent) => {
83
- if (e.data?.type !== "preview-ready") return;
84
- for (const el of Array.from(form.elements)) {
85
- const input = el as HTMLInputElement;
86
- if (!input.name || input.name.startsWith("_") || input.name === "redirectTo") continue;
87
- if (input.type === "hidden" || input.type === "submit" || input.type === "button") continue;
88
- previewChannel.postMessage({ field: input.name, value: input.value });
89
- }
90
- };
83
+ if (previewChannel)
84
+ previewChannel.onmessage = (e: MessageEvent) => {
85
+ if (e.data?.type !== "preview-ready") return;
86
+ for (const el of Array.from(form.elements)) {
87
+ const input = el as HTMLInputElement;
88
+ if (!input.name || input.name.startsWith("_") || input.name === "redirectTo") continue;
89
+ if (input.type === "hidden" || input.type === "submit" || input.type === "button") continue;
90
+ previewChannel?.postMessage({ field: input.name, value: input.value });
91
+ }
92
+ };
91
93
 
92
94
  form.addEventListener("input", checkDirty);
93
95
  form.addEventListener("input", broadcastField);
@@ -101,7 +103,7 @@ export default function UnsavedGuard({
101
103
  form.removeEventListener("change", checkDirty);
102
104
  form.removeEventListener("change", broadcastField);
103
105
  form.removeEventListener("submit", handleSubmit);
104
- previewChannel.close();
106
+ previewChannel?.close();
105
107
  };
106
108
  }, [formId, isNew, isDraft]);
107
109
 
@@ -0,0 +1,13 @@
1
+ // Live preview is scoped per document: the edit view stamps
2
+ // `data-preview-channel="<collection>:<id>"` and links the preview tab with the same
3
+ // key in `?preview=`, so an editor only drives the preview of its own document
4
+ // (a single shared channel let any open edit tab overwrite every preview tab).
5
+
6
+ export const previewChannelName = (key: string) => `cms-preview:${key}`;
7
+
8
+ /** Opens this edit view's preview channel, or null when the document has no preview. */
9
+ export function openPreviewChannel(): BroadcastChannel | null {
10
+ if (typeof document === "undefined" || typeof BroadcastChannel === "undefined") return null;
11
+ const key = document.querySelector<HTMLElement>("[data-preview-channel]")?.dataset.previewChannel;
12
+ return key ? new BroadcastChannel(previewChannelName(key)) : null;
13
+ }
@@ -186,11 +186,12 @@ const hasSidebarMeta = reverseRefs.length > 0 || hasDocMeta;
186
186
  const hasSidebarColumn = !isSubmissionView && (hasSidebarFields || hasSidebarMeta);
187
187
 
188
188
  const hasPreview = !!(mode === "edit" && (collection.preview || (collection.pathPrefix && doc?.slug)));
189
- const previewUrl = hasPreview
190
- ? typeof collection.preview === "string"
191
- ? `${collection.preview}?preview=true`
192
- : `${cms.meta.getRouteForDocument(collection.slug, doc)}?preview=true`
193
- : null;
189
+ // Live-preview channel key: the preview tab only listens to this document's editor.
190
+ const previewKey = hasPreview && documentId ? `${collection.slug}:${documentId}` : null;
191
+ const previewUrl =
192
+ hasPreview && previewKey
193
+ ? `${typeof collection.preview === "string" ? collection.preview : cms.meta.getRouteForDocument(collection.slug, doc)}?preview=${encodeURIComponent(previewKey)}`
194
+ : null;
194
195
 
195
196
  const getCurrentValue = (fieldName: string) => (doc ? doc[fieldName] : undefined);
196
197
  const getSharedValue = (fieldName: string) => (baseDoc ? baseDoc[fieldName] : undefined);
@@ -437,7 +438,7 @@ const publishBlocked =
437
438
  (doc?._status === "draft" || doc?._status === "scheduled" || (doc && getVisualStatus(doc) === "changed")),
438
439
  )}
439
440
  />
440
- <div id="document-edit-area">
441
+ <div id="document-edit-area" data-preview-channel={!translationMode ? previewKey : undefined}>
441
442
  {collection.slug === "users" && mode === "edit" && Astro.url.searchParams.get("inviteToken") && (
442
443
  <AdminCard title={Astro.url.searchParams.get("emailSent") === "true" ? "Invitation sent" : "Invite link"}>
443
444
  {Astro.url.searchParams.get("emailSent") === "true" ? (
@@ -200,7 +200,9 @@
200
200
  }
201
201
  if (u.searchParams.get("_toast") === "success") {
202
202
  try {
203
- new BroadcastChannel("cms-preview").postMessage({ type: "reload" });
203
+ var previewEl = document.querySelector("[data-preview-channel]");
204
+ var previewKey = previewEl && previewEl.getAttribute("data-preview-channel");
205
+ if (previewKey) new BroadcastChannel("cms-preview:" + previewKey).postMessage({ type: "reload" });
204
206
  } catch (e) {}
205
207
  }
206
208
  if (window.parent !== window && u.searchParams.get("_toast") === "success") {
package/client/preview.ts CHANGED
@@ -1,5 +1,8 @@
1
- if (new URLSearchParams(location.search).has("preview")) {
2
- const ch = new BroadcastChannel("cms-preview");
1
+ // `?preview=<collection>:<id>` (as linked from the edit view) scopes live updates to
2
+ // that document's editor. A bare `?preview` / `?preview=true` only shows drafts.
3
+ const previewKey = new URLSearchParams(location.search).get("preview");
4
+ if (previewKey && previewKey !== "true") {
5
+ const ch = new BroadcastChannel(`cms-preview:${previewKey}`);
3
6
  let pending = 0;
4
7
 
5
8
  ch.onmessage = (e: MessageEvent) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.27.0",
3
+ "version": "0.27.2",
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",
@@ -17,10 +17,7 @@
17
17
  // [[d1_databases]] and [[r2_buckets]]. Catches a binding-name typo at typecheck time.
18
18
  // IMAGES isn't in wrangler.toml: @astrojs/cloudflare adds it to every build (its
19
19
  // `imagesBindingName` option), so it's optional here and images.ts copes without it.
20
- export type CfEnv = { CMS_DB?: D1Database; CMS_ASSETS?: R2Bucket; IMAGES?: ImagesBinding } & Record<
21
- string,
22
- unknown
23
- >;
20
+ export type CfEnv = { CMS_DB?: D1Database; CMS_ASSETS?: R2Bucket; IMAGES?: ImagesBinding } & Record<string, unknown>;
24
21
 
25
22
  type CfProxy = { env: CfEnv; dispose: () => Promise<void> };
26
23