From 6482c993e883617e9fa4978c2b64c86edd1305e5 Mon Sep 17 00:00:00 2001 From: "dong.nguyen" Date: Thu, 22 Oct 2026 09:55:24 +0700 Subject: [PATCH] feat(edit): live edit mode with draft store, inline editing, JSON panel, save bar, branch targeting ?edit entry with Basic-auth probe; DraftStore copy-on-write over live branch documents (?ref GET / branch PUT, last_commit_sha optimistic concurrency, three-way rebase on 412); EditableText inline editors; JsonPanel with templates and orphan-free delete; EditBar sequential-PUT save with conflict actions and merge hint on non-master branches. scripts/smoke-draft.ts regression check. --- scripts/smoke-draft.ts | 84 +++ src/App.css | 351 ++++++++++++ src/App.tsx | 52 +- src/components/layout/EditBar.tsx | 208 +++++++ src/components/layout/EditModeShell.tsx | 343 ++++++++++++ src/components/layout/JsonPanel.tsx | 291 ++++++++++ src/components/sections/About.tsx | 19 +- src/components/sections/Experience.tsx | 16 +- src/components/sections/Expertise.tsx | 5 +- src/components/sections/Hero.tsx | 20 +- src/components/sections/Projects.tsx | 9 +- src/components/ui/EditableText.tsx | 108 ++++ src/hooks/useEdit.ts | 17 + src/i18n/draft.ts | 705 ++++++++++++++++++++++++ src/i18n/edit-mode.ts | 104 ++++ src/i18n/index.ts | 27 +- src/i18n/locales/en/ui.json | 61 ++ src/i18n/locales/vi/ui.json | 61 ++ src/i18n/validate.ts | 23 + src/pages/AboutPage.tsx | 23 +- src/pages/ExperiencePage.tsx | 16 +- src/pages/ProjectDetailPage.tsx | 21 +- src/pages/ProjectsListPage.tsx | 9 +- tsconfig.app.json | 2 +- 24 files changed, 2523 insertions(+), 52 deletions(-) create mode 100644 scripts/smoke-draft.ts create mode 100644 src/components/layout/EditBar.tsx create mode 100644 src/components/layout/EditModeShell.tsx create mode 100644 src/components/layout/JsonPanel.tsx create mode 100644 src/components/ui/EditableText.tsx create mode 100644 src/hooks/useEdit.ts create mode 100644 src/i18n/draft.ts create mode 100644 src/i18n/edit-mode.ts diff --git a/scripts/smoke-draft.ts b/scripts/smoke-draft.ts new file mode 100644 index 0000000..00ae9ea --- /dev/null +++ b/scripts/smoke-draft.ts @@ -0,0 +1,84 @@ +// Throwaway smoke test for the draft store (spec-v4 §5.1, §5.5, §5.6). +// Run: pnpm tsx scripts/smoke-draft.ts +import { DraftStore, bundledBase } from '../src/i18n/draft'; + +const fail = (msg: string): never => { + console.error(`FAIL: ${msg}`); + process.exit(1); +}; + +const bases = bundledBase(); +const store = new DraftStore(structuredClone(bases)); + +const projects = store.dataOf('projects') as { id: string }[]; +const firstProject = projects[0].id; + +// 1. setValue on a text path is accepted and tracked. +const rejected = store.setValue('vi', `projects.${firstProject}.summary`, 'SUMMARY CHANGED'); +if (rejected !== null) fail(`valid edit rejected: ${JSON.stringify(rejected)}`); +if (!store.isDirty()) fail('store not dirty after accepted edit'); +const paths = store.changedPaths('content.vi'); +if (!paths.includes(`projects.${firstProject}.summary`)) fail(`path not diffed: ${paths}`); + +// 2. Empty required value is rejected and leaves the draft untouched. +const before = structuredClone(store.dataOf('content.vi')); +const empty = store.setValue('vi', 'profile.bio', ' '); +if (empty === null) fail('empty required value accepted'); +if (JSON.stringify(store.dataOf('content.vi')) !== JSON.stringify(before)) fail('rejected edit mutated draft'); + +// 3. Delete removes the structure record AND both text entries — no orphan. +const del = store.deleteRecord('project', { id: firstProject }); +if (del !== null) fail(`delete rejected: ${JSON.stringify(del)}`); +const stillListed = (store.dataOf('projects') as { id: string }[]).some((p) => p.id === firstProject); +if (stillListed) fail('project still in structure after delete'); +const vi = store.dataOf('content.vi') as Record>; +const en = store.dataOf('content.en') as Record>; +if (vi.projects[firstProject]) fail('vi text orphan after delete'); +if (en.projects[firstProject]) fail('en text orphan after delete'); +const issues = store.validate(); +if (issues.length > 0) fail(`validate after delete: ${JSON.stringify(issues)}`); + +// 4. addRecord creates a complete record in every document at once. +const add = store.addRecord('project'); +if (add !== null) fail(`add rejected: ${JSON.stringify(add)}`); +const baseIds = new Set((bases.projects.data as { id: string }[]).map((p) => p.id)); +const newIds = (store.dataOf('projects') as { id: string }[]).map((p) => p.id).filter((id) => !baseIds.has(id)); +if (newIds.length !== 1) fail(`expected exactly one new project, got ${newIds}`); +const issuesAfterAdd = store.validate(); +if (issuesAfterAdd.length > 0) fail(`validate after add: ${JSON.stringify(issuesAfterAdd)}`); + +// 5. snapshot / applySaved round-trip reproduces the same changed paths. +const snapshot = store.snapshot(); +const restored = new DraftStore(structuredClone(bases)); +const drifted = restored.applySaved(snapshot); +if (drifted.length > 0) fail(`clean rebase reported drift: ${drifted}`); +const same = + JSON.stringify(restored.changedDocs()) === JSON.stringify(store.changedDocs()); +if (!same) fail('restored draft differs from saved snapshot'); + +// 6. Conflict: base changed at a path the draft also touched → rebase reports +// a conflict; take-theirs (discardDocument) clears it. +const store2 = new DraftStore(structuredClone(bases)); +store2.setValue('vi', `projects.${firstProject}.summary`, 'MINE'); +const driftedBase = structuredClone(bases); +(driftedBase['content.vi'].data as Record>).projects[firstProject].summary = 'THEIRS'; +store2.resetBase('content.vi', driftedBase['content.vi']); +const rebaseIssues = store2.rebase('content.vi'); +if (rebaseIssues === null) fail('rebase silently took one side on a real conflict'); +store2.discardDocument('content.vi'); +if (store2.isPathDirty(`projects.${firstProject}.summary`)) fail('take-theirs left draft residue'); + +// 7. Clean rebase: base changed at a DIFFERENT path → draft edit survives. +const store3 = new DraftStore(structuredClone(bases)); +store3.setValue('vi', `projects.${firstProject}.summary`, 'MINE'); +const otherBase = structuredClone(bases); +const otherId = projects[1].id; +(otherBase['content.vi'].data as Record>).projects[otherId].summary = 'THEIRS'; +store3.resetBase('content.vi', otherBase['content.vi']); +const clean = store3.rebase('content.vi'); +if (clean !== null) fail(`clean rebase rejected: ${JSON.stringify(clean)}`); +const merged = (store3.dataOf('content.vi') as Record>).projects; +if (merged[firstProject].summary !== 'MINE') fail('rebase lost the draft edit'); +if (merged[otherId].summary !== 'THEIRS') fail('rebase lost the base edit'); + +console.log('draft store smoke: all 7 checks passed'); diff --git a/src/App.css b/src/App.css index ba3be6d..6382b6e 100644 --- a/src/App.css +++ b/src/App.css @@ -2086,3 +2086,354 @@ .back-to-top:hover { background: var(--accent-hover); } + +/* ── Edit mode (spec-v4 §5.5, §5.4) ───────────────────────────────────── + The Save bar and the JSON panel are chrome, not page content: they sit + fixed over the site, use the 13px chrome type step, and never participate + in the prose scale. The site underneath is untouched. ────────────────── */ + +.edit-bar { + position: fixed; + left: 0; + right: 0; + bottom: 0; + z-index: 900; + background: var(--bg-elevated); + border-top: 1px solid var(--border-strong); + padding: 10px 16px calc(10px + env(safe-area-inset-bottom, 0px)); + font-size: 13px; + line-height: 1.5; + max-height: 45vh; + overflow-y: auto; +} + +.edit-bar-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px; +} + +.edit-bar-title { + color: var(--accent); +} + +.edit-bar-count { + color: var(--text-secondary); +} + +.edit-bar-branch { + color: var(--text-secondary); + font-size: 13px; +} + +.edit-bar-branch code { + color: var(--accent); +} + +.edit-bar-warn { + color: var(--warning); +} + +.edit-bar-actions { + margin-left: auto; + display: flex; + gap: 8px; + flex-wrap: wrap; +} + +.edit-btn { + background: transparent; + color: var(--text-primary); + border: 1px solid var(--border-strong); + border-radius: 6px; + padding: 6px 12px; + font: inherit; + font-size: 13px; + cursor: pointer; + transition: border-color var(--transition-fast), background var(--transition-fast); +} + +.edit-btn:hover:not(:disabled) { + border-color: var(--accent); + color: var(--accent); +} + +.edit-btn:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.edit-btn:disabled { + opacity: 0.45; + cursor: default; +} + +.edit-btn-primary { + background: var(--accent-solid); + border-color: var(--accent-solid); + color: var(--text-on-accent-solid); +} + +.edit-btn-primary:hover:not(:disabled) { + background: var(--accent-solid-hover); + border-color: var(--accent-solid-hover); + color: var(--text-on-accent-solid); +} + +.edit-bar-diff { + margin-top: 10px; + display: grid; + gap: 10px; +} + +.edit-bar-doc { + border: 1px solid var(--border); + border-radius: 8px; + padding: 8px 10px; +} + +.edit-bar-doc-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-bottom: 6px; +} + +.edit-bar-doc ul { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 4px; +} + +.edit-bar-doc li { + display: flex; + align-items: baseline; + gap: 8px; + flex-wrap: wrap; +} + +.edit-bar-path { + color: var(--accent); + font-size: 12px; +} + +.edit-bar-value { + color: var(--text-secondary); + max-width: 34ch; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.edit-bar-conflicts { + margin-top: 10px; + display: grid; + gap: 6px; + color: var(--warning); +} + +.edit-bar-conflict { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + +.edit-bar-issues, +.edit-bar-save { + margin: 10px 0 0; + padding: 0; + list-style: none; + display: grid; + gap: 3px; +} + +.edit-bar-issues { + color: var(--error); +} + +.edit-bar-save code { + color: var(--text-secondary); +} + +.edit-bar-note { + margin-top: 8px; + color: var(--success); +} + +.json-panel { + position: fixed; + top: 0; + right: 0; + bottom: 0; + z-index: 950; + width: min(620px, 100%); + background: var(--bg-elevated); + border-left: 1px solid var(--border-strong); + padding: 14px 16px; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 10px; + font-size: 13px; +} + +.json-panel-head { + display: flex; + align-items: center; + justify-content: space-between; +} + +.json-panel-tabs { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.json-panel-tab { + background: transparent; + border: 1px solid var(--border); + border-radius: 6px; + padding: 4px 8px; + color: var(--text-secondary); + font: inherit; + font-size: 12px; + cursor: pointer; +} + +.json-panel-tab.is-active { + border-color: var(--accent); + color: var(--accent); +} + +.json-panel-conflict-flag { + color: var(--warning); +} + +.json-panel-shape { + margin: 0; + padding: 8px 10px; + background: var(--bg-surface); + border: 1px solid var(--border); + border-radius: 8px; + color: var(--text-muted); + font-size: 12px; + white-space: pre-wrap; +} + +.json-panel-tools, +.json-panel-records { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.json-panel-record { + display: inline-flex; + align-items: center; + gap: 6px; + border: 1px solid var(--border); + border-radius: 6px; + padding: 3px 8px; + color: var(--text-secondary); +} + +.json-panel-readonly { + color: var(--text-muted); +} + +.json-panel-section-add select { + background: var(--bg-surface); + color: var(--text-primary); + border: 1px solid var(--border-strong); + border-radius: 6px; + padding: 4px 6px; + font: inherit; + font-size: 12px; +} + +.json-panel-merge { + display: grid; + gap: 6px; + border: 1px solid var(--warning); + border-radius: 8px; + padding: 8px 10px; +} + +.json-panel-merge textarea { + min-height: 140px; +} + +.json-panel-editor { + flex: 1; + min-height: 300px; + background: var(--bg-surface); + color: var(--text-primary); + border: 1px solid var(--border-strong); + border-radius: 8px; + padding: 10px; + font-family: ui-monospace, 'Cascadia Mono', 'Consolas', monospace; + font-size: 12.5px; + line-height: 1.5; + resize: vertical; +} + +.json-panel-editor:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 1px; +} + +.json-panel-issues { + margin: 0; + padding: 0; + list-style: none; + display: grid; + gap: 3px; + color: var(--error); +} + +.json-panel-status { + color: var(--text-muted); +} + +/* Inline editing affordances (§5.3): outline only — the element itself stays + the site's own, so the page keeps its exact rendering outside edit mode. */ +.editable-text { + outline: 1px dashed transparent; + outline-offset: 2px; + border-radius: 2px; +} + +.editable-text:hover { + outline-color: var(--border-strong); +} + +.editable-text:focus-visible { + outline-color: var(--accent); +} + +.edit-dirty { + outline-style: solid; + outline-color: var(--accent-soft); + box-shadow: inset 2px 0 0 var(--accent); +} + +.edit-invalid { + outline-color: var(--error); + background: var(--accent-tint); +} + +@media (max-width: 768px) { + .json-panel { + width: 100%; + } + + .edit-bar-actions { + margin-left: 0; + } +} diff --git a/src/App.tsx b/src/App.tsx index e71ab85..040a01d 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,6 +1,7 @@ import './App.css' import { lazy, Suspense } from 'react' -import { BrowserRouter, Routes, Route } from 'react-router' +import type { ReactNode } from 'react' +import { BrowserRouter, Routes, Route, useLocation } from 'react-router' import { ThemeProvider } from '@/hooks/useTheme' import { Layout } from '@/components/layout/Layout' import { LanguageProvider } from '@/hooks/useLanguage' @@ -14,8 +15,25 @@ const ExperiencePage = lazy(() => import('@/pages/ExperiencePage').then((m) => ( const ProjectsListPage = lazy(() => import('@/pages/ProjectsListPage').then((m) => ({ default: m.ProjectsListPage }))) const ProjectDetailPage = lazy(() => import('@/pages/ProjectDetailPage').then((m) => ({ default: m.ProjectDetailPage }))) const PhilosophyPage = lazy(() => import('@/pages/PhilosophyPage').then((m) => ({ default: m.PhilosophyPage }))) + const ContactPage = lazy(() => import('@/pages/ContactPage').then((m) => ({ default: m.ContactPage }))) +// Edit mode is lazy too: visitors never download the draft store, the panel +// or the save pipeline (spec-v4 §7 P3.4). The gate only mounts the shell when +// `?edit` is present; the shell then authenticates or strips the query again. +const EditModeShell = lazy(() => import('@/components/layout/EditModeShell')) + +function MaybeEditMode({ children }: { children: ReactNode }) { + const location = useLocation() + const editing = new URLSearchParams(location.search).has('edit') + if (!editing) return <>{children} + return ( + + {children} + + ) +} + function App() { return ( @@ -24,21 +42,23 @@ function App() { {/* I18nProvider sits below LanguageProvider: it resolves the language through useLanguage and hands every consumer the UI/CONTENT of it. */} - - {/* A null fallback keeps the shell (nav, footer) painted without reserving a - box that would shift the page when the route chunk lands. */} - - - } /> - } /> - } /> - } /> - } /> - } /> - } /> - - - + + + {/* A null fallback keeps the shell (nav, footer) painted without reserving a + box that would shift the page when the route chunk lands. */} + + + } /> + } /> + } /> + } /> + } /> + } /> + } /> + + + + diff --git a/src/components/layout/EditBar.tsx b/src/components/layout/EditBar.tsx new file mode 100644 index 0000000..084c4b5 --- /dev/null +++ b/src/components/layout/EditBar.tsx @@ -0,0 +1,208 @@ +// EditBar (spec-v4 §5.5): the fixed status bar of edit mode. It lists every +// changed path grouped by document with before → after and a per-path revert, +// reports save progress (written / conflict / failed), partial-save resume, +// conflict resolution (rebase / take-theirs / hand-merge), validation issues, +// and guards Exit with a confirm when changes are unsaved. +import { useState } from 'react'; +import { useI18n } from '@/i18n/provider'; +import { DRAFT_DOCS } from '@/i18n/draft'; +import { DEFAULT_BRANCH } from '@/i18n/edit-mode'; +import type { DocSaveResult, DraftDocId } from '@/i18n/draft'; +import type { ContentIssue } from '@/i18n/validate'; + +type ChangedDoc = { id: DraftDocId; paths: { path: string; before: unknown; after: unknown }[] }; + +type EditBarProps = { + offline: boolean; + dirty: boolean; + changedDocs: ChangedDoc[]; + conflicts: DraftDocId[]; + issues: ContentIssue[]; + saving: boolean; + saveStopped: boolean; + saveResults: DocSaveResult[]; + unionNote: 'ok' | 'failed' | null; + draftRestored: boolean; + branch: string; + onOpenPanel: () => void; + onSave: () => void; + onExit: () => void; + onRebase: (id: DraftDocId) => void; + onTakeTheirs: (id: DraftDocId) => void; + onHandMerge: (id: DraftDocId) => void; + onDiscardDoc: (id: DraftDocId) => void; + onRevertPath: (path: string) => void; +}; + +function fileOf(id: DraftDocId): string { + return DRAFT_DOCS.find((d) => d.id === id)!.file; +} + +// Diff values are shown truncated; the full value lives in the JSON panel. +function truncate(value: unknown): string { + const text = typeof value === 'string' ? value : JSON.stringify(value) ?? ''; + return text.length > 80 ? `${text.slice(0, 80)}…` : text; +} + +export function EditBar({ + offline, + dirty, + changedDocs, + conflicts, + issues, + saving, + saveStopped, + saveResults, + unionNote, + draftRestored, + branch, + onOpenPanel, + onSave, + onExit, + onRebase, + onTakeTheirs, + onHandMerge, + onDiscardDoc, + onRevertPath, +}: EditBarProps) { + const { ui } = useI18n(); + const s = ui.edit; + const [showDiff, setShowDiff] = useState(false); + + const allWritten = + saveResults.length > 0 && !saveStopped && saveResults.every((r) => r.status === 'written'); + const statusLabel = (result: DocSaveResult) => + result.status === 'written' + ? s.written + : result.status === 'conflict' + ? s.conflictStatus + : `${s.failed} (${result.http ?? 0})`; + + return ( +
+
+ {s.title} + + {dirty ? `${changedDocs.reduce((n, d) => n + d.paths.length, 0)} ${s.changes}` : s.noChanges} + + + {s.branchLabel} {branch} + + {offline && {s.offline}} + {draftRestored && !dirty && {s.draftRestored}} +
+ + + + {saveStopped && ( + + )} + +
+
+ + {showDiff && changedDocs.length > 0 && ( +
+ {changedDocs.map((doc) => ( +
+
+ {fileOf(doc.id)} + +
+
    + {doc.paths.map((p) => ( +
  • + {p.path} + {truncate(p.before)} + + {truncate(p.after)} + +
  • + ))} +
+
+ ))} +
+ )} + + {conflicts.length > 0 && ( +
+ {s.conflicts} + {conflicts.map((id) => ( + + {fileOf(id)} {s.conflictDetail}{' '} + + + + + ))} +
+ )} + + {issues.length > 0 && ( +
    + {issues.map((issue) => ( +
  • + {issue.path}: {issue.message} +
  • + ))} +
+ )} + + {saveResults.length > 0 && ( +
    + {saveResults.map((r) => ( +
  • + {fileOf(r.id)}: {statusLabel(r)} +
  • + ))} +
+ )} + + {unionNote && ( +

{unionNote === 'ok' ? s.unionNote : s.unionFailed}

+ )} + {allWritten && !dirty && ( +

+ {branch === DEFAULT_BRANCH ? s.deployQueued : s.mergeHint} +

+ )} +
+ ); +} diff --git a/src/components/layout/EditModeShell.tsx b/src/components/layout/EditModeShell.tsx new file mode 100644 index 0000000..2b2e74d --- /dev/null +++ b/src/components/layout/EditModeShell.tsx @@ -0,0 +1,343 @@ +// EditModeShell (spec-v4 §5.1, §5.2): the lazy edit-mode wrapper around the +// real site. It authenticates through the protected proxy, fetches the live +// master documents, holds the draft, and re-wraps the tree in an +// I18nProvider override — the seven routes ARE the preview. Visitors never +// mount this component; its code is never in the entry chunk (§7 P3.4). +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import type { ReactNode } from 'react'; +import { useLocation, useNavigate } from 'react-router'; +import { useLanguage } from '@/hooks/useLanguage'; +import { I18nProvider } from '@/i18n/provider'; +import { UI, resolveContent } from '@/i18n'; +import type { ResolvedContent } from '@/i18n'; +import { + DRAFT_DOCS, + DraftStore, + TYPES_FILE, + bundledBase, + fetchDoc, + fetchTextFile, + saveDraft, + saveIdUnions, +} from '@/i18n/draft'; +import type { DocBase, DocSaveResult, DraftDocId } from '@/i18n/draft'; +import { + DEFAULT_BRANCH, + DRAFT_STORAGE, + clearDraftStorage, + ensureEditorAuth, + getEditBranch, + requestedBranch, + setEditBranch, + setEditFlag, +} from '@/i18n/edit-mode'; +import { EditContext } from '@/hooks/useEdit'; +import type { EditApi } from '@/hooks/useEdit'; +import type { ContentIssue } from '@/i18n/validate'; +import { EditBar } from './EditBar'; +import { JsonPanel, type PanelTab } from './JsonPanel'; + +type Phase = 'authenticating' | 'loading' | 'ready' | 'offline'; + +export default function EditModeShell({ children }: { children: ReactNode }) { + const navigate = useNavigate(); + const location = useLocation(); + const { lang } = useLanguage(); + + // The store object itself is stable once created; `store` state exists so + // render reads it legally, and `revision` is the invalidation counter that + // re-derives everything the draft feeds to the UI. + const [store, setStore] = useState(null); + const typesRef = useRef<{ source: string; sha: string } | null>(null); + const [phase, setPhase] = useState('authenticating'); + const [branch, setBranch] = useState(DEFAULT_BRANCH); + const [resolved, setResolved] = useState | null>(null); + const [revision, setRevision] = useState(0); + const [dirty, setDirty] = useState(false); + const [issues, setIssues] = useState([]); + const [conflicts, setConflicts] = useState([]); + const [draftRestored, setDraftRestored] = useState(false); + const [saveResults, setSaveResults] = useState([]); + const [saving, setSaving] = useState(false); + const [saveStopped, setSaveStopped] = useState(false); + const [unionNote, setUnionNote] = useState<'ok' | 'failed' | null>(null); + const [panelOpen, setPanelOpen] = useState(false); + const [panelTab, setPanelTab] = useState('profile'); + + const stripEditQuery = useCallback(() => { + const params = new URLSearchParams(location.search); + params.delete('edit'); + const query = params.toString(); + navigate(`${location.pathname}${query ? `?${query}` : ''}${location.hash}`, { replace: true }); + }, [navigate, location.pathname, location.search, location.hash]); + + // Every accepted edit re-derives the resolved content from the draft + // documents (same join, same fallback rules as the bundled loader) and + // copies the draft to sessionStorage — an accidental reload restores it + // (§5.2). + const refresh = useCallback((active: DraftStore) => { + const texts = active.draftTexts(); + setResolved(resolveContent(active.draftStructures(), texts.vi, texts.en)); + setRevision((r) => r + 1); + const isDirty = active.isDirty(); + setDirty(isDirty); + if (isDirty) sessionStorage.setItem(DRAFT_STORAGE, JSON.stringify(active.snapshot())); + else clearDraftStorage(); + }, []); + + useEffect(() => { + let cancelled = false; + const init = async () => { + // `?edit=` targets that branch; a bare `?edit` resumes the + // session's branch or the default. An illegal name exits edit mode the + // same way a failed auth does. + const requested = requestedBranch(location.search); + if (requested === null) { + setEditFlag(false); + clearDraftStorage(); + stripEditQuery(); + return; + } + const branch = requested ?? getEditBranch(); + setBranch(branch); + const authed = await ensureEditorAuth(branch); + if (cancelled) return; + if (!authed) { + // 401 or a cancelled prompt → normal visitor site, zero affordances. + setEditFlag(false); + clearDraftStorage(); + stripEditQuery(); + return; + } + setEditFlag(true); + setEditBranch(branch); + setPhase('loading'); + + // Draft initialization is the live repository files, never the bundle + // (§5.1); the bundle is only the offline fallback, flagged stale. + let offline = false; + let bases: Record | null = null; + try { + bases = {} as Record; + for (const meta of DRAFT_DOCS) bases[meta.id] = await fetchDoc(meta.file, branch); + } catch { + offline = true; + } + if (!bases) bases = bundledBase(); + + const created = new DraftStore(bases); + + const stored = sessionStorage.getItem(DRAFT_STORAGE); + if (stored) { + try { + const drifted = created.applySaved(JSON.parse(stored)); + if (drifted.length > 0) setConflicts(drifted); + setDraftRestored(true); + } catch { + clearDraftStorage(); + } + } + + try { + const file = await fetchTextFile(TYPES_FILE, branch); + typesRef.current = { source: file.text, sha: file.sha }; + } catch { + typesRef.current = null; + } + + if (cancelled) return; + setStore(created); + setPhase(offline ? 'offline' : 'ready'); + refresh(created); + }; + void init(); + return () => { + cancelled = true; + }; + }, [refresh, stripEditQuery, location.search]); + + // Mid-edit navigation guard (§5.2). + useEffect(() => { + if (!dirty) return; + const warn = (event: BeforeUnloadEvent) => { + event.preventDefault(); + event.returnValue = ''; + }; + window.addEventListener('beforeunload', warn); + return () => window.removeEventListener('beforeunload', warn); + }, [dirty]); + + const editApi = useMemo( + () => + store && (phase === 'ready' || phase === 'offline') + ? { + commit: (path, value) => { + const rejected = store.setValue(lang, path, value); + setIssues(rejected ?? []); + if (!rejected) refresh(store); + return rejected; + }, + revert: (path) => { + const rejected = store.revertPath(path); + setIssues(rejected ?? []); + if (!rejected) refresh(store); + return rejected; + }, + isPathDirty: (path) => store.isPathDirty(path), + } + : null, + [store, phase, lang, refresh], + ); + + const runSave = useCallback(async () => { + if (!store || phase === 'offline') return; + // The full-draft validator runs before any PUT (§5.6); an invalid draft + // never reaches the repository. + const invalid = store.validate(); + if (invalid.length > 0) { + setIssues(invalid); + return; + } + setSaving(true); + setSaveStopped(false); + setUnionNote(null); + setSaveResults([]); + const { results, stoppedEarly } = await saveDraft(store, (result) => { + setSaveResults((prev) => [...prev, result]); + }, branch); + setSaveStopped(stoppedEarly); + const written = new Set(results.filter((r) => r.status === 'written').map((r) => r.id)); + const conflicted = results.filter((r) => r.status === 'conflict').map((r) => r.id); + setConflicts((prev) => [...new Set([...prev.filter((id) => !written.has(id)), ...conflicted])]); + + // The third leg of §3.1: append ids whose documents landed to their unions. + const types = typesRef.current; + if (types) { + const union = await saveIdUnions(store, types, branch); + if (union) { + if (union.failed !== undefined) setUnionNote('failed'); + else { + typesRef.current = { source: union.source!, sha: union.sha! }; + setUnionNote('ok'); + } + } + } + setSaving(false); + refresh(store); + }, [store, phase, refresh, branch]); + + const resolveRebase = useCallback( + async (id: DraftDocId) => { + if (!store) return; + const meta = DRAFT_DOCS.find((d) => d.id === id)!; + try { + store.resetBase(id, await fetchDoc(meta.file, branch)); + } catch { + // unreachable proxy — the conflict UI stays, take-theirs still works + } + const rejected = store.rebase(id); + setIssues(rejected ?? []); + if (!rejected) setConflicts((prev) => prev.filter((x) => x !== id)); + refresh(store); + }, + [store, refresh, branch], + ); + + const resolveTakeTheirs = useCallback( + (id: DraftDocId) => { + store?.discardDocument(id); + setConflicts((prev) => prev.filter((x) => x !== id)); + if (store) refresh(store); + }, + [store, refresh], + ); + + const openHandMerge = useCallback((id: DraftDocId) => { + setPanelTab(id); + setPanelOpen(true); + }, []); + + const discardDoc = useCallback( + (id: DraftDocId) => { + store?.discardDocument(id); + setConflicts((prev) => prev.filter((x) => x !== id)); + if (store) refresh(store); + }, + [store, refresh], + ); + + const revertPath = useCallback( + (path: string) => { + if (!store) return; + const rejected = store.revertPath(path); + setIssues(rejected ?? []); + if (!rejected) refresh(store); + }, + [store, refresh], + ); + + const exit = useCallback(() => { + setEditFlag(false); + clearDraftStorage(); + stripEditQuery(); + }, [stripEditQuery]); + + const openPanel = useCallback(() => { + setPanelOpen(true); + }, []); + + // `revision` is the draft's invalidation counter — the store mutates in + // place, so it is the only signal that a recomputation is due. + // eslint-disable-next-line react-hooks/exhaustive-deps + const changedDocs = useMemo(() => store?.changedDocs() ?? [], [store, revision]); + + const override = resolved ? { ui: UI[lang], content: resolved[lang] } : undefined; + + return ( + + + {children} + {store && ( + <> + void runSave()} + onExit={exit} + onRebase={(id) => void resolveRebase(id)} + onTakeTheirs={resolveTakeTheirs} + onHandMerge={openHandMerge} + onDiscardDoc={discardDoc} + onRevertPath={revertPath} + /> + {panelOpen && ( + setPanelOpen(false)} + onTab={setPanelTab} + onChanged={() => { + setIssues(store.validate()); + refresh(store); + }} + onConflictResolved={(id) => setConflicts((prev) => prev.filter((x) => x !== id))} + /> + )} + + )} + + + ); +} diff --git a/src/components/layout/JsonPanel.tsx b/src/components/layout/JsonPanel.tsx new file mode 100644 index 0000000..8e864d8 --- /dev/null +++ b/src/components/layout/JsonPanel.tsx @@ -0,0 +1,291 @@ +// JsonPanel (spec-v4 §5.4): the structural editor of edit mode. One tab per +// draft document, plus read-only tabs for the two UI dictionaries. The whole +// document is shown as JSON; a valid change applies to the draft immediately +// (the live page re-renders), an invalid one is rejected and reported with +// exact document paths. Templates create records with every required field +// present; delete removes the record from the structure document AND its text +// in both language documents in one validated step, so no orphan is possible +// (§3.4). A conflicted document shows the live master side by side for a +// hand-merge. +import { useEffect, useMemo, useRef, useState } from 'react'; +import { useI18n } from '@/i18n/provider'; +import { UI } from '@/i18n'; +import { DRAFT_DOCS } from '@/i18n/draft'; +import type { DraftDocId, DraftStore } from '@/i18n/draft'; +import type { ContentIssue } from '@/i18n/validate'; + +export type PanelTab = DraftDocId | 'ui.vi' | 'ui.en'; + +const PANEL_TABS: PanelTab[] = [...DRAFT_DOCS.map((d) => d.id), 'ui.vi', 'ui.en']; + +// The shape of each document, shown above the editor so the format is +// discoverable without reading the spec (§5.4). +const SHAPES: Record = { + profile: + 'profile.json — { firstName, lastName, email, githubUrl, linkedinUrl, githubHandle, linkedinHandle, telegramUrl, telegramHandle, currentInterests: [string], roles: [string], philosophy: [{ id, keywords: [string] }] }', + skills: 'skills.json — [{ id, skills: [string] }]', + experience: + 'experience.json — [{ id, company, duration, location?, variant?: "current" | "gap", logo? }]', + projects: + 'projects.json — [{ id, category, role, technologies: [string], metrics?: [string], featured, sections: [{ id, type: "text" | "diagram" | "metrics" | "code" }] }]', + 'content.vi': + 'content.vi.json — { profile: { name, title, tagline: [{ text, emphasis? }], bio, philosophy: { : { title, description } } }, skills: { : { title } }, experience: { : { title, responsibilities: [string] } }, projects: { : { title, summary, sections: { : { title, content } } } } }', + 'content.en': + 'content.en.json — same tree; every field optional, a missing field renders the Vietnamese value', + 'ui.vi': 'locales/vi/ui.json — chrome strings; read-only in edit mode (Phase 4)', + 'ui.en': 'locales/en/ui.json — chrome strings; read-only in edit mode (Phase 4)', +}; + +type RecordRow = { kind: 'project' | 'experience' | 'skill-group' | 'philosophy' | 'section'; id: string; projectId?: string }; + +type JsonPanelProps = { + store: DraftStore; + tab: PanelTab; + revision: number; + conflicts: DraftDocId[]; + onClose: () => void; + onTab: (tab: PanelTab) => void; + onChanged: () => void; + onConflictResolved: (id: DraftDocId) => void; +}; + +export function JsonPanel({ + store, + tab, + revision, + conflicts, + onClose, + onTab, + onChanged, + onConflictResolved, +}: JsonPanelProps) { + const { ui } = useI18n(); + const s = ui.edit.panel; + const isUi = tab === 'ui.vi' || tab === 'ui.en'; + const conflicted = !isUi && conflicts.includes(tab as DraftDocId); + const [text, setText] = useState(''); + const [parseError, setParseError] = useState(null); + const [docIssues, setDocIssues] = useState([]); + const [sectionProject, setSectionProject] = useState(''); + const textRef = useRef(text); + textRef.current = text; + + const documentOf = (target: PanelTab): unknown => + target === 'ui.vi' ? UI.vi : target === 'ui.en' ? UI.en : store.dataOf(target); + + // Load the tab's document as pretty JSON. A textarea that already holds the + // same data is left alone — otherwise the store update our own keystroke + // caused would re-serialize the text out from under the caret. + useEffect(() => { + const canonical = JSON.stringify(documentOf(tab), null, 2); + try { + if (JSON.stringify(JSON.parse(textRef.current), null, 2) === canonical) return; + } catch { + // textarea currently invalid — reload the last good document + } + setText(canonical); + setParseError(null); + setDocIssues([]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [tab, revision]); + + const applyCandidate = (candidate: unknown) => { + const rejected = store.setDocument(tab as DraftDocId, candidate); + setDocIssues(rejected ?? []); + if (!rejected) onChanged(); + }; + + const handleChange = (next: string) => { + setText(next); + if (isUi) return; + let candidate: unknown; + try { + candidate = JSON.parse(next); + setParseError(null); + } catch (error) { + setParseError(error instanceof Error ? error.message : String(error)); + return; + } + applyCandidate(candidate); + }; + + const runTemplate = ( + kind: 'project' | 'experience' | 'skill-group' | 'philosophy' | 'section', + options: { projectId?: string } = {}, + ) => { + const rejected = store.addRecord(kind, options); + setDocIssues(rejected ?? []); + if (!rejected) onChanged(); + }; + + const runDelete = (kind: RecordRow['kind'], ids: { id: string; projectId?: string }) => { + if (!window.confirm(s.deleteConfirm)) return; + const rejected = store.deleteRecord(kind, ids); + setDocIssues(rejected ?? []); + if (!rejected) onChanged(); + }; + + // The record list mirrors the document currently in the draft — the same + // data the textarea shows. + const records = useMemo(() => { + if (isUi) return []; + const list = (value: unknown): { id: string }[] => + Array.isArray(value) ? (value as { id: string }[]) : []; + if (tab === 'profile') { + const data = store.dataOf('profile') as { philosophy?: { id: string }[] }; + return list(data.philosophy).map((r) => ({ kind: 'philosophy', id: r.id })); + } + if (tab === 'skills') { + return list(store.dataOf('skills')).map((r) => ({ kind: 'skill-group', id: r.id })); + } + if (tab === 'experience') { + return list(store.dataOf('experience')).map((r) => ({ kind: 'experience', id: r.id })); + } + const projects = list(store.dataOf('projects')) as { id: string; sections?: { id: string }[] }[]; + return projects.flatMap((p) => [ + { kind: 'project' as const, id: p.id }, + ...list(p.sections).map((sec) => ({ kind: 'section' as const, id: sec.id, projectId: p.id })), + ]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [tab, revision, isUi]); + + const projectIds = useMemo( + () => (Array.isArray(store.dataOf('projects')) ? (store.dataOf('projects') as { id: string }[]).map((p) => p.id) : []), + // eslint-disable-next-line react-hooks/exhaustive-deps + [revision], + ); + + const applyMerge = () => { + let candidate: unknown; + try { + candidate = JSON.parse(text); + } catch { + return; // the draft column must be valid JSON before merging + } + const rejected = store.setDocument(tab as DraftDocId, candidate); + setDocIssues(rejected ?? []); + if (!rejected) { + onConflictResolved(tab as DraftDocId); + onChanged(); + } + }; + + const templateFor: Partial void }>> = { + profile: { label: s.addPhilosophy, run: () => runTemplate('philosophy') }, + skills: { label: s.addSkillGroup, run: () => runTemplate('skill-group') }, + experience: { label: s.addExperience, run: () => runTemplate('experience') }, + projects: { label: s.addProject, run: () => runTemplate('project') }, + }; + + return ( +