feat(editor): page templates - live whole-page embed (MVP)

Embed another page's LIVE content into a host page (it updates when the source
changes, not a static copy). A page can be flagged a template for discovery in
the picker; any accessible page can be embedded.

Server:
- migrations: pages.is_template (+ partial index) and page_template_references
  (whole-page back-refs); db.d.ts/entity types hand-merged (db.d.ts is curated).
- POST /pages/toggle-template (CASL Edit) flips is_template; is_template is
  returned by findById + the sidebar tree select so the tree menu label
  reflects state. Search suggestions gain an onlyTemplates filter for the picker.
- POST /pages/template/lookup ({sourcePageIds[]}, <=50): returns each accessible
  source's {title, icon, slugId, content, sourceUpdatedAt} with comment marks
  stripped (same access path as transclusion: filterViewerAccessiblePageIds;
  inaccessible -> no_access, missing -> not_found; error path -> not_found, never
  raw content).
- reference sync (collectPageEmbedsFromPmJson + syncPageTemplateReferences) on
  the Yjs save hook; duplicatePage remaps pageEmbed.sourcePageId + inserts refs.
  Known MVP gap: REST content updates don't resync refs (lookup uses in-doc ids).

Client:
- pageEmbed node (editor-ext, registered in BOTH client + server schemas);
  read-only NodeView with a batching lookup; '/Embed page' slash + template
  picker (self-embed prevented); 'Make/Unset template' in the tree node menu.
- Cycle guard: an ancestry-chain context + depth cap (5) render a 'circular
  embed' placeholder instead of recursing.
- Public shares show a placeholder (no public lookup in MVP).

MVP excludes (follow-ups): public-share lookup, unsync->static copy, server-side
expansion for export/RAG, MCP schema mirror, point-in-time snapshots.

Implements docs/page-templates-plan.md (MVP, variant A).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
claude code agent 227
2026-06-20 10:05:00 +03:00
parent c8af637654
commit 39ae89264d
41 changed files with 1587 additions and 6 deletions

View File

@@ -0,0 +1,53 @@
import React, { createContext, useContext, useMemo } from "react";
/** Hard cap on nesting depth for whole-page embeds (cycle/runaway guard). */
export const PAGE_EMBED_MAX_DEPTH = 5;
type AncestryValue = {
/** sourcePageIds of every ancestor pageEmbed up the render tree. */
chain: string[];
/** Includes the host page id so a top-level self-embed is also caught. */
hostPageId: string | null;
};
const PageEmbedAncestryContext = createContext<AncestryValue>({
chain: [],
hostPageId: null,
});
/**
* Carries the ancestor `sourcePageId` chain down the nested read-only editors.
* The node view reads it to detect cycles (current id already in the chain) and
* to enforce a hard depth limit before mounting a deeper nested editor.
*/
export function PageEmbedAncestryProvider({
sourcePageId,
hostPageId,
children,
}: {
sourcePageId?: string | null;
hostPageId?: string | null;
children: React.ReactNode;
}) {
const parent = useContext(PageEmbedAncestryContext);
const value = useMemo<AncestryValue>(() => {
const nextHost = parent.hostPageId ?? hostPageId ?? null;
if (!sourcePageId) {
return { chain: parent.chain, hostPageId: nextHost };
}
return {
chain: [...parent.chain, sourcePageId],
hostPageId: nextHost,
};
}, [parent, sourcePageId, hostPageId]);
return (
<PageEmbedAncestryContext.Provider value={value}>
{children}
</PageEmbedAncestryContext.Provider>
);
}
export function usePageEmbedAncestry() {
return useContext(PageEmbedAncestryContext);
}

View File

