Pages edit WYSIWYG: Notion-style editor replaces the source textarea

TipTap + tiptap-markdown render the document as it will appear; Markdown
stays the only storage/transport format so autosave/version conflicts,
server-side link+embed parsing, revisions, exports and the MCP tools are
all untouched.

- components/page-editor.tsx: edit-in-place blocks, Markdown input rules
  (# / ** / [] ), slash block menu, formatting toolbar, GFM tables and
  task lists, bare-URL paste offers a titled-link upgrade, superbrain:page
  links navigate on click
- {{collection:...}} marker paragraphs render as live PageEmbedCards via a
  paragraph node view (components/page-embed-card.tsx, extracted from the
  pages client so both can use it without a cycle)
- the Eye/Pencil source<->preview toggle and the textarea are gone;
  conflict banner, history restore and recovery drafts drive the editor
  through resetContent()
- regressions drive the contenteditable via [data-page-editor] +
  select-all + insertText (fill() cannot target contenteditable)

Pages stay Pages (no rename).
This commit is contained in:
Andrew S Erwin
2026-11-07 15:14:59 -06:00
parent 42376476a0
commit 35b3ff4ab2
6 changed files with 1014 additions and 360 deletions
+329
View File
@@ -0,0 +1,329 @@
'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).
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
}
// 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 },
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 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
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()
}}><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>
)
})
+113
View File
@@ -0,0 +1,113 @@
'use client'
// Read-only live collection view embedded in a page (phase 3). Extracted
// from the pages client so the WYSIWYG page editor can render embed markers
// as cards inside the document (paragraph node view) without an import
// cycle. It fetches the same authorized item endpoint the collection
// workspace uses, so a live embed never exposes a bookmark the viewer
// cannot already see and the server's filters/sorts still apply. It is a
// display, never a publication.
import { useEffect, useState } from 'react'
import Link from 'next/link'
import { Layers } from 'lucide-react'
export type LinkedBookmark = { id: string; url: string; title: string | null; favicon: string | null; ogImage: string | null; ogTitle: string | null; ogDescription: string | null; description: string | null }
export type EmbeddedProperty = {
id: string; name: string
type: 'TEXT' | 'NUMBER' | 'SELECT' | 'MULTI_SELECT' | 'DATE' | 'CHECKBOX' | 'URL'
position: number; config: { options?: { id: string; label: string; color?: string }[]; mode?: 'date' | 'datetime' }
}
export type EmbeddedView = { id: string; name: string; type: string; position: number }
export type PageEmbed = {
collectionId: string; viewId: string | null; position: number
collection: { id: string; name: string; icon: string | null; description: string | null; properties: EmbeddedProperty[]; views: EmbeddedView[] }
view: EmbeddedView | null
}
export type EmbeddedItem = { id: string; propertyValues: Record<string, unknown>; bookmark: LinkedBookmark }
const host = (u: string) => { try { return new URL(u).hostname.replace(/^www\./, '') } catch { return u } }
export function PageEmbedCard({ embed }: { embed: PageEmbed }) {
const viewId = embed.viewId ?? embed.collection.views[0]?.id ?? null
const embedKey = `${embed.collectionId}|${viewId ?? ''}`
// The fetched result carries its embed key so switching collections never
// shows another embed's items for a frame; the effect only writes state
// asynchronously (no cascading synchronous setState).
const [loaded, setLoaded] = useState<{ key: string; items: EmbeddedItem[] | null; failed: boolean }>({ key: '', items: null, failed: false })
useEffect(() => {
let cancelled = false
const params = new URLSearchParams({ limit: '50' })
if (viewId) params.set('viewId', viewId)
fetch(`/api/collections/${embed.collectionId}/items?${params}`)
.then((res) => (res.ok ? res.json() : Promise.reject(new Error('load failed'))))
.then((data: EmbeddedItem[]) => { if (!cancelled) setLoaded({ key: embedKey, items: data, failed: false }) })
.catch(() => { if (!cancelled) setLoaded({ key: embedKey, items: null, failed: true }) })
return () => { cancelled = true }
}, [embed.collectionId, embedKey, viewId])
const current = loaded.key === embedKey ? loaded : { key: embedKey, items: null, failed: false }
const items = current.items
const failed = current.failed
const properties = embed.collection.properties.slice(0, 4)
const optionLabel = (prop: EmbeddedProperty, value: unknown) => {
if (prop.type === 'CHECKBOX') return value === true ? 'Yes' : 'No'
if (prop.type === 'SELECT') return prop.config.options?.find((o) => o.id === value)?.label ?? '—'
if (prop.type === 'MULTI_SELECT') {
if (!Array.isArray(value)) return '—'
return value.map((id) => prop.config.options?.find((o) => o.id === id)?.label).filter(Boolean).join(', ') || '—'
}
if (prop.type === 'DATE' && typeof value === 'string' && value) {
if (prop.config.mode === 'date') return value.slice(0, 10)
const d = new Date(value)
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString('en-US', { timeZone: 'UTC' })
}
if (value === null || value === undefined || value === '') return '—'
return String(value)
}
const viewLabel = embed.view?.name ?? embed.collection.views[0]?.name
return (
<section className="not-prose my-4 overflow-hidden rounded-lg border bg-card">
<div className="flex items-center gap-2 border-b px-3 py-2">
<Layers className="h-4 w-4 shrink-0 text-muted-foreground" />
<Link href="/collections" className="truncate text-sm font-medium hover:underline">{embed.collection.name}</Link>
{viewLabel && <span className="truncate text-xs text-muted-foreground">· {viewLabel}</span>}
<span className="ml-auto text-xs text-muted-foreground">{items ? `${items.length} item${items.length === 1 ? '' : 's'}` : ''}</span>
</div>
{failed ? (
<p className="px-3 py-4 text-sm text-muted-foreground">This collection could not be loaded.</p>
) : items === null ? (
<p className="px-3 py-4 text-sm text-muted-foreground">Loading collection…</p>
) : items.length === 0 ? (
<p className="px-3 py-4 text-sm text-muted-foreground">No items match this view.</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-left text-sm">
<thead className="bg-muted/40 text-xs text-muted-foreground">
<tr>
<th className="px-3 py-2 font-medium">Bookmark</th>
{properties.map((p) => <th key={p.id} className="px-3 py-2 font-medium">{p.name}</th>)}
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.id} className="border-t">
<td className="max-w-[18rem] px-3 py-2">
<Link href={`/bookmarks?open=${item.bookmark.id}`} className="block truncate hover:underline">
{item.bookmark.title || item.bookmark.ogTitle || item.bookmark.url}
</Link>
<span className="block truncate text-xs text-muted-foreground">{host(item.bookmark.url)}</span>
</td>
{properties.map((p) => <td key={p.id} className="max-w-[12rem] truncate px-3 py-2 text-muted-foreground">{optionLabel(p, item.propertyValues?.[p.id])}</td>)}
</tr>
))}
</tbody>
</table>
</div>
)}
</section>
)
}