Files
Andrew S Erwin 3f86214cf5 Page URLs become bookmarks: paste, Link button and popover create-or-reuse a page bookmark
Product invariant: every URL a user adds to a page now becomes a bookmark
linked to that page. Bare-URL pastes and the editor Link button announce
the URL through PageEditor's new onAddUrl; the workspace reuses an
existing same-URL bookmark (normalized: scheme implied, hash dropped,
trailing slash trimmed) instead of minting duplicates, and attaches via
addBookmarkId without refetching — so an editor-triggered attach can
never reset the caret mid-typing. Pasted Markdown stays untouched; the
titled-link upgrade keeps its explicit-click rule.

Fix found by the revived suites: loadPage now repaints the uncontrolled
editor on every load, so discard/recovery no longer leaves stale draft
text on screen.
2026-11-11 15:00:48 -06:00

347 lines
17 KiB
TypeScript

'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<string, PageEmbed>() }
},
})
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<string, PageEmbed> }
// 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(<PageEmbedCard embed={embed} />)
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<PageEditorHandle, Props>(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<typeof slash>(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<Editor | null>(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<string, PageEmbed> }
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 (
<div className="relative">
<div className="mb-2 flex flex-wrap items-center gap-0.5 rounded-md border bg-muted/40 p-1" role="toolbar" aria-label="Formatting">
<Button type="button" variant="ghost" size="sm" className={cn(tb, editor.isActive('bold') && active)} aria-label="Bold" title="Bold" onClick={() => editor.chain().focus().toggleBold().run()}><Bold className="h-3.5 w-3.5" /></Button>
<Button type="button" variant="ghost" size="sm" className={cn(tb, editor.isActive('italic') && active)} aria-label="Italic" title="Italic" onClick={() => editor.chain().focus().toggleItalic().run()}><Italic className="h-3.5 w-3.5" /></Button>
<Button type="button" variant="ghost" size="sm" className={cn(tb, editor.isActive('strike') && active)} aria-label="Strikethrough" title="Strikethrough" onClick={() => editor.chain().focus().toggleStrike().run()}><Strikethrough className="h-3.5 w-3.5" /></Button>
<Button type="button" variant="ghost" size="sm" className={cn(tb, editor.isActive('code') && active)} aria-label="Inline code" title="Inline code" onClick={() => editor.chain().focus().toggleCode().run()}><Code className="h-3.5 w-3.5" /></Button>
<Button type="button" variant="ghost" size="sm" className={tb} aria-label="Link" title="Link" onClick={() => {
const url = window.prompt('Link URL (https://… or superbrain:page/<id>)')
if (!url) return
editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run()
// A real web URL on the page must also become a bookmark; internal
// superbrain: links stay page-to-page edges instead.
if (/^https?:\/\/\S+$/i.test(url)) onAddUrl?.(url)
}}><Link2 className="h-3.5 w-3.5" /></Button>
<span className="mx-1 h-4 w-px bg-border" aria-hidden />
<Button type="button" variant="ghost" size="sm" className={cn(tb, editor.isActive('heading', { level: 1 }) && active)} aria-label="Heading 1" title="Heading 1" onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}><Heading1 className="h-3.5 w-3.5" /></Button>
<Button type="button" variant="ghost" size="sm" className={cn(tb, editor.isActive('heading', { level: 2 }) && active)} aria-label="Heading 2" title="Heading 2" onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}><Heading2 className="h-3.5 w-3.5" /></Button>
<Button type="button" variant="ghost" size="sm" className={cn(tb, editor.isActive('heading', { level: 3 }) && active)} aria-label="Heading 3" title="Heading 3" onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}><Heading3 className="h-3.5 w-3.5" /></Button>
<Button type="button" variant="ghost" size="sm" className={cn(tb, editor.isActive('blockquote') && active)} aria-label="Quote" title="Quote" onClick={() => editor.chain().focus().toggleBlockquote().run()}><Quote className="h-3.5 w-3.5" /></Button>
<span className="mx-1 h-4 w-px bg-border" aria-hidden />
<Button type="button" variant="ghost" size="sm" className={cn(tb, editor.isActive('bulletList') && active)} aria-label="Bulleted list" title="Bulleted list" onClick={() => editor.chain().focus().toggleBulletList().run()}><List className="h-3.5 w-3.5" /></Button>
<Button type="button" variant="ghost" size="sm" className={cn(tb, editor.isActive('orderedList') && active)} aria-label="Numbered list" title="Numbered list" onClick={() => editor.chain().focus().toggleOrderedList().run()}><ListOrdered className="h-3.5 w-3.5" /></Button>
<Button type="button" variant="ghost" size="sm" className={cn(tb, editor.isActive('taskList') && active)} aria-label="To-do list" title="To-do list" onClick={() => editor.chain().focus().toggleTaskList().run()}><ListTodo className="h-3.5 w-3.5" /></Button>
<Button type="button" variant="ghost" size="sm" className={tb} aria-label="Divider" title="Divider" onClick={() => editor.chain().focus().setHorizontalRule().run()}><Minus className="h-3.5 w-3.5" /></Button>
</div>
<EditorContent editor={editor} />
{slash && filtered.length > 0 && (
<div
role="listbox"
aria-label="Blocks to insert"
className="fixed z-50 w-64 overflow-hidden rounded-lg border bg-popover p-1 shadow-lg"
style={{ left: slash.x, top: slash.y + 6 }}
onMouseDown={(e) => e.preventDefault()}
>
{filtered.map((b, i) => (
<button
key={b.key}
role="option"
aria-selected={i === slash.index}
className={cn('flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm', i === slash.index ? 'bg-accent text-accent-foreground' : 'hover:bg-muted')}
onMouseEnter={() => setSlash({ ...slash, index: i })}
onClick={() => applyBlock(b.key)}
>
<b.icon className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="flex-1 truncate">{b.label}</span>
<span className="truncate text-xs text-muted-foreground">{b.desc}</span>
</button>
))}
</div>
)}
</div>
)
})