perf(edit): read only the documents the current route needs

Edit-mode document scope comes from the page manifests (src/i18n/edit-scope.ts): an entity's structure document and its two text documents are read as one unit, the category labels only where a project renders. A route change fetches only the still-missing documents and adopts them through DraftStore.adoptBase, which refuses a document the draft has already changed. A bundle-seeded baseline is never PUT over the branch: saveDraft reads the branch first and reports a conflict. Every manifest now claims profile.name, which the footer renders on every route.
This commit is contained in:
dong.nguyen committed 2026-10-24 15:24:08 +07:00
1 parent ee1d524bd0
commit 5c71b52d81
13 files changed
+320 -71

No files matched your search

+6 -4
View File
@@ -76,7 +76,7 @@ Content is split once, at authoring time, into language-neutral **structure docu
- `src/data/projects.json` + `projects.ts` loader — cards: category / technologies / featured / `sections[].{id, type}`; titles, summaries, role, metrics and section prose are text (role follows the owner's EN title convention; metrics are localized)
- `src/i18n/locales/{vi,en}/content/{profile,skills,experience,projects}.json` — all content text, one file per entity, keyed by the structure ids; the `profile` record is fixed-keyed (`name`, `title`, `bio`, `subtitle`, `tldr`, `tagline`, `currentInterests`, `roles`, `philosophyQuotes`, `philosophy.<id>.{title, description, keywords}`); `src/i18n/locales/{vi,en}/ui/{group}.json` — 14 chrome groups (`navigation`, `footer`, `social`, `hero`, `about`, `expertise`, `experience`, `projects`, `projectDetail`, `contact`, `philosophy`, `resume`, `edit`, `common`), in each language (nav group labels, Mode options, language names `langEn` / `langVi`, action labels, social `aria-label`s, the resume's section labels, edit-mode labels) — person text never lives here; `src/i18n/index.ts` merges both trees back into the same `UI`/`CONTENT` records and asserts the merge against the group lists — a group dropped in the split is a load-time error, never a silent omission
- Content ids and the category values a project uses are **generated**, never hand-maintained (spec: `docs/design/specs/v5/spec-v5-generated-content-ids.md`): `scripts/generate-content-types.ts` reads the four structure documents and writes `src/types/content-ids.ts` (gitignored) under `predev` / `prebuild` / `prepare`; `src/types/index.ts` re-exports those unions type-only and keeps only the code-owned ones (`Language`, `Palette`, `SocialId`, `PageId`, manifest types). A content add or delete touches JSON only — a text entry left behind by a deleted record is a `tsc` error (`TS2741`), never a stale union member — and a category with no label in either language is a validator error naming both `ui/projects.json` files (rule 7)
- `src/data/pages/{home,about,experience,projects,project-detail,contact,philosophy,resume}.json` + `pages.ts` loader — per-route manifests: which entity fields the page renders (`fields[]`; `*` = every field the record id owns) and which UI groups it reads; `src/types/index.ts` carries `PageId` / `PageManifestClaim` / `PageManifest`. The validator enforces: no unknown entity, no unknown UI group, no unresolvable field path, **no orphan text field** (every text leaf in the content documents is claimed by at least one manifest), no missing manifest for a route in `src/data/navigation.ts` plus `/projects/:id`
- `src/data/pages/{home,about,experience,projects,project-detail,contact,philosophy,resume}.json` + `pages.ts` loader — per-route manifests: which entity fields the page renders (`fields[]`; `*` = every field the record id owns) and which UI groups it reads; `src/types/index.ts` carries `PageId` / `PageManifestClaim` / `PageManifest`. A manifest describes the whole page, chrome included — the footer renders `profile.name` on every route, so every manifest claims it. The validator enforces: no unknown entity, no unknown UI group, no unresolvable field path, **no orphan text field** (every text leaf in the content documents is claimed by at least one manifest), no missing manifest for a route in `src/data/navigation.ts` plus `/projects/:id`
- `src/i18n/index.ts` — load + validate + join ONCE at module load; exports `UI` and `CONTENT` as `Record<Language, Resolved…>`; `src/i18n/dict-types.ts` carries the document types; `src/i18n/validate.ts` + `scripts/validate-content.ts` enforce the cross-document rules (orphan or missing keys, HTML markup in text values, the manifest rules above) — a malformed document fails `pnpm build`, CI, and the browser load, never a silent half-render
- `src/i18n/provider.tsx` — `I18nProvider` wraps the app; components consume `const { ui: s, content: c } = useI18n()`: `s` is the chrome of the current language, `c` the joined records (`c.profile`, `c.skillGroups`, `c.experiences`, `c.projects`). There is no `field()` and no `*En` field pair anymore
- Translation is a JSON edit, never a component edit; a new language is a new locale directory plus one `Language` union member
@@ -87,7 +87,9 @@ Content is split once, at authoring time, into language-neutral **structure docu
## Live Edit Mode (`?edit`, v4)
- Entry and persistence: any route with `?edit` — `MaybeEditMode` in `App.tsx` lazy-mounts `EditModeShell` (its own chunk; visitors never load edit code) when the query is present **or** the session flag is set. The mode is a session, not a URL state: while it is active every route change re-attaches `?edit` (a replace-navigation in `EditModeShell`), so clicking any link keeps edit mode and a reload reopens it — only the EditBar's Exit returns to the visitor site (it clears the flag, which unmounts the shell, and strips the query). The shell's initialization runs once per mount (entry URL from a ref, `stripEditQuery` reads `window.location`), so navigation never re-authenticates, re-fetches, or re-restores the draft. The shell authenticates, fetches the live branch documents through the proxy, and re-wraps the tree in an `I18nProvider` override — the seven routes ARE the preview
- Entry and persistence: any route with `?edit` — `MaybeEditMode` in `App.tsx` lazy-mounts `EditModeShell` (its own chunk; visitors never load edit code) when the query is present **or** the session flag is set. The mode is a session, not a URL state: while it is active every route change re-attaches `?edit` (a replace-navigation in `EditModeShell`), so clicking any link keeps edit mode and a reload reopens it — only the EditBar's Exit returns to the visitor site (it clears the flag, which unmounts the shell, and strips the query). The shell's initialization runs once per mount (entry URL from a ref, `stripEditQuery` reads `window.location`), so navigation never re-authenticates, re-fetches, or re-restores the draft. The shell authenticates, reads the live branch documents the current route needs (see the next bullet), and re-wraps the tree in an `I18nProvider` override — the seven routes ARE the preview
- Document scope (`src/i18n/edit-scope.ts`): the documents a session reads come from the page manifests, never from component code — a claim names a joined record, and an entity owns its structure document plus its two text documents, which are always read as one unit (a half-loaded entity would make the validator compare a live document against a bundled one). Entry = the entry route's scope plus anything a restored draft already touched (those need a real blob sha). A route change reads only the documents still missing — each is adopted through `DraftStore.adoptBase`, which refuses a document the draft has already changed — and the category labels only where a project renders. A document still on its bundled baseline is never PUT over the branch: `saveDraft` sees the empty sha, reads the branch, and hands it to the conflict flow. The bundled copy stays the offline fallback, never a silent substitute for a live read
- Target branch (spec D10): `?edit=<branch>` reads (`?ref=`) and writes (`branch` in the PUT body) that branch; a bare `?edit` resumes the session's last branch, default `master`. Names are validated against git ref rules in `src/i18n/edit-session.ts` before any request (illegal → exit like a failed auth); the branch is stored beside the session flag. The target branch must already exist — Contents API updates never create branches. Only `master` deploys, so the EditBar shows a merge hint on other branches
- Auth: HTTP Basic at the nginx `/api/content/` proxy is the security boundary; `src/i18n/edit-mode.ts` probes it through a hidden iframe and nothing else. The `?edit` parsing, the session flag `portfolio-edit`, the branch flag and `portfolio-draft` key live in `src/i18n/edit-session.ts` — a module with no imports, because `App.tsx` reads the mode gate from it and must not pull the auth probe (and through it `draft.ts`) into the entry chunk. A failed probe (401 or cancelled prompt) clears the flag and strips `?edit` → normal visitor site
- `src/i18n/draft.ts` — `DraftStore`: baselines (`data` + blob `sha`) of the 12 writable documents (4 structure + 8 text), copy-on-write draft, leaf-path diff, cross-document validation on every accepted edit, three-way rebase on save conflicts (Gitea 28 reports a blob-sha mismatch as 422 with a "does not match" message; older deployments answered 412 — both are handled; origin / base / working kept separate), draft persisted to sessionStorage `portfolio-draft`, sequential-PUT save (one commit per touched document, resume from the first unwritten one on failure). Edit mode writes JSON only: the id-union leg was deleted when spec-v5 made the unions generated, and the store is handed the branch's category labels (read-only `ui/projects.json` fetches) for rule 7 — `null` when they cannot be read, in which case the rule is skipped and the EditBar says so
@@ -106,7 +108,7 @@ src/
sections/ — Hero, About, Expertise, Experience, Projects, Contact, HeroParticles, DownloadResume (the hero lazer CTA; it gates itself on `resumeAvailable`)
ui/ — Badge, Button, ContactLinks, LanguageIcon, ResumeDialog, SectionHeading, SocialLinks, Tag, Typewriter, InView, RollingTextLink, BackToTop, EditableText, TagListEditor, RecordControls, RecordSettings, icons
data/ — profile, skills, experience, projects (JSON documents + typed loaders), pages (manifest JSON + pages.ts loader), resume, palettes, navigation, social, site (TS modules)
i18n/ — index.ts (loader), dict-types.ts, validate.ts, provider.tsx, draft.ts (DraftStore + save pipeline), edit-session.ts (`?edit`/flag/branch state, dependency-free), edit-mode.ts (Basic-auth probe), locales/{vi,en}/content/{profile,skills,experience,projects}.json + ui/{group}.json (14 chrome groups)
i18n/ — index.ts (loader), dict-types.ts, validate.ts, provider.tsx, draft.ts (DraftStore + save pipeline), edit-scope.ts (manifest-derived read scope), edit-session.ts (`?edit`/flag/branch state, dependency-free), edit-mode.ts (Basic-auth probe), locales/{vi,en}/content/{profile,skills,experience,projects}.json + ui/{group}.json (14 chrome groups)
hooks/ — useTheme.tsx, useLanguage.tsx, useClickOutside.ts, useResumeDialog.ts, useEdit.ts (edit context)
pages/ — HomePage, AboutPage, ExperiencePage, ProjectsListPage, ProjectDetailPage, PhilosophyPage, ContactPage
types/ — shared TypeScript interfaces; content-ids.ts (generated id unions, gitignored)
@@ -137,7 +139,7 @@ src/
- `scripts/generate-resume.ts` — Playwright-based PDF resume generator (bilingual en/vi)
- `scripts/generate-content-types.ts` — writes `src/types/content-ids.ts` from the four structure documents (`pnpm generate:ids`, wired as `predev` / `prebuild` / `prepare`): the id unions and the project category values in document order, `never` for an emptied document, a duplicate id refused with the file named
- `scripts/smoke-draft.ts` — regression check of the draft-store semantics (`pnpm tsx scripts/smoke-draft.ts`): accept/reject paths, empty-required rejection, orphan-free record delete, template creation, id re-sluging on rename, snapshot round-trip, conflict detection, clean rebase, the category-label rule
- `scripts/smoke-draft.ts` — regression check of the draft-store semantics (`pnpm tsx scripts/smoke-draft.ts`): accept/reject paths, empty-required rejection, orphan-free record delete, template creation, id re-sluging on rename, snapshot round-trip, conflict detection, clean rebase, the category-label rule, and the scoped-baseline rules of spec-v4-live-edit §5.1 (an adopted baseline replaces an untouched document only; a bundle-seeded document is never PUT over the branch)
- `scripts/smoke-generated-ids.ts` — regression check of the generator (`pnpm tsx scripts/smoke-generated-ids.ts`): the shipped module equals the shipped documents, byte-stable output, `never` for emptied documents, malformed documents refused with the file named
## Deployment
@@ -96,6 +96,7 @@ The current `ui.json` namespaces map 1:1 onto groups; the split is mechanical. O
- `entity` uses the §3 entity ids; `fields` are paths into the joined text/structure records; `"*"` claims the whole entity.
- `ui` lists **page-owned** groups only. Component-owned groups (`navigation`, `footer`, `social`, `common`, `resume`, `edit`) are owned by the component side and provenance for them is the component mapping in §4 — they are not repeated in every manifest.
- Manifests are language-neutral (which data a page shows is not a translation fact). They are structure-side data: part of validation, committed like structure documents, **read-only in the app** (`spec-v4-inline-editing.md` §3) — edited as repo files by the developer.
- A manifest describes the whole page, **chrome included**: the footer renders `profile.name` on every route, so every manifest claims it. Component-owned *UI* groups stay out of the manifest (previous bullet — chrome labels have no entity provenance to name), but a content field a page renders through its chrome is still that page's claim. This is what makes the manifest usable as the edit-mode read scope (spec-v4-live-edit §5.2, row 26): a session reads exactly the documents the current route's manifest claims, so a page cannot be served a document it does not describe.
Initial content mapping — derived from the code scan of every consumer (2026-10-23), to be re-derived exactly at implementation:
@@ -103,11 +104,11 @@ Initial content mapping — derived from the code scan of every consumer (2026-1
|---|---|---|---|---|
| `home` | `name`, `tagline`, `roles`, `bio`, `currentInterests`, `philosophy`, `tldr`, links (`email`, handles) | `*` (Expertise) | `*` (timeline) | featured subset: `title`, `summary`, `metrics` |
| `about` | `name`, `bio`, `subtitle`, `currentInterests`, `philosophy` | `*` | — | — |
| `experience` | `tldr` | — | `*` | — |
| `projects` | — | — | — | `*`: `title`, `summary`, `metrics` |
| `project-detail` | — | — | — | per-id: `title`, `summary`, `role`, `metrics`, `sections.*` |
| `contact` | links (`email`, handles) | — | — | — |
| `philosophy` | `philosophyQuotes` | — | — | — |
| `experience` | `tldr`, `name` (footer) | — | `*` | — |
| `projects` | `name` (footer) | — | — | `*`: `title`, `summary`, `metrics` |
| `project-detail` | `name` (footer) | — | — | per-id: `title`, `summary`, `role`, `metrics`, `sections.*` |
| `contact` | links (`email`, handles), `name` (footer) | — | — | — |
| `philosophy` | `philosophyQuotes`, `name` (footer) | — | — | — |
| `resume` (synthetic) | `name`, `title`, `bio`, `email`, links | `*` | `*` | `*` |
`home` does **not** claim `title` — the code scan shows Hero renders `name`/`roles`/`tagline` only; `title` is consumed by the resume generator, which the synthetic manifest now covers honestly.
@@ -159,4 +160,5 @@ Order decided 2026-10-23: this spec lands **after** `spec-v4-inline-editing.md`
|---|---|---|
| 0 | Design agreed (D1–D5) | ✅ Done 2026-10-23 |
| 1–6 | Implementation steps §7 | ✅ Done 2026-10-23 — content split (4 files × 2 languages) + UI split (14 groups × 2) with merge asserted in `index.ts`; `src/data/pages/*.json` (8 manifests) + `pages.ts` + `PageId`/`PageManifestClaim`/`PageManifest` in `src/types/index.ts`; validator rules 1–4 in `validate.ts` (run at load and by `validate:content`); `draft.ts` registry data-driven over 12 writable documents (4 structure + 8 text, `entityOfDoc`/`docEntityMap` exported for provenance + EditBar); `describeField()` names the per-entity file automatically; EditBar "appears on" annotations via `manifestsClaiming`/`recordEntity`; AGENTS.md Data Layer + Live Edit Mode + Component Structure updated |
| 7 | Manifests describe the whole page, chrome included: every manifest claims `profile.name`, because the footer renders it on every route — the same claim set is the edit-mode read scope (spec-v4-live-edit §5.2, row 26) | ✅ Done 2026-10-24 — `projects.json` and `project-detail.json` gained a `profile: ["name"]` claim, `contact` / `experience` / `philosophy` gained `name` in their existing claim; the rule is stated in `pages.ts`'s header. Verified: `pnpm validate:content`, `tsc -b`, `pnpm build`, and the scope probe over all 7 routes (evidence in live-edit row 26) |
| — | Acceptance §8 | 🟡 Automated rows verified 2026-10-23 (see §8 checkboxes); browser rows open — the owner verifies in a real browser |
+4 -1
View File
@@ -362,6 +362,8 @@ stateDiagram-v2
- **Durability:** every accepted edit is also copied to `sessionStorage` (the documents are tens of KB). An accidental reload restores the draft: the app re-fetches live files, re-applies the saved draft, and flags any document whose blob `sha` moved → conflict flow (§5.6). SPA navigation never loses the draft; `beforeunload` warns while dirty.
- **Mode persistence (row 24, owner request 2026-10-24):** the mode is a session state, not a URL state. `MaybeEditMode` mounts the shell on `?edit` **or** on the session flag; while the shell is mounted a route change that dropped `?edit` gets it back through a replace-navigation, so the address keeps describing the mode the user is in and a reload reopens it. The session initializes once per mount — the entry URL is read from a ref, `stripEditQuery` reads the live URL — so navigation never re-authenticates, re-fetches, or re-restores the draft. Only Exit leaves; a failed auth or an illegal branch name clears the flag the same way, which unmounts the shell. The flag/query/branch helpers live in `src/i18n/edit-session.ts`, a module with no imports: `App.tsx` reads the gate from it without pulling the auth probe — and through it `draft.ts` — into the entry chunk.
- **Document scope (row 26, owner report 2026-10-24):** a session reads only the documents the page it is on needs. `src/i18n/edit-scope.ts` derives them from the page manifests: a claim names a joined record, an entity owns its structure document plus its two text documents, and those are always read as one unit — a half-loaded entity would make the cross-document validator compare a live document against a bundled one. Entry: the entry route's scope, plus anything a restored draft already touched (those need a real blob sha before any PUT). Navigation: an effect on the route reads only the documents still missing and the label documents only where a project renders; each is adopted with `DraftStore.adoptBase`, which refuses a document the draft has changed, so a late read never replaces work. A document still on its bundled baseline is never PUT over the branch — `saveDraft` sees the empty sha, reads the branch, and hands the document to the conflict flow (or reports a failure when the read itself fails). The bundled copy stays the offline fallback, never a silent substitute for a live read. Because a manifest describes the whole page including its chrome, every manifest claims `profile.name` (the footer renders it on every route); the EditBar's "appears on" annotation for that field reads identically.
### 5.3 `EditableText` contract (inline editing)
- **Visitor mode is transparent:** the component renders exactly the element the site renders today (same tag, same attributes, text as children). Zero DOM/CSS/motion difference outside edit mode.
@@ -417,7 +419,7 @@ v4 exposes no new layout knobs. `featured` and `variant` already exist and are e
Repo: `https://code.vugado.com/dong.nguyen/cv` — self-hosted Gitea (API verified live: `/api/v1/version` → 28.1.0). Contents API paths are fixed to this repo:
- `GET /api/v1/repos/dong.nguyen/cv/contents/{path}` — read the live file + its blob `sha` when a draft session starts (§5.1).
- `GET /api/v1/repos/dong.nguyen/cv/contents/{path}` — read the live file + its blob `sha` for the documents the session's route renders (§5.1, row 26), and again for the documents a later navigation first reaches.
- `PUT /api/v1/repos/dong.nguyen/cv/contents/{path}` — body: base64 content, `message`, `branch`, `sha` (the file's blob ID). Gitea 28 `UpdateFile` keys create-vs-update on this field: empty `sha` → create (an existing file answers 422 "repository file already exists"); a stale `sha` → 422 with a "does not match" message → editor refetches and re-applies; lost updates are impossible. *(Amended 2026-10-23 after the first real save against 28.1.0 — the text previously described the retired `last_commit_sha`/412 contract; `last_commit_sha` exists only in responses.)*
**Save/CI policy (decided):** a save writes its touched documents as **sequential PUTs to `master`** — each is one commit and triggers the existing pipeline. Consequences accepted: a save touching 2–4 documents produces 2–4 sequential CI runs, and between runs the deployed site can transiently mix old/new documents. For a single owner publishing at low frequency this is the boring, correct choice; the final state after the last pipeline is always consistent. (Branch-then-merge for a single pipeline run is noted as a future optimization, not v4.)
@@ -608,3 +610,4 @@ Deferred (not v4):
| 23 | Generated content ids ([`spec-v5-generated-content-ids.md`](../v5/spec-v5-generated-content-ids.md)): the id unions and the project category values are written from the structure documents by `scripts/generate-content-types.ts` (`predev` / `prebuild` / `prepare`), edit mode writes JSON only, validator rule 7 requires a label for every used category in both languages | 3 | ✅ Done 2026-10-24 (automated) — `scripts/generate-content-types.ts` + `generate:ids` / `predev` / `prebuild` / `prepare`, gitignored `src/types/content-ids.ts`, `src/types/index.ts` re-exports it type-only; row 22's machinery deleted (`draft.ts`, `EditModeShell.tsx`, `EditBar.tsx`, both `ui/edit.json`); rule 7 implemented and wired through the draft store, EditBar, `RecordSettings`, `TagListEditor`. Verified: `pnpm generate:ids` (777-byte module, byte-stable on a second run), `pnpm build` (10 chunks, names identical to a build of the same documents before the change, no runtime reference to the generated module), `pnpm validate:content`, `pnpm lint` (no new warnings), `pnpm tsx scripts/smoke-draft.ts` 11/11, `pnpm tsx scripts/smoke-generated-ids.ts` 7/7, `pnpm build:resume-all` (both PDFs; the rendered HTML byte-identical before/after with identical documents). ⬜ Browser: visitor routes unchanged, `?edit` add/delete round-trip with no union card, category-rejection banner |
| 24 | Edit mode survives navigation (owner request 2026-10-24): "if in edit mode, keep the mode when clicking any link; only Exit returns to normal mode" | 3 | ✅ Done 2026-10-24 (automated) — `src/i18n/edit-session.ts` (new, dependency-free): `?edit` parsing, the session flag, the branch flag and rules moved out of `edit-mode.ts`, which is now the Basic-auth handshake alone; `App.tsx` `MaybeEditMode` gates on `editRequested(search) \|\| hasEditFlag()`; `EditModeShell` re-attaches `edit` after a route change that dropped it (replace-navigation, skipped while authenticating so a failed auth is never fought) and its initialization no longer depends on `location.search` (entry URL from a ref, `stripEditQuery` reads `window.location`), so a navigation neither re-authenticates nor re-fetches nor re-restores the draft. `EditBar.tsx` imports `DEFAULT_BRANCH` from the new module. Verified: `tsc -b`, `pnpm build` (entry chunk carries no `probe` literal → the auth handshake stays lazy; `EditModeShell` is still a separate 10.5 kB chunk; the draft module's presence in the entry chunk is pre-existing, via `Hero → EditableText → draft`), `pnpm lint` (no new warnings), throwaway session-semantics smoke 17/17 — gate on query/flag, branch tri-state incl. `?edit=` and an illegal name, flag+branch cleared on exit, cached-credential auth across the new module boundary — deleted after the run. ⬜ Browser: `?edit` → click through Home/About/Experience/Projects/Contact/Philosophy → EditBar and the draft stay; reload reopens the session; Exit → clean URL, visitor site |
| 25 | Edit-mode initialization is one concurrent request wave (owner report 2026-10-24: opening edit mode fetched every document one after another) | 3 | ✅ Done 2026-10-24 (automated) — `EditModeShell.tsx` §5.1 initialization: the 12 draft documents and the 2 label files are issued as two concurrent `Promise.all` requests whose success/failure handlers are attached in the same tick they are created, so a label rejection landing while the documents are still in flight is not an unhandled rejection; the failure split is unchanged (a document failure is the offline state, a label failure only disables rule 7). Measured through the dev proxy, same transport as the app: 12 documents sequential 902 ms → 210 ms for the whole 14-request wave, 38 768 bytes and 12 distinct payloads byte-identical to the sequential loop. Verified: `tsc -b` 0, `pnpm lint` no new warnings, `pnpm build` OK, `smoke-draft.ts` 11/11, throwaway wave probe 6/6 (same bytes as the loop, both failure branches, both-success path, no unhandled rejection) — probe deleted. Paired infra half: `spec-v4-deploy-infra.md` D14 / row 10 — `/api/content/` now proxies to Gitea over HTTP/2, so the wave multiplexes over one pooled upstream connection instead of one HTTP/1.1 connection per in-flight request. ⬜ Browser: edit-mode load on the deployed site |
| 26 | Edit mode reads only what the current page needs (owner report 2026-10-24: `/philosophy?edit` fetched all 14 documents while the page renders profile text alone) | 3 | ✅ Done 2026-10-24 (automated) — `src/i18n/edit-scope.ts` (new): `manifestForPath` + `scopeForPath` derive the needed documents from the page manifests — a claim names a joined record, an entity owns its structure document plus its two text documents, and those are always read as one unit (a half-loaded entity would make the validator compare a live document against a bundled one); the label documents follow the projects scope. `EditModeShell`: the entry fetch is the entry route's scope plus anything a restored draft touched; an effect on `location.pathname` reads only the documents still missing and adopts them through `DraftStore.adoptBase`, which refuses a document the draft has already changed. `saveDraft` never PUTs a bundle-seeded baseline (an empty sha is a create for Gitea 28): it reads the branch first and reports a conflict, or a failure when that read fails. Every manifest now claims `profile.name` — the footer renders it on every route — which also makes the EditBar "appears on" annotation for that field truthful. Verified: `tsc -b`, `pnpm build` (EditModeShell stays a separate lazy chunk), `pnpm lint` (no new warnings), `pnpm validate:content`, `scripts/smoke-draft.ts` 13/13 (new checks 12–13: `adoptBase` replaces an untouched baseline and refuses a touched one; a bundle-seeded document is never written). Throwaway scope probe over all 7 routes + an unknown path + trailing-slash forms (deleted after the run): `/` 12 documents, `/about` 6, `/experience` 6, `/projects` and `/projects/:id` 6 + labels, `/contact` 3, `/philosophy` 3, unknown route 0. ⬜ Browser: `/philosophy?edit` → 3 document GETs; navigating to `/projects` brings the project documents; an edit made before they land goes through the conflict flow instead of overwriting the branch |
+49 -4
View File
@@ -2,11 +2,14 @@
// spec-v4-data-organization §6.1). Id unions are no longer the store's
// business — scripts/generate-content-types.ts derives them from these very
// documents (spec-v5), so what is checked here is the draft itself: text
// writes, record add/delete/rename, conflicts and rebase, and the validator
// rules a rejected edit is reported through.
// writes, record add/delete/rename, conflicts and rebase, the validator rules
// a rejected edit is reported through, and the scoped-baseline rules of
// spec-v4-live-edit §5.1 (adoptBase, and a save that must not PUT a
// bundle-seeded document).
// Run: pnpm tsx scripts/smoke-draft.ts
import { DraftStore, bundledBase } from '../src/i18n/draft';
import { DraftStore, bundledBase, saveDraft } from '../src/i18n/draft';
import type { CategoryLabels } from '../src/i18n/validate';
import type { DocBase } from '../src/i18n/draft';
import projectsEnUiJson from '../src/i18n/locales/en/ui/projects.json';
import projectsViUiJson from '../src/i18n/locales/vi/ui/projects.json';
@@ -163,4 +166,46 @@ if (store7.isDirty()) fail('a rejected structure write mutated the draft');
const acceptedCategory = store7.setStructured('projects', '[0].category', 'logistics');
if (acceptedCategory !== null) fail(`labeled category rejected: ${JSON.stringify(acceptedCategory)}`);
console.log('draft store smoke: all 11 checks passed');
// 12. adoptBase (spec-v4-live-edit §5.1): a document the draft has not touched
// accepts the live baseline a later navigation read brings; a document it has
// already changed keeps its draft and its origin — a late read never silently
// replaces work.
const store8 = new DraftStore(structuredClone(bases), LABELS);
// The live copy keeps the bundled ids: an adopted structure document whose ids
// have no text entries would be a real validation failure, not a probe.
const liveGroups = (structuredClone(bases.skills.data) as { id: string; skills: string[] }[]).map(
(group) => ({ ...group, skills: [...group.skills, 'LIVE SKILL'] }),
);
const liveSkills: DocBase = { data: liveGroups, sha: 'live-sha' };
store8.adoptBase('skills', liveSkills);
if (store8.shaOf('skills') !== 'live-sha') fail('adoptBase kept the bundled sha');
if (JSON.stringify(store8.dataOf('skills')) !== JSON.stringify(liveSkills.data))
fail('adoptBase did not replace the bundled data');
if (store8.setValue('vi', 'profile.bio', 'KEEP MINE') !== null)
fail('the touched-document edit was rejected');
const liveProfile: DocBase = { data: { bio: 'THEIR BIO' }, sha: 'other-sha' };
store8.adoptBase('profile.vi', liveProfile);
if (store8.shaOf('profile.vi') !== '') fail('a touched document adopted a live sha');
if ((store8.dataOf('profile.vi') as Record<string, unknown>).bio !== 'KEEP MINE')
fail('a late read replaced drafted work');
// 13. A baseline that came from the bundle carries no blob sha, so the save
// pipeline must not PUT it over the branch (Gitea reads an empty sha as a
// create). It reads the branch first — with no proxy reachable here that read
// fails, so the document reports a failure, the save stops before any write,
// and the draft survives.
const store9 = new DraftStore(structuredClone(bases), LABELS);
if (store9.setValue('vi', 'profile.bio', 'SCOPED BASELINE') !== null)
fail('the scoped-save probe edit was rejected');
const saveProbe = await saveDraft(store9, () => {}, 'master');
const firstResult = saveProbe.results[0];
if (!firstResult || firstResult.id !== 'profile.vi')
fail(`unexpected save results: ${JSON.stringify(saveProbe.results)}`);
if (firstResult.status !== 'failed')
fail(`a bundle-seeded draft was not read from the branch first: ${firstResult.status}`);
if (!saveProbe.stoppedEarly) fail('the save continued after the branch read failed');
if (saveProbe.results.length !== 1) fail('the save kept going past the stopped document');
if ((store9.dataOf('profile.vi') as Record<string, unknown>).bio !== 'SCOPED BASELINE')
fail('a failed save lost the draft');
console.log('draft store smoke: all 13 checks passed');
+135 -50
View File
@@ -1,8 +1,9 @@
// 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).
// real site. It authenticates through the protected proxy, reads the live
// documents the current route's manifest claims (the rest arrive on
// navigation), 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';
@@ -14,11 +15,13 @@ import {
DRAFT_DOCS,
DraftStore,
bundledBase,
entityOfDoc,
fetchDoc,
saveDraft,
recordForTitlePath,
} from '@/i18n/draft';
import type { DocBase, DocSaveResult, DraftDocId } from '@/i18n/draft';
import type { DocBase, DocSaveResult, DraftDocId, DraftDocMeta, SavedDraft } from '@/i18n/draft';
import { metasForDocs, scopeForPath } from '@/i18n/edit-scope';
import {
DEFAULT_BRANCH,
DRAFT_STORAGE,
@@ -52,6 +55,33 @@ const categoryMap = (data: unknown): Record<string, unknown> => {
return Object.fromEntries(Object.entries(categories));
};
// One wave per scope (§5.1). Each helper catches its own failure, so a label
// rejection that lands while the documents are still in flight is never an
// unhandled rejection, and the two failure paths stay separate: a document
// failure is the offline state, a label failure only disables rule 7.
async function loadDocs(metas: DraftDocMeta[], branch: string): Promise<DocBase[] | null> {
try {
return await Promise.all(metas.map((meta) => fetchDoc(meta.file, branch)));
} catch {
return null;
}
}
// Rule 7's inputs. A failed read yields null: the save bar says the label
// check could not run, and the rule is skipped rather than guessed at from a
// bundle that may predate the branch.
async function loadLabels(branch: string): Promise<CategoryLabels | null> {
try {
const [vi, en] = await Promise.all([
fetchDoc(LABEL_FILES.vi, branch),
fetchDoc(LABEL_FILES.en, branch),
]);
return { vi: categoryMap(vi.data), en: categoryMap(en.data) };
} catch {
return null;
}
}
export default function EditModeShell({ children }: { children: ReactNode }) {
const navigate = useNavigate();
const location = useLocation();
@@ -119,6 +149,10 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
const rest = params.toString();
navigate(`${location.pathname}?edit${rest ? `&${rest}` : ''}${location.hash}`, { replace: true });
}, [phase, location.pathname, location.search, location.hash, navigate]);
// Which documents and label documents this session has actually read from
// the branch (§5.1). A navigation fetches only what is missing here.
const liveDocsRef = useRef(new Set<DraftDocId>());
const labelsLiveRef = useRef(false);
// The session's initialization runs once per mount: the entry URL is read
// from a ref and `stripEditQuery` is stable, so a route change inside the
@@ -152,55 +186,62 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
setPhase('loading');
// Draft initialization is the live repository files, never the bundle
// (§5.1); the bundle is only the offline fallback, flagged stale.
// (§5.1); the bundle is only the offline fallback, flagged stale. The
// scope is the documents this route's manifest claims plus whatever a
// restored draft already touched — those must be read live, so their blob
// shas are known before any PUT. Everything else stays bundled until a
// navigation asks for it.
let offline = false;
let bases: Record<DraftDocId, DocBase> | null = null;
// One concurrent wave instead of 14 serialized round-trips. The handlers
// are attached in the same tick the requests are made, so a label
// rejection that lands while the documents are still in flight is not an
// unhandled rejection; the two failure paths stay separate — a document
// failure is the offline state, a label failure only disables rule 7.
const docsRequest = Promise.all(
DRAFT_DOCS.map((meta) => fetchDoc(meta.file, branch)),
).then(
(docs) => ({ ok: true as const, docs }),
() => ({ ok: false as const }),
);
const labelsRequest = Promise.all([
fetchDoc(LABEL_FILES.vi, branch),
fetchDoc(LABEL_FILES.en, branch),
]).then(
([vi, en]) => ({ ok: true as const, vi, en }),
() => ({ ok: false as const }),
);
const docs = await docsRequest;
if (docs.ok) {
bases = {} as Record<DraftDocId, DocBase>;
DRAFT_DOCS.forEach((meta, index) => {
bases![meta.id] = docs.docs[index];
});
} else {
offline = true;
}
if (!bases) bases = bundledBase();
// Rule 7's inputs. A failed read leaves the labels null: the save bar
// says the label check could not run, and the rule is skipped rather
// than guessed at from a bundle that may predate the branch.
let labels: CategoryLabels | null = null;
const labelDocs = await labelsRequest;
if (labelDocs.ok) {
labels = { vi: categoryMap(labelDocs.vi.data), en: categoryMap(labelDocs.en.data) };
} else {
setLabelsUnavailable(true);
}
const created = new DraftStore(bases, labels);
let saved: SavedDraft | null = null;
const stored = sessionStorage.getItem(DRAFT_STORAGE);
if (stored) {
try {
const drifted = created.applySaved(JSON.parse(stored));
saved = JSON.parse(stored) as SavedDraft;
} catch {
saved = null;
}
}
const initial = scopeForPath(window.location.pathname);
const wanted = new Set<DraftDocId>(initial.docs);
if (saved) {
for (const id of Object.keys(saved.docs)) wanted.add(id as DraftDocId);
}
const metas = metasForDocs([...wanted]);
const needLabels =
initial.needsLabels || metas.some((meta) => entityOfDoc(meta.id) === 'projects');
// The two waves start in the same tick and each catches its own failure,
// so a label rejection that lands while the documents are still in
// flight is not an unhandled rejection. A document failure is the offline
// state; a label failure only disables rule 7.
const docsPromise = loadDocs(metas, branch);
const labelsPromise = needLabels ? loadLabels(branch) : Promise.resolve(null);
const docs = await docsPromise;
const labels = needLabels ? await labelsPromise : null;
if (docs === null) {
offline = true;
} else {
metas.forEach((meta) => {
liveDocsRef.current.add(meta.id);
});
}
if (needLabels) {
if (labels === null) {
setLabelsUnavailable(true);
} else {
labelsLiveRef.current = true;
}
}
const bases = bundledBase();
if (docs) {
metas.forEach((meta, index) => {
bases[meta.id] = docs[index];
});
}
const created = new DraftStore(bases, labels);
if (saved) {
try {
const drifted = created.applySaved(saved);
if (drifted.length > 0) setConflicts(drifted);
setDraftRestored(true);
} catch {
@@ -219,6 +260,50 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
};
}, [refresh, stripEditQuery]);
// A route change needs the documents that route renders (§5.1): only the
// missing ones are read, and only documents the draft has not touched adopt
// the fresh baseline. The page keeps rendering the bundled copy while those
// few reads are in flight; a save of a still-bundled document goes through
// the conflict flow in draft.ts instead of overwriting the branch.
useEffect(() => {
if (phase !== 'ready' || !store) return;
const scope = scopeForPath(location.pathname);
const metas = metasForDocs(scope.docs).filter((meta) => !liveDocsRef.current.has(meta.id));
const needLabels = scope.needsLabels && !labelsLiveRef.current;
if (metas.length === 0 && !needLabels) return;
let cancelled = false;
const load = async () => {
const docsPromise = loadDocs(metas, branch);
const labelsPromise = needLabels ? loadLabels(branch) : Promise.resolve(null);
const docs = await docsPromise;
const labels = needLabels ? await labelsPromise : null;
if (cancelled) return;
if (docs === null) {
// The page stays on the bundled copy and the shell says so; saving is
// disabled until a reload can read the branch again.
setPhase('offline');
return;
}
metas.forEach((meta, index) => {
store.adoptBase(meta.id, docs[index]);
liveDocsRef.current.add(meta.id);
});
if (needLabels) {
if (labels === null) {
setLabelsUnavailable(true);
} else {
store.setCategoryLabels(labels);
labelsLiveRef.current = true;
}
}
refresh(store);
};
void load();
return () => {
cancelled = true;
};
}, [phase, store, branch, location.pathname, refresh]);
// Mid-edit navigation guard (§5.2).
useEffect(() => {
if (!dirty) return;
+4 -2
View File
@@ -1,8 +1,10 @@
// Typed loader for the page manifests (spec-v4-data-organization §5): which
// joined records and which page-owned UI groups each page consumes.
// Manifests are language-neutral, part of validation, and read-only in the
// app — they exist for provenance (EditBar grouping, orphan-field rule),
// never for rendering.
// app — they exist for provenance (EditBar grouping, orphan-field rule) and
// for the edit-mode fetch scope (spec-v4-live-edit §5.1), never for rendering.
// A manifest describes the whole page, chrome included: the footer renders
// `profile.name` on every route, so every manifest claims it.
import aboutJson from './pages/about.json';
import contactJson from './pages/contact.json';
import experienceJson from './pages/experience.json';
+2 -1
View File
@@ -11,7 +11,8 @@
"linkedinUrl",
"linkedinHandle",
"telegramUrl",
"telegramHandle"
"telegramHandle",
"name"
]
}
],
+1 -1
View File
@@ -2,7 +2,7 @@
"id": "experience",
"route": "/experience",
"content": [
{ "entity": "profile", "fields": ["tldr"] },
{ "entity": "profile", "fields": ["tldr", "name"] },
{ "entity": "experiences", "fields": ["*"] }
],
"ui": ["experience"]
+1 -1
View File
@@ -2,7 +2,7 @@
"id": "philosophy",
"route": "/philosophy",
"content": [
{ "entity": "profile", "fields": ["philosophyQuotes"] }
{ "entity": "profile", "fields": ["philosophyQuotes", "name"] }
],
"ui": ["philosophy"]
}
+2 -1
View File
@@ -5,7 +5,8 @@
{
"entity": "projects",
"fields": ["title", "summary", "role", "metrics", "technologies", "category", "sections.*"]
}
},
{ "entity": "profile", "fields": ["name"] }
],
"ui": ["projectDetail"]
}
+2 -1
View File
@@ -2,7 +2,8 @@
"id": "projects",
"route": "/projects",
"content": [
{ "entity": "projects", "fields": ["*"] }
{ "entity": "projects", "fields": ["*"] },
{ "entity": "profile", "fields": ["name"] }
],
"ui": ["projects"]
}
+37
View File
@@ -928,6 +928,22 @@ export class DraftStore {
this.base.set(id, fresh);
}
// A document the session did not need on the entry route becomes needed
// after a navigation (spec-v4-live-edit §5.1): its live baseline replaces the
// bundled one. A document the draft already changed keeps its draft and its
// origin — a late read never silently replaces work.
adoptBase(id: DraftDocId, doc: DocBase): void {
if (this.working.has(id)) return;
this.base.set(id, doc);
this.origin.set(id, doc.data);
}
// Rule 7's category labels arrive with the documents of the route that
// renders a project, which a session may reach only after a navigation.
setCategoryLabels(labels: CategoryLabels | null): void {
this.categoryLabels = labels;
}
// 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 —
@@ -985,6 +1001,27 @@ export async function saveDraft(
const meta = DRAFT_DOCS.find((d) => d.id === id)!;
const paths = store.changedPaths(id);
const message = `content: ${meta.file} (${paths.length} path${paths.length === 1 ? '' : 's'})`;
// A baseline that came from the bundle carries no blob sha. Gitea reads an
// empty sha as a create (422 "repository file already exists"), and PUTting
// a bundle-seeded draft over the branch would drop whatever the branch has.
// Read the branch first and hand the document to the conflict flow: rebase
// replays my paths onto the fresh base, take-theirs discards them. Reached
// when a document is edited before its scoped read lands, or when a
// restored draft touches a document this route never renders.
if (!store.shaOf(id)) {
try {
store.resetBase(id, await fetchDoc(meta.file, branch));
} catch {
const stalled: DocSaveResult = { id, status: 'failed' };
results.push(stalled);
onResult(stalled);
return { results, stoppedEarly: true };
}
const bundleSeeded: DocSaveResult = { id, status: 'conflict' };
results.push(bundleSeeded);
onResult(bundleSeeded);
continue;
}
const res = await putDoc(meta.file, store.dataOf(id), message, store.shaOf(id), branch);
if (res.ok) {
store.markWritten(id, res.sha);
+70
View File
@@ -0,0 +1,70 @@
// Which draft documents a route needs (spec-v4-live-edit §5.1). The answer
// comes from the page manifests, never from component code: a manifest names
// the joined records its page renders, and an entity owns its structure
// document plus its per-language text documents. Those are fetched as one unit
// — a half-loaded entity would make the cross-document validator compare a live
// document against a bundled one.
import { pageManifests, recordEntity } from '../data/pages';
import { DRAFT_DOCS, TEXT_ENTITIES, entityOfDoc } from './draft';
import type { DraftDocId, DraftDocMeta, TextEntity } from './draft';
import type { ContentEntityId, PageManifest } from '../types/index';
// Manifest entity names are the joined-record names (`skillGroups`); the
// document registry names files (`skills`). pages.ts owns one direction, this
// inverts it rather than stating a second mapping.
const DOC_ENTITY = Object.fromEntries(
TEXT_ENTITIES.map((textEntity) => [recordEntity(textEntity), textEntity]),
) as Record<ContentEntityId, TextEntity>;
// Manifest routes are the router's own strings. `/projects/:id` is the only
// pattern; the synthetic `resume` consumer has no route and never matches a
// location. A trailing slash is the same page to the router, so it is removed
// before matching (`/` stays `/`).
export function manifestForPath(pathname: string): PageManifest | null {
const path = pathname !== '/' ? pathname.replace(/\/+$/, '') : pathname;
for (const manifest of pageManifests) {
const route = manifest.route;
if (!route) continue;
if (route.endsWith('/:id')) {
const prefix = route.slice(0, -'/:id'.length);
if (path.startsWith(`${prefix}/`) && path.length > prefix.length + 1) return manifest;
} else if (path === route) {
return manifest;
}
}
return null;
}
export type EditScope = {
// Registry order, so a caller can zip it against DRAFT_DOCS.
docs: DraftDocId[];
// Rule 7 (a project's category against the branch's labels) is only reachable
// where a project renders, so the two label documents follow the projects
// scope instead of riding along on every route.
needsLabels: boolean;
};
// A route no manifest describes renders nothing editable — an empty scope is
// the honest answer, and a later navigation to a real route fetches what it
// needs.
export function scopeForPath(pathname: string): EditScope {
const manifest = manifestForPath(pathname);
const entities = new Set<TextEntity>();
if (manifest) {
for (const claim of manifest.content) entities.add(DOC_ENTITY[claim.entity]);
}
const docs = DRAFT_DOCS.filter((meta) => {
const entity = entityOfDoc(meta.id);
return entity !== null && entities.has(entity);
});
return {
docs: docs.map((meta) => meta.id),
needsLabels: entities.has('projects'),
};
}
// The registry entries for a scope, in registry order.
export function metasForDocs(ids: readonly DraftDocId[]): DraftDocMeta[] {
const wanted = new Set(ids);
return DRAFT_DOCS.filter((meta) => wanted.has(meta.id));
}