'use client' // Notion-style WYSIWYG page editor (Gitea issue: "shown in preview rather // than source"). TipTap renders the document as it will appear; Markdown // remains the ONLY storage/transport format (tiptap-markdown round-trips // it), so autosave/version conflicts, server-side link+embed parsing, // revisions, exports and the MCP tools are all untouched. // // - Markdown input rules give the Notion feel: "# " promotes a heading, // "**" bolds, "[] " starts a to-do, "/" opens the block menu. // - {{collection:...}} marker paragraphs render as live PageEmbedCards via // a paragraph node view; they serialize back to the exact marker text. // - superbrain:page/ links navigate on click instead of editing the href. // - A bare-URL paste stays plain text and offers a titled-link upgrade once // the preview resolves (nothing is rewritten without an explicit click). // - Any external http(s) URL the user adds to the page — a bare-URL paste or // the Link button — is also announced via onAddUrl, so the page workspace // can create (or reuse) a bookmark for it. Product invariant: a URL added // to a page becomes a bookmark on the page. import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react' import { createRoot } from 'react-dom/client' import { EditorContent, useEditor, type Editor } from '@tiptap/react' import StarterKit from '@tiptap/starter-kit' import LinkExt from '@tiptap/extension-link' import Placeholder from '@tiptap/extension-placeholder' import Table from '@tiptap/extension-table' import TableRow from '@tiptap/extension-table-row' import TableCell from '@tiptap/extension-table-cell' import TableHeader from '@tiptap/extension-table-header' import TaskList from '@tiptap/extension-task-list' import TaskItem from '@tiptap/extension-task-item' import Paragraph from '@tiptap/extension-paragraph' import { Extension } from '@tiptap/core' import type { Node as ProseMirrorNode } from '@tiptap/pm/model' import { Markdown } from 'tiptap-markdown' import { Bold, Code, Heading1, Heading2, Heading3, Italic, Link2, List, ListOrdered, ListTodo, Minus, Quote, Strikethrough, Type, } from 'lucide-react' import { toast } from 'sonner' import { Button } from '@/components/ui/button' import { PageEmbedCard, type PageEmbed } from '@/components/page-embed-card' import { internalPageId, parsePageEmbed } from '@/lib/pages' import { fetchLinkPreview } from '@/lib/link-preview' import { cn } from '@/lib/utils' export type PageEditorHandle = { insertSnippet: (snippet: string) => void resetContent: (markdown: string) => void } type Props = { content: string embeds: PageEmbed[] onContentChange: (markdown: string) => void onNavigatePage: (id: string) => void // Fired when the user adds an external http(s) URL to the page (bare-URL // paste or the Link button). The page workspace turns it into a bookmark; // the editor never rewrites the Markdown itself. onAddUrl?: (url: string) => void } // Mutable embed lookup the paragraph node view reads at render time. const EmbedStore = Extension.create({ name: 'superbrainEmbedStore', addStorage() { return { byKey: new Map() } }, }) function embedKeyOf(collectionId: string, viewId: string | null) { return `${collectionId}|${viewId ?? ''}` } // Paragraphs that are exactly an embed marker render the live card instead // of raw marker text; everything else falls back to default rendering. const EmbedAwareParagraph = Paragraph.extend({ addNodeView() { return (({ node, editor }: { node: ProseMirrorNode; editor: Editor }) => { const marker = parsePageEmbed(node.textContent) if (!marker) return null const store = editor.storage.superbrainEmbedStore as { byKey: Map } // The server resolves the view; fall back to the collection default so // a stale viewId still shows the card the preview used to show. const embed = store.byKey.get(embedKeyOf(marker.collectionId, marker.viewId)) ?? [...store.byKey.values()].find((e) => e.collectionId === marker.collectionId) ?? null if (!embed) return null const dom = document.createElement('div') dom.setAttribute('contenteditable', 'false') const root = createRoot(dom) root.render() return { dom, destroy() { root.unmount() } } }) as never }, }) const SLASH_BLOCKS = [ { key: 'text', label: 'Text', desc: 'Plain paragraph', icon: Type }, { key: 'h1', label: 'Heading 1', desc: 'Large section heading', icon: Heading1 }, { key: 'h2', label: 'Heading 2', desc: 'Medium section heading', icon: Heading2 }, { key: 'h3', label: 'Heading 3', desc: 'Small section heading', icon: Heading3 }, { key: 'todo', label: 'To-do list', desc: 'Track tasks with a checkbox', icon: ListTodo }, { key: 'bullet', label: 'Bulleted list', desc: 'Simple bulleted list', icon: List }, { key: 'num', label: 'Numbered list', desc: 'List with numbering', icon: ListOrdered }, { key: 'quote', label: 'Quote', desc: 'Capture a quote', icon: Quote }, { key: 'div', label: 'Divider', desc: 'Visual section break', icon: Minus }, { key: 'code', label: 'Code', desc: 'Code snippet block', icon: Code }, ] as const export const PageEditor = forwardRef(function PageEditor( { content, embeds, onContentChange, onNavigatePage, onAddUrl }, ref, ) { const [slash, setSlash] = useState<{ query: string; from: number; to: number; index: number; x: number; y: number } | null>(null) const [, setTick] = useState(0) // toolbar active-state refresh const suppressEmit = useRef(false) const slashRef = useRef(null) slashRef.current = slash const pasteOffer = useRef<{ from: number; to: number; url: string } | null>(null) const onChange = useRef(onContentChange) onChange.current = onContentChange const navigate = useRef(onNavigatePage) navigate.current = onNavigatePage const addUrl = useRef(onAddUrl) addUrl.current = onAddUrl const editor = useEditor({ content, extensions: [ StarterKit.configure({ codeBlock: { HTMLAttributes: { class: 'not-prose' } } }), LinkExt.configure({ openOnClick: false, autolink: false, linkOnPaste: false }), Placeholder.configure({ placeholder: 'Write Markdown notes… type / for blocks, paste links, lists, thoughts.' }), Table.configure({ resizable: false }), TableRow, TableCell, TableHeader, TaskList, TaskItem.configure({ nested: true }), EmbedStore, EmbedAwareParagraph, Markdown.configure({ html: false, tightLists: true }), ], editorProps: { attributes: { 'data-page-editor': 'true', 'aria-label': 'Page content', 'class': 'prose prose-sm dark:prose-invert max-w-none min-h-[260px] outline-none', }, handleClickOn: (_view, _pos, _node, _nodePos, event) => { const a = (event.target as HTMLElement).closest?.('a[href]') const href = a?.getAttribute('href') if (!href) return false const target = internalPageId(href) if (target) { navigate.current(target) return true } return false }, handleKeyDown: (_view, event) => { const sl = slashRef.current if (!sl) return false const filtered = SLASH_BLOCKS.filter((b) => b.key.includes(sl.query) || b.label.toLowerCase().includes(sl.query)) if (filtered.length === 0) return false if (event.key === 'ArrowDown') { event.preventDefault(); setSlash({ ...sl, index: (sl.index + 1) % filtered.length }); return true } if (event.key === 'ArrowUp') { event.preventDefault(); setSlash({ ...sl, index: (sl.index - 1 + filtered.length) % filtered.length }); return true } if (event.key === 'Enter' || event.key === 'Tab') { event.preventDefault() applyBlock(filtered[Math.min(sl.index, filtered.length - 1)].key) return true } if (event.key === 'Escape') { event.preventDefault(); setSlash(null); return true } return false }, handlePaste: (view, event) => { const text = event.clipboardData?.getData('text/plain').trim() ?? '' if (!/^https?:\/\/\S+$/i.test(text)) return false // The URL lands in the page, so it becomes a bookmark (parent creates // or reuses one and links it to the page). The pasted text itself is // still left untouched — this only adds a link, never rewrites. addUrl.current?.(text) const from = view.state.selection.from pasteOffer.current = { from, to: from + text.length, url: text } void fetchLinkPreview(text).then((p) => { const raw = p?.ogTitle || p?.title const title = raw?.trim() const offer = pasteOffer.current if (!title || !offer) return toast.info('Link pasted', { description: `Use “${title.slice(0, 60)}” as the link text?`, action: { label: 'Use title', onClick: () => { const ed = editorRefLocal.current if (!ed) return const current = ed.state.doc.textBetween(offer.from, offer.to, '') if (current !== offer.url) return // doc moved on; never guess ed.chain() .focus() .setTextSelection({ from: offer.from, to: offer.to }) .insertContent(`[${title}](${offer.url})`) .run() pasteOffer.current = null }, }, }) }) return false // let the default paste insert the plain URL text }, }, onUpdate: ({ editor: ed }) => { if (suppressEmit.current) return onChange.current(ed.storage.markdown.getMarkdown()) refreshSlash(ed) setTick((t) => t + 1) }, onSelectionUpdate: ({ editor: ed }): void => refreshSlash(ed), }) const editorRefLocal = useRef(null) editorRefLocal.current = editor // Refresh the embed lookup the paragraph node views read. useEffect(() => { if (!editor) return const store = editor.storage.superbrainEmbedStore as { byKey: Map } store.byKey = new Map(embeds.map((e) => [embedKeyOf(e.collectionId, e.viewId), e])) editor.view.dispatch(editor.state.tr) // re-render node views }, [embeds, editor]) function refreshSlash(ed: Editor) { const { from } = ed.state.selection const lineStart = ed.state.doc.resolve(from).start() const text = ed.state.doc.textBetween(lineStart, from, '\n') const m = /^\/([\w-]*)$/.exec(text) if (!m) { setSlash(null); return } const coords = ed.view.coordsAtPos(from) setSlash((prev) => ({ query: m[1].toLowerCase(), from: lineStart + text.length - m[0].length, to: from, index: prev && prev.query === m[1].toLowerCase() ? prev.index : 0, x: coords.left, y: coords.bottom, })) } function applyBlock(key: (typeof SLASH_BLOCKS)[number]['key']) { const ed = editor const sl = slashRef.current if (!ed || !sl) return const range = { from: sl.from, to: sl.to } const chain = ed.chain().focus().deleteRange(range) switch (key) { case 'h1': chain.setHeading({ level: 1 }); break case 'h2': chain.setHeading({ level: 2 }); break case 'h3': chain.setHeading({ level: 3 }); break case 'todo': chain.toggleTaskList(); break case 'bullet': chain.toggleBulletList(); break case 'num': chain.toggleOrderedList(); break case 'quote': chain.toggleBlockquote(); break case 'div': chain.setHorizontalRule(); break case 'code': chain.toggleCodeBlock(); break default: chain.setParagraph() } chain.run() setSlash(null) } useImperativeHandle(ref, () => ({ insertSnippet(snippet: string) { editor?.chain().focus().insertContent(snippet).run() }, resetContent(markdown: string) { if (!editor) return suppressEmit.current = true editor.commands.setContent(markdown) suppressEmit.current = false }, }), [editor]) if (!editor) return null const filtered = SLASH_BLOCKS.filter((b) => !slash?.query || b.key.includes(slash.query) || b.label.toLowerCase().includes(slash.query)) const tb = 'h-7 w-7 p-0 text-muted-foreground hover:text-foreground' const active = 'bg-accent text-foreground' return (
{slash && filtered.length > 0 && (
e.preventDefault()} > {filtered.map((b, i) => ( ))}
)}
) })