diff --git a/scripts/regressions.mjs b/scripts/regressions.mjs index 3ca1f2f..a18598b 100644 --- a/scripts/regressions.mjs +++ b/scripts/regressions.mjs @@ -241,28 +241,35 @@ try { assert.equal(chunkedStatus, 413, 'oversized chunked body was not rejected at the proxy') console.log('PASS: oversized chunked request bodies are rejected while streaming') - const editor = page.getByPlaceholder('Write Markdown notes… type / for blocks, paste links, lists, thoughts.') + const editor = page.locator('[data-page-editor]') + // The WYSIWYG editor is a contenteditable ProseMirror view: select-all + + // insertText is the fill() equivalent. + const setEditorText = async (text) => { + await editor.click() + await page.keyboard.press('Control+a') + await page.keyboard.insertText(text) + } await page.goto(`${base}/pages?id=a`) - await editor.fill('A edits before switching') + await setEditorText('A edits before switching') await page.getByRole('button', { name: 'Page B', exact: true }).click() await eventually(() => page.getByRole('textbox', { name: 'Page title' }).inputValue().then(v => v === 'Page B'), 'Page B not selected') - await editor.fill('B edits') + await setEditorText('B edits') await eventually(() => pages.get('b').content === 'B edits', 'Page B not saved') assert.equal(pages.get('a').content, 'A edits before switching') console.log('PASS: rapid page switching preserves both pages') delaySaves = 900 maxConcurrentSaves = 0 - await editor.fill('First in-flight edit') + await setEditorText('First in-flight edit') await eventually(() => activeSaves === 1, 'Save did not start') - await editor.fill('Newest edit wins') + await setEditorText('Newest edit wins') await eventually(() => pages.get('b').content === 'Newest edit wins' && activeSaves === 0, 'Newer edit did not save') assert.equal(maxConcurrentSaves, 1) delaySaves = 0 console.log('PASS: saves are serialized and newer edits win') failSaves = true - await editor.fill('Recover this failed draft') + await setEditorText('Recover this failed draft') await page.getByRole('button', { name: 'Page A', exact: true }).click() await page.getByText('Could not save page. Your draft is kept in this tab; retry saving.').first().waitFor() assert.equal(await page.getByRole('textbox', { name: 'Page title' }).inputValue(), 'Page B') @@ -278,15 +285,14 @@ try { // state. Typing must not schedule another save; only the explicit // overwrite button may replace the remote content. await page.goto(`${base}/pages?id=a`) - await page.getByRole('button', { name: 'Edit', exact: true }).click() - await editor.fill('Local draft before conflict') + await setEditorText('Local draft before conflict') await eventually(() => pages.get('a').content === 'Local draft before conflict', 'Draft did not save before the conflict') pages.get('a').content = 'Remote edit wins' pages.get('a').version++ - await editor.fill('Edit after remote change') + await setEditorText('Edit after remote change') await page.getByText('This page was changed elsewhere', { exact: true }).waitFor() const attemptsAtConflict = patchAttempts - await editor.fill('Typing must not overwrite') + await setEditorText('Typing must not overwrite') await new Promise(resolve => setTimeout(resolve, 1200)) assert.equal(patchAttempts, attemptsAtConflict, 'Typing during a conflict scheduled another save') assert.equal(pages.get('a').content, 'Remote edit wins', 'Conflict silently overwrote the remote content') @@ -300,8 +306,7 @@ try { // rebasing the stale draft onto the newer version. failSaves = true await page.goto(`${base}/pages?id=b`) - await page.getByRole('button', { name: 'Edit', exact: true }).click() - await editor.fill('Draft with an older base') + await setEditorText('Draft with an older base') await page.getByText('Could not save page. Your draft is kept in this tab; retry saving.').first().waitFor() pages.get('b').content = 'Remote saved while draft failed' pages.get('b').version++ @@ -345,10 +350,9 @@ try { delaySaves = 900 failContent = 'Envelope part two' await page.goto(`${base}/pages?id=b`) - await page.getByRole('button', { name: 'Edit', exact: true }).click() - await editor.fill('Envelope part one') + await setEditorText('Envelope part one') await eventually(() => activeSaves === 1, 'First envelope save did not start') - await editor.fill('Envelope part two') + await setEditorText('Envelope part two') await page.getByText('Could not save page. Your draft is kept in this tab; retry saving.').first().waitFor() assert.equal(pages.get('b').content, 'Envelope part one', 'First save of the loop did not land') await page.reload() @@ -366,14 +370,13 @@ try { // acknowledges the draft's base. Adopting it would let a stale draft // overwrite newer remote content without any conflict. await page.goto(`${base}/pages?id=a`) - await page.getByRole('button', { name: 'Edit', exact: true }).click() - await editor.fill('Metadata rebase draft') + await setEditorText('Metadata rebase draft') await eventually(() => pages.get('a').content === 'Metadata rebase draft', 'Draft did not save before the metadata mutation') pages.get('a').content = 'Remote content stays' pages.get('a').version++ await page.locator('button[title="Pin to sidebar"]').click() await eventually(() => pages.get('a').pinned === true, 'Pin metadata patch did not land') - await editor.fill('Stale draft after metadata patch') + await setEditorText('Stale draft after metadata patch') await page.getByText('This page was changed elsewhere', { exact: true }).waitFor() assert.equal(pages.get('a').content, 'Remote content stays', 'Metadata response rebased the stale draft over the remote content') await page.getByRole('button', { name: 'Discard my draft and load latest', exact: true }).click() diff --git a/web/app/(app)/pages/client.tsx b/web/app/(app)/pages/client.tsx index b052b77..a7d0b7c 100644 --- a/web/app/(app)/pages/client.tsx +++ b/web/app/(app)/pages/client.tsx @@ -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; 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 ( -
-
- - {embed.collection.name} - {viewLabel && · {viewLabel}} - {items ? `${items.length} item${items.length === 1 ? '' : 's'}` : ''} -
- {failed ? ( -

This collection could not be loaded.

- ) : items === null ? ( -

Loading collection…

- ) : items.length === 0 ? ( -

No items match this view.

- ) : ( -
- - - - - {properties.map((p) => )} - - - - {items.map((item) => ( - - - {properties.map((p) => )} - - ))} - -
Bookmark{p.name}
- - {item.bookmark.title || item.bookmark.ogTitle || item.bookmark.url} - - {host(item.bookmark.url)} - {optionLabel(p, item.propertyValues?.[p.id])}
-
- )} -
- ) -} - -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

. 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([]) const [activeId, setActiveId] = useState(initialId) const [page, setPage] = useState(null) - const [mode, setMode] = useState<'edit' | 'preview'>('preview') const [title, setTitle] = useState('') const [content, setContent] = useState('') const [saveStates, setSaveStates] = useState>({}) @@ -198,10 +54,7 @@ export function PagesClient({ initialId }: { initialId: string | null }) { const [revisions, setRevisions] = useState([]) const [revision, setRevision] = useState(null) const [historyBusy, setHistoryBusy] = useState(null) - const [slash, setSlash] = useState<{ query: string; start: number } | null>(null) - const [slashIndex, setSlashIndex] = useState(0) - const textareaRef = useRef(null) - const pendingCaret = useRef(null) + const editorRef = useRef(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) => { - 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 }) { 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" /> {saveState === 'saving' ? 'Saving…' : saveState === 'dirty' ? 'Unsaved' : saveState === 'conflict' ? 'Conflict' : 'Saved'} {saveState === 'dirty' && } - @@ -717,111 +498,14 @@ export function PagesClient({ initialId }: { initialId: string | null }) { )} - {mode === 'edit' ? ( -

- -