@elytracms/studio 0.0.9 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
3
- import { createCollectionRegistry, createDocumentStore, documentKey, documentSchema, resolveField, sampleDocuments, sampleFilterableCollections, sampleLocaleConfig, samplePublishedKeys, resolveSingletonDocument, titleFieldOf, validateDocument, } from '@elytracms/core/cms-core';
3
+ import { createCollectionRegistry, clearHiddenForPublish, createDocumentStore, documentKey, documentSchema, resolveField, sampleDocuments, sampleFilterableCollections, sampleLocaleConfig, samplePublishedKeys, resolveSingletonDocument, titleFieldOf, validateDocument, } from '@elytracms/core/cms-core';
4
4
  import { validateCompositionValue } from '@elytracms/core/project-graph';
5
5
  import { collectComponentEmbeds, parseRichTextValue } from '@elytracms/core/rich-text';
6
6
  import { configureStudioLocales, useStudioLocale } from '@elytracms/studio/lib/locale';
@@ -337,7 +337,15 @@ export function CmsProvider({ children, projectId, initialCollections, initialDo
337
337
  }, [projectId, setPublished]);
338
338
  const publishDocument = useCallback(async (ref) => {
339
339
  setPublished(ref, true); // optimistic
340
- persisterRef.current?.publishDocument(ref);
340
+ // EC-273: clear conditionally-hidden, non-opt-out field values from the
341
+ // PUBLISHED snapshot so delivery never carries stale hidden data — the live
342
+ // draft row is untouched. `clearHiddenForPublish` returns the same document
343
+ // when nothing is cleared, so a collection without conditional fields takes
344
+ // the default verbatim-pin path (snapshot omitted).
345
+ const doc = documentsRef.current.find((d) => d.collection === ref.collection && d.id === ref.id);
346
+ const collection = collectionsRef.current.find((c) => c.id === ref.collection);
347
+ const cleared = doc && collection ? clearHiddenForPublish(collection, doc) : undefined;
348
+ persisterRef.current?.publishDocument(ref, cleared && cleared !== doc ? cleared : undefined);
341
349
  await persisterRef.current?.flush();
342
350
  await reconcilePublished(ref);
343
351
  }, [setPublished, reconcilePublished]);