@@ -0,0 +1,49 @@
import { EditorProvider } from "@tiptap/react";
import { useMemo } from "react";
import { mainExtensions } from "@/features/editor/extensions/extensions";
import { UniqueID } from "@docmost/editor-ext";
type Props = {
content: unknown;
};
/**
* Read-only nested renderer for embedded whole-page content. Same pattern as
* the transclusion read-only renderer: drop uniqueID/globalDragHandle, never
* write back, and isolate pointer/drag events from the host editor. Nested
* `pageEmbed`/`transclusionReference` nodes inside the content render with
* their own views (the cycle/depth guard lives in the node view itself).
*/
export default function PageEmbedContent({ content }: Props) {
const extensions = useMemo(() => {
const filtered = mainExtensions.filter(
(e: any) => e.name !== "uniqueID" && e.name !== "globalDragHandle",
);
return [
...filtered,
UniqueID.configure({
types: ["heading", "paragraph", "transclusionSource"],
updateDocument: false,
}),
];
}, []);
const stop = (e: React.SyntheticEvent) => e.stopPropagation();
return (
<div
onMouseDown={stop}
onClick={stop}
onDragStart={stop}
onDragOver={stop}
onDrop={stop}
>
<EditorProvider
editable={false}
immediatelyRender={true}
extensions={extensions}
content={content as any}
/>
</div>
);
}

View File

@@ -0,0 +1,162 @@
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { lookupTemplate } from "@/features/page-embed/services/page-embed-api";
import type { PageTemplateLookup } from "@/features/page-embed/types/page-embed.types";
type ContextValue = {
subscribe: (s: {
sourcePageId: string;
setResult: (r: PageTemplateLookup) => void;
}) => () => void;
refresh: (sourcePageId: string) => Promise<void>;
};
const PageEmbedLookupContext = createContext<ContextValue | null>(null);
/**
* Batching/de-dup lookup context for whole-page embeds (pageEmbed). Mirrors the
* transclusion lookup context but keys purely on `sourcePageId`. On public
* shares there is no lookup in MVP, so the context simply isn't mounted (the
* node view renders a placeholder when the context is absent).
*/
export function PageEmbedLookupProvider({
children,
}: {
children: React.ReactNode;
}) {
const subscribersRef = useRef(new Map<string, Array<(r: PageTemplateLookup) => void>>());
const queueRef = useRef(new Set<string>());
const tickRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const resultCacheRef = useRef(new Map<string, PageTemplateLookup>());
const inFlightRef = useRef(new Set<string>());
const pendingRef = useRef(new Map<string, Array<() => void>>());
const flush = useCallback(async () => {
tickRef.current = null;
const ids = Array.from(queueRef.current);
queueRef.current.clear();
if (ids.length === 0) return;
for (const id of ids) inFlightRef.current.add(id);
const resolveWaiters = (id: string) => {
const waiters = pendingRef.current.get(id);
if (!waiters) return;
pendingRef.current.delete(id);
for (const w of waiters) w();
};
try {
const { items } = await lookupTemplate({ sourcePageIds: ids });
for (const r of items) {
resultCacheRef.current.set(r.sourcePageId, r);
inFlightRef.current.delete(r.sourcePageId);
const subs = subscribersRef.current.get(r.sourcePageId);
if (subs) {
for (const set of subs) set(r);
}
resolveWaiters(r.sourcePageId);
}
} catch (err) {
// Surface the failure: errors must never be swallowed silently.
console.error("[pageEmbed] template lookup failed", err);
for (const id of ids) {
inFlightRef.current.delete(id);
resolveWaiters(id);
}
}
}, []);
const enqueue = useCallback(
(id: string) => {
queueRef.current.add(id);
if (tickRef.current === null) {
tickRef.current = setTimeout(flush, 10);
}
},
[flush],
);
const subscribe = useCallback<ContextValue["subscribe"]>(
({ sourcePageId, setResult }) => {
const list = subscribersRef.current.get(sourcePageId) ?? [];
list.push(setResult);
subscribersRef.current.set(sourcePageId, list);
const cached = resultCacheRef.current.get(sourcePageId);
if (cached) {
setResult(cached);
} else if (!inFlightRef.current.has(sourcePageId)) {
enqueue(sourcePageId);
}
return () => {
const cur = subscribersRef.current.get(sourcePageId) ?? [];
const next = cur.filter((x) => x !== setResult);
if (next.length === 0) subscribersRef.current.delete(sourcePageId);
else subscribersRef.current.set(sourcePageId, next);
};
},
[enqueue],
);
const refresh = useCallback<ContextValue["refresh"]>(
(sourcePageId) =>
new Promise<void>((resolve) => {
resultCacheRef.current.delete(sourcePageId);
inFlightRef.current.delete(sourcePageId);
const waiters = pendingRef.current.get(sourcePageId) ?? [];
waiters.push(resolve);
pendingRef.current.set(sourcePageId, waiters);
enqueue(sourcePageId);
}),
[enqueue],
);
useEffect(
() => () => {
if (tickRef.current) clearTimeout(tickRef.current);
},
[],
);
const value = useMemo<ContextValue>(
() => ({ subscribe, refresh }),
[subscribe, refresh],
);
return (
<PageEmbedLookupContext.Provider value={value}>
{children}
</PageEmbedLookupContext.Provider>
);
}
export function usePageEmbedLookup(sourcePageId: string | null | undefined): {
result: PageTemplateLookup | null;
refresh: () => Promise<void>;
available: boolean;
} {
const ctx = useContext(PageEmbedLookupContext);
const [result, setResult] = useState<PageTemplateLookup | null>(null);
useEffect(() => {
if (!ctx || !sourcePageId) return;
const unsubscribe = ctx.subscribe({ sourcePageId, setResult });
return unsubscribe;
}, [ctx, sourcePageId]);
const refresh = useCallback(async () => {
if (!ctx || !sourcePageId) return;
await ctx.refresh(sourcePageId);
}, [ctx, sourcePageId]);
return { result, refresh, available: Boolean(ctx) };
}

