@elytracms/studio 0.0.48 → 0.0.49
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.
- package/dist/components/cms/cms-store.d.ts +7 -2
- package/dist/components/cms/cms-store.js +35 -4
- package/dist/components/cms/cms-store.js.map +1 -1
- package/dist/components/cms/view-bar.js +4 -2
- package/dist/components/cms/view-bar.js.map +1 -1
- package/dist/lib/cms-views/view-model.d.ts +33 -4
- package/dist/lib/cms-views/view-model.js +66 -10
- package/dist/lib/cms-views/view-model.js.map +1 -1
- package/dist/lib/collection-view/collection-view-source.d.ts +3 -2
- package/dist/lib/collection-view/collection-view-source.js.map +1 -1
- package/package.json +2 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ReactNode } from 'react';
|
|
2
|
-
import type { CmsDocument, CmsValidationIssue, CollectionDef, CollectionRegistry, DocumentRef, FieldDef, Locale, LocaleConfig, RestoreScope } from '@elytracms/core/cms-core';
|
|
2
|
+
import type { CmsDocument, CmsValidationIssue, CollectionDef, CollectionRegistry, DocumentRef, FieldDef, Locale, LocaleConfig, LocalizedString, RestoreScope } from '@elytracms/core/cms-core';
|
|
3
3
|
import type { DocumentVersionRecord } from '@elytracms/core/persistence';
|
|
4
4
|
import type { OperationError } from '@elytracms/studio/lib/operations';
|
|
5
5
|
import type { TableViewState } from '@elytracms/studio/lib/cms-views';
|
|
@@ -14,7 +14,12 @@ import type { BulkAction, BulkReport, BulkSetField } from './bulk-actions';
|
|
|
14
14
|
*/
|
|
15
15
|
export interface SavedView {
|
|
16
16
|
id: string;
|
|
17
|
-
|
|
17
|
+
/**
|
|
18
|
+
* The view label — a {@link LocalizedString} (EC-343): the built-in "All" default is
|
|
19
|
+
* a plain translated string; a config view's name may be a `{ locale }` map, resolved
|
|
20
|
+
* at the render site (`ViewTabs`) via the same `resolveLabel` path as `form.label`.
|
|
21
|
+
*/
|
|
22
|
+
name: LocalizedString;
|
|
18
23
|
state: TableViewState;
|
|
19
24
|
}
|
|
20
25
|
export interface ImportReport {
|
|
@@ -9,7 +9,7 @@ import { validateComposition, validateRichTextEmbeds } from './cms-composition-v
|
|
|
9
9
|
import { matchesRef, removeDoc, replaceDoc, upsertDoc } from './document-ref-utils';
|
|
10
10
|
import { createRequiredContext } from '@elytracms/studio/lib/required-context';
|
|
11
11
|
import { createCmsPersister, getStudioOperations } from '@elytracms/studio/lib/operations';
|
|
12
|
-
import { ALL_VIEW_ID, canonicalViewState, configViewsFor, defaultViewState, viewStatesEqual, } from '@elytracms/studio/lib/cms-views';
|
|
12
|
+
import { ALL_VIEW_ID, canonicalViewState, configViewIssues, configViewsFor, defaultConfigViewId, defaultViewState, viewStatesEqual, } from '@elytracms/studio/lib/cms-views';
|
|
13
13
|
import { useOptionalAssets } from '../assets/assets-store';
|
|
14
14
|
import { consumeStagedDocuments } from './document-staging';
|
|
15
15
|
import { applyCellValue, commitCellEdit } from './cell-edit';
|
|
@@ -63,6 +63,24 @@ export function buildNewDocument(collectionId, registry, seq, existingDocs) {
|
|
|
63
63
|
export function hasDocumentFor(docs, collectionId) {
|
|
64
64
|
return docs.some((d) => d.collection === collectionId);
|
|
65
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* Surface a duplicate `default: true` across a collection's config views (EC-343) as
|
|
68
|
+
* a visible, one-time console warning — never a silent swallow. This is a developer
|
|
69
|
+
* config mistake (editors can't fix config-as-code), so it takes the same warn-once
|
|
70
|
+
* console channel the i18n runtime uses for config problems, not an editor banner;
|
|
71
|
+
* the first-declared default still seeds deterministically. Deduped per collection id.
|
|
72
|
+
*/
|
|
73
|
+
const warnedDuplicateDefaultCollections = new Set();
|
|
74
|
+
function warnDuplicateDefaultViews(collection) {
|
|
75
|
+
if (warnedDuplicateDefaultCollections.has(collection.id))
|
|
76
|
+
return;
|
|
77
|
+
const issues = configViewIssues(collection);
|
|
78
|
+
if (issues.length === 0)
|
|
79
|
+
return;
|
|
80
|
+
warnedDuplicateDefaultCollections.add(collection.id);
|
|
81
|
+
if (typeof console !== 'undefined')
|
|
82
|
+
console.warn(`[views] ${issues[0].message}`);
|
|
83
|
+
}
|
|
66
84
|
/** The unnamed built-in view: no filters, no sort, every field visible. */
|
|
67
85
|
function defaultView(collection) {
|
|
68
86
|
return {
|
|
@@ -441,11 +459,23 @@ export function CmsProvider({ children, projectId, initialCollections, initialDo
|
|
|
441
459
|
...(configCollection ? configViewsFor(configCollection) : []),
|
|
442
460
|
];
|
|
443
461
|
}, [registry]);
|
|
462
|
+
// The INITIAL active view for a collection (EC-343): a config view flagged
|
|
463
|
+
// `default: true` seeds the first-load lens; else the built-in "All" default. Only
|
|
464
|
+
// consulted before the editor has picked a view (`activeViews[id]` wins once set),
|
|
465
|
+
// so transient switching + Reset are unaffected. A duplicate `default` is warned
|
|
466
|
+
// once (never silent) and the first-declared default seeds deterministically.
|
|
467
|
+
const initialViewId = useCallback((collectionId) => {
|
|
468
|
+
const configCollection = resolveDeploymentCollections().find((c) => c.id === collectionId);
|
|
469
|
+
if (!configCollection)
|
|
470
|
+
return ALL_VIEW_ID;
|
|
471
|
+
warnDuplicateDefaultViews(configCollection);
|
|
472
|
+
return defaultConfigViewId(configCollection) ?? ALL_VIEW_ID;
|
|
473
|
+
}, []);
|
|
444
474
|
const activeViewOf = useCallback((collectionId) => {
|
|
445
|
-
const id = activeViews[collectionId] ??
|
|
475
|
+
const id = activeViews[collectionId] ?? initialViewId(collectionId);
|
|
446
476
|
return (viewsOf(collectionId).find((view) => view.id === id) ??
|
|
447
477
|
defaultView(registry.get(collectionId)));
|
|
448
|
-
}, [activeViews, viewsOf, registry]);
|
|
478
|
+
}, [activeViews, initialViewId, viewsOf, registry]);
|
|
449
479
|
const tableStateOf = useCallback((collectionId) => tableStates[collectionId] ?? activeViewOf(collectionId).state, [tableStates, activeViewOf]);
|
|
450
480
|
const dropTableState = useCallback((collectionId) => {
|
|
451
481
|
setTableStates((prev) => {
|
|
@@ -565,7 +595,7 @@ export function CmsProvider({ children, projectId, initialCollections, initialDo
|
|
|
565
595
|
validate,
|
|
566
596
|
isFieldReadOnly,
|
|
567
597
|
viewsOf,
|
|
568
|
-
activeViewId: (collectionId) => activeViews[collectionId] ??
|
|
598
|
+
activeViewId: (collectionId) => activeViews[collectionId] ?? initialViewId(collectionId),
|
|
569
599
|
setActiveView,
|
|
570
600
|
tableStateOf,
|
|
571
601
|
setTableState: (collectionId, update) => setTableStates((prev) => {
|
|
@@ -617,6 +647,7 @@ export function CmsProvider({ children, projectId, initialCollections, initialDo
|
|
|
617
647
|
viewsOf,
|
|
618
648
|
activeViews,
|
|
619
649
|
activeViewOf,
|
|
650
|
+
initialViewId,
|
|
620
651
|
tableStates,
|
|
621
652
|
tableStateOf,
|
|
622
653
|
setActiveView,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cms-store.js","sourceRoot":"","sources":["../../../src/components/cms/cms-store.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAEzE,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,WAAW,EACX,cAAc,EACd,oBAAoB,EACpB,YAAY,EACZ,eAAe,EACf,YAAY,EACZ,2BAA2B,EAC3B,kBAAkB,EAClB,mBAAmB,EACnB,wBAAwB,EACxB,YAAY,EACZ,gBAAgB,GACjB,MAAM,0BAA0B,CAAA;AAajC,OAAO,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAA;AACtD,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAA;AACtF,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAA;AACrE,OAAO,EAAE,4BAA4B,EAAE,MAAM,iCAAiC,CAAA;AAC9E,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,8BAA8B,CAAA;AAC1F,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,UAA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,YAAY;QACZ,WAAW;QACX,YAAY;QACZ,aAAa;QACb,cAAc;QACd,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,OAAO,EAAE,MAAM,EAAE,CAAA;AAEjB,OAAO,EAAE,YAAY,EAAE,CAAA","sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport {\n createCollectionRegistry,\n createDocumentStore,\n documentKey,\n documentSchema,\n resolveDocumentTitle,\n resolveField,\n sampleDocuments,\n seedDefaults,\n sampleFilterableCollections,\n sampleLocaleConfig,\n samplePublishedKeys,\n resolveSingletonDocument,\n titleFieldOf,\n validateDocument,\n} from '@elytracms/core/cms-core'\nimport type {\n CmsDocument,\n CmsValidationIssue,\n CollectionDef,\n CollectionRegistry,\n DocumentRef,\n FieldDef,\n Locale,\n LocaleConfig,\n RestoreScope,\n} from '@elytracms/core/cms-core'\nimport type { DocumentVersionRecord } from '@elytracms/core/persistence'\nimport { translate } from '@elytracms/studio/lib/i18n'\nimport { configureStudioLocales, useStudioLocale } from '@elytracms/studio/lib/locale'\nimport { studioManifestLookup } from '@elytracms/studio/lib/registry'\nimport { resolveDeploymentCollections } from '@elytracms/studio/lib/workspace'\nimport { validateComposition, validateRichTextEmbeds } from './cms-composition-validators'\nimport { matchesRef, removeDoc, replaceDoc, upsertDoc } from './document-ref-utils'\nimport { createRequiredContext } from '@elytracms/studio/lib/required-context'\nimport { createCmsPersister, getStudioOperations } from '@elytracms/studio/lib/operations'\nimport type {\n CmsPersister,\n OperationError,\n OperationResult,\n} from '@elytracms/studio/lib/operations'\nimport {\n ALL_VIEW_ID,\n canonicalViewState,\n configViewsFor,\n defaultViewState,\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 { consumeStagedDocuments } from './document-staging'\nimport { applyCellValue, commitCellEdit } from './cell-edit'\nimport type { CellCommitInput, CellCommitOutcome } from './cell-edit'\nimport { runBulkAction } from './bulk-actions'\nimport type { BulkAction, BulkReport, BulkSetField } from './bulk-actions'\n\n/**\n * A resolved table view: a named bundle of filters (closed AD-3 vocabulary),\n * sort, and visible/ordered columns. EC-246b: named views are **config-as-code**\n * (declared in `cms/`, read live via `configViewsFor`) — the editor-owned DB\n * saved-view store (EC-169) is retired. The unnamed \"All documents\" default is\n * derived per collection; editors keep only transient in-session tweaks + Reset.\n */\nexport interface SavedView {\n id: string\n name: string\n state: TableViewState\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 /**\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. An optional `scope` (EC-298) restores only one\n * field or block, laid over the current draft, instead of the whole document.\n * Returns the restored draft (or null on failure/fixture session) so the open\n * editor can adopt it.\n */\n restoreDocumentVersion(\n ref: DocumentRef,\n version: number,\n scope?: RestoreScope,\n ): Promise<CmsDocument | null>\n importDocuments(collectionId: string, docs: unknown[]): ImportReport\n validate(doc: CmsDocument): CmsValidationIssue[]\n isFieldReadOnly(field: FieldDef): boolean\n // Views (EC-246b): the built-in default + config-declared named views (from\n // `cms/`, read live). Shared views are code, not editor-owned DB data.\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 /**\n * Bulk publish/unpublish/delete (EC-169) + set-field (EC-247): one operations\n * command PER item, per-item outcomes in the report — partial failure is\n * enumerated, never silent. Only succeeded items mutate the session. A\n * `set-field` carries its `{ field, value }` payload.\n */\n runBulk(\n collectionId: string,\n ids: readonly string[],\n action: BulkAction,\n setField?: BulkSetField,\n ): 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 { Context: CmsContext, useRequired: useCms } = createRequiredContext<CmsStore>('Cms')\n\nfunction primaryField(collection: CollectionDef): string {\n return titleFieldOf(collection)?.name ?? collection.fields[0]?.name ?? 'id'\n}\n\n/**\n * EC-316 (bug fix) — mint a fresh, COLLISION-FREE document id for `+ New`.\n *\n * `seq` is an in-memory, per-session counter (reset to 0 on every reload). A\n * document minted `new-<collection>-<n>` in a PRIOR session can already occupy\n * whatever `n` this session's counter would next reissue — the pre-fix bug:\n * `+ New` on a `post` collection that already held a (possibly published)\n * `new-post-1` handed out that SAME id again, silently opening the existing\n * document for editing instead of creating a fresh draft. Walking the counter\n * past every id already in `existingIds` makes the mint collision-free\n * regardless of what a prior session left behind.\n */\nexport function mintDocumentId(\n collectionId: string,\n seq: { current: number },\n existingIds: ReadonlySet<string>,\n): string {\n let id: string\n do {\n seq.current += 1\n id = `new-${collectionId}-${seq.current}`\n } while (existingIds.has(id))\n return id\n}\n\n/**\n * Build a fresh document for `collectionId`: a collision-free id (EC-316, via\n * {@link mintDocumentId} against every id `existingDocs` already holds for\n * this collection) and the collection's declared field defaults (EC-297, via\n * `seedDefaults`). Pure — the sensitive part of the insert sequence shared by\n * `createDocument` and `ensureSingletonDocument`'s empty branch (via the\n * private `insertNewDocument` below), factored out so it's unit-testable\n * without a `CmsProvider`.\n */\nexport function buildNewDocument(\n collectionId: string,\n registry: CollectionRegistry,\n seq: { current: number },\n existingDocs: readonly CmsDocument[],\n): CmsDocument {\n const existingIds = new Set(\n existingDocs.filter((d) => d.collection === collectionId).map((d) => d.id),\n )\n const id = mintDocumentId(collectionId, seq, existingIds)\n const collection = registry.get(collectionId)\n return { collection: collectionId, id, values: collection ? seedDefaults(collection) : {} }\n}\n\n/**\n * Does `docs` already hold a document for `collectionId`? `ensureSingletonDocument`'s\n * empty branch re-checks this INSIDE the `setDocuments` updater (against the\n * latest `prev`, not a stale snapshot) so a concurrent invocation — StrictMode's\n * double-invoked effect, or a second caller racing the same synchronous guard —\n * can never materialize a second singleton document.\n */\nexport function hasDocumentFor(docs: readonly CmsDocument[], collectionId: string): boolean {\n return docs.some((d) => d.collection === collectionId)\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: translate('cms.list.view.all'),\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 const seeded = (initialDocuments ?? sampleDocuments).map((d) => structuredClone(d))\n // EC-320 (0.0.44 follow-up): merge any documents STAGED by the\n // Components-view \"Use in document…\" transfer — a cross-mount handoff in\n // EVERY mode now (see document-staging.ts), not just the playground. The\n // merge rule itself stays mode-aware there: playground's seeded set is a\n // static baseline that never reflects a write (staged always wins);\n // Convex's is a fresh per-mount hydration query (staged fills gaps only,\n // dropped once the seeded set actually carries the key).\n return consumeStagedDocuments(projectId, seeded)\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 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) => matchesRef(d, ref)),\n [documents],\n )\n\n const titleOf = useCallback(\n (ref: DocumentRef) => {\n const doc = documents.find((d) => matchesRef(d, ref))\n const collection = registry.get(ref.collection)\n if (!doc || !collection) return ref.id\n // EC-296/EC-242: a function `titleField` (title pattern) composes the title\n // from the document's resolved values (active locale). Only resolve the full\n // value set when a function is declared — the common string `titleField` case\n // still resolves the single title field below (primaryField === the title field).\n if (typeof collection.titleField === 'function') {\n const values: Record<string, unknown> = {}\n for (const field of collection.fields) {\n values[field.name] = resolveField(collection, doc, field.name, activeLocale, localeConfig).value\n }\n return resolveDocumentTitle(collection, values, ref.id)\n }\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 // Replace-or-append (upsert): a brand-new document must still land even\n // though nothing in the session matches its ref yet.\n setDocuments((prev) => upsertDoc(prev, doc))\n persisterRef.current?.upsertDocument(doc)\n }, [])\n\n const commitFieldEdit = useCallback(\n (input: CellCommitInput): Promise<CellCommitOutcome> => {\n // Pure map-replace: an edit always targets a document already open in\n // the session, so a miss (already gone) is a no-op, never an append.\n const replaceWith = (doc: CmsDocument) => setDocuments((prev) => replaceDoc(prev, doc))\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 // Shared insert sequence (EC-326): existingIds/mint/seedDefaults (via\n // `buildNewDocument`) + optimistic append + persist, consumed by both\n // `createDocument` (always inserts) and `ensureSingletonDocument`'s empty\n // branch (`guardExisting: true` — re-checks \"no document for this collection\n // yet\" against the LATEST `prev` inside the `setDocuments` updater, not the\n // `documentsRef.current` snapshot the caller already checked, so a\n // concurrent invocation — StrictMode's double-invoked effect — can never\n // materialize a second singleton document).\n const insertNewDocument = useCallback(\n (collectionId: string, options?: { guardExisting?: boolean }): CmsDocument => {\n const doc = buildNewDocument(collectionId, registry, seq, documentsRef.current)\n setDocuments((prev) =>\n options?.guardExisting && hasDocumentFor(prev, collectionId) ? prev : [...prev, doc],\n )\n persisterRef.current?.upsertDocument(doc)\n return doc\n },\n [registry],\n )\n\n const createDocument = useCallback(\n (collectionId: string): DocumentRef => {\n const doc = insertNewDocument(collectionId)\n return { collection: collectionId, id: doc.id }\n },\n [insertNewDocument],\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 // EC-316: same collision-free mint as `createDocument` (via the shared\n // `insertNewDocument` — defensive here, the singleton-empty branch only\n // runs when no document exists yet).\n const doc = insertNewDocument(collectionId, { guardExisting: true })\n return { collection: collectionId, id: doc.id }\n },\n [registry, insertNewDocument],\n )\n\n const deleteDocument = useCallback((ref: DocumentRef) => {\n setDocuments((prev) => removeDoc(prev, ref))\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: no clearing here — the draft is already free of conditionally-hidden\n // values (the editor clears them on write), so the snapshot the publish op\n // pins is clean by construction.\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 (\n ref: DocumentRef,\n version: number,\n scope?: RestoreScope,\n ): 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). This is\n // what makes a granular (field/block) restore merge over the LATEST draft.\n await persisterRef.current?.ensureBaseline()\n const { operations } = await getStudioOperations()\n const result = await operations.documents.restore({\n projectId,\n ref,\n version,\n ...(scope ? { scope } : {}),\n })\n if (!result.ok) {\n setPersistError(result.error)\n return null\n }\n const restored = result.value.document\n // Pure map-replace: a restore always targets a document already open in\n // the session.\n setDocuments((prev) => replaceDoc(prev, restored))\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 ?? translate('cms.list.import.noId'),\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 // Replace-or-append (upsert): an imported row may be brand new to the\n // session, so each accepted document must land even with no prior\n // entry for its ref.\n setDocuments((prev) => accepted.reduce((acc, doc) => upsertDoc(acc, doc), prev))\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((field: FieldDef) => field.form?.readOnly === true, [])\n\n // --- Views (EC-246b: config-as-code) --------------------------------------\n\n const viewsOf = useCallback(\n (collectionId: string): SavedView[] => {\n // The built-in default plus the collection's config-declared views (EC-246b).\n // Views are PRESENTATION, read live from elytra.config.ts (AD-11) — not the\n // persisted content schema the session booted from — so they reflect code\n // immediately without a re-seed (the persisted schema is only baselined on\n // first run). The EC-169 DB saved-view store is retired: shared views are\n // code, editors keep only transient in-session tweaks + Reset.\n const configCollection = resolveDeploymentCollections().find((c) => c.id === collectionId)\n return [\n defaultView(registry.get(collectionId)),\n ...(configCollection ? configViewsFor(configCollection) : []),\n ]\n },\n [registry],\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 // --- Bulk actions (EC-169) ------------------------------------------------\n\n const runBulk = useCallback(\n async (\n collectionId: string,\n ids: readonly string[],\n action: BulkAction,\n setField?: BulkSetField,\n ): Promise<BulkReport> => {\n const collection = registry.get(collectionId)\n // A set-field needs both the field payload AND the collection def to fold\n // the value the locale-aware way — guard so a misconfigured call fails\n // loud rather than silently no-opping each item.\n if (action === 'set-field' && (!setField || !collection)) {\n return {\n action,\n ...(setField ? { setField } : {}),\n results: ids.map((id) => ({\n ref: { collection: collectionId, id },\n title: titleOf({ collection: collectionId, id }),\n ok: false,\n reason: translate('cms.list.bulk.error.invalidSetField'),\n error: { code: 'unknown', message: 'Invalid set-field request.' },\n })),\n }\n }\n // The next document for a set-field item: fold the value into the active\n // locale's bag (localized) or the shared `values` (non-localized).\n const setFieldDoc = (doc: CmsDocument): CmsDocument =>\n applyCellValue(collection!, doc, setField!.field, activeLocale, setField!.value)\n\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 if (bulkAction === 'delete') return operations.documents.delete({ projectId, ref })\n if (bulkAction === 'publish') return operations.documents.publish({ projectId, ref })\n if (bulkAction === 'unpublish') return operations.documents.unpublish({ projectId, ref })\n // set-field: upsert the document carrying the new value. The write\n // path self-types it through the schema lens (EC-277); a scalar field\n // stores its scalar as-is.\n const current = documentsRef.current.find((d) => matchesRef(d, ref))\n if (!current) {\n return Promise.resolve<OperationResult<unknown>>({\n ok: false,\n error: {\n code: 'not-found',\n message: 'Document is no longer in the session.',\n entity: 'cms-document',\n key: `${ref.collection}:${ref.id}`,\n },\n })\n }\n return operations.documents.upsert({ projectId, document: setFieldDoc(current) })\n }\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`) via setPublished — there is no separate flat\n // `state` mirror to keep in sync (published-ness is derived from the\n // pointer set).\n applyState: (ref, state) => setPublished(ref, state === 'published'),\n applyDelete: (ref) => setDocuments((prev) => removeDoc(prev, ref)),\n // EC-247: fold the new value into the session document (same\n // locale-aware path the dispatched upsert used). Not a plain\n // `replaceDoc` — the replacement is computed FROM each matched\n // document (`setFieldDoc(d)`), not a fixed value to swap in.\n applySetField: (ref) =>\n setDocuments((prev) => prev.map((d) => (matchesRef(d, ref) ? setFieldDoc(d) : d))),\n ...(dispatch ? { dispatch } : {}),\n },\n collectionId,\n ids,\n action,\n setField,\n )\n },\n [projectId, titleOf, registry, localeConfig, activeLocale, 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 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 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 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 runBulk,\n registry,\n persistError,\n ],\n )\n\n return <CmsContext.Provider value={store$}>{children}</CmsContext.Provider>\n}\n\nexport { useCms }\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,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAEzE,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,WAAW,EACX,cAAc,EACd,oBAAoB,EACpB,YAAY,EACZ,eAAe,EACf,YAAY,EACZ,2BAA2B,EAC3B,kBAAkB,EAClB,mBAAmB,EACnB,wBAAwB,EACxB,YAAY,EACZ,gBAAgB,GACjB,MAAM,0BAA0B,CAAA;AAcjC,OAAO,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAA;AACtD,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAA;AACtF,OAAO,EAAE,oBAAoB,EAAE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a;QACb,WAAW;QACX,YAAY;QACZ,aAAa;QACb,cAAc;QACd,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,OAAO,EAAE,MAAM,EAAE,CAAA;AAEjB,OAAO,EAAE,YAAY,EAAE,CAAA","sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport {\n createCollectionRegistry,\n createDocumentStore,\n documentKey,\n documentSchema,\n resolveDocumentTitle,\n resolveField,\n sampleDocuments,\n seedDefaults,\n sampleFilterableCollections,\n sampleLocaleConfig,\n samplePublishedKeys,\n resolveSingletonDocument,\n titleFieldOf,\n validateDocument,\n} from '@elytracms/core/cms-core'\nimport type {\n CmsDocument,\n CmsValidationIssue,\n CollectionDef,\n CollectionRegistry,\n DocumentRef,\n FieldDef,\n Locale,\n LocaleConfig,\n LocalizedString,\n RestoreScope,\n} from '@elytracms/core/cms-core'\nimport type { DocumentVersionRecord } from '@elytracms/core/persistence'\nimport { translate } from '@elytracms/studio/lib/i18n'\nimport { configureStudioLocales, useStudioLocale } from '@elytracms/studio/lib/locale'\nimport { studioManifestLookup } from '@elytracms/studio/lib/registry'\nimport { resolveDeploymentCollections } from '@elytracms/studio/lib/workspace'\nimport { validateComposition, validateRichTextEmbeds } from './cms-composition-validators'\nimport { matchesRef, removeDoc, replaceDoc, upsertDoc } from './document-ref-utils'\nimport { createRequiredContext } from '@elytracms/studio/lib/required-context'\nimport { createCmsPersister, getStudioOperations } from '@elytracms/studio/lib/operations'\nimport type {\n CmsPersister,\n OperationError,\n OperationResult,\n} from '@elytracms/studio/lib/operations'\nimport {\n ALL_VIEW_ID,\n canonicalViewState,\n configViewIssues,\n configViewsFor,\n defaultConfigViewId,\n defaultViewState,\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 { consumeStagedDocuments } from './document-staging'\nimport { applyCellValue, commitCellEdit } from './cell-edit'\nimport type { CellCommitInput, CellCommitOutcome } from './cell-edit'\nimport { runBulkAction } from './bulk-actions'\nimport type { BulkAction, BulkReport, BulkSetField } from './bulk-actions'\n\n/**\n * A resolved table view: a named bundle of filters (closed AD-3 vocabulary),\n * sort, and visible/ordered columns. EC-246b: named views are **config-as-code**\n * (declared in `cms/`, read live via `configViewsFor`) — the editor-owned DB\n * saved-view store (EC-169) is retired. The unnamed \"All documents\" default is\n * derived per collection; editors keep only transient in-session tweaks + Reset.\n */\nexport interface SavedView {\n id: string\n /**\n * The view label — a {@link LocalizedString} (EC-343): the built-in \"All\" default is\n * a plain translated string; a config view's name may be a `{ locale }` map, resolved\n * at the render site (`ViewTabs`) via the same `resolveLabel` path as `form.label`.\n */\n name: LocalizedString\n state: TableViewState\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 /**\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. An optional `scope` (EC-298) restores only one\n * field or block, laid over the current draft, instead of the whole document.\n * Returns the restored draft (or null on failure/fixture session) so the open\n * editor can adopt it.\n */\n restoreDocumentVersion(\n ref: DocumentRef,\n version: number,\n scope?: RestoreScope,\n ): Promise<CmsDocument | null>\n importDocuments(collectionId: string, docs: unknown[]): ImportReport\n validate(doc: CmsDocument): CmsValidationIssue[]\n isFieldReadOnly(field: FieldDef): boolean\n // Views (EC-246b): the built-in default + config-declared named views (from\n // `cms/`, read live). Shared views are code, not editor-owned DB data.\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 /**\n * Bulk publish/unpublish/delete (EC-169) + set-field (EC-247): one operations\n * command PER item, per-item outcomes in the report — partial failure is\n * enumerated, never silent. Only succeeded items mutate the session. A\n * `set-field` carries its `{ field, value }` payload.\n */\n runBulk(\n collectionId: string,\n ids: readonly string[],\n action: BulkAction,\n setField?: BulkSetField,\n ): 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 { Context: CmsContext, useRequired: useCms } = createRequiredContext<CmsStore>('Cms')\n\nfunction primaryField(collection: CollectionDef): string {\n return titleFieldOf(collection)?.name ?? collection.fields[0]?.name ?? 'id'\n}\n\n/**\n * EC-316 (bug fix) — mint a fresh, COLLISION-FREE document id for `+ New`.\n *\n * `seq` is an in-memory, per-session counter (reset to 0 on every reload). A\n * document minted `new-<collection>-<n>` in a PRIOR session can already occupy\n * whatever `n` this session's counter would next reissue — the pre-fix bug:\n * `+ New` on a `post` collection that already held a (possibly published)\n * `new-post-1` handed out that SAME id again, silently opening the existing\n * document for editing instead of creating a fresh draft. Walking the counter\n * past every id already in `existingIds` makes the mint collision-free\n * regardless of what a prior session left behind.\n */\nexport function mintDocumentId(\n collectionId: string,\n seq: { current: number },\n existingIds: ReadonlySet<string>,\n): string {\n let id: string\n do {\n seq.current += 1\n id = `new-${collectionId}-${seq.current}`\n } while (existingIds.has(id))\n return id\n}\n\n/**\n * Build a fresh document for `collectionId`: a collision-free id (EC-316, via\n * {@link mintDocumentId} against every id `existingDocs` already holds for\n * this collection) and the collection's declared field defaults (EC-297, via\n * `seedDefaults`). Pure — the sensitive part of the insert sequence shared by\n * `createDocument` and `ensureSingletonDocument`'s empty branch (via the\n * private `insertNewDocument` below), factored out so it's unit-testable\n * without a `CmsProvider`.\n */\nexport function buildNewDocument(\n collectionId: string,\n registry: CollectionRegistry,\n seq: { current: number },\n existingDocs: readonly CmsDocument[],\n): CmsDocument {\n const existingIds = new Set(\n existingDocs.filter((d) => d.collection === collectionId).map((d) => d.id),\n )\n const id = mintDocumentId(collectionId, seq, existingIds)\n const collection = registry.get(collectionId)\n return { collection: collectionId, id, values: collection ? seedDefaults(collection) : {} }\n}\n\n/**\n * Does `docs` already hold a document for `collectionId`? `ensureSingletonDocument`'s\n * empty branch re-checks this INSIDE the `setDocuments` updater (against the\n * latest `prev`, not a stale snapshot) so a concurrent invocation — StrictMode's\n * double-invoked effect, or a second caller racing the same synchronous guard —\n * can never materialize a second singleton document.\n */\nexport function hasDocumentFor(docs: readonly CmsDocument[], collectionId: string): boolean {\n return docs.some((d) => d.collection === collectionId)\n}\n\n/**\n * Surface a duplicate `default: true` across a collection's config views (EC-343) as\n * a visible, one-time console warning — never a silent swallow. This is a developer\n * config mistake (editors can't fix config-as-code), so it takes the same warn-once\n * console channel the i18n runtime uses for config problems, not an editor banner;\n * the first-declared default still seeds deterministically. Deduped per collection id.\n */\nconst warnedDuplicateDefaultCollections = new Set<string>()\nfunction warnDuplicateDefaultViews(collection: CollectionDef): void {\n if (warnedDuplicateDefaultCollections.has(collection.id)) return\n const issues = configViewIssues(collection)\n if (issues.length === 0) return\n warnedDuplicateDefaultCollections.add(collection.id)\n if (typeof console !== 'undefined') console.warn(`[views] ${issues[0]!.message}`)\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: translate('cms.list.view.all'),\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 const seeded = (initialDocuments ?? sampleDocuments).map((d) => structuredClone(d))\n // EC-320 (0.0.44 follow-up): merge any documents STAGED by the\n // Components-view \"Use in document…\" transfer — a cross-mount handoff in\n // EVERY mode now (see document-staging.ts), not just the playground. The\n // merge rule itself stays mode-aware there: playground's seeded set is a\n // static baseline that never reflects a write (staged always wins);\n // Convex's is a fresh per-mount hydration query (staged fills gaps only,\n // dropped once the seeded set actually carries the key).\n return consumeStagedDocuments(projectId, seeded)\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 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) => matchesRef(d, ref)),\n [documents],\n )\n\n const titleOf = useCallback(\n (ref: DocumentRef) => {\n const doc = documents.find((d) => matchesRef(d, ref))\n const collection = registry.get(ref.collection)\n if (!doc || !collection) return ref.id\n // EC-296/EC-242: a function `titleField` (title pattern) composes the title\n // from the document's resolved values (active locale). Only resolve the full\n // value set when a function is declared — the common string `titleField` case\n // still resolves the single title field below (primaryField === the title field).\n if (typeof collection.titleField === 'function') {\n const values: Record<string, unknown> = {}\n for (const field of collection.fields) {\n values[field.name] = resolveField(collection, doc, field.name, activeLocale, localeConfig).value\n }\n return resolveDocumentTitle(collection, values, ref.id)\n }\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 // Replace-or-append (upsert): a brand-new document must still land even\n // though nothing in the session matches its ref yet.\n setDocuments((prev) => upsertDoc(prev, doc))\n persisterRef.current?.upsertDocument(doc)\n }, [])\n\n const commitFieldEdit = useCallback(\n (input: CellCommitInput): Promise<CellCommitOutcome> => {\n // Pure map-replace: an edit always targets a document already open in\n // the session, so a miss (already gone) is a no-op, never an append.\n const replaceWith = (doc: CmsDocument) => setDocuments((prev) => replaceDoc(prev, doc))\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 // Shared insert sequence (EC-326): existingIds/mint/seedDefaults (via\n // `buildNewDocument`) + optimistic append + persist, consumed by both\n // `createDocument` (always inserts) and `ensureSingletonDocument`'s empty\n // branch (`guardExisting: true` — re-checks \"no document for this collection\n // yet\" against the LATEST `prev` inside the `setDocuments` updater, not the\n // `documentsRef.current` snapshot the caller already checked, so a\n // concurrent invocation — StrictMode's double-invoked effect — can never\n // materialize a second singleton document).\n const insertNewDocument = useCallback(\n (collectionId: string, options?: { guardExisting?: boolean }): CmsDocument => {\n const doc = buildNewDocument(collectionId, registry, seq, documentsRef.current)\n setDocuments((prev) =>\n options?.guardExisting && hasDocumentFor(prev, collectionId) ? prev : [...prev, doc],\n )\n persisterRef.current?.upsertDocument(doc)\n return doc\n },\n [registry],\n )\n\n const createDocument = useCallback(\n (collectionId: string): DocumentRef => {\n const doc = insertNewDocument(collectionId)\n return { collection: collectionId, id: doc.id }\n },\n [insertNewDocument],\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 // EC-316: same collision-free mint as `createDocument` (via the shared\n // `insertNewDocument` — defensive here, the singleton-empty branch only\n // runs when no document exists yet).\n const doc = insertNewDocument(collectionId, { guardExisting: true })\n return { collection: collectionId, id: doc.id }\n },\n [registry, insertNewDocument],\n )\n\n const deleteDocument = useCallback((ref: DocumentRef) => {\n setDocuments((prev) => removeDoc(prev, ref))\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: no clearing here — the draft is already free of conditionally-hidden\n // values (the editor clears them on write), so the snapshot the publish op\n // pins is clean by construction.\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 (\n ref: DocumentRef,\n version: number,\n scope?: RestoreScope,\n ): 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). This is\n // what makes a granular (field/block) restore merge over the LATEST draft.\n await persisterRef.current?.ensureBaseline()\n const { operations } = await getStudioOperations()\n const result = await operations.documents.restore({\n projectId,\n ref,\n version,\n ...(scope ? { scope } : {}),\n })\n if (!result.ok) {\n setPersistError(result.error)\n return null\n }\n const restored = result.value.document\n // Pure map-replace: a restore always targets a document already open in\n // the session.\n setDocuments((prev) => replaceDoc(prev, restored))\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 ?? translate('cms.list.import.noId'),\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 // Replace-or-append (upsert): an imported row may be brand new to the\n // session, so each accepted document must land even with no prior\n // entry for its ref.\n setDocuments((prev) => accepted.reduce((acc, doc) => upsertDoc(acc, doc), prev))\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((field: FieldDef) => field.form?.readOnly === true, [])\n\n // --- Views (EC-246b: config-as-code) --------------------------------------\n\n const viewsOf = useCallback(\n (collectionId: string): SavedView[] => {\n // The built-in default plus the collection's config-declared views (EC-246b).\n // Views are PRESENTATION, read live from elytra.config.ts (AD-11) — not the\n // persisted content schema the session booted from — so they reflect code\n // immediately without a re-seed (the persisted schema is only baselined on\n // first run). The EC-169 DB saved-view store is retired: shared views are\n // code, editors keep only transient in-session tweaks + Reset.\n const configCollection = resolveDeploymentCollections().find((c) => c.id === collectionId)\n return [\n defaultView(registry.get(collectionId)),\n ...(configCollection ? configViewsFor(configCollection) : []),\n ]\n },\n [registry],\n )\n\n // The INITIAL active view for a collection (EC-343): a config view flagged\n // `default: true` seeds the first-load lens; else the built-in \"All\" default. Only\n // consulted before the editor has picked a view (`activeViews[id]` wins once set),\n // so transient switching + Reset are unaffected. A duplicate `default` is warned\n // once (never silent) and the first-declared default seeds deterministically.\n const initialViewId = useCallback((collectionId: string): string => {\n const configCollection = resolveDeploymentCollections().find((c) => c.id === collectionId)\n if (!configCollection) return ALL_VIEW_ID\n warnDuplicateDefaultViews(configCollection)\n return defaultConfigViewId(configCollection) ?? ALL_VIEW_ID\n }, [])\n\n const activeViewOf = useCallback(\n (collectionId: string): SavedView => {\n const id = activeViews[collectionId] ?? initialViewId(collectionId)\n return (\n viewsOf(collectionId).find((view) => view.id === id) ??\n defaultView(registry.get(collectionId))\n )\n },\n [activeViews, initialViewId, 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 // --- Bulk actions (EC-169) ------------------------------------------------\n\n const runBulk = useCallback(\n async (\n collectionId: string,\n ids: readonly string[],\n action: BulkAction,\n setField?: BulkSetField,\n ): Promise<BulkReport> => {\n const collection = registry.get(collectionId)\n // A set-field needs both the field payload AND the collection def to fold\n // the value the locale-aware way — guard so a misconfigured call fails\n // loud rather than silently no-opping each item.\n if (action === 'set-field' && (!setField || !collection)) {\n return {\n action,\n ...(setField ? { setField } : {}),\n results: ids.map((id) => ({\n ref: { collection: collectionId, id },\n title: titleOf({ collection: collectionId, id }),\n ok: false,\n reason: translate('cms.list.bulk.error.invalidSetField'),\n error: { code: 'unknown', message: 'Invalid set-field request.' },\n })),\n }\n }\n // The next document for a set-field item: fold the value into the active\n // locale's bag (localized) or the shared `values` (non-localized).\n const setFieldDoc = (doc: CmsDocument): CmsDocument =>\n applyCellValue(collection!, doc, setField!.field, activeLocale, setField!.value)\n\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 if (bulkAction === 'delete') return operations.documents.delete({ projectId, ref })\n if (bulkAction === 'publish') return operations.documents.publish({ projectId, ref })\n if (bulkAction === 'unpublish') return operations.documents.unpublish({ projectId, ref })\n // set-field: upsert the document carrying the new value. The write\n // path self-types it through the schema lens (EC-277); a scalar field\n // stores its scalar as-is.\n const current = documentsRef.current.find((d) => matchesRef(d, ref))\n if (!current) {\n return Promise.resolve<OperationResult<unknown>>({\n ok: false,\n error: {\n code: 'not-found',\n message: 'Document is no longer in the session.',\n entity: 'cms-document',\n key: `${ref.collection}:${ref.id}`,\n },\n })\n }\n return operations.documents.upsert({ projectId, document: setFieldDoc(current) })\n }\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`) via setPublished — there is no separate flat\n // `state` mirror to keep in sync (published-ness is derived from the\n // pointer set).\n applyState: (ref, state) => setPublished(ref, state === 'published'),\n applyDelete: (ref) => setDocuments((prev) => removeDoc(prev, ref)),\n // EC-247: fold the new value into the session document (same\n // locale-aware path the dispatched upsert used). Not a plain\n // `replaceDoc` — the replacement is computed FROM each matched\n // document (`setFieldDoc(d)`), not a fixed value to swap in.\n applySetField: (ref) =>\n setDocuments((prev) => prev.map((d) => (matchesRef(d, ref) ? setFieldDoc(d) : d))),\n ...(dispatch ? { dispatch } : {}),\n },\n collectionId,\n ids,\n action,\n setField,\n )\n },\n [projectId, titleOf, registry, localeConfig, activeLocale, 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 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] ?? initialViewId(collectionId),\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 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 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 initialViewId,\n tableStates,\n tableStateOf,\n setActiveView,\n dropTableState,\n runBulk,\n registry,\n persistError,\n ],\n )\n\n return <CmsContext.Provider value={store$}>{children}</CmsContext.Provider>\n}\n\nexport { useCms }\n\nexport { primaryField }\nexport type { Locale }\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { ArrowDown, ArrowUp, Check, List, ListTree, SlidersHorizontal } from 'lucide-react';
|
|
3
3
|
import { Button, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, Row, SegmentedControl, Text, } from '@elytracms/studio/ui';
|
|
4
|
-
import { translate } from '@elytracms/studio/lib/i18n';
|
|
4
|
+
import { localizedLabel, translate } from '@elytracms/studio/lib/i18n';
|
|
5
5
|
import { moveColumn, resolveColumns, toggleColumn } from '@elytracms/studio/lib/cms-views';
|
|
6
6
|
import { fieldLabel } from './cms-labels';
|
|
7
7
|
import { useCollectionView } from '../collection-view/collection-view-context';
|
|
@@ -26,7 +26,9 @@ export function ViewTabs() {
|
|
|
26
26
|
const active = views.find((view) => view.id === activeId) ?? views[0];
|
|
27
27
|
return (_jsx(SegmentedControl, { testId: "view-bar", items: views.map((view) => ({
|
|
28
28
|
key: view.id,
|
|
29
|
-
|
|
29
|
+
// EC-343: a config view's `name` may be a LocalizedString — resolve it against
|
|
30
|
+
// the active UI locale at the render site, exactly like `form.label` (fieldLabel).
|
|
31
|
+
label: localizedLabel(view.name, view.id),
|
|
30
32
|
active: view.id === active.id,
|
|
31
33
|
onClick: () => source.views?.setActive(view.id),
|
|
32
34
|
testId: `view-chip-${view.id}`,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"view-bar.js","sourceRoot":"","sources":["../../../src/components/cms/view-bar.tsx"],"names":[],"mappings":";AACA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAE3F,OAAO,EACL,MAAM,EACN,YAAY,EACZ,mBAAmB,EACnB,gBAAgB,EAChB,iBAAiB,EACjB,qBAAqB,EACrB,mBAAmB,EACnB,GAAG,EACH,gBAAgB,EAChB,IAAI,GACL,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAA;AACtD,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAA;AAC1F,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,4CAA4C,CAAA;AAE9E;;;;;;;;;;GAUG;AACH,MAAM,UAAU,QAAQ;IACtB,MAAM,MAAM,GAAG,iBAAiB,EAAE,CAAA;IAClC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,CAAA;IAExC,mFAAmF;IACnF,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC;QAAE,OAAO,IAAI,CAAA;IAElC,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,EAAE,QAAQ,EAAE,CAAA;IACzC,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,QAAQ,CAAC,IAAI,KAAK,CAAC,CAAC,CAAE,CAAA;IAEtE,OAAO,CACL,KAAC,gBAAgB,IACf,MAAM,EAAC,UAAU,EACjB,KAAK,EAAE,KAAK,CAAC,GAAG,CAA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D,MAAM,CAAC,KAAK,CA0CA,CACpB,CAAA;oBACH,CAAC,CAAC,IACkB,IACT,CAChB,CAAA;AACH,CAAC;AAED,4EAA4E;AAC5E,SAAS,YAAY,CAAC,EACpB,KAAK,EACL,IAAI,EACJ,MAAM,EACN,QAAQ,GAMT;IACC,OAAO,CACL,MAAC,gBAAgB,mBACF,UAAU,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,EAAE,EACrD,QAAQ,EAAE,CAAC,KAAK,EAAE,EAAE;YAClB,KAAK,CAAC,cAAc,EAAE,CAAA;YACtB,QAAQ,EAAE,CAAA;QACZ,CAAC,aAEA,IAAI,EACL,KAAC,IAAI,IAAC,EAAE,EAAC,MAAM,EAAC,IAAI,EAAC,IAAI,EAAC,SAAS,EAAC,yBAAyB,YAC1D,KAAK,GACD,EACN,MAAM,CAAC,CAAC,CAAC,KAAC,KAAK,IAAC,SAAS,EAAC,uBAAuB,GAAG,CAAC,CAAC,CAAC,IAAI,IAC3C,CACpB,CAAA;AACH,CAAC;AAED,SAAS,gBAAgB,CAAC,EACxB,KAAK,EACL,IAAI,EACJ,QAAQ,EACR,MAAM,GAMP;IACC,OAAO,CACL,KAAC,MAAM,IACL,OAAO,EAAC,OAAO,EACf,IAAI,EAAC,SAAS,EACd,SAAS,EAAC,uBAAuB,gBACrB,KAAK,EACjB,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;YACjB,KAAK,CAAC,cAAc,EAAE,CAAA;YACtB,KAAK,CAAC,eAAe,EAAE,CAAA;YACvB,MAAM,EAAE,CAAA;QACV,CAAC,YAEA,IAAI,GACE,CACV,CAAA;AACH,CAAC","sourcesContent":["import type { ReactNode } from 'react'\nimport { ArrowDown, ArrowUp, Check, List, ListTree, SlidersHorizontal } from 'lucide-react'\nimport type { CollectionDef } from '@elytracms/core/cms-core'\nimport {\n Button,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n Row,\n SegmentedControl,\n Text,\n} from '@elytracms/studio/ui'\nimport { translate } from '@elytracms/studio/lib/i18n'\nimport { moveColumn, resolveColumns, toggleColumn } from '@elytracms/studio/lib/cms-views'\nimport { fieldLabel } from './cms-labels'\nimport { useCollectionView } from '../collection-view/collection-view-context'\n\n/**\n * The view selector of the collection table (EC-169) — a segmented control that\n * switches between the built-in \"All documents\" default and the project's\n * code-defined views (EC-246b: views are config-as-code, so this only *picks* a\n * lens; it never creates, edits, or deletes one at runtime). Renders nothing\n * when the default view is the only one — no lonely single-tab chrome. Shares\n * the segmented-control language of the locale switcher for a consistent header.\n *\n * AD-19: reads the named-views capability off the portable {@link useCollectionView}\n * source, so a rail without config-declared views simply shows no selector.\n */\nexport function ViewTabs() {\n const source = useCollectionView()\n const views = source.views?.list() ?? []\n\n // A single (default) view needs no selector — the breadcrumb names the collection.\n if (views.length <= 1) return null\n\n const activeId = source.views?.activeId()\n const active = views.find((view) => view.id === activeId) ?? views[0]!\n\n return (\n <SegmentedControl\n testId=\"view-bar\"\n items={views.map((view) => ({\n key: view.id,\n label: view.name,\n active: view.id === active.id,\n onClick: () => source.views?.setActive(view.id),\n testId: `view-chip-${view.id}`,\n }))}\n />\n )\n}\n\n/**\n * Display options for the collection table (EC-246a) — one far-right control,\n * aligned with where per-row actions live, folding together how the list is\n * *shown*: the page hierarchy layout (flat vs tree, for hierarchical collections)\n * and visible/ordered columns. Column order is a property of all columns (visible\n * or not); the first visible column is the title/link and can't be hidden.\n */\nexport function DisplayMenu({\n collection,\n hierarchical,\n treeMode,\n onToggleTree,\n}: {\n collection: CollectionDef\n hierarchical: boolean\n treeMode: boolean\n onToggleTree: (tree: boolean) => void\n}) {\n const source = useCollectionView()\n const state = source.viewState()\n const columns = resolveColumns(collection, state)\n const titleField = columns.find((column) => column.visible)?.field\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n aria-label={translate('cms.list.display.ariaLabel')}\n title={translate('cms.list.display.title')}\n data-testid=\"display-menu\"\n >\n <SlidersHorizontal />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" className=\"w-64\">\n {hierarchical ? (\n <>\n <DropdownMenuLabel>{translate('cms.list.display.layout')}</DropdownMenuLabel>\n <LayoutOption\n label={translate('cms.list.display.flatList')}\n icon={<List />}\n active={!treeMode}\n onSelect={() => onToggleTree(false)}\n />\n <LayoutOption\n label={translate('cms.list.display.pageHierarchy')}\n icon={<ListTree />}\n active={treeMode}\n onSelect={() => onToggleTree(true)}\n />\n <DropdownMenuSeparator />\n </>\n ) : null}\n <DropdownMenuLabel>{translate('cms.list.display.columns')}</DropdownMenuLabel>\n {columns.map((column, index) => {\n const field = collection.fields.find((f) => f.name === column.field)\n if (!field) return null\n const isTitle = column.field === titleField\n return (\n <DropdownMenuItem\n key={column.field}\n onSelect={(event) => event.preventDefault()}\n data-testid={`column-row-${column.field}`}\n >\n <input\n type=\"checkbox\"\n className=\"size-3.5 accent-primary\"\n checked={column.visible}\n disabled={isTitle}\n onChange={() =>\n source.setViewState((prev) => toggleColumn(collection, prev, column.field))\n }\n aria-label={translate('cms.list.display.toggleColumn', { field: fieldLabel(field) })}\n data-testid={`column-toggle-${column.field}`}\n />\n <Text as=\"span\" size=\"sm\" className=\"min-w-0 flex-1 truncate\">\n {fieldLabel(field)}\n {isTitle ? (\n <Text as=\"span\" size=\"xs\" tone=\"subtle\">\n {' '}\n {translate('cms.list.display.titleTag')}\n </Text>\n ) : null}\n </Text>\n <Row gap=\"1\">\n <ColumnMoveButton\n label={translate('cms.list.display.moveColumnUp', { field: fieldLabel(field) })}\n icon={<ArrowUp />}\n disabled={index <= 0}\n onMove={() =>\n source.setViewState((prev) => moveColumn(collection, prev, column.field, -1))\n }\n />\n <ColumnMoveButton\n label={translate('cms.list.display.moveColumnDown', { field: fieldLabel(field) })}\n icon={<ArrowDown />}\n disabled={index >= columns.length - 1}\n onMove={() =>\n source.setViewState((prev) => moveColumn(collection, prev, column.field, 1))\n }\n />\n </Row>\n </DropdownMenuItem>\n )\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\n/** One layout choice (flat vs tree) — a checkmark marks the active mode. */\nfunction LayoutOption({\n label,\n icon,\n active,\n onSelect,\n}: {\n label: string\n icon: ReactNode\n active: boolean\n onSelect: () => void\n}) {\n return (\n <DropdownMenuItem\n data-testid={`layout-${active ? 'active' : 'option'}`}\n onSelect={(event) => {\n event.preventDefault()\n onSelect()\n }}\n >\n {icon}\n <Text as=\"span\" size=\"sm\" className=\"min-w-0 flex-1 truncate\">\n {label}\n </Text>\n {active ? <Check className=\"size-3.5 text-primary\" /> : null}\n </DropdownMenuItem>\n )\n}\n\nfunction ColumnMoveButton({\n label,\n icon,\n disabled,\n onMove,\n}: {\n label: string\n icon: ReactNode\n disabled: boolean\n onMove: () => void\n}) {\n return (\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n className=\"size-5 [&_svg]:size-3\"\n aria-label={label}\n disabled={disabled}\n onClick={(event) => {\n event.preventDefault()\n event.stopPropagation()\n onMove()\n }}\n >\n {icon}\n </Button>\n )\n}\n"]}
|
|
1
|
+
{"version":3,"file":"view-bar.js","sourceRoot":"","sources":["../../../src/components/cms/view-bar.tsx"],"names":[],"mappings":";AACA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAE3F,OAAO,EACL,MAAM,EACN,YAAY,EACZ,mBAAmB,EACnB,gBAAgB,EAChB,iBAAiB,EACjB,qBAAqB,EACrB,mBAAmB,EACnB,GAAG,EACH,gBAAgB,EAChB,IAAI,GACL,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAA;AACtE,OAAO,EAAE,UAAU,EAAE,cAA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,MAAM,EAAC,IAAI,EAAC,IAAI,EAAC,SAAS,EAAC,yBAAyB,YAC1D,KAAK,GACD,EACN,MAAM,CAAC,CAAC,CAAC,KAAC,KAAK,IAAC,SAAS,EAAC,uBAAuB,GAAG,CAAC,CAAC,CAAC,IAAI,IAC3C,CACpB,CAAA;AACH,CAAC;AAED,SAAS,gBAAgB,CAAC,EACxB,KAAK,EACL,IAAI,EACJ,QAAQ,EACR,MAAM,GAMP;IACC,OAAO,CACL,KAAC,MAAM,IACL,OAAO,EAAC,OAAO,EACf,IAAI,EAAC,SAAS,EACd,SAAS,EAAC,uBAAuB,gBACrB,KAAK,EACjB,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;YACjB,KAAK,CAAC,cAAc,EAAE,CAAA;YACtB,KAAK,CAAC,eAAe,EAAE,CAAA;YACvB,MAAM,EAAE,CAAA;QACV,CAAC,YAEA,IAAI,GACE,CACV,CAAA;AACH,CAAC","sourcesContent":["import type { ReactNode } from 'react'\nimport { ArrowDown, ArrowUp, Check, List, ListTree, SlidersHorizontal } from 'lucide-react'\nimport type { CollectionDef } from '@elytracms/core/cms-core'\nimport {\n Button,\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuLabel,\n DropdownMenuSeparator,\n DropdownMenuTrigger,\n Row,\n SegmentedControl,\n Text,\n} from '@elytracms/studio/ui'\nimport { localizedLabel, translate } from '@elytracms/studio/lib/i18n'\nimport { moveColumn, resolveColumns, toggleColumn } from '@elytracms/studio/lib/cms-views'\nimport { fieldLabel } from './cms-labels'\nimport { useCollectionView } from '../collection-view/collection-view-context'\n\n/**\n * The view selector of the collection table (EC-169) — a segmented control that\n * switches between the built-in \"All documents\" default and the project's\n * code-defined views (EC-246b: views are config-as-code, so this only *picks* a\n * lens; it never creates, edits, or deletes one at runtime). Renders nothing\n * when the default view is the only one — no lonely single-tab chrome. Shares\n * the segmented-control language of the locale switcher for a consistent header.\n *\n * AD-19: reads the named-views capability off the portable {@link useCollectionView}\n * source, so a rail without config-declared views simply shows no selector.\n */\nexport function ViewTabs() {\n const source = useCollectionView()\n const views = source.views?.list() ?? []\n\n // A single (default) view needs no selector — the breadcrumb names the collection.\n if (views.length <= 1) return null\n\n const activeId = source.views?.activeId()\n const active = views.find((view) => view.id === activeId) ?? views[0]!\n\n return (\n <SegmentedControl\n testId=\"view-bar\"\n items={views.map((view) => ({\n key: view.id,\n // EC-343: a config view's `name` may be a LocalizedString — resolve it against\n // the active UI locale at the render site, exactly like `form.label` (fieldLabel).\n label: localizedLabel(view.name, view.id),\n active: view.id === active.id,\n onClick: () => source.views?.setActive(view.id),\n testId: `view-chip-${view.id}`,\n }))}\n />\n )\n}\n\n/**\n * Display options for the collection table (EC-246a) — one far-right control,\n * aligned with where per-row actions live, folding together how the list is\n * *shown*: the page hierarchy layout (flat vs tree, for hierarchical collections)\n * and visible/ordered columns. Column order is a property of all columns (visible\n * or not); the first visible column is the title/link and can't be hidden.\n */\nexport function DisplayMenu({\n collection,\n hierarchical,\n treeMode,\n onToggleTree,\n}: {\n collection: CollectionDef\n hierarchical: boolean\n treeMode: boolean\n onToggleTree: (tree: boolean) => void\n}) {\n const source = useCollectionView()\n const state = source.viewState()\n const columns = resolveColumns(collection, state)\n const titleField = columns.find((column) => column.visible)?.field\n\n return (\n <DropdownMenu>\n <DropdownMenuTrigger asChild>\n <Button\n variant=\"outline\"\n size=\"icon-sm\"\n aria-label={translate('cms.list.display.ariaLabel')}\n title={translate('cms.list.display.title')}\n data-testid=\"display-menu\"\n >\n <SlidersHorizontal />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\" className=\"w-64\">\n {hierarchical ? (\n <>\n <DropdownMenuLabel>{translate('cms.list.display.layout')}</DropdownMenuLabel>\n <LayoutOption\n label={translate('cms.list.display.flatList')}\n icon={<List />}\n active={!treeMode}\n onSelect={() => onToggleTree(false)}\n />\n <LayoutOption\n label={translate('cms.list.display.pageHierarchy')}\n icon={<ListTree />}\n active={treeMode}\n onSelect={() => onToggleTree(true)}\n />\n <DropdownMenuSeparator />\n </>\n ) : null}\n <DropdownMenuLabel>{translate('cms.list.display.columns')}</DropdownMenuLabel>\n {columns.map((column, index) => {\n const field = collection.fields.find((f) => f.name === column.field)\n if (!field) return null\n const isTitle = column.field === titleField\n return (\n <DropdownMenuItem\n key={column.field}\n onSelect={(event) => event.preventDefault()}\n data-testid={`column-row-${column.field}`}\n >\n <input\n type=\"checkbox\"\n className=\"size-3.5 accent-primary\"\n checked={column.visible}\n disabled={isTitle}\n onChange={() =>\n source.setViewState((prev) => toggleColumn(collection, prev, column.field))\n }\n aria-label={translate('cms.list.display.toggleColumn', { field: fieldLabel(field) })}\n data-testid={`column-toggle-${column.field}`}\n />\n <Text as=\"span\" size=\"sm\" className=\"min-w-0 flex-1 truncate\">\n {fieldLabel(field)}\n {isTitle ? (\n <Text as=\"span\" size=\"xs\" tone=\"subtle\">\n {' '}\n {translate('cms.list.display.titleTag')}\n </Text>\n ) : null}\n </Text>\n <Row gap=\"1\">\n <ColumnMoveButton\n label={translate('cms.list.display.moveColumnUp', { field: fieldLabel(field) })}\n icon={<ArrowUp />}\n disabled={index <= 0}\n onMove={() =>\n source.setViewState((prev) => moveColumn(collection, prev, column.field, -1))\n }\n />\n <ColumnMoveButton\n label={translate('cms.list.display.moveColumnDown', { field: fieldLabel(field) })}\n icon={<ArrowDown />}\n disabled={index >= columns.length - 1}\n onMove={() =>\n source.setViewState((prev) => moveColumn(collection, prev, column.field, 1))\n }\n />\n </Row>\n </DropdownMenuItem>\n )\n })}\n </DropdownMenuContent>\n </DropdownMenu>\n )\n}\n\n/** One layout choice (flat vs tree) — a checkmark marks the active mode. */\nfunction LayoutOption({\n label,\n icon,\n active,\n onSelect,\n}: {\n label: string\n icon: ReactNode\n active: boolean\n onSelect: () => void\n}) {\n return (\n <DropdownMenuItem\n data-testid={`layout-${active ? 'active' : 'option'}`}\n onSelect={(event) => {\n event.preventDefault()\n onSelect()\n }}\n >\n {icon}\n <Text as=\"span\" size=\"sm\" className=\"min-w-0 flex-1 truncate\">\n {label}\n </Text>\n {active ? <Check className=\"size-3.5 text-primary\" /> : null}\n </DropdownMenuItem>\n )\n}\n\nfunction ColumnMoveButton({\n label,\n icon,\n disabled,\n onMove,\n}: {\n label: string\n icon: ReactNode\n disabled: boolean\n onMove: () => void\n}) {\n return (\n <Button\n variant=\"ghost\"\n size=\"icon-sm\"\n className=\"size-5 [&_svg]:size-3\"\n aria-label={label}\n disabled={disabled}\n onClick={(event) => {\n event.preventDefault()\n event.stopPropagation()\n onMove()\n }}\n >\n {icon}\n </Button>\n )\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import type { CmsDocument, CollectionDef, FieldDef, LocaleConfig } from '@elytracms/core/cms-core';
|
|
2
|
+
import type { CmsDocument, CollectionDef, FieldDef, LocaleConfig, LocalizedString } from '@elytracms/core/cms-core';
|
|
3
3
|
import type { FilterOperator, FilterScalar } from '@elytracms/core/content';
|
|
4
4
|
/**
|
|
5
5
|
* The pure table-view model for the CMS collection table (EC-169).
|
|
@@ -152,7 +152,8 @@ export declare function defaultViewState(collection: CollectionDef): TableViewSt
|
|
|
152
152
|
*/
|
|
153
153
|
export declare const configViewSchema: z.ZodObject<{
|
|
154
154
|
id: z.ZodOptional<z.ZodString>;
|
|
155
|
-
name: z.ZodString
|
|
155
|
+
name: z.ZodUnion<readonly [z.ZodString, z.ZodRecord<z.ZodString, z.ZodString>]>;
|
|
156
|
+
default: z.ZodOptional<z.ZodBoolean>;
|
|
156
157
|
filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
157
158
|
field: z.ZodString;
|
|
158
159
|
op: z.ZodEnum<{
|
|
@@ -176,11 +177,16 @@ export declare const configViewSchema: z.ZodObject<{
|
|
|
176
177
|
hidden: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
177
178
|
}, z.core.$strip>;
|
|
178
179
|
export type ConfigView = z.infer<typeof configViewSchema>;
|
|
179
|
-
/**
|
|
180
|
+
/**
|
|
181
|
+
* A resolved view: identity + the table state it restores (matches `SavedView`).
|
|
182
|
+
* `name` stays a {@link LocalizedString} — resolved at the render site (EC-343), like
|
|
183
|
+
* `form.label`. `default` marks the initial-view seed (see {@link defaultConfigViewId}).
|
|
184
|
+
*/
|
|
180
185
|
export interface ResolvedView {
|
|
181
186
|
id: string;
|
|
182
|
-
name:
|
|
187
|
+
name: LocalizedString;
|
|
183
188
|
state: TableViewState;
|
|
189
|
+
default?: boolean;
|
|
184
190
|
}
|
|
185
191
|
/**
|
|
186
192
|
* Resolve a collection's config-declared `views` into full {@link ResolvedView}s
|
|
@@ -191,6 +197,29 @@ export interface ResolvedView {
|
|
|
191
197
|
* code — the runtime never mutates them.
|
|
192
198
|
*/
|
|
193
199
|
export declare function configViewsFor(collection: CollectionDef): ResolvedView[];
|
|
200
|
+
/**
|
|
201
|
+
* The id of the config view flagged `default: true` (EC-343) — the seed for a
|
|
202
|
+
* collection's INITIAL active view. When several are flagged (a misconfiguration,
|
|
203
|
+
* reported by {@link configViewIssues}) the FIRST in declaration order wins
|
|
204
|
+
* deterministically; when none is flagged the caller falls back to the built-in
|
|
205
|
+
* "All" lens. `undefined` when the collection declares no default view.
|
|
206
|
+
*/
|
|
207
|
+
export declare function defaultConfigViewId(collection: CollectionDef): string | undefined;
|
|
208
|
+
/** A config-level problem with a collection's declared views (EC-343). */
|
|
209
|
+
export interface ConfigViewIssue {
|
|
210
|
+
code: 'duplicate-default';
|
|
211
|
+
message: string;
|
|
212
|
+
/** The offending view ids (all views flagged `default`, in declaration order). */
|
|
213
|
+
viewIds: string[];
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Validate a collection's config-declared views (EC-343): at most one may set
|
|
217
|
+
* `default: true`. A duplicate is returned as an explicit, structured issue —
|
|
218
|
+
* never silently swallowed — so the studio can surface it (the first default still
|
|
219
|
+
* wins deterministically for seeding, per {@link defaultConfigViewId}). Pure and
|
|
220
|
+
* schema-only; the DOM-free counterpart of the "failures are first-class" contract.
|
|
221
|
+
*/
|
|
222
|
+
export declare function configViewIssues(collection: CollectionDef): ConfigViewIssue[];
|
|
194
223
|
/** Deep-cloned canonical form (stable key order via the Zod shape). */
|
|
195
224
|
export declare function normalizeViewState(state: TableViewState): TableViewState;
|
|
196
225
|
/** Structural equality on normalized states — drives the "unsaved changes" affordance. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { documentDefaultLocale, resolveField, titleFieldOf } from '@elytracms/core/cms-core';
|
|
2
|
+
import { documentDefaultLocale, localizedStringSchema, resolveField, resolveLabel, titleFieldOf, } from '@elytracms/core/cms-core';
|
|
3
3
|
import { localizedLabel } from '@elytracms/studio/lib/i18n';
|
|
4
4
|
import { FILTER_OPERATORS, compareListEntries, filterScalarOf, filterableFields, matchesCondition, validateWhere, } from '@elytracms/core/content';
|
|
5
5
|
/**
|
|
@@ -237,18 +237,27 @@ export const ALL_VIEW_ID = 'all';
|
|
|
237
237
|
* and any named view may list them in its `columns`; they're just off by default.
|
|
238
238
|
*/
|
|
239
239
|
const NON_DEFAULT_COLUMN_TYPES = new Set(['blocks', 'richText', 'object']);
|
|
240
|
-
/**
|
|
241
|
-
|
|
242
|
-
|
|
240
|
+
/**
|
|
241
|
+
* Field names OFF the built-in "All" lens by default: the composite editing surfaces
|
|
242
|
+
* (blocks/richText/object) — always noise in a scalar list — PLUS any scalar the
|
|
243
|
+
* schema opts out with `form.column: false` (EC-343). Both only affect the default
|
|
244
|
+
* columns: the field stays in the picker one toggle away, its form and filterability
|
|
245
|
+
* are untouched, and a named view's explicit `columns` list ignores this entirely.
|
|
246
|
+
*/
|
|
247
|
+
function defaultHiddenColumns(collection) {
|
|
248
|
+
return collection.fields
|
|
249
|
+
.filter((f) => NON_DEFAULT_COLUMN_TYPES.has(f.type) || f.form?.column === false)
|
|
250
|
+
.map((f) => f.name);
|
|
243
251
|
}
|
|
244
252
|
export function defaultViewState(collection) {
|
|
245
253
|
return {
|
|
246
254
|
filters: [],
|
|
247
255
|
sort: null,
|
|
248
|
-
// Every field keeps a slot (order + picker), but the composite surfaces
|
|
249
|
-
// hidden so the default lens is the
|
|
256
|
+
// Every field keeps a slot (order + picker), but the composite surfaces and any
|
|
257
|
+
// `form.column: false` scalars start hidden so the default lens is the
|
|
258
|
+
// collection's chosen scalar columns (EC-246b / EC-343).
|
|
250
259
|
columns: orderedColumnNames(collection),
|
|
251
|
-
hidden:
|
|
260
|
+
hidden: defaultHiddenColumns(collection),
|
|
252
261
|
};
|
|
253
262
|
}
|
|
254
263
|
/**
|
|
@@ -261,16 +270,32 @@ export function defaultViewState(collection) {
|
|
|
261
270
|
export const configViewSchema = z.object({
|
|
262
271
|
/** Optional stable id; defaults to a slug of `name`. */
|
|
263
272
|
id: z.string().min(1).optional(),
|
|
264
|
-
|
|
273
|
+
/**
|
|
274
|
+
* View label; localizable (EC-343): a plain string or a `{ locale }` map, resolved
|
|
275
|
+
* at the render site via the same `resolveLabel` path as `form.label` (EC-241).
|
|
276
|
+
*/
|
|
277
|
+
name: localizedStringSchema,
|
|
278
|
+
/**
|
|
279
|
+
* When true this view seeds the collection's INITIAL active view (EC-343) — the
|
|
280
|
+
* curated lens an editor lands on before picking one. At most one per collection;
|
|
281
|
+
* a duplicate is a visible validation issue ({@link configViewIssues}), never
|
|
282
|
+
* silent. The built-in "All" lens stays available and stays the fallback.
|
|
283
|
+
*/
|
|
284
|
+
default: z.boolean().optional(),
|
|
265
285
|
filters: z.array(filterClauseSchema).optional(),
|
|
266
286
|
sort: viewSortSchema.nullable().optional(),
|
|
267
287
|
/** Column order; when omitted, the view inherits the collection's default columns. */
|
|
268
288
|
columns: z.array(z.string().min(1)).optional(),
|
|
269
289
|
hidden: z.array(z.string().min(1)).optional(),
|
|
270
290
|
});
|
|
271
|
-
/**
|
|
291
|
+
/**
|
|
292
|
+
* Slug used to derive a config view's stable id from its name. A localized name
|
|
293
|
+
* (EC-343) slugs its DEFAULT-locale text so the id is stable across the active UI
|
|
294
|
+
* locale (an id must not shift when a German editor loads the same config).
|
|
295
|
+
*/
|
|
272
296
|
function configViewId(name, index) {
|
|
273
|
-
const
|
|
297
|
+
const text = resolveLabel(name) ?? '';
|
|
298
|
+
const slug = text
|
|
274
299
|
.toLowerCase()
|
|
275
300
|
.replace(/[^a-z0-9]+/g, '-')
|
|
276
301
|
.replace(/^-+|-+$/g, '');
|
|
@@ -303,6 +328,7 @@ export function configViewsFor(collection) {
|
|
|
303
328
|
resolved.push({
|
|
304
329
|
id,
|
|
305
330
|
name: view.name,
|
|
331
|
+
...(view.default ? { default: true } : {}),
|
|
306
332
|
state: normalizeViewState({
|
|
307
333
|
filters: view.filters ?? [],
|
|
308
334
|
sort: view.sort ?? null,
|
|
@@ -313,6 +339,36 @@ export function configViewsFor(collection) {
|
|
|
313
339
|
});
|
|
314
340
|
return resolved;
|
|
315
341
|
}
|
|
342
|
+
/**
|
|
343
|
+
* The id of the config view flagged `default: true` (EC-343) — the seed for a
|
|
344
|
+
* collection's INITIAL active view. When several are flagged (a misconfiguration,
|
|
345
|
+
* reported by {@link configViewIssues}) the FIRST in declaration order wins
|
|
346
|
+
* deterministically; when none is flagged the caller falls back to the built-in
|
|
347
|
+
* "All" lens. `undefined` when the collection declares no default view.
|
|
348
|
+
*/
|
|
349
|
+
export function defaultConfigViewId(collection) {
|
|
350
|
+
return configViewsFor(collection).find((view) => view.default)?.id;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Validate a collection's config-declared views (EC-343): at most one may set
|
|
354
|
+
* `default: true`. A duplicate is returned as an explicit, structured issue —
|
|
355
|
+
* never silently swallowed — so the studio can surface it (the first default still
|
|
356
|
+
* wins deterministically for seeding, per {@link defaultConfigViewId}). Pure and
|
|
357
|
+
* schema-only; the DOM-free counterpart of the "failures are first-class" contract.
|
|
358
|
+
*/
|
|
359
|
+
export function configViewIssues(collection) {
|
|
360
|
+
const defaults = configViewsFor(collection).filter((view) => view.default);
|
|
361
|
+
if (defaults.length <= 1)
|
|
362
|
+
return [];
|
|
363
|
+
const viewIds = defaults.map((view) => view.id);
|
|
364
|
+
return [
|
|
365
|
+
{
|
|
366
|
+
code: 'duplicate-default',
|
|
367
|
+
message: `Collection "${collection.id}" declares ${defaults.length} default views (${viewIds.join(', ')}); at most one view may set \`default: true\`. Seeding "${viewIds[0]}".`,
|
|
368
|
+
viewIds,
|
|
369
|
+
},
|
|
370
|
+
];
|
|
371
|
+
}
|
|
316
372
|
/**
|
|
317
373
|
* The default column order: the schema's title field first (it becomes the
|
|
318
374
|
* default title/link column — EC-213 drops the separate primary-column
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"view-model.js","sourceRoot":"","sources":["../../../src/lib/cms-views/view-model.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAA;AAC5F,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAA;AAE3D,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,aAAa,GACd,MAAM,yBAAyB,CAAA;AAShC;;;;;;;;;;;;;;;GAeG;AAEH,iFAAiF;AAEjF,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAA;AAEhF,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC;IACzC,6EAA6E;IAC7E,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC;IACxB,EAAE,EAAE,CAAC,C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B,KAAqB,EACrB,KAAa;IAEb,MAAM,IAAI,GAAG,iBAAiB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAA;IACjD,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QACxC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,KAAK,CAAC;QAC9C,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAA;IAC3B,OAAO,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,CAAA;AAC5B,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,UAAU,CACxB,UAAyB,EACzB,KAAqB,EACrB,KAAa,EACb,KAAa;IAEb,MAAM,IAAI,GAAG,iBAAiB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAA;IACjD,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;IACxC,MAAM,EAAE,GAAG,IAAI,GAAG,KAAK,CAAA;IACvB,IAAI,IAAI,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,EAAE,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM;QAAE,OAAO,KAAK,CAAA;IACjE,MAAM,OAAO,GAAG,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAA;IACjC,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;IACvB,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,EAAE,KAAK,CAAC,CAAA;IAC5B,OAAO,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,CAAA;AAC7B,CAAC","sourcesContent":["import { z } from 'zod'\nimport { documentDefaultLocale, resolveField, titleFieldOf } from '@elytracms/core/cms-core'\nimport { localizedLabel } from '@elytracms/studio/lib/i18n'\nimport type { CmsDocument, CollectionDef, FieldDef, LocaleConfig } from '@elytracms/core/cms-core'\nimport {\n FILTER_OPERATORS,\n compareListEntries,\n filterScalarOf,\n filterableFields,\n matchesCondition,\n validateWhere,\n} from '@elytracms/core/content'\nimport type {\n FilterCondition,\n FilterOperator,\n FilterScalar,\n NormalizedCondition,\n WhereInput,\n} from '@elytracms/core/content'\n\n/**\n * The pure table-view model for the CMS collection table (EC-169).\n *\n * A view bundles three things: filters in the closed AD-3 vocabulary\n * (`eq`/`in`/`lt`/`lte`/`gt`/`gte`, AND-only — exactly `@elytracms/core/content`'s\n * query model, evaluated with the same matching/ordering primitives), a sort\n * (field + direction), and the visible/ordered columns. Everything here is\n * plain data + functions so filtering, dirtiness, and column edits are\n * testable without a DOM.\n *\n * Filters are offered ONLY on fields the schema declares `filterable: true`\n * (EC-143), plus one built-in option: the document's publication state. The\n * state is document metadata, not a schema field — it powers the\n * \"show me drafts → bulk publish\" working set and still speaks only the\n * closed vocabulary (`eq`/`in`).\n */\n\n// --- Schemas (single source of truth — persisted view records reuse these) ----\n\nexport const filterScalarSchema = z.union([z.string(), z.number(), z.boolean()])\n\nexport const filterClauseSchema = z.object({\n /** A schema field name, or {@link STATE_FIELD} for the publication state. */\n field: z.string().min(1),\n op: z.enum(FILTER_OPERATORS),\n /** `in` carries an array of scalars; every other operator one scalar. */\n value: z.union([filterScalarSchema, z.array(filterScalarSchema)]),\n})\nexport type FilterClause = z.infer<typeof filterClauseSchema>\n\nexport const viewSortSchema = z.object({\n field: z.string().min(1),\n dir: z.enum(['asc', 'desc']),\n})\nexport type ViewSort = z.infer<typeof viewSortSchema>\n\nexport const tableViewStateSchema = z.object({\n /** AND-only list of conditions (no OR, no nesting — vision AD-3). */\n filters: z.array(filterClauseSchema),\n sort: viewSortSchema.nullable(),\n /**\n * The canonical column order (field names) — EVERY column, visible or not\n * (EC-213). Order is independent of visibility: hiding then re-showing a\n * column keeps its place. Schema fields absent here resolve in at the end\n * (see {@link resolveColumns}).\n */\n columns: z.array(z.string().min(1)),\n /**\n * The subset of {@link TableViewState.columns} that is hidden. Defaults to\n * `[]` so views persisted before EC-213 (no `hidden` key) load unchanged.\n */\n hidden: z.array(z.string().min(1)).default([]),\n})\nexport type TableViewState = z.infer<typeof tableViewStateSchema>\n\n// --- The built-in publication-state filter column ------------------------------\n\n/**\n * Sentinel field key for the publication state. `$`-prefixed so it can never\n * collide with a schema field name (`fieldDefSchema` names are identifiers).\n */\nexport const STATE_FIELD = '$state'\n\nconst STATE_VALUES = ['draft', 'published'] as const\n\n/** One field the filter builder may offer. */\nexport interface FilterableFieldOption {\n /** Clause field key: a schema field name, or {@link STATE_FIELD}. */\n field: string\n label: string\n /** The schema field def, or `null` for the built-in publication state. */\n def: FieldDef | null\n}\n\nexport const STATE_OPTION: FilterableFieldOption = {\n field: STATE_FIELD,\n label: 'State',\n def: null,\n}\n\n/**\n * The closed list of fields the filter builder offers: exactly the schema's\n * `filterable: true` fields (EC-143) plus the publication state. Nothing else\n * is ever offered — the UI builds queries, it does not invent a language.\n */\nexport function filterableFieldOptions(collection: CollectionDef): FilterableFieldOption[] {\n const schemaOptions = filterableFields(collection).map((field) => ({\n field: field.name,\n label: localizedLabel(field.form?.label, field.name),\n def: field,\n }))\n return [...schemaOptions, STATE_OPTION]\n}\n\nexport function filterOptionFor(\n collection: CollectionDef,\n field: string,\n): FilterableFieldOption | undefined {\n return filterableFieldOptions(collection).find((option) => option.field === field)\n}\n\n// --- Operators per field type ---------------------------------------------------\n\n/** Display order + labels for the closed vocabulary. */\nexport const OPERATOR_LABELS: Record<FilterOperator, string> = {\n eq: 'equals',\n in: 'is one of',\n lt: 'less than',\n lte: 'at most',\n gt: 'greater than',\n gte: 'at least',\n}\n\nconst ORDERED_OPERATORS: readonly FilterOperator[] = ['eq', 'in', 'lt', 'lte', 'gt', 'gte']\n\n/**\n * The vocabulary subset that makes sense for a field's type. Always a subset\n * of the closed `FILTER_OPERATORS` — never an extension.\n */\nexport function operatorsFor(option: FilterableFieldOption): FilterOperator[] {\n if (option.def === null) return ['eq', 'in'] // publication state\n switch (option.def.type) {\n case 'boolean':\n return ['eq']\n case 'select':\n case 'relation':\n case 'asset':\n return ['eq', 'in']\n default:\n return [...ORDERED_OPERATORS]\n }\n}\n\n/** A sensible starting clause when a field is added to the builder. */\nexport function defaultClause(option: FilterableFieldOption): FilterClause {\n if (option.def === null) return { field: STATE_FIELD, op: 'eq', value: 'published' }\n switch (option.def.type) {\n case 'boolean':\n return { field: option.field, op: 'eq', value: true }\n case 'number':\n return { field: option.field, op: 'eq', value: 0 }\n case 'select':\n return { field: option.field, op: 'eq', value: option.def.options[0]?.value ?? '' }\n default:\n return { field: option.field, op: 'eq', value: '' }\n }\n}\n\n// --- Text ⇄ scalar coercion (the value inputs of the builder) -------------------\n\nconst DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/\n\n/** Coerce one text input into the scalar a clause compares against. */\nexport function scalarFromText(\n option: FilterableFieldOption | undefined,\n raw: string,\n): FilterScalar {\n const type = option?.def?.type\n if (type === 'number') {\n const trimmed = raw.trim()\n if (trimmed === '') return raw // an emptied input must not become eq 0\n const parsed = Number(trimmed)\n return Number.isNaN(parsed) ? raw : parsed\n }\n if (type === 'boolean') return raw === 'true'\n // Stored dates are full ISO strings; a date-input value compares correctly\n // once expanded to midnight UTC (ISO strings order by code units).\n if (type === 'date' && DATE_ONLY.test(raw)) return `${raw}T00:00:00.000Z`\n return raw\n}\n\n/** Parse a comma-separated list for the `in` operator. */\nexport function scalarListFromText(\n option: FilterableFieldOption | undefined,\n raw: string,\n): FilterScalar[] {\n return raw\n .split(',')\n .map((part) => part.trim())\n .filter((part) => part !== '')\n .map((part) => scalarFromText(option, part))\n}\n\nexport function scalarListToText(value: FilterScalar | FilterScalar[]): string {\n const list = Array.isArray(value) ? value : [value]\n return list.map(String).join(', ')\n}\n\n// --- Clause validation -----------------------------------------------------------\n\n/** A structured problem with one clause (by index in the filter list). */\nexport interface ClauseIssue {\n index: number\n message: string\n}\n\n/**\n * Validate clauses against the collection schema. Schema-field clauses run\n * through the canonical `validateWhere` (EC-143: `filterable` enforcement +\n * operator/value shape); state clauses check the `eq`/`in` subset and the\n * draft/published value set. Invalid clauses (e.g. a persisted view whose\n * field is no longer filterable) are reported — never silently applied.\n */\nexport function validateClauses(\n collection: CollectionDef,\n clauses: readonly FilterClause[],\n): ClauseIssue[] {\n const issues: ClauseIssue[] = []\n clauses.forEach((clause, index) => {\n if (clause.field === STATE_FIELD) {\n if (clause.op !== 'eq' && clause.op !== 'in') {\n issues.push({ index, message: 'State filters support only \"eq\" and \"in\".' })\n return\n }\n const values = Array.isArray(clause.value) ? clause.value : [clause.value]\n if (!values.every((value) => (STATE_VALUES as readonly unknown[]).includes(value))) {\n issues.push({ index, message: 'State must be \"draft\" or \"published\".' })\n }\n return\n }\n const where: WhereInput = {\n [clause.field]: { [clause.op]: clause.value } as FilterCondition,\n }\n const errors = validateWhere(collection, where)\n if (errors.length > 0) issues.push({ index, message: errors[0]!.message })\n })\n return issues\n}\n\n// --- Matching & sorting (delegates to @elytracms/core/content's primitives) -------------\n\n/**\n * Published-ness source for the `$state` pseudo-field (EC-224): the version\n * POINTER, supplied by the caller as `cms.isPublished`. Defaults to \"nothing\n * published\" — a bare row carries no publish signal now that the flat `state`\n * field is gone, so the table (which knows the pointer) passes the real\n * predicate; fixtures/tests that don't surface `$state` get the safe default.\n */\nexport type IsPublished = (doc: CmsDocument) => boolean\nconst defaultIsPublished: IsPublished = () => false\n\n/** The scalar a document exposes for a clause/sort field, locale-resolved. */\nfunction scalarOf(\n collection: CollectionDef,\n doc: CmsDocument,\n field: string,\n localeConfig: LocaleConfig,\n isPublished: IsPublished,\n): FilterScalar | null {\n if (field === STATE_FIELD) return isPublished(doc) ? 'published' : 'draft'\n if (!collection.fields.some((f) => f.name === field)) return null\n const locale = documentDefaultLocale(doc, localeConfig)\n return filterScalarOf(resolveField(collection, doc, field, locale, localeConfig).value)\n}\n\n/** Does a document satisfy one clause? Same semantics as the content accessors. */\nexport function clauseMatches(\n collection: CollectionDef,\n doc: CmsDocument,\n localeConfig: LocaleConfig,\n clause: FilterClause,\n isPublished: IsPublished = defaultIsPublished,\n): boolean {\n const value = scalarOf(collection, doc, clause.field, localeConfig, isPublished)\n const condition = { [clause.op]: clause.value } as NormalizedCondition\n return matchesCondition(value, condition)\n}\n\n/**\n * Sort documents by one column in the canonical deterministic order\n * (`compareListEntries`: typed value order, id-ascending tiebreak). Unlike the\n * content accessors, the *table* may sort any rendered column — sorting is a\n * presentation concern here; the `filterable` flag governs filters.\n */\nexport function sortViewDocuments(\n collection: CollectionDef,\n docs: readonly CmsDocument[],\n localeConfig: LocaleConfig,\n sort: ViewSort | null,\n isPublished: IsPublished = defaultIsPublished,\n): CmsDocument[] {\n if (sort === null) return [...docs]\n const positions = new Map(\n docs.map((doc) => [doc.id, scalarOf(collection, doc, sort.field, localeConfig, isPublished)]),\n )\n return [...docs].sort((a, b) =>\n compareListEntries(\n { id: a.id, sortValue: positions.get(a.id) ?? null },\n { id: b.id, sortValue: positions.get(b.id) ?? null },\n sort.dir,\n ),\n )\n}\n\n/** The filtered + sorted documents of a view, plus any clause issues. */\nexport interface AppliedViewState {\n docs: CmsDocument[]\n /** Clauses that failed validation — reported AND excluded from matching. */\n issues: ClauseIssue[]\n}\n\n/**\n * Apply a view state to a document list: validate clauses, AND-match the valid\n * ones, sort. Invalid clauses never filter silently — they come back as\n * issues for the UI to surface.\n */\nexport function applyViewState(\n collection: CollectionDef,\n docs: readonly CmsDocument[],\n localeConfig: LocaleConfig,\n state: TableViewState,\n isPublished: IsPublished = defaultIsPublished,\n): AppliedViewState {\n const issues = validateClauses(collection, state.filters)\n const invalid = new Set(issues.map((issue) => issue.index))\n const active = state.filters.filter((_, index) => !invalid.has(index))\n const matched = docs.filter((doc) =>\n active.every((clause) => clauseMatches(collection, doc, localeConfig, clause, isPublished)),\n )\n return {\n docs: sortViewDocuments(collection, matched, localeConfig, state.sort, isPublished),\n issues,\n }\n}\n\n// --- View state construction, equality, columns ----------------------------------\n\n/** The id of the unnamed built-in \"All documents\" view. */\nexport const ALL_VIEW_ID = 'all'\n\n/** The default (unnamed) view: no filters, no sort, every field visible. */\n/**\n * Field types kept OFF the default table columns (EC-246b): the composite editing\n * surfaces — a blocks canvas, rich text, a structured object/repeater — read as\n * noise in a scalar list. `filterable` no longer forces (or governs) a column; the\n * default lens is \"all scalars\". These stay in the column picker one toggle away,\n * and any named view may list them in its `columns`; they're just off by default.\n */\nconst NON_DEFAULT_COLUMN_TYPES = new Set<FieldDef['type']>(['blocks', 'richText', 'object'])\n\n/** The collection's composite (non-scalar) field names — hidden in the default view. */\nfunction nonScalarColumns(collection: CollectionDef): string[] {\n return collection.fields.filter((f) => NON_DEFAULT_COLUMN_TYPES.has(f.type)).map((f) => f.name)\n}\n\nexport function defaultViewState(collection: CollectionDef): TableViewState {\n return {\n filters: [],\n sort: null,\n // Every field keeps a slot (order + picker), but the composite surfaces start\n // hidden so the default lens is the collection's scalars (EC-246b).\n columns: orderedColumnNames(collection),\n hidden: nonScalarColumns(collection),\n }\n}\n\n/**\n * A config-declared view (EC-246b) — the flat authoring shape a collection\n * declares in `cms/` config: `{ name, filters?, sort?, columns?, hidden? }`.\n * Filters/sort/columns sit at the top level (no nested `state` wrapper). The\n * studio validates + interprets these; `cms-core` stores them opaquely (it\n * can't reference the filter vocabulary without a layering cycle).\n */\nexport const configViewSchema = z.object({\n /** Optional stable id; defaults to a slug of `name`. */\n id: z.string().min(1).optional(),\n name: z.string().min(1),\n filters: z.array(filterClauseSchema).optional(),\n sort: viewSortSchema.nullable().optional(),\n /** Column order; when omitted, the view inherits the collection's default columns. */\n columns: z.array(z.string().min(1)).optional(),\n hidden: z.array(z.string().min(1)).optional(),\n})\nexport type ConfigView = z.infer<typeof configViewSchema>\n\n/** A resolved view: identity + the table state it restores (matches `SavedView`). */\nexport interface ResolvedView {\n id: string\n name: string\n state: TableViewState\n}\n\n/** Slug used to derive a config view's stable id from its name. */\nfunction configViewId(name: string, index: number): string {\n const slug = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n return `config:${slug || index}`\n}\n\n/**\n * Resolve a collection's config-declared `views` into full {@link ResolvedView}s\n * (EC-246b). Each is validated with {@link configViewSchema}; malformed entries\n * and duplicate ids are dropped (defensive). Columns fall back to the collection\n * default when a view doesn't pin them, so a filter-only view still renders every\n * column. Config views are shared and change only in\n * code — the runtime never mutates them.\n */\nexport function configViewsFor(collection: CollectionDef): ResolvedView[] {\n const declared = collection.views\n if (!Array.isArray(declared)) return []\n const base = defaultViewState(collection)\n const seen = new Set<string>()\n const resolved: ResolvedView[] = []\n declared.forEach((raw, index) => {\n const parsed = configViewSchema.safeParse(raw)\n if (!parsed.success) return\n const view = parsed.data\n const id = view.id ?? configViewId(view.name, index)\n if (seen.has(id)) return\n seen.add(id)\n resolved.push({\n id,\n name: view.name,\n state: normalizeViewState({\n filters: view.filters ?? [],\n sort: view.sort ?? null,\n columns: view.columns && view.columns.length > 0 ? view.columns : base.columns,\n hidden: view.hidden ?? [],\n }),\n })\n })\n return resolved\n}\n\n/**\n * The default column order: the schema's title field first (it becomes the\n * default title/link column — EC-213 drops the separate primary-column\n * selector, treating the first visible column as the title), then the\n * remaining fields in schema order.\n */\nfunction orderedColumnNames(collection: CollectionDef): string[] {\n const names = collection.fields.map((field) => field.name)\n const title = titleFieldOf(collection)?.name\n if (title === undefined || !names.includes(title)) return names\n return [title, ...names.filter((name) => name !== title)]\n}\n\n/** Deep-cloned canonical form (stable key order via the Zod shape). */\nexport function normalizeViewState(state: TableViewState): TableViewState {\n return tableViewStateSchema.parse(state)\n}\n\n/** Structural equality on normalized states — drives the \"unsaved changes\" affordance. */\nexport function viewStatesEqual(a: TableViewState, b: TableViewState): boolean {\n return JSON.stringify(normalizeViewState(a)) === JSON.stringify(normalizeViewState(b))\n}\n\n/** One column of a view resolved against the current schema (EC-213). */\nexport interface ResolvedColumn {\n /** The schema field name. */\n field: string\n /** Whether the column renders (`false` ⇒ in {@link TableViewState.hidden}). */\n visible: boolean\n}\n\n/**\n * Resolve a view's columns against the live schema (EC-213): every schema\n * field exactly once, in the view's saved order, with any fields the view\n * predates appended (visible) and any fields no longer in the schema dropped.\n * This is the single source of truth for \"which columns, in what order, shown\n * or hidden\" — order is preserved across hide/show because visibility lives in\n * `hidden`, never in the order.\n */\nexport function resolveColumns(\n collection: CollectionDef,\n state: TableViewState,\n): ResolvedColumn[] {\n const schemaNames = collection.fields.map((field) => field.name)\n const schema = new Set(schemaNames)\n const hidden = new Set(state.hidden)\n // Keep the saved order, restricted to live fields and de-duplicated (a\n // corrupted persisted state must never render one field as two columns).\n const ordered: string[] = []\n const seen = new Set<string>()\n for (const name of state.columns) {\n if (schema.has(name) && !seen.has(name)) {\n ordered.push(name)\n seen.add(name)\n }\n }\n const appended = schemaNames.filter((name) => !seen.has(name))\n return [...ordered, ...appended].map((field) => ({ field, visible: !hidden.has(field) }))\n}\n\n/** The visible columns of a view, in render order (EC-213). */\nexport function visibleColumns(collection: CollectionDef, state: TableViewState): string[] {\n return resolveColumns(collection, state)\n .filter((column) => column.visible)\n .map((column) => column.field)\n}\n\n/**\n * The title/link column — the document IDENTITY column (EC-242): the schema title\n * field, shown as the leftmost linked cell whose content is `resolveDocumentTitle`\n * (a string `titleField` or a function pattern). Always present regardless of\n * column visibility — it is the document's identity, not a toggleable data column —\n * and excluded from the data columns so the title never shows twice. Falls back to\n * the first visible column, then the first field, then `id`, when no title field\n * is resolvable (e.g. a function title with no backing `title` field).\n */\nexport function primaryColumn(collection: CollectionDef, state: TableViewState): string {\n return (\n titleFieldOf(collection)?.name ??\n visibleColumns(collection, state)[0] ??\n collection.fields[0]?.name ??\n 'id'\n )\n}\n\n/**\n * Reconcile `columns` to the full resolved order so column edits operate on a\n * complete, stable order (drops removed fields, pins appended ones), and prune\n * `hidden` to fields the live schema still has (a column removed from the schema\n * must not leave dead `hidden` cruft that trips dirty-detection / persists).\n */\nfunction withResolvedOrder(collection: CollectionDef, state: TableViewState): TableViewState {\n const columns = resolveColumns(collection, state).map((column) => column.field)\n const live = new Set(columns)\n const hidden = state.hidden.filter((name) => live.has(name))\n return { ...state, columns, hidden }\n}\n\n/**\n * The canonical, schema-resolved form of a view state — full column order with\n * `hidden` pruned to live fields (EC-213). Two states that render identically\n * share one canonical form, so dirty-detection never trips on a mere column\n * reconciliation or a stale `hidden` entry (only a real filter/sort/visibility/\n * order change counts as \"unsaved\").\n */\nexport function canonicalViewState(\n collection: CollectionDef,\n state: TableViewState,\n): TableViewState {\n return normalizeViewState(withResolvedOrder(collection, state))\n}\n\n/**\n * Toggle a column's visibility — position is preserved (EC-213): visibility\n * lives in `hidden`, the order in `columns` is untouched. Columns the saved\n * order predates are pinned into `columns` first so their place is stable.\n */\nexport function toggleColumn(\n collection: CollectionDef,\n state: TableViewState,\n field: string,\n): TableViewState {\n const base = withResolvedOrder(collection, state)\n const hidden = base.hidden.includes(field)\n ? base.hidden.filter((name) => name !== field)\n : [...base.hidden, field]\n return { ...base, hidden }\n}\n\n/** Move a column one position left (-1) or right (+1) in the full column order. */\nexport function moveColumn(\n collection: CollectionDef,\n state: TableViewState,\n field: string,\n delta: -1 | 1,\n): TableViewState {\n const base = withResolvedOrder(collection, state)\n const from = base.columns.indexOf(field)\n const to = from + delta\n if (from < 0 || to < 0 || to >= base.columns.length) return state\n const columns = [...base.columns]\n columns.splice(from, 1)\n columns.splice(to, 0, field)\n return { ...base, columns }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"view-model.js","sourceRoot":"","sources":["../../../src/lib/cms-views/view-model.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,YAAY,EACZ,YAAY,EACZ,YAAY,GACb,MAAM,0BAA0B,CAAA;AACjC,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAA;AAQ3D,OAAO,EACL,gBAAgB,EAChB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AC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;IACvB,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,EAAE,KAAK,CAAC,CAAA;IAC5B,OAAO,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,CAAA;AAC7B,CAAC","sourcesContent":["import { z } from 'zod'\nimport {\n documentDefaultLocale,\n localizedStringSchema,\n resolveField,\n resolveLabel,\n titleFieldOf,\n} from '@elytracms/core/cms-core'\nimport { localizedLabel } from '@elytracms/studio/lib/i18n'\nimport type {\n CmsDocument,\n CollectionDef,\n FieldDef,\n LocaleConfig,\n LocalizedString,\n} from '@elytracms/core/cms-core'\nimport {\n FILTER_OPERATORS,\n compareListEntries,\n filterScalarOf,\n filterableFields,\n matchesCondition,\n validateWhere,\n} from '@elytracms/core/content'\nimport type {\n FilterCondition,\n FilterOperator,\n FilterScalar,\n NormalizedCondition,\n WhereInput,\n} from '@elytracms/core/content'\n\n/**\n * The pure table-view model for the CMS collection table (EC-169).\n *\n * A view bundles three things: filters in the closed AD-3 vocabulary\n * (`eq`/`in`/`lt`/`lte`/`gt`/`gte`, AND-only — exactly `@elytracms/core/content`'s\n * query model, evaluated with the same matching/ordering primitives), a sort\n * (field + direction), and the visible/ordered columns. Everything here is\n * plain data + functions so filtering, dirtiness, and column edits are\n * testable without a DOM.\n *\n * Filters are offered ONLY on fields the schema declares `filterable: true`\n * (EC-143), plus one built-in option: the document's publication state. The\n * state is document metadata, not a schema field — it powers the\n * \"show me drafts → bulk publish\" working set and still speaks only the\n * closed vocabulary (`eq`/`in`).\n */\n\n// --- Schemas (single source of truth — persisted view records reuse these) ----\n\nexport const filterScalarSchema = z.union([z.string(), z.number(), z.boolean()])\n\nexport const filterClauseSchema = z.object({\n /** A schema field name, or {@link STATE_FIELD} for the publication state. */\n field: z.string().min(1),\n op: z.enum(FILTER_OPERATORS),\n /** `in` carries an array of scalars; every other operator one scalar. */\n value: z.union([filterScalarSchema, z.array(filterScalarSchema)]),\n})\nexport type FilterClause = z.infer<typeof filterClauseSchema>\n\nexport const viewSortSchema = z.object({\n field: z.string().min(1),\n dir: z.enum(['asc', 'desc']),\n})\nexport type ViewSort = z.infer<typeof viewSortSchema>\n\nexport const tableViewStateSchema = z.object({\n /** AND-only list of conditions (no OR, no nesting — vision AD-3). */\n filters: z.array(filterClauseSchema),\n sort: viewSortSchema.nullable(),\n /**\n * The canonical column order (field names) — EVERY column, visible or not\n * (EC-213). Order is independent of visibility: hiding then re-showing a\n * column keeps its place. Schema fields absent here resolve in at the end\n * (see {@link resolveColumns}).\n */\n columns: z.array(z.string().min(1)),\n /**\n * The subset of {@link TableViewState.columns} that is hidden. Defaults to\n * `[]` so views persisted before EC-213 (no `hidden` key) load unchanged.\n */\n hidden: z.array(z.string().min(1)).default([]),\n})\nexport type TableViewState = z.infer<typeof tableViewStateSchema>\n\n// --- The built-in publication-state filter column ------------------------------\n\n/**\n * Sentinel field key for the publication state. `$`-prefixed so it can never\n * collide with a schema field name (`fieldDefSchema` names are identifiers).\n */\nexport const STATE_FIELD = '$state'\n\nconst STATE_VALUES = ['draft', 'published'] as const\n\n/** One field the filter builder may offer. */\nexport interface FilterableFieldOption {\n /** Clause field key: a schema field name, or {@link STATE_FIELD}. */\n field: string\n label: string\n /** The schema field def, or `null` for the built-in publication state. */\n def: FieldDef | null\n}\n\nexport const STATE_OPTION: FilterableFieldOption = {\n field: STATE_FIELD,\n label: 'State',\n def: null,\n}\n\n/**\n * The closed list of fields the filter builder offers: exactly the schema's\n * `filterable: true` fields (EC-143) plus the publication state. Nothing else\n * is ever offered — the UI builds queries, it does not invent a language.\n */\nexport function filterableFieldOptions(collection: CollectionDef): FilterableFieldOption[] {\n const schemaOptions = filterableFields(collection).map((field) => ({\n field: field.name,\n label: localizedLabel(field.form?.label, field.name),\n def: field,\n }))\n return [...schemaOptions, STATE_OPTION]\n}\n\nexport function filterOptionFor(\n collection: CollectionDef,\n field: string,\n): FilterableFieldOption | undefined {\n return filterableFieldOptions(collection).find((option) => option.field === field)\n}\n\n// --- Operators per field type ---------------------------------------------------\n\n/** Display order + labels for the closed vocabulary. */\nexport const OPERATOR_LABELS: Record<FilterOperator, string> = {\n eq: 'equals',\n in: 'is one of',\n lt: 'less than',\n lte: 'at most',\n gt: 'greater than',\n gte: 'at least',\n}\n\nconst ORDERED_OPERATORS: readonly FilterOperator[] = ['eq', 'in', 'lt', 'lte', 'gt', 'gte']\n\n/**\n * The vocabulary subset that makes sense for a field's type. Always a subset\n * of the closed `FILTER_OPERATORS` — never an extension.\n */\nexport function operatorsFor(option: FilterableFieldOption): FilterOperator[] {\n if (option.def === null) return ['eq', 'in'] // publication state\n switch (option.def.type) {\n case 'boolean':\n return ['eq']\n case 'select':\n case 'relation':\n case 'asset':\n return ['eq', 'in']\n default:\n return [...ORDERED_OPERATORS]\n }\n}\n\n/** A sensible starting clause when a field is added to the builder. */\nexport function defaultClause(option: FilterableFieldOption): FilterClause {\n if (option.def === null) return { field: STATE_FIELD, op: 'eq', value: 'published' }\n switch (option.def.type) {\n case 'boolean':\n return { field: option.field, op: 'eq', value: true }\n case 'number':\n return { field: option.field, op: 'eq', value: 0 }\n case 'select':\n return { field: option.field, op: 'eq', value: option.def.options[0]?.value ?? '' }\n default:\n return { field: option.field, op: 'eq', value: '' }\n }\n}\n\n// --- Text ⇄ scalar coercion (the value inputs of the builder) -------------------\n\nconst DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/\n\n/** Coerce one text input into the scalar a clause compares against. */\nexport function scalarFromText(\n option: FilterableFieldOption | undefined,\n raw: string,\n): FilterScalar {\n const type = option?.def?.type\n if (type === 'number') {\n const trimmed = raw.trim()\n if (trimmed === '') return raw // an emptied input must not become eq 0\n const parsed = Number(trimmed)\n return Number.isNaN(parsed) ? raw : parsed\n }\n if (type === 'boolean') return raw === 'true'\n // Stored dates are full ISO strings; a date-input value compares correctly\n // once expanded to midnight UTC (ISO strings order by code units).\n if (type === 'date' && DATE_ONLY.test(raw)) return `${raw}T00:00:00.000Z`\n return raw\n}\n\n/** Parse a comma-separated list for the `in` operator. */\nexport function scalarListFromText(\n option: FilterableFieldOption | undefined,\n raw: string,\n): FilterScalar[] {\n return raw\n .split(',')\n .map((part) => part.trim())\n .filter((part) => part !== '')\n .map((part) => scalarFromText(option, part))\n}\n\nexport function scalarListToText(value: FilterScalar | FilterScalar[]): string {\n const list = Array.isArray(value) ? value : [value]\n return list.map(String).join(', ')\n}\n\n// --- Clause validation -----------------------------------------------------------\n\n/** A structured problem with one clause (by index in the filter list). */\nexport interface ClauseIssue {\n index: number\n message: string\n}\n\n/**\n * Validate clauses against the collection schema. Schema-field clauses run\n * through the canonical `validateWhere` (EC-143: `filterable` enforcement +\n * operator/value shape); state clauses check the `eq`/`in` subset and the\n * draft/published value set. Invalid clauses (e.g. a persisted view whose\n * field is no longer filterable) are reported — never silently applied.\n */\nexport function validateClauses(\n collection: CollectionDef,\n clauses: readonly FilterClause[],\n): ClauseIssue[] {\n const issues: ClauseIssue[] = []\n clauses.forEach((clause, index) => {\n if (clause.field === STATE_FIELD) {\n if (clause.op !== 'eq' && clause.op !== 'in') {\n issues.push({ index, message: 'State filters support only \"eq\" and \"in\".' })\n return\n }\n const values = Array.isArray(clause.value) ? clause.value : [clause.value]\n if (!values.every((value) => (STATE_VALUES as readonly unknown[]).includes(value))) {\n issues.push({ index, message: 'State must be \"draft\" or \"published\".' })\n }\n return\n }\n const where: WhereInput = {\n [clause.field]: { [clause.op]: clause.value } as FilterCondition,\n }\n const errors = validateWhere(collection, where)\n if (errors.length > 0) issues.push({ index, message: errors[0]!.message })\n })\n return issues\n}\n\n// --- Matching & sorting (delegates to @elytracms/core/content's primitives) -------------\n\n/**\n * Published-ness source for the `$state` pseudo-field (EC-224): the version\n * POINTER, supplied by the caller as `cms.isPublished`. Defaults to \"nothing\n * published\" — a bare row carries no publish signal now that the flat `state`\n * field is gone, so the table (which knows the pointer) passes the real\n * predicate; fixtures/tests that don't surface `$state` get the safe default.\n */\nexport type IsPublished = (doc: CmsDocument) => boolean\nconst defaultIsPublished: IsPublished = () => false\n\n/** The scalar a document exposes for a clause/sort field, locale-resolved. */\nfunction scalarOf(\n collection: CollectionDef,\n doc: CmsDocument,\n field: string,\n localeConfig: LocaleConfig,\n isPublished: IsPublished,\n): FilterScalar | null {\n if (field === STATE_FIELD) return isPublished(doc) ? 'published' : 'draft'\n if (!collection.fields.some((f) => f.name === field)) return null\n const locale = documentDefaultLocale(doc, localeConfig)\n return filterScalarOf(resolveField(collection, doc, field, locale, localeConfig).value)\n}\n\n/** Does a document satisfy one clause? Same semantics as the content accessors. */\nexport function clauseMatches(\n collection: CollectionDef,\n doc: CmsDocument,\n localeConfig: LocaleConfig,\n clause: FilterClause,\n isPublished: IsPublished = defaultIsPublished,\n): boolean {\n const value = scalarOf(collection, doc, clause.field, localeConfig, isPublished)\n const condition = { [clause.op]: clause.value } as NormalizedCondition\n return matchesCondition(value, condition)\n}\n\n/**\n * Sort documents by one column in the canonical deterministic order\n * (`compareListEntries`: typed value order, id-ascending tiebreak). Unlike the\n * content accessors, the *table* may sort any rendered column — sorting is a\n * presentation concern here; the `filterable` flag governs filters.\n */\nexport function sortViewDocuments(\n collection: CollectionDef,\n docs: readonly CmsDocument[],\n localeConfig: LocaleConfig,\n sort: ViewSort | null,\n isPublished: IsPublished = defaultIsPublished,\n): CmsDocument[] {\n if (sort === null) return [...docs]\n const positions = new Map(\n docs.map((doc) => [doc.id, scalarOf(collection, doc, sort.field, localeConfig, isPublished)]),\n )\n return [...docs].sort((a, b) =>\n compareListEntries(\n { id: a.id, sortValue: positions.get(a.id) ?? null },\n { id: b.id, sortValue: positions.get(b.id) ?? null },\n sort.dir,\n ),\n )\n}\n\n/** The filtered + sorted documents of a view, plus any clause issues. */\nexport interface AppliedViewState {\n docs: CmsDocument[]\n /** Clauses that failed validation — reported AND excluded from matching. */\n issues: ClauseIssue[]\n}\n\n/**\n * Apply a view state to a document list: validate clauses, AND-match the valid\n * ones, sort. Invalid clauses never filter silently — they come back as\n * issues for the UI to surface.\n */\nexport function applyViewState(\n collection: CollectionDef,\n docs: readonly CmsDocument[],\n localeConfig: LocaleConfig,\n state: TableViewState,\n isPublished: IsPublished = defaultIsPublished,\n): AppliedViewState {\n const issues = validateClauses(collection, state.filters)\n const invalid = new Set(issues.map((issue) => issue.index))\n const active = state.filters.filter((_, index) => !invalid.has(index))\n const matched = docs.filter((doc) =>\n active.every((clause) => clauseMatches(collection, doc, localeConfig, clause, isPublished)),\n )\n return {\n docs: sortViewDocuments(collection, matched, localeConfig, state.sort, isPublished),\n issues,\n }\n}\n\n// --- View state construction, equality, columns ----------------------------------\n\n/** The id of the unnamed built-in \"All documents\" view. */\nexport const ALL_VIEW_ID = 'all'\n\n/** The default (unnamed) view: no filters, no sort, every field visible. */\n/**\n * Field types kept OFF the default table columns (EC-246b): the composite editing\n * surfaces — a blocks canvas, rich text, a structured object/repeater — read as\n * noise in a scalar list. `filterable` no longer forces (or governs) a column; the\n * default lens is \"all scalars\". These stay in the column picker one toggle away,\n * and any named view may list them in its `columns`; they're just off by default.\n */\nconst NON_DEFAULT_COLUMN_TYPES = new Set<FieldDef['type']>(['blocks', 'richText', 'object'])\n\n/**\n * Field names OFF the built-in \"All\" lens by default: the composite editing surfaces\n * (blocks/richText/object) — always noise in a scalar list — PLUS any scalar the\n * schema opts out with `form.column: false` (EC-343). Both only affect the default\n * columns: the field stays in the picker one toggle away, its form and filterability\n * are untouched, and a named view's explicit `columns` list ignores this entirely.\n */\nfunction defaultHiddenColumns(collection: CollectionDef): string[] {\n return collection.fields\n .filter((f) => NON_DEFAULT_COLUMN_TYPES.has(f.type) || f.form?.column === false)\n .map((f) => f.name)\n}\n\nexport function defaultViewState(collection: CollectionDef): TableViewState {\n return {\n filters: [],\n sort: null,\n // Every field keeps a slot (order + picker), but the composite surfaces and any\n // `form.column: false` scalars start hidden so the default lens is the\n // collection's chosen scalar columns (EC-246b / EC-343).\n columns: orderedColumnNames(collection),\n hidden: defaultHiddenColumns(collection),\n }\n}\n\n/**\n * A config-declared view (EC-246b) — the flat authoring shape a collection\n * declares in `cms/` config: `{ name, filters?, sort?, columns?, hidden? }`.\n * Filters/sort/columns sit at the top level (no nested `state` wrapper). The\n * studio validates + interprets these; `cms-core` stores them opaquely (it\n * can't reference the filter vocabulary without a layering cycle).\n */\nexport const configViewSchema = z.object({\n /** Optional stable id; defaults to a slug of `name`. */\n id: z.string().min(1).optional(),\n /**\n * View label; localizable (EC-343): a plain string or a `{ locale }` map, resolved\n * at the render site via the same `resolveLabel` path as `form.label` (EC-241).\n */\n name: localizedStringSchema,\n /**\n * When true this view seeds the collection's INITIAL active view (EC-343) — the\n * curated lens an editor lands on before picking one. At most one per collection;\n * a duplicate is a visible validation issue ({@link configViewIssues}), never\n * silent. The built-in \"All\" lens stays available and stays the fallback.\n */\n default: z.boolean().optional(),\n filters: z.array(filterClauseSchema).optional(),\n sort: viewSortSchema.nullable().optional(),\n /** Column order; when omitted, the view inherits the collection's default columns. */\n columns: z.array(z.string().min(1)).optional(),\n hidden: z.array(z.string().min(1)).optional(),\n})\nexport type ConfigView = z.infer<typeof configViewSchema>\n\n/**\n * A resolved view: identity + the table state it restores (matches `SavedView`).\n * `name` stays a {@link LocalizedString} — resolved at the render site (EC-343), like\n * `form.label`. `default` marks the initial-view seed (see {@link defaultConfigViewId}).\n */\nexport interface ResolvedView {\n id: string\n name: LocalizedString\n state: TableViewState\n default?: boolean\n}\n\n/**\n * Slug used to derive a config view's stable id from its name. A localized name\n * (EC-343) slugs its DEFAULT-locale text so the id is stable across the active UI\n * locale (an id must not shift when a German editor loads the same config).\n */\nfunction configViewId(name: LocalizedString, index: number): string {\n const text = resolveLabel(name) ?? ''\n const slug = text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n return `config:${slug || index}`\n}\n\n/**\n * Resolve a collection's config-declared `views` into full {@link ResolvedView}s\n * (EC-246b). Each is validated with {@link configViewSchema}; malformed entries\n * and duplicate ids are dropped (defensive). Columns fall back to the collection\n * default when a view doesn't pin them, so a filter-only view still renders every\n * column. Config views are shared and change only in\n * code — the runtime never mutates them.\n */\nexport function configViewsFor(collection: CollectionDef): ResolvedView[] {\n const declared = collection.views\n if (!Array.isArray(declared)) return []\n const base = defaultViewState(collection)\n const seen = new Set<string>()\n const resolved: ResolvedView[] = []\n declared.forEach((raw, index) => {\n const parsed = configViewSchema.safeParse(raw)\n if (!parsed.success) return\n const view = parsed.data\n const id = view.id ?? configViewId(view.name, index)\n if (seen.has(id)) return\n seen.add(id)\n resolved.push({\n id,\n name: view.name,\n ...(view.default ? { default: true } : {}),\n state: normalizeViewState({\n filters: view.filters ?? [],\n sort: view.sort ?? null,\n columns: view.columns && view.columns.length > 0 ? view.columns : base.columns,\n hidden: view.hidden ?? [],\n }),\n })\n })\n return resolved\n}\n\n/**\n * The id of the config view flagged `default: true` (EC-343) — the seed for a\n * collection's INITIAL active view. When several are flagged (a misconfiguration,\n * reported by {@link configViewIssues}) the FIRST in declaration order wins\n * deterministically; when none is flagged the caller falls back to the built-in\n * \"All\" lens. `undefined` when the collection declares no default view.\n */\nexport function defaultConfigViewId(collection: CollectionDef): string | undefined {\n return configViewsFor(collection).find((view) => view.default)?.id\n}\n\n/** A config-level problem with a collection's declared views (EC-343). */\nexport interface ConfigViewIssue {\n code: 'duplicate-default'\n message: string\n /** The offending view ids (all views flagged `default`, in declaration order). */\n viewIds: string[]\n}\n\n/**\n * Validate a collection's config-declared views (EC-343): at most one may set\n * `default: true`. A duplicate is returned as an explicit, structured issue —\n * never silently swallowed — so the studio can surface it (the first default still\n * wins deterministically for seeding, per {@link defaultConfigViewId}). Pure and\n * schema-only; the DOM-free counterpart of the \"failures are first-class\" contract.\n */\nexport function configViewIssues(collection: CollectionDef): ConfigViewIssue[] {\n const defaults = configViewsFor(collection).filter((view) => view.default)\n if (defaults.length <= 1) return []\n const viewIds = defaults.map((view) => view.id)\n return [\n {\n code: 'duplicate-default',\n message: `Collection \"${collection.id}\" declares ${defaults.length} default views (${viewIds.join(', ')}); at most one view may set \\`default: true\\`. Seeding \"${viewIds[0]}\".`,\n viewIds,\n },\n ]\n}\n\n/**\n * The default column order: the schema's title field first (it becomes the\n * default title/link column — EC-213 drops the separate primary-column\n * selector, treating the first visible column as the title), then the\n * remaining fields in schema order.\n */\nfunction orderedColumnNames(collection: CollectionDef): string[] {\n const names = collection.fields.map((field) => field.name)\n const title = titleFieldOf(collection)?.name\n if (title === undefined || !names.includes(title)) return names\n return [title, ...names.filter((name) => name !== title)]\n}\n\n/** Deep-cloned canonical form (stable key order via the Zod shape). */\nexport function normalizeViewState(state: TableViewState): TableViewState {\n return tableViewStateSchema.parse(state)\n}\n\n/** Structural equality on normalized states — drives the \"unsaved changes\" affordance. */\nexport function viewStatesEqual(a: TableViewState, b: TableViewState): boolean {\n return JSON.stringify(normalizeViewState(a)) === JSON.stringify(normalizeViewState(b))\n}\n\n/** One column of a view resolved against the current schema (EC-213). */\nexport interface ResolvedColumn {\n /** The schema field name. */\n field: string\n /** Whether the column renders (`false` ⇒ in {@link TableViewState.hidden}). */\n visible: boolean\n}\n\n/**\n * Resolve a view's columns against the live schema (EC-213): every schema\n * field exactly once, in the view's saved order, with any fields the view\n * predates appended (visible) and any fields no longer in the schema dropped.\n * This is the single source of truth for \"which columns, in what order, shown\n * or hidden\" — order is preserved across hide/show because visibility lives in\n * `hidden`, never in the order.\n */\nexport function resolveColumns(\n collection: CollectionDef,\n state: TableViewState,\n): ResolvedColumn[] {\n const schemaNames = collection.fields.map((field) => field.name)\n const schema = new Set(schemaNames)\n const hidden = new Set(state.hidden)\n // Keep the saved order, restricted to live fields and de-duplicated (a\n // corrupted persisted state must never render one field as two columns).\n const ordered: string[] = []\n const seen = new Set<string>()\n for (const name of state.columns) {\n if (schema.has(name) && !seen.has(name)) {\n ordered.push(name)\n seen.add(name)\n }\n }\n const appended = schemaNames.filter((name) => !seen.has(name))\n return [...ordered, ...appended].map((field) => ({ field, visible: !hidden.has(field) }))\n}\n\n/** The visible columns of a view, in render order (EC-213). */\nexport function visibleColumns(collection: CollectionDef, state: TableViewState): string[] {\n return resolveColumns(collection, state)\n .filter((column) => column.visible)\n .map((column) => column.field)\n}\n\n/**\n * The title/link column — the document IDENTITY column (EC-242): the schema title\n * field, shown as the leftmost linked cell whose content is `resolveDocumentTitle`\n * (a string `titleField` or a function pattern). Always present regardless of\n * column visibility — it is the document's identity, not a toggleable data column —\n * and excluded from the data columns so the title never shows twice. Falls back to\n * the first visible column, then the first field, then `id`, when no title field\n * is resolvable (e.g. a function title with no backing `title` field).\n */\nexport function primaryColumn(collection: CollectionDef, state: TableViewState): string {\n return (\n titleFieldOf(collection)?.name ??\n visibleColumns(collection, state)[0] ??\n collection.fields[0]?.name ??\n 'id'\n )\n}\n\n/**\n * Reconcile `columns` to the full resolved order so column edits operate on a\n * complete, stable order (drops removed fields, pins appended ones), and prune\n * `hidden` to fields the live schema still has (a column removed from the schema\n * must not leave dead `hidden` cruft that trips dirty-detection / persists).\n */\nfunction withResolvedOrder(collection: CollectionDef, state: TableViewState): TableViewState {\n const columns = resolveColumns(collection, state).map((column) => column.field)\n const live = new Set(columns)\n const hidden = state.hidden.filter((name) => live.has(name))\n return { ...state, columns, hidden }\n}\n\n/**\n * The canonical, schema-resolved form of a view state — full column order with\n * `hidden` pruned to live fields (EC-213). Two states that render identically\n * share one canonical form, so dirty-detection never trips on a mere column\n * reconciliation or a stale `hidden` entry (only a real filter/sort/visibility/\n * order change counts as \"unsaved\").\n */\nexport function canonicalViewState(\n collection: CollectionDef,\n state: TableViewState,\n): TableViewState {\n return normalizeViewState(withResolvedOrder(collection, state))\n}\n\n/**\n * Toggle a column's visibility — position is preserved (EC-213): visibility\n * lives in `hidden`, the order in `columns` is untouched. Columns the saved\n * order predates are pinned into `columns` first so their place is stable.\n */\nexport function toggleColumn(\n collection: CollectionDef,\n state: TableViewState,\n field: string,\n): TableViewState {\n const base = withResolvedOrder(collection, state)\n const hidden = base.hidden.includes(field)\n ? base.hidden.filter((name) => name !== field)\n : [...base.hidden, field]\n return { ...base, hidden }\n}\n\n/** Move a column one position left (-1) or right (+1) in the full column order. */\nexport function moveColumn(\n collection: CollectionDef,\n state: TableViewState,\n field: string,\n delta: -1 | 1,\n): TableViewState {\n const base = withResolvedOrder(collection, state)\n const from = base.columns.indexOf(field)\n const to = from + delta\n if (from < 0 || to < 0 || to >= base.columns.length) return state\n const columns = [...base.columns]\n columns.splice(from, 1)\n columns.splice(to, 0, field)\n return { ...base, columns }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CmsDocument, CollectionDef, DocumentRef, DocumentUrl, FieldDef, Locale, LocaleConfig, RestoreScope } from '@elytracms/core/cms-core';
|
|
1
|
+
import type { CmsDocument, CollectionDef, DocumentRef, DocumentUrl, FieldDef, Locale, LocaleConfig, LocalizedString, RestoreScope } from '@elytracms/core/cms-core';
|
|
2
2
|
import type { CmsValidationIssue } from '@elytracms/core/cms-core';
|
|
3
3
|
import type { OperationError } from '@elytracms/core/operations';
|
|
4
4
|
import type { TableViewState } from '../cms-views/view-model';
|
|
@@ -230,7 +230,8 @@ export interface InlineEditCapability {
|
|
|
230
230
|
/** A named lens the header selector offers — id + display name only (the header never needs its state). */
|
|
231
231
|
export interface NamedView {
|
|
232
232
|
readonly id: string;
|
|
233
|
-
|
|
233
|
+
/** Display name; a {@link LocalizedString} (EC-343), resolved at the render site like `form.label`. */
|
|
234
|
+
readonly name: LocalizedString;
|
|
234
235
|
}
|
|
235
236
|
/** `importExport` capability: validate + fold external JSON records into the collection (EC-079). */
|
|
236
237
|
export interface ImportCapability {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collection-view-source.js","sourceRoot":"","sources":["../../../src/lib/collection-view/collection-view-source.ts"],"names":[],"mappings":"AAkNA;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAChC,MAA4B,EAC5B,KAAe,EACf,MAAoB;IAEpB,OAAO,MAAM,CAAC,WAAW,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAA;AACjG,CAAC","sourcesContent":["import type {\n CmsDocument,\n CollectionDef,\n DocumentRef,\n DocumentUrl,\n FieldDef,\n Locale,\n LocaleConfig,\n RestoreScope,\n} from '@elytracms/core/cms-core'\nimport type { CmsValidationIssue } from '@elytracms/core/cms-core'\nimport type { OperationError } from '@elytracms/core/operations'\nimport type { TableViewState } from '../cms-views/view-model'\n// The concrete inline-edit + bulk vocabulary (Stream A relocates it into `lib` as it settles).\nimport type { CellCommitInput, CellCommitOutcome } from '../../components/cms/cell-edit'\nimport type { BulkAction, BulkReport, BulkSetField } from '../../components/cms/bulk-actions'\nimport type { DocumentVersionsView, ImportReport } from '../../components/cms/cms-store'\n\n/**\n * `CollectionViewSource` — the studio's UNIVERSAL interaction seam (EC-240,\n * vision AD-19).\n *\n * The list surface (`CollectionTable`) and the edit-shell (`DetailEditor`) are\n * the studio's universal interaction surfaces. Historically they read the\n * concrete `CmsStore` through `useCms()`, so they only served `cmsDocuments`.\n * This interface is the data-agnostic seam they render over instead, so the SAME\n * surfaces drive the users rail (EC-240), redirects (EC-303), the Components app\n * edit-shell, and any future rail — no hand-rolled UI per rail.\n *\n * **Shape:** the source is scoped to ONE collection (it carries `schema` +\n * `collectionId`), and its methods mirror the subset of `CmsStore` the surfaces\n * actually use — dropping the `collectionId` argument (the source already knows\n * it). Keeping the names/signatures aligned makes the CMS adapter a\n * behaviour-preserving pass-through and the migration near-mechanical.\n *\n * **Referential stability:** the surfaces put `documents`, `isPublished`,\n * `localeConfig`, etc. in `useMemo` dependency arrays. An implementation MUST\n * return stable references across renders (delegate to the underlying store's\n * already-stable methods; never wrap in a fresh closure each render) or memos\n * bust and the inline-edit order snapshot / perf regress.\n *\n * **Capabilities:** flags gate whole shell regions AND method presence — a source\n * with `capabilities.versions === false` (the users rail) never mounts the\n * Versions pane, so no `listVersions` read fires on credential records. Optional\n * method groups are present iff the flag is set.\n */\nexport interface CollectionViewSource {\n /** The rail/collection this source serves. */\n readonly collectionId: string\n /** The schema lens: fields, form tabs/groups, `titleField`, display nouns. */\n readonly schema: CollectionDef\n /** Which regions/methods this source supports. */\n readonly capabilities: CollectionViewCapabilities\n\n /** The project scope (asset picker, published-pool queries). Absent in fixture sessions. */\n readonly projectId?: string\n /**\n * The collection id assets live in (for a cell/field's `titleOf` label fallback\n * when {@link resolveAsset} finds no record). Present only for sources that\n * reference assets — a rail without assets (users) omits it.\n */\n readonly assetCollectionId?: string\n /** The ambient locale lens (only meaningful when `capabilities.locales`). */\n readonly localeConfig: LocaleConfig\n readonly activeLocale: Locale\n\n // --- Reads -----------------------------------------------------------------\n /** The full row set (view mechanics filter/sort this client-side). */\n documents(): CmsDocument[]\n get(ref: DocumentRef): CmsDocument | undefined\n /** A relation/asset target's display title (hides the string-vs-function `titleField`). */\n titleOf(ref: DocumentRef): string\n /**\n * List the candidate records of a relation field's declared `target` collection\n * — the pick-list for a relation picker (EC-072). References are first-class and\n * collection-based: the field's schema declares which collection(s) it targets,\n * and this resolves those rows for ANY target (cross-collection), not just this\n * source's own collection. The caller passes `field.target`; a multi-target field\n * (future) merges one call per declared target. An unknown/empty target yields `[]`.\n */\n referenceCandidates(collectionId: string): CmsDocument[]\n /**\n * The workspace schema a reference/asset can point at — the schema counterpart to\n * {@link referenceCandidates}. Needed for the cases that read a TARGET collection's\n * fields (an asset field editing the asset collection's own metadata; the reuse\n * capability correlating embed manifests against their target collection). A\n * reference is collection-based, so resolving one sometimes needs the target's\n * schema, not just its rows.\n */\n readonly collections: readonly CollectionDef[]\n isFieldReadOnly(field: FieldDef): boolean\n /**\n * Principal-based field access (EC-240, vision AD-18): `edit` (writable), `read`\n * (visible but read-only), or `hidden` (not rendered for this principal). This is\n * IDENTITY-driven and distinct from a field's content-conditional `hidden(values)`\n * — e.g. an editor's own `role` resolves to `read`, a viewer never SEES a\n * sensitive field (`hidden`). A single tri-state (never two independent flags) so\n * the nonsensical writable-but-invisible state can't be expressed. Optional:\n * absent ⇒ derived from {@link isFieldReadOnly} (`read`|`edit`), i.e. default-open\n * (permissions RESTRICT, never grant a baseline). Per-rail policy lives on the\n * source; the starter's policy flows into its construction (engine = mechanism).\n * Prefer {@link resolveFieldAccess} over calling this directly (it applies the\n * default-open fallback).\n */\n fieldAccess?(field: FieldDef, record?: CmsDocument): FieldAccess\n validate(doc: CmsDocument): CmsValidationIssue[]\n /**\n * Resolve an asset id to its display metadata for a cell/field, or `undefined`\n * when there is no asset backend (a source without assets degrades to a label\n * via {@link titleOf}, matching today's \"no AssetsProvider\" behaviour).\n */\n resolveAsset?(id: string): ResolvedAsset | undefined\n /** The last failed/denied mutation, surfaced by the shell (never a silent failure). */\n readonly lastError: OperationError | null\n clearLastError(): void\n /**\n * Land any queued/optimistic writes so a subsequent pre-flight READ sees them\n * (the reference index is maintained on write). A source with no async\n * persistence omits it — its reads are already authoritative.\n */\n flush?(): Promise<void>\n\n /**\n * The studio route splat for a record's detail surface (the row link + the\n * post-create navigation target), e.g. `studioPath.cmsDocument(collectionId, id)`.\n * Rail-owned so the list never hard-codes the CMS route. `undefined` ⇒ the rail\n * has no detail surface, so rows render as plain text (no navigation).\n */\n detailPath?(id: string): string\n /**\n * The studio route splat for this rail's LIST surface — the edit shell's\n * \"back to list\" breadcrumb crumb and its post-delete navigation target, e.g.\n * `studioPath.cmsCollection(collectionId)`. Rail-owned so the edit shell never\n * hard-codes the CMS route (the counterpart to {@link detailPath}). `undefined`\n * ⇒ the crumb is unlinked and delete falls back to the project index.\n */\n readonly listPath?: string\n\n // --- View state (list) -----------------------------------------------------\n viewState(): TableViewState\n setViewState(update: TableViewState | ((prev: TableViewState) => TableViewState)): void\n\n // --- Writes ----------------------------------------------------------------\n create(): DocumentRef\n save(doc: CmsDocument): void\n remove(ref: DocumentRef): void\n /**\n * Bulk publish/unpublish/delete/set-field (only when `capabilities.bulk`): one\n * command PER item, per-item outcomes enumerated in the report (partial failure\n * is never silent).\n */\n bulk?(ids: readonly string[], action: BulkAction, setField?: BulkSetField): Promise<BulkReport>\n\n // --- Capability method groups (present iff the matching flag is set) --------\n /** `publish` — published-pool predicate + publish/unpublish. */\n readonly publishing?: PublishingCapability\n /** `versions` — version history + restore. */\n readonly versioning?: VersioningCapability\n /** `inlineEdit` — the list's single-command optimistic cell write. */\n readonly inlineEditing?: InlineEditCapability\n /**\n * Config-as-code named lenses (EC-246b) the header view selector switches\n * between. Optional: a source that declares no named views (a non-CMS rail\n * like users) omits it, and the selector renders nothing (single default).\n */\n readonly views?: NamedViewsCapability\n /**\n * `importExport` — JSON round-trip of the collection's records. CMS-specific;\n * a rail whose records are credential-bearing (users) omits it, so neither the\n * import dialog nor the export action mounts (identities aren't dumped to JSON).\n */\n readonly imports?: ImportCapability\n}\n\n/**\n * The capability matrix. Each flag gates a shell region AND the presence of its\n * method group. The **users rail** (EC-240) sets `publish:false`, `versions:false`\n * (credential caution), `create:false` (identity minted by sign-up), and no\n * `liveUrl`/`hierarchy`.\n */\nexport interface CollectionViewCapabilities {\n readonly publish: boolean\n readonly versions: boolean\n readonly locales: boolean\n readonly inlineEdit: boolean\n readonly create: boolean\n readonly remove: boolean\n readonly bulk: boolean\n /** The derived live-URL column (published pool × deployment routes). */\n readonly liveUrl: boolean\n /** Parent-self-relation tree mode (hierarchical collections only). */\n readonly hierarchy: boolean\n /** JSON import/export of the collection's records (off for credential rails). */\n readonly importExport: boolean\n /**\n * The rail is administration-scoped (mirrors `ADMIN_ONLY_OPERATIONS`). The\n * nav-permission layer reads this to gate the rail item. Absent ⇒ not admin-only.\n */\n readonly adminOnly?: boolean\n}\n\n/**\n * Principal-based field access (EC-240, AD-18). One tri-state drives BOTH visibility\n * and writability: `edit` (writable), `read` (visible, read-only), `hidden` (not\n * rendered). Default `edit` (default-open). Distinct from content-`hidden(values)`;\n * they compose — a field shows iff *not content-hidden AND access ≠ hidden*, and is\n * editable iff *access = edit AND not otherwise read-only* (published view, `form.readOnly`).\n */\nexport type FieldAccess = 'edit' | 'read' | 'hidden'\n\n/**\n * Resolve a field's effective principal access for a source — its {@link\n * CollectionViewSource.fieldAccess} policy when present, else derived from the\n * boolean `isFieldReadOnly` (default-open). The one place the shell asks \"may this\n * principal edit / see this field?\", so the default-open fallback lives in one spot.\n */\nexport function resolveFieldAccess(\n source: CollectionViewSource,\n field: FieldDef,\n record?: CmsDocument,\n): FieldAccess {\n return source.fieldAccess?.(field, record) ?? (source.isFieldReadOnly(field) ? 'read' : 'edit')\n}\n\n/** Asset display metadata a cell/field renders (thumbnail or labelled badge). */\nexport interface ResolvedAsset {\n readonly url?: string\n readonly contentType?: string\n readonly title?: string\n readonly filename?: string\n readonly alt?: string\n}\n\n/** `publish` capability. */\nexport interface PublishingCapability {\n /** Published-ness from the version pointer (NOT a row field). */\n isPublished(ref: DocumentRef): boolean\n publish(ref: DocumentRef): Promise<void>\n unpublish(ref: DocumentRef): Promise<void>\n /**\n * Live URLs for the routable documents, keyed by id — derived from the\n * PUBLISHED pool (never draft rows) so an unpublished slug/parent edit can't\n * leak into a live link (EC-205/EC-216). `null` when the collection is not\n * routable → the live-URL column is hidden. Only present when `capabilities.liveUrl`.\n */\n liveUrls?(): Map<string, DocumentUrl> | null\n}\n\n/** `versions` capability. */\nexport interface VersioningCapability {\n restore(ref: DocumentRef, version: number, scope?: RestoreScope): Promise<CmsDocument | null>\n /**\n * The document's recorded version history + live pin. Folds the flush-before-read\n * ordering INTO the loader (the adapter's concern), so every fetch lists an\n * authoritative history regardless of which surface triggered the change (EC-224).\n */\n load(ref: DocumentRef): Promise<DocumentVersionsView>\n}\n\n/** `inlineEdit` capability: the list's single-command optimistic cell write (EC-168). */\nexport interface InlineEditCapability {\n commitField(input: CellCommitInput): Promise<CellCommitOutcome>\n}\n\n/** A named lens the header selector offers — id + display name only (the header never needs its state). */\nexport interface NamedView {\n readonly id: string\n readonly name: string\n}\n\n/** `importExport` capability: validate + fold external JSON records into the collection (EC-079). */\nexport interface ImportCapability {\n importDocuments(items: unknown[]): ImportReport\n}\n\n/**\n * `views` capability: config-as-code named lenses (EC-246b). The header selector\n * only *picks* a lens — it never creates/edits/deletes one (shared views are code).\n */\nexport interface NamedViewsCapability {\n /** The built-in default + config-declared named views. */\n list(): readonly NamedView[]\n /** The currently-selected view id. */\n activeId(): string\n /** Switch views (resets the working table state to the view's baseline). */\n setActive(id: string): void\n}\n\nexport type { CellCommitInput, CellCommitOutcome, ImportReport }\n"]}
|
|
1
|
+
{"version":3,"file":"collection-view-source.js","sourceRoot":"","sources":["../../../src/lib/collection-view/collection-view-source.ts"],"names":[],"mappings":"AAmNA;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAChC,MAA4B,EAC5B,KAAe,EACf,MAAoB;IAEpB,OAAO,MAAM,CAAC,WAAW,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAA;AACjG,CAAC","sourcesContent":["import type {\n CmsDocument,\n CollectionDef,\n DocumentRef,\n DocumentUrl,\n FieldDef,\n Locale,\n LocaleConfig,\n LocalizedString,\n RestoreScope,\n} from '@elytracms/core/cms-core'\nimport type { CmsValidationIssue } from '@elytracms/core/cms-core'\nimport type { OperationError } from '@elytracms/core/operations'\nimport type { TableViewState } from '../cms-views/view-model'\n// The concrete inline-edit + bulk vocabulary (Stream A relocates it into `lib` as it settles).\nimport type { CellCommitInput, CellCommitOutcome } from '../../components/cms/cell-edit'\nimport type { BulkAction, BulkReport, BulkSetField } from '../../components/cms/bulk-actions'\nimport type { DocumentVersionsView, ImportReport } from '../../components/cms/cms-store'\n\n/**\n * `CollectionViewSource` — the studio's UNIVERSAL interaction seam (EC-240,\n * vision AD-19).\n *\n * The list surface (`CollectionTable`) and the edit-shell (`DetailEditor`) are\n * the studio's universal interaction surfaces. Historically they read the\n * concrete `CmsStore` through `useCms()`, so they only served `cmsDocuments`.\n * This interface is the data-agnostic seam they render over instead, so the SAME\n * surfaces drive the users rail (EC-240), redirects (EC-303), the Components app\n * edit-shell, and any future rail — no hand-rolled UI per rail.\n *\n * **Shape:** the source is scoped to ONE collection (it carries `schema` +\n * `collectionId`), and its methods mirror the subset of `CmsStore` the surfaces\n * actually use — dropping the `collectionId` argument (the source already knows\n * it). Keeping the names/signatures aligned makes the CMS adapter a\n * behaviour-preserving pass-through and the migration near-mechanical.\n *\n * **Referential stability:** the surfaces put `documents`, `isPublished`,\n * `localeConfig`, etc. in `useMemo` dependency arrays. An implementation MUST\n * return stable references across renders (delegate to the underlying store's\n * already-stable methods; never wrap in a fresh closure each render) or memos\n * bust and the inline-edit order snapshot / perf regress.\n *\n * **Capabilities:** flags gate whole shell regions AND method presence — a source\n * with `capabilities.versions === false` (the users rail) never mounts the\n * Versions pane, so no `listVersions` read fires on credential records. Optional\n * method groups are present iff the flag is set.\n */\nexport interface CollectionViewSource {\n /** The rail/collection this source serves. */\n readonly collectionId: string\n /** The schema lens: fields, form tabs/groups, `titleField`, display nouns. */\n readonly schema: CollectionDef\n /** Which regions/methods this source supports. */\n readonly capabilities: CollectionViewCapabilities\n\n /** The project scope (asset picker, published-pool queries). Absent in fixture sessions. */\n readonly projectId?: string\n /**\n * The collection id assets live in (for a cell/field's `titleOf` label fallback\n * when {@link resolveAsset} finds no record). Present only for sources that\n * reference assets — a rail without assets (users) omits it.\n */\n readonly assetCollectionId?: string\n /** The ambient locale lens (only meaningful when `capabilities.locales`). */\n readonly localeConfig: LocaleConfig\n readonly activeLocale: Locale\n\n // --- Reads -----------------------------------------------------------------\n /** The full row set (view mechanics filter/sort this client-side). */\n documents(): CmsDocument[]\n get(ref: DocumentRef): CmsDocument | undefined\n /** A relation/asset target's display title (hides the string-vs-function `titleField`). */\n titleOf(ref: DocumentRef): string\n /**\n * List the candidate records of a relation field's declared `target` collection\n * — the pick-list for a relation picker (EC-072). References are first-class and\n * collection-based: the field's schema declares which collection(s) it targets,\n * and this resolves those rows for ANY target (cross-collection), not just this\n * source's own collection. The caller passes `field.target`; a multi-target field\n * (future) merges one call per declared target. An unknown/empty target yields `[]`.\n */\n referenceCandidates(collectionId: string): CmsDocument[]\n /**\n * The workspace schema a reference/asset can point at — the schema counterpart to\n * {@link referenceCandidates}. Needed for the cases that read a TARGET collection's\n * fields (an asset field editing the asset collection's own metadata; the reuse\n * capability correlating embed manifests against their target collection). A\n * reference is collection-based, so resolving one sometimes needs the target's\n * schema, not just its rows.\n */\n readonly collections: readonly CollectionDef[]\n isFieldReadOnly(field: FieldDef): boolean\n /**\n * Principal-based field access (EC-240, vision AD-18): `edit` (writable), `read`\n * (visible but read-only), or `hidden` (not rendered for this principal). This is\n * IDENTITY-driven and distinct from a field's content-conditional `hidden(values)`\n * — e.g. an editor's own `role` resolves to `read`, a viewer never SEES a\n * sensitive field (`hidden`). A single tri-state (never two independent flags) so\n * the nonsensical writable-but-invisible state can't be expressed. Optional:\n * absent ⇒ derived from {@link isFieldReadOnly} (`read`|`edit`), i.e. default-open\n * (permissions RESTRICT, never grant a baseline). Per-rail policy lives on the\n * source; the starter's policy flows into its construction (engine = mechanism).\n * Prefer {@link resolveFieldAccess} over calling this directly (it applies the\n * default-open fallback).\n */\n fieldAccess?(field: FieldDef, record?: CmsDocument): FieldAccess\n validate(doc: CmsDocument): CmsValidationIssue[]\n /**\n * Resolve an asset id to its display metadata for a cell/field, or `undefined`\n * when there is no asset backend (a source without assets degrades to a label\n * via {@link titleOf}, matching today's \"no AssetsProvider\" behaviour).\n */\n resolveAsset?(id: string): ResolvedAsset | undefined\n /** The last failed/denied mutation, surfaced by the shell (never a silent failure). */\n readonly lastError: OperationError | null\n clearLastError(): void\n /**\n * Land any queued/optimistic writes so a subsequent pre-flight READ sees them\n * (the reference index is maintained on write). A source with no async\n * persistence omits it — its reads are already authoritative.\n */\n flush?(): Promise<void>\n\n /**\n * The studio route splat for a record's detail surface (the row link + the\n * post-create navigation target), e.g. `studioPath.cmsDocument(collectionId, id)`.\n * Rail-owned so the list never hard-codes the CMS route. `undefined` ⇒ the rail\n * has no detail surface, so rows render as plain text (no navigation).\n */\n detailPath?(id: string): string\n /**\n * The studio route splat for this rail's LIST surface — the edit shell's\n * \"back to list\" breadcrumb crumb and its post-delete navigation target, e.g.\n * `studioPath.cmsCollection(collectionId)`. Rail-owned so the edit shell never\n * hard-codes the CMS route (the counterpart to {@link detailPath}). `undefined`\n * ⇒ the crumb is unlinked and delete falls back to the project index.\n */\n readonly listPath?: string\n\n // --- View state (list) -----------------------------------------------------\n viewState(): TableViewState\n setViewState(update: TableViewState | ((prev: TableViewState) => TableViewState)): void\n\n // --- Writes ----------------------------------------------------------------\n create(): DocumentRef\n save(doc: CmsDocument): void\n remove(ref: DocumentRef): void\n /**\n * Bulk publish/unpublish/delete/set-field (only when `capabilities.bulk`): one\n * command PER item, per-item outcomes enumerated in the report (partial failure\n * is never silent).\n */\n bulk?(ids: readonly string[], action: BulkAction, setField?: BulkSetField): Promise<BulkReport>\n\n // --- Capability method groups (present iff the matching flag is set) --------\n /** `publish` — published-pool predicate + publish/unpublish. */\n readonly publishing?: PublishingCapability\n /** `versions` — version history + restore. */\n readonly versioning?: VersioningCapability\n /** `inlineEdit` — the list's single-command optimistic cell write. */\n readonly inlineEditing?: InlineEditCapability\n /**\n * Config-as-code named lenses (EC-246b) the header view selector switches\n * between. Optional: a source that declares no named views (a non-CMS rail\n * like users) omits it, and the selector renders nothing (single default).\n */\n readonly views?: NamedViewsCapability\n /**\n * `importExport` — JSON round-trip of the collection's records. CMS-specific;\n * a rail whose records are credential-bearing (users) omits it, so neither the\n * import dialog nor the export action mounts (identities aren't dumped to JSON).\n */\n readonly imports?: ImportCapability\n}\n\n/**\n * The capability matrix. Each flag gates a shell region AND the presence of its\n * method group. The **users rail** (EC-240) sets `publish:false`, `versions:false`\n * (credential caution), `create:false` (identity minted by sign-up), and no\n * `liveUrl`/`hierarchy`.\n */\nexport interface CollectionViewCapabilities {\n readonly publish: boolean\n readonly versions: boolean\n readonly locales: boolean\n readonly inlineEdit: boolean\n readonly create: boolean\n readonly remove: boolean\n readonly bulk: boolean\n /** The derived live-URL column (published pool × deployment routes). */\n readonly liveUrl: boolean\n /** Parent-self-relation tree mode (hierarchical collections only). */\n readonly hierarchy: boolean\n /** JSON import/export of the collection's records (off for credential rails). */\n readonly importExport: boolean\n /**\n * The rail is administration-scoped (mirrors `ADMIN_ONLY_OPERATIONS`). The\n * nav-permission layer reads this to gate the rail item. Absent ⇒ not admin-only.\n */\n readonly adminOnly?: boolean\n}\n\n/**\n * Principal-based field access (EC-240, AD-18). One tri-state drives BOTH visibility\n * and writability: `edit` (writable), `read` (visible, read-only), `hidden` (not\n * rendered). Default `edit` (default-open). Distinct from content-`hidden(values)`;\n * they compose — a field shows iff *not content-hidden AND access ≠ hidden*, and is\n * editable iff *access = edit AND not otherwise read-only* (published view, `form.readOnly`).\n */\nexport type FieldAccess = 'edit' | 'read' | 'hidden'\n\n/**\n * Resolve a field's effective principal access for a source — its {@link\n * CollectionViewSource.fieldAccess} policy when present, else derived from the\n * boolean `isFieldReadOnly` (default-open). The one place the shell asks \"may this\n * principal edit / see this field?\", so the default-open fallback lives in one spot.\n */\nexport function resolveFieldAccess(\n source: CollectionViewSource,\n field: FieldDef,\n record?: CmsDocument,\n): FieldAccess {\n return source.fieldAccess?.(field, record) ?? (source.isFieldReadOnly(field) ? 'read' : 'edit')\n}\n\n/** Asset display metadata a cell/field renders (thumbnail or labelled badge). */\nexport interface ResolvedAsset {\n readonly url?: string\n readonly contentType?: string\n readonly title?: string\n readonly filename?: string\n readonly alt?: string\n}\n\n/** `publish` capability. */\nexport interface PublishingCapability {\n /** Published-ness from the version pointer (NOT a row field). */\n isPublished(ref: DocumentRef): boolean\n publish(ref: DocumentRef): Promise<void>\n unpublish(ref: DocumentRef): Promise<void>\n /**\n * Live URLs for the routable documents, keyed by id — derived from the\n * PUBLISHED pool (never draft rows) so an unpublished slug/parent edit can't\n * leak into a live link (EC-205/EC-216). `null` when the collection is not\n * routable → the live-URL column is hidden. Only present when `capabilities.liveUrl`.\n */\n liveUrls?(): Map<string, DocumentUrl> | null\n}\n\n/** `versions` capability. */\nexport interface VersioningCapability {\n restore(ref: DocumentRef, version: number, scope?: RestoreScope): Promise<CmsDocument | null>\n /**\n * The document's recorded version history + live pin. Folds the flush-before-read\n * ordering INTO the loader (the adapter's concern), so every fetch lists an\n * authoritative history regardless of which surface triggered the change (EC-224).\n */\n load(ref: DocumentRef): Promise<DocumentVersionsView>\n}\n\n/** `inlineEdit` capability: the list's single-command optimistic cell write (EC-168). */\nexport interface InlineEditCapability {\n commitField(input: CellCommitInput): Promise<CellCommitOutcome>\n}\n\n/** A named lens the header selector offers — id + display name only (the header never needs its state). */\nexport interface NamedView {\n readonly id: string\n /** Display name; a {@link LocalizedString} (EC-343), resolved at the render site like `form.label`. */\n readonly name: LocalizedString\n}\n\n/** `importExport` capability: validate + fold external JSON records into the collection (EC-079). */\nexport interface ImportCapability {\n importDocuments(items: unknown[]): ImportReport\n}\n\n/**\n * `views` capability: config-as-code named lenses (EC-246b). The header selector\n * only *picks* a lens — it never creates/edits/deletes one (shared views are code).\n */\nexport interface NamedViewsCapability {\n /** The built-in default + config-declared named views. */\n list(): readonly NamedView[]\n /** The currently-selected view id. */\n activeId(): string\n /** Switch views (resets the working table state to the view's baseline). */\n setActive(id: string): void\n}\n\nexport type { CellCommitInput, CellCommitOutcome, ImportReport }\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@elytracms/studio",
|
|
3
3
|
"author": "finaldream <hi@finaldream.de>",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.49",
|
|
5
5
|
"private": false,
|
|
6
6
|
"description": "The Elytra studio engine (UI + lib + routes + data-only Convex schema) as an importable package. Extraction staged in EXTRACTION.md (EC-223); Stages 1-2 = UI primitives + router-free lib leaves.",
|
|
7
7
|
"license": "MIT",
|
|
@@ -136,7 +136,7 @@
|
|
|
136
136
|
"lucide-react": "^1.23.0",
|
|
137
137
|
"tailwind-merge": "^3.6.0",
|
|
138
138
|
"zod": "^4.4.3",
|
|
139
|
-
"@elytracms/core": "^0.0.
|
|
139
|
+
"@elytracms/core": "^0.0.49"
|
|
140
140
|
},
|
|
141
141
|
"peerDependencies": {
|
|
142
142
|
"@tanstack/react-router": "^1.170.0",
|