@@ -1 +1 @@
1
- {"version":3,"file":"cms-store.js","sourceRoot":"","sources":["../../../src/components/cms/cms-store.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAEpG,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,WAAW,EACX,cAAc,EACd,YAAY,EACZ,eAAe,EACf,2BAA2B,EAC3B,kBAAkB,EAClB,mBAAmB,EACnB,wBAAwB,EACxB,YAAY,EACZ,gBAAgB,GACjB,MAAM,0BAA0B,CAAA;AAajC,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAA;AAExE,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAA;AAEtF,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAA;AACtF,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAA;AACxF,OAAO,EAAE,OAAO,EAAE,MAAM,6BAA6B,CAAA;AACrD,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAA;AAO1F,OAAO,EACL,WAAW,EACX,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,cAAc,EACd,SAAS,EACT,kBAAkB,EAClB,aAAa,EACb,eAAe,GAChB,MAAM,iCAAiC,CAAA;AAExC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AAgB9C,oFAAoF;AACpF,MAAM,gBAAgB,GAA6B;IACjD,KAAK,EAAE,CAAC,KAAK,CAAC;CACf,CAAA;AAED;;;;;GAKG;AACH,MAAM,UA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AAU;QACV,UAAU;QACV,OAAO;QACP,QAAQ;QACR,YAAY;KACb,CACF,CAAA;IAED,OAAO,KAAC,UAAU,CAAC,QAAQ,IAAC,KAAK,EAAE,MAAM,YAAG,QAAQ,GAAuB,CAAA;AAC7E,CAAC;AAED,MAAM,UAAU,MAAM;IACpB,MAAM,KAAK,GAAG,UAAU,CAAC,UAAU,CAAC,CAAA;IACpC,IAAI,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAA;IAC1E,OAAO,KAAK,CAAA;AACd,CAAC;AAED,oEAAoE;AACpE,MAAM,UAAU,UAAU,CAAC,KAAe;IACxC,OAAO,KAAK,CAAC,IAAI,EAAE,KAAK,IAAI,KAAK,CAAC,IAAI,CAAA;AACxC,CAAC;AAED,OAAO,EAAE,YAAY,EAAE,CAAA","sourcesContent":["import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport {\n createCollectionRegistry,\n createDocumentStore,\n documentKey,\n documentSchema,\n resolveField,\n sampleDocuments,\n sampleFilterableCollections,\n sampleLocaleConfig,\n samplePublishedKeys,\n resolveSingletonDocument,\n titleFieldOf,\n validateDocument,\n} from '@elytracms/core/cms-core'\nimport type {\n BlocksFieldDef,\n CmsDocument,\n CmsValidationIssue,\n CollectionDef,\n CompositionIssue,\n DocumentRef,\n FieldDef,\n Locale,\n LocaleConfig,\n RichTextFieldDef,\n} from '@elytracms/core/cms-core'\nimport { validateCompositionValue } from '@elytracms/core/project-graph'\nimport type { ComponentNode } from '@elytracms/core/project-graph'\nimport { collectComponentEmbeds, parseRichTextValue } from '@elytracms/core/rich-text'\nimport type { DocumentVersionRecord } from '@elytracms/core/persistence'\nimport { configureStudioLocales, useStudioLocale } from '@elytracms/studio/lib/locale'\nimport { getStudioRegistry, studioManifestLookup } from '@elytracms/studio/lib/registry'\nimport { slugify } from '@elytracms/studio/lib/utils'\nimport { createCmsPersister, getStudioOperations } from '@elytracms/studio/lib/operations'\nimport type {\n CmsPersister,\n OperationError,\n OperationResult,\n OperationsClient,\n} from '@elytracms/studio/lib/operations'\nimport {\n ALL_VIEW_ID,\n canonicalViewState,\n defaultViewState,\n deleteSavedView,\n loadSavedViews,\n newViewId,\n normalizeViewState,\n saveSavedView,\n viewStatesEqual,\n} from '@elytracms/studio/lib/cms-views'\nimport type { TableViewState } from '@elytracms/studio/lib/cms-views'\nimport { useOptionalAssets } from '../assets/assets-store'\nimport { commitCellEdit } from './cell-edit'\nimport type { CellCommitInput, CellCommitOutcome } from './cell-edit'\nimport { runBulkAction } from './bulk-actions'\nimport type { BulkAction, BulkReport } from './bulk-actions'\n\n/**\n * A saved table view (EC-169, supersedes the EC-071 column presets): a named\n * bundle of filters (closed AD-3 vocabulary), sort, and visible/ordered\n * columns. Named views persist project-scoped through operations (see\n * `lib/cms-views/views-store`); the unnamed \"All documents\" default is derived\n * per collection and never persisted.\n */\nexport interface SavedView {\n id: string\n name: string\n state: TableViewState\n}\n\n/** Demo per-field access (brief §8.4, EC-078). Read-only fields render disabled. */\nconst READ_ONLY_FIELDS: Record<string, string[]> = {\n asset: ['url'],\n}\n\n/**\n * Mint a collision-safe, slug-derived page id (EC-192): the slug of the page name,\n * suffixed `-2`/`-3`/… until it is free among the ids already taken. Empty or\n * symbol-only names fall back to `page`. Pure so the id rule is testable without\n * the store; `createPage` applies it against the live page documents.\n */\nexport function nextPageId(name: string, taken: ReadonlySet<string>): string {\n const base = slugify(name) || 'page'\n let id = base\n for (let n = 2; taken.has(id); n += 1) id = `${base}-${n}`\n return id\n}\n\n/**\n * EC-188: validate a `blocks` composition field value against the field's `allow`\n * vocabulary + the code-owned component registry (the leash), mapping graph\n * issues into plain CMS findings. Injected into `validateDocument` so cms-core\n * stays free of `@elytracms/core/project-graph`. Never throws — a malformed (non-node)\n * value degrades to a single finding, matching the \"validation is first-class,\n * never a crash\" rule.\n */\nfunction validateComposition(value: unknown, field: BlocksFieldDef): CompositionIssue[] {\n if (value == null) return []\n const roots = Array.isArray(value) ? value : [value]\n if (!roots.every((r) => r != null && typeof r === 'object' && 'componentId' in r)) {\n return [{ message: 'is not a valid composition (expected component nodes)', severity: 'error' }]\n }\n const components = getStudioRegistry().registry.lookup\n return validateCompositionValue(value as ComponentNode | ComponentNode[], {\n allow: field.allow,\n components,\n }).map((issue) => ({\n message: issue.message,\n severity: issue.severity,\n nodePath: issue.path.join('/'),\n }))\n}\n\n/**\n * EC-189: validate the composition embeds inside a `richText` field value. Each\n * `componentEmbed` holds a single `ComponentNode` constrained by the field's\n * `allow` vocabulary (the SAME leash a `blocks` field uses). Parse the value, walk\n * its embeds at any depth, and validate each embedded node via\n * `validateCompositionValue`; findings carry the rich-text node path joined with\n * the in-embed graph path. Injected into `validateDocument` so cms-core depends on\n * neither `@elytracms/core/project-graph` nor `@elytracms/core/rich-text`. Never throws — a\n * malformed embed degrades to a single finding.\n */\nfunction validateRichTextEmbeds(value: unknown, field: RichTextFieldDef): CompositionIssue[] {\n if (value == null) return []\n const parsed = parseRichTextValue(value)\n // A plain-string / schema-invalid rich-text value carries no embeds to check\n // here (scalar type validation owns reporting a malformed value).\n if (!parsed.ok) return []\n const components = getStudioRegistry().registry.lookup\n const out: CompositionIssue[] = []\n for (const occurrence of collectComponentEmbeds(parsed.value.doc)) {\n if (!occurrence.embedded) {\n out.push({\n message: `embed at ${occurrence.nodePath} is missing a valid embedded component`,\n severity: 'error',\n nodePath: occurrence.nodePath,\n })\n continue\n }\n for (const issue of validateCompositionValue(occurrence.embedded, {\n allow: field.allow,\n components,\n })) {\n out.push({\n message: issue.message,\n severity: issue.severity,\n nodePath: `${occurrence.nodePath}/attrs/node/${issue.path.join('/')}`,\n })\n }\n }\n return out\n}\n\nexport interface ImportReport {\n added: number\n rejected: { id: string; issues: CmsValidationIssue[] }[]\n}\n\n/**\n * A document's recorded version history plus its live pin (EC-224), as the\n * Versions inspector pane reads it. `versions` is newest-first; `publishedVersion`\n * is the recorded version currently pinned live, absent when unpublished.\n */\nexport interface DocumentVersionsView {\n versions: DocumentVersionRecord[]\n publishedVersion?: number\n}\n\nexport interface CmsStore {\n /** The project this CMS session edits (set when persistence is enabled); the asset picker scopes the real library by it (EC-152). */\n projectId?: string\n collections: readonly CollectionDef[]\n localeConfig: LocaleConfig\n /**\n * The studio's ambient active locale (EC-176): table cells, detail forms,\n * and inline edits all display and write THIS locale. Switched once via the\n * shared `LocaleSwitcher`, never per control.\n */\n activeLocale: Locale\n getCollection(id: string): CollectionDef | undefined\n documentsOf(collectionId: string): CmsDocument[]\n getDocument(ref: DocumentRef): CmsDocument | undefined\n /** Resolve a relation/asset target's display title. */\n titleOf(ref: DocumentRef): string\n saveDocument(doc: CmsDocument): void\n /**\n * Commit ONE field edit from the table (EC-168): optimistic session apply +\n * exactly one `documents.upsert` operations command, awaited. Validation\n * failures and operation rejections return a structured error (the caller\n * renders it on the cell) and leave the session rolled back.\n */\n commitFieldEdit(input: CellCommitInput): Promise<CellCommitOutcome>\n createDocument(collectionId: string): DocumentRef\n /** Create a named page (`page` collection) with a stable, slug-derived id. */\n createPage(input: { name: string }): DocumentRef\n /**\n * Ensure a singleton collection's lone document exists and return its ref\n * (EC-274). Resolves the existing single document, or creates one with a normal\n * generated id (never the collection id). Idempotent. The singleton route opens\n * through this so the one document always exists to edit.\n */\n ensureSingletonDocument(collectionId: string): DocumentRef\n deleteDocument(ref: DocumentRef): void\n /**\n * Is this document currently published? Sourced from the version POINTER\n * (EC-224), not the flat `state` enum — seeded from hydration and updated by\n * {@link publishDocument}/{@link unpublishDocument}.\n */\n isPublished(ref: DocumentRef): boolean\n /**\n * Publish: snapshot the draft as a new version and pin it live (EC-224).\n * Flips published-ness optimistically, then reconciles against the backend\n * record (EC-225) so the badge can never claim a publish the backend refused\n * (e.g. blocked by publish-time field validation).\n */\n publishDocument(ref: DocumentRef): Promise<void>\n /**\n * Unpublish: clear the live version pin (EC-224). Blocked at the operations\n * layer while strict relation fields published-reference it (EC-173); the\n * optimistic flip reconciles against the backend on rejection (EC-225).\n */\n unpublishDocument(ref: DocumentRef): Promise<void>\n /**\n * Load this document's recorded version history + live pin (EC-224) for the\n * Versions inspector pane. Fixture/playground sessions (no project) have no\n * persisted history → an empty view. Failures surface as {@link persistError}.\n */\n loadDocumentVersions(ref: DocumentRef): Promise<DocumentVersionsView>\n /**\n * Restore a recorded version as the new working draft (EC-224): the operation\n * snapshots the current draft first (so the rollback is itself undoable), then\n * loads the chosen snapshot. Returns the restored draft (or null on\n * failure/fixture session) so the open editor can adopt it.\n */\n restoreDocumentVersion(ref: DocumentRef, version: number): Promise<CmsDocument | null>\n importDocuments(collectionId: string, docs: unknown[]): ImportReport\n validate(doc: CmsDocument): CmsValidationIssue[]\n isFieldReadOnly(collectionId: string, field: FieldDef): boolean\n // Saved views (EC-169): named filter/sort/column bundles per collection,\n // persisted project-scoped through operations commands (lib/cms-views).\n viewsOf(collectionId: string): SavedView[]\n activeViewId(collectionId: string): string\n /** Switch views — resets the working table state to the view's state. */\n setActiveView(collectionId: string, viewId: string): void\n /** The live table state (the active view's state plus unsaved edits). */\n tableStateOf(collectionId: string): TableViewState\n /**\n * Update the working state. Always pass an updater when deriving from the\n * previous state — render-time snapshots go stale across rapid events.\n */\n setTableState(\n collectionId: string,\n update: TableViewState | ((prev: TableViewState) => TableViewState),\n ): void\n /** Does the working state diverge from the active view (\"unsaved changes\")? */\n isViewDirty(collectionId: string): boolean\n /** Discard working-state edits, back to the active view. */\n resetTableState(collectionId: string): void\n /** Persist the working state into the active named view. False on rejection. */\n saveActiveView(collectionId: string): Promise<boolean>\n /** Persist the working state as a new named view and activate it. */\n saveViewAs(collectionId: string, name: string): Promise<boolean>\n /** Delete a named view — a view-only operation; documents are never touched. */\n deleteView(collectionId: string, viewId: string): Promise<boolean>\n /**\n * Bulk publish/unpublish/delete (EC-169): one operations command PER item,\n * per-item outcomes in the report — partial failure is enumerated, never\n * silent. Only succeeded items mutate the session.\n */\n runBulk(collectionId: string, ids: readonly string[], action: BulkAction): Promise<BulkReport>\n /**\n * Mirror a collection into the session (e.g. an accepted AI-generated\n * schema, EC-097). Replaces by id. Session-only: persistence happens through\n * the accept flow's changeset (`schema.upsertCollection`), not here.\n */\n addCollection(def: CollectionDef): void\n /**\n * Most recent failed/denied persisted mutation (structured, from the\n * operation result). Rendered by the CMS surface — never a silent failure.\n */\n persistError: OperationError | null\n clearPersistError(): void\n /** Seed the persisted baseline now (e.g. before applying an AI changeset). */\n ensurePersistedBaseline(): Promise<void>\n /** Await all queued persisted mutations (tests, publish flows). */\n flushPersistence(): Promise<void>\n}\n\nconst CmsContext = createContext<CmsStore | null>(null)\n\nfunction primaryField(collection: CollectionDef): string {\n return titleFieldOf(collection)?.name ?? collection.fields[0]?.name ?? 'id'\n}\n\n/** The unnamed built-in view: no filters, no sort, every field visible. */\nfunction defaultView(collection: CollectionDef | undefined): SavedView {\n return {\n id: ALL_VIEW_ID,\n name: 'All documents',\n state: collection\n ? defaultViewState(collection)\n : { filters: [], sort: null, columns: [], hidden: [] },\n }\n}\n\n/**\n * The CMS session store (EC-141): documents and collections are optimistic,\n * synchronous session state (live validation while typing); every mutation —\n * create/save/delete/state transitions — is mirrored onto the operations\n * layer (`documents.*` / `schema.*` commands) through {@link createCmsPersister}.\n * Failed/denied commands surface as {@link CmsStore.persistError}.\n */\nexport function CmsProvider({\n children,\n projectId,\n initialCollections,\n initialDocuments,\n initialPublishedKeys,\n initialLocaleConfig,\n}: {\n children: ReactNode\n /** Enables persistence through the shared operations client. */\n projectId?: string\n /** Seed collections (e.g. from an imported starter kit, EC-119); defaults to the samples. */\n initialCollections?: CollectionDef[]\n initialDocuments?: CmsDocument[]\n /**\n * Published document keys from hydration (EC-224): the version pointer\n * (`publishedVersion` set). Absent (kit / fixture sessions) → the sample\n * fixtures' published set (`samplePublishedKeys`).\n */\n initialPublishedKeys?: readonly string[]\n /** Locale config for the seeded content; defaults to the sample config. */\n initialLocaleConfig?: LocaleConfig\n}) {\n const [documents, setDocuments] = useState<CmsDocument[]>(() =>\n (initialDocuments ?? sampleDocuments).map((d) => structuredClone(d)),\n )\n // Published-ness as the version POINTER (EC-224), decoupled from the flat\n // `state` enum: seeded from hydration's pointer set, or — when none is supplied\n // — the canonical sample published set for the playground. A kit's imported\n // content (`initialDocuments` without a pointer set) starts unpublished\n // (drafts) until an editor publishes it. The flat `state` is never consulted.\n const [publishedKeys, setPublishedKeys] = useState<Set<string>>(() => {\n if (initialPublishedKeys) return new Set(initialPublishedKeys)\n return new Set(initialDocuments ? [] : samplePublishedKeys)\n })\n // Named saved views per collection (EC-169): loaded from the operations\n // layer (project-scoped, shared across editors) and mutated through it.\n const [savedViews, setSavedViews] = useState<Record<string, SavedView[]>>({})\n const [activeViews, setActiveViews] = useState<Record<string, string>>({})\n // The live table state per collection where it diverges from the active\n // view; absent key = exactly the active view's state (not dirty).\n const [tableStates, setTableStates] = useState<Record<string, TableViewState>>({})\n // Collections are stateful so AI-generated schemas (EC-097) can be accepted\n // into the session. The session schema IS the source the sort/filter\n // offering follows (EC-177 gap 3): hydrated sessions receive the persisted\n // schema via `initialCollections`; the fixture fallback is the canonical\n // cms-core sample schema WITH its declared `filterable` flags — no\n // session-side widenings, so the studio never offers a field the backend's\n // delivery engine would reject.\n const [collections, setCollections] = useState<CollectionDef[]>(() => [\n ...(initialCollections ?? sampleFilterableCollections),\n ])\n const [persistError, setPersistError] = useState<OperationError | null>(null)\n const seq = useRef(0)\n // EC-274: collection ids whose lone singleton document this session has already\n // created — a synchronous guard so a re-invoked effect (or StrictMode's double\n // mount) never materializes a second document under a freshly generated id.\n const ensuredSingletons = useRef<Set<string>>(new Set())\n\n // Latest session state for the persister's lazy baseline (no re-subscribing).\n const collectionsRef = useRef(collections)\n collectionsRef.current = collections\n const documentsRef = useRef(documents)\n documentsRef.current = documents\n\n const persisterRef = useRef<CmsPersister | null>(null)\n if (persisterRef.current === null && projectId !== undefined) {\n persisterRef.current = createCmsPersister({\n projectId,\n getOperations: async () => (await getStudioOperations()).operations,\n getCollections: () => collectionsRef.current,\n getDocuments: () => documentsRef.current,\n // EC-277: self-type composition static props on write (the manifest half of\n // the lens), so extraction stays schema-free. Document fields self-type via\n // the schema alone (above); the registry adds blocks/embed prop coverage.\n lookupManifest: studioManifestLookup(),\n onError: setPersistError,\n })\n }\n\n const registry = useMemo(() => createCollectionRegistry(collections), [collections])\n const store = useMemo(() => createDocumentStore(documents), [documents])\n const localeConfig = initialLocaleConfig ?? sampleLocaleConfig\n\n // Asset existence is validated against the REAL asset library (assets live in\n // their own repository, not as CMS documents). With the ambient AssetsProvider\n // present, the oracle is the set of uploaded asset ids — but only once loaded;\n // while it loads we are optimistic so a valid upload is never transiently\n // flagged \"unknown\". With no provider (tests/fixtures), the oracle is absent\n // and asset existence falls back to the document store.\n const assetStore = useOptionalAssets()\n const assetExists = useMemo<((id: string) => boolean) | undefined>(() => {\n if (!assetStore) return undefined\n if (assetStore.status !== 'ready') return () => true\n const ids = new Set(assetStore.assets.map((asset) => asset.id))\n return (id) => ids.has(id)\n }, [assetStore])\n\n // The ambient studio locale (EC-176): this session's locale config drives\n // the switcher options; every CMS surface follows the one active locale.\n const { locale: activeLocale } = useStudioLocale()\n useEffect(() => {\n configureStudioLocales(localeConfig)\n }, [localeConfig])\n\n const getCollection = useCallback((id: string) => registry.get(id), [registry])\n\n const getDocument = useCallback(\n (ref: DocumentRef) => documents.find((d) => d.collection === ref.collection && d.id === ref.id),\n [documents],\n )\n\n const titleOf = useCallback(\n (ref: DocumentRef) => {\n const doc = documents.find((d) => d.collection === ref.collection && d.id === ref.id)\n const collection = registry.get(ref.collection)\n if (!doc || !collection) return ref.id\n // Resolve through the locale layer in the ambient active locale (EC-176)\n // with EC-018 fallback, so localized titles follow the switcher.\n const { value } = resolveField(\n collection,\n doc,\n primaryField(collection),\n activeLocale,\n localeConfig,\n )\n return typeof value === 'string' && value ? value : ref.id\n },\n [documents, registry, localeConfig, activeLocale],\n )\n\n const saveDocument = useCallback((doc: CmsDocument) => {\n setDocuments((prev) => {\n const i = prev.findIndex((d) => d.collection === doc.collection && d.id === doc.id)\n if (i < 0) return [...prev, doc]\n const next = [...prev]\n next[i] = doc\n return next\n })\n persisterRef.current?.upsertDocument(doc)\n }, [])\n\n const commitFieldEdit = useCallback(\n (input: CellCommitInput): Promise<CellCommitOutcome> => {\n const replaceWith = (doc: CmsDocument) =>\n setDocuments((prev) =>\n prev.map((d) => (d.collection === doc.collection && d.id === doc.id ? doc : d)),\n )\n const persister = persisterRef.current\n return commitCellEdit(\n {\n registry,\n documents: documentsRef.current,\n localeConfig,\n applySession: replaceWith,\n rollbackSession: replaceWith,\n ...(persister && projectId !== undefined\n ? {\n dispatch: async (next: CmsDocument) => {\n // Make sure the persisted baseline + every queued mutation\n // landed first, then issue the commit's single command.\n await persister.ensureBaseline()\n const { operations } = await getStudioOperations()\n return operations.documents.upsert({ projectId, document: next })\n },\n }\n : {}),\n },\n input,\n )\n },\n [registry, localeConfig, projectId],\n )\n\n const createDocument = useCallback((collectionId: string): DocumentRef => {\n seq.current += 1\n const id = `new-${collectionId}-${seq.current}`\n const doc: CmsDocument = { collection: collectionId, id, values: {} }\n setDocuments((prev) => [...prev, doc])\n persisterRef.current?.upsertDocument(doc)\n return { collection: collectionId, id }\n }, [])\n\n // EC-192: create a named page document with a stable, slug-derived id (not an\n // opaque `new-page-N`), so the route bound to it reads as a real address and\n // the id survives as the canonical key. Collision-safe against existing page\n // ids. The route itself is written by the caller (NewPageDialog) through the\n // operations layer, so the two writes stay in their own concerns.\n const createPage = useCallback((input: { name: string }): DocumentRef => {\n const collectionId = 'page'\n const taken = new Set(\n documentsRef.current.filter((d) => d.collection === collectionId).map((d) => d.id),\n )\n const id = nextPageId(input.name, taken)\n const doc: CmsDocument = {\n collection: collectionId,\n id,\n values: { name: input.name },\n }\n setDocuments((prev) => [...prev, doc])\n persisterRef.current?.upsertDocument(doc)\n return { collection: collectionId, id }\n }, [])\n\n // EC-274 (re-scopes EC-217): a singleton is a UI lens, not a fixed id. Resolve\n // the collection's lone document and return its ref; if none exists yet, create\n // one with a NORMAL generated id (never the collection id — no code ever names a\n // literal doc id). Idempotent under React effects/StrictMode: the create guard\n // keys on \"any document in this collection\", so a re-invocation never adds a\n // second. On drift (>1 doc) the studio routes to the list, so this defensively\n // returns the first; the empty draft persists like any create.\n const ensureSingletonDocument = useCallback(\n (collectionId: string): DocumentRef => {\n const collection = registry.get(collectionId)\n const resolution = collection\n ? resolveSingletonDocument(collection, documentsRef.current)\n : ({ kind: 'empty' } as const)\n if (resolution.kind === 'ready') {\n return { collection: collectionId, id: resolution.doc.id }\n }\n if (resolution.kind === 'drift') {\n return { collection: collectionId, id: resolution.docs[0]!.id }\n }\n // Empty: create the lone document once. The ref guard (synchronous) plus the\n // updater's \"any doc in collection\" check make this idempotent under a\n // re-invoked effect or StrictMode's double mount — never a second draft.\n const existing = documentsRef.current.find((d) => d.collection === collectionId)\n if (existing) return { collection: collectionId, id: existing.id }\n if (ensuredSingletons.current.has(collectionId)) {\n return { collection: collectionId, id: `new-${collectionId}-pending` }\n }\n ensuredSingletons.current.add(collectionId)\n seq.current += 1\n const id = `new-${collectionId}-${seq.current}`\n const doc: CmsDocument = { collection: collectionId, id, values: {} }\n setDocuments((prev) =>\n prev.some((d) => d.collection === collectionId) ? prev : [...prev, doc],\n )\n persisterRef.current?.upsertDocument(doc)\n return { collection: collectionId, id }\n },\n [registry],\n )\n\n const deleteDocument = useCallback((ref: DocumentRef) => {\n setDocuments((prev) =>\n prev.filter((d) => !(d.collection === ref.collection && d.id === ref.id)),\n )\n persisterRef.current?.deleteDocument(ref)\n }, [])\n\n // EC-224: published-ness IS the version pointer (`publishedKeys`) — the SOLE\n // studio source of truth, read via `isPublished`. The live row stays a\n // continuous draft (Sanity model); no flat `state` mirror is maintained. Every\n // reader now consults the pointer (the table badge/$state via `isPublished`,\n // the preview engine via the pin), so the flat field is read by nothing here.\n const setPublished = useCallback((ref: DocumentRef, published: boolean) => {\n const key = documentKey(ref)\n setPublishedKeys((prev) => {\n if (prev.has(key) === published) return prev\n const next = new Set(prev)\n if (published) next.add(key)\n else next.delete(key)\n return next\n })\n }, [])\n\n const isPublished = useCallback(\n (ref: DocumentRef) => publishedKeys.has(documentKey(ref)),\n [publishedKeys],\n )\n\n // Reconcile published-ness for a ref against the AUTHORITATIVE backend record\n // (EC-225): the optimistic flip is a guess; once the queued op settles we read\n // the actual pin so the badge can never claim a state the backend refused\n // (a publish blocked by field rules, an unpublish blocked by a strict ref).\n const reconcilePublished = useCallback(\n async (ref: DocumentRef) => {\n if (projectId === undefined) return\n const { operations } = await getStudioOperations()\n const record = await operations.documents.get({ projectId, ref })\n if (record.ok) setPublished(ref, record.value.publishedVersion !== undefined)\n },\n [projectId, setPublished],\n )\n\n const publishDocument = useCallback(\n async (ref: DocumentRef) => {\n setPublished(ref, true) // optimistic\n persisterRef.current?.publishDocument(ref)\n await persisterRef.current?.flush()\n await reconcilePublished(ref)\n },\n [setPublished, reconcilePublished],\n )\n\n const unpublishDocument = useCallback(\n async (ref: DocumentRef) => {\n setPublished(ref, false) // optimistic\n persisterRef.current?.unpublishDocument(ref)\n await persisterRef.current?.flush()\n await reconcilePublished(ref)\n },\n [setPublished, reconcilePublished],\n )\n\n const loadDocumentVersions = useCallback(\n async (ref: DocumentRef): Promise<DocumentVersionsView> => {\n // No persisted backend (fixture/playground): no recorded history.\n if (projectId === undefined) return { versions: [] }\n const { operations } = await getStudioOperations()\n const [versionsRes, recordRes] = await Promise.all([\n operations.documents.listVersions({ projectId, ref }),\n operations.documents.get({ projectId, ref }),\n ])\n if (!versionsRes.ok) {\n setPersistError(versionsRes.error)\n return { versions: [] }\n }\n // The pinned (live) version comes off the document record; a never-saved\n // doc simply has no record (and no versions) — not an error to surface.\n const publishedVersion = recordRes.ok ? recordRes.value.publishedVersion : undefined\n return {\n versions: versionsRes.value,\n ...(publishedVersion !== undefined ? { publishedVersion } : {}),\n }\n },\n [projectId],\n )\n\n const restoreDocumentVersion = useCallback(\n async (ref: DocumentRef, version: number): Promise<CmsDocument | null> => {\n if (projectId === undefined) return null\n // Land any queued edits before the restore reads the current draft to\n // snapshot it (same ordering contract as commitFieldEdit/runBulk).\n await persisterRef.current?.ensureBaseline()\n const { operations } = await getStudioOperations()\n const result = await operations.documents.restore({ projectId, ref, version })\n if (!result.ok) {\n setPersistError(result.error)\n return null\n }\n const restored = result.value.document\n setDocuments((prev) =>\n prev.map((d) =>\n d.collection === restored.collection && d.id === restored.id ? restored : d,\n ),\n )\n return restored\n },\n [projectId],\n )\n\n const validate = useCallback(\n (doc: CmsDocument) =>\n validateDocument(registry, doc, {\n store,\n localeConfig,\n validateComposition,\n validateRichTextEmbeds,\n // EC-224: the EC-173 weak-reference warning sources published-ness from\n // the version pointer, so editing a published doc that references an\n // unpublished target surfaces the fallback warning again (it had gone\n // inert once the flat `state` mirror was dropped in B-3b).\n isPublished,\n assetExists,\n }),\n [registry, store, localeConfig, isPublished, assetExists],\n )\n\n const importDocuments = useCallback(\n (collectionId: string, raw: unknown[]): ImportReport => {\n const report: ImportReport = { added: 0, rejected: [] }\n // Pre-parse so intra-batch relation/asset targets resolve during validation.\n const parsedBatch: CmsDocument[] = []\n const schemaFails: { item: unknown; error: ReturnType<typeof documentSchema.safeParse> }[] =\n []\n for (const item of raw) {\n const parsed = documentSchema.safeParse({ ...(item as object), collection: collectionId })\n if (parsed.success) parsedBatch.push(parsed.data)\n else schemaFails.push({ item, error: parsed })\n }\n for (const { item, error } of schemaFails) {\n report.rejected.push({\n id: (item as { id?: string })?.id ?? '(no id)',\n issues: (error.success ? [] : error.error.issues).map((e) => ({\n code: 'invalid-field-value' as const,\n severity: 'error' as const,\n message: e.message,\n path: e.path.map((p) => (typeof p === 'symbol' ? String(p) : p)),\n })),\n })\n }\n // Validate each against existing docs PLUS the rest of the batch.\n const batchStore = createDocumentStore([...documents, ...parsedBatch])\n const accepted: CmsDocument[] = []\n for (const doc of parsedBatch) {\n const issues = validateDocument(registry, doc, { store: batchStore, localeConfig, assetExists })\n const errors = issues.filter((iss) => iss.severity === 'error')\n if (errors.length > 0) report.rejected.push({ id: doc.id, issues: errors })\n else accepted.push(doc)\n }\n if (accepted.length > 0) {\n setDocuments((prev) => {\n const next = [...prev]\n for (const doc of accepted) {\n const i = next.findIndex((d) => d.collection === doc.collection && d.id === doc.id)\n if (i < 0) next.push(doc)\n else next[i] = doc\n }\n return next\n })\n for (const doc of accepted) persisterRef.current?.upsertDocument(doc)\n // EC-224: imports land as the working DRAFT. Publish-ness is the version\n // pointer (`publishedKeys`), set by publishing — never carried in the\n // imported row — so an import never auto-publishes; the editor publishes\n // explicitly afterward.\n report.added = accepted.length\n }\n return report\n },\n [registry, documents, localeConfig, assetExists],\n )\n\n const isFieldReadOnly = useCallback((collectionId: string, field: FieldDef) => {\n return (\n field.form?.readOnly === true ||\n (READ_ONLY_FIELDS[collectionId]?.includes(field.name) ?? false)\n )\n }, [])\n\n // --- Saved views (EC-169) -------------------------------------------------\n\n // Load the project's persisted views once (operations query). Views saved by\n // other editors/sessions on the same project show up here.\n useEffect(() => {\n if (projectId === undefined) return\n let cancelled = false\n void getStudioOperations()\n .then(({ operations }) => loadSavedViews(operations, projectId))\n .then((result) => {\n if (cancelled) return\n if (!result.ok) {\n setPersistError(result.error)\n return\n }\n const grouped: Record<string, SavedView[]> = {}\n for (const record of result.value) {\n ;(grouped[record.collection] ??= []).push({\n id: record.id,\n name: record.name,\n state: record.state,\n })\n }\n setSavedViews(grouped)\n })\n return () => {\n cancelled = true\n }\n }, [projectId])\n\n const viewsOf = useCallback(\n (collectionId: string): SavedView[] => [\n defaultView(registry.get(collectionId)),\n ...(savedViews[collectionId] ?? []),\n ],\n [registry, savedViews],\n )\n\n const activeViewOf = useCallback(\n (collectionId: string): SavedView => {\n const id = activeViews[collectionId] ?? ALL_VIEW_ID\n return (\n viewsOf(collectionId).find((view) => view.id === id) ??\n defaultView(registry.get(collectionId))\n )\n },\n [activeViews, viewsOf, registry],\n )\n\n const tableStateOf = useCallback(\n (collectionId: string): TableViewState =>\n tableStates[collectionId] ?? activeViewOf(collectionId).state,\n [tableStates, activeViewOf],\n )\n\n const dropTableState = useCallback((collectionId: string) => {\n setTableStates((prev) => {\n if (!(collectionId in prev)) return prev\n const next = { ...prev }\n delete next[collectionId]\n return next\n })\n }, [])\n\n const setActiveView = useCallback(\n (collectionId: string, viewId: string) => {\n setActiveViews((prev) => ({ ...prev, [collectionId]: viewId }))\n dropTableState(collectionId)\n },\n [dropTableState],\n )\n\n /**\n * Run one persisted view mutation: pending content mutations + the persisted\n * baseline land first (so the system collection never pre-empts the content\n * schema), then exactly one operations command. Failures surface as\n * `persistError` and report `false` — the session is only updated on success.\n */\n const dispatchViewMutation = useCallback(\n async (\n run: (operations: OperationsClient, projectId: string) => Promise<OperationResult<unknown>>,\n ): Promise<boolean> => {\n if (projectId === undefined) return true // fixture-only session: views stay session-local\n await persisterRef.current?.ensureBaseline()\n const { operations } = await getStudioOperations()\n const result = await run(operations, projectId)\n if (!result.ok) {\n setPersistError(result.error)\n return false\n }\n return true\n },\n [projectId],\n )\n\n const saveViewAs = useCallback(\n async (collectionId: string, name: string): Promise<boolean> => {\n const trimmed = name.trim()\n if (trimmed === '') return false\n const id = newViewId()\n const state = normalizeViewState(tableStateOf(collectionId))\n const ok = await dispatchViewMutation((operations, pid) =>\n saveSavedView(operations, pid, { id, name: trimmed, collection: collectionId, state }),\n )\n if (!ok) return false\n setSavedViews((prev) => ({\n ...prev,\n [collectionId]: [...(prev[collectionId] ?? []), { id, name: trimmed, state }],\n }))\n setActiveViews((prev) => ({ ...prev, [collectionId]: id }))\n dropTableState(collectionId)\n return true\n },\n [dispatchViewMutation, tableStateOf, dropTableState],\n )\n\n const saveActiveView = useCallback(\n async (collectionId: string): Promise<boolean> => {\n const activeId = activeViews[collectionId] ?? ALL_VIEW_ID\n if (activeId === ALL_VIEW_ID) return false // the default view is not persistable\n const current = (savedViews[collectionId] ?? []).find((view) => view.id === activeId)\n if (!current) return false\n const state = normalizeViewState(tableStateOf(collectionId))\n const ok = await dispatchViewMutation((operations, pid) =>\n saveSavedView(operations, pid, {\n id: activeId,\n name: current.name,\n collection: collectionId,\n state,\n }),\n )\n if (!ok) return false\n setSavedViews((prev) => ({\n ...prev,\n [collectionId]: (prev[collectionId] ?? []).map((view) =>\n view.id === activeId ? { ...view, state } : view,\n ),\n }))\n dropTableState(collectionId)\n return true\n },\n [activeViews, savedViews, dispatchViewMutation, tableStateOf, dropTableState],\n )\n\n const deleteView = useCallback(\n async (collectionId: string, viewId: string): Promise<boolean> => {\n if (viewId === ALL_VIEW_ID) return false\n // One documents.delete against the views system collection — content\n // documents are untouched by construction.\n const ok = await dispatchViewMutation((operations, pid) =>\n deleteSavedView(operations, pid, viewId),\n )\n if (!ok) return false\n setSavedViews((prev) => ({\n ...prev,\n [collectionId]: (prev[collectionId] ?? []).filter((view) => view.id !== viewId),\n }))\n if ((activeViews[collectionId] ?? ALL_VIEW_ID) === viewId) {\n setActiveViews((prev) => ({ ...prev, [collectionId]: ALL_VIEW_ID }))\n dropTableState(collectionId)\n }\n return true\n },\n [dispatchViewMutation, activeViews, dropTableState],\n )\n\n // --- Bulk actions (EC-169) ------------------------------------------------\n\n const runBulk = useCallback(\n async (\n collectionId: string,\n ids: readonly string[],\n action: BulkAction,\n ): Promise<BulkReport> => {\n let dispatch:\n | ((action: BulkAction, ref: DocumentRef) => Promise<OperationResult<unknown>>)\n | undefined\n const persister = persisterRef.current\n if (persister && projectId !== undefined) {\n // Pending queued mutations + baseline land first, then one awaited\n // command per item (same ordering contract as commitFieldEdit).\n await persister.ensureBaseline()\n const { operations } = await getStudioOperations()\n dispatch = (bulkAction, ref) =>\n bulkAction === 'delete'\n ? operations.documents.delete({ projectId, ref })\n : bulkAction === 'publish'\n ? operations.documents.publish({ projectId, ref })\n : operations.documents.unpublish({ projectId, ref })\n }\n return runBulkAction(\n {\n documents: documentsRef.current,\n titleOf,\n validate: (doc) =>\n validateDocument(registry, doc, {\n store: createDocumentStore(documentsRef.current),\n localeConfig,\n // EC-225: include the composition validators so a bulk PUBLISH\n // gates blocks/richText validity the same way the detail editor\n // does — the operations-layer publish gate has no component\n // registry, so composition validity is a studio-validation invariant.\n validateComposition,\n validateRichTextEmbeds,\n assetExists,\n }),\n // EC-224: a succeeded publish/unpublish moves the version pointer\n // (`publishedKeys`); the flat `state` mirror is updated in lockstep.\n applyState: (ref, state) => setPublished(ref, state === 'published'),\n applyDelete: (ref) =>\n setDocuments((prev) =>\n prev.filter((d) => !(d.collection === ref.collection && d.id === ref.id)),\n ),\n ...(dispatch ? { dispatch } : {}),\n },\n collectionId,\n ids,\n action,\n )\n },\n [projectId, titleOf, registry, localeConfig, setPublished, assetExists],\n )\n\n const store$ = useMemo<CmsStore>(\n () => ({\n ...(projectId !== undefined ? { projectId } : {}),\n collections,\n localeConfig,\n activeLocale,\n getCollection,\n documentsOf: (collectionId) => documents.filter((d) => d.collection === collectionId),\n getDocument,\n titleOf,\n saveDocument,\n commitFieldEdit,\n createDocument,\n createPage,\n ensureSingletonDocument,\n deleteDocument,\n isPublished,\n publishDocument,\n unpublishDocument,\n loadDocumentVersions,\n restoreDocumentVersion,\n importDocuments,\n validate,\n isFieldReadOnly,\n viewsOf,\n activeViewId: (collectionId) => activeViews[collectionId] ?? ALL_VIEW_ID,\n setActiveView,\n tableStateOf,\n setTableState: (collectionId, update) =>\n setTableStates((prev) => {\n const current = prev[collectionId] ?? activeViewOf(collectionId).state\n const next = typeof update === 'function' ? update(current) : update\n return { ...prev, [collectionId]: next }\n }),\n isViewDirty: (collectionId) => {\n const working = tableStates[collectionId]\n if (working === undefined) return false\n const active = activeViewOf(collectionId).state\n const collection = registry.get(collectionId)\n if (collection === undefined) return !viewStatesEqual(working, active)\n // Compare schema-resolved forms (EC-213): a column-order reconciliation\n // or a stale `hidden` entry must not read as an unsaved edit.\n return !viewStatesEqual(\n canonicalViewState(collection, working),\n canonicalViewState(collection, active),\n )\n },\n resetTableState: dropTableState,\n saveActiveView,\n saveViewAs,\n deleteView,\n runBulk,\n addCollection: (def) =>\n setCollections((prev) => [...prev.filter((c) => c.id !== def.id), def]),\n persistError,\n clearPersistError: () => setPersistError(null),\n ensurePersistedBaseline: () => persisterRef.current?.ensureBaseline() ?? Promise.resolve(),\n flushPersistence: () => persisterRef.current?.flush() ?? Promise.resolve(),\n }),\n [\n projectId,\n collections,\n documents,\n localeConfig,\n activeLocale,\n getCollection,\n getDocument,\n titleOf,\n saveDocument,\n commitFieldEdit,\n createDocument,\n createPage,\n ensureSingletonDocument,\n deleteDocument,\n isPublished,\n publishDocument,\n unpublishDocument,\n loadDocumentVersions,\n restoreDocumentVersion,\n importDocuments,\n validate,\n isFieldReadOnly,\n viewsOf,\n activeViews,\n activeViewOf,\n tableStates,\n tableStateOf,\n setActiveView,\n dropTableState,\n saveActiveView,\n saveViewAs,\n deleteView,\n runBulk,\n registry,\n persistError,\n ],\n )\n\n return <CmsContext.Provider value={store$}>{children}</CmsContext.Provider>\n}\n\nexport function useCms(): CmsStore {\n const store = useContext(CmsContext)\n if (!store) throw new Error('useCms must be used within a <CmsProvider>.')\n return store\n}\n\n/** Export a locale-aware label for a field (form label or name). */\nexport function fieldLabel(field: FieldDef): string {\n return field.form?.label ?? field.name\n}\n\nexport { primaryField }\nexport type { Locale }\n"]}
1
+ {"version":3,"file":"cms-store.js","sourceRoot":"","sources":["../../../src/components/cms/cms-store.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAEpG,OAAO,EACL,wBAAwB,EACxB,qBAAqB,EACrB,mBAAmB,EACnB,WAAW,EACX,cAAc,EACd,YAAY,EACZ,eAAe,EACf,2BAA2B,EAC3B,kBAAkB,EAClB,mBAAmB,EACnB,wBAAwB,EACxB,YAAY,EACZ,gBAAgB,GACjB,MAAM,0BAA0B,CAAA;AAajC,OAAO,EAAE,wBAA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BAAiB;QACjB,oBAAoB;QACpB,sBAAsB;QACtB,eAAe;QACf,QAAQ;QACR,eAAe;QACf,OAAO;QACP,WAAW;QACX,YAAY;QACZ,WAAW;QACX,YAAY;QACZ,aAAa;QACb,cAAc;QACd,cAAc;QACd,UAAU;QACV,UAAU;QACV,OAAO;QACP,QAAQ;QACR,YAAY;KACb,CACF,CAAA;IAED,OAAO,KAAC,UAAU,CAAC,QAAQ,IAAC,KAAK,EAAE,MAAM,YAAG,QAAQ,GAAuB,CAAA;AAC7E,CAAC;AAED,MAAM,UAAU,MAAM;IACpB,MAAM,KAAK,GAAG,UAAU,CAAC,UAAU,CAAC,CAAA;IACpC,IAAI,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAA;IAC1E,OAAO,KAAK,CAAA;AACd,CAAC;AAED,oEAAoE;AACpE,MAAM,UAAU,UAAU,CAAC,KAAe;IACxC,OAAO,KAAK,CAAC,IAAI,EAAE,KAAK,IAAI,KAAK,CAAC,IAAI,CAAA;AACxC,CAAC;AAED,OAAO,EAAE,YAAY,EAAE,CAAA","sourcesContent":["import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport {\n createCollectionRegistry,\n clearHiddenForPublish,\n createDocumentStore,\n documentKey,\n documentSchema,\n resolveField,\n sampleDocuments,\n sampleFilterableCollections,\n sampleLocaleConfig,\n samplePublishedKeys,\n resolveSingletonDocument,\n titleFieldOf,\n validateDocument,\n} from '@elytracms/core/cms-core'\nimport type {\n BlocksFieldDef,\n CmsDocument,\n CmsValidationIssue,\n CollectionDef,\n CompositionIssue,\n DocumentRef,\n FieldDef,\n Locale,\n LocaleConfig,\n RichTextFieldDef,\n} from '@elytracms/core/cms-core'\nimport { validateCompositionValue } from '@elytracms/core/project-graph'\nimport type { ComponentNode } from '@elytracms/core/project-graph'\nimport { collectComponentEmbeds, parseRichTextValue } from '@elytracms/core/rich-text'\nimport type { DocumentVersionRecord } from '@elytracms/core/persistence'\nimport { configureStudioLocales, useStudioLocale } from '@elytracms/studio/lib/locale'\nimport { getStudioRegistry, studioManifestLookup } from '@elytracms/studio/lib/registry'\nimport { slugify } from '@elytracms/studio/lib/utils'\nimport { createCmsPersister, getStudioOperations } from '@elytracms/studio/lib/operations'\nimport type {\n CmsPersister,\n OperationError,\n OperationResult,\n OperationsClient,\n} from '@elytracms/studio/lib/operations'\nimport {\n ALL_VIEW_ID,\n canonicalViewState,\n defaultViewState,\n deleteSavedView,\n loadSavedViews,\n newViewId,\n normalizeViewState,\n saveSavedView,\n viewStatesEqual,\n} from '@elytracms/studio/lib/cms-views'\nimport type { TableViewState } from '@elytracms/studio/lib/cms-views'\nimport { useOptionalAssets } from '../assets/assets-store'\nimport { commitCellEdit } from './cell-edit'\nimport type { CellCommitInput, CellCommitOutcome } from './cell-edit'\nimport { runBulkAction } from './bulk-actions'\nimport type { BulkAction, BulkReport } from './bulk-actions'\n\n/**\n * A saved table view (EC-169, supersedes the EC-071 column presets): a named\n * bundle of filters (closed AD-3 vocabulary), sort, and visible/ordered\n * columns. Named views persist project-scoped through operations (see\n * `lib/cms-views/views-store`); the unnamed \"All documents\" default is derived\n * per collection and never persisted.\n */\nexport interface SavedView {\n id: string\n name: string\n state: TableViewState\n}\n\n/** Demo per-field access (brief §8.4, EC-078). Read-only fields render disabled. */\nconst READ_ONLY_FIELDS: Record<string, string[]> = {\n asset: ['url'],\n}\n\n/**\n * Mint a collision-safe, slug-derived page id (EC-192): the slug of the page name,\n * suffixed `-2`/`-3`/… until it is free among the ids already taken. Empty or\n * symbol-only names fall back to `page`. Pure so the id rule is testable without\n * the store; `createPage` applies it against the live page documents.\n */\nexport function nextPageId(name: string, taken: ReadonlySet<string>): string {\n const base = slugify(name) || 'page'\n let id = base\n for (let n = 2; taken.has(id); n += 1) id = `${base}-${n}`\n return id\n}\n\n/**\n * EC-188: validate a `blocks` composition field value against the field's `allow`\n * vocabulary + the code-owned component registry (the leash), mapping graph\n * issues into plain CMS findings. Injected into `validateDocument` so cms-core\n * stays free of `@elytracms/core/project-graph`. Never throws — a malformed (non-node)\n * value degrades to a single finding, matching the \"validation is first-class,\n * never a crash\" rule.\n */\nfunction validateComposition(value: unknown, field: BlocksFieldDef): CompositionIssue[] {\n if (value == null) return []\n const roots = Array.isArray(value) ? value : [value]\n if (!roots.every((r) => r != null && typeof r === 'object' && 'componentId' in r)) {\n return [{ message: 'is not a valid composition (expected component nodes)', severity: 'error' }]\n }\n const components = getStudioRegistry().registry.lookup\n return validateCompositionValue(value as ComponentNode | ComponentNode[], {\n allow: field.allow,\n components,\n }).map((issue) => ({\n message: issue.message,\n severity: issue.severity,\n nodePath: issue.path.join('/'),\n }))\n}\n\n/**\n * EC-189: validate the composition embeds inside a `richText` field value. Each\n * `componentEmbed` holds a single `ComponentNode` constrained by the field's\n * `allow` vocabulary (the SAME leash a `blocks` field uses). Parse the value, walk\n * its embeds at any depth, and validate each embedded node via\n * `validateCompositionValue`; findings carry the rich-text node path joined with\n * the in-embed graph path. Injected into `validateDocument` so cms-core depends on\n * neither `@elytracms/core/project-graph` nor `@elytracms/core/rich-text`. Never throws — a\n * malformed embed degrades to a single finding.\n */\nfunction validateRichTextEmbeds(value: unknown, field: RichTextFieldDef): CompositionIssue[] {\n if (value == null) return []\n const parsed = parseRichTextValue(value)\n // A plain-string / schema-invalid rich-text value carries no embeds to check\n // here (scalar type validation owns reporting a malformed value).\n if (!parsed.ok) return []\n const components = getStudioRegistry().registry.lookup\n const out: CompositionIssue[] = []\n for (const occurrence of collectComponentEmbeds(parsed.value.doc)) {\n if (!occurrence.embedded) {\n out.push({\n message: `embed at ${occurrence.nodePath} is missing a valid embedded component`,\n severity: 'error',\n nodePath: occurrence.nodePath,\n })\n continue\n }\n for (const issue of validateCompositionValue(occurrence.embedded, {\n allow: field.allow,\n components,\n })) {\n out.push({\n message: issue.message,\n severity: issue.severity,\n nodePath: `${occurrence.nodePath}/attrs/node/${issue.path.join('/')}`,\n })\n }\n }\n return out\n}\n\nexport interface ImportReport {\n added: number\n rejected: { id: string; issues: CmsValidationIssue[] }[]\n}\n\n/**\n * A document's recorded version history plus its live pin (EC-224), as the\n * Versions inspector pane reads it. `versions` is newest-first; `publishedVersion`\n * is the recorded version currently pinned live, absent when unpublished.\n */\nexport interface DocumentVersionsView {\n versions: DocumentVersionRecord[]\n publishedVersion?: number\n}\n\nexport interface CmsStore {\n /** The project this CMS session edits (set when persistence is enabled); the asset picker scopes the real library by it (EC-152). */\n projectId?: string\n collections: readonly CollectionDef[]\n localeConfig: LocaleConfig\n /**\n * The studio's ambient active locale (EC-176): table cells, detail forms,\n * and inline edits all display and write THIS locale. Switched once via the\n * shared `LocaleSwitcher`, never per control.\n */\n activeLocale: Locale\n getCollection(id: string): CollectionDef | undefined\n documentsOf(collectionId: string): CmsDocument[]\n getDocument(ref: DocumentRef): CmsDocument | undefined\n /** Resolve a relation/asset target's display title. */\n titleOf(ref: DocumentRef): string\n saveDocument(doc: CmsDocument): void\n /**\n * Commit ONE field edit from the table (EC-168): optimistic session apply +\n * exactly one `documents.upsert` operations command, awaited. Validation\n * failures and operation rejections return a structured error (the caller\n * renders it on the cell) and leave the session rolled back.\n */\n commitFieldEdit(input: CellCommitInput): Promise<CellCommitOutcome>\n createDocument(collectionId: string): DocumentRef\n /** Create a named page (`page` collection) with a stable, slug-derived id. */\n createPage(input: { name: string }): DocumentRef\n /**\n * Ensure a singleton collection's lone document exists and return its ref\n * (EC-274). Resolves the existing single document, or creates one with a normal\n * generated id (never the collection id). Idempotent. The singleton route opens\n * through this so the one document always exists to edit.\n */\n ensureSingletonDocument(collectionId: string): DocumentRef\n deleteDocument(ref: DocumentRef): void\n /**\n * Is this document currently published? Sourced from the version POINTER\n * (EC-224), not the flat `state` enum — seeded from hydration and updated by\n * {@link publishDocument}/{@link unpublishDocument}.\n */\n isPublished(ref: DocumentRef): boolean\n /**\n * Publish: snapshot the draft as a new version and pin it live (EC-224).\n * Flips published-ness optimistically, then reconciles against the backend\n * record (EC-225) so the badge can never claim a publish the backend refused\n * (e.g. blocked by publish-time field validation).\n */\n publishDocument(ref: DocumentRef): Promise<void>\n /**\n * Unpublish: clear the live version pin (EC-224). Blocked at the operations\n * layer while strict relation fields published-reference it (EC-173); the\n * optimistic flip reconciles against the backend on rejection (EC-225).\n */\n unpublishDocument(ref: DocumentRef): Promise<void>\n /**\n * Load this document's recorded version history + live pin (EC-224) for the\n * Versions inspector pane. Fixture/playground sessions (no project) have no\n * persisted history → an empty view. Failures surface as {@link persistError}.\n */\n loadDocumentVersions(ref: DocumentRef): Promise<DocumentVersionsView>\n /**\n * Restore a recorded version as the new working draft (EC-224): the operation\n * snapshots the current draft first (so the rollback is itself undoable), then\n * loads the chosen snapshot. Returns the restored draft (or null on\n * failure/fixture session) so the open editor can adopt it.\n */\n restoreDocumentVersion(ref: DocumentRef, version: number): Promise<CmsDocument | null>\n importDocuments(collectionId: string, docs: unknown[]): ImportReport\n validate(doc: CmsDocument): CmsValidationIssue[]\n isFieldReadOnly(collectionId: string, field: FieldDef): boolean\n // Saved views (EC-169): named filter/sort/column bundles per collection,\n // persisted project-scoped through operations commands (lib/cms-views).\n viewsOf(collectionId: string): SavedView[]\n activeViewId(collectionId: string): string\n /** Switch views — resets the working table state to the view's state. */\n setActiveView(collectionId: string, viewId: string): void\n /** The live table state (the active view's state plus unsaved edits). */\n tableStateOf(collectionId: string): TableViewState\n /**\n * Update the working state. Always pass an updater when deriving from the\n * previous state — render-time snapshots go stale across rapid events.\n */\n setTableState(\n collectionId: string,\n update: TableViewState | ((prev: TableViewState) => TableViewState),\n ): void\n /** Does the working state diverge from the active view (\"unsaved changes\")? */\n isViewDirty(collectionId: string): boolean\n /** Discard working-state edits, back to the active view. */\n resetTableState(collectionId: string): void\n /** Persist the working state into the active named view. False on rejection. */\n saveActiveView(collectionId: string): Promise<boolean>\n /** Persist the working state as a new named view and activate it. */\n saveViewAs(collectionId: string, name: string): Promise<boolean>\n /** Delete a named view — a view-only operation; documents are never touched. */\n deleteView(collectionId: string, viewId: string): Promise<boolean>\n /**\n * Bulk publish/unpublish/delete (EC-169): one operations command PER item,\n * per-item outcomes in the report — partial failure is enumerated, never\n * silent. Only succeeded items mutate the session.\n */\n runBulk(collectionId: string, ids: readonly string[], action: BulkAction): Promise<BulkReport>\n /**\n * Mirror a collection into the session (e.g. an accepted AI-generated\n * schema, EC-097). Replaces by id. Session-only: persistence happens through\n * the accept flow's changeset (`schema.upsertCollection`), not here.\n */\n addCollection(def: CollectionDef): void\n /**\n * Most recent failed/denied persisted mutation (structured, from the\n * operation result). Rendered by the CMS surface — never a silent failure.\n */\n persistError: OperationError | null\n clearPersistError(): void\n /** Seed the persisted baseline now (e.g. before applying an AI changeset). */\n ensurePersistedBaseline(): Promise<void>\n /** Await all queued persisted mutations (tests, publish flows). */\n flushPersistence(): Promise<void>\n}\n\nconst CmsContext = createContext<CmsStore | null>(null)\n\nfunction primaryField(collection: CollectionDef): string {\n return titleFieldOf(collection)?.name ?? collection.fields[0]?.name ?? 'id'\n}\n\n/** The unnamed built-in view: no filters, no sort, every field visible. */\nfunction defaultView(collection: CollectionDef | undefined): SavedView {\n return {\n id: ALL_VIEW_ID,\n name: 'All documents',\n state: collection\n ? defaultViewState(collection)\n : { filters: [], sort: null, columns: [], hidden: [] },\n }\n}\n\n/**\n * The CMS session store (EC-141): documents and collections are optimistic,\n * synchronous session state (live validation while typing); every mutation —\n * create/save/delete/state transitions — is mirrored onto the operations\n * layer (`documents.*` / `schema.*` commands) through {@link createCmsPersister}.\n * Failed/denied commands surface as {@link CmsStore.persistError}.\n */\nexport function CmsProvider({\n children,\n projectId,\n initialCollections,\n initialDocuments,\n initialPublishedKeys,\n initialLocaleConfig,\n}: {\n children: ReactNode\n /** Enables persistence through the shared operations client. */\n projectId?: string\n /** Seed collections (e.g. from an imported starter kit, EC-119); defaults to the samples. */\n initialCollections?: CollectionDef[]\n initialDocuments?: CmsDocument[]\n /**\n * Published document keys from hydration (EC-224): the version pointer\n * (`publishedVersion` set). Absent (kit / fixture sessions) → the sample\n * fixtures' published set (`samplePublishedKeys`).\n */\n initialPublishedKeys?: readonly string[]\n /** Locale config for the seeded content; defaults to the sample config. */\n initialLocaleConfig?: LocaleConfig\n}) {\n const [documents, setDocuments] = useState<CmsDocument[]>(() =>\n (initialDocuments ?? sampleDocuments).map((d) => structuredClone(d)),\n )\n // Published-ness as the version POINTER (EC-224), decoupled from the flat\n // `state` enum: seeded from hydration's pointer set, or — when none is supplied\n // — the canonical sample published set for the playground. A kit's imported\n // content (`initialDocuments` without a pointer set) starts unpublished\n // (drafts) until an editor publishes it. The flat `state` is never consulted.\n const [publishedKeys, setPublishedKeys] = useState<Set<string>>(() => {\n if (initialPublishedKeys) return new Set(initialPublishedKeys)\n return new Set(initialDocuments ? [] : samplePublishedKeys)\n })\n // Named saved views per collection (EC-169): loaded from the operations\n // layer (project-scoped, shared across editors) and mutated through it.\n const [savedViews, setSavedViews] = useState<Record<string, SavedView[]>>({})\n const [activeViews, setActiveViews] = useState<Record<string, string>>({})\n // The live table state per collection where it diverges from the active\n // view; absent key = exactly the active view's state (not dirty).\n const [tableStates, setTableStates] = useState<Record<string, TableViewState>>({})\n // Collections are stateful so AI-generated schemas (EC-097) can be accepted\n // into the session. The session schema IS the source the sort/filter\n // offering follows (EC-177 gap 3): hydrated sessions receive the persisted\n // schema via `initialCollections`; the fixture fallback is the canonical\n // cms-core sample schema WITH its declared `filterable` flags — no\n // session-side widenings, so the studio never offers a field the backend's\n // delivery engine would reject.\n const [collections, setCollections] = useState<CollectionDef[]>(() => [\n ...(initialCollections ?? sampleFilterableCollections),\n ])\n const [persistError, setPersistError] = useState<OperationError | null>(null)\n const seq = useRef(0)\n // EC-274: collection ids whose lone singleton document this session has already\n // created — a synchronous guard so a re-invoked effect (or StrictMode's double\n // mount) never materializes a second document under a freshly generated id.\n const ensuredSingletons = useRef<Set<string>>(new Set())\n\n // Latest session state for the persister's lazy baseline (no re-subscribing).\n const collectionsRef = useRef(collections)\n collectionsRef.current = collections\n const documentsRef = useRef(documents)\n documentsRef.current = documents\n\n const persisterRef = useRef<CmsPersister | null>(null)\n if (persisterRef.current === null && projectId !== undefined) {\n persisterRef.current = createCmsPersister({\n projectId,\n getOperations: async () => (await getStudioOperations()).operations,\n getCollections: () => collectionsRef.current,\n getDocuments: () => documentsRef.current,\n // EC-277: self-type composition static props on write (the manifest half of\n // the lens), so extraction stays schema-free. Document fields self-type via\n // the schema alone (above); the registry adds blocks/embed prop coverage.\n lookupManifest: studioManifestLookup(),\n onError: setPersistError,\n })\n }\n\n const registry = useMemo(() => createCollectionRegistry(collections), [collections])\n const store = useMemo(() => createDocumentStore(documents), [documents])\n const localeConfig = initialLocaleConfig ?? sampleLocaleConfig\n\n // Asset existence is validated against the REAL asset library (assets live in\n // their own repository, not as CMS documents). With the ambient AssetsProvider\n // present, the oracle is the set of uploaded asset ids — but only once loaded;\n // while it loads we are optimistic so a valid upload is never transiently\n // flagged \"unknown\". With no provider (tests/fixtures), the oracle is absent\n // and asset existence falls back to the document store.\n const assetStore = useOptionalAssets()\n const assetExists = useMemo<((id: string) => boolean) | undefined>(() => {\n if (!assetStore) return undefined\n if (assetStore.status !== 'ready') return () => true\n const ids = new Set(assetStore.assets.map((asset) => asset.id))\n return (id) => ids.has(id)\n }, [assetStore])\n\n // The ambient studio locale (EC-176): this session's locale config drives\n // the switcher options; every CMS surface follows the one active locale.\n const { locale: activeLocale } = useStudioLocale()\n useEffect(() => {\n configureStudioLocales(localeConfig)\n }, [localeConfig])\n\n const getCollection = useCallback((id: string) => registry.get(id), [registry])\n\n const getDocument = useCallback(\n (ref: DocumentRef) => documents.find((d) => d.collection === ref.collection && d.id === ref.id),\n [documents],\n )\n\n const titleOf = useCallback(\n (ref: DocumentRef) => {\n const doc = documents.find((d) => d.collection === ref.collection && d.id === ref.id)\n const collection = registry.get(ref.collection)\n if (!doc || !collection) return ref.id\n // Resolve through the locale layer in the ambient active locale (EC-176)\n // with EC-018 fallback, so localized titles follow the switcher.\n const { value } = resolveField(\n collection,\n doc,\n primaryField(collection),\n activeLocale,\n localeConfig,\n )\n return typeof value === 'string' && value ? value : ref.id\n },\n [documents, registry, localeConfig, activeLocale],\n )\n\n const saveDocument = useCallback((doc: CmsDocument) => {\n setDocuments((prev) => {\n const i = prev.findIndex((d) => d.collection === doc.collection && d.id === doc.id)\n if (i < 0) return [...prev, doc]\n const next = [...prev]\n next[i] = doc\n return next\n })\n persisterRef.current?.upsertDocument(doc)\n }, [])\n\n const commitFieldEdit = useCallback(\n (input: CellCommitInput): Promise<CellCommitOutcome> => {\n const replaceWith = (doc: CmsDocument) =>\n setDocuments((prev) =>\n prev.map((d) => (d.collection === doc.collection && d.id === doc.id ? doc : d)),\n )\n const persister = persisterRef.current\n return commitCellEdit(\n {\n registry,\n documents: documentsRef.current,\n localeConfig,\n applySession: replaceWith,\n rollbackSession: replaceWith,\n ...(persister && projectId !== undefined\n ? {\n dispatch: async (next: CmsDocument) => {\n // Make sure the persisted baseline + every queued mutation\n // landed first, then issue the commit's single command.\n await persister.ensureBaseline()\n const { operations } = await getStudioOperations()\n return operations.documents.upsert({ projectId, document: next })\n },\n }\n : {}),\n },\n input,\n )\n },\n [registry, localeConfig, projectId],\n )\n\n const createDocument = useCallback((collectionId: string): DocumentRef => {\n seq.current += 1\n const id = `new-${collectionId}-${seq.current}`\n const doc: CmsDocument = { collection: collectionId, id, values: {} }\n setDocuments((prev) => [...prev, doc])\n persisterRef.current?.upsertDocument(doc)\n return { collection: collectionId, id }\n }, [])\n\n // EC-192: create a named page document with a stable, slug-derived id (not an\n // opaque `new-page-N`), so the route bound to it reads as a real address and\n // the id survives as the canonical key. Collision-safe against existing page\n // ids. The route itself is written by the caller (NewPageDialog) through the\n // operations layer, so the two writes stay in their own concerns.\n const createPage = useCallback((input: { name: string }): DocumentRef => {\n const collectionId = 'page'\n const taken = new Set(\n documentsRef.current.filter((d) => d.collection === collectionId).map((d) => d.id),\n )\n const id = nextPageId(input.name, taken)\n const doc: CmsDocument = {\n collection: collectionId,\n id,\n values: { name: input.name },\n }\n setDocuments((prev) => [...prev, doc])\n persisterRef.current?.upsertDocument(doc)\n return { collection: collectionId, id }\n }, [])\n\n // EC-274 (re-scopes EC-217): a singleton is a UI lens, not a fixed id. Resolve\n // the collection's lone document and return its ref; if none exists yet, create\n // one with a NORMAL generated id (never the collection id — no code ever names a\n // literal doc id). Idempotent under React effects/StrictMode: the create guard\n // keys on \"any document in this collection\", so a re-invocation never adds a\n // second. On drift (>1 doc) the studio routes to the list, so this defensively\n // returns the first; the empty draft persists like any create.\n const ensureSingletonDocument = useCallback(\n (collectionId: string): DocumentRef => {\n const collection = registry.get(collectionId)\n const resolution = collection\n ? resolveSingletonDocument(collection, documentsRef.current)\n : ({ kind: 'empty' } as const)\n if (resolution.kind === 'ready') {\n return { collection: collectionId, id: resolution.doc.id }\n }\n if (resolution.kind === 'drift') {\n return { collection: collectionId, id: resolution.docs[0]!.id }\n }\n // Empty: create the lone document once. The ref guard (synchronous) plus the\n // updater's \"any doc in collection\" check make this idempotent under a\n // re-invoked effect or StrictMode's double mount — never a second draft.\n const existing = documentsRef.current.find((d) => d.collection === collectionId)\n if (existing) return { collection: collectionId, id: existing.id }\n if (ensuredSingletons.current.has(collectionId)) {\n return { collection: collectionId, id: `new-${collectionId}-pending` }\n }\n ensuredSingletons.current.add(collectionId)\n seq.current += 1\n const id = `new-${collectionId}-${seq.current}`\n const doc: CmsDocument = { collection: collectionId, id, values: {} }\n setDocuments((prev) =>\n prev.some((d) => d.collection === collectionId) ? prev : [...prev, doc],\n )\n persisterRef.current?.upsertDocument(doc)\n return { collection: collectionId, id }\n },\n [registry],\n )\n\n const deleteDocument = useCallback((ref: DocumentRef) => {\n setDocuments((prev) =>\n prev.filter((d) => !(d.collection === ref.collection && d.id === ref.id)),\n )\n persisterRef.current?.deleteDocument(ref)\n }, [])\n\n // EC-224: published-ness IS the version pointer (`publishedKeys`) — the SOLE\n // studio source of truth, read via `isPublished`. The live row stays a\n // continuous draft (Sanity model); no flat `state` mirror is maintained. Every\n // reader now consults the pointer (the table badge/$state via `isPublished`,\n // the preview engine via the pin), so the flat field is read by nothing here.\n const setPublished = useCallback((ref: DocumentRef, published: boolean) => {\n const key = documentKey(ref)\n setPublishedKeys((prev) => {\n if (prev.has(key) === published) return prev\n const next = new Set(prev)\n if (published) next.add(key)\n else next.delete(key)\n return next\n })\n }, [])\n\n const isPublished = useCallback(\n (ref: DocumentRef) => publishedKeys.has(documentKey(ref)),\n [publishedKeys],\n )\n\n // Reconcile published-ness for a ref against the AUTHORITATIVE backend record\n // (EC-225): the optimistic flip is a guess; once the queued op settles we read\n // the actual pin so the badge can never claim a state the backend refused\n // (a publish blocked by field rules, an unpublish blocked by a strict ref).\n const reconcilePublished = useCallback(\n async (ref: DocumentRef) => {\n if (projectId === undefined) return\n const { operations } = await getStudioOperations()\n const record = await operations.documents.get({ projectId, ref })\n if (record.ok) setPublished(ref, record.value.publishedVersion !== undefined)\n },\n [projectId, setPublished],\n )\n\n const publishDocument = useCallback(\n async (ref: DocumentRef) => {\n setPublished(ref, true) // optimistic\n // EC-273: clear conditionally-hidden, non-opt-out field values from the\n // PUBLISHED snapshot so delivery never carries stale hidden data — the live\n // draft row is untouched. `clearHiddenForPublish` returns the same document\n // when nothing is cleared, so a collection without conditional fields takes\n // the default verbatim-pin path (snapshot omitted).\n const doc = documentsRef.current.find(\n (d) => d.collection === ref.collection && d.id === ref.id,\n )\n const collection = collectionsRef.current.find((c) => c.id === ref.collection)\n const cleared = doc && collection ? clearHiddenForPublish(collection, doc) : undefined\n persisterRef.current?.publishDocument(ref, cleared && cleared !== doc ? cleared : undefined)\n await persisterRef.current?.flush()\n await reconcilePublished(ref)\n },\n [setPublished, reconcilePublished],\n )\n\n const unpublishDocument = useCallback(\n async (ref: DocumentRef) => {\n setPublished(ref, false) // optimistic\n persisterRef.current?.unpublishDocument(ref)\n await persisterRef.current?.flush()\n await reconcilePublished(ref)\n },\n [setPublished, reconcilePublished],\n )\n\n const loadDocumentVersions = useCallback(\n async (ref: DocumentRef): Promise<DocumentVersionsView> => {\n // No persisted backend (fixture/playground): no recorded history.\n if (projectId === undefined) return { versions: [] }\n const { operations } = await getStudioOperations()\n const [versionsRes, recordRes] = await Promise.all([\n operations.documents.listVersions({ projectId, ref }),\n operations.documents.get({ projectId, ref }),\n ])\n if (!versionsRes.ok) {\n setPersistError(versionsRes.error)\n return { versions: [] }\n }\n // The pinned (live) version comes off the document record; a never-saved\n // doc simply has no record (and no versions) — not an error to surface.\n const publishedVersion = recordRes.ok ? recordRes.value.publishedVersion : undefined\n return {\n versions: versionsRes.value,\n ...(publishedVersion !== undefined ? { publishedVersion } : {}),\n }\n },\n [projectId],\n )\n\n const restoreDocumentVersion = useCallback(\n async (ref: DocumentRef, version: number): Promise<CmsDocument | null> => {\n if (projectId === undefined) return null\n // Land any queued edits before the restore reads the current draft to\n // snapshot it (same ordering contract as commitFieldEdit/runBulk).\n await persisterRef.current?.ensureBaseline()\n const { operations } = await getStudioOperations()\n const result = await operations.documents.restore({ projectId, ref, version })\n if (!result.ok) {\n setPersistError(result.error)\n return null\n }\n const restored = result.value.document\n setDocuments((prev) =>\n prev.map((d) =>\n d.collection === restored.collection && d.id === restored.id ? restored : d,\n ),\n )\n return restored\n },\n [projectId],\n )\n\n const validate = useCallback(\n (doc: CmsDocument) =>\n validateDocument(registry, doc, {\n store,\n localeConfig,\n validateComposition,\n validateRichTextEmbeds,\n // EC-224: the EC-173 weak-reference warning sources published-ness from\n // the version pointer, so editing a published doc that references an\n // unpublished target surfaces the fallback warning again (it had gone\n // inert once the flat `state` mirror was dropped in B-3b).\n isPublished,\n assetExists,\n }),\n [registry, store, localeConfig, isPublished, assetExists],\n )\n\n const importDocuments = useCallback(\n (collectionId: string, raw: unknown[]): ImportReport => {\n const report: ImportReport = { added: 0, rejected: [] }\n // Pre-parse so intra-batch relation/asset targets resolve during validation.\n const parsedBatch: CmsDocument[] = []\n const schemaFails: { item: unknown; error: ReturnType<typeof documentSchema.safeParse> }[] =\n []\n for (const item of raw) {\n const parsed = documentSchema.safeParse({ ...(item as object), collection: collectionId })\n if (parsed.success) parsedBatch.push(parsed.data)\n else schemaFails.push({ item, error: parsed })\n }\n for (const { item, error } of schemaFails) {\n report.rejected.push({\n id: (item as { id?: string })?.id ?? '(no id)',\n issues: (error.success ? [] : error.error.issues).map((e) => ({\n code: 'invalid-field-value' as const,\n severity: 'error' as const,\n message: e.message,\n path: e.path.map((p) => (typeof p === 'symbol' ? String(p) : p)),\n })),\n })\n }\n // Validate each against existing docs PLUS the rest of the batch.\n const batchStore = createDocumentStore([...documents, ...parsedBatch])\n const accepted: CmsDocument[] = []\n for (const doc of parsedBatch) {\n const issues = validateDocument(registry, doc, { store: batchStore, localeConfig, assetExists })\n const errors = issues.filter((iss) => iss.severity === 'error')\n if (errors.length > 0) report.rejected.push({ id: doc.id, issues: errors })\n else accepted.push(doc)\n }\n if (accepted.length > 0) {\n setDocuments((prev) => {\n const next = [...prev]\n for (const doc of accepted) {\n const i = next.findIndex((d) => d.collection === doc.collection && d.id === doc.id)\n if (i < 0) next.push(doc)\n else next[i] = doc\n }\n return next\n })\n for (const doc of accepted) persisterRef.current?.upsertDocument(doc)\n // EC-224: imports land as the working DRAFT. Publish-ness is the version\n // pointer (`publishedKeys`), set by publishing — never carried in the\n // imported row — so an import never auto-publishes; the editor publishes\n // explicitly afterward.\n report.added = accepted.length\n }\n return report\n },\n [registry, documents, localeConfig, assetExists],\n )\n\n const isFieldReadOnly = useCallback((collectionId: string, field: FieldDef) => {\n return (\n field.form?.readOnly === true ||\n (READ_ONLY_FIELDS[collectionId]?.includes(field.name) ?? false)\n )\n }, [])\n\n // --- Saved views (EC-169) -------------------------------------------------\n\n // Load the project's persisted views once (operations query). Views saved by\n // other editors/sessions on the same project show up here.\n useEffect(() => {\n if (projectId === undefined) return\n let cancelled = false\n void getStudioOperations()\n .then(({ operations }) => loadSavedViews(operations, projectId))\n .then((result) => {\n if (cancelled) return\n if (!result.ok) {\n setPersistError(result.error)\n return\n }\n const grouped: Record<string, SavedView[]> = {}\n for (const record of result.value) {\n ;(grouped[record.collection] ??= []).push({\n id: record.id,\n name: record.name,\n state: record.state,\n })\n }\n setSavedViews(grouped)\n })\n return () => {\n cancelled = true\n }\n }, [projectId])\n\n const viewsOf = useCallback(\n (collectionId: string): SavedView[] => [\n defaultView(registry.get(collectionId)),\n ...(savedViews[collectionId] ?? []),\n ],\n [registry, savedViews],\n )\n\n const activeViewOf = useCallback(\n (collectionId: string): SavedView => {\n const id = activeViews[collectionId] ?? ALL_VIEW_ID\n return (\n viewsOf(collectionId).find((view) => view.id === id) ??\n defaultView(registry.get(collectionId))\n )\n },\n [activeViews, viewsOf, registry],\n )\n\n const tableStateOf = useCallback(\n (collectionId: string): TableViewState =>\n tableStates[collectionId] ?? activeViewOf(collectionId).state,\n [tableStates, activeViewOf],\n )\n\n const dropTableState = useCallback((collectionId: string) => {\n setTableStates((prev) => {\n if (!(collectionId in prev)) return prev\n const next = { ...prev }\n delete next[collectionId]\n return next\n })\n }, [])\n\n const setActiveView = useCallback(\n (collectionId: string, viewId: string) => {\n setActiveViews((prev) => ({ ...prev, [collectionId]: viewId }))\n dropTableState(collectionId)\n },\n [dropTableState],\n )\n\n /**\n * Run one persisted view mutation: pending content mutations + the persisted\n * baseline land first (so the system collection never pre-empts the content\n * schema), then exactly one operations command. Failures surface as\n * `persistError` and report `false` — the session is only updated on success.\n */\n const dispatchViewMutation = useCallback(\n async (\n run: (operations: OperationsClient, projectId: string) => Promise<OperationResult<unknown>>,\n ): Promise<boolean> => {\n if (projectId === undefined) return true // fixture-only session: views stay session-local\n await persisterRef.current?.ensureBaseline()\n const { operations } = await getStudioOperations()\n const result = await run(operations, projectId)\n if (!result.ok) {\n setPersistError(result.error)\n return false\n }\n return true\n },\n [projectId],\n )\n\n const saveViewAs = useCallback(\n async (collectionId: string, name: string): Promise<boolean> => {\n const trimmed = name.trim()\n if (trimmed === '') return false\n const id = newViewId()\n const state = normalizeViewState(tableStateOf(collectionId))\n const ok = await dispatchViewMutation((operations, pid) =>\n saveSavedView(operations, pid, { id, name: trimmed, collection: collectionId, state }),\n )\n if (!ok) return false\n setSavedViews((prev) => ({\n ...prev,\n [collectionId]: [...(prev[collectionId] ?? []), { id, name: trimmed, state }],\n }))\n setActiveViews((prev) => ({ ...prev, [collectionId]: id }))\n dropTableState(collectionId)\n return true\n },\n [dispatchViewMutation, tableStateOf, dropTableState],\n )\n\n const saveActiveView = useCallback(\n async (collectionId: string): Promise<boolean> => {\n const activeId = activeViews[collectionId] ?? ALL_VIEW_ID\n if (activeId === ALL_VIEW_ID) return false // the default view is not persistable\n const current = (savedViews[collectionId] ?? []).find((view) => view.id === activeId)\n if (!current) return false\n const state = normalizeViewState(tableStateOf(collectionId))\n const ok = await dispatchViewMutation((operations, pid) =>\n saveSavedView(operations, pid, {\n id: activeId,\n name: current.name,\n collection: collectionId,\n state,\n }),\n )\n if (!ok) return false\n setSavedViews((prev) => ({\n ...prev,\n [collectionId]: (prev[collectionId] ?? []).map((view) =>\n view.id === activeId ? { ...view, state } : view,\n ),\n }))\n dropTableState(collectionId)\n return true\n },\n [activeViews, savedViews, dispatchViewMutation, tableStateOf, dropTableState],\n )\n\n const deleteView = useCallback(\n async (collectionId: string, viewId: string): Promise<boolean> => {\n if (viewId === ALL_VIEW_ID) return false\n // One documents.delete against the views system collection — content\n // documents are untouched by construction.\n const ok = await dispatchViewMutation((operations, pid) =>\n deleteSavedView(operations, pid, viewId),\n )\n if (!ok) return false\n setSavedViews((prev) => ({\n ...prev,\n [collectionId]: (prev[collectionId] ?? []).filter((view) => view.id !== viewId),\n }))\n if ((activeViews[collectionId] ?? ALL_VIEW_ID) === viewId) {\n setActiveViews((prev) => ({ ...prev, [collectionId]: ALL_VIEW_ID }))\n dropTableState(collectionId)\n }\n return true\n },\n [dispatchViewMutation, activeViews, dropTableState],\n )\n\n // --- Bulk actions (EC-169) ------------------------------------------------\n\n const runBulk = useCallback(\n async (\n collectionId: string,\n ids: readonly string[],\n action: BulkAction,\n ): Promise<BulkReport> => {\n let dispatch:\n | ((action: BulkAction, ref: DocumentRef) => Promise<OperationResult<unknown>>)\n | undefined\n const persister = persisterRef.current\n if (persister && projectId !== undefined) {\n // Pending queued mutations + baseline land first, then one awaited\n // command per item (same ordering contract as commitFieldEdit).\n await persister.ensureBaseline()\n const { operations } = await getStudioOperations()\n dispatch = (bulkAction, ref) =>\n bulkAction === 'delete'\n ? operations.documents.delete({ projectId, ref })\n : bulkAction === 'publish'\n ? operations.documents.publish({ projectId, ref })\n : operations.documents.unpublish({ projectId, ref })\n }\n return runBulkAction(\n {\n documents: documentsRef.current,\n titleOf,\n validate: (doc) =>\n validateDocument(registry, doc, {\n store: createDocumentStore(documentsRef.current),\n localeConfig,\n // EC-225: include the composition validators so a bulk PUBLISH\n // gates blocks/richText validity the same way the detail editor\n // does — the operations-layer publish gate has no component\n // registry, so composition validity is a studio-validation invariant.\n validateComposition,\n validateRichTextEmbeds,\n assetExists,\n }),\n // EC-224: a succeeded publish/unpublish moves the version pointer\n // (`publishedKeys`); the flat `state` mirror is updated in lockstep.\n applyState: (ref, state) => setPublished(ref, state === 'published'),\n applyDelete: (ref) =>\n setDocuments((prev) =>\n prev.filter((d) => !(d.collection === ref.collection && d.id === ref.id)),\n ),\n ...(dispatch ? { dispatch } : {}),\n },\n collectionId,\n ids,\n action,\n )\n },\n [projectId, titleOf, registry, localeConfig, setPublished, assetExists],\n )\n\n const store$ = useMemo<CmsStore>(\n () => ({\n ...(projectId !== undefined ? { projectId } : {}),\n collections,\n localeConfig,\n activeLocale,\n getCollection,\n documentsOf: (collectionId) => documents.filter((d) => d.collection === collectionId),\n getDocument,\n titleOf,\n saveDocument,\n commitFieldEdit,\n createDocument,\n createPage,\n ensureSingletonDocument,\n deleteDocument,\n isPublished,\n publishDocument,\n unpublishDocument,\n loadDocumentVersions,\n restoreDocumentVersion,\n importDocuments,\n validate,\n isFieldReadOnly,\n viewsOf,\n activeViewId: (collectionId) => activeViews[collectionId] ?? ALL_VIEW_ID,\n setActiveView,\n tableStateOf,\n setTableState: (collectionId, update) =>\n setTableStates((prev) => {\n const current = prev[collectionId] ?? activeViewOf(collectionId).state\n const next = typeof update === 'function' ? update(current) : update\n return { ...prev, [collectionId]: next }\n }),\n isViewDirty: (collectionId) => {\n const working = tableStates[collectionId]\n if (working === undefined) return false\n const active = activeViewOf(collectionId).state\n const collection = registry.get(collectionId)\n if (collection === undefined) return !viewStatesEqual(working, active)\n // Compare schema-resolved forms (EC-213): a column-order reconciliation\n // or a stale `hidden` entry must not read as an unsaved edit.\n return !viewStatesEqual(\n canonicalViewState(collection, working),\n canonicalViewState(collection, active),\n )\n },\n resetTableState: dropTableState,\n saveActiveView,\n saveViewAs,\n deleteView,\n runBulk,\n addCollection: (def) =>\n setCollections((prev) => [...prev.filter((c) => c.id !== def.id), def]),\n persistError,\n clearPersistError: () => setPersistError(null),\n ensurePersistedBaseline: () => persisterRef.current?.ensureBaseline() ?? Promise.resolve(),\n flushPersistence: () => persisterRef.current?.flush() ?? Promise.resolve(),\n }),\n [\n projectId,\n collections,\n documents,\n localeConfig,\n activeLocale,\n getCollection,\n getDocument,\n titleOf,\n saveDocument,\n commitFieldEdit,\n createDocument,\n createPage,\n ensureSingletonDocument,\n deleteDocument,\n isPublished,\n publishDocument,\n unpublishDocument,\n loadDocumentVersions,\n restoreDocumentVersion,\n importDocuments,\n validate,\n isFieldReadOnly,\n viewsOf,\n activeViews,\n activeViewOf,\n tableStates,\n tableStateOf,\n setActiveView,\n dropTableState,\n saveActiveView,\n saveViewAs,\n deleteView,\n runBulk,\n registry,\n persistError,\n ],\n )\n\n return <CmsContext.Provider value={store$}>{children}</CmsContext.Provider>\n}\n\nexport function useCms(): CmsStore {\n const store = useContext(CmsContext)\n if (!store) throw new Error('useCms must be used within a <CmsProvider>.')\n return store\n}\n\n/** Export a locale-aware label for a field (form label or name). */\nexport function fieldLabel(field: FieldDef): string {\n return field.form?.label ?? field.name\n}\n\nexport { primaryField }\nexport type { Locale }\n"]}
@@ -1,8 +1,8 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { Link, STUDIO_PROJECT_ROUTE, studioPath, useNavigate } from '@elytracms/studio/router';
3
- import { CircleAlert, CircleCheck, ExternalLink, Eye, EyeOff, History, Languages, Loader2, Lock, MoreHorizontal, Trash2, } from 'lucide-react';
3
+ import { CircleAlert, CircleCheck, ExternalLink, Eye, EyeOff, History, Languages, Loader2, Lock, MoreHorizontal, Tag, Trash2, } from 'lucide-react';
4
4
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
5
- import { documentKey, isBlocksField, isFieldLocalized, isSingleton, resolveField, urlForDocument, } from '@elytracms/core/cms-core';
5
+ import { SIDEBAR_FIELD_GROUP, documentKey, hasAliases, isBlocksField, isFieldHidden, isFieldLocalized, isSingleton, resolveField, sidebarFields, staticFieldHidden, urlForDocument, } from '@elytracms/core/cms-core';
6
6
  import { Badge, Button, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, Field, Heading, Panel, PanelHeader, Row, Spacer, Stack, Text, toast, } from '@elytracms/studio/ui';
7
7
  import { cn } from '@elytracms/studio/lib/utils';
8
8
  import { LocaleSwitcher, displayedFieldFallback, hasLocaleVariant, localeChipLabel, setStudioLocale, } from '@elytracms/studio/lib/locale';
@@ -18,7 +18,7 @@ import { InspectorSidebar } from '../inspector/inspector-sidebar';
18
18
  import { DocumentEditorProvider } from './document-editor-context';
19
19
  import { VersionsPane } from './versions-pane';
20
20
  import { IssuesPane } from './issues-pane';
21
- import { AliasSelector } from './alias-selector';
21
+ import { DetailsPane } from './details-pane';
22
22
  import { useSetBreadcrumb } from '../breadcrumb-context';
23
23
  import { resolveDeploymentFrontendUrl, resolveDeploymentRoutes } from '@elytracms/studio/lib/workspace';
24
24
  import { usePublishedDocuments } from '@elytracms/studio/lib/cms/published-documents';
@@ -136,13 +136,27 @@ function EditorBody({ projectId, collection, doc, focusPath, }) {
136
136
  const REFERENCES_TAB = 'references';
137
137
  const editorTabs = [...tabs, REFERENCES_TAB];
138
138
  const [activeTab, setActiveTab] = useState(tabs[0]);
139
- const tabFields = collection.fields.filter((f) => (f.form?.tab ?? tabs[0]) === activeTab && !f.form?.hidden);
139
+ // EC-285: the reserved `sidebar` group is document-level metadata (slug, author…)
140
+ // — it renders in the Details inspector pane, not as a content tab, so it is
141
+ // excluded from the tab fields here and collected once below.
142
+ const sidebarFieldDefs = useMemo(() => sidebarFields(collection), [collection]);
143
+ // EC-273: only STATICALLY hidden fields (`hidden: true`) are structurally
144
+ // excluded here; a conditionally (predicate) hidden field stays in the tab and
145
+ // is evaluated per-render against the current values (it may show or hide as the
146
+ // editor types).
147
+ const tabFields = collection.fields.filter((f) => (f.form?.tab ?? tabs[0]) === activeTab &&
148
+ !staticFieldHidden(f) &&
149
+ f.form?.group !== SIDEBAR_FIELD_GROUP);
140
150
  const groups = groupFields(tabFields, collection);
141
151
  // EC-188 (AD-12): a composition (`blocks`) field is a special content feature,
142
152
  // not a field-row — it takes over its tab with the full page-builder canvas.
143
153
  // Convention: such a field lives on its own dedicated fieldset tab.
144
154
  const canvasField = tabFields.find(isBlocksField);
145
155
  const [highlightedField, setHighlightedField] = useState(null);
156
+ // EC-285: the form-path inspector's active pane, controlled so a jump to a
157
+ // `sidebar`-group field can open the Details pane (where it renders). Undefined
158
+ // = uncontrolled (the sidebar defaults to its first pane).
159
+ const [inspectorPaneId, setInspectorPaneId] = useState();
146
160
  // Focus a field by name: switch to its tab (and locale, when given), scroll the
147
161
  // control into view, and ring-highlight it. Shared by the reference deep-link
148
162
  // (`focusPath`, EC-172) and the Issues pane's jump-to-field (EC-283).
@@ -151,8 +165,15 @@ function EditorBody({ projectId, collection, doc, focusPath, }) {
151
165
  const field = collection.fields.find((f) => f.name === fieldName);
152
166
  if (!field)
153
167
  return;
154
- const fieldTabs = collection.form?.tabs ?? ['main'];
155
- setActiveTab(field.form?.tab ?? fieldTabs[0]);
168
+ // EC-285: a `sidebar`-group field renders in the Details inspector pane, not
169
+ // a content tab — open that pane instead of switching tabs.
170
+ if (field.form?.group === SIDEBAR_FIELD_GROUP) {
171
+ setInspectorPaneId('details');
172
+ }
173
+ else {
174
+ const fieldTabs = collection.form?.tabs ?? ['main'];
175
+ setActiveTab(field.form?.tab ?? fieldTabs[0]);
176
+ }
156
177
  if (localeHint !== undefined && cms.localeConfig.locales.includes(localeHint)) {
157
178
  setStudioLocale(localeHint);
158
179
  }
@@ -211,6 +232,40 @@ function EditorBody({ projectId, collection, doc, focusPath, }) {
211
232
  return { ...d, values };
212
233
  });
213
234
  }
235
+ // EC-273: conditional-visibility context — the draft's values for the active
236
+ // locale, against which a field's `hidden(values)` predicate is evaluated. A
237
+ // hidden field's row is omitted (and it is not validated). Recomputed as the
238
+ // draft changes, so a field shows/hides live as the editor types.
239
+ const conditionValues = { ...draft.values, ...(draft.localized?.[locale] ?? {}) };
240
+ const isHidden = (field) => isFieldHidden(field, { values: conditionValues });
241
+ const visibleSidebarFields = sidebarFieldDefs.filter((f) => !isHidden(f));
242
+ // One document field row (label + fallback/translation/read-only badges + the
243
+ // control), shared by the content groups and the EC-285 Details pane so a
244
+ // sidebar field renders identically — same control, validation, localization,
245
+ // and EC-283 highlight/jump target — wherever it surfaces. Returns null when the
246
+ // field is conditionally hidden (EC-273).
247
+ function renderFieldRow(field) {
248
+ if (isHidden(field))
249
+ return null;
250
+ // Field-level read-only (the Lock badge) vs the view-level read-only
251
+ // (Published perspective) — the control honors both.
252
+ const fieldLevelReadOnly = cms.isFieldReadOnly(collection.id, field);
253
+ const fieldReadOnly = viewReadOnly || fieldLevelReadOnly;
254
+ const localized = isFieldLocalized(collection, field.name);
255
+ // Fallback visibility (EC-176): the control DISPLAYS the fallback value, and
256
+ // this marker says so on the exact field.
257
+ const fallback = localized
258
+ ? displayedFieldFallback(collection, viewDoc, field.name, locale, cms.localeConfig)
259
+ : null;
260
+ // The variant was created in this editing session (the saved document doesn't
261
+ // have it yet): editing a fallback-shown value is an explicit translation act.
262
+ // Moot (and hidden) while viewing the read-only published snapshot.
263
+ const newlyTranslated = !viewReadOnly &&
264
+ localized &&
265
+ hasLocaleVariant(draft, field.name, locale) &&
266
+ !hasLocaleVariant(doc, field.name, locale);
267
+ return (_jsx(Field, { className: cn('rounded-md transition-shadow', highlightedField === field.name && 'bg-primary/5 p-2 ring-2 ring-primary/70'), label: _jsxs(Row, { gap: "2", children: [_jsx("span", { children: fieldLabel(field) }), field.validation?.required ? _jsx("span", { className: "text-destructive", children: "*" }) : null, localized ? _jsx(Badge, { variant: "outline", children: locale }) : null, fallback ? (_jsxs(Badge, { variant: "warning", title: fallbackTitle(fallback), "data-testid": `field-fallback-${field.name}`, children: ["showing ", localeChipLabel(fallback.sourceLocale)] })) : null, newlyTranslated ? (_jsxs(Badge, { variant: "success", "data-testid": `field-translated-${field.name}`, children: [_jsx(Languages, { className: "size-3" }), " translated to ", localeChipLabel(locale)] })) : null, fieldLevelReadOnly ? (_jsxs(Badge, { variant: "outline", children: [_jsx(Lock, { className: "size-3" }), " read-only"] })) : null, _jsx(Spacer, {})] }), htmlFor: `f-${field.name}`, hint: fallback ? (_jsxs(_Fragment, { children: ["Showing the ", localeChipLabel(fallback.sourceLocale), " (fallback) value \u2014 edit to translate to ", localeChipLabel(locale), ". Clearing the ", localeChipLabel(locale), " text falls back again."] })) : (field.form?.description), error: fieldReadOnly ? undefined : errorsByField.get(field.name), children: _jsx(FieldControl, { id: `f-${field.name}`, field: field, value: getValue(field), onChange: (v) => setValue(field, v), readOnly: fieldReadOnly }) }, field.name));
268
+ }
214
269
  function save() {
215
270
  cms.saveDocument(draft);
216
271
  }
@@ -245,7 +300,31 @@ function EditorBody({ projectId, collection, doc, focusPath, }) {
245
300
  badge: issues.length === 0 ? undefined : (_jsx(Badge, { variant: errorCount > 0 ? 'error' : 'warning', className: "px-1.5 py-0 leading-none", children: issues.length })),
246
301
  render: () => (_jsx(IssuesPane, { issues: issues, collection: collection, onJumpToField: focusField })),
247
302
  }), [issues, errorCount, collection, focusField]);
