@kidecms/core 0.25.1 → 0.26.1

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.
@@ -248,6 +248,11 @@
248
248
  margin: 0.75em 0 0.4em;
249
249
  }
250
250
 
251
+ /* A bold mark inside a heading (legacy imports) must not out-weigh the heading. */
252
+ .tiptap :is(h1, h2, h3, h4, h5, h6) strong {
253
+ font-weight: inherit;
254
+ }
255
+
251
256
  .tiptap ul:not([data-node-view-wrapper] *),
252
257
  [data-node-view-wrapper] .tiptap ul {
253
258
  padding-left: 1.5em;
@@ -2,7 +2,8 @@ import { useEditor, EditorContent, NodeViewWrapper, ReactNodeViewRenderer, type
2
2
  import { BubbleMenu } from "@tiptap/react/menus";
3
3
  import { Node } from "@tiptap/core";
4
4
  import StarterKit from "@tiptap/starter-kit";
5
- import Image from "@tiptap/extension-image";
5
+ import { EditorImage } from "./EditorImage";
6
+ import ImageBrowseDialog from "./ImageBrowseDialog";
6
7
  import Link from "@tiptap/extension-link";
7
8
  import Placeholder from "@tiptap/extension-placeholder";
8
9
  import { useCallback, useEffect, useId, useRef, useState } from "react";
@@ -25,6 +26,7 @@ import { Button, buttonVariants } from "./ui/button";
25
26
  import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "./ui/dialog";
26
27
  import { Input } from "./ui/input";
27
28
  import { cn } from "../lib/utils";
29
+ import { toggleHeading } from "../lib/editor-commands";
28
30
  import {
29
31
  LinkDialog,
30
32
  fetchLinkGroups,
@@ -381,6 +383,12 @@ type Props = {
381
383
  fullscreen?: boolean;
382
384
  };
383
385
 
386
+ // Stable identities: BubbleMenu dispatches an "updateOptions" transaction whenever
387
+ // these props change, and that transaction would trigger forceTick and a new render.
388
+ const BUBBLE_MENU_OPTIONS = { placement: "top" as const };
389
+ const shouldShowBubbleMenu: React.ComponentProps<typeof BubbleMenu>["shouldShow"] = ({ editor, from, to }) =>
390
+ from !== to && !editor.isActive(BLOCK_NODE_NAME) && !editor.isActive("image");
391
+
384
392
  export default function ContentEditor({
385
393
  name,
386
394
  label,
@@ -404,6 +412,7 @@ export default function ContentEditor({
404
412
  );
405
413
  const previewChannelRef = useRef<BroadcastChannel | null>(null);
406
414
  const [linkDialogOpen, setLinkDialogOpen] = useState(false);
415
+ const [imageBrowseOpen, setImageBrowseOpen] = useState(false);
407
416
  const [linkType, setLinkType] = useState<"internal" | "external">("internal");
408
417
  const [linkUrl, setLinkUrl] = useState("");
409
418
  const [linkGroups, setLinkGroups] = useState<LinkGroup[]>([]);
@@ -429,14 +438,22 @@ export default function ContentEditor({
429
438
  }
430
439
  })();
431
440
 
441
+ // The form value only moves when the content really differs from the editor's
442
+ // own serialisation of the initial document. A no-op transaction (a click,
443
+ // TrailingNode appending its paragraph) re-serialises with normalised keys,
444
+ // which would otherwise read as an unsaved change.
445
+ const [initialJson] = useState(cmsJson);
446
+ const [baseline, setBaseline] = useState<string | null>(null);
447
+ const formValue = cmsJson === baseline ? initialJson : cmsJson;
448
+
432
449
  // Notify the form of value changes so UnsavedGuard detects them
433
- const prevCmsJsonRef = useRef(cmsJson);
450
+ const prevFormValueRef = useRef(formValue);
434
451
  useEffect(() => {
435
- if (prevCmsJsonRef.current !== cmsJson) {
436
- prevCmsJsonRef.current = cmsJson;
452
+ if (prevFormValueRef.current !== formValue) {
453
+ prevFormValueRef.current = formValue;
437
454
  hiddenRef.current?.dispatchEvent(new Event("change", { bubbles: true }));
438
455
  }
439
- }, [cmsJson]);
456
+ }, [formValue]);
440
457
 
441
458
  // Replay the current value when a preview tab opened after edits announces itself
442
459
  useEffect(() => {
@@ -451,10 +468,13 @@ export default function ContentEditor({
451
468
 
452
469
  const editor = useEditor({
453
470
  immediatelyRender: false,
471
+ onCreate: ({ editor }) => {
472
+ setBaseline(JSON.stringify(tiptapToContent(editor.getJSON())));
473
+ },
454
474
  extensions: [
455
475
  // StarterKit bundles its own Link; disabled so the configured one below is the only registration.
456
476
  StarterKit.configure({ link: false }),
457
- Image,
477
+ EditorImage,
458
478
  Link.configure({
459
479
  openOnClick: false,
460
480
  autolink: false,
@@ -467,7 +487,7 @@ export default function ContentEditor({
467
487
  placeholder: ({ node }) => (node.type.name === "paragraph" ? "Type / for commands…" : ""),
468
488
  }),
469
489
  BlockNode.configure({ types, linkOptions, fieldName: name }),
470
- SlashCommand.configure({ types, sharedSections }),
490
+ SlashCommand.configure({ types, sharedSections, onInsertImage: () => setImageBrowseOpen(true) }),
471
491
  ],
472
492
  content: contentToTiptap(parsedInitial),
473
493
  onUpdate: ({ editor }) => {
@@ -595,7 +615,7 @@ export default function ContentEditor({
595
615
  : "border-input hover:border-foreground/20 bg-field relative overflow-hidden rounded-lg border transition-colors",
596
616
  )}
597
617
  >
598
- <input ref={hiddenRef} type="hidden" name={name} value={cmsJson} />
618
+ <input ref={hiddenRef} type="hidden" name={name} value={formValue} />
599
619
 
600
620
  {/* Fullscreen header — keeps the field title and an exit affordance in view */}
601
621
  {isFullscreen && (
@@ -639,13 +659,14 @@ export default function ContentEditor({
639
659
  {/* Selection toolbar — appears when text is highlighted */}
640
660
  <BubbleMenu
641
661
  editor={editor}
642
- options={{ placement: "top" }}
643
- shouldShow={({ editor: ed, from, to }) => from !== to && !ed.isActive(BLOCK_NODE_NAME)}
662
+ options={BUBBLE_MENU_OPTIONS}
663
+ shouldShow={shouldShowBubbleMenu}
644
664
  className="bg-popover flex items-center gap-0.5 rounded-md border p-1 shadow-md"
645
665
  >
646
666
  <ToolbarButton
647
667
  onClick={() => editor.chain().focus().toggleBold().run()}
648
668
  active={editor.isActive("bold")}
669
+ disabled={editor.isActive("heading")}
649
670
  title="Bold"
650
671
  >
651
672
  <Bold className="size-4" />
@@ -659,14 +680,14 @@ export default function ContentEditor({
659
680
  </ToolbarButton>
660
681
  <div className="bg-border mx-0.5 h-5 w-px" />
661
682
  <ToolbarButton
662
- onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
683
+ onClick={() => editor && toggleHeading(editor, 2)}
663
684
  active={editor.isActive("heading", { level: 2 })}
664
685
  title="Heading 2"
665
686
  >
666
687
  <Heading2 className="size-4" />
667
688
  </ToolbarButton>
668
689
  <ToolbarButton
669
- onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}
690
+ onClick={() => editor && toggleHeading(editor, 3)}
670
691
  active={editor.isActive("heading", { level: 3 })}
671
692
  title="Heading 3"
672
693
  >
@@ -684,6 +705,14 @@ export default function ContentEditor({
684
705
  <div className="prose prose-sm max-w-none" style={{ minHeight, padding: "0.625rem 0.75rem" }} />
685
706
  )}
686
707
 
708
+ <ImageBrowseDialog
709
+ open={imageBrowseOpen}
710
+ onOpenChange={setImageBrowseOpen}
711
+ onSelect={(asset) => {
712
+ editor?.chain().focus().setImage({ src: asset.url, alt: asset.filename }).run();
713
+ }}
714
+ />
715
+
687
716
  <LinkDialog
688
717
  open={linkDialogOpen}
689
718
  onOpenChange={setLinkDialogOpen}
@@ -15,9 +15,13 @@ import { MIN_QUERY_LENGTH, fetchDocuments, useDocumentSearch, type DocumentHit }
15
15
  * blocks, internal-link pickers) renders this and differs only in how it
16
16
  * stores the pick.
17
17
  */
18
+ /** A selected document known only by id + label (see `useRelationLabels`). */
19
+ export type PinnedDoc = { docId: string; title: string; status?: string | null };
20
+
18
21
  export default function DocumentCombobox({
19
22
  collections,
20
23
  groups,
24
+ pinned = [],
21
25
  placeholder,
22
26
  display,
23
27
  isSelected,
@@ -33,6 +37,11 @@ export default function DocumentCombobox({
33
37
  collections: string[];
34
38
  /** When set, results render grouped by collection under these labels. */
35
39
  groups?: Array<{ collection: string; label: string }>;
40
+ /**
41
+ * Current selection, shown first while the query is empty so it is always
42
+ * visible (and deselectable) even when it falls outside the recent `limit`.
43
+ */
44
+ pinned?: PinnedDoc[];
36
45
  placeholder: string;
37
46
  /** Trigger text; empty renders the placeholder muted. */
38
47
  display: string;
@@ -48,7 +57,7 @@ export default function DocumentCombobox({
48
57
  triggerClassName?: string;
49
58
  }) {
50
59
  const [open, setOpen] = React.useState(false);
51
- const { query, setQuery, results, loading, tooShort, reset } = useDocumentSearch({
60
+ const { query, setQuery, results, hasMore, loading, tooShort, reset } = useDocumentSearch({
52
61
  collections,
53
62
  limit,
54
63
  recentWhenEmpty: true,
@@ -65,6 +74,24 @@ export default function DocumentCombobox({
65
74
  if (closeOnPick) handleOpenChange(false);
66
75
  };
67
76
 
77
+ // Empty query: selection first, then recent documents minus the selection.
78
+ const showPinned = !groups && query.trim().length === 0 && pinned.length > 0;
79
+ const pinnedHits: DocumentHit[] = showPinned
80
+ ? pinned.map((doc) => ({
81
+ collection: collections[0],
82
+ collectionLabel: "",
83
+ docId: doc.docId,
84
+ title: doc.title,
85
+ editUrl: "",
86
+ href: null,
87
+ status: doc.status ?? null,
88
+ }))
89
+ : [];
90
+ const rows = showPinned
91
+ ? [...pinnedHits, ...results.filter((hit) => !pinned.some((doc) => doc.docId === hit.docId))]
92
+ : results;
93
+ const recentCount = rows.length - pinnedHits.length;
94
+
68
95
  const grouped = React.useMemo(() => {
69
96
  if (!groups) return null;
70
97
  const byCollection = new Map<string, DocumentHit[]>();
@@ -79,7 +106,7 @@ export default function DocumentCombobox({
79
106
  key={hit.docId}
80
107
  value={`${hit.collection}:${hit.docId}`}
81
108
  onSelect={() => pick(hit)}
82
- className={cn(dimUnselected && !isSelected(hit) && "opacity-40")}
109
+ className={cn("px-1", dimUnselected && !isSelected(hit) && "opacity-40")}
83
110
  >
84
111
  <Check className={cn("size-4", isSelected(hit) ? "opacity-100" : "opacity-0")} />
85
112
  <span className="flex-1 truncate">{hit.title}</span>
@@ -115,17 +142,24 @@ export default function DocumentCombobox({
115
142
  Type at least {MIN_QUERY_LENGTH} characters to search.
116
143
  </div>
117
144
  )}
118
- {loading && results.length === 0 && (
145
+ {loading && rows.length === 0 && (
119
146
  <div className="text-muted-foreground py-6 text-center text-sm">Searching…</div>
120
147
  )}
121
- {!loading && !tooShort && results.length === 0 && <CommandEmpty>No documents found.</CommandEmpty>}
148
+ {!loading && !tooShort && rows.length === 0 && <CommandEmpty>No documents found.</CommandEmpty>}
122
149
  {grouped
123
150
  ? grouped.map((group) => (
124
151
  <CommandGroup key={group.collection} heading={group.label}>
125
152
  {group.items.map(renderHit)}
126
153
  </CommandGroup>
127
154
  ))
128
- : results.map(renderHit)}
155
+ : rows.map(renderHit)}
156
+ {hasMore && recentCount > 0 && (
157
+ <div className="text-muted-foreground bg-popover sticky bottom-0 border-t px-3 py-1.5 text-xs">
158
+ {query.trim()
159
+ ? `Showing the first ${recentCount} matches. Refine your search to see others.`
160
+ : `Showing the ${recentCount} most recent. Type to search all.`}
161
+ </div>
162
+ )}
129
163
  </CommandList>
130
164
  </Command>
131
165
  </PopoverContent>
@@ -144,13 +178,16 @@ export function useRelationLabels(
144
178
  initialSelected: string[],
145
179
  seed: Array<{ value: string; label: string }> = [],
146
180
  ) {
147
- const [labels, setLabels] = React.useState<Record<string, string>>(() =>
148
- Object.fromEntries(seed.map((option) => [option.value, option.label])),
181
+ const [labels, setLabels] = React.useState<Record<string, PinnedDoc>>(() =>
182
+ Object.fromEntries(seed.map((option) => [option.value, { docId: option.value, title: option.label }])),
149
183
  );
150
184
 
151
- const remember = React.useCallback((hits: Array<{ docId: string; title: string }>) => {
185
+ const remember = React.useCallback((hits: PinnedDoc[]) => {
152
186
  if (hits.length === 0) return;
153
- setLabels((prev) => ({ ...prev, ...Object.fromEntries(hits.map((hit) => [hit.docId, hit.title])) }));
187
+ setLabels((prev) => ({
188
+ ...prev,
189
+ ...Object.fromEntries(hits.map((hit) => [hit.docId, { docId: hit.docId, title: hit.title, status: hit.status }])),
190
+ }));
154
191
  }, []);
155
192
 
156
193
  // Only the initial selection needs resolving; later picks arrive with their label.
@@ -165,7 +202,12 @@ export function useRelationLabels(
165
202
  // eslint-disable-next-line react-hooks/exhaustive-deps
166
203
  }, []);
167
204
 
168
- const getLabel = React.useCallback((id: string): string | undefined => labels[id], [labels]);
205
+ const getLabel = React.useCallback((id: string): string | undefined => labels[id]?.title, [labels]);
206
+ /** Pinned-row shape for ids in the selection; unresolved ids render as "…" until the lookup lands. */
207
+ const getPinned = React.useCallback(
208
+ (ids: string[]): PinnedDoc[] => ids.map((id) => labels[id] ?? { docId: id, title: "…" }),
209
+ [labels],
210
+ );
169
211
 
170
- return { getLabel, remember };
212
+ return { getLabel, getPinned, remember };
171
213
  }
@@ -244,12 +244,11 @@ export default function DocumentsDataTable({
244
244
  id: String(entry._id),
245
245
  editHref: `/admin/${collectionSlug}/${entry._id}`,
246
246
  status: getVisualStatus(entry),
247
- locales: [
248
- ...(defaultLocale ? [defaultLocale] : []),
249
- ...(Array.isArray(entry._availableLocales)
250
- ? (entry._availableLocales as string[]).filter((l) => l !== defaultLocale)
251
- : []),
252
- ],
247
+ locales: Array.isArray(entry._availableLocales)
248
+ ? (entry._availableLocales as string[])
249
+ : defaultLocale
250
+ ? [defaultLocale]
251
+ : [],
253
252
  searchText: String(entry[labelField] ?? entry.slug ?? entry._id ?? ""),
254
253
  pageHref: entry._pageHref as string | undefined,
255
254
  values: Object.fromEntries(columns.map((column) => [column.key, formatRowValue(column.key, entry)])),
@@ -0,0 +1,134 @@
1
+ "use client";
2
+
3
+ import { useEffect, useRef, useState } from "react";
4
+ import type { Editor } from "@tiptap/core";
5
+ import Image from "@tiptap/extension-image";
6
+ import { NodeViewWrapper, ReactNodeViewRenderer, type NodeViewProps } from "@tiptap/react";
7
+ import { ImageIcon, Trash2 } from "lucide-react";
8
+ import { Button } from "./ui/button";
9
+ import { Input } from "./ui/input";
10
+ import ImageBrowseDialog from "./ImageBrowseDialog";
11
+ import { cn, thumbnail } from "../lib/utils";
12
+
13
+ /** Node views only re-render on node/selection changes, so track editor focus ourselves. */
14
+ function useEditorFocus(editor: Editor) {
15
+ const [focused, setFocused] = useState(editor.isFocused);
16
+ useEffect(() => {
17
+ const on = () => setFocused(true);
18
+ const off = () => setFocused(false);
19
+ editor.on("focus", on);
20
+ editor.on("blur", off);
21
+ return () => {
22
+ editor.off("focus", on);
23
+ editor.off("blur", off);
24
+ };
25
+ }, [editor]);
26
+ return focused;
27
+ }
28
+
29
+ /**
30
+ * Inline image in rich text / content fields. Selecting it reveals alt text,
31
+ * replace (asset browser) and remove, so an image is editable rather than a
32
+ * fixed blob that can only be deleted.
33
+ */
34
+ function ImageNodeView({ node, selected, editor, getPos, updateAttributes, deleteNode }: NodeViewProps) {
35
+ const [browseOpen, setBrowseOpen] = useState(false);
36
+ const [focusWithin, setFocusWithin] = useState(false);
37
+ const focused = useEditorFocus(editor);
38
+ const src = String(node.attrs.src ?? "");
39
+ const alt = String(node.attrs.alt ?? "");
40
+
41
+ // On load the initial selection sits on the first block, so `selected` alone
42
+ // would show the controls before anyone clicked — require editor focus too.
43
+ const active = editor.isEditable && ((selected && focused) || focusWithin);
44
+
45
+ // A click on a non-editable node view doesn't focus the editor by itself.
46
+ // Focus synchronously: the async `focus()` command re-syncs the selection
47
+ // from the DOM afterwards and would undo the node selection.
48
+ const select = () => {
49
+ const pos = getPos();
50
+ if (typeof pos !== "number") return;
51
+ editor.view.focus();
52
+ editor.commands.setNodeSelection(pos);
53
+ };
54
+
55
+ // Dragging a full-size image hides the drop target under the ghost. Chrome
56
+ // draws a bare <img> at natural size, so the ghost is a sized div. A real drag
57
+ // starts on Tiptap's outer node element (the wrapper's parent), and Tiptap
58
+ // sets its own ghost from React's root listener — override from the document.
59
+ const wrapperRef = useRef<HTMLDivElement>(null);
60
+ const ghostRef = useRef<HTMLDivElement>(null);
61
+ useEffect(() => {
62
+ const onDragStart = (e: DragEvent) => {
63
+ const ghost = ghostRef.current;
64
+ const wrapper = wrapperRef.current;
65
+ const target = e.target as Node | null;
66
+ if (!ghost || !wrapper || !target || !e.dataTransfer) return;
67
+ if (!wrapper.contains(target) && !target.contains(wrapper)) return;
68
+ e.dataTransfer.setDragImage(ghost, ghost.offsetWidth / 2, ghost.offsetHeight / 2);
69
+ };
70
+ document.addEventListener("dragstart", onDragStart);
71
+ return () => document.removeEventListener("dragstart", onDragStart);
72
+ }, []);
73
+
74
+ return (
75
+ <NodeViewWrapper
76
+ ref={wrapperRef}
77
+ className="relative isolate my-3"
78
+ data-drag-handle
79
+ onFocusCapture={() => setFocusWithin(true)}
80
+ onBlurCapture={(e: React.FocusEvent<HTMLDivElement>) => {
81
+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocusWithin(false);
82
+ }}
83
+ >
84
+ <img
85
+ src={src}
86
+ alt={alt}
87
+ draggable={false}
88
+ onClick={select}
89
+ className={cn("relative z-10 max-w-full rounded-md", active && "ring-ring/50 ring-2 ring-offset-2")}
90
+ />
91
+ <div
92
+ ref={ghostRef}
93
+ aria-hidden
94
+ className="pointer-events-none absolute top-0 left-0 z-0 w-40 max-w-full overflow-hidden rounded-md"
95
+ >
96
+ <img src={thumbnail(src, 320)} alt="" className="block w-full" />
97
+ </div>
98
+ {active && (
99
+ <div
100
+ contentEditable={false}
101
+ className="bg-popover mt-2 flex flex-wrap items-center gap-2 rounded-md border p-1.5 shadow-xs"
102
+ >
103
+ <Input
104
+ value={alt}
105
+ onChange={(e) => updateAttributes({ alt: e.target.value })}
106
+ placeholder="Alt text"
107
+ aria-label="Alt text"
108
+ className="h-8 min-w-40 flex-1"
109
+ />
110
+ <Button type="button" variant="outline" size="sm" onClick={() => setBrowseOpen(true)}>
111
+ <ImageIcon className="size-3.5" />
112
+ Replace
113
+ </Button>
114
+ <Button type="button" variant="outline" size="sm" onClick={deleteNode}>
115
+ <Trash2 className="size-3.5" />
116
+ Remove
117
+ </Button>
118
+ </div>
119
+ )}
120
+ <ImageBrowseDialog
121
+ open={browseOpen}
122
+ onOpenChange={setBrowseOpen}
123
+ onSelect={(asset) => updateAttributes({ src: asset.url, alt: alt || asset.filename })}
124
+ />
125
+ </NodeViewWrapper>
126
+ );
127
+ }
128
+
129
+ /** `@tiptap/extension-image` with the editable node view attached. */
130
+ export const EditorImage = Image.extend({
131
+ addNodeView() {
132
+ return ReactNodeViewRenderer(ImageNodeView);
133
+ },
134
+ });
@@ -109,7 +109,7 @@ export default function RelationField({
109
109
  }
110
110
  return initialValue ? [initialValue] : [];
111
111
  });
112
- const { getLabel: findLabel, remember } = useRelationLabels(collectionSlug, selected, initialOptions);
112
+ const { getLabel: findLabel, getPinned, remember } = useRelationLabels(collectionSlug, selected, initialOptions);
113
113
  const [sheetOpen, setSheetOpen] = useState(false);
114
114
 
115
115
  const hiddenRef = useRef<HTMLInputElement>(null);
@@ -207,6 +207,7 @@ export default function RelationField({
207
207
 
208
208
  <DocumentCombobox
209
209
  collections={[collectionSlug]}
210
+ pinned={getPinned(selected)}
210
211
  placeholder={`Search ${collectionLabel.toLowerCase()}...`}
211
212
  display={displayLabel}
212
213
  isSelected={(hit) => selected.includes(hit.docId)}
@@ -1,6 +1,6 @@
1
1
  import { useEditor, EditorContent } from "@tiptap/react";
2
2
  import StarterKit from "@tiptap/starter-kit";
3
- import Image from "@tiptap/extension-image";
3
+ import { EditorImage } from "./EditorImage";
4
4
  import Link from "@tiptap/extension-link";
5
5
  import { Markdown } from "@tiptap/markdown";
6
6
  import { useCallback, useEffect, useRef, useState } from "react";
@@ -26,6 +26,7 @@ import { Input } from "./ui/input";
26
26
  import { Label } from "./ui/label";
27
27
  import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
28
28
  import { cn } from "../lib/utils";
29
+ import { toggleHeading } from "../lib/editor-commands";
29
30
  import ImageBrowseDialog from "./ImageBrowseDialog";
30
31
 
31
32
  // -----------------------------------------------
@@ -182,9 +183,7 @@ const ToolbarButton = ({
182
183
  title={title}
183
184
  className={cn(
184
185
  "disabled:hover:text-muted-foreground inline-flex size-8 items-center justify-center rounded-md transition-colors outline-none disabled:opacity-50 disabled:hover:bg-transparent",
185
- active
186
- ? "bg-foreground/10 text-foreground"
187
- : "text-muted-foreground hover:bg-muted-strong hover:text-foreground",
186
+ active ? "bg-foreground/10 text-foreground" : "text-muted-foreground hover:bg-muted-strong hover:text-foreground",
188
187
  )}
189
188
  >
190
189
  {children}
@@ -423,14 +422,22 @@ export default function RichTextEditor({ name, initialValue, rows = 10, onChange
423
422
  }
424
423
  })();
425
424
 
425
+ // The form value only moves when the content really differs from the editor's
426
+ // own serialisation of the initial document. A no-op transaction (a click,
427
+ // TrailingNode appending its paragraph) re-serialises with normalised keys,
428
+ // which would otherwise read as an unsaved change.
429
+ const [initialJson] = useState(cmsJson);
430
+ const [baseline, setBaseline] = useState<string | null>(null);
431
+ const formValue = cmsJson === baseline ? initialJson : cmsJson;
432
+
426
433
  // Notify the form of value changes so UnsavedGuard detects them
427
- const prevCmsJsonRef = useRef(cmsJson);
434
+ const prevFormValueRef = useRef(formValue);
428
435
  useEffect(() => {
429
- if (prevCmsJsonRef.current !== cmsJson) {
430
- prevCmsJsonRef.current = cmsJson;
436
+ if (prevFormValueRef.current !== formValue) {
437
+ prevFormValueRef.current = formValue;
431
438
  hiddenRef.current?.dispatchEvent(new Event("change", { bubbles: true }));
432
439
  }
433
- }, [cmsJson]);
440
+ }, [formValue]);
434
441
 
435
442
  // Replay the current value when a preview tab opened after edits announces itself
436
443
  useEffect(() => {
@@ -445,10 +452,13 @@ export default function RichTextEditor({ name, initialValue, rows = 10, onChange
445
452
 
446
453
  const editor = useEditor({
447
454
  immediatelyRender: false,
455
+ onCreate: ({ editor }) => {
456
+ setBaseline(JSON.stringify(tiptapToCms(editor.getJSON())));
457
+ },
448
458
  extensions: [
449
459
  // StarterKit bundles its own Link; disabled so the configured one below is the only registration.
450
460
  StarterKit.configure({ link: false }),
451
- Image,
461
+ EditorImage,
452
462
  Markdown,
453
463
  Link.configure({
454
464
  openOnClick: false,
@@ -522,14 +532,14 @@ export default function RichTextEditor({ name, initialValue, rows = 10, onChange
522
532
  data-slot="editor"
523
533
  className="border-input hover:border-foreground/20 overflow-hidden rounded-lg border transition-colors"
524
534
  >
525
- <input ref={hiddenRef} type="hidden" name={name} value={cmsJson} />
535
+ <input ref={hiddenRef} type="hidden" name={name} value={formValue} />
526
536
 
527
537
  {/* Toolbar */}
528
538
  <div className="bg-field flex flex-wrap items-center gap-0.5 border-b px-2 py-1.5">
529
539
  <ToolbarButton
530
540
  onClick={() => editor?.chain().focus().toggleBold().run()}
531
541
  active={editor?.isActive("bold")}
532
- disabled={!editor || markdownMode}
542
+ disabled={!editor || markdownMode || editor.isActive("heading")}
533
543
  title="Bold"
534
544
  >
535
545
  <Bold className="size-4" />
@@ -546,7 +556,7 @@ export default function RichTextEditor({ name, initialValue, rows = 10, onChange
546
556
  <div className="bg-border mx-1 h-5 w-px" />
547
557
 
548
558
  <ToolbarButton
549
- onClick={() => editor?.chain().focus().toggleHeading({ level: 2 }).run()}
559
+ onClick={() => editor && toggleHeading(editor, 2)}
550
560
  active={editor?.isActive("heading", { level: 2 })}
551
561
  disabled={!editor || markdownMode}
552
562
  title="Heading 2"
@@ -554,7 +564,7 @@ export default function RichTextEditor({ name, initialValue, rows = 10, onChange
554
564
  <Heading2 className="size-4" />
555
565
  </ToolbarButton>
556
566
  <ToolbarButton
557
- onClick={() => editor?.chain().focus().toggleHeading({ level: 3 }).run()}
567
+ onClick={() => editor && toggleHeading(editor, 3)}
558
568
  active={editor?.isActive("heading", { level: 3 })}
559
569
  disabled={!editor || markdownMode}
560
570
  title="Heading 3"
@@ -194,7 +194,7 @@ function RelationControl({
194
194
  }) {
195
195
  const selected = parseSelected(meta, value);
196
196
  const collectionSlug = meta.collection ?? "";
197
- const { getLabel, remember } = useRelationLabels(collectionSlug, selected);
197
+ const { getLabel, getPinned, remember } = useRelationLabels(collectionSlug, selected);
198
198
  const toggle = (id: string) => {
199
199
  if (meta.hasMany) {
200
200
  const next = selected.includes(id) ? selected.filter((v) => v !== id) : [...selected, id];
@@ -226,6 +226,7 @@ function RelationControl({
226
226
  )}
227
227
  <DocumentCombobox
228
228
  collections={[collectionSlug]}
229
+ pinned={getPinned(selected)}
229
230
  placeholder={`Search ${meta.label?.toLowerCase() ?? "documents"}...`}
230
231
  display={meta.hasMany ? "" : selected[0] ? (getLabel(selected[0]) ?? "…") : ""}
231
232
  isSelected={(hit) => selected.includes(hit.docId)}
@@ -2,7 +2,7 @@ import { Extension, type Editor, type Range } from "@tiptap/core";
2
2
  import Suggestion, { type SuggestionOptions } from "@tiptap/suggestion";
3
3
  import { ReactRenderer } from "@tiptap/react";
4
4
  import { forwardRef, useEffect, useImperativeHandle, useRef, useState, type ComponentType } from "react";
5
- import { Heading2, Heading3, List, ListOrdered, Quote, Blocks, Link2, type LucideProps } from "lucide-react";
5
+ import { Heading2, Heading3, List, ListOrdered, Quote, Blocks, Link2, ImageIcon, type LucideProps } from "lucide-react";
6
6
  import { cn } from "../lib/utils";
7
7
  import { insertBlockNode, SHARED_BLOCK_TYPE } from "./content-block-spec";
8
8
  import { blankBlockFields, humanize, type BlockTypesMeta } from "./block-fields";
@@ -21,7 +21,12 @@ type SlashItem = {
21
21
  run: (editor: Editor, range: Range) => void;
22
22
  };
23
23
 
24
- const buildItems = (types: BlockTypesMeta, sharedSections: SharedSectionOption[], query: string): SlashItem[] => {
24
+ const buildItems = (
25
+ types: BlockTypesMeta,
26
+ sharedSections: SharedSectionOption[],
27
+ onInsertImage: (() => void) | undefined,
28
+ query: string,
29
+ ): SlashItem[] => {
25
30
  const formatting: SlashItem[] = [
26
31
  {
27
32
  title: "Heading 2",
@@ -53,6 +58,19 @@ const buildItems = (types: BlockTypesMeta, sharedSections: SharedSectionOption[]
53
58
  icon: Quote,
54
59
  run: (e, r) => e.chain().focus().deleteRange(r).toggleBlockquote().run(),
55
60
  },
61
+ ...(onInsertImage
62
+ ? [
63
+ {
64
+ title: "Image",
65
+ subtitle: "From the asset library",
66
+ icon: ImageIcon,
67
+ run: (e: Editor, r: Range) => {
68
+ e.chain().focus().deleteRange(r).run();
69
+ onInsertImage();
70
+ },
71
+ },
72
+ ]
73
+ : []),
56
74
  ];
57
75
 
58
76
  const blocks: SlashItem[] = Object.keys(types).map((typeName) => ({
@@ -155,13 +173,18 @@ SlashMenu.displayName = "SlashMenu";
155
173
  // Extension
156
174
  // -----------------------------------------------
157
175
 
158
- type SlashCommandOptions = { types: BlockTypesMeta; sharedSections: SharedSectionOption[] };
176
+ type SlashCommandOptions = {
177
+ types: BlockTypesMeta;
178
+ sharedSections: SharedSectionOption[];
179
+ /** Opens the host's asset browser; the "Image" item is listed only when provided. */
180
+ onInsertImage?: () => void;
181
+ };
159
182
 
160
183
  export const SlashCommand = Extension.create<SlashCommandOptions>({
161
184
  name: "slashCommand",
162
185
 
163
186
  addOptions() {
164
- return { types: {}, sharedSections: [] };
187
+ return { types: {}, sharedSections: [], onInsertImage: undefined };
165
188
  },
166
189
 
167
190
  addProseMirrorPlugins() {
@@ -170,7 +193,8 @@ export const SlashCommand = Extension.create<SlashCommandOptions>({
170
193
  startOfLine: false,
171
194
  allowSpaces: false,
172
195
  command: ({ editor, range, props }) => props.run(editor, range),
173
- items: ({ query }) => buildItems(this.options.types, this.options.sharedSections, query),
196
+ items: ({ query }) =>
197
+ buildItems(this.options.types, this.options.sharedSections, this.options.onInsertImage, query),
174
198
  render: () => {
175
199
  let component: ReactRenderer<SlashMenuRef, SlashMenuProps> | null = null;
176
200