feat(edit): keep edit mode across navigation, only Exit leaves

Edit mode is a session, not a URL state. MaybeEditMode mounts the shell on
?edit or on the session flag; while mounted, EditModeShell re-attaches ?edit
after a route change that dropped it (replace navigation, skipped while
authenticating so it never fights a failed auth). The session initializes once
per mount - entry URL from a ref, stripEditQuery reads window.location - so
navigation neither re-authenticates, re-fetches, nor re-restores the draft.

?edit parsing, the session/branch flags and the portfolio-draft key move to a
dependency-free src/i18n/edit-session.ts so App.tsx can read the gate without
pulling the Basic-auth probe (and through it draft.ts) into the entry chunk;
edit-mode.ts is now the auth handshake alone.

Verified: tsc -b, pnpm build (entry chunk carries no probe literal,
EditModeShell stays a separate lazy chunk), pnpm lint (no new warnings),
throwaway smokes for the session semantics (17/17) and the router behaviour
behind the guard (5/5), both deleted after the run.
This commit is contained in:
dong.nguyen committed 2026-10-24 13:56:16 +07:00
1 parent 1bc12d23a6
commit 7b4a782f59
7 files changed
+121 -73

No files matched your search

+5 -3
View File
@@ -88,7 +88,7 @@ The only HTML string in the entire data layer is `profile.tagline` (`src/data/pr
### D10 — Target-branch editing via `?edit=<branch>` (owner decision, 2026-10-22)
The Gitea Contents API already supports branch targeting natively — `?ref=<branch>` on GET, `branch` in the PUT body — so the editor exposes it in the entry URL instead of hardcoding `master`: `?edit=<branch>` reads and writes that branch; a bare `?edit` (or `?edit=1`) resumes the session's last branch, defaulting to `master`. Branch names are validated against git's ref rules (`edit-mode.ts`) before any request; an illegal name exits edit mode exactly like a failed auth. The target branch must already exist in the repository — Contents API updates never create branches. Deploy semantics are unchanged (owner decision): only pushes to `master` trigger the pipeline, so a save to a working branch shows a merge hint in the EditBar instead of the deploy-queued note. Chosen over a fixed env-configured branch (no per-session flexibility) and over a branch-selector UI (branch-list API call + a new control surface for a single user).
The Gitea Contents API already supports branch targeting natively — `?ref=<branch>` on GET, `branch` in the PUT body — so the editor exposes it in the entry URL instead of hardcoding `master`: `?edit=<branch>` reads and writes that branch; a bare `?edit` (or `?edit=1`) resumes the session's last branch, defaulting to `master`. Branch names are validated against git's ref rules (`edit-session.ts`) before any request; an illegal name exits edit mode exactly like a failed auth. The target branch must already exist in the repository — Contents API updates never create branches. Deploy semantics are unchanged (owner decision): only pushes to `master` trigger the pipeline, so a save to a working branch shows a merge hint in the EditBar instead of the deploy-queued note. Chosen over a fixed env-configured branch (no per-session flexibility) and over a branch-selector UI (branch-list API call + a new control surface for a single user).
---
@@ -330,7 +330,7 @@ Type changes in `src/types/index.ts`: every `*En` optional is deleted from the 6
The site itself gains an edit mode. There is no second preview machinery — the seven routes *are* the preview.
- **Entry:** edit mode activates only for the authenticated owner (handshake against the protected proxy endpoint, §6.2; activation stored in `sessionStorage`; a `?edit` query on any route re-enters the mode within a session; the query is stripped from the URL on exit so shared/canonical URLs stay clean). Anonymous visitors never see edit affordances.
- **Entry:** edit mode activates only for the authenticated owner (handshake against the protected proxy endpoint, §6.2; activation stored in `sessionStorage`). A `?edit` query on any route opens the mode; from there the session flag **is** the mode — every internal navigation carries `?edit` again and a reload reopens the same session (row 24). The query is stripped from the URL on exit so shared/canonical URLs stay clean. Anonymous visitors never see edit affordances.
- **Draft initialization:** the draft is initialized from **live repository files fetched through the proxy** (`GET` per document + its blob `sha`), not from the bundle — the bundle may be older than master if anyone edited via Gitea web since the last build, and a bundle-seeded draft would silently revert those edits. The static bundle is used only as an offline fallback, with a visible "stale" warning.
- **Mechanism:** edit mode wraps `<Layout>` in `<I18nProvider override={draft}>`. All pages, all components, both languages render the draft — text **and** structure.
- **Inline text editing:** rendered text nodes bound to a text-document path become editable on focus (`contentEditable`); blur writes `{ path, value }` into the draft. Editing `projects['iot-dws-integration'].title` updates the card on `/projects`, the header on `/projects/:id`, and the featured block on the home page **simultaneously** — one draft, every consumer.
@@ -349,6 +349,7 @@ stateDiagram-v2
authenticating --> visitor: 401 / cancel
authenticating --> editing: auth ok — draft = live branch docs + shas
editing --> editing: accepted edit → draft + sessionStorage copy
editing --> editing: internal navigation → `?edit` re-attached, same session
editing --> saving: save (validator passes, §3.6)
saving --> saved: commits written — deploy queued
saving --> conflict: 412 on a document
@@ -359,7 +360,7 @@ stateDiagram-v2
- **Entry:** `?edit` on any route → the app probes the protected endpoint once (hidden-iframe GET to trigger the native Basic prompt, §6.2). 401 or cancel → normal visitor site, zero affordances. Auth OK → session flag in `sessionStorage` + draft initialization (§5.1). Within a session the browser re-attaches Basic credentials to later requests on its own — no repeated prompt. The probe targets the session's branch: `?edit=<branch>` selects it, a bare `?edit` resumes the last one or `master` (D10); the branch name is validated before the probe and stored beside the session flag.
- **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.
- **Exit:** explicit action in the EditBar — save-or-discard prompt if dirty, clear flag + draft, `history.replaceState` strips `?edit`.
- **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.
### 5.3 `EditableText` contract (inline editing)
@@ -605,3 +606,4 @@ Deferred (not v4):
| 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`. **Superseded the same day by row 23**: the whole union leg — `saveIdUnions`, `diffIdsWithUnions`, `applyUnionChanges`, `unionNote`, `unionError`, `UnionLogEntry`, `onUnionsSaved` — was deleted with spec-v5; the `TS2741` it fixed is now prevented by regenerating the unions, and the delete case is covered by `smoke-generated-ids.ts` + the `tsc` re-check |
| 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 |