View File

@@ -0,0 +1,117 @@
import { useEffect, useRef, useState } from "react";
import { Modal, ScrollArea, TextInput, Text, UnstyledButton, Group } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import { IconFileText, IconSearch } from "@tabler/icons-react";
import type { Editor, Range } from "@tiptap/core";
import { searchSuggestions } from "@/features/search/services/search-service";
import type { IPage } from "@/features/page/types/page.types";
export const PAGE_EMBED_PICKER_EVENT = "open-page-embed-picker";
type PickerDetail = {
editor: Editor;
range: Range;
/** Host page id, used to forbid self-embed in the picker. */
hostPageId?: string;
};
/**
* Modal page picker for inserting a `pageEmbed`. Queries search-suggestions
* with `onlyTemplates` so only template-flagged pages are offered. Forbids
* selecting the current (host) page (self-embed guard at insertion time).
* Mounted once per editor; opened via a CustomEvent dispatched by the slash
* command item.
*/
export default function PageEmbedPicker() {
const { t } = useTranslation();
const [opened, setOpened] = useState(false);
const [query, setQuery] = useState("");
const detailRef = useRef<PickerDetail | null>(null);
useEffect(() => {
const handler = (e: Event) => {
const detail = (e as CustomEvent<PickerDetail>).detail;
if (!detail?.editor) return;
detailRef.current = detail;
setQuery("");
setOpened(true);
};
document.addEventListener(PAGE_EMBED_PICKER_EVENT, handler);
return () => document.removeEventListener(PAGE_EMBED_PICKER_EVENT, handler);
}, []);
const { data, isFetching } = useQuery({
queryKey: ["page-embed-template-picker", query],
queryFn: () =>
searchSuggestions({
query,
includePages: true,
onlyTemplates: true,
limit: 20,
}),
enabled: opened,
staleTime: 30 * 1000,
});
const hostPageId = detailRef.current?.hostPageId;
const pages = ((data?.pages ?? []) as IPage[]).filter(
(p) => p && p.id !== hostPageId,
);
const handleSelect = (page: IPage) => {
const detail = detailRef.current;
if (!detail) return;
const { editor, range } = detail;
editor
.chain()
.focus()
.deleteRange(range)
.insertPageEmbed({ sourcePageId: page.id })
.run();
setOpened(false);
};
return (
<Modal
opened={opened}
onClose={() => setOpened(false)}
title={t("Embed page")}
size="md"
>
<TextInput
placeholder={t("Search templates...")}
leftSection={<IconSearch size={16} />}
value={query}
onChange={(e) => setQuery(e.currentTarget.value)}
autoFocus
mb="sm"
/>
<ScrollArea.Autosize mah={320}>
{pages.length === 0 && !isFetching && (
<Text size="sm" c="dimmed" ta="center" py="md">
{t("No templates found")}
</Text>
)}
{pages.map((page) => (
<UnstyledButton
key={page.id}
onClick={() => handleSelect(page)}
style={{ display: "block", width: "100%", padding: "8px 4px" }}
>
<Group gap="xs" wrap="nowrap">
{page.icon ? (
<span>{page.icon}</span>
) : (
<IconFileText size={16} />
)}
<Text size="sm" truncate>
{page.title || t("Untitled")}
</Text>
</Group>
</UnstyledButton>
))}
</ScrollArea.Autosize>
</Modal>
);
}

