mirror of
https://github.com/dong-nz/cv.git
synced 2026-11-22 16:10:40 +07:00
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.
This commit is contained in:
1 parent
f113dfc7b5
commit
6482c993e8
24 files changed
+2523
-52
No files matched your search
@@ -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 (
|
||||
<footer className="edit-bar" aria-label={s.title}>
|
||||
<div className="edit-bar-row">
|
||||
<strong className="edit-bar-title">{s.title}</strong>
|
||||
<span className="edit-bar-count" role="status">
|
||||
{dirty ? `${changedDocs.reduce((n, d) => n + d.paths.length, 0)} ${s.changes}` : s.noChanges}
|
||||
</span>
|
||||
<span className="edit-bar-branch">
|
||||
{s.branchLabel} <code>{branch}</code>
|
||||
</span>
|
||||
{offline && <span className="edit-bar-warn">{s.offline}</span>}
|
||||
{draftRestored && !dirty && <span className="edit-bar-warn">{s.draftRestored}</span>}
|
||||
<div className="edit-bar-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="edit-btn"
|
||||
aria-expanded={showDiff}
|
||||
onClick={() => setShowDiff((v) => !v)}
|
||||
>
|
||||
{s.changesTitle}
|
||||
</button>
|
||||
<button type="button" className="edit-btn" onClick={onOpenPanel}>
|
||||
{s.openPanel}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="edit-btn edit-btn-primary"
|
||||
disabled={!dirty || saving || offline}
|
||||
onClick={onSave}
|
||||
>
|
||||
{saving ? s.saving : s.save}
|
||||
</button>
|
||||
{saveStopped && (
|
||||
<button type="button" className="edit-btn edit-btn-primary" disabled={saving} onClick={onSave}>
|
||||
{s.resume}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="edit-btn"
|
||||
onClick={() => {
|
||||
if (!dirty || window.confirm(s.exitConfirm)) onExit();
|
||||
}}
|
||||
>
|
||||
{s.exit}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showDiff && changedDocs.length > 0 && (
|
||||
<div className="edit-bar-diff">
|
||||
{changedDocs.map((doc) => (
|
||||
<div key={doc.id} className="edit-bar-doc">
|
||||
<div className="edit-bar-doc-head">
|
||||
<code>{fileOf(doc.id)}</code>
|
||||
<button type="button" className="edit-btn" onClick={() => onDiscardDoc(doc.id)}>
|
||||
{s.discardDoc}
|
||||
</button>
|
||||
</div>
|
||||
<ul>
|
||||
{doc.paths.map((p) => (
|
||||
<li key={p.path}>
|
||||
<code className="edit-bar-path">{p.path}</code>
|
||||
<span className="edit-bar-value">{truncate(p.before)}</span>
|
||||
<span aria-hidden="true">→</span>
|
||||
<span className="edit-bar-value">{truncate(p.after)}</span>
|
||||
<button type="button" className="edit-btn" onClick={() => onRevertPath(p.path)}>
|
||||
{s.revert}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{conflicts.length > 0 && (
|
||||
<div className="edit-bar-conflicts">
|
||||
<strong>{s.conflicts}</strong>
|
||||
{conflicts.map((id) => (
|
||||
<span key={id} className="edit-bar-conflict">
|
||||
<code>{fileOf(id)}</code> {s.conflictDetail}{' '}
|
||||
<button type="button" className="edit-btn" onClick={() => onRebase(id)}>
|
||||
{s.rebase}
|
||||
</button>
|
||||
<button type="button" className="edit-btn" onClick={() => onTakeTheirs(id)}>
|
||||
{s.takeTheirs}
|
||||
</button>
|
||||
<button type="button" className="edit-btn" onClick={() => onHandMerge(id)}>
|
||||
{s.handMerge}
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{issues.length > 0 && (
|
||||
<ul className="edit-bar-issues">
|
||||
{issues.map((issue) => (
|
||||
<li key={`${issue.path}:${issue.message}`}>
|
||||
<code>{issue.path}</code>: {issue.message}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{saveResults.length > 0 && (
|
||||
<ul className="edit-bar-save">
|
||||
{saveResults.map((r) => (
|
||||
<li key={r.id}>
|
||||
<code>{fileOf(r.id)}</code>: {statusLabel(r)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{unionNote && (
|
||||
<p className="edit-bar-note">{unionNote === 'ok' ? s.unionNote : s.unionFailed}</p>
|
||||
)}
|
||||
{allWritten && !dirty && (
|
||||
<p className="edit-bar-note">
|
||||
{branch === DEFAULT_BRANCH ? s.deployQueued : s.mergeHint}
|
||||
</p>
|
||||
)}
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
@@ -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<DraftStore | null>(null);
|
||||
const typesRef = useRef<{ source: string; sha: string } | null>(null);
|
||||
const [phase, setPhase] = useState<Phase>('authenticating');
|
||||
const [branch, setBranch] = useState<string>(DEFAULT_BRANCH);
|
||||
const [resolved, setResolved] = useState<Record<'vi' | 'en', ResolvedContent> | null>(null);
|
||||
const [revision, setRevision] = useState(0);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const [issues, setIssues] = useState<ContentIssue[]>([]);
|
||||
const [conflicts, setConflicts] = useState<DraftDocId[]>([]);
|
||||
const [draftRestored, setDraftRestored] = useState(false);
|
||||
const [saveResults, setSaveResults] = useState<DocSaveResult[]>([]);
|
||||
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<PanelTab>('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=<branch>` 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<DraftDocId, DocBase> | null = null;
|
||||
try {
|
||||
bases = {} as Record<DraftDocId, DocBase>;
|
||||
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<EditApi | null>(
|
||||
() =>
|
||||
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 (
|
||||
<I18nProvider override={override}>
|
||||
<EditContext.Provider value={editApi}>
|
||||
{children}
|
||||
{store && (
|
||||
<>
|
||||
<EditBar
|
||||
offline={phase === 'offline'}
|
||||
dirty={dirty}
|
||||
changedDocs={changedDocs}
|
||||
conflicts={conflicts}
|
||||
issues={issues}
|
||||
saving={saving}
|
||||
saveStopped={saveStopped}
|
||||
saveResults={saveResults}
|
||||
unionNote={unionNote}
|
||||
draftRestored={draftRestored}
|
||||
branch={branch}
|
||||
onOpenPanel={openPanel}
|
||||
onSave={() => void runSave()}
|
||||
onExit={exit}
|
||||
onRebase={(id) => void resolveRebase(id)}
|
||||
onTakeTheirs={resolveTakeTheirs}
|
||||
onHandMerge={openHandMerge}
|
||||
onDiscardDoc={discardDoc}
|
||||
onRevertPath={revertPath}
|
||||
/>
|
||||
{panelOpen && (
|
||||
<JsonPanel
|
||||
store={store}
|
||||
tab={panelTab}
|
||||
revision={revision}
|
||||
conflicts={conflicts}
|
||||
onClose={() => setPanelOpen(false)}
|
||||
onTab={setPanelTab}
|
||||
onChanged={() => {
|
||||
setIssues(store.validate());
|
||||
refresh(store);
|
||||
}}
|
||||
onConflictResolved={(id) => setConflicts((prev) => prev.filter((x) => x !== id))}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</EditContext.Provider>
|
||||
</I18nProvider>
|
||||
);
|
||||
}
|
||||
@@ -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<PanelTab, string> = {
|
||||
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: { <id>: { title, description } } }, skills: { <id>: { title } }, experience: { <id>: { title, responsibilities: [string] } }, projects: { <id>: { title, summary, sections: { <id>: { 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<string | null>(null);
|
||||
const [docIssues, setDocIssues] = useState<ContentIssue[]>([]);
|
||||
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<RecordRow[]>(() => {
|
||||
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<Record<PanelTab, { label: string; run: () => 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 (
|
||||
<aside className="json-panel" aria-label={s.title}>
|
||||
<div className="json-panel-head">
|
||||
<strong>{s.title}</strong>
|
||||
<button type="button" className="edit-btn" onClick={onClose}>
|
||||
{ui.edit.closePanel}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<nav className="json-panel-tabs" aria-label={s.title}>
|
||||
{PANEL_TABS.map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
className={`json-panel-tab${t === tab ? ' is-active' : ''}`}
|
||||
aria-selected={t === tab}
|
||||
role="tab"
|
||||
onClick={() => onTab(t)}
|
||||
>
|
||||
<code>{t === 'ui.vi' || t === 'ui.en' ? `locales/${t.slice(3)}/ui.json` : DRAFT_DOCS.find((d) => d.id === t)!.file}</code>
|
||||
{conflicts.includes(t as DraftDocId) && <span className="json-panel-conflict-flag">●</span>}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<pre className="json-panel-shape">{SHAPES[tab]}</pre>
|
||||
|
||||
<div className="json-panel-tools">
|
||||
{templateFor[tab] && (
|
||||
<button type="button" className="edit-btn" onClick={templateFor[tab]!.run}>
|
||||
{templateFor[tab]!.label}
|
||||
</button>
|
||||
)}
|
||||
{(tab === 'content.vi' || tab === 'content.en') && (
|
||||
<span className="json-panel-section-add">
|
||||
<label>
|
||||
{s.addSection}{' '}
|
||||
<select value={sectionProject} onChange={(e) => setSectionProject(e.target.value)}>
|
||||
<option value="">{s.projectLabel}</option>
|
||||
{projectIds.map((id) => (
|
||||
<option key={id} value={id}>
|
||||
{id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="edit-btn"
|
||||
disabled={!sectionProject}
|
||||
onClick={() => runTemplate('section', { projectId: sectionProject })}
|
||||
>
|
||||
{s.addSection}
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
{isUi && <span className="json-panel-readonly">{s.readOnly}</span>}
|
||||
</div>
|
||||
|
||||
{records.length > 0 && (
|
||||
<div className="json-panel-records">
|
||||
{records.map((r) => (
|
||||
<span key={`${r.kind}:${r.projectId ?? ''}:${r.id}`} className="json-panel-record">
|
||||
<code>{r.projectId ? `${r.projectId} / ${r.id}` : r.id}</code>
|
||||
<button
|
||||
type="button"
|
||||
className="edit-btn"
|
||||
onClick={() => runDelete(r.kind, { id: r.id, projectId: r.projectId })}
|
||||
>
|
||||
{s.deleteRecord}
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{conflicted && (
|
||||
<div className="json-panel-merge">
|
||||
<label>{s.baseLabel}</label>
|
||||
<textarea value={JSON.stringify(store.baseDataOf(tab as DraftDocId), null, 2)} readOnly spellCheck={false} />
|
||||
<label>{s.draftLabel}</label>
|
||||
<button type="button" className="edit-btn edit-btn-primary" onClick={applyMerge}>
|
||||
{s.applyMerge}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<textarea
|
||||
className="json-panel-editor"
|
||||
value={text}
|
||||
readOnly={isUi}
|
||||
spellCheck={false}
|
||||
aria-label={tab}
|
||||
onChange={(e) => handleChange(e.target.value)}
|
||||
/>
|
||||
|
||||
{(parseError || docIssues.length > 0) && (
|
||||
<ul className="json-panel-issues">
|
||||
{parseError && <li>{s.parseError}: {parseError}</li>}
|
||||
{docIssues.map((issue) => (
|
||||
<li key={`${issue.path}:${issue.message}`}>
|
||||
<code>{issue.path}</code>: {issue.message}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<span className="json-panel-status" role="status">
|
||||
{parseError ? s.parseError : docIssues.length > 0 ? s.invalid : isUi ? s.readOnly : s.valid}
|
||||
</span>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user