Keep incomplete structured drafts editable and add block ordering
Validate / validate (push) Successful in 3m37s
Validate / validate (push) Successful in 3m37s
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import type { GetServerSideProps } from 'next';
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import Layout from '../../../components/Layout';
|
||||
import Blocks from '../../../components/Blocks';
|
||||
@@ -8,30 +8,125 @@ import { getBlocks, seedPage } from '../../../lib/block-store';
|
||||
import { defaultBlocks } from '../../../lib/content-defaults';
|
||||
import { resolveBlocks } from '../../../lib/block-resolve';
|
||||
import type { Block, PageBlock } from '../../../lib/blocks';
|
||||
|
||||
export const getServerSideProps: GetServerSideProps = async ({ params }) => {
|
||||
const node = findNode(String(params?.node)); if (!node || node.id === 'root') return {notFound:true};
|
||||
const page = `content/${node.id}`; let blocks = await getBlocks(page);
|
||||
if (!blocks.length) { await seedPage(page, defaultBlocks(node)); blocks = await getBlocks(page); }
|
||||
return {props:{node:node.id,title:node.title,blocks:await resolveBlocks(blocks)}};
|
||||
const node = findNode(String(params?.node));
|
||||
if (!node || node.id === 'root') return { notFound: true };
|
||||
const page = `content/${node.id}`;
|
||||
let blocks = await getBlocks(page);
|
||||
if (!blocks.length) { await seedPage(page, defaultBlocks(node)); blocks = await getBlocks(page); }
|
||||
return { props: { node: node.id, title: node.title, blocks: await resolveBlocks(blocks) } };
|
||||
};
|
||||
export default function Workspace({node,title,blocks}:{node:string;title:string;blocks:PageBlock[]}) {
|
||||
const [raw,setRaw] = useState(false);
|
||||
const [preview,setPreview] = useState(blocks);
|
||||
const [text,setText] = useState(JSON.stringify(blocks.map(b=>b.block),null,2)); const [message,setMessage] = useState(''); const [busy,setBusy] = useState(false);
|
||||
function editBlock(index: number, value: string, structured: boolean) {
|
||||
try { const next: Block[] = JSON.parse(text); if (structured) next[index] = JSON.parse(value); else next[index] = {...next[index], data:{...next[index].data,text:value}} as Block; setText(JSON.stringify(next,null,2)); setMessage(''); }
|
||||
catch { setMessage('Switch to JSON mode to edit an incomplete JSON block.'); }
|
||||
}
|
||||
function addParagraph() { try { const next = JSON.parse(text); next.push({type:'markdown',data:{text:'Write a research note here.'}}); setText(JSON.stringify(next,null,2)); } catch {setMessage('Fix JSON before adding a block.');} }
|
||||
function removeBlock(index:number) {const next=JSON.parse(text);next.splice(index,1);setText(JSON.stringify(next,null,2));}
|
||||
let editable: Block[] = []; try { const value = JSON.parse(text); if(Array.isArray(value)) editable = value; } catch {}
|
||||
async function refreshPreview() { setBusy(true); setMessage(''); try {
|
||||
const response=await fetch('/api/editor/preview',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({blocks:JSON.parse(text)})});
|
||||
const result=await response.json(); if(!response.ok) throw new Error(result.error); setPreview(result.blocks);
|
||||
} catch(e) {setMessage((e as Error).message);} finally {setBusy(false);} }
|
||||
async function publish() { setBusy(true); setMessage(''); try {
|
||||
const response=await fetch(`/api/blocks?page=${encodeURIComponent(`content/${node}`)}`,{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({blocks:JSON.parse(text)})});
|
||||
const result=await response.json(); if(!response.ok) throw new Error(result.error); window.location.reload();
|
||||
} catch(e) {setMessage((e as Error).message);} finally {setBusy(false);} }
|
||||
return <Layout title={`Edit ${title}`}><Link href="/editor">← Editorial desk</Link><h1>{title}</h1><p>Write and arrange your research notes, then preview your draft. Unsaved changes are lost when you leave. Publishing updates the public study immediately.</p><div className="editor-split"><section><button onClick={()=>setRaw(!raw)}>{raw?'Writing mode':'JSON mode'}</button> <button onClick={addParagraph}>Add paragraph</button>{raw ? <><label htmlFor="blocks">Content blocks (JSON)</label><textarea id="blocks" value={text} onChange={e=>setText(e.target.value)} spellCheck={false}/></> : editable.map((block,i)=><div className="editor-block" key={i}><label htmlFor={`block-${i}`}>Block {i+1} · {block.type}</label><textarea id={`block-${i}`} value={'text' in (block.data || {}) ? String((block.data as {text:string}).text) : JSON.stringify(block,null,2)} onChange={e=>editBlock(i,e.target.value,!('text' in (block.data || {})))}/><button onClick={()=>removeBlock(i)}>Remove block</button></div>)}<button disabled={busy} onClick={refreshPreview}>Preview draft</button> <button disabled={busy} onClick={publish}>{busy?'Publishing…':'Publish changes'}</button><p role="alert">{message}</p></section><section><p>Preview · <Link target="_blank" href={`/contents/${node}`}>Open public page ↗</Link></p><Blocks blocks={preview}/></section></div></Layout>;
|
||||
|
||||
const serialize = (value: unknown) => JSON.stringify(value, null, 2);
|
||||
function parseBlock(source: string): Block | null {
|
||||
try {
|
||||
const value = JSON.parse(source);
|
||||
return value && typeof value.type === 'string' && value.data && typeof value.data === 'object' ? value : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
export default function Workspace({ node, title, blocks }: { node: string; title: string; blocks: PageBlock[] }) {
|
||||
// Keep each block as source text so incomplete structured edits remain editable.
|
||||
const [drafts, setDrafts] = useState(() => blocks.map(b => serialize(b.block)));
|
||||
const [rawSource, setRawSource] = useState<string | null>(null);
|
||||
const [preview, setPreview] = useState(blocks);
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const published = useRef(false);
|
||||
const initial = serialize(blocks.map(b => b.block));
|
||||
const dirty = rawSource !== null ? rawSource !== initial : serialize(drafts.map(source => {
|
||||
try { return JSON.parse(source); } catch { return source; }
|
||||
})) !== initial;
|
||||
|
||||
useEffect(() => {
|
||||
if (!dirty) return;
|
||||
const warn = (event: BeforeUnloadEvent) => { if (published.current) return; event.preventDefault(); event.returnValue = ''; };
|
||||
window.addEventListener('beforeunload', warn);
|
||||
// A normal browser navigation receives the same unsaved-draft warning.
|
||||
return () => window.removeEventListener('beforeunload', warn);
|
||||
}, [dirty]);
|
||||
|
||||
function draftBlocks(): Block[] {
|
||||
const value = rawSource !== null ? JSON.parse(rawSource) : drafts.map(source => JSON.parse(source));
|
||||
if (!Array.isArray(value) || !value.length) throw new Error('A study needs at least one content block.');
|
||||
if (value.some(block => !block || typeof block.type !== 'string' || !block.data || typeof block.data !== 'object')) {
|
||||
throw new Error('Each block needs a type and a data object.');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function switchMode() {
|
||||
try {
|
||||
const value = draftBlocks();
|
||||
if (rawSource === null) setRawSource(serialize(value));
|
||||
else { setDrafts(value.map(serialize)); setRawSource(null); }
|
||||
setMessage('');
|
||||
} catch (error) { setMessage((error as Error).message); }
|
||||
}
|
||||
function update(index: number, value: string) {
|
||||
setDrafts(current => current.map((source, i) => i === index ? value : source));
|
||||
}
|
||||
function move(index: number, offset: number) {
|
||||
setDrafts(current => {
|
||||
const next = [...current];
|
||||
[next[index], next[index + offset]] = [next[index + offset], next[index]];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
async function request(previewOnly: boolean) {
|
||||
setBusy(true); setMessage('');
|
||||
try {
|
||||
const value = draftBlocks();
|
||||
const response = await fetch(previewOnly ? '/api/editor/preview' : `/api/blocks?page=${encodeURIComponent(`content/${node}`)}`, {
|
||||
method: previewOnly ? 'POST' : 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ blocks: value }),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.error);
|
||||
if (previewOnly) { setPreview(result.blocks); setMessage('Draft preview updated. Nothing has been published.'); }
|
||||
else { published.current = true; window.location.reload(); }
|
||||
} catch (error) { setMessage((error as Error).message); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
|
||||
return <Layout title={`Edit ${title}`}>
|
||||
<Link href="/editor">← Editorial desk</Link>
|
||||
<h1>{title}</h1>
|
||||
<p>Write and arrange your research notes, then preview your draft. Unsaved changes are lost when you leave. Publishing updates the public study immediately.</p>
|
||||
<div className="editor-split">
|
||||
<section aria-label="Write content">
|
||||
<div className="editor-toolbar">
|
||||
<button disabled={busy} onClick={switchMode}>{rawSource !== null ? 'Writing mode' : 'JSON mode'}</button>
|
||||
{rawSource === null && <button disabled={busy} onClick={() => setDrafts(current => [...current, serialize({ type: 'markdown', data: { text: '' } })])}>Add paragraph</button>}
|
||||
</div>
|
||||
{rawSource !== null ? <>
|
||||
<label htmlFor="blocks">Content blocks (JSON)</label>
|
||||
<textarea id="blocks" value={rawSource} onChange={event => setRawSource(event.target.value)} spellCheck={false} />
|
||||
</> : drafts.map((source, index) => {
|
||||
const block = parseBlock(source);
|
||||
const textBlock = block && ['markdown', 'callout', 'code'].includes(block.type) && 'text' in block.data;
|
||||
return <div className="editor-block" key={index}>
|
||||
<label htmlFor={`block-${index}`}>Block {index + 1} · {block?.type || 'Structured content'}</label>
|
||||
<textarea id={`block-${index}`} value={textBlock ? String((block!.data as { text: string }).text) : source}
|
||||
spellCheck={!!textBlock} onChange={event => update(index, textBlock ? serialize({ ...block, data: { ...block!.data, text: event.target.value } }) : event.target.value)} />
|
||||
<div className="editor-toolbar">
|
||||
<button disabled={busy || index === 0} aria-label={`Move block ${index + 1} up`} onClick={() => move(index, -1)}>↑</button>
|
||||
<button disabled={busy || index === drafts.length - 1} aria-label={`Move block ${index + 1} down`} onClick={() => move(index, 1)}>↓</button>
|
||||
<button disabled={busy || drafts.length === 1} onClick={() => setDrafts(current => current.filter((_, i) => i !== index))}>Remove block</button>
|
||||
</div>
|
||||
</div>;
|
||||
})}
|
||||
<div className="editor-toolbar">
|
||||
<button disabled={busy} onClick={() => request(true)}>Preview draft</button>
|
||||
<button disabled={busy} onClick={() => request(false)}>{busy ? 'Working…' : 'Publish changes'}</button>
|
||||
</div>
|
||||
<p role="status" aria-live="polite">{message}</p>
|
||||
</section>
|
||||
<section aria-label="Preview content">
|
||||
<p>Preview · <Link target="_blank" href={`/contents/${node}`}>Open public page ↗</Link></p>
|
||||
<Blocks blocks={preview} />
|
||||
</section>
|
||||
</div>
|
||||
</Layout>;
|
||||
}
|
||||
|
||||
@@ -237,3 +237,4 @@ a:focus-visible,button:focus-visible,input:focus-visible,textarea:focus-visible{
|
||||
.journal-footer .brand span{max-width:180px}
|
||||
}
|
||||
.editor-block{padding:16px 0;border-bottom:1px solid var(--line);margin-bottom:16px}.editor-block textarea{height:180px;font:14px/1.7 system-ui}.editor-block label{font-size:12px;color:var(--muted)}
|
||||
.editor-toolbar{display:flex;flex-wrap:wrap;gap:8px;margin:12px 0}
|
||||
|
||||
Reference in New Issue
Block a user