View File

@@ -0,0 +1,253 @@
import { NodeViewProps, NodeViewWrapper } from "@tiptap/react";
import { ActionIcon, Menu, Tooltip } from "@mantine/core";
import {
IconAlertTriangle,
IconArrowsMaximize,
IconDots,
IconExternalLink,
IconEyeOff,
IconInfoCircle,
IconRefresh,
IconRepeat,
IconTrash,
} from "@tabler/icons-react";
import { useState } from "react";
import { Link } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { ErrorBoundary } from "react-error-boundary";
import { buildPageUrl } from "@/features/page/page.utils.ts";
import classes from "../transclusion/transclusion.module.css";
import { usePageEmbedLookup } from "./page-embed-lookup-context";
import {
PageEmbedAncestryProvider,
usePageEmbedAncestry,
PAGE_EMBED_MAX_DEPTH,
} from "./page-embed-ancestry-context";
import PageEmbedContent from "./page-embed-content";
function Placeholder({
icon,
label,
}: {
icon: React.ReactNode;
label: string;
}) {
return (
<div className={classes.placeholder}>
<span className={classes.placeholderIcon}>{icon}</span>
<span>{label}</span>
</div>
);
}
export default function PageEmbedView(props: NodeViewProps) {
const isEditable = props.editor.isEditable;
const sourcePageId: string | null = props.node.attrs.sourcePageId ?? null;
const [openMenus, setOpenMenus] = useState(0);
const trackOpen = (open: boolean) =>
setOpenMenus((n) => Math.max(0, n + (open ? 1 : -1)));
return (
<NodeViewWrapper
className={classes.includeWrap}
data-editable={isEditable ? "true" : "false"}
data-focused={isEditable && props.selected ? "true" : "false"}
data-menu-open={openMenus > 0 ? "true" : "false"}
contentEditable={false}
>
<ErrorBoundary
resetKeys={[sourcePageId]}
onError={(err) =>
// Never swallow: log the full error with the offending source id.
console.error("[pageEmbed] render error", { sourcePageId, err })
}
fallback={
<Placeholder
icon={<IconAlertTriangle size={18} stroke={1.6} />}
label="Failed to load this embedded page"
/>
}
>
<PageEmbedBody {...props} trackOpen={trackOpen} />
</ErrorBoundary>
</NodeViewWrapper>
);
}
function PageEmbedBody({
editor,
node,
deleteNode,
trackOpen,
}: NodeViewProps & { trackOpen: (open: boolean) => void }) {
const { t } = useTranslation();
const sourcePageId: string | null = node.attrs.sourcePageId ?? null;
const isEditable = editor.isEditable;
const ancestry = usePageEmbedAncestry();
// @ts-ignore - editor.storage.pageId is set by the host editor
const hostPageId: string | undefined = editor.storage?.pageId;
const { result, refresh, available } = usePageEmbedLookup(sourcePageId);
const [refreshing, setRefreshing] = useState(false);
const handleRefresh = async () => {
setRefreshing(true);
try {
await refresh();
} finally {
setRefreshing(false);
}
};
// --- Cycle / depth guard (evaluated before any lookup is rendered) ---------
// Self-embed or a source already present in the ancestor chain → cycle.
const isCycle =
!!sourcePageId &&
(ancestry.chain.includes(sourcePageId) ||
ancestry.hostPageId === sourcePageId);
const isTooDeep = ancestry.chain.length >= PAGE_EMBED_MAX_DEPTH;
const sourceTitle =
result && !("status" in result) ? result.title : null;
const sourceIcon = result && !("status" in result) ? result.icon : null;
// The app routes pages by slugId, not the raw UUID. Build the link from the
// resolved slugId (the `/p/:pageSlug` route redirects to the full URL).
const sourceSlugId =
result && !("status" in result) ? result.slugId : null;
const sourceHref = sourceSlugId
? buildPageUrl(undefined, sourceSlugId, sourceTitle ?? undefined)
: null;
const controls = isEditable ? (
<div
className={classes.includeControls}
contentEditable={false}
onMouseDown={(e) => e.preventDefault()}
>
<Tooltip label={t("Refresh")}>
<ActionIcon
variant="subtle"
color="gray"
size="sm"
onClick={handleRefresh}
loading={refreshing}
disabled={!sourcePageId}
>
<IconRefresh size={14} />
</ActionIcon>
</Tooltip>
{sourceHref && (
<Tooltip label={t("Open source page")}>
<ActionIcon
component={Link}
to={sourceHref}
variant="subtle"
color="gray"
size="sm"
style={{ textDecoration: "none", borderBottom: "none" }}
>
<IconExternalLink size={14} />
</ActionIcon>
</Tooltip>
)}
<Menu position="bottom-end" withinPortal onChange={trackOpen}>
<Menu.Target>
<ActionIcon variant="subtle" color="gray" size="sm">
<IconDots size={14} />
</ActionIcon>
</Menu.Target>
<Menu.Dropdown>
<Menu.Item
color="red"
leftSection={<IconTrash size={14} />}
onClick={() => deleteNode()}
>
{t("Remove from page")}
</Menu.Item>
</Menu.Dropdown>
</Menu>
</div>
) : null;
const header =
sourceTitle || sourceIcon ? (
<div className={classes.transclusionBadge}>
{sourceIcon ? `${sourceIcon} ` : <IconArrowsMaximize size={12} />}
{sourceHref ? (
<Link
to={sourceHref}
style={{ borderBottom: "none", textDecoration: "none" }}
>
{sourceTitle || t("Untitled")}
</Link>
) : (
sourceTitle || t("Untitled")
)}
</div>
) : null;
let body: React.ReactNode;
if (!sourcePageId) {
body = (
<Placeholder
icon={<IconInfoCircle size={18} stroke={1.6} />}
label={t("No page selected")}
/>
);
} else if (isCycle) {
body = (
<Placeholder
icon={<IconRepeat size={18} stroke={1.6} />}
label={t("Circular embed: this page is already shown above")}
/>
);
} else if (isTooDeep) {
body = (
<Placeholder
icon={<IconRepeat size={18} stroke={1.6} />}
label={t("Embed nesting limit reached")}
/>
);
} else if (!available) {
// No lookup context (e.g. public share) → placeholder, no fetch in MVP.
body = (
<Placeholder
icon={<IconEyeOff size={18} stroke={1.6} />}
label={t("Embedded page is not available here")}
/>
);
} else if (!result) {
body = <div style={{ minHeight: 24 }} />;
} else if (!("status" in result)) {
body = (
<PageEmbedAncestryProvider
sourcePageId={sourcePageId}
hostPageId={hostPageId}
>
<PageEmbedContent content={result.content} />
</PageEmbedAncestryProvider>
);
} else if (result.status === "no_access") {
body = (
<Placeholder
icon={<IconEyeOff size={18} stroke={1.6} />}
label={t("You don't have access to this page")}
/>
);
} else {
body = (
<Placeholder
icon={<IconInfoCircle size={18} stroke={1.6} />}
label={t("The embedded page no longer exists")}
/>
);
}
return (
<>
{controls}
{header}
{body}
</>
);
}

View File

@@ -28,7 +28,9 @@ import {
IconTag,
IconMoodSmile,
IconRotate2,
IconArrowsMaximize,
} from "@tabler/icons-react";
import { PAGE_EMBED_PICKER_EVENT } from "@/features/editor/components/page-embed/page-embed-picker";
import {
CommandProps,
SlashMenuGroupedItemsType,
@@ -535,6 +537,29 @@ const CommandGroups: SlashMenuGroupedItemsType = {
.run();
},
},
{
title: "Embed page",
description: "Insert a live, read-only copy of another page.",
searchTerms: [
"template",
"embed",
"embed page",
"page",
"live",
"include",
"reuse",
],
icon: IconArrowsMaximize,
command: ({ editor, range }: CommandProps) => {
// @ts-ignore - editor.storage.pageId is set by the host editor
const hostPageId: string | undefined = editor.storage?.pageId;
document.dispatchEvent(
new CustomEvent(PAGE_EMBED_PICKER_EVENT, {
detail: { editor, range, hostPageId },
}),
);
},
},
{
title: "2 Columns",
description: "Split content into two columns.",