mirror of
https://github.com/dong-nz/cv.git
synced 2026-11-22 16:10:40 +07:00
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:
1 parent
1bc12d23a6
commit
7b4a782f59
7 files changed
+121
-73
No files matched your search
@@ -87,9 +87,9 @@ Content is split once, at authoring time, into language-neutral **structure docu
|
||||
|
||||
## Live Edit Mode (`?edit`, v4)
|
||||
|
||||
- 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
|
||||
- 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)
|
||||
- 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
|
||||
- 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
|
||||
- `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
|
||||
@@ -106,7 +106,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-mode.ts (session/auth), 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-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)
|
||||
|
||||
@@ -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 |
|
||||
+9
-3
@@ -6,6 +6,7 @@ import { ThemeProvider } from '@/hooks/useTheme'
|
||||
import { Layout } from '@/components/layout/Layout'
|
||||
import { LanguageProvider } from '@/hooks/useLanguage'
|
||||
import { I18nProvider } from '@/i18n/provider'
|
||||
import { editRequested, hasEditFlag } from '@/i18n/edit-session'
|
||||
import { HomePage } from '@/pages/HomePage'
|
||||
|
||||
// HomePage stays eager: it is the landing route and owns the LCP, so its code must
|
||||
@@ -19,13 +20,18 @@ const PhilosophyPage = lazy(() => import('@/pages/PhilosophyPage').then((m) => (
|
||||
const ContactPage = lazy(() => import('@/pages/ContactPage').then((m) => ({ default: m.ContactPage })))
|
||||
|
||||
// Edit mode is lazy too: visitors never download the draft store, the panel
|
||||
// or the save pipeline (spec-v4 §7 P3.4). The gate only mounts the shell when
|
||||
// `?edit` is present; the shell then authenticates or strips the query again.
|
||||
// or the save pipeline (spec-v4 §7 P3.4). The gate opens the shell on `?edit`
|
||||
// or on a session that is already in the mode; the shell authenticates, or it
|
||||
// closes the session again.
|
||||
const EditModeShell = lazy(() => import('@/components/layout/EditModeShell'))
|
||||
|
||||
function MaybeEditMode({ children }: { children: ReactNode }) {
|
||||
const location = useLocation()
|
||||
const editing = new URLSearchParams(location.search).has('edit')
|
||||
// `?edit` opens edit mode; from there the session flag keeps it across every
|
||||
// navigation and every reload until the EditBar's Exit ends it. The flag and
|
||||
// the query test live in `edit-session.ts`, which carries no dependency on
|
||||
// the draft store, so this gate keeps the edit code out of the entry chunk.
|
||||
const editing = editRequested(location.search) || hasEditFlag()
|
||||
if (!editing) return <>{children}</>
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
|
||||
@@ -9,7 +9,7 @@ import { useState } from 'react';
|
||||
import { useI18n } from '@/i18n/provider';
|
||||
import { DRAFT_DOCS, entityOfDoc } from '@/i18n/draft';
|
||||
import { manifestsClaiming, recordEntity } from '@/data/pages';
|
||||
import { DEFAULT_BRANCH } from '@/i18n/edit-mode';
|
||||
import { DEFAULT_BRANCH } from '@/i18n/edit-session';
|
||||
import type { ConflictField, DocSaveResult, DraftDocId } from '@/i18n/draft';
|
||||
import type { ContentIssue } from '@/i18n/validate';
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// master documents, holds the draft, and re-wraps the tree in an
|
||||
// I18nProvider override — the seven routes ARE the preview. Visitors never
|
||||
// mount this component; its code is never in the entry chunk (§7 P3.4).
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router';
|
||||
import { useLanguage } from '@/hooks/useLanguage';
|
||||
@@ -23,12 +23,13 @@ import {
|
||||
DEFAULT_BRANCH,
|
||||
DRAFT_STORAGE,
|
||||
clearDraftStorage,
|
||||
ensureEditorAuth,
|
||||
editRequested,
|
||||
getEditBranch,
|
||||
requestedBranch,
|
||||
setEditBranch,
|
||||
setEditFlag,
|
||||
} from '@/i18n/edit-mode';
|
||||
} from '@/i18n/edit-session';
|
||||
import { ensureEditorAuth } from '@/i18n/edit-mode';
|
||||
import { EditContext } from '@/hooks/useEdit';
|
||||
import type { EditApi } from '@/hooks/useEdit';
|
||||
import type { CategoryLabels, ContentIssue } from '@/i18n/validate';
|
||||
@@ -73,12 +74,22 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
|
||||
const [saveStopped, setSaveStopped] = useState(false);
|
||||
const [labelsUnavailable, setLabelsUnavailable] = useState(false);
|
||||
|
||||
// The entry URL is read once. The session keeps its branch across internal
|
||||
// navigation (the guard below re-attaches `?edit` to every route), so a
|
||||
// navigation must not re-run the initialization and re-fetch every document.
|
||||
const entrySearchRef = useRef(location.search);
|
||||
|
||||
// Stable across navigations: it reads the live URL instead of closing over
|
||||
// `location`, so the initialization effect that calls it on a failed auth
|
||||
// does not re-run on every route change.
|
||||
const stripEditQuery = useCallback(() => {
|
||||
const params = new URLSearchParams(location.search);
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
params.delete('edit');
|
||||
const query = params.toString();
|
||||
navigate(`${location.pathname}${query ? `?${query}` : ''}${location.hash}`, { replace: true });
|
||||
}, [navigate, location.pathname, location.search, location.hash]);
|
||||
navigate(`${window.location.pathname}${query ? `?${query}` : ''}${window.location.hash}`, {
|
||||
replace: true,
|
||||
});
|
||||
}, [navigate]);
|
||||
|
||||
// Every accepted edit re-derives the resolved content from the draft
|
||||
// documents (same join, same fallback rules as the bundled loader) and
|
||||
@@ -94,13 +105,31 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
|
||||
else clearDraftStorage();
|
||||
}, []);
|
||||
|
||||
// Edit mode survives navigation (owner request 2026-10-24): a route change
|
||||
// that dropped `?edit` gets the parameter back immediately, so the address
|
||||
// keeps describing the mode the session is actually in and a reload from
|
||||
// here reopens it. Only the EditBar's Exit — or a failed auth — ends the
|
||||
// session, and both clear the flag, which unmounts this shell before this
|
||||
// guard could run against them.
|
||||
useEffect(() => {
|
||||
if (phase === 'authenticating') return;
|
||||
if (editRequested(location.search)) return;
|
||||
const params = new URLSearchParams(location.search);
|
||||
params.delete('edit');
|
||||
const rest = params.toString();
|
||||
navigate(`${location.pathname}?edit${rest ? `&${rest}` : ''}${location.hash}`, { replace: true });
|
||||
}, [phase, location.pathname, location.search, location.hash, navigate]);
|
||||
|
||||
// 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
|
||||
// session neither re-authenticates nor re-fetches the documents.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const init = async () => {
|
||||
// `?edit=<branch>` targets that branch; a bare `?edit` resumes the
|
||||
// session's branch or the default. An illegal name exits edit mode the
|
||||
// same way a failed auth does.
|
||||
const requested = requestedBranch(location.search);
|
||||
const requested = requestedBranch(entrySearchRef.current);
|
||||
if (requested === null) {
|
||||
setEditFlag(false);
|
||||
clearDraftStorage();
|
||||
@@ -170,7 +199,7 @@ export default function EditModeShell({ children }: { children: ReactNode }) {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [refresh, stripEditQuery, location.search]);
|
||||
}, [refresh, stripEditQuery]);
|
||||
|
||||
// Mid-edit navigation guard (§5.2).
|
||||
useEffect(() => {
|
||||
|
||||
+5
-54
@@ -1,62 +1,13 @@
|
||||
// Edit-mode session mechanics (spec-v4 §5.2, §6.2): the `?edit` entry, the
|
||||
// sessionStorage flags that keep a session in the mode across reloads, the
|
||||
// target branch (`?edit=<branch>`), and the Basic-auth handshake through the
|
||||
// Edit-mode authentication (spec-v4 §5.2): the Basic-auth handshake through the
|
||||
// protected proxy endpoint. The protected endpoint is the security boundary —
|
||||
// edit mode is only a UI affordance.
|
||||
// edit mode is only a UI affordance. The `?edit` entry, the session flags and
|
||||
// the branch rules live in `edit-session.ts`, which App.tsx reads without
|
||||
// pulling this file's dependency on the draft store into the entry chunk.
|
||||
import { PROXY_BASE } from './draft';
|
||||
|
||||
const EDIT_FLAG = 'portfolio-edit';
|
||||
const BRANCH_FLAG = 'portfolio-edit-branch';
|
||||
export const DRAFT_STORAGE = 'portfolio-draft';
|
||||
|
||||
// The repository's default branch — what a bare `?edit` targets.
|
||||
export const DEFAULT_BRANCH = 'master';
|
||||
import { hasEditFlag } from './edit-session';
|
||||
|
||||
const PROBE_FILE = 'src/data/profile.json';
|
||||
|
||||
// Git's own ref rules, reduced to what a working branch name can be: no
|
||||
// leading '-' or '/', no '..', no '//', no trailing '/', no `.lock` suffix,
|
||||
// and only characters safe in a URL query value.
|
||||
const BRANCH_RE = /^(?!-)(?!\/)(?!.*\.\.)(?!.*\/\/)(?!.*\.lock$)(?!.*\/$)[A-Za-z0-9][A-Za-z0-9._/-]{0,63}$/;
|
||||
|
||||
export function editRequested(search: string): boolean {
|
||||
return new URLSearchParams(search).has('edit');
|
||||
}
|
||||
|
||||
// `?edit` or `?edit=1` → undefined (fall back to the session's branch, or
|
||||
// the default); `?edit=<branch>` → that branch; an illegal name → null (the
|
||||
// shell exits edit mode the same way it does on a failed auth).
|
||||
export function requestedBranch(search: string): string | null | undefined {
|
||||
const value = new URLSearchParams(search).get('edit');
|
||||
if (!value || value === '1') return undefined;
|
||||
return BRANCH_RE.test(value) ? value : null;
|
||||
}
|
||||
|
||||
export function getEditBranch(): string {
|
||||
const saved = sessionStorage.getItem(BRANCH_FLAG);
|
||||
return saved && BRANCH_RE.test(saved) ? saved : DEFAULT_BRANCH;
|
||||
}
|
||||
|
||||
export function setEditBranch(branch: string): void {
|
||||
sessionStorage.setItem(BRANCH_FLAG, branch);
|
||||
}
|
||||
|
||||
export function hasEditFlag(): boolean {
|
||||
return sessionStorage.getItem(EDIT_FLAG) === '1';
|
||||
}
|
||||
|
||||
export function setEditFlag(on: boolean): void {
|
||||
if (on) sessionStorage.setItem(EDIT_FLAG, '1');
|
||||
else {
|
||||
sessionStorage.removeItem(EDIT_FLAG);
|
||||
sessionStorage.removeItem(BRANCH_FLAG);
|
||||
}
|
||||
}
|
||||
|
||||
export function clearDraftStorage(): void {
|
||||
sessionStorage.removeItem(DRAFT_STORAGE);
|
||||
}
|
||||
|
||||
function probeUrl(branch: string, cacheBust: boolean): string {
|
||||
const url = new URL(`${PROXY_BASE}${PROBE_FILE}`, window.location.origin);
|
||||
url.searchParams.set('ref', branch);
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// The edit-mode session state (spec-v4 §5.2, §6.2): the `?edit` entry, the
|
||||
// sessionStorage flags that keep a session in the mode across navigation and
|
||||
// reloads, and the target branch. Dependency-free on purpose — App.tsx reads
|
||||
// the mode gate from here, and that import must not pull the draft store or
|
||||
// the save pipeline into the entry chunk (spec-v4 §7 P3.4). The Basic-auth
|
||||
// handshake that needs them stays in `edit-mode.ts`.
|
||||
const EDIT_FLAG = 'portfolio-edit';
|
||||
const BRANCH_FLAG = 'portfolio-edit-branch';
|
||||
export const DRAFT_STORAGE = 'portfolio-draft';
|
||||
|
||||
// The repository's default branch — what a bare `?edit` targets.
|
||||
export const DEFAULT_BRANCH = 'master';
|
||||
|
||||
// Git's own ref rules, reduced to what a working branch name can be: no
|
||||
// leading '-' or '/', no '..', no '//', no trailing '/', no `.lock` suffix,
|
||||
// and only characters safe in a URL query value.
|
||||
const BRANCH_RE = /^(?!-)(?!\/)(?!.*\.\.)(?!.*\/\/)(?!.*\.lock$)(?!.*\/$)[A-Za-z0-9][A-Za-z0-9._/-]{0,63}$/;
|
||||
|
||||
export function editRequested(search: string): boolean {
|
||||
return new URLSearchParams(search).has('edit');
|
||||
}
|
||||
|
||||
// `?edit` or `?edit=1` → undefined (fall back to the session's branch, or
|
||||
// the default); `?edit=<branch>` → that branch; an illegal name → null (the
|
||||
// shell exits edit mode the same way it does on a failed auth).
|
||||
export function requestedBranch(search: string): string | null | undefined {
|
||||
const value = new URLSearchParams(search).get('edit');
|
||||
if (!value || value === '1') return undefined;
|
||||
return BRANCH_RE.test(value) ? value : null;
|
||||
}
|
||||
|
||||
export function getEditBranch(): string {
|
||||
const saved = sessionStorage.getItem(BRANCH_FLAG);
|
||||
return saved && BRANCH_RE.test(saved) ? saved : DEFAULT_BRANCH;
|
||||
}
|
||||
|
||||
export function setEditBranch(branch: string): void {
|
||||
sessionStorage.setItem(BRANCH_FLAG, branch);
|
||||
}
|
||||
|
||||
// The mode is a session, not a URL state (owner request 2026-10-24): `?edit`
|
||||
// opens it, the flag keeps it while the user moves through the site, and only
|
||||
// the EditBar's Exit clears it. Every internal link the shell hands the router
|
||||
// carries `?edit`, so the URL and the flag agree in practice; the flag is what
|
||||
// survives a back navigation to an address taken before edit mode opened.
|
||||
export function hasEditFlag(): boolean {
|
||||
return sessionStorage.getItem(EDIT_FLAG) === '1';
|
||||
}
|
||||
|
||||
export function setEditFlag(on: boolean): void {
|
||||
if (on) sessionStorage.setItem(EDIT_FLAG, '1');
|
||||
else {
|
||||
sessionStorage.removeItem(EDIT_FLAG);
|
||||
sessionStorage.removeItem(BRANCH_FLAG);
|
||||
}
|
||||
}
|
||||
|
||||
export function clearDraftStorage(): void {
|
||||
sessionStorage.removeItem(DRAFT_STORAGE);
|
||||
}
|
||||
Reference in new issue
Block a user