Repository Public
1"use client";2/**3 * file: src/components/editor/nodes/RefViews.tsx4 * description: `blockRef` (cross-reference / transclusion: the source block of another page rendered live and read-only, or as a link)5 * and `canvasLink` (card that opens a canvas page). Both only hold ids: the content is always read from the source at display time.6 * author: Simon-Pierre Boucher — contact@spboucher.ai7 */8import * as React from "react";9import Link from "next/link";10import { useQuery } from "@tanstack/react-query";11import { CornerDownRight, ExternalLink, Search, Unlink, Link2, Rows3, Shapes, Plus, Replace } from "lucide-react";12import type { BlockRefAttrs, CanvasLinkAttrs } from "@/lib/editor/next-node-defs";13import { docBlocks, type PMNode } from "@/lib/editor/text";14import { api, ApiError } from "@/lib/client/api";15import { toast } from "@/components/ui/toast";16import { NodeFrame, NodeButton, NodeState, type LeafViewProps } from "./frame";1718// The embed is rendered by the editor itself (read-only), loaded lazily: Editor imports this file, so a static import would be circular.19const EmbeddedEditor = React.lazy(() => import("../Editor").then((m) => ({ default: m.Editor })));20/** Nesting depth of transclusions (a referenced block may itself contain references): past 2 levels only a link is shown. */21const RefDepth = React.createContext(0);22interface PageLite { id: string; title: string; icon: string | null; type?: string; content: PMNode; deletedAt?: string | null }23interface Hit { id: string; title: string; icon: string | null; type?: string }24export function findBlock(doc: PMNode | null | undefined, blockId: string): PMNode | null {25 if (!doc) return null; if (doc.attrs?.id === blockId && doc.type !== "doc") return doc;26 for (const c of doc.content ?? []) { const f = findBlock(c, blockId); if (f) return f; } return null;27}28const usePage = (pageId: string | null) => useQuery({ queryKey: ["page-source", pageId], enabled: Boolean(pageId), staleTime: 15_000, refetchOnWindowFocus: true, retry: false,29 queryFn: async () => { try { return await api<PageLite>(`/api/pages/${pageId}`); } catch (e) { if (e instanceof ApiError && (e.status === 404 || e.status === 400)) return null; throw e; } } });3031function BlockPicker({ onPick, exclude }: { onPick: (pageId: string, blockId: string) => void; exclude?: string | null }) {32 const [q, setQ] = React.useState(""); const [page, setPage] = React.useState<Hit | null>(null);33 const hits = useQuery({ queryKey: ["blockref-search", q], enabled: !page, staleTime: 10_000, queryFn: () => api<Hit[]>(`/api/search?mode=quick&q=${encodeURIComponent(q)}&limit=8`) });34 const src = usePage(page?.id ?? null); const blocks = React.useMemo(() => docBlocks(src.data?.content).filter((b) => b.id), [src.data]);35 if (page) return (36 <div className="ref-picker" data-testid="blockref-blocks">37 <div className="mb-1 flex items-center gap-2 text-ui"><button type="button" className="nb-btn nb-btn-text" onClick={() => setPage(null)}>← Pages</button><span className="min-w-0 truncate font-medium">{page.icon ?? "📄"} {page.title || "Untitled"}</span></div>38 {src.isLoading ? <div className="skeleton h-5 w-2/3" /> : blocks.length === 0 ? <div className="p-2 text-ui text-fg-muted">This page has no block to reference yet.</div>39 : <div className="max-h-64 overflow-y-auto" role="listbox" aria-label="Blocks">{blocks.map((b) => <button key={b.id} type="button" role="option" aria-selected={false} className="ref-option" onClick={() => onPick(page.id, b.id!)}><span className="ref-kind">{b.type === "heading" ? "H" : "¶"}</span><span className="line-clamp-2 min-w-0">{b.text}</span></button>)}</div>}40 </div>41 );42 return (43 <div className="ref-picker">44 <label className="flex items-center gap-2 rounded-control border border-line bg-bg px-2"><Search className="size-4 text-fg-faint" aria-hidden /><input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search a page…" aria-label="Search a page" className="h-9 min-w-0 flex-1 bg-transparent text-ui outline-none" style={{ outline: "none" }} /></label>45 <div className="mt-1 max-h-64 overflow-y-auto" role="listbox" aria-label="Pages">{(hits.data ?? []).filter((h) => h.type !== "database" && h.id !== exclude).map((h) => <button key={h.id} type="button" role="option" aria-selected={false} className="ref-option" onClick={() => setPage(h)}><span className="ref-kind">{h.icon ?? "📄"}</span><span className="min-w-0 truncate">{h.title || "Untitled"}</span></button>)}{hits.data && hits.data.length === 0 && <div className="p-2 text-ui text-fg-muted">No page matches.</div>}</div>46 </div>47 );48}4950export function BlockRefView({ attrs, update, editable, selected, pageId }: LeafViewProps<BlockRefAttrs>) {51 const depth = React.useContext(RefDepth); const [picking, setPicking] = React.useState(false);52 const src = usePage(attrs.pageId); const block = React.useMemo(() => (attrs.blockId ? findBlock(src.data?.content, attrs.blockId) : null), [src.data, attrs.blockId]);53 const href = attrs.pageId ? `/p/${attrs.pageId}${attrs.blockId ? `#block-${attrs.blockId}` : ""}` : null;54 const pageTitle = src.data ? `${src.data.icon ?? "📄"} ${src.data.title || "Untitled"}` : "";55 const missing = Boolean(attrs.pageId) && !src.isLoading && (!src.data || src.data.deletedAt || !block);56 const actions = <>{href && !missing && <Link href={href} className="nb-btn" title="Jump to the source" aria-label="Jump to the source"><ExternalLink /></Link>}57 {editable && attrs.pageId && <NodeButton label={attrs.mode === "embed" ? "Show as a link" : "Show the content"} onClick={() => update({ mode: attrs.mode === "embed" ? "link" : "embed" })}>{attrs.mode === "embed" ? <Link2 /> : <Rows3 />}</NodeButton>}58 {editable && attrs.pageId && <NodeButton label="Choose another block" active={picking} onClick={() => setPicking((p) => !p)}><Replace /></NodeButton>}</>;59 return (60 <NodeFrame kind="blockRef" icon={<CornerDownRight />} label="Reference" title={pageTitle} selected={selected} actions={actions}>61 {(!attrs.pageId || picking) && (editable ? <div className="p-2"><BlockPicker exclude={null} onPick={(p, b) => { update({ pageId: p, blockId: b }); setPicking(false); }} /></div> : <NodeState icon={<Unlink />} title="Empty reference" />)}62 {attrs.pageId && !picking && (src.isLoading ? <div className="p-3"><div className="skeleton h-5 w-3/4" /></div>63 : src.isError ? <NodeState tone="danger" icon={<Unlink />} title="The source could not be loaded" hint={(src.error as Error)?.message}><NodeButton label="Retry" text onClick={() => src.refetch()} /></NodeState>64 : missing ? <NodeState icon={<Unlink />} title="Reference not found" hint={<span lang="fr">Référence introuvable — the source block or its page was removed.</span>} />65 : attrs.mode === "link" || depth >= 2 || attrs.pageId === pageId && depth > 0 ? <Link href={href!} className="ref-link"><CornerDownRight className="size-4 shrink-0 text-fg-faint" aria-hidden /><span className="line-clamp-2 min-w-0">{docBlocks({ type: "doc", content: [block!] })[0]?.text ?? pageTitle}</span></Link>66 : <div className="ref-embed" data-testid="blockref-embed"><RefDepth.Provider value={depth + 1}><React.Suspense fallback={<div className="skeleton h-5 w-3/4" />}><EmbeddedEditor key={`${attrs.pageId}-${attrs.blockId}-${src.dataUpdatedAt}`} content={{ type: "doc", content: [block!] }} editable={false} embedded className="ref-embed-editor" /></React.Suspense></RefDepth.Provider></div>)}67 </NodeFrame>68 );69}7071interface TreeLite { id: string; title: string; icon: string | null; type: string }72export function CanvasLinkView({ attrs, update, editable, selected, pageId }: LeafViewProps<CanvasLinkAttrs>) {73 const tree = useQuery({ queryKey: ["tree"], staleTime: 10_000, queryFn: () => api<TreeLite[]>("/api/tree") });74 const [unavailable, setUnavailable] = React.useState(false); const [busy, setBusy] = React.useState(false);75 const canvases = (tree.data ?? []).filter((n) => n.type === "canvas"); const target = (tree.data ?? []).find((n) => n.id === attrs.pageId);76 const head = useQuery({ queryKey: ["page-head", attrs.pageId], enabled: Boolean(attrs.pageId) && tree.isSuccess && !target, retry: false, staleTime: 30_000, queryFn: async () => { try { return await api<{ id: string; deletedAt: string | null }>(`/api/pages/${attrs.pageId}?head=1`); } catch { return null; } } });77 async function create() {78 setBusy(true);79 try { const p = await api<{ id: string }>("/api/pages", { method: "POST", json: { title: "New canvas", type: "canvas", parentId: pageId ?? null } }); update({ pageId: p.id }); tree.refetch(); }80 catch (e) { if (e instanceof ApiError && [400, 404, 422].includes(e.status)) setUnavailable(true); else toast("Canvas not created", { description: (e as Error).message, tone: "danger" }); }81 finally { setBusy(false); }82 }83 if (attrs.pageId) {84 const gone = tree.isSuccess && !target && head.isFetched && (!head.data || head.data.deletedAt);85 return (86 <NodeFrame kind="canvasLink" icon={<Shapes />} label="Canvas" selected={selected} bare>87 {gone ? <div className="canvas-card is-missing"><Unlink className="size-4" aria-hidden /><span>Canvas not found — it may have been deleted.</span></div>88 : <Link href={`/p/${attrs.pageId}`} className="canvas-card"><span className="canvas-thumb" aria-hidden><Shapes /></span><span className="min-w-0 flex-1"><span className="block truncate font-medium text-fg">{target ? `${target.icon ?? ""} ${target.title || "Untitled canvas"}`.trim() : "Canvas"}</span><span className="block text-micro text-fg-faint">Open the canvas</span></span><ExternalLink className="size-4 shrink-0 text-fg-faint" aria-hidden /></Link>}89 </NodeFrame>90 );91 }92 return (93 <NodeFrame kind="canvasLink" icon={<Shapes />} label="Canvas" selected={selected}>94 {!editable ? <NodeState icon={<Shapes />} title="No canvas linked" />95 : unavailable ? <NodeState icon={<Shapes />} title="Canvases are not available on this server yet" hint="The block is kept; link a canvas once the server is updated." />96 : <NodeState icon={<Shapes />} title="Link a canvas" hint={canvases.length ? "Choose an existing canvas or create one." : "No canvas exists yet."}>97 {canvases.slice(0, 6).map((c) => <NodeButton key={c.id} label={c.title || "Untitled canvas"} text onClick={() => update({ pageId: c.id })}><Shapes /></NodeButton>)}98 <NodeButton label="New canvas" text tone="accent" disabled={busy} onClick={create}><Plus /></NodeButton>99 </NodeState>}100 </NodeFrame>101 );102}103