248
- const trailingPanes = useMemo(() => [versionsPane, issuesPane], [versionsPane, issuesPane]);
303
+ // EC-284 + EC-285: the document-metadata pane — slot assignment (EC-284) and/or
304
+ // the document-level `sidebar`-group fields (EC-285). Present only when the
305
+ // collection has either, so it never adds an empty tab elsewhere. First in the
306
+ // order, so a slotted / sidebar-bearing document opens straight to it. Not
307
+ // memoized: its render closes over per-render edit state (draft, highlight,
308
+ // field errors) via `renderFieldRow`, and the inspector re-renders with the rest
309
+ // of the editor anyway, so a stable pane identity would buy nothing here.
310
+ const detailsPane = hasAliases(collection) || visibleSidebarFields.length > 0
311
+ ? {
312
+ id: 'details',
313
+ label: 'Details',
314
+ icon: _jsx(Tag, { className: "size-3.5" }),
315
+ render: () => (_jsx(DetailsPane, { collection: collection, doc: draft, siblings: cms.documentsOf(collection.id), readOnly: viewReadOnly, fields: visibleSidebarFields, renderField: renderFieldRow, onAliasChange: (alias) => setDraft((d) => {
316
+ const next = { ...d };
317
+ if (alias === undefined)
318
+ delete next.alias;
319
+ else
320
+ next.alias = alias;
321
+ return next;
322
+ }) })),
323
+ }
324
+ : null;
325
+ const trailingPanes = detailsPane
326
+ ? [detailsPane, versionsPane, issuesPane]
327
+ : [versionsPane, issuesPane];
249
328
  // EC-268: the Publish button is its own indicator — pending while the publish
