mirror of
https://github.com/dong-nz/cv.git
synced 2026-11-22 16:10:40 +07:00
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:
1 parent
ee1d524bd0
commit
5c71b52d81
13 files changed
+320
-71
No files matched your search
@@ -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
@@ -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';
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
"linkedinUrl",
|
||||
"linkedinHandle",
|
||||
"telegramUrl",
|
||||
"telegramHandle"
|
||||
"telegramHandle",
|
||||
"name"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"id": "experience",
|
||||
"route": "/experience",
|
||||
"content": [
|
||||
{ "entity": "profile", "fields": ["tldr"] },
|
||||
{ "entity": "profile", "fields": ["tldr", "name"] },
|
||||
{ "entity": "experiences", "fields": ["*"] }
|
||||
],
|
||||
"ui": ["experience"]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"id": "philosophy",
|
||||
"route": "/philosophy",
|
||||
"content": [
|
||||
{ "entity": "profile", "fields": ["philosophyQuotes"] }
|
||||
{ "entity": "profile", "fields": ["philosophyQuotes", "name"] }
|
||||
],
|
||||
"ui": ["philosophy"]
|
||||
}
|
||||
@@ -5,7 +5,8 @@
|
||||
{
|
||||
"entity": "projects",
|
||||
"fields": ["title", "summary", "role", "metrics", "technologies", "category", "sections.*"]
|
||||
}
|
||||
},
|
||||
{ "entity": "profile", "fields": ["name"] }
|
||||
],
|
||||
"ui": ["projectDetail"]
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
"id": "projects",
|
||||
"route": "/projects",
|
||||
"content": [
|
||||
{ "entity": "projects", "fields": ["*"] }
|
||||
{ "entity": "projects", "fields": ["*"] },
|
||||
{ "entity": "profile", "fields": ["name"] }
|
||||
],
|
||||
"ui": ["projects"]
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
Reference in new issue
Block a user