fix(edit): balance id unions when a record is deleted

Deleting a record in edit mode removed the structure row and its text but left the id union member in src/types/index.ts, so Record<SkillGroupId, SkillGroupText> rejected the shortened text document (TS2741) and pnpm build failed. draft.ts: readUnionBlock reads a union as its declaration span (CRLF/LF safe, never round-trips), diffIdsWithUnions reports missing and stale members against committedStructures(), applyUnionChanges rewrites only that member list in one PUT; newIdsInCommitted/patchUnionSource removed. types/index.ts drops logistics-technology. Verified: smoke-draft 12/12 (new checks 9-12), validate:content, lint (no new warnings), build.
This commit is contained in:
dong.nguyen committed 2026-10-24 10:08:58 +07:00
1 parent a0a1451272
commit 150ef90c73
8 files changed
+234 -40

No files matched your search

+1 -1
View File
@@ -88,7 +88,7 @@ Content is split once, at authoring time, into language-neutral **structure docu
- Entry: any route with `?edit` — `MaybeEditMode` in `App.tsx` lazy-mounts `EditModeShell` (its own chunk; visitors never load edit code). The shell authenticates, fetches the live master documents through the proxy, and re-wraps the tree in an `I18nProvider` override — the seven routes ARE the preview - Entry: any route with `?edit` — `MaybeEditMode` in `App.tsx` lazy-mounts `EditModeShell` (its own chunk; visitors never load edit code). The shell authenticates, fetches the live master documents through the proxy, and re-wraps the tree in an `I18nProvider` override — the seven routes ARE the preview
- 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-mode.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 - 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-mode.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, keeps the session flag `portfolio-edit` in sessionStorage, and strips `?edit` when the probe fails (401 or cancelled prompt → normal visitor site) - Auth: HTTP Basic at the nginx `/api/content/` proxy is the security boundary; `src/i18n/edit-mode.ts` probes it through a hidden iframe, keeps the session flag `portfolio-edit` in sessionStorage, and strips `?edit` when the probe fails (401 or cancelled prompt → 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), and appending new id union members to `src/types/index.ts` after their documents land - `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), and **balancing** id union members in `src/types/index.ts` after their documents land — appending the ids a new record introduces and removing the ids a deleted record leaves behind, because a stale member makes `Record<SkillGroupId, SkillGroupText>` reject the shortened text document and the build fails (`TS2741`)
- `src/components/ui/EditableText.tsx` — the site's own element (`as` = the tag or motion component it renders today) becomes the inline editor only in edit mode; commit on blur only (Vietnamese IME-safe), Esc cancels, Enter commits single-line fields, paste is plain-text, empty required values are rejected at commit; without an `EditContext` provider it renders byte-identical markup to the plain element - `src/components/ui/EditableText.tsx` — the site's own element (`as` = the tag or motion component it renders today) becomes the inline editor only in edit mode; commit on blur only (Vietnamese IME-safe), Esc cancels, Enter commits single-line fields, paste is plain-text, empty required values are rejected at commit; without an `EditContext` provider it renders byte-identical markup to the plain element
- `src/components/layout/EditBar.tsx` — fixed save bar: per-path diff with revert and "appears on" page annotations (computed from the page manifests via `manifestsClaiming`, never from component code), conflict resolution (rebase / take-theirs / per-field keep-mine–keep-theirs), per-document save status, partial-save resume, exit confirm - `src/components/layout/EditBar.tsx` — fixed save bar: per-path diff with revert and "appears on" page annotations (computed from the page manifests via `manifestsClaiming`, never from component code), conflict resolution (rebase / take-theirs / per-field keep-mine–keep-theirs), per-document save status, partial-save resume, exit confirm
- Editable surface: content text inline (pencil-triggered, click never edits) **and** structure — chip-level tag editors (technologies, categories, interests, roles, keywords, tagline emphasis), ghost add/delete/move on every record surface, per-record settings popover (`featured`, project section list + type picker, `variant`, location, logo), ids auto-generated from title slugs, social links handle-only with URLs derived in the loaders. Implemented 2026-10-23 (`spec-v4-inline-editing.md` + `spec-v4-data-organization.md`); the JSON panel is deleted. UI documents stay read-only in v4. Field provenance: hovering any pencil shows `document → pointer` (`describeField()` names the per-entity file automatically); the EditBar diff line and a `validate:content` error for the same field read identically - Editable surface: content text inline (pencil-triggered, click never edits) **and** structure — chip-level tag editors (technologies, categories, interests, roles, keywords, tagline emphasis), ghost add/delete/move on every record surface, per-record settings popover (`featured`, project section list + type picker, `variant`, location, logo), ids auto-generated from title slugs, social links handle-only with URLs derived in the loaders. Implemented 2026-10-23 (`spec-v4-inline-editing.md` + `spec-v4-data-organization.md`); the JSON panel is deleted. UI documents stay read-only in v4. Field provenance: hovering any pencil shows `document → pointer` (`describeField()` names the per-entity file automatically); the EditBar diff line and a `validate:content` error for the same field read identically
@@ -128,6 +128,7 @@ export type PhilosophyId = /* NEW — slug of point title */;
- `SkillGroupId` / `PhilosophyId` do not exist today and must be added to the structure documents; they are internal-only keys and never appear in URLs. - `SkillGroupId` / `PhilosophyId` do not exist today and must be added to the structure documents; they are internal-only keys and never appear in URLs.
- **No `SectionId` union.** Section ids collide across projects (`context`, `problem`, `result`, … appear in several projects); a global union would force every project's text to cover every other project's sections. Section coverage is enforced per project by the validator (§3.6) instead. - **No `SectionId` union.** Section ids collide across projects (`context`, `problem`, `result`, … appear in several projects); a global union would force every project's text to cover every other project's sections. Section coverage is enforced per project by the validator (§3.6) instead.
- Adding a new project/experience/skill/philosophy item = 3 edits: one line in the union, one record in the structure document, one entry in `content.vi.json`. tsc + validator catch any missing leg. - Adding a new project/experience/skill/philosophy item = 3 edits: one line in the union, one record in the structure document, one entry in `content.vi.json`. tsc + validator catch any missing leg.
- **Deleting a record is the mirror image** (owner-reported 2026-10-24): the structure row and its text go, and the union member must go with them. A stale member makes `Record<SkillGroupId, SkillGroupText>` reject the shortened text document — `TS2741: Property '"logistics-technology"' is missing …` at `src/i18n/index.ts:69`: `pnpm build` and the CI gate fail after a delete the editor itself performed correctly. `saveIdUnions` therefore **balances** the unions instead of only appending: `diffIdsWithUnions` reports missing *and* stale members against `committedStructures()` (the post-PUT base, so a document that has not landed never reads as stale), `applyUnionChanges` rewrites exactly that union's member list — survivors keep their order, an emptied union renders `never` — in one PUT under the same commit policy. Unions are parsed as their declaration span, never searched as substrings: a slug can legitimately appear elsewhere in the same file (`ProjectCategory` carries project-like slugs, `PageId` carries `home`), and a substring test silently skips the leg. Line endings are preserved, so the reviewed commit stays one line.
### 3.2 Document types (`dict-types.ts`) ### 3.2 Document types (`dict-types.ts`)
@@ -533,6 +534,7 @@ The phase lands as **three separately verified sub-steps** — each ends with it
- [ ] P3: a mid-edit reload restores the draft and flags any document whose live sha has moved. - [ ] P3: a mid-edit reload restores the draft and flags any document whose live sha has moved.
- [ ] P3: 412 conflict offers rebase / take-theirs / hand-merge per document; a partial save resumes from the first unwritten document without rewriting landed ones. - [ ] P3: 412 conflict offers rebase / take-theirs / hand-merge per document; a partial save resumes from the first unwritten document without rewriting landed ones.
- [ ] P3: a template add creates the structure record and its text stubs together; a delete leaves no orphan text (validator confirms). - [ ] P3: a template add creates the structure record and its text stubs together; a delete leaves no orphan text (validator confirms).
- [x] P3 (2026-10-24): adding a record appends its id to the union and deleting one removes it; a record deleted in edit mode never leaves a union member behind — `scripts/smoke-draft.ts` checks 9–12.
## 10. Risks & Mitigations ## 10. Risks & Mitigations
@@ -600,3 +602,4 @@ Deferred (not v4):
| 19 | Localize the §4 structure-assigned strings (`experience.company` of non-company entries, `duration`, `currentInterests`, `roles`, `keywords`, `projects.role`/`metrics`) or keep them EN-only like `technologies` | post-v4 | ✅ Done 2026-10-22 (automated) — fields moved to the text documents (§4 follow-up); VI document carries localized values (numeric dates + "nay", "Sẵn sàng cho cơ hội mới", "Nghỉ giữa chặng", "Đã triển khai tại 16 sortations", "Xử lý 70.000 ảnh/tháng"), en overrides with the originals, proper nouns and term lists identical (en omits); company/duration/role inline-editable, tag arrays JSON-panel-only; templates in `draft.ts` and JsonPanel hints follow the new shapes; resume generator reads `profile.tldr` from content. Verified: `pnpm build`, `pnpm validate:content`, `pnpm lint` (no new warnings), `pnpm build:resume-all` (both PDFs), SSR smoke marker sets per language incl. localized durations/companies/metrics/roles on home + `/experience` + project detail — deleted after the run. ⬜ Browser: VI pages show the localized timeline; `?edit` company/duration/role | | 19 | Localize the §4 structure-assigned strings (`experience.company` of non-company entries, `duration`, `currentInterests`, `roles`, `keywords`, `projects.role`/`metrics`) or keep them EN-only like `technologies` | post-v4 | ✅ Done 2026-10-22 (automated) — fields moved to the text documents (§4 follow-up); VI document carries localized values (numeric dates + "nay", "Sẵn sàng cho cơ hội mới", "Nghỉ giữa chặng", "Đã triển khai tại 16 sortations", "Xử lý 70.000 ảnh/tháng"), en overrides with the originals, proper nouns and term lists identical (en omits); company/duration/role inline-editable, tag arrays JSON-panel-only; templates in `draft.ts` and JsonPanel hints follow the new shapes; resume generator reads `profile.tldr` from content. Verified: `pnpm build`, `pnpm validate:content`, `pnpm lint` (no new warnings), `pnpm build:resume-all` (both PDFs), SSR smoke marker sets per language incl. localized durations/companies/metrics/roles on home + `/experience` + project detail — deleted after the run. ⬜ Browser: VI pages show the localized timeline; `?edit` company/duration/role |
| 20 | Save pipeline adapted to the live Gitea 28 Contents API | 3 | ✅ Done 2026-10-23 — the first real save answered 422 "repository file already exists [path: src/i18n/locales/vi/content.json]": Gitea 28 decides create-vs-update by the body `sha` (blob ID), which the client never sent. `draft.ts`: `fetchDoc`/`fetchTextFile` keep the blob `sha`; PUT bodies send `sha`; the new blob sha is read from the FileResponse `content.sha`; save conflict detection = 422 with a "does not match" message (412 kept for older deployments); §6.1 amended. Verified: `tsc -b`, `pnpm lint` (no new warnings), `scripts/smoke-draft.ts` 8/8. ⬜ Browser + Gitea: save → commit lands on the target branch; stale blob sha → conflict flow | | 20 | Save pipeline adapted to the live Gitea 28 Contents API | 3 | ✅ Done 2026-10-23 — the first real save answered 422 "repository file already exists [path: src/i18n/locales/vi/content.json]": Gitea 28 decides create-vs-update by the body `sha` (blob ID), which the client never sent. `draft.ts`: `fetchDoc`/`fetchTextFile` keep the blob `sha`; PUT bodies send `sha`; the new blob sha is read from the FileResponse `content.sha`; save conflict detection = 422 with a "does not match" message (412 kept for older deployments); §6.1 amended. Verified: `tsc -b`, `pnpm lint` (no new warnings), `scripts/smoke-draft.ts` 8/8. ⬜ Browser + Gitea: save → commit lands on the target branch; stale blob sha → conflict flow |
| 21 | v4 cutover: `spec-v4-inline-editing.md` E1–E7 (pencil-trigger inline editing, chip tag editors, ghost record add/delete/move, settings popovers, auto-ids, handle-only socials, `JsonPanel.tsx` deleted) + `spec-v4-data-organization.md` (content per entity, UI in 14 groups, per-route manifests + validator rules 1–4, 12-document draft registry, EditBar "appears on" annotations) | post-v4 | ✅ Done 2026-10-23 (automated) — details and evidence in each spec's Progress Tracking: the split is gated against baseline dumps (merged `CONTENT` byte-identical both languages; `UI` differs only by the intentional label changes), the manifest validator rejects all five bad cases (unknown entity / field path / orphan field / ui group / missing manifest), `smoke-draft.ts` 8/8 on the new registry, `tsc -b`, `pnpm build`, `pnpm lint` (no new warnings), `pnpm build:resume-all` all pass. ⬜ Browser: edit-mode walkthrough (pencil-only editing, provenance chips, save → per-file commits with page annotations) + visitor routes unchanged; the Gitea content repository must carry the new file layout before saves answer 200 (row 11 dependency) | | 21 | v4 cutover: `spec-v4-inline-editing.md` E1–E7 (pencil-trigger inline editing, chip tag editors, ghost record add/delete/move, settings popovers, auto-ids, handle-only socials, `JsonPanel.tsx` deleted) + `spec-v4-data-organization.md` (content per entity, UI in 14 groups, per-route manifests + validator rules 1–4, 12-document draft registry, EditBar "appears on" annotations) | post-v4 | ✅ Done 2026-10-23 (automated) — details and evidence in each spec's Progress Tracking: the split is gated against baseline dumps (merged `CONTENT` byte-identical both languages; `UI` differs only by the intentional label changes), the manifest validator rejects all five bad cases (unknown entity / field path / orphan field / ui group / missing manifest), `smoke-draft.ts` 8/8 on the new registry, `tsc -b`, `pnpm build`, `pnpm lint` (no new warnings), `pnpm build:resume-all` all pass. ⬜ Browser: edit-mode walkthrough (pencil-only editing, provenance chips, save → per-file commits with page annotations) + visitor routes unchanged; the Gitea content repository must carry the new file layout before saves answer 200 (row 11 dependency) |
| 22 | Union balance on delete: a record removed in edit mode prunes its id out of `src/types/index.ts` (the `TS2741` after the `logistics-technology` skill group was deleted) | 3 | ✅ Done 2026-10-24 (automated) — `draft.ts`: `readUnionBlock` reads a union as its exact declaration span (CRLF- and LF-safe, `never` round-trips), `diffIdsWithUnions` reports missing **and** stale members against `committedStructures()`, `applyUnionChanges` rewrites only that member list (survivors keep their order), one PUT with the message `content: update id union members (+id, -id)`; `newIdsInCommitted` / `patchUnionSource` deleted; `types/index.ts` `SkillGroupId` no longer lists `logistics-technology`; `ui/edit.json` `unionNote` reworded for both directions. Verified: `pnpm tsx scripts/smoke-draft.ts` 12/12 — new checks 9–12 (shipped documents ↔ shipped unions agree, a delete prunes exactly one line, an id colliding with a `PageId` member is still appended, `never` round-trip), `pnpm validate:content`, `pnpm lint` (no new warnings), `pnpm build`. ⬜ Browser + Gitea: delete a record in edit mode → the union commit lands on the target branch and CI builds |
+101 -4
View File
@@ -1,13 +1,17 @@
// Throwaway smoke test for the draft store (spec-v4 §5.1, §5.5, §5.6; // Smoke test for the draft store (spec-v4 §5.1, §5.5, §5.6; registry per
// registry per spec-v4-data-organization §6.1). // spec-v4-data-organization §6.1; id-union legs per §3.1).
// Run: pnpm tsx scripts/smoke-draft.ts // Run: pnpm tsx scripts/smoke-draft.ts
import { DraftStore, bundledBase } from '../src/i18n/draft'; import { readFileSync } from 'node:fs';
import { DraftStore, applyUnionChanges, bundledBase, diffIdsWithUnions } from '../src/i18n/draft';
const fail = (msg: string): never => { const fail = (msg: string): never => {
console.error(`FAIL: ${msg}`); console.error(`FAIL: ${msg}`);
process.exit(1); process.exit(1);
}; };
// The file the save pipeline patches.
const TYPES = readFileSync(new URL('../src/types/index.ts', import.meta.url), 'utf8');
const bases = bundledBase(); const bases = bundledBase();
const store = new DraftStore(structuredClone(bases)); const store = new DraftStore(structuredClone(bases));
@@ -98,4 +102,97 @@ const arr = (store4.dataOf('profile.vi') as Record<string, Record<string, unknow
if (!Array.isArray(arr)) fail(`setPath made ${JSON.stringify(arr)}, not an array`); if (!Array.isArray(arr)) fail(`setPath made ${JSON.stringify(arr)}, not an array`);
if (arr[0] !== 'NEW TAG') fail('array element not set'); if (arr[0] !== 'NEW TAG') fail('array element not set');
console.log('draft store smoke: all 8 checks passed'); // 9. The shipped documents and the shipped id unions agree. This is the check
// that was missing: a skill group deleted in edit mode left 'logistics-
// technology' in SkillGroupId, and `Record<SkillGroupId, …>` then failed the
// build with TS2741.
const drift = diffIdsWithUnions(new DraftStore(structuredClone(bases)), TYPES);
if (drift.added.length + drift.removed.length > 0)
fail(`documents and id unions disagree: ${JSON.stringify(drift)}`);
// 10. A deleted record prunes its union member — and only that line, in
// either line ending (git stores LF, a Windows checkout reads CRLF).
const store5 = new DraftStore(structuredClone(bases));
const groupIds = (store5.dataOf('skills') as { id: string }[]).map((g) => g.id);
const victim = groupIds[groupIds.length - 1];
const delGroup = store5.deleteRecord('skill-group', { id: victim });
if (delGroup !== null) fail(`skill-group delete rejected: ${JSON.stringify(delGroup)}`);
const afterDelete = store5.validate();
if (afterDelete.length > 0) fail(`validate after delete: ${JSON.stringify(afterDelete)}`);
// The union leg follows ids whose documents actually landed.
for (const id of ['skills', 'skills.vi', 'skills.en'] as const) store5.markWritten(id, 'simulated-sha');
const stale = diffIdsWithUnions(store5, TYPES);
if (stale.added.length > 0) fail(`a delete reported additions: ${JSON.stringify(stale.added)}`);
if (stale.removed.length !== 1 || stale.removed[0].id !== victim || stale.removed[0].union !== 'SkillGroupId')
fail(`stale union member not reported: ${JSON.stringify(stale.removed)}`);
const pruned = applyUnionChanges(TYPES, [{ union: 'SkillGroupId', add: [], remove: [victim] }]);
if (pruned === null) fail('prune refused a multi-line union');
if (pruned.includes(`'${victim}'`)) fail('stale member survived the prune');
const EOL = TYPES.includes('\r\n') ? '\r\n' : '\n';
const expectedBlock = `export type SkillGroupId =${EOL}${groupIds
.filter((id) => id !== victim)
.map((id) => ` | '${id}'`)
.join(EOL)};${EOL}`;
const expected = TYPES.replace(/export type SkillGroupId =\r?\n(?:[ \t]*\| '[^']+';?\r?\n)+/, () => expectedBlock);
if (pruned !== expected) fail('prune rewrote more than the SkillGroupId member list');
const afterPrune = diffIdsWithUnions(store5, pruned);
if (afterPrune.added.length + afterPrune.removed.length > 0)
fail(`union still mismatched after the prune: ${JSON.stringify(afterPrune)}`);
const lfTypes = TYPES.replace(/\r\n/g, '\n');
const prunedLf = applyUnionChanges(lfTypes, [{ union: 'SkillGroupId', add: [], remove: [victim] }]);
if (prunedLf === null) fail('prune refused an LF union');
if (prunedLf.includes('\r\n')) fail('an LF patch introduced CRLF');
if (prunedLf !== expected.replace(/\r\n/g, '\n')) fail('LF patch differs from the LF source');
const afterPruneLf = diffIdsWithUnions(store5, prunedLf);
if (afterPruneLf.added.length + afterPruneLf.removed.length > 0)
fail(`union still mismatched after the LF prune: ${JSON.stringify(afterPruneLf)}`);
// 11. An id that also reads as a string elsewhere in the file is still
// appended. 'home' is a PageId member, so a substring test would have skipped
// this leg and the build would have broken the other way.
const store6 = new DraftStore(structuredClone(bases));
const addGroup = store6.addRecord('skill-group');
if (addGroup !== null) fail(`skill-group add rejected: ${JSON.stringify(addGroup)}`);
const known = new Set(groupIds);
const created = (store6.dataOf('skills') as { id: string }[]).find((g) => !known.has(g.id));
if (!created) fail('no new skill group created');
const rename = store6.renameRecord('skill-group', { id: created.id }, 'Home');
if (rename !== null) fail(`rename rejected: ${JSON.stringify(rename)}`);
if (!(store6.dataOf('skills') as { id: string }[]).some((g) => g.id === 'home'))
fail('rename did not apply');
const afterRename = store6.validate();
if (afterRename.length > 0) fail(`validate after rename: ${JSON.stringify(afterRename)}`);
for (const id of ['skills', 'skills.vi', 'skills.en'] as const) store6.markWritten(id, 'simulated-sha');
const missing = diffIdsWithUnions(store6, TYPES);
if (!missing.added.some((a) => a.union === 'SkillGroupId' && a.id === 'home'))
fail(`id colliding with another union member was not appended: ${JSON.stringify(missing.added)}`);
if (missing.removed.length > 0) fail(`an add reported removals: ${JSON.stringify(missing.removed)}`);
const appended = applyUnionChanges(TYPES, [{ union: 'SkillGroupId', add: ['home'], remove: [] }]);
if (appended === null) fail('append refused a multi-line union');
const afterAppend = diffIdsWithUnions(store6, appended);
if (afterAppend.added.length + afterAppend.removed.length > 0)
fail(`union still mismatched after the append: ${JSON.stringify(afterAppend)}`);
// 12. An emptied document prunes its union to `never`, and a record added on
// top of that state is appended back rather than silently skipped.
const emptied = applyUnionChanges(TYPES, [{ union: 'SkillGroupId', add: [], remove: groupIds }]);
if (emptied === null) fail('prune of every member refused');
if (!emptied.includes('export type SkillGroupId = never;')) fail('emptied union is not never');
const store7 = new DraftStore(structuredClone(bases));
if (store7.addRecord('skill-group') !== null) fail('skill-group add rejected on a never union');
const addedGroup = (store7.dataOf('skills') as { id: string }[]).find((g) => !known.has(g.id));
if (!addedGroup) fail('no new skill group created for the never case');
for (const id of ['skills', 'skills.vi', 'skills.en'] as const) store7.markWritten(id, 'simulated-sha');
const revived = diffIdsWithUnions(store7, emptied);
if (!revived.added.some((a) => a.union === 'SkillGroupId' && a.id === addedGroup.id))
fail(`never union skipped the new id: ${JSON.stringify(revived.added)}`);
if (revived.removed.length > 0) fail(`the never case reported removals: ${JSON.stringify(revived.removed)}`);
const back = applyUnionChanges(
emptied,
[{ union: 'SkillGroupId', add: revived.added.map((a) => a.id), remove: [] }],
);
if (back === null) fail('append onto never refused');
const afterNever = diffIdsWithUnions(store7, back);
if (afterNever.added.length + afterNever.removed.length > 0)
fail(`never round-trip left a mismatch: ${JSON.stringify(afterNever)}`);
console.log('draft store smoke: all 12 checks passed');
+2 -1
View File
@@ -281,7 +281,8 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
const conflicted = results.filter((r) => r.status === 'conflict').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])]); 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. // The third leg of §3.1: bring the unions to the ids whose documents
// landed — appended when a record was added, dropped when one was deleted.
const types = typesRef.current; const types = typesRef.current;
if (types) { if (types) {
const union = await saveIdUnions(store, types, branch); const union = await saveIdUnions(store, types, branch);
+125 -31
View File
@@ -319,8 +319,10 @@ export function bundledBase(): Record<DraftDocId, DocBase> {
// --- id unions (§3.1) ------------------------------------------------------------ // --- id unions (§3.1) ------------------------------------------------------------
// Adding a content item is three edits: a union member, a structure record, // 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 // its Vietnamese text. Deleting one is the mirror image: the record and its
// land, saveIdUnions appends the new ids to src/types/index.ts. // text go, and the union member must go with them. The editor does every leg
// — once the content documents land, saveIdUnions brings each union in
// src/types/index.ts to exactly the ids its document carries.
const UNION_SPECS: ReadonlyArray<{ union: string; ids: (s: ContentStructures) => string[] }> = [ const UNION_SPECS: ReadonlyArray<{ union: string; ids: (s: ContentStructures) => string[] }> = [
{ union: 'ProjectId', ids: (s) => s.projects.map((p) => p.id) }, { union: 'ProjectId', ids: (s) => s.projects.map((p) => p.id) },
@@ -329,23 +331,99 @@ const UNION_SPECS: ReadonlyArray<{ union: string; ids: (s: ContentStructures) =>
{ union: 'PhilosophyId', ids: (s) => s.profile.philosophy.map((p) => p.id) }, { union: 'PhilosophyId', ids: (s) => s.profile.philosophy.map((p) => p.id) },
]; ];
export function newIdsInCommitted(store: DraftStore, typesSource: string): { union: string; id: string }[] { // A union is read as a block — `export type X =` followed by its ` | 'id'`
const structures = store.committedStructures(); // member lines — never as a substring search: an id slug can legitimately
const out: { union: string; id: string }[] = []; // appear elsewhere in the same file (ProjectCategory carries slugs that also
for (const spec of UNION_SPECS) { // read as project ids), and a substring test would silently skip that leg. An
for (const id of spec.ids(structures)) { // emptied union (`never`, the state an emptied document leaves) reads as an
if (!typesSource.includes(`'${id}'`)) out.push({ union: spec.union, id }); // empty member list, so a record added on top of it is appended back. Any
// other shape (a one-line union) is reported as unpatchable, never corrupted.
type UnionBlock = { union: string; members: string[]; from: number; to: number };
const MEMBER_LINE = /^[ \t]*\| '([^']+)'[ \t]*;?[ \t]*\r?\n?$/;
const CLOSING_LINE = /^[ \t]*;[ \t]*\r?\n?$/;
// One line of the source including its terminator, or null at end of file.
function nextLine(source: string, from: number): { text: string; end: number } | null {
if (from >= source.length) return null;
const at = source.indexOf('\n', from);
const end = at < 0 ? source.length : at + 1;
return { text: source.slice(from, end), end };
} }
// `from`/`to` are the exact span of the declaration, so nothing else in the
// file is ever rewritten.
function readUnionBlock(source: string, union: string): UnionBlock | null {
const never = new RegExp(`^export type ${union} = never;\\r?\\n?`, 'm').exec(source);
if (never) return { union, members: [], from: never.index, to: never.index + never[0].length };
const header = new RegExp(`^export type ${union} =\\r?\\n`, 'm').exec(source);
if (!header) return null;
const from = header.index;
let pos = from + header[0].length;
const members: string[] = [];
for (;;) {
const line = nextLine(source, pos);
if (!line) break;
const member = MEMBER_LINE.exec(line.text);
if (!member) break;
members.push(member[1]);
pos = line.end;
}
if (members.length === 0) return null;
const closing = nextLine(source, pos);
if (closing && CLOSING_LINE.test(closing.text)) pos = closing.end;
return { union, members, from, to: pos };
}
// An emptied union is `never`, which keeps `Record<never, T>` valid against an
// empty document.
function renderUnion(union: string, members: readonly string[], eol: string): string {
if (members.length === 0) return `export type ${union} = never;${eol}`;
const body = members.map((id) => ` | '${id}'`).join(eol);
return `export type ${union} =${eol}${body};${eol}`;
}
// One pass per union: surviving members keep their order, removed ids are
// dropped, added ids follow the document order. Null when a union's shape is
// not the one the editor writes.
export function applyUnionChanges(
source: string,
changes: { union: string; add: string[]; remove: string[] }[],
): string | null {
// git stores LF; a Windows checkout reads CRLF. A patch keeps the line
// ending the file already uses, so the commit the owner reviews is one line.
const eol = source.includes('\r\n') ? '\r\n' : '\n';
let out = source;
for (const change of changes) {
const block = readUnionBlock(out, change.union);
if (!block) return null;
const removed = new Set(change.remove);
const members = block.members.filter((id) => !removed.has(id));
for (const id of change.add) if (!members.includes(id)) members.push(id);
out = `${out.slice(0, block.from)}${renderUnion(change.union, members, eol)}${out.slice(block.to)}`;
} }
return out; return out;
} }
export function patchUnionSource(source: string, union: string, id: string): string | null { // Ids whose documents have landed but whose union does not match them:
const marker = `export type ${union} =\n`; // missing members to append, stale members to drop. committedStructures() reads
const at = source.indexOf(marker); // the post-PUT base, so a document that has not landed keeps the branch's ids
if (at < 0) return null; // and never reads as stale.
const insertAt = at + marker.length; export function diffIdsWithUnions(
return `${source.slice(0, insertAt)} | '${id}'\n${source.slice(insertAt)}`; store: DraftStore,
typesSource: string,
): { added: { union: string; id: string }[]; removed: { union: string; id: string }[] } {
const structures = store.committedStructures();
const added: { union: string; id: string }[] = [];
const removed: { union: string; id: string }[] = [];
for (const spec of UNION_SPECS) {
const block = readUnionBlock(typesSource, spec.union);
if (!block) continue;
const live = new Set(spec.ids(structures));
for (const id of live) if (!block.members.includes(id)) added.push({ union: spec.union, id });
for (const id of block.members) if (!live.has(id)) removed.push({ union: spec.union, id });
}
return { added, removed };
} }
// --- the store --------------------------------------------------------------------- // --- the store ---------------------------------------------------------------------
@@ -1070,26 +1148,42 @@ export async function saveDraft(
return { results, stoppedEarly: false }; return { results, stoppedEarly: false };
} }
// The third leg of §3.1: once the documents that introduce new ids have // The third leg of §3.1: once the documents that add or drop ids have landed,
// landed, append those ids to their unions in src/types/index.ts so the next // bring their unions in src/types/index.ts to exactly those ids so the next CI
// CI build compiles. Returns the updated source/sha, or null when the patch // build compiles. Returns the updated source/sha, or null when nothing needs
// could not be written (the EditBar reports it and the owner finishes the // changing (an unpatchable shape or a rejected PUT is reported to the EditBar,
// edit in Gitea). // and the owner finishes that edit in Gitea).
export async function saveIdUnions( export async function saveIdUnions(
store: DraftStore, store: DraftStore,
types: { source: string; sha: string }, types: { source: string; sha: string },
branch: string, branch: string,
): Promise<{ added: { union: string; id: string }[]; source?: string; sha?: string; failed?: number } | null> { ): Promise<{
const added = newIdsInCommitted(store, types.source); added: { union: string; id: string }[];
if (added.length === 0) return null; removed: { union: string; id: string }[];
let source = types.source; source?: string;
for (const { union, id } of added) { sha?: string;
const patched = patchUnionSource(source, union, id); failed?: number;
if (!patched) return { added, failed: 0 }; } | null> {
source = patched; const { added, removed } = diffIdsWithUnions(store, types.source);
} if (added.length === 0 && removed.length === 0) return null;
const message = `content: add id union members (${added.map((a) => a.id).join(', ')})`; const grouped = new Map<string, { add: string[]; remove: string[] }>();
const bucket = (union: string) => {
const existing = grouped.get(union);
if (existing) return existing;
const fresh = { add: [] as string[], remove: [] as string[] };
grouped.set(union, fresh);
return fresh;
};
for (const { union, id } of added) bucket(union).add.push(id);
for (const { union, id } of removed) bucket(union).remove.push(id);
const source = applyUnionChanges(
types.source,
[...grouped].map(([union, change]) => ({ union, ...change })),
);
if (source === null) return { added, removed, failed: 0 };
const summary = [...added.map((a) => `+${a.id}`), ...removed.map((r) => `-${r.id}`)].join(', ');
const message = `content: update id union members (${summary})`;
const res = await putTextFile(TYPES_FILE, source, message, types.sha, branch); const res = await putTextFile(TYPES_FILE, source, message, types.sha, branch);
if (!res.ok) return { added, failed: res.status }; if (!res.ok) return { added, removed, failed: res.status };
return { added, source, sha: res.sha }; return { added, removed, source, sha: res.sha };
} }
+1 -1
View File
@@ -66,7 +66,7 @@
"mergeHint": "written to the branch — merge into master to deploy", "mergeHint": "written to the branch — merge into master to deploy",
"offline": "offline — showing bundled content, save disabled", "offline": "offline — showing bundled content, save disabled",
"draftRestored": "draft restored from this session", "draftRestored": "draft restored from this session",
"unionNote": "new ids are also appended to src/types/index.ts", "unionNote": "id unions in src/types/index.ts updated to match the saved content",
"unionFailed": "could not update src/types/index.ts — finish that edit in Gitea", "unionFailed": "could not update src/types/index.ts — finish that edit in Gitea",
"appearsHome": "home", "appearsHome": "home",
"appearsResume": "resume PDF", "appearsResume": "resume PDF",
+1 -1
View File
@@ -66,7 +66,7 @@
"mergeHint": "đã ghi lên branch — merge vào master để deploy", "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", "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", "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", "unionNote": "các id union trong src/types/index.ts đã được cập nhật theo nội dung đã lưu",
"unionFailed": "không cập nhật được src/types/index.ts — hãy hoàn tất sửa trong Gitea", "unionFailed": "không cập nhật được src/types/index.ts — hãy hoàn tất sửa trong Gitea",
"appearsHome": "Trang chủ", "appearsHome": "Trang chủ",
"appearsResume": "CV PDF", "appearsResume": "CV PDF",
-1
View File
@@ -33,7 +33,6 @@ export type ExperienceId =
export type SkillGroupId = export type SkillGroupId =
| 'software-engineering' | 'software-engineering'
| 'system-architecture' | 'system-architecture'
| 'logistics-technology'
| 'ai-ml' | 'ai-ml'
| 'infrastructure' | 'infrastructure'
| 'engineering-practices'; | 'engineering-practices';