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
+18 -334
View File
@@ -1,64 +1,28 @@
'use client'
import { useCallback, useEffect, useRef, useState, type ClipboardEvent } from 'react'
import Link from 'next/link'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { toast } from 'sonner'
import {
Code, CornerUpLeft, Download, Eye, FileText,
Heading1, Heading2, Heading3, History, Layers, Link2, List, ListOrdered, ListTodo, Minus, Pencil,
Pin, PinOff, Plus, Quote, RotateCcw, Trash2, Type, X,
CornerUpLeft, Download, FileText, History, Layers, Link2, Pin, PinOff, Plus, RotateCcw, Trash2, X,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { cn } from '@/lib/utils'
import { MarkdownToolbar } from '@/components/markdown-toolbar'
import { PageAutosave, PageConflictError, type PageSaveState } from '@/lib/page-autosave'
import {
PAGES_CHANGED, collectionEmbedMarkdown, descendantPageIds, internalPageId, nextUntitledTitle,
notifyActivePage, notifyPagesChanged, pageLinkMarkdown, parsePageEmbed, type PageSummary,
PAGES_CHANGED, collectionEmbedMarkdown, descendantPageIds, nextUntitledTitle,
notifyActivePage, notifyPagesChanged, pageLinkMarkdown, type PageSummary,
} from '@/lib/pages'
import { fetchLinkPreview } from '@/lib/link-preview'
import { PageEditor, type PageEditorHandle } from '@/components/page-editor'
import { type PageEmbed, type LinkedBookmark } from '@/components/page-embed-card'
import { LinkPreviewCard } from '@/components/link-preview-card'
import type { Element, ElementContent } from 'hast'
export { PAGES_CHANGED }
// Notion-style slash menu: typing "/" at the start of a line offers blocks
// that insert their Markdown equivalent. The textarea stays the source of
// truth, so autosave and conflict handling are untouched.
const SLASH_BLOCKS = [
{ key: 'text', label: 'Text', desc: 'Plain paragraph', icon: Type, prefix: '' },
{ key: 'h1', label: 'Heading 1', desc: 'Large section heading', icon: Heading1, prefix: '# ' },
{ key: 'h2', label: 'Heading 2', desc: 'Medium section heading', icon: Heading2, prefix: '## ' },
{ key: 'h3', label: 'Heading 3', desc: 'Small section heading', icon: Heading3, prefix: '### ' },
{ key: 'todo', label: 'To-do list', desc: 'Track tasks with a checkbox', icon: ListTodo, prefix: '- [ ] ' },
{ key: 'bullet', label: 'Bulleted list', desc: 'Simple bulleted list', icon: List, prefix: '- ' },
{ key: 'num', label: 'Numbered list', desc: 'List with numbering', icon: ListOrdered, prefix: '1. ' },
{ key: 'quote', label: 'Quote', desc: 'Capture a quote', icon: Quote, prefix: '> ' },
{ key: 'div', label: 'Divider', desc: 'Visual section break', icon: Minus, prefix: '---\n' },
{ key: 'code', label: 'Code', desc: 'Code snippet block', icon: Code, prefix: '```\n' },
] as const
type LinkedBookmark = { id: string; url: string; title: string | null; favicon: string | null; ogImage: string | null; ogTitle: string | null; ogDescription: string | null; description: string | null }
type PageBacklink = { id: string; title: string; updatedAt: string }
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' }
}
type EmbeddedView = { id: string; name: string; type: string; position: number }
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
}
type EmbeddedItem = { id: string; propertyValues: Record<string, unknown>; bookmark: LinkedBookmark }
type PageDetail = PageSummary & {
content: string; version: number
bookmarks: { bookmark: LinkedBookmark }[]
@@ -71,119 +35,11 @@ type PageRevisionDetail = PageRevisionSummary & { content: string; icon: string
const notify = notifyPagesChanged
const host = (u: string) => { try { return new URL(u).hostname.replace(/^www\./, '') } catch { return u } }
// Read-only live collection view embedded in a page (phase 3). 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.
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 date = new Date(value)
return Number.isNaN(date.getTime()) ? value : date.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>
)
}
const textOf = (nodes: ElementContent[]): string =>
nodes.map((n) => (n.type === 'text' ? n.value : n.type === 'element' ? textOf(n.children) : '')).join('')
// A paragraph whose only content is a single external link — a bare URL
// autolinked by GFM or a lone [label](url) — renders as a Notion-style
// preview card instead of a plain <p><a>. Links woven into sentences stay
// inline text; the Markdown source remains the source of truth either way.
function standaloneLink(node: Element | undefined): { href: string; label: string } | null {
if (!node) return null
const kids = node.children.filter((c) => !(c.type === 'text' && c.value.trim() === ''))
if (kids.length !== 1) return null
const a = kids[0]
if (a.type !== 'element' || a.tagName !== 'a') return null
const href = a.properties?.href
if (typeof href !== 'string' || !/^https?:\/\//i.test(href)) return null
return { href, label: textOf(a.children) }
}
export function PagesClient({ initialId }: { initialId: string | null }) {
const router = useRouter()
const [pages, setPages] = useState<PageSummary[]>([])
const [activeId, setActiveId] = useState<string | null>(initialId)
const [page, setPage] = useState<PageDetail | null>(null)
const [mode, setMode] = useState<'edit' | 'preview'>('preview')
const [title, setTitle] = useState('')
const [content, setContent] = useState('')
const [saveStates, setSaveStates] = useState<Record<string, PageSaveState>>({})
@@ -198,10 +54,7 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
const [revisions, setRevisions] = useState<PageRevisionSummary[]>([])
const [revision, setRevision] = useState<PageRevisionDetail | null>(null)
const [historyBusy, setHistoryBusy] = useState<string | null>(null)
const [slash, setSlash] = useState<{ query: string; start: number } | null>(null)
const [slashIndex, setSlashIndex] = useState(0)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const pendingCaret = useRef<number | null>(null)
const editorRef = useRef<PageEditorHandle>(null)
const activePage = useRef(initialId)
const loadSequence = useRef(0)
const selectionSequence = useRef(0)
@@ -281,7 +134,7 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
setTitle(data.title)
setContent(draft ?? data.content)
notifyActivePage(data.title)
if (draft !== undefined || !data.content) setMode('edit')
if (draft !== undefined) editorRef.current?.resetContent(draft)
}, [autosave])
useEffect(() => {
@@ -355,7 +208,6 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
const p = await res.json()
await loadPages()
notify()
setMode('edit')
select(p.id)
}
@@ -370,16 +222,7 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
// embeds are resolved by the server from this text.
const insertSnippet = (snippet: string) => {
if (!page || page.id !== activeId) return
const ta = textareaRef.current
const caret = mode === 'edit' && ta ? ta.selectionStart : content.length
const before = content.slice(0, caret)
const after = content.slice(caret)
const lead = before && !before.endsWith('\n') ? '\n\n' : ''
const trail = after.startsWith('\n') ? '' : '\n'
const next = before + lead + snippet + trail + after
pendingCaret.current = before.length + lead.length + snippet.length
setMode('edit')
onContentChange(next)
editorRef.current?.insertSnippet(snippet)
}
const setParent = async (value: string) => {
@@ -436,7 +279,7 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
setPage(restored)
setTitle(restored.title)
setContent(restored.content)
setMode('preview')
editorRef.current?.resetContent(restored.content)
notifyActivePage(restored.title)
setHistoryOpen(false)
toast.success(`Restored version ${rev.version} as version ${restored.version}`)
@@ -445,38 +288,6 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
finally { setHistoryBusy(null) }
}
// Show the block menu only while the caret sits on a bare "/token" line.
const updateSlash = (text: string, caret: number) => {
const lineStart = text.lastIndexOf('\n', caret - 1) + 1
const line = text.slice(lineStart, caret)
const m = /^\/([\w-]*)$/.exec(line)
if (m) { setSlash({ query: m[1].toLowerCase(), start: lineStart }); setSlashIndex(0) }
else setSlash(null)
}
const slashFiltered = SLASH_BLOCKS.filter((b) => !slash?.query || b.key.includes(slash.query) || b.label.toLowerCase().includes(slash.query))
const applyBlock = (block: (typeof SLASH_BLOCKS)[number]) => {
const ta = textareaRef.current
if (!slash || !ta) return
const caret = ta.selectionStart
const next = content.slice(0, slash.start) + block.prefix + content.slice(caret)
pendingCaret.current = slash.start + block.prefix.length
onContentChange(next)
setSlash(null)
}
// Restore the caret after a programmatic content rewrite (slash insert,
// "[] " shortcut). Runs once the new content has reached the textarea.
useEffect(() => {
if (pendingCaret.current === null || mode !== 'edit') return
const ta = textareaRef.current
if (!ta) return
const c = pendingCaret.current
pendingCaret.current = null
ta.focus()
ta.setSelectionRange(c, c)
}, [content, mode])
const saveTitle = async () => {
if (!page) return
@@ -595,35 +406,6 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
// Notion-style paste: a bare URL lands in the textarea untouched, and once
// its preview resolves we offer to upgrade it to a titled Markdown link.
// Nothing is rewritten without an explicit click, so undo stays intact.
const offerTitleForPastedUrl = (url: string) => {
void fetchLinkPreview(url).then((p) => {
const raw = p?.ogTitle || p?.title
if (!raw) return
const title = raw.replace(/[\[\]\n]/g, ' ').trim()
if (!title || title === url) return
toast.info('Paste as titled link?', {
description: title,
duration: 10000,
action: {
label: 'Use title',
onClick: () => {
const ta = textareaRef.current
if (!ta) return
const idx = ta.value.indexOf(url)
if (idx < 0) return
const markdown = `[${title}](${url})`
pendingCaret.current = idx + markdown.length
onContentChange(ta.value.slice(0, idx) + markdown + ta.value.slice(idx + url.length))
},
},
})
})
}
const onPaste = (e: ClipboardEvent<HTMLTextAreaElement>) => {
const text = e.clipboardData.getData('text/plain').trim()
if (/^https?:\/\/\S+$/i.test(text)) offerTitleForPastedUrl(text)
}
const looksLikeUrl = /^(https?:\/\/)?[\w-]+(\.[\w-]+)+/i.test(linkQuery.trim())
// A page may move under any page except itself or one of its descendants
@@ -649,7 +431,6 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
<input value={title} onChange={(e) => setTitle(e.target.value)} onBlur={saveTitle} onKeyDown={(e) => e.key === 'Enter' && (e.target as HTMLInputElement).blur()} className="min-w-0 flex-1 bg-transparent font-display text-3xl font-bold outline-none" aria-label="Page title" />
<span className="text-xs text-muted-foreground">{saveState === 'saving' ? 'Saving…' : saveState === 'dirty' ? 'Unsaved' : saveState === 'conflict' ? 'Conflict' : 'Saved'}</span>
{saveState === 'dirty' && <Button size="sm" variant="outline" onClick={() => autosave.flush(page.id)}>Save now</Button>}
<Button variant="ghost" size="icon-sm" title={mode === 'edit' ? 'Preview' : 'Edit'} onClick={() => { setMode(mode === 'edit' ? 'preview' : 'edit'); setSlash(null) }}>{mode === 'edit' ? <Eye className="h-4 w-4" /> : <Pencil className="h-4 w-4" />}</Button>
<Button variant="ghost" size="icon-sm" title={page.pinned ? 'Unpin' : 'Pin to sidebar'} onClick={togglePin}>{page.pinned ? <PinOff className="h-4 w-4" /> : <Pin className="h-4 w-4" />}</Button>
<Button variant="ghost" size="icon-sm" title="Download .md" onClick={download}><Download className="h-4 w-4" /></Button>
<Button variant="ghost" size="icon-sm" title="Version history" onClick={() => void openHistory()}><History className="h-4 w-4" /></Button>
@@ -717,111 +498,14 @@ export function PagesClient({ initialId }: { initialId: string | null }) {
</div>
)}
{mode === 'edit' ? (
<div className="relative">
<MarkdownToolbar textareaRef={textareaRef} value={content} onChange={onContentChange} className="mb-2" />
<Textarea
ref={textareaRef}
value={content}
onChange={(e) => { onContentChange(e.target.value); updateSlash(e.target.value, e.target.selectionStart) }}
onClick={(e) => updateSlash(e.currentTarget.value, e.currentTarget.selectionStart)}
onPaste={onPaste}
onBlur={() => setSlash(null)}
onKeyDown={(e) => {
// While the slash menu is open, arrows/Enter/Tab/Escape drive it.
if (slash && slashFiltered.length > 0) {
if (e.key === 'ArrowDown') { e.preventDefault(); setSlashIndex((i) => (i + 1) % slashFiltered.length); return }
if (e.key === 'ArrowUp') { e.preventDefault(); setSlashIndex((i) => (i - 1 + slashFiltered.length) % slashFiltered.length); return }
if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); applyBlock(slashFiltered[Math.min(slashIndex, slashFiltered.length - 1)]); return }
if (e.key === 'Escape') { e.preventDefault(); setSlash(null); return }
}
// Notion Markdown shortcut: "[]" + space becomes a to-do item.
if (e.key === ' ') {
const ta = e.currentTarget
const caret = ta.selectionStart
const lineStart = ta.value.lastIndexOf('\n', caret - 1) + 1
if (ta.value.slice(lineStart, caret) === '[]') {
e.preventDefault()
const next = ta.value.slice(0, lineStart) + '- [ ] ' + ta.value.slice(caret)
pendingCaret.current = lineStart + '- [ ] '.length
onContentChange(next)
}
}
}}
placeholder="Write Markdown notes… type / for blocks, paste links, lists, thoughts."
className="min-h-[260px] font-mono text-sm"
/>
{slash && slashFiltered.length > 0 && (
<div
onMouseDown={(e) => e.preventDefault()}
role="listbox"
aria-label="Blocks to insert"
className="absolute left-2 top-full z-20 mt-1 w-72 rounded-lg border bg-popover p-1 shadow-lg"
>
<p className="px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">Basic blocks</p>
<div className="max-h-64 overflow-y-auto">
{slashFiltered.map((b, i) => (
<button
key={b.key}
type="button"
role="option"
aria-selected={i === slashIndex}
onMouseEnter={() => setSlashIndex(i)}
onClick={() => applyBlock(b)}
className={cn('flex w-full items-center gap-2.5 rounded-md px-2 py-1.5 text-left', i === slashIndex ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50')}
>
<span className="flex h-7 w-7 shrink-0 items-center justify-center rounded border bg-card">
<b.icon className="h-3.5 w-3.5 text-muted-foreground" />
</span>
<span className="min-w-0">
<span className="block text-sm font-medium">{b.label}</span>
<span className="block truncate text-xs text-muted-foreground">{b.desc}</span>
</span>
</button>
))}
</div>
</div>
)}
</div>
) : (
<div className="prose prose-sm max-w-none dark:prose-invert min-h-[80px] cursor-text" onDoubleClick={() => setMode('edit')}>
{content ? (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
p: ({ node, ...props }) => {
// A paragraph that is exactly an embed marker renders a
// live, read-only collection view instead of raw text.
const marker = node ? parsePageEmbed(textOf(node.children)) : null
if (marker) {
const embed = page.embeds.find((e) => e.collectionId === marker.collectionId)
return embed ? (
<PageEmbedCard embed={embed} />
) : (
<p className="text-xs text-muted-foreground">This embedded collection is unavailable or not yours.</p>
)
}
const link = standaloneLink(node)
return link ? (
<LinkPreviewCard url={link.href} label={link.label !== link.href ? link.label : undefined} />
) : (
<p {...props} />
)
},
a: ({ href, ...props }) => {
const target = href ? internalPageId(href) : null
if (target) {
return <Link href={`/pages?id=${target}`} className="text-primary underline-offset-2 hover:underline" {...props} />
}
return <a {...props} href={href} target="_blank" rel="noopener noreferrer" />
},
}}
>{content}</ReactMarkdown>
) : (
<p className="text-muted-foreground">No notes yet. Double-click or press the pencil to write.</p>
)}
</div>
)}
<PageEditor
key={page.id}
ref={editorRef}
content={content}
embeds={page.embeds}
onContentChange={onContentChange}
onNavigatePage={(id) => { void select(id) }}
/>
<div className="mt-10 mb-3 flex items-center justify-between">
<h3 className="font-display text-lg font-semibold">Links on this page <span className="text-sm font-normal text-muted-foreground">({page.bookmarks.length})</span></h3>