250
329
  // round-trips, a brief success, and an error toast if it rejects at transport.
251
330
  const [publishState, setPublishState] = useState('idle');
@@ -349,40 +428,19 @@ function EditorBody({ projectId, collection, doc, focusPath, }) {
349
428
  ? 'Switch to Draft to publish'
350
429
  : hasErrors
351
430
  ? `Fix ${errorCount} ${errorCount === 1 ? 'issue' : 'issues'} to publish`
352
- : undefined, children: publishState === 'pending' ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "animate-spin" }), " Publishing\u2026"] })) : publishState === 'success' ? (_jsxs(_Fragment, { children: [_jsx(CircleCheck, {}), " Published"] })) : (_jsxs(_Fragment, { children: [_jsx(Eye, {}), " Publish"] })) }), cms.isPublished(ref) || !singleton ? (_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { asChild: true, children: _jsx(Button, { variant: "outline", size: "icon-sm", "aria-label": "More actions", children: _jsx(MoreHorizontal, {}) }) }), _jsxs(DropdownMenuContent, { align: "end", children: [cms.isPublished(ref) ? (_jsxs(DropdownMenuItem, { onClick: () => setConfirmAction('unpublish'), children: [_jsx(EyeOff, {}), " Unpublish"] })) : null, singleton ? null : (_jsxs(DropdownMenuItem, { "data-testid": "doc-delete", className: "text-destructive", onClick: () => setConfirmAction('delete'), children: [_jsx(Trash2, {}), " Delete"] }))] })] })) : null] }), _jsxs(Row, { gap: "3", className: "mt-3", wrap: true, children: [_jsx(LocaleSwitcher, {}), _jsx(Row, { gap: "1", children: editorTabs.map((tab) => (_jsx("button", { type: "button", "aria-pressed": tab === activeTab, onClick: () => setActiveTab(tab), className: cn('rounded-md px-2.5 py-1 text-xs font-medium capitalize transition-colors', tab === activeTab ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:bg-muted'), children: tab }, tab))) }), _jsx(AliasSelector, { collection: collection, doc: draft, siblings: cms.documentsOf(collection.id), readOnly: viewReadOnly, onChange: (alias) => setDraft((d) => {
353
- const next = { ...d };
354
- if (alias === undefined)
355
- delete next.alias;
356
- else
357
- next.alias = alias;
358
- return next;
359
- }) }), _jsx(Spacer, {}), _jsxs(Row, { gap: "px", className: "rounded-md bg-muted/60 p-0.5", children: [_jsx(PerspectiveButton, { label: "Draft", active: perspective === 'draft', onClick: () => setPerspective('draft') }), _jsx(PerspectiveButton, { label: "Published", active: perspective === 'published', accent: "info", disabled: !published, title: published ? undefined : 'Publish this document to view its published version', onClick: () => setPerspective('published') })] })] })] }), viewReadOnly ? (_jsxs(Row, { gap: "2", className: "shrink-0 border-b border-info/30 bg-info/10 px-4 py-1.5 text-info sm:px-6", "data-testid": "published-view-banner", children: [_jsx(Lock, { className: "size-3.5 shrink-0", "aria-hidden": true }), _jsx(Text, { size: "xs", className: "text-info", children: "Viewing the published version \u2014 read-only." }), _jsx(Spacer, {}), _jsx("button", { type: "button", onClick: () => setPerspective('draft'), className: "text-xs font-medium underline-offset-2 hover:underline", children: "Switch to Draft" })] })) : null, publishedPending ? (_jsx("div", { className: "grid min-h-0 flex-1 place-items-center p-8", children: _jsx(Text, { size: "sm", tone: "muted", children: publishedSnapshot.status === 'loading'
431
+ : undefined, children: publishState === 'pending' ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "animate-spin" }), " Publishing\u2026"] })) : publishState === 'success' ? (_jsxs(_Fragment, { children: [_jsx(CircleCheck, {}), " Published"] })) : (_jsxs(_Fragment, { children: [_jsx(Eye, {}), " Publish"] })) }), cms.isPublished(ref) || !singleton ? (_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { asChild: true, children: _jsx(Button, { variant: "outline", size: "icon-sm", "aria-label": "More actions", children: _jsx(MoreHorizontal, {}) }) }), _jsxs(DropdownMenuContent, { align: "end", children: [cms.isPublished(ref) ? (_jsxs(DropdownMenuItem, { onClick: () => setConfirmAction('unpublish'), children: [_jsx(EyeOff, {}), " Unpublish"] })) : null, singleton ? null : (_jsxs(DropdownMenuItem, { "data-testid": "doc-delete", className: "text-destructive", onClick: () => setConfirmAction('delete'), children: [_jsx(Trash2, {}), " Delete"] }))] })] })) : null] }), _jsxs(Row, { gap: "3", className: "mt-3", wrap: true, children: [_jsx(LocaleSwitcher, {}), _jsx(Row, { gap: "1", children: editorTabs.map((tab) => (_jsx("button", { type: "button", "aria-pressed": tab === activeTab, onClick: () => setActiveTab(tab), className: cn('rounded-md px-2.5 py-1 text-xs font-medium capitalize transition-colors', tab === activeTab ? 'bg-accent text-accent-foreground' : 'text-muted-foreground hover:bg-muted'), children: tab }, tab))) }), _jsx(Spacer, {}), _jsxs(Row, { gap: "px", className: "rounded-md bg-muted/60 p-0.5", children: [_jsx(PerspectiveButton, { label: "Draft", active: perspective === 'draft', onClick: () => setPerspective('draft') }), _jsx(PerspectiveButton, { label: "Published", active: perspective === 'published', accent: "info", disabled: !published, title: published ? undefined : 'Publish this document to view its published version', onClick: () => setPerspective('published') })] })] })] }), viewReadOnly ? (_jsxs(Row, { gap: "2", className: "shrink-0 border-b border-info/30 bg-info/10 px-4 py-1.5 text-info sm:px-6", "data-testid": "published-view-banner", children: [_jsx(Lock, { className: "size-3.5 shrink-0", "aria-hidden": true }), _jsx(Text, { size: "xs", className: "text-info", children: "Viewing the published version \u2014 read-only." }), _jsx(Spacer, {}), _jsx("button", { type: "button", onClick: () => setPerspective('draft'), className: "text-xs font-medium underline-offset-2 hover:underline", children: "Switch to Draft" })] })) : null, publishedPending ? (_jsx("div", { className: "grid min-h-0 flex-1 place-items-center p-8", children: _jsx(Text, { size: "sm", tone: "muted", children: publishedSnapshot.status === 'loading'
360
432
  ? 'Loading the published version…'
361
433
  : 'No published version found for this document.' }) })) : canvasField ? (_jsx("div", { className: "min-h-0 flex-1 overflow-hidden", children: _jsx(CompositionFieldEditor, { field: canvasField, value: getValue(canvasField), onChange: (v) => setValue(canvasField, v), readOnly: viewReadOnly || cms.isFieldReadOnly(collection.id, canvasField), trailingPanes: trailingPanes }, `${canvasField.name}:${restoreNonce}:${perspective}`) })) : activeTab === REFERENCES_TAB ? (
362
434
  // EC-269: mounted only while this tab is active → reference data loads on
363
435
  // demand and is torn down on leave (no fetching during normal editing).
364
- _jsx("div", { className: "flex min-h-0 flex-1 overflow-hidden", children: _jsx("div", { className: "min-h-0 flex-1 overflow-auto p-4 sm:p-6", children: _jsx("div", { className: "mx-auto w-full max-w-2xl", children: _jsx(ReferencesPanel, { projectId: projectId, source: { type: 'document', id: documentKey(ref) }, target: { type: 'document', id: documentKey(ref) } }) }) }) })) : (_jsxs("div", { className: "flex min-h-0 flex-1 overflow-hidden", children: [_jsx("div", { className: "min-h-0 flex-1 overflow-auto p-4 sm:p-6", children: _jsx("div", { className: "mx-auto w-full max-w-2xl", children: _jsx(Stack, { gap: "6", children: groups.map((group) => (_jsxs(Panel, { children: [_jsx(PanelHeader, { children: _jsx(Text, { size: "sm", weight: "semibold", className: "capitalize", children: group.name }) }), _jsx(Stack, { gap: "4", className: "p-4", children: group.fields.map((field) => {
365
- // Field-level read-only (the Lock badge) vs the view-level
366
- // read-only (Published perspective) — the control honors both.
367
- const fieldLevelReadOnly = cms.isFieldReadOnly(collection.id, field);
368
- const fieldReadOnly = viewReadOnly || fieldLevelReadOnly;
369
- const localized = isFieldLocalized(collection, field.name);
370
- // Fallback visibility (EC-176): the control DISPLAYS the
371
- // fallback value, and this marker says so on the exact field.
372
- const fallback = localized
373
- ? displayedFieldFallback(collection, viewDoc, field.name, locale, cms.localeConfig)
374
- : null;
375
- // The variant was created in this editing session (the
376
- // saved document doesn't have it yet): editing a
377
- // fallback-shown value is an explicit translation act. Moot
378
- // (and hidden) while viewing the read-only published snapshot.
379
- const newlyTranslated = !viewReadOnly &&
380
- localized &&
381
- hasLocaleVariant(draft, field.name, locale) &&
382
- !hasLocaleVariant(doc, field.name, locale);
383
- return (_jsx(Field, { className: cn('rounded-md transition-shadow', highlightedField === field.name &&
384
- 'bg-primary/5 p-2 ring-2 ring-primary/70'), label: _jsxs(Row, { gap: "2", children: [_jsx("span", { children: fieldLabel(field) }), field.validation?.required ? _jsx("span", { className: "text-destructive", children: "*" }) : null, localized ? _jsx(Badge, { variant: "outline", children: locale }) : null, fallback ? (_jsxs(Badge, { variant: "warning", title: fallbackTitle(fallback), "data-testid": `field-fallback-${field.name}`, children: ["showing ", localeChipLabel(fallback.sourceLocale)] })) : null, newlyTranslated ? (_jsxs(Badge, { variant: "success", "data-testid": `field-translated-${field.name}`, children: [_jsx(Languages, { className: "size-3" }), " translated to ", localeChipLabel(locale)] })) : null, fieldLevelReadOnly ? (_jsxs(Badge, { variant: "outline", children: [_jsx(Lock, { className: "size-3" }), " read-only"] })) : null, _jsx(Spacer, {})] }), htmlFor: `f-${field.name}`, hint: fallback ? (_jsxs(_Fragment, { children: ["Showing the ", localeChipLabel(fallback.sourceLocale), " (fallback) value \u2014 edit to translate to ", localeChipLabel(locale), ". Clearing the", ' ', localeChipLabel(locale), " text falls back again."] })) : (field.form?.description), error: fieldReadOnly ? undefined : errorsByField.get(field.name), children: _jsx(FieldControl, { id: `f-${field.name}`, field: field, value: getValue(field), onChange: (v) => setValue(field, v), readOnly: fieldReadOnly }) }, field.name));
385
- }) })] }, group.name))) }) }) }), _jsx(InspectorSidebar, { panes: trailingPanes, className: "w-[320px] shrink-0 border-l border-border" })] })), confirmAction !== null ? (_jsx(ReferenceConfirmDialog, { projectId: projectId, action: confirmAction, targets: confirmTargets, open: true, onOpenChange: (open) => {
436
+ _jsx("div", { className: "flex min-h-0 flex-1 overflow-hidden", children: _jsx("div", { className: "min-h-0 flex-1 overflow-auto p-4 sm:p-6", children: _jsx("div", { className: "mx-auto w-full max-w-2xl", children: _jsx(ReferencesPanel, { projectId: projectId, source: { type: 'document', id: documentKey(ref) }, target: { type: 'document', id: documentKey(ref) } }) }) }) })) : (_jsxs("div", { className: "flex min-h-0 flex-1 overflow-hidden", children: [_jsx("div", { className: "min-h-0 flex-1 overflow-auto p-4 sm:p-6", children: _jsx("div", { className: "mx-auto w-full max-w-2xl", children: _jsx(Stack, { gap: "6", children: groups.map((group) => {
437
+ // EC-273: drop a fieldset whose every field is conditionally hidden,
438
+ // so the form never shows an empty panel header.
439
+ const visible = group.fields.filter((f) => !isHidden(f));
440
+ if (visible.length === 0)
441
+ return null;
442
+ return (_jsxs(Panel, { children: [_jsx(PanelHeader, { children: _jsx(Text, { size: "sm", weight: "semibold", className: "capitalize", children: group.name }) }), _jsx(Stack, { gap: "4", className: "p-4", children: visible.map(renderFieldRow) })] }, group.name));
443
+ }) }) }) }), _jsx(InspectorSidebar, { panes: trailingPanes, activeId: inspectorPaneId, onActiveChange: setInspectorPaneId, className: "w-[320px] shrink-0 border-l border-border" })] })), confirmAction !== null ? (_jsx(ReferenceConfirmDialog, { projectId: projectId, action: confirmAction, targets: confirmTargets, open: true, onOpenChange: (open) => {
386
444
  if (!open)
387
445
  setConfirmAction(null);
388
446
  }, onConfirm: handleConfirmedAction })) : null] }) }));