mirror of
https://github.com/dong-nz/cv.git
synced 2026-11-23 00:20: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,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<string, Record<string, unknown>>;
|
||||||
|
const en = store.dataOf('content.en') as Record<string, Record<string, unknown>>;
|
||||||
|
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<string, Record<string, string>>).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<string, Record<string, string>>).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<string, Record<string, string>>).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');
|
||||||
+351
@@ -2086,3 +2086,354 @@
|
|||||||
.back-to-top:hover {
|
.back-to-top:hover {
|
||||||
background: var(--accent-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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+36
-16
@@ -1,6 +1,7 @@
|
|||||||
import './App.css'
|
import './App.css'
|
||||||
import { lazy, Suspense } from 'react'
|
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 { ThemeProvider } from '@/hooks/useTheme'
|
||||||
import { Layout } from '@/components/layout/Layout'
|
import { Layout } from '@/components/layout/Layout'
|
||||||
import { LanguageProvider } from '@/hooks/useLanguage'
|
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 ProjectsListPage = lazy(() => import('@/pages/ProjectsListPage').then((m) => ({ default: m.ProjectsListPage })))
|
||||||
const ProjectDetailPage = lazy(() => import('@/pages/ProjectDetailPage').then((m) => ({ default: m.ProjectDetailPage })))
|
const ProjectDetailPage = lazy(() => import('@/pages/ProjectDetailPage').then((m) => ({ default: m.ProjectDetailPage })))
|
||||||
const PhilosophyPage = lazy(() => import('@/pages/PhilosophyPage').then((m) => ({ default: m.PhilosophyPage })))
|
const PhilosophyPage = lazy(() => import('@/pages/PhilosophyPage').then((m) => ({ default: m.PhilosophyPage })))
|
||||||
|
|
||||||
const ContactPage = lazy(() => import('@/pages/ContactPage').then((m) => ({ default: m.ContactPage })))
|
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 (
|
||||||
|
<Suspense fallback={null}>
|
||||||
|
<EditModeShell>{children}</EditModeShell>
|
||||||
|
</Suspense>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
return (
|
return (
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
@@ -24,21 +42,23 @@ function App() {
|
|||||||
{/* I18nProvider sits below LanguageProvider: it resolves the language
|
{/* I18nProvider sits below LanguageProvider: it resolves the language
|
||||||
through useLanguage and hands every consumer the UI/CONTENT of it. */}
|
through useLanguage and hands every consumer the UI/CONTENT of it. */}
|
||||||
<I18nProvider>
|
<I18nProvider>
|
||||||
<Layout>
|
<MaybeEditMode>
|
||||||
{/* A null fallback keeps the shell (nav, footer) painted without reserving a
|
<Layout>
|
||||||
box that would shift the page when the route chunk lands. */}
|
{/* A null fallback keeps the shell (nav, footer) painted without reserving a
|
||||||
<Suspense fallback={null}>
|
box that would shift the page when the route chunk lands. */}
|
||||||
<Routes>
|
<Suspense fallback={null}>
|
||||||
<Route path="/" element={<HomePage />} />
|
<Routes>
|
||||||
<Route path="/about" element={<AboutPage />} />
|
<Route path="/" element={<HomePage />} />
|
||||||
<Route path="/experience" element={<ExperiencePage />} />
|
<Route path="/about" element={<AboutPage />} />
|
||||||
<Route path="/projects" element={<ProjectsListPage />} />
|
<Route path="/experience" element={<ExperiencePage />} />
|
||||||
<Route path="/projects/:id" element={<ProjectDetailPage />} />
|
<Route path="/projects" element={<ProjectsListPage />} />
|
||||||
<Route path="/philosophy" element={<PhilosophyPage />} />
|
<Route path="/projects/:id" element={<ProjectDetailPage />} />
|
||||||
<Route path="/contact" element={<ContactPage />} />
|
<Route path="/philosophy" element={<PhilosophyPage />} />
|
||||||
</Routes>
|
<Route path="/contact" element={<ContactPage />} />
|
||||||
</Suspense>
|
</Routes>
|
||||||
</Layout>
|
</Suspense>
|
||||||
|
</Layout>
|
||||||
|
</MaybeEditMode>
|
||||||
</I18nProvider>
|
</I18nProvider>
|
||||||
</LanguageProvider>
|
</LanguageProvider>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ import { SectionHeading } from '@/components/ui/SectionHeading'
|
|||||||
import { motion } from 'motion/react'
|
import { motion } from 'motion/react'
|
||||||
import { InView } from '@/components/ui/InView'
|
import { InView } from '@/components/ui/InView'
|
||||||
import { Tag } from '@/components/ui/Tag'
|
import { Tag } from '@/components/ui/Tag'
|
||||||
|
import { EditableText } from '@/components/ui/EditableText'
|
||||||
import { useI18n } from '@/i18n/provider'
|
import { useI18n } from '@/i18n/provider'
|
||||||
export function About() {
|
export function About() {
|
||||||
const { ui: s, content: c } = useI18n()
|
const { ui: s, content: c } = useI18n()
|
||||||
@@ -19,9 +20,15 @@ export function About() {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<SectionHeading title={s.about.heading} tag={s.about.heading} />
|
<SectionHeading title={s.about.heading} tag={s.about.heading} />
|
||||||
<p className="prose-lede lede-wide">
|
<EditableText
|
||||||
|
as="p"
|
||||||
|
className="prose-lede lede-wide"
|
||||||
|
path="profile.bio"
|
||||||
|
label={s.edit.fields.bio}
|
||||||
|
multiline
|
||||||
|
>
|
||||||
{c.profile.bio}
|
{c.profile.bio}
|
||||||
</p>
|
</EditableText>
|
||||||
|
|
||||||
<h3 className="subheading">
|
<h3 className="subheading">
|
||||||
{s.about.engineeringTitle}
|
{s.about.engineeringTitle}
|
||||||
@@ -38,8 +45,12 @@ export function About() {
|
|||||||
whileHover={{ scale: 1.02, y: -4 }}
|
whileHover={{ scale: 1.02, y: -4 }}
|
||||||
whileTap={{ scale: 0.98 }}
|
whileTap={{ scale: 0.98 }}
|
||||||
>
|
>
|
||||||
<h3>{point.title}</h3>
|
<EditableText as="h3" path={`profile.philosophy.${point.id}.title`} label={s.edit.fields.pointTitle}>
|
||||||
<p>{point.description}</p>
|
{point.title}
|
||||||
|
</EditableText>
|
||||||
|
<EditableText as="p" path={`profile.philosophy.${point.id}.description`} label={s.edit.fields.pointDescription} multiline>
|
||||||
|
{point.description}
|
||||||
|
</EditableText>
|
||||||
<div className="philosophy-keywords">
|
<div className="philosophy-keywords">
|
||||||
{point.keywords.map((kw) => (
|
{point.keywords.map((kw) => (
|
||||||
<Tag key={kw}>{kw}</Tag>
|
<Tag key={kw}>{kw}</Tag>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { SectionHeading } from '@/components/ui/SectionHeading'
|
import { SectionHeading } from '@/components/ui/SectionHeading'
|
||||||
import { motion } from "motion/react"
|
import { motion } from "motion/react"
|
||||||
import { InView } from "@/components/ui/InView"
|
import { InView } from "@/components/ui/InView"
|
||||||
|
import { EditableText } from '@/components/ui/EditableText'
|
||||||
import { useI18n } from '@/i18n/provider'
|
import { useI18n } from '@/i18n/provider'
|
||||||
|
|
||||||
export function Experience() {
|
export function Experience() {
|
||||||
@@ -32,9 +33,9 @@ export function Experience() {
|
|||||||
>
|
>
|
||||||
<div className="timeline-marker" />
|
<div className="timeline-marker" />
|
||||||
<div className="timeline-header">
|
<div className="timeline-header">
|
||||||
<div className="timeline-title">
|
<EditableText as="div" className="timeline-title" path={`experience.${exp.id}.title`} label={s.edit.fields.expTitle}>
|
||||||
{exp.title}
|
{exp.title}
|
||||||
</div>
|
</EditableText>
|
||||||
<div className="timeline-company">{exp.company}</div>
|
<div className="timeline-company">{exp.company}</div>
|
||||||
<div className="timeline-meta">
|
<div className="timeline-meta">
|
||||||
<span className="timeline-duration">{exp.duration}</span>
|
<span className="timeline-duration">{exp.duration}</span>
|
||||||
@@ -44,8 +45,15 @@ export function Experience() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<ul className="timeline-responsibilities">
|
<ul className="timeline-responsibilities">
|
||||||
{exp.responsibilities.map((r) => (
|
{exp.responsibilities.map((r, ri) => (
|
||||||
<li key={r}>{r}</li>
|
<EditableText
|
||||||
|
as="li"
|
||||||
|
key={ri}
|
||||||
|
path={`experience.${exp.id}.responsibilities[${ri}]`}
|
||||||
|
label={`${exp.title} — ${s.edit.fields.responsibility} ${ri + 1}`}
|
||||||
|
>
|
||||||
|
{r}
|
||||||
|
</EditableText>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { motion } from "motion/react"
|
import { motion } from "motion/react"
|
||||||
import { SectionHeading } from "@/components/ui/SectionHeading"
|
import { SectionHeading } from "@/components/ui/SectionHeading"
|
||||||
import { InView } from '@/components/ui/InView'
|
import { InView } from '@/components/ui/InView'
|
||||||
|
import { EditableText } from '@/components/ui/EditableText'
|
||||||
import { useI18n } from '@/i18n/provider'
|
import { useI18n } from '@/i18n/provider'
|
||||||
|
|
||||||
export function Expertise() {
|
export function Expertise() {
|
||||||
@@ -31,7 +32,9 @@ export function Expertise() {
|
|||||||
whileHover={{ scale: 1.02, y: -4 }}
|
whileHover={{ scale: 1.02, y: -4 }}
|
||||||
whileTap={{ scale: 0.98 }}
|
whileTap={{ scale: 0.98 }}
|
||||||
>
|
>
|
||||||
<h3>{group.title}</h3>
|
<EditableText as="h3" path={`skills.${group.id}.title`} label={s.edit.fields.groupTitle}>
|
||||||
|
{group.title}
|
||||||
|
</EditableText>
|
||||||
<ul className="expertise-skills">
|
<ul className="expertise-skills">
|
||||||
{group.skills.map((skill) => (
|
{group.skills.map((skill) => (
|
||||||
<li key={skill} className="expertise-skill">
|
<li key={skill} className="expertise-skill">
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {DownloadResume} from '@/components/sections/DownloadResume'
|
|||||||
import {Button} from "@/components/ui/Button"
|
import {Button} from "@/components/ui/Button"
|
||||||
import {Typewriter} from '@/components/ui/Typewriter'
|
import {Typewriter} from '@/components/ui/Typewriter'
|
||||||
import {HeroParticles} from '@/components/sections/HeroParticles'
|
import {HeroParticles} from '@/components/sections/HeroParticles'
|
||||||
|
import {EditableText} from '@/components/ui/EditableText'
|
||||||
import {SocialLinks} from "@/components/ui/SocialLinks"
|
import {SocialLinks} from "@/components/ui/SocialLinks"
|
||||||
|
|
||||||
|
|
||||||
@@ -74,9 +75,24 @@ export function Hero() {
|
|||||||
never content — the emphasis span keeps its classes. */}
|
never content — the emphasis span keeps its classes. */}
|
||||||
{c.profile.tagline.map((segment, i) => (
|
{c.profile.tagline.map((segment, i) => (
|
||||||
segment.emphasis ? (
|
segment.emphasis ? (
|
||||||
<span key={i} className="ok-possible name-highlight">{segment.text}</span>
|
<EditableText
|
||||||
|
as="span"
|
||||||
|
key={i}
|
||||||
|
className="ok-possible name-highlight"
|
||||||
|
path={`profile.tagline[${i}].text`}
|
||||||
|
label={`${s.edit.fields.tagline} ${i + 1}`}
|
||||||
|
>
|
||||||
|
{segment.text}
|
||||||
|
</EditableText>
|
||||||
) : (
|
) : (
|
||||||
<span key={i}>{segment.text}</span>
|
<EditableText
|
||||||
|
as="span"
|
||||||
|
key={i}
|
||||||
|
path={`profile.tagline[${i}].text`}
|
||||||
|
label={`${s.edit.fields.tagline} ${i + 1}`}
|
||||||
|
>
|
||||||
|
{segment.text}
|
||||||
|
</EditableText>
|
||||||
)
|
)
|
||||||
))}
|
))}
|
||||||
</motion.p>
|
</motion.p>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { Link } from "react-router"
|
|||||||
import { motion } from "motion/react"
|
import { motion } from "motion/react"
|
||||||
import { Badge } from "@/components/ui/Badge"
|
import { Badge } from "@/components/ui/Badge"
|
||||||
import { InView } from "@/components/ui/InView"
|
import { InView } from "@/components/ui/InView"
|
||||||
|
import { EditableText } from '@/components/ui/EditableText'
|
||||||
import { useI18n } from '@/i18n/provider'
|
import { useI18n } from '@/i18n/provider'
|
||||||
|
|
||||||
const MotionLink = motion.create(Link)
|
const MotionLink = motion.create(Link)
|
||||||
@@ -46,12 +47,16 @@ export function Projects() {
|
|||||||
>
|
>
|
||||||
<div className="project-card-content">
|
<div className="project-card-content">
|
||||||
<div className="project-card-header">
|
<div className="project-card-header">
|
||||||
<h3>{project.title}</h3>
|
<EditableText as="h3" path={`projects.${project.id}.title`} label={s.edit.fields.title}>
|
||||||
|
{project.title}
|
||||||
|
</EditableText>
|
||||||
<Badge variant="outline">
|
<Badge variant="outline">
|
||||||
{s.projects.categories[project.category]}
|
{s.projects.categories[project.category]}
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
<p className="project-card-summary">{project.summary}</p>
|
<EditableText as="p" className="project-card-summary" path={`projects.${project.id}.summary`} label={`${project.title} — ${s.edit.fields.summary}`}>
|
||||||
|
{project.summary}
|
||||||
|
</EditableText>
|
||||||
<div className="project-card-techs">
|
<div className="project-card-techs">
|
||||||
{project.technologies.slice(0, 4).map((tech) => (
|
{project.technologies.slice(0, 4).map((tech) => (
|
||||||
<span key={tech} className="tag">
|
<span key={tech} className="tag">
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
// EditableText (spec-v4 §5.3): a text node bound to a text-document path.
|
||||||
|
// Outside edit mode it renders exactly the element the site renders today —
|
||||||
|
// same tag, same attributes, text as children, zero DOM/CSS/motion difference.
|
||||||
|
// In edit mode the same element becomes the inline editor.
|
||||||
|
//
|
||||||
|
// Hard rules implemented here:
|
||||||
|
// - commit on blur only, never per keystroke — Vietnamese IME composition is
|
||||||
|
// never truncated because no keystroke ever reaches the draft;
|
||||||
|
// - Esc cancels the current edit and restores the last committed value;
|
||||||
|
// - Enter commits + blurs single-line fields, inserts \n in multi-line ones;
|
||||||
|
// - paste is sanitized to plain text;
|
||||||
|
// - an empty required value is rejected at commit (validator rule 6) and the
|
||||||
|
// field keeps focus;
|
||||||
|
// - motion keeps transform ownership: this component edits only the text node
|
||||||
|
// inside already-animated elements.
|
||||||
|
import { useContext, useRef, useState } from 'react';
|
||||||
|
import type { ElementType, ReactNode } from 'react';
|
||||||
|
import { EditContext } from '@/hooks/useEdit';
|
||||||
|
|
||||||
|
type EditableTextProps = {
|
||||||
|
// The element this site renders today — tag or motion component.
|
||||||
|
as?: ElementType;
|
||||||
|
// Text-document path, e.g. `projects.iot-dws-integration.summary`.
|
||||||
|
path: string;
|
||||||
|
// Human-readable field name for the accessibility label (§5.3).
|
||||||
|
label: string;
|
||||||
|
multiline?: boolean;
|
||||||
|
children: ReactNode;
|
||||||
|
className?: string;
|
||||||
|
[prop: string]: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function EditableText({
|
||||||
|
as,
|
||||||
|
path,
|
||||||
|
label,
|
||||||
|
multiline = false,
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
...rest
|
||||||
|
}: EditableTextProps) {
|
||||||
|
const edit = useContext(EditContext);
|
||||||
|
const ref = useRef<HTMLElement | null>(null);
|
||||||
|
const [invalid, setInvalid] = useState(false);
|
||||||
|
const Comp = (as ?? 'p') as ElementType;
|
||||||
|
|
||||||
|
if (!edit) {
|
||||||
|
return (
|
||||||
|
<Comp {...rest} className={className}>
|
||||||
|
{children}
|
||||||
|
</Comp>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const dirty = edit.isPathDirty(path);
|
||||||
|
const cls = [className, 'editable-text', dirty && 'edit-dirty', invalid && 'edit-invalid']
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ');
|
||||||
|
|
||||||
|
const commit = () => {
|
||||||
|
const el = ref.current;
|
||||||
|
if (!el) return;
|
||||||
|
// innerText normalizes <br>/<div> line boxes into \n — multi-line text
|
||||||
|
// is stored as plain text with newlines, rendering unchanged (§5.3).
|
||||||
|
const value = (el.innerText ?? '').replace(/\n+$/, '');
|
||||||
|
const issues = edit.commit(path, value);
|
||||||
|
setInvalid(issues !== null);
|
||||||
|
if (issues) el.focus(); // empty-required: the field keeps focus
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
{...rest}
|
||||||
|
ref={ref}
|
||||||
|
className={cls}
|
||||||
|
contentEditable
|
||||||
|
suppressContentEditableWarning
|
||||||
|
role="textbox"
|
||||||
|
aria-multiline={multiline || undefined}
|
||||||
|
aria-label={label}
|
||||||
|
data-edit-path={path}
|
||||||
|
// Editing text must not follow the card link it sits inside.
|
||||||
|
onClick={(event: React.MouseEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
}}
|
||||||
|
onBlur={commit}
|
||||||
|
onKeyDown={(event: React.KeyboardEvent) => {
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
event.preventDefault();
|
||||||
|
const el = ref.current;
|
||||||
|
if (el && typeof children === 'string') el.innerText = children;
|
||||||
|
el?.blur(); // blurring commits the restored value — a no-op change
|
||||||
|
setInvalid(false);
|
||||||
|
} else if (event.key === 'Enter' && !multiline) {
|
||||||
|
event.preventDefault();
|
||||||
|
ref.current?.blur(); // blur performs the commit (§5.3)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onPaste={(event: React.ClipboardEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
document.execCommand('insertText', false, event.clipboardData.getData('text/plain'));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</Comp>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
// The edit-mode context (spec-v4 §5.3): the API EditModeShell hands to
|
||||||
|
// EditableText consumers. Lives on its own so component files stay pure
|
||||||
|
// components (react/only-export-components).
|
||||||
|
import { createContext } from 'react';
|
||||||
|
import type { ContentIssue } from '@/i18n/validate';
|
||||||
|
|
||||||
|
// commit/revert return the validator issues when the candidate draft is
|
||||||
|
// invalid (the edit was NOT applied), or null when it was accepted.
|
||||||
|
export type EditApi = {
|
||||||
|
commit: (path: string, value: string) => ContentIssue[] | null;
|
||||||
|
revert: (path: string) => ContentIssue[] | null;
|
||||||
|
isPathDirty: (path: string) => boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Without a provider (every visitor request, every page outside edit mode)
|
||||||
|
// the context is null and EditableText is transparent.
|
||||||
|
export const EditContext = createContext<EditApi | null>(null);
|
||||||
@@ -0,0 +1,705 @@
|
|||||||
|
// Draft store (spec-v4 §5.1, §5.5, §5.6, §6.1): the live branch documents
|
||||||
|
// fetched through the proxy, a copy-on-write draft over them, changed-path
|
||||||
|
// tracking, cross-document validation on every accepted edit, sessionStorage
|
||||||
|
// durability, and the sequential-PUT save pipeline with last_commit_sha
|
||||||
|
// optimistic concurrency. Pure logic — the React glue lives in EditModeShell.
|
||||||
|
import contentEnJson from './locales/en/content.json';
|
||||||
|
import contentViJson from './locales/vi/content.json';
|
||||||
|
import experienceJson from '../data/experience.json';
|
||||||
|
import profileJson from '../data/profile.json';
|
||||||
|
import projectsJson from '../data/projects.json';
|
||||||
|
import skillsJson from '../data/skills.json';
|
||||||
|
import { collectContentIssues } from './validate';
|
||||||
|
import type { ContentIssue, ContentStructures } from './validate';
|
||||||
|
import type { ContentEn, ContentVi } from './dict-types';
|
||||||
|
import type { Language } from '../types/index';
|
||||||
|
|
||||||
|
export type DraftDocId =
|
||||||
|
| 'profile'
|
||||||
|
| 'skills'
|
||||||
|
| 'experience'
|
||||||
|
| 'projects'
|
||||||
|
| 'content.vi'
|
||||||
|
| 'content.en';
|
||||||
|
|
||||||
|
export type DraftDocMeta = {
|
||||||
|
id: DraftDocId;
|
||||||
|
file: string;
|
||||||
|
kind: 'structure' | 'text';
|
||||||
|
lang?: Language;
|
||||||
|
};
|
||||||
|
|
||||||
|
// The six documents an edit session may write. `ui.{vi,en}.json` are shown
|
||||||
|
// read-only in the panel (§5.1) and never enter a draft.
|
||||||
|
export const DRAFT_DOCS: readonly DraftDocMeta[] = [
|
||||||
|
{ id: 'profile', file: 'src/data/profile.json', kind: 'structure' },
|
||||||
|
{ id: 'skills', file: 'src/data/skills.json', kind: 'structure' },
|
||||||
|
{ id: 'experience', file: 'src/data/experience.json', kind: 'structure' },
|
||||||
|
{ id: 'projects', file: 'src/data/projects.json', kind: 'structure' },
|
||||||
|
{ id: 'content.vi', file: 'src/i18n/locales/vi/content.json', kind: 'text', lang: 'vi' },
|
||||||
|
{ id: 'content.en', file: 'src/i18n/locales/en/content.json', kind: 'text', lang: 'en' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const PROXY_BASE = '/api/content/';
|
||||||
|
export const TYPES_FILE = 'src/types/index.ts';
|
||||||
|
|
||||||
|
export function proxyUrl(file: string, ref: string): string {
|
||||||
|
return `${PROXY_BASE}${file}?ref=${encodeURIComponent(ref)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- JSON paths -----------------------------------------------------------------
|
||||||
|
// A path is a dot-separated chain of object keys and [n] array indices, e.g.
|
||||||
|
// `projects.iot-dws-integration.sections.tldr.content` or
|
||||||
|
// `profile.tagline[2].text` — the same shape the EditBar and validator print.
|
||||||
|
|
||||||
|
export type PathSeg = string | number;
|
||||||
|
|
||||||
|
export function parsePath(path: string): PathSeg[] {
|
||||||
|
const out: PathSeg[] = [];
|
||||||
|
for (const m of path.matchAll(/([^.[\]]+)|\[(\d+)\]/g)) {
|
||||||
|
out.push(m[2] !== undefined ? Number(m[2]) : m[1]);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPath(root: unknown, segs: PathSeg[]): unknown {
|
||||||
|
let cur: unknown = root;
|
||||||
|
for (const seg of segs) {
|
||||||
|
if (cur === undefined || cur === null) return undefined;
|
||||||
|
cur = (cur as Record<PathSeg, unknown>)[seg];
|
||||||
|
}
|
||||||
|
return cur;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setPath(root: unknown, segs: PathSeg[], value: unknown): unknown {
|
||||||
|
if (segs.length === 0) return value;
|
||||||
|
const [head, ...rest] = segs;
|
||||||
|
const copy = (
|
||||||
|
Array.isArray(root) ? [...(root as unknown[])] : { ...(root as Record<PathSeg, unknown>) }
|
||||||
|
) as Record<PathSeg, unknown>;
|
||||||
|
copy[head] = rest.length === 0 ? value : setPath(copy[head], rest, value);
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deletePath(root: unknown, segs: PathSeg[]): unknown {
|
||||||
|
if (segs.length === 0) return undefined;
|
||||||
|
const [head, ...rest] = segs;
|
||||||
|
if (rest.length === 0) {
|
||||||
|
if (Array.isArray(root)) {
|
||||||
|
const copy = [...root];
|
||||||
|
copy.splice(Number(head), 1);
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
const copy = { ...(root as Record<PathSeg, unknown>) };
|
||||||
|
delete copy[head as string];
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
const copy = (
|
||||||
|
Array.isArray(root) ? [...(root as unknown[])] : { ...(root as Record<PathSeg, unknown>) }
|
||||||
|
) as Record<PathSeg, unknown>;
|
||||||
|
copy[head] = deletePath(copy[head], rest);
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isPlainObject = (v: unknown): v is Record<string, unknown> =>
|
||||||
|
typeof v === 'object' && v !== null && !Array.isArray(v);
|
||||||
|
|
||||||
|
// Leaf-level diff between a baseline document and its draft copy: object keys
|
||||||
|
// added or removed report the key itself, arrays whose length changed report
|
||||||
|
// the array path, everything else recurses to the differing leaf.
|
||||||
|
export function diffPaths(a: unknown, b: unknown, prefix = ''): string[] {
|
||||||
|
if (isPlainObject(a) && isPlainObject(b)) {
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
|
||||||
|
const child = prefix ? `${prefix}.${key}` : key;
|
||||||
|
if (a[key] === undefined || b[key] === undefined) {
|
||||||
|
out.push(child);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.push(...diffPaths(a[key], b[key], child));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (Array.isArray(a) && Array.isArray(b)) {
|
||||||
|
if (a.length !== b.length) return prefix ? [prefix] : [];
|
||||||
|
const out: string[] = [];
|
||||||
|
for (let i = 0; i < a.length; i++) {
|
||||||
|
out.push(...diffPaths(a[i], b[i], `${prefix}[${i}]`));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (a === b) return [];
|
||||||
|
return prefix ? [prefix] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- proxy transport -------------------------------------------------------------
|
||||||
|
|
||||||
|
export type DocBase = { data: unknown; sha: string };
|
||||||
|
|
||||||
|
function decodeBase64(b64: string): string {
|
||||||
|
const bin = atob(b64.replace(/\s+/g, ''));
|
||||||
|
const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
||||||
|
return new TextDecoder('utf-8').decode(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeBase64(text: string): string {
|
||||||
|
const bytes = new TextEncoder().encode(text);
|
||||||
|
let bin = '';
|
||||||
|
for (const b of bytes) bin += String.fromCharCode(b);
|
||||||
|
return btoa(bin);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchDoc(file: string, branch: string): Promise<DocBase> {
|
||||||
|
const res = await fetch(proxyUrl(file, branch));
|
||||||
|
if (!res.ok) throw new Error(`GET ${file}: ${res.status}`);
|
||||||
|
const json = (await res.json()) as { content?: string; last_commit_sha?: string };
|
||||||
|
return {
|
||||||
|
data: JSON.parse(decodeBase64(json.content ?? '')),
|
||||||
|
sha: String(json.last_commit_sha ?? ''),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchTextFile(file: string, branch: string): Promise<{ text: string; sha: string }> {
|
||||||
|
const res = await fetch(proxyUrl(file, branch));
|
||||||
|
if (!res.ok) throw new Error(`GET ${file}: ${res.status}`);
|
||||||
|
const json = (await res.json()) as { content?: string; last_commit_sha?: string };
|
||||||
|
return { text: decodeBase64(json.content ?? ''), sha: String(json.last_commit_sha ?? '') };
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PutResult = { ok: true; sha: string } | { ok: false; status: number };
|
||||||
|
|
||||||
|
async function putBase64(
|
||||||
|
file: string,
|
||||||
|
encoded: string,
|
||||||
|
message: string,
|
||||||
|
lastCommitSha: string,
|
||||||
|
branch: string,
|
||||||
|
): Promise<PutResult> {
|
||||||
|
const res = await fetch(proxyUrl(file, branch), {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
content: encoded,
|
||||||
|
message,
|
||||||
|
branch,
|
||||||
|
last_commit_sha: lastCommitSha,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
if (!res.ok) return { ok: false, status: res.status };
|
||||||
|
const json = (await res.json()) as { last_commit_sha?: string };
|
||||||
|
return { ok: true, sha: String(json.last_commit_sha ?? '') };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serialize exactly as the repository file is formatted (2-space indent, key
|
||||||
|
// order preserved from the parsed document) so Gitea diffs stay reviewable
|
||||||
|
// (§6.1).
|
||||||
|
export function putDoc(
|
||||||
|
file: string,
|
||||||
|
data: unknown,
|
||||||
|
message: string,
|
||||||
|
lastCommitSha: string,
|
||||||
|
branch: string,
|
||||||
|
): Promise<PutResult> {
|
||||||
|
return putBase64(file, encodeBase64(`${JSON.stringify(data, null, 2)}\n`), message, lastCommitSha, branch);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function putTextFile(
|
||||||
|
file: string,
|
||||||
|
text: string,
|
||||||
|
message: string,
|
||||||
|
lastCommitSha: string,
|
||||||
|
branch: string,
|
||||||
|
): Promise<PutResult> {
|
||||||
|
return putBase64(file, encodeBase64(text), message, lastCommitSha, branch);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Offline fallback (§5.1): the bundled build-time documents, flagged stale in
|
||||||
|
// the UI, save disabled — the draft is never initialized from a bundle that
|
||||||
|
// might be older than master when the proxy is reachable.
|
||||||
|
export function bundledBase(): Record<DraftDocId, DocBase> {
|
||||||
|
return {
|
||||||
|
profile: { data: structuredClone(profileJson), sha: '' },
|
||||||
|
skills: { data: structuredClone(skillsJson), sha: '' },
|
||||||
|
experience: { data: structuredClone(experienceJson), sha: '' },
|
||||||
|
projects: { data: structuredClone(projectsJson), sha: '' },
|
||||||
|
'content.vi': { data: structuredClone(contentViJson), sha: '' },
|
||||||
|
'content.en': { data: structuredClone(contentEnJson), sha: '' },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- id unions (§3.1) ------------------------------------------------------------
|
||||||
|
// Adding a content item is three edits: a union member, a structure record,
|
||||||
|
// its Vietnamese text. The editor does all three: after the content documents
|
||||||
|
// land, saveIdUnions appends the new ids to src/types/index.ts.
|
||||||
|
|
||||||
|
const UNION_SPECS: ReadonlyArray<{ union: string; ids: (s: ContentStructures) => string[] }> = [
|
||||||
|
{ union: 'ProjectId', ids: (s) => s.projects.map((p) => p.id) },
|
||||||
|
{ union: 'ExperienceId', ids: (s) => s.experience.map((e) => e.id) },
|
||||||
|
{ union: 'SkillGroupId', ids: (s) => s.skills.map((g) => g.id) },
|
||||||
|
{ union: 'PhilosophyId', ids: (s) => s.profile.philosophy.map((p) => p.id) },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function newIdsInCommitted(store: DraftStore, typesSource: string): { union: string; id: string }[] {
|
||||||
|
const structures = store.committedStructures();
|
||||||
|
const out: { union: string; id: string }[] = [];
|
||||||
|
for (const spec of UNION_SPECS) {
|
||||||
|
for (const id of spec.ids(structures)) {
|
||||||
|
if (!typesSource.includes(`'${id}'`)) out.push({ union: spec.union, id });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function patchUnionSource(source: string, union: string, id: string): string | null {
|
||||||
|
const marker = `export type ${union} =\n`;
|
||||||
|
const at = source.indexOf(marker);
|
||||||
|
if (at < 0) return null;
|
||||||
|
const insertAt = at + marker.length;
|
||||||
|
return `${source.slice(0, insertAt)} | '${id}'\n${source.slice(insertAt)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- the store ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
export type SavedDraft = {
|
||||||
|
docs: Record<string, unknown>;
|
||||||
|
baseShas: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
function uniqueId(base: string, taken: readonly string[]): string {
|
||||||
|
let id = base;
|
||||||
|
let n = 2;
|
||||||
|
while (taken.includes(id)) id = `${base}-${n++}`;
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class DraftStore {
|
||||||
|
private base = new Map<DraftDocId, DocBase>();
|
||||||
|
// The baseline the draft was taken against. `base` may be refreshed by a
|
||||||
|
// 412 conflict; `origin` never moves until a document lands, so a rebase
|
||||||
|
// can always tell my changes from theirs (§5.6).
|
||||||
|
private origin = new Map<DraftDocId, unknown>();
|
||||||
|
private working = new Map<DraftDocId, unknown>();
|
||||||
|
private changes = new Map<DraftDocId, string[]>;
|
||||||
|
|
||||||
|
constructor(bases: Record<DraftDocId, DocBase>) {
|
||||||
|
for (const meta of DRAFT_DOCS) {
|
||||||
|
this.base.set(meta.id, bases[meta.id]);
|
||||||
|
this.origin.set(meta.id, bases[meta.id].data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dataOf(id: DraftDocId): unknown {
|
||||||
|
return this.working.has(id) ? this.working.get(id) : this.base.get(id)!.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
shaOf(id: DraftDocId): string {
|
||||||
|
return this.base.get(id)!.sha;
|
||||||
|
}
|
||||||
|
|
||||||
|
touched(): DraftDocId[] {
|
||||||
|
return [...this.working.keys()];
|
||||||
|
}
|
||||||
|
|
||||||
|
changedPaths(id: DraftDocId): string[] {
|
||||||
|
return this.changes.get(id) ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
isDirty(): boolean {
|
||||||
|
return this.working.size > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
isPathDirty(path: string): boolean {
|
||||||
|
return this.touched().some((id) => this.changedPaths(id).includes(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
changedDocs(): { id: DraftDocId; paths: { path: string; before: unknown; after: unknown }[] }[] {
|
||||||
|
return this.touched().map((id) => ({
|
||||||
|
id,
|
||||||
|
paths: this.changedPaths(id).map((p) => ({
|
||||||
|
path: p,
|
||||||
|
before: getPath(this.base.get(id)!.data, parsePath(p)),
|
||||||
|
after: getPath(this.dataOf(id), parsePath(p)),
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
draftStructures(): ContentStructures {
|
||||||
|
return {
|
||||||
|
profile: this.dataOf('profile'),
|
||||||
|
skills: this.dataOf('skills'),
|
||||||
|
experience: this.dataOf('experience'),
|
||||||
|
projects: this.dataOf('projects'),
|
||||||
|
} as unknown as ContentStructures;
|
||||||
|
}
|
||||||
|
|
||||||
|
baseDataOf(id: DraftDocId): unknown {
|
||||||
|
return this.base.get(id)!.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Structures as they would exist in master after the already-written PUTs —
|
||||||
|
// the union patch only covers ids whose documents actually landed.
|
||||||
|
committedStructures(): ContentStructures {
|
||||||
|
const baseData = (id: DraftDocId) => this.base.get(id)!.data;
|
||||||
|
return {
|
||||||
|
profile: baseData('profile'),
|
||||||
|
skills: baseData('skills'),
|
||||||
|
experience: baseData('experience'),
|
||||||
|
projects: baseData('projects'),
|
||||||
|
} as unknown as ContentStructures;
|
||||||
|
}
|
||||||
|
|
||||||
|
draftTexts(): { vi: ContentVi; en: ContentEn } {
|
||||||
|
return {
|
||||||
|
vi: this.dataOf('content.vi') as ContentVi,
|
||||||
|
en: this.dataOf('content.en') as ContentEn,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
validate(): ContentIssue[] {
|
||||||
|
const texts = this.draftTexts();
|
||||||
|
return collectContentIssues(this.draftStructures(), texts.vi, texts.en);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inline text edit (§5.3): the value lands in the text document of the
|
||||||
|
// language being edited; missing en entries are created, vi paths always
|
||||||
|
// exist. Returns the validator issues when the candidate draft is invalid,
|
||||||
|
// leaving the store untouched.
|
||||||
|
setValue(lang: Language, path: string, value: string): ContentIssue[] | null {
|
||||||
|
const id: DraftDocId = lang === 'vi' ? 'content.vi' : 'content.en';
|
||||||
|
return this.tryApply(new Map([[id, setPath(this.dataOf(id), parsePath(path), value)]]));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Whole-document replacement from the JSON panel (§5.4).
|
||||||
|
setDocument(id: DraftDocId, data: unknown): ContentIssue[] | null {
|
||||||
|
return this.tryApply(new Map([[id, data]]));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Per-field revert (§5.3): restore the baseline value at this path in every
|
||||||
|
// touched text document; a path that was newly created is removed instead.
|
||||||
|
revertPath(path: string): ContentIssue[] | null {
|
||||||
|
const segs = parsePath(path);
|
||||||
|
let lastIssues: ContentIssue[] | null = null;
|
||||||
|
for (const id of ['content.vi', 'content.en'] as const) {
|
||||||
|
if (!this.changedPaths(id).includes(path)) continue;
|
||||||
|
const original = getPath(this.base.get(id)!.data, segs);
|
||||||
|
const current = this.dataOf(id);
|
||||||
|
const next =
|
||||||
|
original === undefined
|
||||||
|
? deletePath(current, segs)
|
||||||
|
: setPath(current, segs, original);
|
||||||
|
lastIssues = this.tryApply(new Map([[id, next]]));
|
||||||
|
}
|
||||||
|
return lastIssues;
|
||||||
|
}
|
||||||
|
|
||||||
|
discardDocument(id: DraftDocId): void {
|
||||||
|
this.working.delete(id);
|
||||||
|
this.changes.delete(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Templates and record deletes (§5.4): structure record and text entries
|
||||||
|
// are created or removed in one action — orphan text is never produced.
|
||||||
|
addRecord(
|
||||||
|
kind: 'project' | 'experience' | 'skill-group' | 'philosophy' | 'section',
|
||||||
|
options: { projectId?: string } = {},
|
||||||
|
): ContentIssue[] | null {
|
||||||
|
const candidates = new Map<DraftDocId, unknown>();
|
||||||
|
const vi = structuredClone(this.dataOf('content.vi')) as Record<string, any>;
|
||||||
|
const en = structuredClone(this.dataOf('content.en')) as Record<string, any>;
|
||||||
|
|
||||||
|
if (kind === 'project') {
|
||||||
|
const projects = structuredClone(this.dataOf('projects')) as Record<string, any>[];
|
||||||
|
const id = uniqueId('new-project', projects.map((p) => p.id));
|
||||||
|
projects.push({ id, category: 'experiment', role: 'Owner', technologies: [], featured: false, sections: [] });
|
||||||
|
candidates.set('projects', projects);
|
||||||
|
const stub = { title: 'New project', summary: 'Write the summary here.', sections: {} };
|
||||||
|
vi.projects = { ...vi.projects, [id]: structuredClone(stub) };
|
||||||
|
en.projects = { ...en.projects, [id]: structuredClone(stub) };
|
||||||
|
} else if (kind === 'experience') {
|
||||||
|
const experiences = structuredClone(this.dataOf('experience')) as Record<string, any>[];
|
||||||
|
const id = uniqueId('new-experience', experiences.map((e) => e.id));
|
||||||
|
experiences.push({ id, company: 'New company', duration: 'present' });
|
||||||
|
candidates.set('experience', experiences);
|
||||||
|
const stub = { title: 'New role', responsibilities: ['Write a responsibility here.'] };
|
||||||
|
vi.experience = { ...vi.experience, [id]: structuredClone(stub) };
|
||||||
|
en.experience = { ...en.experience, [id]: structuredClone(stub) };
|
||||||
|
} else if (kind === 'skill-group') {
|
||||||
|
const groups = structuredClone(this.dataOf('skills')) as Record<string, any>[];
|
||||||
|
const id = uniqueId('new-skill-group', groups.map((g) => g.id));
|
||||||
|
groups.push({ id, skills: ['New skill'] });
|
||||||
|
candidates.set('skills', groups);
|
||||||
|
vi.skills = { ...vi.skills, [id]: { title: 'New skill group' } };
|
||||||
|
en.skills = { ...en.skills, [id]: { title: 'New skill group' } };
|
||||||
|
} else if (kind === 'philosophy') {
|
||||||
|
const profile = structuredClone(this.dataOf('profile')) as Record<string, any>;
|
||||||
|
const points = profile.philosophy as Record<string, any>[];
|
||||||
|
const id = uniqueId('new-philosophy-point', points.map((p) => p.id));
|
||||||
|
points.push({ id, keywords: ['new-keyword'] });
|
||||||
|
candidates.set('profile', profile);
|
||||||
|
const stub = { title: 'New principle', description: 'Write the principle here.' };
|
||||||
|
vi.profile = { ...vi.profile, philosophy: { ...vi.profile.philosophy, [id]: structuredClone(stub) } };
|
||||||
|
en.profile = { ...en.profile, philosophy: { ...en.profile.philosophy, [id]: structuredClone(stub) } };
|
||||||
|
} else {
|
||||||
|
const projectId = options.projectId;
|
||||||
|
if (!projectId) return [{ path: 'projects.json', message: 'pick a project first' }];
|
||||||
|
const projects = structuredClone(this.dataOf('projects')) as Record<string, any>[];
|
||||||
|
const project = projects.find((p) => p.id === projectId);
|
||||||
|
if (!project) return [{ path: 'projects.json', message: `no project ${projectId}` }];
|
||||||
|
const sectionId = uniqueId('new-section', (project.sections as Record<string, any>[]).map((s) => s.id));
|
||||||
|
project.sections = [...project.sections, { id: sectionId, type: 'text' }];
|
||||||
|
candidates.set('projects', projects);
|
||||||
|
const stub = { title: 'New section', content: 'Write the section here.' };
|
||||||
|
for (const texts of [vi, en]) {
|
||||||
|
const text = texts.projects[projectId] as Record<string, any>;
|
||||||
|
texts.projects = {
|
||||||
|
...texts.projects,
|
||||||
|
[projectId]: { ...text, sections: { ...text.sections, [sectionId]: structuredClone(stub) } },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
candidates.set('content.vi', vi);
|
||||||
|
candidates.set('content.en', en);
|
||||||
|
return this.tryApply(candidates);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete removes the record's text entries from both language documents in
|
||||||
|
// the same action — the validator can never see orphan text (§5.4).
|
||||||
|
deleteRecord(
|
||||||
|
kind: 'project' | 'experience' | 'skill-group' | 'philosophy' | 'section',
|
||||||
|
ids: { id: string; projectId?: string },
|
||||||
|
): ContentIssue[] | null {
|
||||||
|
const candidates = new Map<DraftDocId, unknown>();
|
||||||
|
|
||||||
|
const dropFromTexts = (mutate: (doc: Record<string, any>) => void) => {
|
||||||
|
for (const id of ['content.vi', 'content.en'] as const) {
|
||||||
|
const doc = structuredClone(this.dataOf(id)) as Record<string, any>;
|
||||||
|
mutate(doc);
|
||||||
|
candidates.set(id, doc);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (kind === 'project') {
|
||||||
|
const projects = (this.dataOf('projects') as Record<string, any>[]).filter((p) => p.id !== ids.id);
|
||||||
|
candidates.set('projects', projects);
|
||||||
|
dropFromTexts((doc) => {
|
||||||
|
delete doc.projects[ids.id];
|
||||||
|
});
|
||||||
|
} else if (kind === 'experience') {
|
||||||
|
candidates.set('experience', (this.dataOf('experience') as Record<string, any>[]).filter((e) => e.id !== ids.id));
|
||||||
|
dropFromTexts((doc) => {
|
||||||
|
delete doc.experience[ids.id];
|
||||||
|
});
|
||||||
|
} else if (kind === 'skill-group') {
|
||||||
|
candidates.set('skills', (this.dataOf('skills') as Record<string, any>[]).filter((g) => g.id !== ids.id));
|
||||||
|
dropFromTexts((doc) => {
|
||||||
|
delete doc.skills[ids.id];
|
||||||
|
});
|
||||||
|
} else if (kind === 'philosophy') {
|
||||||
|
const profile = structuredClone(this.dataOf('profile')) as Record<string, any>;
|
||||||
|
profile.philosophy = (profile.philosophy as Record<string, any>[]).filter((p) => p.id !== ids.id);
|
||||||
|
candidates.set('profile', profile);
|
||||||
|
dropFromTexts((doc) => {
|
||||||
|
delete doc.profile.philosophy[ids.id];
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const projectId = ids.projectId;
|
||||||
|
if (!projectId || !ids.id) return [{ path: 'projects.json', message: 'pick a project and section first' }];
|
||||||
|
const projects = structuredClone(this.dataOf('projects')) as Record<string, any>[];
|
||||||
|
const project = projects.find((p) => p.id === projectId);
|
||||||
|
if (!project) return [{ path: 'projects.json', message: `no project ${projectId}` }];
|
||||||
|
project.sections = (project.sections as Record<string, any>[]).filter((s) => s.id !== ids.id);
|
||||||
|
candidates.set('projects', projects);
|
||||||
|
dropFromTexts((doc) => {
|
||||||
|
const text = doc.projects[projectId];
|
||||||
|
if (text) text.sections = { ...text.sections };
|
||||||
|
delete text?.sections[ids.id];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return this.tryApply(candidates);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply candidate documents atomically: replace, recompute changed paths,
|
||||||
|
// run the full cross-document validator, roll every document back when the
|
||||||
|
// candidate draft is invalid (§5.4 — an invalid draft never reaches the
|
||||||
|
// preview). A document that ends up equal to its baseline stops being
|
||||||
|
// touched, so save only ever PUTs documents that actually differ.
|
||||||
|
private tryApply(candidates: Map<DraftDocId, unknown>): ContentIssue[] | null {
|
||||||
|
const undo: [DraftDocId, boolean, unknown, string[] | undefined][] = [];
|
||||||
|
for (const [id, data] of candidates) {
|
||||||
|
undo.push([id, this.working.has(id), this.working.get(id), this.changes.get(id)]);
|
||||||
|
this.working.set(id, data);
|
||||||
|
this.refreshChanges(id);
|
||||||
|
}
|
||||||
|
const issues = this.validate();
|
||||||
|
if (issues.length > 0) {
|
||||||
|
for (const [id, had, prev, prevChanges] of undo) {
|
||||||
|
if (had) {
|
||||||
|
this.working.set(id, prev);
|
||||||
|
if (prevChanges) this.changes.set(id, prevChanges);
|
||||||
|
} else {
|
||||||
|
this.working.delete(id);
|
||||||
|
this.changes.delete(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return issues;
|
||||||
|
}
|
||||||
|
for (const id of candidates.keys()) {
|
||||||
|
if (JSON.stringify(this.dataOf(id)) === JSON.stringify(this.base.get(id)!.data)) {
|
||||||
|
this.working.delete(id);
|
||||||
|
this.changes.delete(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private refreshChanges(id: DraftDocId): void {
|
||||||
|
const diff = diffPaths(this.base.get(id)!.data, this.working.get(id));
|
||||||
|
if (diff.length > 0) this.changes.set(id, diff);
|
||||||
|
else this.changes.delete(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- persistence (§5.2) ---
|
||||||
|
|
||||||
|
snapshot(): SavedDraft {
|
||||||
|
const docs: Record<string, unknown> = {};
|
||||||
|
for (const [id, data] of this.working) docs[id] = data;
|
||||||
|
const baseShas: Record<string, string> = {};
|
||||||
|
for (const [id, meta] of this.base) baseShas[id] = meta.sha;
|
||||||
|
return { docs, baseShas };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Re-apply a persisted draft onto freshly fetched baselines. A document
|
||||||
|
// whose last_commit_sha moved since the draft was taken is returned as
|
||||||
|
// drifted → the conflict flow (§5.6) owns it from here.
|
||||||
|
applySaved(saved: SavedDraft): DraftDocId[] {
|
||||||
|
const drifted: DraftDocId[] = [];
|
||||||
|
for (const [idStr, data] of Object.entries(saved.docs)) {
|
||||||
|
const id = idStr as DraftDocId;
|
||||||
|
if (!DRAFT_DOCS.some((d) => d.id === id)) continue;
|
||||||
|
const savedSha = saved.baseShas[id] ?? '';
|
||||||
|
const liveSha = this.shaOf(id);
|
||||||
|
if (savedSha && savedSha !== liveSha) drifted.push(id);
|
||||||
|
this.working.set(id, data);
|
||||||
|
this.refreshChanges(id);
|
||||||
|
}
|
||||||
|
return drifted;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- save pipeline (§5.6, §6.1) ---
|
||||||
|
|
||||||
|
markWritten(id: DraftDocId, newSha: string): void {
|
||||||
|
const data = this.dataOf(id);
|
||||||
|
this.base.set(id, { data, sha: newSha });
|
||||||
|
this.origin.set(id, data);
|
||||||
|
this.working.delete(id);
|
||||||
|
this.changes.delete(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
resetBase(id: DraftDocId, fresh: DocBase): void {
|
||||||
|
this.base.set(id, fresh);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rebase (§5.6): a real three-way merge of origin → mine against origin →
|
||||||
|
// theirs. Paths only I touched replay onto the refreshed base; a path both
|
||||||
|
// sides changed differently is a conflict the store refuses to resolve —
|
||||||
|
// the caller falls back to take-theirs or hand-merge.
|
||||||
|
rebase(id: DraftDocId): ContentIssue[] | null {
|
||||||
|
const origin = this.origin.get(id)!;
|
||||||
|
const theirs = this.base.get(id)!.data;
|
||||||
|
const mine = this.dataOf(id);
|
||||||
|
const myPaths = diffPaths(origin, mine);
|
||||||
|
const theirPaths = new Set(diffPaths(origin, theirs));
|
||||||
|
const clashes = myPaths.filter(
|
||||||
|
(p) =>
|
||||||
|
theirPaths.has(p) &&
|
||||||
|
JSON.stringify(getPath(mine, parsePath(p))) !== JSON.stringify(getPath(theirs, parsePath(p))),
|
||||||
|
);
|
||||||
|
if (clashes.length > 0) {
|
||||||
|
return clashes.map((p) => ({
|
||||||
|
path: p,
|
||||||
|
message: 'changed both locally and in master — hand-merge or take theirs',
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
let data = theirs;
|
||||||
|
for (const p of myPaths) {
|
||||||
|
const value = getPath(mine, parsePath(p));
|
||||||
|
if (value !== undefined) data = setPath(data, parsePath(p), value);
|
||||||
|
}
|
||||||
|
const issues = this.tryApply(new Map([[id, data]]));
|
||||||
|
if (issues === null) this.origin.set(id, theirs);
|
||||||
|
return issues;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- save pipeline -----------------------------------------------------------------
|
||||||
|
|
||||||
|
export type DocSaveResult = {
|
||||||
|
id: DraftDocId;
|
||||||
|
status: 'written' | 'conflict' | 'failed';
|
||||||
|
http?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Sequential PUTs, one commit per touched document (§6.1). A 412 refreshes
|
||||||
|
// that document's base and reports a conflict without stopping the sequence;
|
||||||
|
// any other failure stops so a retry resumes from the first unwritten
|
||||||
|
// document — landed documents are never rewritten (§5.6).
|
||||||
|
export async function saveDraft(
|
||||||
|
store: DraftStore,
|
||||||
|
onResult: (result: DocSaveResult) => void,
|
||||||
|
branch: string,
|
||||||
|
): Promise<{ results: DocSaveResult[]; stoppedEarly: boolean }> {
|
||||||
|
const results: DocSaveResult[] = [];
|
||||||
|
for (const id of store.touched()) {
|
||||||
|
const meta = DRAFT_DOCS.find((d) => d.id === id)!;
|
||||||
|
const paths = store.changedPaths(id);
|
||||||
|
const message = `content: ${paths[0] ?? meta.file} (${paths.length} path${paths.length === 1 ? '' : 's'})`;
|
||||||
|
const res = await putDoc(meta.file, store.dataOf(id), message, store.shaOf(id), branch);
|
||||||
|
if (res.ok) {
|
||||||
|
store.markWritten(id, res.sha);
|
||||||
|
const result: DocSaveResult = { id, status: 'written' };
|
||||||
|
results.push(result);
|
||||||
|
onResult(result);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (res.status === 412) {
|
||||||
|
try {
|
||||||
|
store.resetBase(id, await fetchDoc(meta.file, branch));
|
||||||
|
} catch {
|
||||||
|
// keep the old base; the conflict UI still offers take-theirs
|
||||||
|
}
|
||||||
|
const result: DocSaveResult = { id, status: 'conflict', http: 412 };
|
||||||
|
results.push(result);
|
||||||
|
onResult(result);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const result: DocSaveResult = { id, status: 'failed', http: res.status };
|
||||||
|
results.push(result);
|
||||||
|
onResult(result);
|
||||||
|
return { results, stoppedEarly: true };
|
||||||
|
}
|
||||||
|
return { results, stoppedEarly: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
// The third leg of §3.1: once the documents that introduce new ids have
|
||||||
|
// landed, append those ids to their unions in src/types/index.ts so the next
|
||||||
|
// CI build compiles. Returns the updated source/sha, or null when the patch
|
||||||
|
// could not be written (the EditBar reports it and the owner finishes the
|
||||||
|
// edit in Gitea).
|
||||||
|
export async function saveIdUnions(
|
||||||
|
store: DraftStore,
|
||||||
|
types: { source: string; sha: string },
|
||||||
|
branch: string,
|
||||||
|
): Promise<{ added: { union: string; id: string }[]; source?: string; sha?: string; failed?: number } | null> {
|
||||||
|
const added = newIdsInCommitted(store, types.source);
|
||||||
|
if (added.length === 0) return null;
|
||||||
|
let source = types.source;
|
||||||
|
for (const { union, id } of added) {
|
||||||
|
const patched = patchUnionSource(source, union, id);
|
||||||
|
if (!patched) return { added, failed: 0 };
|
||||||
|
source = patched;
|
||||||
|
}
|
||||||
|
const message = `content: add id union members (${added.map((a) => a.id).join(', ')})`;
|
||||||
|
const res = await putTextFile(TYPES_FILE, source, message, types.sha, branch);
|
||||||
|
if (!res.ok) return { added, failed: res.status };
|
||||||
|
return { added, source, sha: res.sha };
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
// Edit-mode session mechanics (spec-v4 §5.2, §6.2): the `?edit` entry, the
|
||||||
|
// sessionStorage flags that keep a session in the mode across reloads, the
|
||||||
|
// target branch (`?edit=<branch>`), and the Basic-auth handshake through the
|
||||||
|
// protected proxy endpoint. The protected endpoint is the security boundary —
|
||||||
|
// edit mode is only a UI affordance.
|
||||||
|
import { PROXY_BASE } from './draft';
|
||||||
|
|
||||||
|
const EDIT_FLAG = 'portfolio-edit';
|
||||||
|
const BRANCH_FLAG = 'portfolio-edit-branch';
|
||||||
|
export const DRAFT_STORAGE = 'portfolio-draft';
|
||||||
|
|
||||||
|
// The repository's default branch — what a bare `?edit` targets.
|
||||||
|
export const DEFAULT_BRANCH = 'master';
|
||||||
|
|
||||||
|
const PROBE_FILE = 'src/data/profile.json';
|
||||||
|
|
||||||
|
// Git's own ref rules, reduced to what a working branch name can be: no
|
||||||
|
// leading '-' or '/', no '..', no '//', no trailing '/', no `.lock` suffix,
|
||||||
|
// and only characters safe in a URL query value.
|
||||||
|
const BRANCH_RE = /^(?!-)(?!\/)(?!.*\.\.)(?!.*\/\/)(?!.*\.lock$)(?!.*\/$)[A-Za-z0-9][A-Za-z0-9._/-]{0,63}$/;
|
||||||
|
|
||||||
|
export function editRequested(search: string): boolean {
|
||||||
|
return new URLSearchParams(search).has('edit');
|
||||||
|
}
|
||||||
|
|
||||||
|
// `?edit` or `?edit=1` → undefined (fall back to the session's branch, or
|
||||||
|
// the default); `?edit=<branch>` → that branch; an illegal name → null (the
|
||||||
|
// shell exits edit mode the same way it does on a failed auth).
|
||||||
|
export function requestedBranch(search: string): string | null | undefined {
|
||||||
|
const value = new URLSearchParams(search).get('edit');
|
||||||
|
if (!value || value === '1') return undefined;
|
||||||
|
return BRANCH_RE.test(value) ? value : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getEditBranch(): string {
|
||||||
|
const saved = sessionStorage.getItem(BRANCH_FLAG);
|
||||||
|
return saved && BRANCH_RE.test(saved) ? saved : DEFAULT_BRANCH;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setEditBranch(branch: string): void {
|
||||||
|
sessionStorage.setItem(BRANCH_FLAG, branch);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasEditFlag(): boolean {
|
||||||
|
return sessionStorage.getItem(EDIT_FLAG) === '1';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setEditFlag(on: boolean): void {
|
||||||
|
if (on) sessionStorage.setItem(EDIT_FLAG, '1');
|
||||||
|
else {
|
||||||
|
sessionStorage.removeItem(EDIT_FLAG);
|
||||||
|
sessionStorage.removeItem(BRANCH_FLAG);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearDraftStorage(): void {
|
||||||
|
sessionStorage.removeItem(DRAFT_STORAGE);
|
||||||
|
}
|
||||||
|
|
||||||
|
function probeUrl(branch: string, cacheBust: boolean): string {
|
||||||
|
const url = new URL(`${PROXY_BASE}${PROBE_FILE}`, window.location.origin);
|
||||||
|
url.searchParams.set('ref', branch);
|
||||||
|
if (cacheBust) url.searchParams.set('probe', String(Date.now()));
|
||||||
|
return url.pathname + url.search;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkAuth(branch: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const res = await fetch(probeUrl(branch, false));
|
||||||
|
return res.ok;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function probeEditorAuth(branch: string): Promise<boolean> {
|
||||||
|
const { promise, resolve } = Promise.withResolvers<boolean>();
|
||||||
|
const iframe = document.createElement('iframe');
|
||||||
|
iframe.style.display = 'none';
|
||||||
|
let settled = false;
|
||||||
|
const settle = (ok: boolean) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
iframe.remove();
|
||||||
|
resolve(ok);
|
||||||
|
};
|
||||||
|
iframe.onload = () => {
|
||||||
|
void checkAuth(branch).then(settle);
|
||||||
|
};
|
||||||
|
iframe.src = probeUrl(branch, true);
|
||||||
|
document.body.appendChild(iframe);
|
||||||
|
return promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A session that already holds the flag re-checks silently first: the browser
|
||||||
|
// re-attaches cached Basic credentials on its own, so no prompt appears again
|
||||||
|
// unless the cache is gone (new tab) — then the probe runs as on first entry.
|
||||||
|
export async function ensureEditorAuth(branch: string): Promise<boolean> {
|
||||||
|
if (hasEditFlag()) {
|
||||||
|
const cached = await checkAuth(branch);
|
||||||
|
if (cached) return true;
|
||||||
|
}
|
||||||
|
return probeEditorAuth(branch);
|
||||||
|
}
|
||||||
+20
-7
@@ -25,6 +25,7 @@ import type {
|
|||||||
} from './dict-types';
|
} from './dict-types';
|
||||||
import type { Language, PhilosophyId } from '../types/index';
|
import type { Language, PhilosophyId } from '../types/index';
|
||||||
import { validateContent } from './validate';
|
import { validateContent } from './validate';
|
||||||
|
import type { ContentStructures } from './validate';
|
||||||
|
|
||||||
const uiVi: UIDict = uiViJson;
|
const uiVi: UIDict = uiViJson;
|
||||||
// tsc enforces en completeness against the derived Vietnamese tree (§3.3).
|
// tsc enforces en completeness against the derived Vietnamese tree (§3.3).
|
||||||
@@ -65,8 +66,6 @@ function deepMerge<T>(base: T, patch: unknown): T {
|
|||||||
return out as T;
|
return out as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
const mergedEn: ContentVi = deepMerge(contentVi, contentEn);
|
|
||||||
|
|
||||||
export const UI: Record<Language, UIDict> = { vi: uiVi, en: uiEn };
|
export const UI: Record<Language, UIDict> = { vi: uiVi, en: uiEn };
|
||||||
|
|
||||||
// Resolved records: structure joined with text. These are the shapes every
|
// Resolved records: structure joined with text. These are the shapes every
|
||||||
@@ -97,7 +96,7 @@ export type ResolvedContent = {
|
|||||||
projects: ResolvedProject[];
|
projects: ResolvedProject[];
|
||||||
};
|
};
|
||||||
|
|
||||||
function joinContent(text: ContentVi): ResolvedContent {
|
function joinContent(structures: ContentStructures, text: ContentVi): ResolvedContent {
|
||||||
return {
|
return {
|
||||||
profile: {
|
profile: {
|
||||||
...structures.profile,
|
...structures.profile,
|
||||||
@@ -130,7 +129,21 @@ function joinContent(text: ContentVi): ResolvedContent {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export const CONTENT: Record<Language, ResolvedContent> = {
|
// Resolve one pair of text documents against one set of structure documents.
|
||||||
vi: joinContent(contentVi),
|
// The Phase 1 constant below is the bundled answer; the edit-mode draft store
|
||||||
en: joinContent(mergedEn),
|
// (src/i18n/draft.ts) calls this on every accepted edit to rebuild the
|
||||||
};
|
// provider override — same join, same fallback rules, draft documents in.
|
||||||
|
export function resolveContent(
|
||||||
|
structures: ContentStructures,
|
||||||
|
vi: ContentVi,
|
||||||
|
en: ContentEn,
|
||||||
|
): Record<Language, ResolvedContent> {
|
||||||
|
const mergedEn: ContentVi = deepMerge(vi, en);
|
||||||
|
return { vi: joinContent(structures, vi), en: joinContent(structures, mergedEn) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CONTENT: Record<Language, ResolvedContent> = resolveContent(
|
||||||
|
structures,
|
||||||
|
contentVi,
|
||||||
|
contentEn,
|
||||||
|
);
|
||||||
@@ -124,5 +124,66 @@
|
|||||||
"PROJECTS": "Projects",
|
"PROJECTS": "Projects",
|
||||||
"UPDATED": "Last updated",
|
"UPDATED": "Last updated",
|
||||||
"QR_ALT": "QR code"
|
"QR_ALT": "QR code"
|
||||||
|
},
|
||||||
|
"edit": {
|
||||||
|
"title": "Edit mode",
|
||||||
|
"changes": "Unsaved changes",
|
||||||
|
"noChanges": "No unsaved changes",
|
||||||
|
"openPanel": "JSON panel",
|
||||||
|
"closePanel": "Close panel",
|
||||||
|
"save": "Save",
|
||||||
|
"saving": "Saving…",
|
||||||
|
"resume": "Resume save",
|
||||||
|
"exit": "Exit",
|
||||||
|
"exitConfirm": "Discard unsaved changes?",
|
||||||
|
"changesTitle": "Changes",
|
||||||
|
"discardDoc": "Discard document",
|
||||||
|
"revert": "Revert",
|
||||||
|
"conflicts": "Conflicts",
|
||||||
|
"conflictDetail": "changed externally after this draft was taken",
|
||||||
|
"rebase": "Rebase",
|
||||||
|
"takeTheirs": "Take theirs",
|
||||||
|
"handMerge": "Hand-merge",
|
||||||
|
"written": "written",
|
||||||
|
"conflictStatus": "conflict",
|
||||||
|
"failed": "failed",
|
||||||
|
"deployQueued": "deploy queued — the change goes live after the pipeline finishes",
|
||||||
|
"branchLabel": "target branch",
|
||||||
|
"mergeHint": "written to the branch — merge into master to deploy",
|
||||||
|
"offline": "offline — showing bundled content, save disabled",
|
||||||
|
"draftRestored": "draft restored from this session",
|
||||||
|
"unionNote": "new ids are also appended to src/types/index.ts",
|
||||||
|
"unionFailed": "could not update src/types/index.ts — finish that edit in Gitea",
|
||||||
|
"panel": {
|
||||||
|
"title": "Content documents",
|
||||||
|
"readOnly": "read-only",
|
||||||
|
"valid": "valid",
|
||||||
|
"invalid": "invalid",
|
||||||
|
"parseError": "JSON error",
|
||||||
|
"addProject": "Add project",
|
||||||
|
"addExperience": "Add experience",
|
||||||
|
"addSkillGroup": "Add skill group",
|
||||||
|
"addPhilosophy": "Add philosophy point",
|
||||||
|
"addSection": "Add section",
|
||||||
|
"projectLabel": "project",
|
||||||
|
"deleteRecord": "Delete",
|
||||||
|
"deleteConfirm": "Delete this record and its text in both languages?",
|
||||||
|
"baseLabel": "live master",
|
||||||
|
"draftLabel": "draft",
|
||||||
|
"applyMerge": "Apply merged draft"
|
||||||
|
},
|
||||||
|
"fields": {
|
||||||
|
"title": "title",
|
||||||
|
"summary": "summary",
|
||||||
|
"bio": "bio",
|
||||||
|
"tagline": "tagline segment",
|
||||||
|
"groupTitle": "skill group title",
|
||||||
|
"expTitle": "role title",
|
||||||
|
"responsibility": "responsibility",
|
||||||
|
"sectionTitle": "section title",
|
||||||
|
"sectionContent": "section content",
|
||||||
|
"pointTitle": "philosophy title",
|
||||||
|
"pointDescription": "philosophy description"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,5 +124,66 @@
|
|||||||
"PROJECTS": "Dự án",
|
"PROJECTS": "Dự án",
|
||||||
"UPDATED": "Cập nhật lần cuối",
|
"UPDATED": "Cập nhật lần cuối",
|
||||||
"QR_ALT": "mã QR"
|
"QR_ALT": "mã QR"
|
||||||
|
},
|
||||||
|
"edit": {
|
||||||
|
"title": "Chế độ sửa",
|
||||||
|
"changes": "Thay đổi chưa lưu",
|
||||||
|
"noChanges": "Không có thay đổi chưa lưu",
|
||||||
|
"openPanel": "Bảng JSON",
|
||||||
|
"closePanel": "Đóng bảng",
|
||||||
|
"save": "Lưu",
|
||||||
|
"saving": "Đang lưu…",
|
||||||
|
"resume": "Tiếp tục lưu",
|
||||||
|
"exit": "Thoát",
|
||||||
|
"exitConfirm": "Hủy các thay đổi chưa lưu?",
|
||||||
|
"changesTitle": "Changes",
|
||||||
|
"discardDoc": "Bỏ tài liệu",
|
||||||
|
"revert": "Hoàn tác",
|
||||||
|
"conflicts": "Xung đột",
|
||||||
|
"conflictDetail": "đã bị sửa từ ngoài sau khi bản nháp này được tạo",
|
||||||
|
"rebase": "Rebase",
|
||||||
|
"takeTheirs": "Lấy bản gốc",
|
||||||
|
"handMerge": "Tự hợp nhất",
|
||||||
|
"written": "đã ghi",
|
||||||
|
"conflictStatus": "xung đột",
|
||||||
|
"failed": "thất bại",
|
||||||
|
"deployQueued": "đã xếp lịch deploy — nội dung lên site sau khi pipeline chạy xong",
|
||||||
|
"branchLabel": "branch đích",
|
||||||
|
"mergeHint": "đã ghi lên branch — merge vào master để deploy",
|
||||||
|
"offline": "ngoại tuyến — đang hiển thị nội dung đóng gói, không lưu được",
|
||||||
|
"draftRestored": "bản nháp đã khôi phục từ phiên này",
|
||||||
|
"unionNote": "id mới cũng được thêm vào src/types/index.ts",
|
||||||
|
"unionFailed": "không cập nhật được src/types/index.ts — hãy hoàn tất sửa trong Gitea",
|
||||||
|
"panel": {
|
||||||
|
"title": "Tài liệu nội dung",
|
||||||
|
"readOnly": "chỉ đọc",
|
||||||
|
"valid": "hợp lệ",
|
||||||
|
"invalid": "không hợp lệ",
|
||||||
|
"parseError": "Lỗi JSON",
|
||||||
|
"addProject": "Thêm dự án",
|
||||||
|
"addExperience": "Thêm kinh nghiệm",
|
||||||
|
"addSkillGroup": "Thêm nhóm kỹ năng",
|
||||||
|
"addPhilosophy": "Thêm nguyên lý",
|
||||||
|
"addSection": "Thêm mục",
|
||||||
|
"projectLabel": "dự án",
|
||||||
|
"deleteRecord": "Xóa",
|
||||||
|
"deleteConfirm": "Xóa bản ghi này và text của cả hai ngôn ngữ?",
|
||||||
|
"baseLabel": "bản master",
|
||||||
|
"draftLabel": "bản nháp",
|
||||||
|
"applyMerge": "Áp dụng bản hợp nhất"
|
||||||
|
},
|
||||||
|
"fields": {
|
||||||
|
"title": "tiêu đề",
|
||||||
|
"summary": "tóm tắt",
|
||||||
|
"bio": "giới thiệu",
|
||||||
|
"tagline": "đoạn tagline",
|
||||||
|
"groupTitle": "tiêu đề nhóm kỹ năng",
|
||||||
|
"expTitle": "tên vị trí",
|
||||||
|
"responsibility": "trách nhiệm",
|
||||||
|
"sectionTitle": "tiêu đề mục",
|
||||||
|
"sectionContent": "nội dung mục",
|
||||||
|
"pointTitle": "tiêu đề nguyên lý",
|
||||||
|
"pointDescription": "mô tả nguyên lý"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -26,6 +26,20 @@ export type ContentStructures = {
|
|||||||
|
|
||||||
const hasHtml = (value: string) => value.includes('<') || value.includes('>');
|
const hasHtml = (value: string) => value.includes('<') || value.includes('>');
|
||||||
|
|
||||||
|
// Walks every string value of a text document, collecting the document paths
|
||||||
|
// of empty strings — an empty required value is a half-finished edit, never
|
||||||
|
// content (rule 6). Mirrors the walk in findHtmlStrings.
|
||||||
|
function findEmptyStrings(value: unknown, docPath: string): string[] {
|
||||||
|
if (typeof value === 'string') return value.trim() === '' ? [docPath] : [];
|
||||||
|
if (Array.isArray(value))
|
||||||
|
return value.flatMap((item, i) => findEmptyStrings(item, `${docPath}[${i}]`));
|
||||||
|
if (value && typeof value === 'object')
|
||||||
|
return Object.entries(value).flatMap(([key, item]) =>
|
||||||
|
findEmptyStrings(item, `${docPath}.${key}`),
|
||||||
|
);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
// Walks every string value of a text document, collecting its document path.
|
// Walks every string value of a text document, collecting its document path.
|
||||||
function findHtmlStrings(value: unknown, docPath: string): string[] {
|
function findHtmlStrings(value: unknown, docPath: string): string[] {
|
||||||
if (typeof value === 'string') return hasHtml(value) ? [docPath] : [];
|
if (typeof value === 'string') return hasHtml(value) ? [docPath] : [];
|
||||||
@@ -128,6 +142,15 @@ export function collectContentIssues(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Rule 6: no empty text values in either language document. Every string in
|
||||||
|
// a text document is a required field; the editor rejects an empty commit
|
||||||
|
// with exactly this rule, and CI keeps an emptied field out of master.
|
||||||
|
for (const [lang, doc] of [['vi', vi], ['en', en]] as const) {
|
||||||
|
for (const path of findEmptyStrings(doc, `content.${lang}.json`)) {
|
||||||
|
issues.push({ path, message: 'empty text value' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return issues;
|
return issues;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+18
-5
@@ -2,6 +2,7 @@ import { motion } from 'motion/react'
|
|||||||
import { SectionHeading } from '@/components/ui/SectionHeading'
|
import { SectionHeading } from '@/components/ui/SectionHeading'
|
||||||
import { Tag } from '@/components/ui/Tag'
|
import { Tag } from '@/components/ui/Tag'
|
||||||
import { InView } from '@/components/ui/InView'
|
import { InView } from '@/components/ui/InView'
|
||||||
|
import { EditableText } from '@/components/ui/EditableText'
|
||||||
import { useI18n } from '@/i18n/provider'
|
import { useI18n } from '@/i18n/provider'
|
||||||
|
|
||||||
export function AboutPage() {
|
export function AboutPage() {
|
||||||
@@ -25,9 +26,15 @@ export function AboutPage() {
|
|||||||
subtitle={s.about.subtitle}
|
subtitle={s.about.subtitle}
|
||||||
tag={s.about.heading}
|
tag={s.about.heading}
|
||||||
/>
|
/>
|
||||||
<p className="prose-lede lede-wide">
|
<EditableText
|
||||||
|
as="p"
|
||||||
|
className="prose-lede lede-wide"
|
||||||
|
path="profile.bio"
|
||||||
|
label={s.edit.fields.bio}
|
||||||
|
multiline
|
||||||
|
>
|
||||||
{c.profile.bio}
|
{c.profile.bio}
|
||||||
</p>
|
</EditableText>
|
||||||
|
|
||||||
<h3 className="subheading">
|
<h3 className="subheading">
|
||||||
{s.about.engineeringTitle}
|
{s.about.engineeringTitle}
|
||||||
@@ -44,8 +51,12 @@ export function AboutPage() {
|
|||||||
whileHover={{ scale: 1.02, y: -4 }}
|
whileHover={{ scale: 1.02, y: -4 }}
|
||||||
whileTap={{ scale: 0.98 }}
|
whileTap={{ scale: 0.98 }}
|
||||||
>
|
>
|
||||||
<h3>{point.title}</h3>
|
<EditableText as="h3" path={`profile.philosophy.${point.id}.title`} label={s.edit.fields.pointTitle}>
|
||||||
<p>{point.description}</p>
|
{point.title}
|
||||||
|
</EditableText>
|
||||||
|
<EditableText as="p" path={`profile.philosophy.${point.id}.description`} label={s.edit.fields.pointDescription} multiline>
|
||||||
|
{point.description}
|
||||||
|
</EditableText>
|
||||||
<div className="philosophy-keywords">
|
<div className="philosophy-keywords">
|
||||||
{point.keywords.map((kw) => (
|
{point.keywords.map((kw) => (
|
||||||
<Tag key={kw}>{kw}</Tag>
|
<Tag key={kw}>{kw}</Tag>
|
||||||
@@ -92,7 +103,9 @@ export function AboutPage() {
|
|||||||
whileHover={{ scale: 1.02, y: -4 }}
|
whileHover={{ scale: 1.02, y: -4 }}
|
||||||
whileTap={{ scale: 0.98 }}
|
whileTap={{ scale: 0.98 }}
|
||||||
>
|
>
|
||||||
<h3>{group.title}</h3>
|
<EditableText as="h3" path={`skills.${group.id}.title`} label={s.edit.fields.groupTitle}>
|
||||||
|
{group.title}
|
||||||
|
</EditableText>
|
||||||
<ul className="expertise-skills">
|
<ul className="expertise-skills">
|
||||||
{group.skills.map((skill: string) => (
|
{group.skills.map((skill: string) => (
|
||||||
<li key={skill} className="expertise-skill">
|
<li key={skill} className="expertise-skill">
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { motion } from 'motion/react'
|
import { motion } from 'motion/react'
|
||||||
import { SectionHeading } from '@/components/ui/SectionHeading'
|
import { SectionHeading } from '@/components/ui/SectionHeading'
|
||||||
import { InView } from '@/components/ui/InView'
|
import { InView } from '@/components/ui/InView'
|
||||||
|
import { EditableText } from '@/components/ui/EditableText'
|
||||||
import { useI18n } from '@/i18n/provider'
|
import { useI18n } from '@/i18n/provider'
|
||||||
|
|
||||||
export function ExperiencePage() {
|
export function ExperiencePage() {
|
||||||
@@ -31,7 +32,9 @@ export function ExperiencePage() {
|
|||||||
>
|
>
|
||||||
<div className="timeline-marker" />
|
<div className="timeline-marker" />
|
||||||
<div className="timeline-header">
|
<div className="timeline-header">
|
||||||
<div className="timeline-title">{exp.title}</div>
|
<EditableText as="div" className="timeline-title" path={`experience.${exp.id}.title`} label={s.edit.fields.expTitle}>
|
||||||
|
{exp.title}
|
||||||
|
</EditableText>
|
||||||
<div className="timeline-company">{exp.company}</div>
|
<div className="timeline-company">{exp.company}</div>
|
||||||
<div className="timeline-meta">
|
<div className="timeline-meta">
|
||||||
<span className="timeline-duration">{exp.duration}</span>
|
<span className="timeline-duration">{exp.duration}</span>
|
||||||
@@ -39,8 +42,15 @@ export function ExperiencePage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<ul className="timeline-responsibilities">
|
<ul className="timeline-responsibilities">
|
||||||
{exp.responsibilities.map((r) => (
|
{exp.responsibilities.map((r, ri) => (
|
||||||
<li key={r}>{r}</li>
|
<EditableText
|
||||||
|
as="li"
|
||||||
|
key={ri}
|
||||||
|
path={`experience.${exp.id}.responsibilities[${ri}]`}
|
||||||
|
label={`${exp.title} — ${s.edit.fields.responsibility} ${ri + 1}`}
|
||||||
|
>
|
||||||
|
{r}
|
||||||
|
</EditableText>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useParams, Link } from 'react-router'
|
|||||||
import { motion, type Transition } from 'motion/react'
|
import { motion, type Transition } from 'motion/react'
|
||||||
import { Badge } from '@/components/ui/Badge'
|
import { Badge } from '@/components/ui/Badge'
|
||||||
import { Tag } from '@/components/ui/Tag'
|
import { Tag } from '@/components/ui/Tag'
|
||||||
|
import { EditableText } from '@/components/ui/EditableText'
|
||||||
import { InView } from '@/components/ui/InView'
|
import { InView } from '@/components/ui/InView'
|
||||||
import { useI18n } from '@/i18n/provider'
|
import { useI18n } from '@/i18n/provider'
|
||||||
|
|
||||||
@@ -61,19 +62,25 @@ export function ProjectDetailPage() {
|
|||||||
viewport={{ once: true, amount: 0.2 }}
|
viewport={{ once: true, amount: 0.2 }}
|
||||||
transition={itemTransition(0)}
|
transition={itemTransition(0)}
|
||||||
>
|
>
|
||||||
<h1 id="project-title" style={{ flex: 1 }}>{project.title}</h1>
|
<EditableText as="h1" id="project-title" style={{ flex: 1 }} path={`projects.${project.id}.title`} label={s.edit.fields.title}>
|
||||||
|
{project.title}
|
||||||
|
</EditableText>
|
||||||
<Badge variant="outline">{s.projects.categories[project.category]}</Badge>
|
<Badge variant="outline">{s.projects.categories[project.category]}</Badge>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
|
|
||||||
<motion.p
|
<EditableText
|
||||||
|
as={motion.p}
|
||||||
className="prose-lede"
|
className="prose-lede"
|
||||||
initial={{ opacity: 0, y: 24 }}
|
initial={{ opacity: 0, y: 24 }}
|
||||||
whileInView={{ opacity: 1, y: 0 }}
|
whileInView={{ opacity: 1, y: 0 }}
|
||||||
viewport={{ once: true, amount: 0.2 }}
|
viewport={{ once: true, amount: 0.2 }}
|
||||||
transition={itemTransition(0.08)}
|
transition={itemTransition(0.08)}
|
||||||
|
path={`projects.${project.id}.summary`}
|
||||||
|
label={`${project.title} — ${s.edit.fields.summary}`}
|
||||||
|
multiline
|
||||||
>
|
>
|
||||||
{project.summary}
|
{project.summary}
|
||||||
</motion.p>
|
</EditableText>
|
||||||
|
|
||||||
<div className="prose">
|
<div className="prose">
|
||||||
{project.metrics && project.metrics.length > 0 && (
|
{project.metrics && project.metrics.length > 0 && (
|
||||||
@@ -137,8 +144,12 @@ export function ProjectDetailPage() {
|
|||||||
viewport={{ once: true, amount: 0.2 }}
|
viewport={{ once: true, amount: 0.2 }}
|
||||||
transition={itemTransition(0.48 + idx * 0.08)}
|
transition={itemTransition(0.48 + idx * 0.08)}
|
||||||
>
|
>
|
||||||
<h4>{section.title}</h4>
|
<EditableText as="h4" path={`projects.${project.id}.sections.${section.id}.title`} label={`${section.title} — ${s.edit.fields.sectionTitle}`}>
|
||||||
<p>{section.content}</p>
|
{section.title}
|
||||||
|
</EditableText>
|
||||||
|
<EditableText as="p" path={`projects.${project.id}.sections.${section.id}.content`} label={`${section.title} — ${s.edit.fields.sectionContent}`} multiline>
|
||||||
|
{section.content}
|
||||||
|
</EditableText>
|
||||||
<Tag accent>{section.type}</Tag>
|
<Tag accent>{section.type}</Tag>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { SectionHeading } from '@/components/ui/SectionHeading'
|
|||||||
import { Badge } from '@/components/ui/Badge'
|
import { Badge } from '@/components/ui/Badge'
|
||||||
import { motion } from 'motion/react'
|
import { motion } from 'motion/react'
|
||||||
import { InView } from '@/components/ui/InView'
|
import { InView } from '@/components/ui/InView'
|
||||||
|
import { EditableText } from '@/components/ui/EditableText'
|
||||||
import { useI18n } from '@/i18n/provider'
|
import { useI18n } from '@/i18n/provider'
|
||||||
|
|
||||||
import { Link } from 'react-router'
|
import { Link } from 'react-router'
|
||||||
@@ -39,12 +40,16 @@ export function ProjectsListPage() {
|
|||||||
whileTap={{ scale: 0.98 }}
|
whileTap={{ scale: 0.98 }}
|
||||||
>
|
>
|
||||||
<div className="project-card-header">
|
<div className="project-card-header">
|
||||||
<h3>{project.title}</h3>
|
<EditableText as="h3" path={`projects.${project.id}.title`} label={s.edit.fields.title}>
|
||||||
|
{project.title}
|
||||||
|
</EditableText>
|
||||||
<Badge variant="outline">
|
<Badge variant="outline">
|
||||||
{s.projects.categories[project.category]}
|
{s.projects.categories[project.category]}
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
<p className="project-card-summary">{project.summary}</p>
|
<EditableText as="p" className="project-card-summary" path={`projects.${project.id}.summary`} label={`${project.title} — ${s.edit.fields.summary}`}>
|
||||||
|
{project.summary}
|
||||||
|
</EditableText>
|
||||||
<div className="project-card-techs">
|
<div className="project-card-techs">
|
||||||
{project.technologies.slice(0, 4).map((tech) => (
|
{project.technologies.slice(0, 4).map((tech) => (
|
||||||
<span key={tech} className="tag">
|
<span key={tech} className="tag">
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||||
"target": "es2023",
|
"target": "es2023",
|
||||||
"lib": ["ES2023", "DOM"],
|
"lib": ["ES2024", "DOM"],
|
||||||
"module": "esnext",
|
"module": "esnext",
|
||||||
"types": ["vite/client"],
|
"types": ["vite/client"],
|
||||||
"allowArbitraryExtensions": true,
|
"allowArbitraryExtensions": true,
|
||||||
|
|||||||
Reference in new issue
Block a user