@elytracms/studio 0.0.86 → 0.0.88
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/convex/asset-revalidate.test.ts +186 -0
- package/convex/assets.ts +53 -19
- package/convex/cms.ts +22 -0
- package/convex/delivery.ts +33 -116
- package/convex/functions.ts +3 -3
- package/convex/rail-write-parity.test.ts +180 -0
- package/convex/redirects.ts +33 -11
- package/convex/revalidate.ts +7 -5
- package/convex/triggers.ts +53 -3
- package/dist/components/ai/ai-chat-panel.js +8 -1
- package/dist/components/ai/ai-chat-panel.js.map +1 -1
- package/dist/components/app-views/default-modules.d.ts +20 -20
- package/dist/components/app-views/default-modules.js +27 -48
- package/dist/components/app-views/default-modules.js.map +1 -1
- package/dist/components/app-views/studio-config.d.ts +5 -6
- package/dist/components/app-views/studio-config.js.map +1 -1
- package/dist/components/assets/asset-metadata.d.ts +28 -19
- package/dist/components/assets/asset-metadata.js +24 -31
- package/dist/components/assets/asset-metadata.js.map +1 -1
- package/dist/components/assets/asset-selection.d.ts +24 -5
- package/dist/components/assets/asset-selection.js +39 -9
- package/dist/components/assets/asset-selection.js.map +1 -1
- package/dist/components/assets/assets-collection-view-source.d.ts +17 -14
- package/dist/components/assets/assets-collection-view-source.js +25 -31
- package/dist/components/assets/assets-collection-view-source.js.map +1 -1
- package/dist/components/assets/assets-store.d.ts +11 -1
- package/dist/components/assets/assets-store.js +10 -0
- package/dist/components/assets/assets-store.js.map +1 -1
- package/dist/components/assets/focal-point.d.ts +0 -7
- package/dist/components/assets/focal-point.js +0 -10
- package/dist/components/assets/focal-point.js.map +1 -1
- package/dist/components/builder/blocks-panel.js +3 -3
- package/dist/components/builder/blocks-panel.js.map +1 -1
- package/dist/components/builder/builder-store.d.ts +25 -1
- package/dist/components/builder/builder-store.js +3 -2
- package/dist/components/builder/builder-store.js.map +1 -1
- package/dist/components/builder/canvas-chrome-css.js +0 -17
- package/dist/components/builder/canvas-chrome-css.js.map +1 -1
- package/dist/components/builder/canvas-chrome.d.ts +10 -12
- package/dist/components/builder/canvas-chrome.js +12 -13
- package/dist/components/builder/canvas-chrome.js.map +1 -1
- package/dist/components/builder/canvas-dnd.d.ts +8 -0
- package/dist/components/builder/canvas-dnd.js +5 -3
- package/dist/components/builder/canvas-dnd.js.map +1 -1
- package/dist/components/builder/canvas-render-context.d.ts +23 -24
- package/dist/components/builder/canvas-render-context.js +35 -60
- package/dist/components/builder/canvas-render-context.js.map +1 -1
- package/dist/components/builder/canvas.js +5 -11
- package/dist/components/builder/canvas.js.map +1 -1
- package/dist/components/builder/clipboard-actions.d.ts +14 -6
- package/dist/components/builder/clipboard-actions.js +29 -20
- package/dist/components/builder/clipboard-actions.js.map +1 -1
- package/dist/components/builder/composition-field-editor.d.ts +19 -26
- package/dist/components/builder/composition-field-editor.js +30 -52
- package/dist/components/builder/composition-field-editor.js.map +1 -1
- package/dist/components/builder/insert-context.d.ts +3 -1
- package/dist/components/builder/insert-context.js +15 -10
- package/dist/components/builder/insert-context.js.map +1 -1
- package/dist/components/builder/page-tree.d.ts +29 -0
- package/dist/components/builder/page-tree.js +56 -58
- package/dist/components/builder/page-tree.js.map +1 -1
- package/dist/components/builder/reuse.js +5 -2
- package/dist/components/builder/reuse.js.map +1 -1
- package/dist/components/cms/asset-field.d.ts +2 -1
- package/dist/components/cms/asset-field.js +39 -83
- package/dist/components/cms/asset-field.js.map +1 -1
- package/dist/components/cms/asset-picker-core.d.ts +77 -40
- package/dist/components/cms/asset-picker-core.js +73 -46
- package/dist/components/cms/asset-picker-core.js.map +1 -1
- package/dist/components/cms/asset-picker.d.ts +48 -19
- package/dist/components/cms/asset-picker.js +69 -30
- package/dist/components/cms/asset-picker.js.map +1 -1
- package/dist/components/cms/cell-edit.d.ts +3 -1
- package/dist/components/cms/cell-edit.js +2 -2
- package/dist/components/cms/cell-edit.js.map +1 -1
- package/dist/components/cms/cms-composition-validators.js +11 -2
- package/dist/components/cms/cms-composition-validators.js.map +1 -1
- package/dist/components/cms/cms-store.js +15 -23
- package/dist/components/cms/cms-store.js.map +1 -1
- package/dist/components/cms/editable-cell.js +3 -3
- package/dist/components/cms/editable-cell.js.map +1 -1
- package/dist/components/cms/gate-validation.d.ts +27 -2
- package/dist/components/cms/gate-validation.js +19 -1
- package/dist/components/cms/gate-validation.js.map +1 -1
- package/dist/components/cms/rich-text/editor.js +2 -2
- package/dist/components/cms/rich-text/editor.js.map +1 -1
- package/dist/components/cms/rich-text/insert.d.ts +7 -0
- package/dist/components/cms/rich-text/insert.js +7 -0
- package/dist/components/cms/rich-text/insert.js.map +1 -1
- package/dist/components/cms/use-document-versions.js +1 -0
- package/dist/components/cms/use-document-versions.js.map +1 -1
- package/dist/components/cms/versions-model.d.ts +0 -12
- package/dist/components/cms/versions-model.js +3 -15
- package/dist/components/cms/versions-model.js.map +1 -1
- package/dist/components/components/component-detail.js +1 -1
- package/dist/components/components/component-detail.js.map +1 -1
- package/dist/components/components/transfer-dialog.js +2 -4
- package/dist/components/components/transfer-dialog.js.map +1 -1
- package/dist/components/components/transfer.d.ts +13 -10
- package/dist/components/components/transfer.js +21 -19
- package/dist/components/components/transfer.js.map +1 -1
- package/dist/components/nav-issues.d.ts +23 -3
- package/dist/components/nav-issues.js +38 -2
- package/dist/components/nav-issues.js.map +1 -1
- package/dist/components/project-session.d.ts +9 -0
- package/dist/components/project-session.js +1 -1
- package/dist/components/project-session.js.map +1 -1
- package/dist/components/redirects/redirects-collection-view-source.d.ts +17 -2
- package/dist/components/redirects/redirects-collection-view-source.js +20 -6
- package/dist/components/redirects/redirects-collection-view-source.js.map +1 -1
- package/dist/components/section-nav.js +26 -2
- package/dist/components/section-nav.js.map +1 -1
- package/dist/components/section-surface.js +3 -2
- package/dist/components/section-surface.js.map +1 -1
- package/dist/components/settings-form.js +1 -2
- package/dist/components/settings-form.js.map +1 -1
- package/dist/components/studio-context.js +1 -18
- package/dist/components/studio-context.js.map +1 -1
- package/dist/components/studio-project-screen.js +3 -5
- package/dist/components/studio-project-screen.js.map +1 -1
- package/dist/lib/ai/apply-content.js +73 -29
- package/dist/lib/ai/apply-content.js.map +1 -1
- package/dist/lib/ai/constraints.d.ts +35 -0
- package/dist/lib/ai/constraints.js +104 -4
- package/dist/lib/ai/constraints.js.map +1 -1
- package/dist/lib/ai/route.js +4 -1
- package/dist/lib/ai/route.js.map +1 -1
- package/dist/lib/ai/shape.d.ts +3 -2
- package/dist/lib/ai/shape.js +16 -24
- package/dist/lib/ai/shape.js.map +1 -1
- package/dist/lib/ai/tools.d.ts +10 -4
- package/dist/lib/ai/tools.js +12 -4
- package/dist/lib/ai/tools.js.map +1 -1
- package/dist/lib/ai/types.d.ts +8 -0
- package/dist/lib/ai/types.js.map +1 -1
- package/dist/lib/ai/update-fields.js +33 -12
- package/dist/lib/ai/update-fields.js.map +1 -1
- package/dist/lib/assets/asset-placements.d.ts +35 -0
- package/dist/lib/assets/asset-placements.js +74 -0
- package/dist/lib/assets/asset-placements.js.map +1 -0
- package/dist/lib/assets/backfill-thumbs.d.ts +9 -8
- package/dist/lib/assets/backfill-thumbs.js +13 -25
- package/dist/lib/assets/backfill-thumbs.js.map +1 -1
- package/dist/lib/clipboard/paste-issues.d.ts +17 -15
- package/dist/lib/clipboard/paste-issues.js +8 -45
- package/dist/lib/clipboard/paste-issues.js.map +1 -1
- package/dist/lib/clipboard/paste-target.d.ts +25 -1
- package/dist/lib/clipboard/paste-target.js +13 -6
- package/dist/lib/clipboard/paste-target.js.map +1 -1
- package/dist/lib/cms/published-documents.js +1 -0
- package/dist/lib/cms/published-documents.js.map +1 -1
- package/dist/lib/cms-views/view-model.d.ts +3 -3
- package/dist/lib/data/collection-content.d.ts +22 -1
- package/dist/lib/data/collection-content.js +15 -0
- package/dist/lib/data/collection-content.js.map +1 -1
- package/dist/lib/data/index.d.ts +0 -3
- package/dist/lib/data/index.js +4 -6
- package/dist/lib/data/index.js.map +1 -1
- package/dist/lib/dnd/drop-rules.d.ts +45 -2
- package/dist/lib/dnd/drop-rules.js +64 -9
- package/dist/lib/dnd/drop-rules.js.map +1 -1
- package/dist/lib/engine-version.d.ts +3 -3
- package/dist/lib/engine-version.js +3 -3
- package/dist/lib/engine-version.js.map +1 -1
- package/dist/lib/i18n/messages.de.js +9 -56
- package/dist/lib/i18n/messages.de.js.map +1 -1
- package/dist/lib/i18n/messages.en.d.ts +8 -53
- package/dist/lib/i18n/messages.en.js +14 -57
- package/dist/lib/i18n/messages.en.js.map +1 -1
- package/dist/lib/locale/fallback.js +8 -2
- package/dist/lib/locale/fallback.js.map +1 -1
- package/dist/lib/locale/index.d.ts +0 -1
- package/dist/lib/locale/index.js +0 -1
- package/dist/lib/locale/index.js.map +1 -1
- package/dist/lib/locale/locale-store.d.ts +10 -3
- package/dist/lib/locale/locale-store.js +12 -5
- package/dist/lib/locale/locale-store.js.map +1 -1
- package/dist/lib/operations/session-hydration.d.ts +24 -22
- package/dist/lib/operations/session-hydration.js +15 -53
- package/dist/lib/operations/session-hydration.js.map +1 -1
- package/dist/lib/persistence/convex-adapter.js +63 -75
- package/dist/lib/persistence/convex-adapter.js.map +1 -1
- package/dist/lib/persona/labels.d.ts +0 -2
- package/dist/lib/persona/labels.js +1 -7
- package/dist/lib/persona/labels.js.map +1 -1
- package/dist/lib/registry/index.d.ts +4 -2
- package/dist/lib/registry/index.js +26 -21
- package/dist/lib/registry/index.js.map +1 -1
- package/dist/lib/registry/project-components.js +0 -3
- package/dist/lib/registry/project-components.js.map +1 -1
- package/dist/lib/routes/route-issues.js +4 -5
- package/dist/lib/routes/route-issues.js.map +1 -1
- package/dist/lib/theme.js +3 -2
- package/dist/lib/theme.js.map +1 -1
- package/dist/lib/webhooks/tags.js +11 -14
- package/dist/lib/webhooks/tags.js.map +1 -1
- package/dist/lib/workspace/config-issues.d.ts +6 -0
- package/dist/lib/workspace/config-issues.js +8 -4
- package/dist/lib/workspace/config-issues.js.map +1 -1
- package/dist/lib/workspace/index.d.ts +2 -2
- package/dist/lib/workspace/index.js +2 -2
- package/dist/lib/workspace/index.js.map +1 -1
- package/dist/previews/enumerate.d.ts +27 -9
- package/dist/previews/enumerate.js +27 -6
- package/dist/previews/enumerate.js.map +1 -1
- package/dist/previews/manifest-format.d.ts +9 -0
- package/dist/previews/manifest-format.js.map +1 -1
- package/dist/router/match.d.ts +0 -2
- package/dist/router/match.js +0 -2
- package/dist/router/match.js.map +1 -1
- package/dist/router/navigate-once.d.ts +19 -4
- package/dist/router/navigate-once.js +22 -5
- package/dist/router/navigate-once.js.map +1 -1
- package/dist/ui/badge.d.ts +1 -1
- package/package.json +3 -3
- package/src/styles/studio.css +5 -4
- package/src/styles/tokens.css +72 -55
- package/convex/content.ts +0 -291
- package/dist/components/collab/collab-context.d.ts +0 -27
- package/dist/components/collab/collab-context.js +0 -39
- package/dist/components/collab/collab-context.js.map +0 -1
- package/dist/components/collab/collab-seed.d.ts +0 -15
- package/dist/components/collab/collab-seed.js +0 -20
- package/dist/components/collab/collab-seed.js.map +0 -1
- package/dist/components/extensions/extensions-view.d.ts +0 -7
- package/dist/components/extensions/extensions-view.js +0 -127
- package/dist/components/extensions/extensions-view.js.map +0 -1
- package/dist/lib/bindings/section-bindings.d.ts +0 -24
- package/dist/lib/bindings/section-bindings.js +0 -9
- package/dist/lib/bindings/section-bindings.js.map +0 -1
- package/dist/lib/data/data-store.d.ts +0 -98
- package/dist/lib/data/data-store.js +0 -211
- package/dist/lib/data/data-store.js.map +0 -1
- package/dist/lib/data/providers.d.ts +0 -143
- package/dist/lib/data/providers.js +0 -255
- package/dist/lib/data/providers.js.map +0 -1
- package/dist/lib/data/sample-capture.d.ts +0 -30
- package/dist/lib/data/sample-capture.js +0 -70
- package/dist/lib/data/sample-capture.js.map +0 -1
- package/dist/lib/data/sources-store.d.ts +0 -42
- package/dist/lib/data/sources-store.js +0 -120
- package/dist/lib/data/sources-store.js.map +0 -1
- package/dist/lib/locale/binding-fallback.d.ts +0 -35
- package/dist/lib/locale/binding-fallback.js +0 -73
- package/dist/lib/locale/binding-fallback.js.map +0 -1
- package/dist/lib/starters/kit-session.d.ts +0 -5
- package/dist/lib/starters/kit-session.js +0 -17
- package/dist/lib/starters/kit-session.js.map +0 -1
|
@@ -1,3 +1,17 @@
|
|
|
1
|
+
import type { AssetsStore } from '../assets/assets-store.js';
|
|
2
|
+
/** The picker's props — see {@link AssetPicker}. */
|
|
3
|
+
export interface AssetPickerProps {
|
|
4
|
+
value: string | null;
|
|
5
|
+
open: boolean;
|
|
6
|
+
onOpenChange: (open: boolean) => void;
|
|
7
|
+
onChange: (assetId: string | null) => void;
|
|
8
|
+
/** EC-460: commit a whole settled upload batch (a `many` field passes this). */
|
|
9
|
+
onChangeMany?: (assetIds: string[]) => void;
|
|
10
|
+
/** Whether the consuming field holds many assets (enables batch commit). */
|
|
11
|
+
multiple?: boolean;
|
|
12
|
+
/** The field's `accept` list (EC-588) — absent means any file. */
|
|
13
|
+
accept?: readonly string[];
|
|
14
|
+
}
|
|
1
15
|
/**
|
|
2
16
|
* Pick an asset for a CMS `asset` field (brief §8.4, §8.6, EC-075 → EC-152).
|
|
3
17
|
* Backed by the *real* asset library (the assets store over the operations
|
|
@@ -14,24 +28,39 @@
|
|
|
14
28
|
* expanded rich-text stage toolbar it rides ABOVE that stage on the EC-392 layer
|
|
15
29
|
* stack — Escape closes the browser first, the rich-text stage stays.
|
|
16
30
|
*
|
|
17
|
-
* The component CONTRACT
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
31
|
+
* The component CONTRACT (`{ open, onOpenChange, value, accept, onChange }`) serves
|
|
32
|
+
* every call site — asset fields, rich-text image insertion, editable cells. EC-460
|
|
33
|
+
* adds an OPTIONAL multi-commit pair (`multiple` + `onChangeMany`): a `many` asset
|
|
34
|
+
* field passes both so uploading N files in ONE picker interaction attaches ALL N
|
|
35
|
+
* (the old flow committed the first upload to land and closed — the rest reached the
|
|
36
|
+
* library but never the field, silent partial data loss). Grid clicks stay
|
|
37
|
+
* single-pick-and-close in every mode.
|
|
38
|
+
*
|
|
39
|
+
* EC-588: `accept` is the field's STRUCTURED list (it was a file-input string that the
|
|
40
|
+
* core re-split — two shapes for one fact). The grid filter, the file-input attribute
|
|
41
|
+
* and the drop/upload split all derive from it, and an absent `accept` is unrestricted
|
|
42
|
+
* everywhere (the Upload dialog used to fall back to `image/*`). A field-backed caller
|
|
43
|
+
* passes `assetPickerBinding`'s output (`asset-picker-core`) rather than wiring props
|
|
44
|
+
* by hand.
|
|
25
45
|
*/
|
|
26
|
-
export declare function AssetPicker({ value, open, onOpenChange, onChange, onChangeMany, multiple, accept, }:
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
46
|
+
export declare function AssetPicker({ value, open, onOpenChange, onChange, onChangeMany, multiple, accept, }: AssetPickerProps): import("react").JSX.Element | null;
|
|
47
|
+
/** The slice of the assets store the browser reads and drives. */
|
|
48
|
+
export type AssetPickerStore = Pick<AssetsStore, 'status' | 'errorMessage' | 'assets' | 'uploads' | 'upload' | 'landedAssetId'>;
|
|
49
|
+
/**
|
|
50
|
+
* The media browser itself — search, Upload, the grid, the drop zone — rendered inside
|
|
51
|
+
* the stage. A named component of its own (EC-588) so its markup is reachable by a
|
|
52
|
+
* node-env smoke render (the stage portal is `null` there): the file input's `accept`
|
|
53
|
+
* attribute and the grid's filter are pinned against the field's `accept`.
|
|
54
|
+
*/
|
|
55
|
+
export declare function AssetPickerBrowser({ store, value, onOpenChange, onChange, onChangeMany, multiple, accept, }: Omit<AssetPickerProps, 'open'> & {
|
|
56
|
+
store: AssetPickerStore;
|
|
57
|
+
}): import("react").JSX.Element;
|
|
58
|
+
/**
|
|
59
|
+
* The visible notice for files an upload path refused against the field's `accept`
|
|
60
|
+
* (EC-301 → EC-588): named, never silently dropped. Shared by the field's drop zone and
|
|
61
|
+
* the picker, which apply the same rule. Renders nothing when nothing was refused.
|
|
62
|
+
*/
|
|
63
|
+
export declare function AssetRejectedNotice({ rejected, accept, }: {
|
|
64
|
+
rejected: readonly string[];
|
|
65
|
+
accept: readonly string[] | undefined;
|
|
37
66
|
}): import("react").JSX.Element | null;
|
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { AlertTriangle, Check, ImageIcon, Search, Upload } from 'lucide-react';
|
|
3
|
-
import { useEffect,
|
|
3
|
+
import { useEffect, useRef, useState } from 'react';
|
|
4
|
+
import { assetAcceptAttr, describeAccept } from '@elytracms/core/cms-core';
|
|
4
5
|
import { Button, Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, ExpandableSurface, Input, Row, Spacer, Text, } from '@elytracms/studio/ui';
|
|
5
6
|
import { cn } from '@elytracms/studio/lib/utils';
|
|
6
7
|
import { translate } from '@elytracms/studio/lib/i18n';
|
|
7
8
|
import { AssetThumb } from '../assets/asset-thumb.js';
|
|
8
9
|
import { AssetsProvider, useAssets, useOptionalAssets } from '../assets/assets-store.js';
|
|
9
10
|
import { useCollectionView } from '../collection-view/collection-view-context.js';
|
|
10
|
-
import { ASSET_PICKER_STAGE_PRESET, commitPickerSelection, commitPickerSelectionMany, uploadBatchProgress, visiblePickerAssets, } from './asset-picker-core.js';
|
|
11
|
+
import { ASSET_PICKER_STAGE_PRESET, commitPickerSelection, commitPickerSelectionMany, splitByAccept, uploadBatchProgress, visiblePickerAssets, } from './asset-picker-core.js';
|
|
11
12
|
/**
|
|
12
13
|
* Pick an asset for a CMS `asset` field (brief §8.4, §8.6, EC-075 → EC-152).
|
|
13
14
|
* Backed by the *real* asset library (the assets store over the operations
|
|
@@ -24,14 +25,20 @@ import { ASSET_PICKER_STAGE_PRESET, commitPickerSelection, commitPickerSelection
|
|
|
24
25
|
* expanded rich-text stage toolbar it rides ABOVE that stage on the EC-392 layer
|
|
25
26
|
* stack — Escape closes the browser first, the rich-text stage stays.
|
|
26
27
|
*
|
|
27
|
-
* The component CONTRACT
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
28
|
+
* The component CONTRACT (`{ open, onOpenChange, value, accept, onChange }`) serves
|
|
29
|
+
* every call site — asset fields, rich-text image insertion, editable cells. EC-460
|
|
30
|
+
* adds an OPTIONAL multi-commit pair (`multiple` + `onChangeMany`): a `many` asset
|
|
31
|
+
* field passes both so uploading N files in ONE picker interaction attaches ALL N
|
|
32
|
+
* (the old flow committed the first upload to land and closed — the rest reached the
|
|
33
|
+
* library but never the field, silent partial data loss). Grid clicks stay
|
|
34
|
+
* single-pick-and-close in every mode.
|
|
35
|
+
*
|
|
36
|
+
* EC-588: `accept` is the field's STRUCTURED list (it was a file-input string that the
|
|
37
|
+
* core re-split — two shapes for one fact). The grid filter, the file-input attribute
|
|
38
|
+
* and the drop/upload split all derive from it, and an absent `accept` is unrestricted
|
|
39
|
+
* everywhere (the Upload dialog used to fall back to `image/*`). A field-backed caller
|
|
40
|
+
* passes `assetPickerBinding`'s output (`asset-picker-core`) rather than wiring props
|
|
41
|
+
* by hand.
|
|
35
42
|
*/
|
|
36
43
|
export function AssetPicker({ value, open, onOpenChange, onChange, onChangeMany, multiple = false, accept, }) {
|
|
37
44
|
const source = useCollectionView();
|
|
@@ -51,52 +58,69 @@ export function AssetPicker({ value, open, onOpenChange, onChange, onChangeMany,
|
|
|
51
58
|
return (_jsx(AssetsProvider, { projectId: source.projectId, children: _jsx(AssetPickerStage, { value: value, onOpenChange: onOpenChange, onChange: onChange, ...(onChangeMany ? { onChangeMany } : {}), multiple: multiple, accept: accept }) }));
|
|
52
59
|
}
|
|
53
60
|
/** The open media-browser stage over a mounted assets store. */
|
|
54
|
-
function AssetPickerStage(
|
|
61
|
+
function AssetPickerStage(props) {
|
|
55
62
|
const store = useAssets();
|
|
63
|
+
return (_jsx(ExpandableSurface, { title: translate('cms.asset.pickTitle'), closeLabel: translate('common.close'), variant: "stage", preset: ASSET_PICKER_STAGE_PRESET, onDismiss: () => props.onOpenChange(false), headerLeading: _jsx(ImageIcon, { className: "size-4 text-muted-foreground", "aria-hidden": true }), children: _jsx(AssetPickerBrowser, { store: store, ...props }) }));
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The media browser itself — search, Upload, the grid, the drop zone — rendered inside
|
|
67
|
+
* the stage. A named component of its own (EC-588) so its markup is reachable by a
|
|
68
|
+
* node-env smoke render (the stage portal is `null` there): the file input's `accept`
|
|
69
|
+
* attribute and the grid's filter are pinned against the field's `accept`.
|
|
70
|
+
*/
|
|
71
|
+
export function AssetPickerBrowser({ store, value, onOpenChange, onChange, onChangeMany, multiple = false, accept, }) {
|
|
56
72
|
// Fresh per open: the picker unmounts entirely while closed.
|
|
57
73
|
const [query, setQuery] = useState('');
|
|
58
74
|
const [dragging, setDragging] = useState(false);
|
|
75
|
+
// Names of files a drop/upload refused against the field's `accept` (EC-588) — shown
|
|
76
|
+
// as a visible notice and never uploaded. Cleared by the next upload attempt.
|
|
77
|
+
const [rejected, setRejected] = useState([]);
|
|
59
78
|
const fileInputRef = useRef(null);
|
|
60
|
-
// The active upload BATCH (EC-460):
|
|
61
|
-
//
|
|
62
|
-
// batch (the `upload()` API returns nothing — the library diff is the signal).
|
|
79
|
+
// The active upload BATCH (EC-460): exactly the upload ids this interaction started
|
|
80
|
+
// (EC-588 A7), so the effect below attaches this batch's uploads and nothing else.
|
|
63
81
|
const pendingRef = useRef(null);
|
|
64
82
|
// Drag depth (EC-301): keeps the drop overlay steady as the pointer crosses
|
|
65
83
|
// child boundaries — the same per-element dragenter/dragleave flicker the field
|
|
66
84
|
// fixes. Only hide when the count returns to zero.
|
|
67
85
|
const dragDepth = useRef(0);
|
|
68
86
|
const assets = visiblePickerAssets(store.assets, query, accept);
|
|
69
|
-
const libraryIds = useMemo(() => store.assets.map((a) => a.id), [store.assets]);
|
|
70
|
-
// Uploads still running (failed entries are terminal — they stay in the queue
|
|
71
|
-
// for retry, and must not keep a batch waiting forever).
|
|
72
|
-
const uploadsInFlight = store.uploads.filter((u) => u.state.phase !== 'failed').length;
|
|
73
87
|
// Auto-select what an in-picker upload added, then close. A `many` consumer
|
|
74
88
|
// (multiple + onChangeMany) waits for the batch to SETTLE and commits every
|
|
75
89
|
// added id — uploading 2 files attaches 2 (EC-460); a single consumer keeps
|
|
76
|
-
// the first-to-land commit.
|
|
90
|
+
// the first-to-land commit. Only uploads whose record satisfies `accept` commit.
|
|
77
91
|
useEffect(() => {
|
|
78
92
|
const batch = pendingRef.current;
|
|
79
93
|
if (!batch)
|
|
80
94
|
return;
|
|
81
|
-
const progress = uploadBatchProgress(batch,
|
|
95
|
+
const progress = uploadBatchProgress(batch, store, accept);
|
|
82
96
|
if (multiple && onChangeMany) {
|
|
83
|
-
if (!progress.settled
|
|
97
|
+
if (!progress.settled)
|
|
84
98
|
return;
|
|
85
99
|
pendingRef.current = null;
|
|
86
|
-
|
|
100
|
+
if (progress.added.length > 0) {
|
|
101
|
+
commitPickerSelectionMany(progress.added, { onChangeMany, onOpenChange });
|
|
102
|
+
}
|
|
87
103
|
return;
|
|
88
104
|
}
|
|
89
105
|
const picked = progress.added[0] ?? null;
|
|
90
|
-
if (picked === null)
|
|
106
|
+
if (picked === null) {
|
|
107
|
+
if (progress.settled)
|
|
108
|
+
pendingRef.current = null; // everything failed — disarm
|
|
91
109
|
return;
|
|
110
|
+
}
|
|
92
111
|
pendingRef.current = null;
|
|
93
112
|
commitPickerSelection(picked, { onChange, onOpenChange });
|
|
94
|
-
}, [
|
|
113
|
+
}, [store, accept, multiple, onChange, onChangeMany, onOpenChange]);
|
|
95
114
|
function handleUpload(files) {
|
|
96
115
|
if (files.length === 0)
|
|
97
116
|
return;
|
|
98
|
-
|
|
99
|
-
|
|
117
|
+
// EC-588: the drop rule — the same split the field's drop zone uses. A drop
|
|
118
|
+
// bypasses the dialog's soft filter; refused files are named, never uploaded.
|
|
119
|
+
const { accepted, rejected: refused } = splitByAccept(files, accept);
|
|
120
|
+
setRejected(refused);
|
|
121
|
+
if (accepted.length === 0)
|
|
122
|
+
return;
|
|
123
|
+
pendingRef.current = { uploadIds: store.upload(accepted) };
|
|
100
124
|
}
|
|
101
125
|
// The stage portals to document.body, but React synthetic events still bubble up
|
|
102
126
|
// the COMPONENT tree — and this picker is rendered as a child of the asset field,
|
|
@@ -129,10 +153,25 @@ function AssetPickerStage({ value, onOpenChange, onChange, onChangeMany, multipl
|
|
|
129
153
|
setDragging(false);
|
|
130
154
|
handleUpload(Array.from(e.dataTransfer.files));
|
|
131
155
|
}
|
|
132
|
-
return (
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
156
|
+
return (_jsxs("div", { className: "relative flex min-h-0 flex-1 flex-col gap-3 p-4", onDragEnter: onDragEnter, onDragOver: onDragOver, onDragLeave: onDragLeave, onDrop: onDrop, children: [_jsxs(Row, { gap: "2", align: "center", children: [_jsxs("span", { className: "relative flex-1", children: [_jsx(Search, { className: "pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" }), _jsx(Input, { autoFocus: true, value: query, onChange: (e) => setQuery(e.target.value), placeholder: translate('cms.asset.searchPlaceholder'), className: "pl-8", "data-testid": "asset-picker-search" })] }), _jsxs(Button, { variant: "outline", size: "sm", onClick: () => fileInputRef.current?.click(), children: [_jsx(Upload, {}), " ", translate('common.upload')] }), _jsx("input", { ref: fileInputRef, type: "file", multiple: true, accept: assetAcceptAttr(accept), className: "hidden", "data-testid": "asset-picker-file-input", onChange: (e) => {
|
|
157
|
+
handleUpload(Array.from(e.target.files ?? []));
|
|
158
|
+
e.target.value = '';
|
|
159
|
+
} })] }), _jsx(AssetRejectedNotice, { rejected: rejected, accept: accept }), _jsx("div", { className: "grid min-h-0 flex-1 auto-rows-min grid-cols-2 gap-2 overflow-y-auto sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5", "data-testid": "asset-picker-grid", children: store.status === 'loading' ? (_jsx(Text, { size: "sm", tone: "muted", className: "col-span-full p-3", children: translate('cms.asset.loading') })) : store.status === 'error' ? (_jsxs(Row, { gap: "2", className: "col-span-full p-3", "data-testid": "asset-picker-error", children: [_jsx(AlertTriangle, { className: "size-4 text-destructive" }), _jsx(Text, { size: "sm", tone: "muted", children: store.errorMessage ?? translate('cms.asset.loadError') })] })) : assets.length === 0 ? (_jsx(Text, { size: "sm", tone: "muted", className: "col-span-full p-3", children: query.trim() ? translate('cms.asset.noMatches') : translate('cms.asset.empty') })) : (assets.map((asset) => (_jsx(AssetPickerCard, { asset: asset, selected: asset.id === value, onPick: () => commitPickerSelection(asset.id, { onChange, onOpenChange }) }, asset.id)))) }), _jsxs(Row, { gap: "2", children: [_jsx(Spacer, {}), value ? (_jsx(Button, { variant: "ghost", size: "sm", onClick: () => commitPickerSelection(null, { onChange, onOpenChange }), children: translate('common.clear') })) : null] }), dragging ? (_jsx("div", { className: "pointer-events-none absolute inset-0 z-10 grid place-items-center rounded-lg border-2 border-dashed border-primary bg-background/85", children: _jsxs(Row, { gap: "2", align: "center", children: [_jsx(Upload, { className: "size-5 text-primary" }), _jsx(Text, { className: "font-medium", children: translate('cms.asset.dropToUpload') })] }) })) : null] }));
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The visible notice for files an upload path refused against the field's `accept`
|
|
163
|
+
* (EC-301 → EC-588): named, never silently dropped. Shared by the field's drop zone and
|
|
164
|
+
* the picker, which apply the same rule. Renders nothing when nothing was refused.
|
|
165
|
+
*/
|
|
166
|
+
export function AssetRejectedNotice({ rejected, accept, }) {
|
|
167
|
+
if (rejected.length === 0)
|
|
168
|
+
return null;
|
|
169
|
+
return (_jsxs(Row, { gap: "2", align: "center", "data-testid": "asset-rejected-notice", children: [_jsx(AlertTriangle, { className: "size-4 shrink-0 text-warning" }), _jsx(Text, { size: "xs", tone: "muted", children: rejected.length === 1
|
|
170
|
+
? translate('cms.asset.rejected.one', { name: rejected[0], types: describeAccept(accept) })
|
|
171
|
+
: translate('cms.asset.rejected.other', {
|
|
172
|
+
count: rejected.length,
|
|
173
|
+
types: describeAccept(accept),
|
|
174
|
+
}) })] }));
|
|
136
175
|
}
|
|
137
176
|
/** One selectable asset: EC-400 thumb tile + title/filename + alt text. The
|
|
138
177
|
* internal asset id is intentionally not shown — it's noise to editors (EC-301). */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"asset-picker.js","sourceRoot":"","sources":["../../../src/components/cms/asset-picker.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAC9E,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAE5D,OAAO,EACL,MAAM,EACN,MAAM,EACN,aAAa,EACb,iBAAiB,EACjB,YAAY,EACZ,WAAW,EACX,iBAAiB,EACjB,KAAK,EACL,GAAG,EACH,MAAM,EACN,IAAI,GACL,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,EAAE,EAAE,MAAM,6BAA6B,CAAA;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,4BAA4B,CAAA;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAA;AAClD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AACrF,OAAO,EAAE,iBAAiB,EAAE,MAAM,4CAA4C,CAAA;AAC9E,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,yBAAyB,EACzB,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,qBAAqB,CAAA;AAG5B;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,WAAW,CAAC,EAC1B,KAAK,EACL,IA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IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,SAAS,EAAC,UAAU,YACvE,KAAK,CAAC,GAAG,IAAI,SAAS,CAAC,qBAAqB,CAAC,GACzC,IACA,CACV,CAAA;AACH,CAAC","sourcesContent":["import { AlertTriangle, Check, ImageIcon, Search, Upload } from 'lucide-react'\nimport { useEffect, useMemo, useRef, useState } from 'react'\nimport type { AssetRecord } from '@elytracms/core/persistence'\nimport {\n Button,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n ExpandableSurface,\n Input,\n Row,\n Spacer,\n Text,\n} from '@elytracms/studio/ui'\nimport { cn } from '@elytracms/studio/lib/utils'\nimport { translate } from '@elytracms/studio/lib/i18n'\nimport { AssetThumb } from '../assets/asset-thumb'\nimport { AssetsProvider, useAssets, useOptionalAssets } from '../assets/assets-store'\nimport { useCollectionView } from '../collection-view/collection-view-context'\nimport {\n ASSET_PICKER_STAGE_PRESET,\n commitPickerSelection,\n commitPickerSelectionMany,\n uploadBatchProgress,\n visiblePickerAssets,\n} from './asset-picker-core'\nimport type { UploadBatch } from './asset-picker-core'\n\n/**\n * Pick an asset for a CMS `asset` field (brief §8.4, §8.6, EC-075 → EC-152).\n * Backed by the *real* asset library (the assets store over the operations\n * client) — the same records the Assets section lists — not by fixture\n * documents. Selecting stores the asset id on the document field.\n *\n * EC-432 (AD-C): the picker is a real MEDIA BROWSER on the {@link ExpandableSurface}\n * `stage` (`grid` preset — `min(1240px, 94vw)`, near-full height), replacing the\n * old `max-w-md` (448px) Dialog. It reuses the shipped assets-rail machinery: the\n * assets store, the EC-152 search, the EC-400 thumb tile ({@link AssetThumb}), and\n * the upload-then-select path. It is a SELECTION browser, not a form — click = pick\n * (fires `onChange`, closes) plus the shipped clear/cancel affordances; the\n * forms-never-modal rule governs document forms and is untouched. Opened from the\n * expanded rich-text stage toolbar it rides ABOVE that stage on the EC-392 layer\n * stack — Escape closes the browser first, the rich-text stage stays.\n *\n * The component CONTRACT is unchanged (`{ open, onOpenChange, value, accept,\n * onChange }`) so every call site — asset fields, rich-text image insertion,\n * editable cells — works with zero edits, just a bigger surface. EC-460 adds an\n * OPTIONAL multi-commit pair (`multiple` + `onChangeMany`): a `many` asset field\n * passes both so uploading N files in ONE picker interaction attaches ALL N\n * (the old flow committed the first upload to land and closed — the rest\n * reached the library but never the field, silent partial data loss). Grid\n * clicks stay single-pick-and-close in every mode.\n */\nexport function AssetPicker({\n value,\n open,\n onOpenChange,\n onChange,\n onChangeMany,\n multiple = false,\n accept,\n}: {\n value: string | null\n open: boolean\n onOpenChange: (open: boolean) => void\n onChange: (assetId: string | null) => void\n /** EC-460: commit a whole settled upload batch (a `many` field passes this). */\n onChangeMany?: (assetIds: string[]) => void\n /** Whether the consuming field holds many assets (enables batch commit). */\n multiple?: boolean\n /** The file input's `accept` attribute for in-picker upload + grid filter (field-derived). */\n accept?: string\n}) {\n const source = useCollectionView()\n const ambient = useOptionalAssets()\n // Mount nothing while closed: the self-provided assets store would\n // otherwise load the library eagerly for every asset field on the form.\n if (!open) return null\n if (ambient) {\n return (\n <AssetPickerStage\n value={value}\n onOpenChange={onOpenChange}\n onChange={onChange}\n {...(onChangeMany ? { onChangeMany } : {})}\n multiple={multiple}\n accept={accept}\n />\n )\n }\n if (source.projectId === undefined) {\n // No project scope (fixture-only CMS session): the library is\n // unreachable — say so instead of silently showing nothing.\n return (\n <Dialog open onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-md\">\n <DialogHeader>\n <DialogTitle>{translate('cms.asset.pickTitle')}</DialogTitle>\n <DialogDescription>{translate('cms.asset.pickDescription')}</DialogDescription>\n </DialogHeader>\n <Row gap=\"2\" data-testid=\"asset-picker-no-project\">\n <AlertTriangle className=\"size-4 text-warning\" />\n <Text size=\"sm\" tone=\"muted\">\n {translate('cms.asset.noProject')}\n </Text>\n </Row>\n </DialogContent>\n </Dialog>\n )\n }\n return (\n <AssetsProvider projectId={source.projectId}>\n <AssetPickerStage\n value={value}\n onOpenChange={onOpenChange}\n onChange={onChange}\n {...(onChangeMany ? { onChangeMany } : {})}\n multiple={multiple}\n accept={accept}\n />\n </AssetsProvider>\n )\n}\n\n/** The open media-browser stage over a mounted assets store. */\nfunction AssetPickerStage({\n value,\n onOpenChange,\n onChange,\n onChangeMany,\n multiple = false,\n accept,\n}: {\n value: string | null\n onOpenChange: (open: boolean) => void\n onChange: (assetId: string | null) => void\n onChangeMany?: (assetIds: string[]) => void\n multiple?: boolean\n accept?: string\n}) {\n const store = useAssets()\n // Fresh per open: the picker unmounts entirely while closed.\n const [query, setQuery] = useState('')\n const [dragging, setDragging] = useState(false)\n const fileInputRef = useRef<HTMLInputElement>(null)\n // The active upload BATCH (EC-460): pre-upload library snapshot + how many\n // files the interaction submitted, so the effect below can attach the WHOLE\n // batch (the `upload()` API returns nothing — the library diff is the signal).\n const pendingRef = useRef<UploadBatch | null>(null)\n // Drag depth (EC-301): keeps the drop overlay steady as the pointer crosses\n // child boundaries — the same per-element dragenter/dragleave flicker the field\n // fixes. Only hide when the count returns to zero.\n const dragDepth = useRef(0)\n const assets = visiblePickerAssets(store.assets, query, accept)\n const libraryIds = useMemo(() => store.assets.map((a) => a.id), [store.assets])\n // Uploads still running (failed entries are terminal — they stay in the queue\n // for retry, and must not keep a batch waiting forever).\n const uploadsInFlight = store.uploads.filter((u) => u.state.phase !== 'failed').length\n\n // Auto-select what an in-picker upload added, then close. A `many` consumer\n // (multiple + onChangeMany) waits for the batch to SETTLE and commits every\n // added id — uploading 2 files attaches 2 (EC-460); a single consumer keeps\n // the first-to-land commit.\n useEffect(() => {\n const batch = pendingRef.current\n if (!batch) return\n const progress = uploadBatchProgress(batch, libraryIds, uploadsInFlight)\n if (multiple && onChangeMany) {\n if (!progress.settled || progress.added.length === 0) return\n pendingRef.current = null\n commitPickerSelectionMany(progress.added, { onChangeMany, onOpenChange })\n return\n }\n const picked = progress.added[0] ?? null\n if (picked === null) return\n pendingRef.current = null\n commitPickerSelection(picked, { onChange, onOpenChange })\n }, [libraryIds, uploadsInFlight, multiple, onChange, onChangeMany, onOpenChange])\n\n function handleUpload(files: File[]) {\n if (files.length === 0) return\n pendingRef.current = { before: new Set(libraryIds), expected: files.length }\n store.upload(files)\n }\n // The stage portals to document.body, but React synthetic events still bubble up\n // the COMPONENT tree — and this picker is rendered as a child of the asset field,\n // which has its own drag-to-upload handlers. Without stopPropagation a drop inside\n // the stage would fire BOTH the picker's and the field's `onDrop`, uploading the\n // file twice. Stop every DnD event here so the picker owns its drop entirely.\n function onDragEnter(e: React.DragEvent) {\n e.preventDefault()\n e.stopPropagation()\n dragDepth.current += 1\n if (!dragging) setDragging(true)\n }\n function onDragOver(e: React.DragEvent) {\n e.preventDefault()\n e.stopPropagation()\n }\n function onDragLeave(e: React.DragEvent) {\n e.stopPropagation()\n dragDepth.current -= 1\n if (dragDepth.current <= 0) {\n dragDepth.current = 0\n setDragging(false)\n }\n }\n function onDrop(e: React.DragEvent) {\n e.preventDefault()\n e.stopPropagation()\n dragDepth.current = 0\n setDragging(false)\n handleUpload(Array.from(e.dataTransfer.files))\n }\n\n return (\n <ExpandableSurface\n title={translate('cms.asset.pickTitle')}\n closeLabel={translate('common.close')}\n variant=\"stage\"\n preset={ASSET_PICKER_STAGE_PRESET}\n onDismiss={() => onOpenChange(false)}\n headerLeading={<ImageIcon className=\"size-4 text-muted-foreground\" aria-hidden />}\n >\n <div\n className=\"relative flex min-h-0 flex-1 flex-col gap-3 p-4\"\n onDragEnter={onDragEnter}\n onDragOver={onDragOver}\n onDragLeave={onDragLeave}\n onDrop={onDrop}\n >\n <Row gap=\"2\" align=\"center\">\n <span className=\"relative flex-1\">\n <Search className=\"pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground\" />\n <Input\n autoFocus\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n placeholder={translate('cms.asset.searchPlaceholder')}\n className=\"pl-8\"\n data-testid=\"asset-picker-search\"\n />\n </span>\n <Button variant=\"outline\" size=\"sm\" onClick={() => fileInputRef.current?.click()}>\n <Upload /> {translate('common.upload')}\n </Button>\n <input\n ref={fileInputRef}\n type=\"file\"\n multiple\n accept={accept ?? 'image/*'}\n className=\"hidden\"\n onChange={(e) => {\n handleUpload(Array.from(e.target.files ?? []))\n e.target.value = ''\n }}\n />\n </Row>\n\n <div\n className=\"grid min-h-0 flex-1 auto-rows-min grid-cols-2 gap-2 overflow-y-auto sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5\"\n data-testid=\"asset-picker-grid\"\n >\n {store.status === 'loading' ? (\n <Text size=\"sm\" tone=\"muted\" className=\"col-span-full p-3\">\n {translate('cms.asset.loading')}\n </Text>\n ) : store.status === 'error' ? (\n <Row gap=\"2\" className=\"col-span-full p-3\" data-testid=\"asset-picker-error\">\n <AlertTriangle className=\"size-4 text-destructive\" />\n <Text size=\"sm\" tone=\"muted\">\n {store.errorMessage ?? translate('cms.asset.loadError')}\n </Text>\n </Row>\n ) : assets.length === 0 ? (\n <Text size=\"sm\" tone=\"muted\" className=\"col-span-full p-3\">\n {query.trim() ? translate('cms.asset.noMatches') : translate('cms.asset.empty')}\n </Text>\n ) : (\n assets.map((asset) => (\n <AssetPickerCard\n key={asset.id}\n asset={asset}\n selected={asset.id === value}\n onPick={() => commitPickerSelection(asset.id, { onChange, onOpenChange })}\n />\n ))\n )}\n </div>\n\n <Row gap=\"2\">\n <Spacer />\n {value ? (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => commitPickerSelection(null, { onChange, onOpenChange })}\n >\n {translate('common.clear')}\n </Button>\n ) : null}\n </Row>\n\n {dragging ? (\n <div className=\"pointer-events-none absolute inset-0 z-10 grid place-items-center rounded-lg border-2 border-dashed border-primary bg-background/85\">\n <Row gap=\"2\" align=\"center\">\n <Upload className=\"size-5 text-primary\" />\n <Text className=\"font-medium\">{translate('cms.asset.dropToUpload')}</Text>\n </Row>\n </div>\n ) : null}\n </div>\n </ExpandableSurface>\n )\n}\n\n/** One selectable asset: EC-400 thumb tile + title/filename + alt text. The\n * internal asset id is intentionally not shown — it's noise to editors (EC-301). */\nfunction AssetPickerCard({\n asset,\n selected,\n onPick,\n}: {\n asset: AssetRecord\n selected: boolean\n onPick: () => void\n}) {\n return (\n <button\n type=\"button\"\n onClick={onPick}\n className={cn(\n 'flex flex-col gap-1.5 rounded-lg border p-2 text-left transition-colors',\n selected ? 'border-primary bg-primary/5' : 'border-border hover:bg-muted',\n )}\n data-testid=\"asset-picker-card\"\n aria-pressed={selected}\n >\n <span className=\"relative block\">\n <AssetThumb record={asset} className=\"aspect-video w-full\" />\n {selected ? (\n <span className=\"absolute right-1 top-1 grid size-5 place-items-center rounded-full bg-primary text-primary-foreground shadow\">\n <Check className=\"size-3\" />\n </span>\n ) : null}\n </span>\n <Text size=\"xs\" className=\"min-w-0 truncate font-medium\">\n {asset.title ?? asset.filename}\n </Text>\n <Text size=\"xs\" tone={asset.alt ? 'muted' : 'subtle'} className=\"truncate\">\n {asset.alt ?? translate('cms.asset.noAltText')}\n </Text>\n </button>\n )\n}\n"]}
|
|
1
|
+
{"version":3,"file":"asset-picker.js","sourceRoot":"","sources":["../../../src/components/cms/asset-picker.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AAC9E,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AACnD,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAA;AAE1E,OAAO,EACL,MAAM,EACN,MAAM,EACN,aAAa,EACb,iBAAiB,EACjB,YAAY,EACZ,WAAW,EACX,iBAAiB,EACjB,KAAK,EACL,GAAG,EACH,MAAM,EACN,IAAI,GACL,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,EAAE,EAAE,MAAM,6BAA6B,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,GAAG,GACvB,CACR,CAAC,CAAC,CAAC,IAAI,IACH,EACP,KAAC,IAAI,IAAC,IAAI,EAAC,IAAI,EAAC,SAAS,EAAC,8BAA8B,YACrD,KAAK,CAAC,KAAK,IAAI,KAAK,CAAC,QAAQ,GACzB,EACP,KAAC,IAAI,IAAC,IAAI,EAAC,IAAI,EAAC,IAAI,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,SAAS,EAAC,UAAU,YACvE,KAAK,CAAC,GAAG,IAAI,SAAS,CAAC,qBAAqB,CAAC,GACzC,IACA,CACV,CAAA;AACH,CAAC","sourcesContent":["import { AlertTriangle, Check, ImageIcon, Search, Upload } from 'lucide-react'\nimport { useEffect, useRef, useState } from 'react'\nimport { assetAcceptAttr, describeAccept } from '@elytracms/core/cms-core'\nimport type { AssetRecord } from '@elytracms/core/persistence'\nimport {\n Button,\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n ExpandableSurface,\n Input,\n Row,\n Spacer,\n Text,\n} from '@elytracms/studio/ui'\nimport { cn } from '@elytracms/studio/lib/utils'\nimport { translate } from '@elytracms/studio/lib/i18n'\nimport { AssetThumb } from '../assets/asset-thumb'\nimport { AssetsProvider, useAssets, useOptionalAssets } from '../assets/assets-store'\nimport type { AssetsStore } from '../assets/assets-store'\nimport { useCollectionView } from '../collection-view/collection-view-context'\nimport {\n ASSET_PICKER_STAGE_PRESET,\n commitPickerSelection,\n commitPickerSelectionMany,\n splitByAccept,\n uploadBatchProgress,\n visiblePickerAssets,\n} from './asset-picker-core'\nimport type { UploadBatch } from './asset-picker-core'\n\n/** The picker's props — see {@link AssetPicker}. */\nexport interface AssetPickerProps {\n value: string | null\n open: boolean\n onOpenChange: (open: boolean) => void\n onChange: (assetId: string | null) => void\n /** EC-460: commit a whole settled upload batch (a `many` field passes this). */\n onChangeMany?: (assetIds: string[]) => void\n /** Whether the consuming field holds many assets (enables batch commit). */\n multiple?: boolean\n /** The field's `accept` list (EC-588) — absent means any file. */\n accept?: readonly string[]\n}\n\n/**\n * Pick an asset for a CMS `asset` field (brief §8.4, §8.6, EC-075 → EC-152).\n * Backed by the *real* asset library (the assets store over the operations\n * client) — the same records the Assets section lists — not by fixture\n * documents. Selecting stores the asset id on the document field.\n *\n * EC-432 (AD-C): the picker is a real MEDIA BROWSER on the {@link ExpandableSurface}\n * `stage` (`grid` preset — `min(1240px, 94vw)`, near-full height), replacing the\n * old `max-w-md` (448px) Dialog. It reuses the shipped assets-rail machinery: the\n * assets store, the EC-152 search, the EC-400 thumb tile ({@link AssetThumb}), and\n * the upload-then-select path. It is a SELECTION browser, not a form — click = pick\n * (fires `onChange`, closes) plus the shipped clear/cancel affordances; the\n * forms-never-modal rule governs document forms and is untouched. Opened from the\n * expanded rich-text stage toolbar it rides ABOVE that stage on the EC-392 layer\n * stack — Escape closes the browser first, the rich-text stage stays.\n *\n * The component CONTRACT (`{ open, onOpenChange, value, accept, onChange }`) serves\n * every call site — asset fields, rich-text image insertion, editable cells. EC-460\n * adds an OPTIONAL multi-commit pair (`multiple` + `onChangeMany`): a `many` asset\n * field passes both so uploading N files in ONE picker interaction attaches ALL N\n * (the old flow committed the first upload to land and closed — the rest reached the\n * library but never the field, silent partial data loss). Grid clicks stay\n * single-pick-and-close in every mode.\n *\n * EC-588: `accept` is the field's STRUCTURED list (it was a file-input string that the\n * core re-split — two shapes for one fact). The grid filter, the file-input attribute\n * and the drop/upload split all derive from it, and an absent `accept` is unrestricted\n * everywhere (the Upload dialog used to fall back to `image/*`). A field-backed caller\n * passes `assetPickerBinding`'s output (`asset-picker-core`) rather than wiring props\n * by hand.\n */\nexport function AssetPicker({\n value,\n open,\n onOpenChange,\n onChange,\n onChangeMany,\n multiple = false,\n accept,\n}: AssetPickerProps) {\n const source = useCollectionView()\n const ambient = useOptionalAssets()\n // Mount nothing while closed: the self-provided assets store would\n // otherwise load the library eagerly for every asset field on the form.\n if (!open) return null\n if (ambient) {\n return (\n <AssetPickerStage\n value={value}\n onOpenChange={onOpenChange}\n onChange={onChange}\n {...(onChangeMany ? { onChangeMany } : {})}\n multiple={multiple}\n accept={accept}\n />\n )\n }\n if (source.projectId === undefined) {\n // No project scope (fixture-only CMS session): the library is\n // unreachable — say so instead of silently showing nothing.\n return (\n <Dialog open onOpenChange={onOpenChange}>\n <DialogContent className=\"max-w-md\">\n <DialogHeader>\n <DialogTitle>{translate('cms.asset.pickTitle')}</DialogTitle>\n <DialogDescription>{translate('cms.asset.pickDescription')}</DialogDescription>\n </DialogHeader>\n <Row gap=\"2\" data-testid=\"asset-picker-no-project\">\n <AlertTriangle className=\"size-4 text-warning\" />\n <Text size=\"sm\" tone=\"muted\">\n {translate('cms.asset.noProject')}\n </Text>\n </Row>\n </DialogContent>\n </Dialog>\n )\n }\n return (\n <AssetsProvider projectId={source.projectId}>\n <AssetPickerStage\n value={value}\n onOpenChange={onOpenChange}\n onChange={onChange}\n {...(onChangeMany ? { onChangeMany } : {})}\n multiple={multiple}\n accept={accept}\n />\n </AssetsProvider>\n )\n}\n\n/** The open media-browser stage over a mounted assets store. */\nfunction AssetPickerStage(props: Omit<AssetPickerProps, 'open'>) {\n const store = useAssets()\n return (\n <ExpandableSurface\n title={translate('cms.asset.pickTitle')}\n closeLabel={translate('common.close')}\n variant=\"stage\"\n preset={ASSET_PICKER_STAGE_PRESET}\n onDismiss={() => props.onOpenChange(false)}\n headerLeading={<ImageIcon className=\"size-4 text-muted-foreground\" aria-hidden />}\n >\n <AssetPickerBrowser store={store} {...props} />\n </ExpandableSurface>\n )\n}\n\n/** The slice of the assets store the browser reads and drives. */\nexport type AssetPickerStore = Pick<\n AssetsStore,\n 'status' | 'errorMessage' | 'assets' | 'uploads' | 'upload' | 'landedAssetId'\n>\n\n/**\n * The media browser itself — search, Upload, the grid, the drop zone — rendered inside\n * the stage. A named component of its own (EC-588) so its markup is reachable by a\n * node-env smoke render (the stage portal is `null` there): the file input's `accept`\n * attribute and the grid's filter are pinned against the field's `accept`.\n */\nexport function AssetPickerBrowser({\n store,\n value,\n onOpenChange,\n onChange,\n onChangeMany,\n multiple = false,\n accept,\n}: Omit<AssetPickerProps, 'open'> & { store: AssetPickerStore }) {\n // Fresh per open: the picker unmounts entirely while closed.\n const [query, setQuery] = useState('')\n const [dragging, setDragging] = useState(false)\n // Names of files a drop/upload refused against the field's `accept` (EC-588) — shown\n // as a visible notice and never uploaded. Cleared by the next upload attempt.\n const [rejected, setRejected] = useState<string[]>([])\n const fileInputRef = useRef<HTMLInputElement>(null)\n // The active upload BATCH (EC-460): exactly the upload ids this interaction started\n // (EC-588 A7), so the effect below attaches this batch's uploads and nothing else.\n const pendingRef = useRef<UploadBatch | null>(null)\n // Drag depth (EC-301): keeps the drop overlay steady as the pointer crosses\n // child boundaries — the same per-element dragenter/dragleave flicker the field\n // fixes. Only hide when the count returns to zero.\n const dragDepth = useRef(0)\n const assets = visiblePickerAssets(store.assets, query, accept)\n\n // Auto-select what an in-picker upload added, then close. A `many` consumer\n // (multiple + onChangeMany) waits for the batch to SETTLE and commits every\n // added id — uploading 2 files attaches 2 (EC-460); a single consumer keeps\n // the first-to-land commit. Only uploads whose record satisfies `accept` commit.\n useEffect(() => {\n const batch = pendingRef.current\n if (!batch) return\n const progress = uploadBatchProgress(batch, store, accept)\n if (multiple && onChangeMany) {\n if (!progress.settled) return\n pendingRef.current = null\n if (progress.added.length > 0) {\n commitPickerSelectionMany(progress.added, { onChangeMany, onOpenChange })\n }\n return\n }\n const picked = progress.added[0] ?? null\n if (picked === null) {\n if (progress.settled) pendingRef.current = null // everything failed — disarm\n return\n }\n pendingRef.current = null\n commitPickerSelection(picked, { onChange, onOpenChange })\n }, [store, accept, multiple, onChange, onChangeMany, onOpenChange])\n\n function handleUpload(files: File[]) {\n if (files.length === 0) return\n // EC-588: the drop rule — the same split the field's drop zone uses. A drop\n // bypasses the dialog's soft filter; refused files are named, never uploaded.\n const { accepted, rejected: refused } = splitByAccept(files, accept)\n setRejected(refused)\n if (accepted.length === 0) return\n pendingRef.current = { uploadIds: store.upload(accepted) }\n }\n // The stage portals to document.body, but React synthetic events still bubble up\n // the COMPONENT tree — and this picker is rendered as a child of the asset field,\n // which has its own drag-to-upload handlers. Without stopPropagation a drop inside\n // the stage would fire BOTH the picker's and the field's `onDrop`, uploading the\n // file twice. Stop every DnD event here so the picker owns its drop entirely.\n function onDragEnter(e: React.DragEvent) {\n e.preventDefault()\n e.stopPropagation()\n dragDepth.current += 1\n if (!dragging) setDragging(true)\n }\n function onDragOver(e: React.DragEvent) {\n e.preventDefault()\n e.stopPropagation()\n }\n function onDragLeave(e: React.DragEvent) {\n e.stopPropagation()\n dragDepth.current -= 1\n if (dragDepth.current <= 0) {\n dragDepth.current = 0\n setDragging(false)\n }\n }\n function onDrop(e: React.DragEvent) {\n e.preventDefault()\n e.stopPropagation()\n dragDepth.current = 0\n setDragging(false)\n handleUpload(Array.from(e.dataTransfer.files))\n }\n\n return (\n <div\n className=\"relative flex min-h-0 flex-1 flex-col gap-3 p-4\"\n onDragEnter={onDragEnter}\n onDragOver={onDragOver}\n onDragLeave={onDragLeave}\n onDrop={onDrop}\n >\n <Row gap=\"2\" align=\"center\">\n <span className=\"relative flex-1\">\n <Search className=\"pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground\" />\n <Input\n autoFocus\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n placeholder={translate('cms.asset.searchPlaceholder')}\n className=\"pl-8\"\n data-testid=\"asset-picker-search\"\n />\n </span>\n <Button variant=\"outline\" size=\"sm\" onClick={() => fileInputRef.current?.click()}>\n <Upload /> {translate('common.upload')}\n </Button>\n <input\n ref={fileInputRef}\n type=\"file\"\n multiple\n accept={assetAcceptAttr(accept)}\n className=\"hidden\"\n data-testid=\"asset-picker-file-input\"\n onChange={(e) => {\n handleUpload(Array.from(e.target.files ?? []))\n e.target.value = ''\n }}\n />\n </Row>\n\n <AssetRejectedNotice rejected={rejected} accept={accept} />\n\n <div\n className=\"grid min-h-0 flex-1 auto-rows-min grid-cols-2 gap-2 overflow-y-auto sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5\"\n data-testid=\"asset-picker-grid\"\n >\n {store.status === 'loading' ? (\n <Text size=\"sm\" tone=\"muted\" className=\"col-span-full p-3\">\n {translate('cms.asset.loading')}\n </Text>\n ) : store.status === 'error' ? (\n <Row gap=\"2\" className=\"col-span-full p-3\" data-testid=\"asset-picker-error\">\n <AlertTriangle className=\"size-4 text-destructive\" />\n <Text size=\"sm\" tone=\"muted\">\n {store.errorMessage ?? translate('cms.asset.loadError')}\n </Text>\n </Row>\n ) : assets.length === 0 ? (\n <Text size=\"sm\" tone=\"muted\" className=\"col-span-full p-3\">\n {query.trim() ? translate('cms.asset.noMatches') : translate('cms.asset.empty')}\n </Text>\n ) : (\n assets.map((asset) => (\n <AssetPickerCard\n key={asset.id}\n asset={asset}\n selected={asset.id === value}\n onPick={() => commitPickerSelection(asset.id, { onChange, onOpenChange })}\n />\n ))\n )}\n </div>\n\n <Row gap=\"2\">\n <Spacer />\n {value ? (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => commitPickerSelection(null, { onChange, onOpenChange })}\n >\n {translate('common.clear')}\n </Button>\n ) : null}\n </Row>\n\n {dragging ? (\n <div className=\"pointer-events-none absolute inset-0 z-10 grid place-items-center rounded-lg border-2 border-dashed border-primary bg-background/85\">\n <Row gap=\"2\" align=\"center\">\n <Upload className=\"size-5 text-primary\" />\n <Text className=\"font-medium\">{translate('cms.asset.dropToUpload')}</Text>\n </Row>\n </div>\n ) : null}\n </div>\n )\n}\n\n/**\n * The visible notice for files an upload path refused against the field's `accept`\n * (EC-301 → EC-588): named, never silently dropped. Shared by the field's drop zone and\n * the picker, which apply the same rule. Renders nothing when nothing was refused.\n */\nexport function AssetRejectedNotice({\n rejected,\n accept,\n}: {\n rejected: readonly string[]\n accept: readonly string[] | undefined\n}) {\n if (rejected.length === 0) return null\n return (\n <Row gap=\"2\" align=\"center\" data-testid=\"asset-rejected-notice\">\n <AlertTriangle className=\"size-4 shrink-0 text-warning\" />\n <Text size=\"xs\" tone=\"muted\">\n {rejected.length === 1\n ? translate('cms.asset.rejected.one', { name: rejected[0]!, types: describeAccept(accept) })\n : translate('cms.asset.rejected.other', {\n count: rejected.length,\n types: describeAccept(accept),\n })}\n </Text>\n </Row>\n )\n}\n\n/** One selectable asset: EC-400 thumb tile + title/filename + alt text. The\n * internal asset id is intentionally not shown — it's noise to editors (EC-301). */\nfunction AssetPickerCard({\n asset,\n selected,\n onPick,\n}: {\n asset: AssetRecord\n selected: boolean\n onPick: () => void\n}) {\n return (\n <button\n type=\"button\"\n onClick={onPick}\n className={cn(\n 'flex flex-col gap-1.5 rounded-lg border p-2 text-left transition-colors',\n selected ? 'border-primary bg-primary/5' : 'border-border hover:bg-muted',\n )}\n data-testid=\"asset-picker-card\"\n aria-pressed={selected}\n >\n <span className=\"relative block\">\n <AssetThumb record={asset} className=\"aspect-video w-full\" />\n {selected ? (\n <span className=\"absolute right-1 top-1 grid size-5 place-items-center rounded-full bg-primary text-primary-foreground shadow\">\n <Check className=\"size-3\" />\n </span>\n ) : null}\n </span>\n <Text size=\"xs\" className=\"min-w-0 truncate font-medium\">\n {asset.title ?? asset.filename}\n </Text>\n <Text size=\"xs\" tone={asset.alt ? 'muted' : 'subtle'} className=\"truncate\">\n {asset.alt ?? translate('cms.asset.noAltText')}\n </Text>\n </button>\n )\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { CmsDocument, CmsValidationIssue, CollectionDef, CollectionRegistry, DocumentRef, FieldDef, Locale, LocaleConfig } from '@elytracms/core/cms-core';
|
|
2
|
+
import type { FindAsset } from './gate-validation.js';
|
|
2
3
|
import type { OperationError, OperationResult } from '@elytracms/studio/lib/operations';
|
|
3
4
|
/**
|
|
4
5
|
* Inline cell editing for the collection table (EC-168) — the pure half.
|
|
@@ -82,7 +83,8 @@ export interface CellCommitInput {
|
|
|
82
83
|
*/
|
|
83
84
|
export interface CellEditOracles {
|
|
84
85
|
isPublished?: (ref: DocumentRef) => boolean;
|
|
85
|
-
|
|
86
|
+
/** The asset-library oracle (EC-588) — record lookup; absent = no asset checks. */
|
|
87
|
+
findAsset?: FindAsset;
|
|
86
88
|
}
|
|
87
89
|
export interface CellCommitContext extends CellEditOracles {
|
|
88
90
|
registry: CollectionRegistry;
|
|
@@ -95,7 +95,7 @@ export function cellEditIssues(registry, documents, localeConfig, collection, ne
|
|
|
95
95
|
store,
|
|
96
96
|
localeConfig,
|
|
97
97
|
isPublished: oracles.isPublished ?? (() => false),
|
|
98
|
-
...(oracles.
|
|
98
|
+
...(oracles.findAsset ? { findAsset: oracles.findAsset } : {}),
|
|
99
99
|
}));
|
|
100
100
|
const localized = isFieldLocalized(collection, fieldName);
|
|
101
101
|
return issues.filter((issue) => {
|
|
@@ -122,7 +122,7 @@ export async function commitCellEdit(context, input) {
|
|
|
122
122
|
const next = applyCellValue(input.collection, input.doc, input.field.name, input.locale, input.value);
|
|
123
123
|
const issues = cellEditIssues(context.registry, context.documents, context.localeConfig, input.collection, next, input.field.name, input.locale, {
|
|
124
124
|
...(context.isPublished ? { isPublished: context.isPublished } : {}),
|
|
125
|
-
...(context.
|
|
125
|
+
...(context.findAsset ? { findAsset: context.findAsset } : {}),
|
|
126
126
|
});
|
|
127
127
|
if (issues.length > 0) {
|
|
128
128
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cell-edit.js","sourceRoot":"","sources":["../../../src/components/cms/cell-edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAA;AAWlG,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAA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,qBAAqB,CAAC,KAAK,CAAC,CAAA;AACrC,CAAC","sourcesContent":["import { createDocumentStore, isFieldLocalized, validateDocument } from '@elytracms/core/cms-core'\nimport type {\n CmsDocument,\n CmsValidationIssue,\n CollectionDef,\n CollectionRegistry,\n DocumentRef,\n FieldDef,\n Locale,\n LocaleConfig,\n} from '@elytracms/core/cms-core'\nimport { gateValidateOptions } from './gate-validation'\nimport { anchorFieldName } from './inline-field-errors'\nimport type { OperationError, OperationResult } from '@elytracms/studio/lib/operations'\nimport { replaceDoc } from './document-ref-utils'\nimport {\n cmsValidationIssueMessage,\n operationErrorMessage,\n operationIssueMessage,\n} from '@elytracms/studio/lib/persona/labels'\n\n/**\n * Inline cell editing for the collection table (EC-168) — the pure half.\n *\n * Everything here is plain data + functions so the cell-edit state machine is\n * testable without a DOM: which cells are editable, how Tab/Enter advance,\n * how a draft value is folded into a document (active locale only), and how a\n * commit flows through exactly one `documents.upsert` operations command with\n * optimistic apply + rollback on rejection.\n */\n\n// --- Cell identity -----------------------------------------------------------\n\n/** A cell in the collection table: one document × one field column. */\nexport interface CellCoord {\n docId: string\n field: string\n}\n\n/** Stable key for a cell (state maps, DOM lookups). */\nexport function cellKey(coord: CellCoord): string {\n return `${coord.docId}::${coord.field}`\n}\n\n// --- Editability -------------------------------------------------------------\n\n/** How a cell edits: inline control, anchored picker dialog, or not at all. */\nexport type CellEditKind = 'inline' | 'picker' | 'none'\n\nconst INLINE_TYPES: ReadonlySet<FieldDef['type']> = new Set([\n 'text',\n 'number',\n 'boolean',\n 'select',\n 'date',\n])\n\n/**\n * Classify a field's in-table editing surface. Rich text is deliberately not\n * inline-editable (the detail editor owns it); read-only fields never edit.\n */\nexport function cellEditKind(field: FieldDef, readOnly: boolean): CellEditKind {\n if (readOnly) return 'none'\n if (field.type === 'relation' || field.type === 'asset') return 'picker'\n return INLINE_TYPES.has(field.type) ? 'inline' : 'none'\n}\n\n// --- Keyboard advance --------------------------------------------------------\n\n/** Where a committed edit moves next: Tab → next, Shift-Tab → prev, Enter → down. */\nexport type AdvanceDirection = 'next' | 'prev' | 'down'\n\n/**\n * The next editable cell in the table grid, or `null` at a boundary.\n * `docIds` is the rendered row order; `fields` the editable column order.\n * 'next'/'prev' walk row-major (wrapping across rows); 'down' stays in the\n * same column.\n */\nexport function nextEditableCell(\n docIds: readonly string[],\n fields: readonly string[],\n current: CellCoord,\n direction: AdvanceDirection,\n): CellCoord | null {\n const row = docIds.indexOf(current.docId)\n const col = fields.indexOf(current.field)\n if (row < 0 || col < 0 || fields.length === 0) return null\n if (direction === 'down') {\n const nextDoc = docIds[row + 1]\n return nextDoc === undefined ? null : { docId: nextDoc, field: current.field }\n }\n const flat = row * fields.length + col + (direction === 'next' ? 1 : -1)\n if (flat < 0 || flat >= docIds.length * fields.length) return null\n const docId = docIds[Math.floor(flat / fields.length)]!\n return { docId, field: fields[flat % fields.length]! }\n}\n\n// --- Applying a draft value ----------------------------------------------------\n\n/**\n * Fold one field value into a document. Localized fields write ONLY the given\n * locale's bag (other locale variants untouched, EC-018); non-localized fields\n * write the shared `values` bag. `undefined` clears the entry.\n */\nexport function applyCellValue(\n collection: CollectionDef,\n doc: CmsDocument,\n fieldName: string,\n locale: Locale,\n value: unknown,\n): CmsDocument {\n if (isFieldLocalized(collection, fieldName)) {\n const perLocale = { ...(doc.localized?.[locale] ?? {}) }\n if (value === undefined) delete perLocale[fieldName]\n else perLocale[fieldName] = value\n return { ...doc, localized: { ...doc.localized, [locale]: perLocale } }\n }\n const values = { ...doc.values }\n if (value === undefined) delete values[fieldName]\n else values[fieldName] = value\n return { ...doc, values }\n}\n\n// --- Validation gate -----------------------------------------------------------\n\n/**\n * Error-severity issues that the edited cell itself caused. Localized fields\n * only reject on issues for the edited locale — a missing translation in some\n * *other* locale must not block this commit.\n *\n * EC-497: validates with THE bag (`gateValidateOptions`), not the `store` +\n * `localeConfig` subset it used to assemble here. A cell edit is not a weaker\n * KIND of validation — it is the same validation, FILTERED to the cell being\n * committed, which is the whole option-set contract in one function: surfaces\n * differ in what they do with the issues, never in what they validated with.\n *\n * EC-516: an issue belongs to the edited cell when the TOP-LEVEL field its\n * `path` resolves to is the edited column — `anchorFieldName`, the grammar the\n * document form's inline errors already use. `meta.field` is never compared\n * here: `validateObject` stamps it with the LEAF subfield name, so a broken\n * `items[0].title` used to pass for a `title` issue and block an unrelated\n * `title` edit (and the owning `items` column saw nothing).\n */\nexport function cellEditIssues(\n registry: CollectionRegistry,\n documents: readonly CmsDocument[],\n localeConfig: LocaleConfig,\n collection: CollectionDef,\n next: CmsDocument,\n fieldName: string,\n locale: Locale,\n oracles: CellEditOracles = {},\n): CmsValidationIssue[] {\n // Validate against the session with the edited document swapped in, so\n // self-relations and same-document targets resolve.\n const store = createDocumentStore(replaceDoc(documents, next))\n const issues = validateDocument(\n registry,\n next,\n gateValidateOptions({\n store,\n localeConfig,\n isPublished: oracles.isPublished ?? (() => false),\n ...(oracles.assetExists ? { assetExists: oracles.assetExists } : {}),\n }),\n )\n const localized = isFieldLocalized(collection, fieldName)\n return issues.filter((issue) => {\n if (issue.severity !== 'error') return false\n if (anchorFieldName(collection, issue) !== fieldName) return false\n if (!localized) return true\n // Localized field paths are ['documents', key, 'localized', <locale>, <field>, …].\n const at = issue.path.indexOf('localized')\n return at < 0 || issue.path[at + 1] === locale\n })\n}\n\n// --- Commit pipeline -------------------------------------------------------------\n\n/** Outcome of one cell commit: the new document, or a structured rejection. */\nexport type CellCommitOutcome =\n | { ok: true; doc: CmsDocument }\n | { ok: false; error: OperationError }\n\nexport interface CellCommitInput {\n collection: CollectionDef\n /** The document as currently rendered (the rollback target). */\n doc: CmsDocument\n field: FieldDef\n /** The active locale at the point of edit (table locale resolution). */\n locale: Locale\n /** The committed draft value (`undefined` clears the field). */\n value: unknown\n}\n\n/**\n * The session oracles the canonical option bag needs beyond the store + locales\n * (EC-497). Optional so a fixture-only caller still gets the rest of the bag;\n * absent `isPublished` means \"nothing is published\", the engine's own default.\n */\nexport interface CellEditOracles {\n isPublished?: (ref: DocumentRef) => boolean\n assetExists?: (id: string) => boolean\n}\n\nexport interface CellCommitContext extends CellEditOracles {\n registry: CollectionRegistry\n /** Current session documents (relation/asset target resolution). */\n documents: readonly CmsDocument[]\n localeConfig: LocaleConfig\n /** Optimistically apply the edited document to the session. */\n applySession: (next: CmsDocument) => void\n /** Restore the pre-edit document after a rejected dispatch. */\n rollbackSession: (previous: CmsDocument) => void\n /**\n * Dispatch the ONE operations command for this commit\n * (`documents.upsert`, EC-141). Absent in fixture-only sessions\n * (no project scope) — the commit is session-only then.\n */\n dispatch?: (next: CmsDocument) => Promise<OperationResult<unknown>>\n}\n\n/**\n * Commit one cell edit:\n * 1. fold the value into the document (active locale only),\n * 2. gate on field validation — rejected edits dispatch NOTHING and report a\n * structured validation error for the cell,\n * 3. apply optimistically, dispatch exactly one operations command,\n * 4. roll the session back when the operation result is a rejection.\n */\nexport async function commitCellEdit(\n context: CellCommitContext,\n input: CellCommitInput,\n): Promise<CellCommitOutcome> {\n const next = applyCellValue(input.collection, input.doc, input.field.name, input.locale, input.value)\n\n const issues = cellEditIssues(\n context.registry,\n context.documents,\n context.localeConfig,\n input.collection,\n next,\n input.field.name,\n input.locale,\n {\n ...(context.isPublished ? { isPublished: context.isPublished } : {}),\n ...(context.assetExists ? { assetExists: context.assetExists } : {}),\n },\n )\n if (issues.length > 0) {\n return {\n ok: false,\n error: {\n code: 'validation',\n // EC-487/EC-494: this producer is CLIENT-side and already holds the structured\n // issue, so it resolves the message here. (Since EC-494 the wire also carries\n // the ref, which is what makes the SERVER-side publish gate localize.)\n message: cmsValidationIssueMessage(issues[0]!),\n issues: issues.map((issue) => ({\n code: issue.code,\n message: cmsValidationIssueMessage(issue),\n path: [...issue.path],\n domain: 'cms',\n })),\n },\n }\n }\n\n context.applySession(next)\n if (context.dispatch) {\n let result: OperationResult<unknown>\n try {\n result = await context.dispatch(next)\n } catch (cause) {\n // Operations never throw by contract; treat a broken transport the same\n // as a failed command so the cell still rolls back visibly.\n result = {\n ok: false,\n error: { code: 'unknown', message: cause instanceof Error ? cause.message : String(cause) },\n }\n }\n if (!result.ok) {\n context.rollbackSession(input.doc)\n return { ok: false, error: result.error }\n }\n }\n return { ok: true, doc: next }\n}\n\n/** The message the cell renders for a rejection: the first issue beats the envelope. */\nexport function cellErrorMessage(error: OperationError): string {\n // EC-494: an OperationIssue now carries its catalog ref across the wire, so a\n // rejection built SERVER-SIDE (the publish gate) localizes here too — not only the\n // studio-built ones above.\n if (error.code === 'validation' && error.issues.length > 0)\n return operationIssueMessage(error.issues[0]!)\n return operationErrorMessage(error)\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cell-edit.js","sourceRoot":"","sources":["../../../src/components/cms/cell-edit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAA;AAWlG,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AAEvD,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAA;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AACjD,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,sCAAsC,CAAA;AAoB7C,uDAAuD;AACvD,MAAM,UAAU,OAAO,CAAC,KAAgB;IACtC,OAAO,GAAG,KAAK,CAAC,KAAK,KAAK,KAAK,CAAC,KAAK,EAAE,CAAA;AACzC,CAAC;AAOD,MAAM,YAAY,GAAkC,IAAI,GAAG,CAAC;IAC1D,MAAM;IACN,QAAQ;IACR,SAAS;IACT,QAAQ;IACR,MAAM;CACP,CAAC,CAAA;AAEF;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAC,KAAe,EAAE,QAAiB;IAC7D,IAAI,QAAQ;QAAE,OAAO,MAAM,CAAA;IAC3B,IAAI,KAAK,CAAC,IAAI,KAAK,UAAU,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;QA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,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE;aAC5F,CAAA;QACH,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;YACf,OAAO,CAAC,eAAe,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;YAClC,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAA;QAC3C,CAAC;IACH,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,CAAA;AAChC,CAAC;AAED,wFAAwF;AACxF,MAAM,UAAU,gBAAgB,CAAC,KAAqB;IACpD,8EAA8E;IAC9E,mFAAmF;IACnF,2BAA2B;IAC3B,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC;QACxD,OAAO,qBAAqB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAE,CAAC,CAAA;IAChD,OAAO,qBAAqB,CAAC,KAAK,CAAC,CAAA;AACrC,CAAC","sourcesContent":["import { createDocumentStore, isFieldLocalized, validateDocument } from '@elytracms/core/cms-core'\nimport type {\n CmsDocument,\n CmsValidationIssue,\n CollectionDef,\n CollectionRegistry,\n DocumentRef,\n FieldDef,\n Locale,\n LocaleConfig,\n} from '@elytracms/core/cms-core'\nimport { gateValidateOptions } from './gate-validation'\nimport type { FindAsset } from './gate-validation'\nimport { anchorFieldName } from './inline-field-errors'\nimport type { OperationError, OperationResult } from '@elytracms/studio/lib/operations'\nimport { replaceDoc } from './document-ref-utils'\nimport {\n cmsValidationIssueMessage,\n operationErrorMessage,\n operationIssueMessage,\n} from '@elytracms/studio/lib/persona/labels'\n\n/**\n * Inline cell editing for the collection table (EC-168) — the pure half.\n *\n * Everything here is plain data + functions so the cell-edit state machine is\n * testable without a DOM: which cells are editable, how Tab/Enter advance,\n * how a draft value is folded into a document (active locale only), and how a\n * commit flows through exactly one `documents.upsert` operations command with\n * optimistic apply + rollback on rejection.\n */\n\n// --- Cell identity -----------------------------------------------------------\n\n/** A cell in the collection table: one document × one field column. */\nexport interface CellCoord {\n docId: string\n field: string\n}\n\n/** Stable key for a cell (state maps, DOM lookups). */\nexport function cellKey(coord: CellCoord): string {\n return `${coord.docId}::${coord.field}`\n}\n\n// --- Editability -------------------------------------------------------------\n\n/** How a cell edits: inline control, anchored picker dialog, or not at all. */\nexport type CellEditKind = 'inline' | 'picker' | 'none'\n\nconst INLINE_TYPES: ReadonlySet<FieldDef['type']> = new Set([\n 'text',\n 'number',\n 'boolean',\n 'select',\n 'date',\n])\n\n/**\n * Classify a field's in-table editing surface. Rich text is deliberately not\n * inline-editable (the detail editor owns it); read-only fields never edit.\n */\nexport function cellEditKind(field: FieldDef, readOnly: boolean): CellEditKind {\n if (readOnly) return 'none'\n if (field.type === 'relation' || field.type === 'asset') return 'picker'\n return INLINE_TYPES.has(field.type) ? 'inline' : 'none'\n}\n\n// --- Keyboard advance --------------------------------------------------------\n\n/** Where a committed edit moves next: Tab → next, Shift-Tab → prev, Enter → down. */\nexport type AdvanceDirection = 'next' | 'prev' | 'down'\n\n/**\n * The next editable cell in the table grid, or `null` at a boundary.\n * `docIds` is the rendered row order; `fields` the editable column order.\n * 'next'/'prev' walk row-major (wrapping across rows); 'down' stays in the\n * same column.\n */\nexport function nextEditableCell(\n docIds: readonly string[],\n fields: readonly string[],\n current: CellCoord,\n direction: AdvanceDirection,\n): CellCoord | null {\n const row = docIds.indexOf(current.docId)\n const col = fields.indexOf(current.field)\n if (row < 0 || col < 0 || fields.length === 0) return null\n if (direction === 'down') {\n const nextDoc = docIds[row + 1]\n return nextDoc === undefined ? null : { docId: nextDoc, field: current.field }\n }\n const flat = row * fields.length + col + (direction === 'next' ? 1 : -1)\n if (flat < 0 || flat >= docIds.length * fields.length) return null\n const docId = docIds[Math.floor(flat / fields.length)]!\n return { docId, field: fields[flat % fields.length]! }\n}\n\n// --- Applying a draft value ----------------------------------------------------\n\n/**\n * Fold one field value into a document. Localized fields write ONLY the given\n * locale's bag (other locale variants untouched, EC-018); non-localized fields\n * write the shared `values` bag. `undefined` clears the entry.\n */\nexport function applyCellValue(\n collection: CollectionDef,\n doc: CmsDocument,\n fieldName: string,\n locale: Locale,\n value: unknown,\n): CmsDocument {\n if (isFieldLocalized(collection, fieldName)) {\n const perLocale = { ...(doc.localized?.[locale] ?? {}) }\n if (value === undefined) delete perLocale[fieldName]\n else perLocale[fieldName] = value\n return { ...doc, localized: { ...doc.localized, [locale]: perLocale } }\n }\n const values = { ...doc.values }\n if (value === undefined) delete values[fieldName]\n else values[fieldName] = value\n return { ...doc, values }\n}\n\n// --- Validation gate -----------------------------------------------------------\n\n/**\n * Error-severity issues that the edited cell itself caused. Localized fields\n * only reject on issues for the edited locale — a missing translation in some\n * *other* locale must not block this commit.\n *\n * EC-497: validates with THE bag (`gateValidateOptions`), not the `store` +\n * `localeConfig` subset it used to assemble here. A cell edit is not a weaker\n * KIND of validation — it is the same validation, FILTERED to the cell being\n * committed, which is the whole option-set contract in one function: surfaces\n * differ in what they do with the issues, never in what they validated with.\n *\n * EC-516: an issue belongs to the edited cell when the TOP-LEVEL field its\n * `path` resolves to is the edited column — `anchorFieldName`, the grammar the\n * document form's inline errors already use. `meta.field` is never compared\n * here: `validateObject` stamps it with the LEAF subfield name, so a broken\n * `items[0].title` used to pass for a `title` issue and block an unrelated\n * `title` edit (and the owning `items` column saw nothing).\n */\nexport function cellEditIssues(\n registry: CollectionRegistry,\n documents: readonly CmsDocument[],\n localeConfig: LocaleConfig,\n collection: CollectionDef,\n next: CmsDocument,\n fieldName: string,\n locale: Locale,\n oracles: CellEditOracles = {},\n): CmsValidationIssue[] {\n // Validate against the session with the edited document swapped in, so\n // self-relations and same-document targets resolve.\n const store = createDocumentStore(replaceDoc(documents, next))\n const issues = validateDocument(\n registry,\n next,\n gateValidateOptions({\n store,\n localeConfig,\n isPublished: oracles.isPublished ?? (() => false),\n ...(oracles.findAsset ? { findAsset: oracles.findAsset } : {}),\n }),\n )\n const localized = isFieldLocalized(collection, fieldName)\n return issues.filter((issue) => {\n if (issue.severity !== 'error') return false\n if (anchorFieldName(collection, issue) !== fieldName) return false\n if (!localized) return true\n // Localized field paths are ['documents', key, 'localized', <locale>, <field>, …].\n const at = issue.path.indexOf('localized')\n return at < 0 || issue.path[at + 1] === locale\n })\n}\n\n// --- Commit pipeline -------------------------------------------------------------\n\n/** Outcome of one cell commit: the new document, or a structured rejection. */\nexport type CellCommitOutcome =\n | { ok: true; doc: CmsDocument }\n | { ok: false; error: OperationError }\n\nexport interface CellCommitInput {\n collection: CollectionDef\n /** The document as currently rendered (the rollback target). */\n doc: CmsDocument\n field: FieldDef\n /** The active locale at the point of edit (table locale resolution). */\n locale: Locale\n /** The committed draft value (`undefined` clears the field). */\n value: unknown\n}\n\n/**\n * The session oracles the canonical option bag needs beyond the store + locales\n * (EC-497). Optional so a fixture-only caller still gets the rest of the bag;\n * absent `isPublished` means \"nothing is published\", the engine's own default.\n */\nexport interface CellEditOracles {\n isPublished?: (ref: DocumentRef) => boolean\n /** The asset-library oracle (EC-588) — record lookup; absent = no asset checks. */\n findAsset?: FindAsset\n}\n\nexport interface CellCommitContext extends CellEditOracles {\n registry: CollectionRegistry\n /** Current session documents (relation/asset target resolution). */\n documents: readonly CmsDocument[]\n localeConfig: LocaleConfig\n /** Optimistically apply the edited document to the session. */\n applySession: (next: CmsDocument) => void\n /** Restore the pre-edit document after a rejected dispatch. */\n rollbackSession: (previous: CmsDocument) => void\n /**\n * Dispatch the ONE operations command for this commit\n * (`documents.upsert`, EC-141). Absent in fixture-only sessions\n * (no project scope) — the commit is session-only then.\n */\n dispatch?: (next: CmsDocument) => Promise<OperationResult<unknown>>\n}\n\n/**\n * Commit one cell edit:\n * 1. fold the value into the document (active locale only),\n * 2. gate on field validation — rejected edits dispatch NOTHING and report a\n * structured validation error for the cell,\n * 3. apply optimistically, dispatch exactly one operations command,\n * 4. roll the session back when the operation result is a rejection.\n */\nexport async function commitCellEdit(\n context: CellCommitContext,\n input: CellCommitInput,\n): Promise<CellCommitOutcome> {\n const next = applyCellValue(input.collection, input.doc, input.field.name, input.locale, input.value)\n\n const issues = cellEditIssues(\n context.registry,\n context.documents,\n context.localeConfig,\n input.collection,\n next,\n input.field.name,\n input.locale,\n {\n ...(context.isPublished ? { isPublished: context.isPublished } : {}),\n ...(context.findAsset ? { findAsset: context.findAsset } : {}),\n },\n )\n if (issues.length > 0) {\n return {\n ok: false,\n error: {\n code: 'validation',\n // EC-487/EC-494: this producer is CLIENT-side and already holds the structured\n // issue, so it resolves the message here. (Since EC-494 the wire also carries\n // the ref, which is what makes the SERVER-side publish gate localize.)\n message: cmsValidationIssueMessage(issues[0]!),\n issues: issues.map((issue) => ({\n code: issue.code,\n message: cmsValidationIssueMessage(issue),\n path: [...issue.path],\n domain: 'cms',\n })),\n },\n }\n }\n\n context.applySession(next)\n if (context.dispatch) {\n let result: OperationResult<unknown>\n try {\n result = await context.dispatch(next)\n } catch (cause) {\n // Operations never throw by contract; treat a broken transport the same\n // as a failed command so the cell still rolls back visibly.\n result = {\n ok: false,\n error: { code: 'unknown', message: cause instanceof Error ? cause.message : String(cause) },\n }\n }\n if (!result.ok) {\n context.rollbackSession(input.doc)\n return { ok: false, error: result.error }\n }\n }\n return { ok: true, doc: next }\n}\n\n/** The message the cell renders for a rejection: the first issue beats the envelope. */\nexport function cellErrorMessage(error: OperationError): string {\n // EC-494: an OperationIssue now carries its catalog ref across the wire, so a\n // rejection built SERVER-SIDE (the publish gate) localizes here too — not only the\n // studio-built ones above.\n if (error.code === 'validation' && error.issues.length > 0)\n return operationIssueMessage(error.issues[0]!)\n return operationErrorMessage(error)\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { validateCompositionValue } from '@elytracms/core/project-graph';
|
|
1
|
+
import { legacyNodeMemberIssues, validateCompositionValue } from '@elytracms/core/project-graph';
|
|
2
2
|
import { BLOCK_SEQUENCE_VERSION, classifyBlockNode, isBlockSequenceValueShape, parseBlockSequenceValue, } from '@elytracms/core/rich-text';
|
|
3
3
|
import { getStudioRegistry } from '@elytracms/studio/lib/registry';
|
|
4
4
|
/**
|
|
@@ -47,9 +47,19 @@ function validateBlockSequence(value, allow) {
|
|
|
47
47
|
},
|
|
48
48
|
];
|
|
49
49
|
}
|
|
50
|
+
// EC-574: retired node members (a render `condition`, a `kind: 'binding'` prop)
|
|
51
|
+
// are judged on the value AS STORED, before the parse below — the parser strips
|
|
52
|
+
// a stray `condition` silently and rejects a binding prop only generically, so
|
|
53
|
+
// this is the one place the stored shape is still visible to name precisely.
|
|
54
|
+
const out = legacyNodeMemberIssues(value).map((issue) => ({
|
|
55
|
+
message: issue.message,
|
|
56
|
+
severity: issue.severity,
|
|
57
|
+
nodePath: issue.path.join('/'),
|
|
58
|
+
}));
|
|
50
59
|
const parsed = parseBlockSequenceValue(value);
|
|
51
60
|
if (!parsed.ok) {
|
|
52
61
|
return [
|
|
62
|
+
...out,
|
|
53
63
|
{
|
|
54
64
|
message: `is not a valid block sequence (version ${BLOCK_SEQUENCE_VERSION})`,
|
|
55
65
|
severity: 'error',
|
|
@@ -58,7 +68,6 @@ function validateBlockSequence(value, allow) {
|
|
|
58
68
|
}
|
|
59
69
|
const components = getStudioRegistry().registry.lookup;
|
|
60
70
|
const opts = { ...(allow ? { allow } : {}), components };
|
|
61
|
-
const out = [];
|
|
62
71
|
/** `root/0/<rest>` from a single-node validation call → `<base>/<rest>`. */
|
|
63
72
|
const nestedPath = (base, path) => {
|
|
64
73
|
const rest = path.slice(2);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cms-composition-validators.js","sourceRoot":"","sources":["../../../src/components/cms/cms-composition-validators.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAA;AAEx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'@elytracms/core/project-graph'\nimport type { ComponentNode } from '@elytracms/core/project-graph'\nimport {\n BLOCK_SEQUENCE_VERSION,\n classifyBlockNode,\n isBlockSequenceValueShape,\n parseBlockSequenceValue,\n} from '@elytracms/core/rich-text'\nimport type { BlockNode } from '@elytracms/core/rich-text'\nimport { getStudioRegistry } from '@elytracms/studio/lib/registry'\n\n/**\n * Composition validator adapters (EC-326, extracted from `cms-store.tsx`) —\n * injected into `validateDocument`'s `validateComposition`/`validateRichTextEmbeds`\n * options so `@elytracms/core/cms-core` stays free of `@elytracms/core/project-graph`\n * and `@elytracms/core/rich-text`.\n *\n * EC-547 (EC-500 D1/D4): both field types now share ONE stored shape — the v2\n * block sequence `{ version: 2, content: BlockNode[] }` — and therefore ONE\n * validation walk: unwrap the envelope, validate the sequence's component nodes\n * (top-level roots AND nodes nested inside typography content) against the\n * field's `allow` vocabulary + the code-owned component registry. \"`allow`\n * means component ids insertable at this position\" is now literally the same\n * check on the same shape for `blocks` and `richText`.\n *\n * Pre-convergence shapes (the v1 `{ version, doc }` envelope, bare node lists)\n * never reach these adapters: `validateDocument`'s shape pass reports them as\n * the explicit pre-convergence issue and skips the deeper validators (EC-548\n * removed the legacy walks). A retired `componentEmbed` node riding in v2\n * content is a foreign typography node — not rendered, not validated, surfaced\n * by the renderer's unknown-node fallback (render/validate parity, EC-497).\n */\n\n/**\n * Validate the component nodes of a v2 block sequence against the field leash.\n *\n * - Top-level component roots validate in ONE `validateCompositionValue` call,\n * so cross-root checks (duplicate node ids) see the whole sequence. Their\n * `root/<k>` issue paths are re-keyed to the node's actual sequence index\n * (`content/<i>/…`).\n * - A component nested in typography content validates per-node with the SAME\n * leash, its findings prefixed with the typography path\n * (`content/<i>/content/<j>/…`).\n * - A malformed value degrades to a single finding, never a crash.\n */\nfunction validateBlockSequence(\n value: unknown,\n allow: readonly string[] | undefined,\n): CompositionIssue[] {\n // Structural gate FIRST: only the stored `{ version: 2, content }` object is a\n // sequence here. The parser alone would also accept a JSON-string encoding of\n // one — which no delivery reader accepts — and validating that clean would be\n // the invisible divergence EC-390 exists to prevent.\n if (!isBlockSequenceValueShape(value)) {\n return [\n {\n message: `is not a valid block sequence (version ${BLOCK_SEQUENCE_VERSION})`,\n severity: 'error',\n },\n ]\n }\n const parsed = parseBlockSequenceValue(value)\n if (!parsed.ok) {\n return [\n {\n message: `is not a valid block sequence (version ${BLOCK_SEQUENCE_VERSION})`,\n severity: 'error',\n },\n ]\n }\n const components = getStudioRegistry().registry.lookup\n const opts = { ...(allow ? { allow } : {}), components }\n const out: CompositionIssue[] = []\n\n /** `root/0/<rest>` from a single-node validation call → `<base>/<rest>`. */\n const nestedPath = (base: string, path: ReadonlyArray<string | number>): string => {\n const rest = path.slice(2)\n return rest.length > 0 ? `${base}/${rest.join('/')}` : base\n }\n\n const walkTypography = (nodes: readonly BlockNode[] | undefined, base: string): void => {\n nodes?.forEach((child, i) => {\n const here = `${base}/content/${i}`\n const kind = classifyBlockNode(child)\n if (kind.kind === 'component') {\n for (const issue of validateCompositionValue(kind.node, opts)) {\n out.push({ message: issue.message, severity: issue.severity, nodePath: nestedPath(here, issue.path) })\n }\n } else {\n walkTypography(kind.node.content, here)\n }\n })\n }\n\n const roots: { node: ComponentNode; index: number }[] = []\n parsed.value.content.forEach((node, index) => {\n const kind = classifyBlockNode(node)\n if (kind.kind === 'component') roots.push({ node: kind.node, index })\n else walkTypography(kind.node.content, `content/${index}`)\n })\n\n for (const issue of validateCompositionValue(roots.map((r) => r.node), opts)) {\n // path is `['root', <k>, ...rest]` — re-key <k> to the sequence index.\n const [, k, ...rest] = issue.path\n const index = typeof k === 'number' ? (roots[k]?.index ?? k) : k\n out.push({\n message: issue.message,\n severity: issue.severity,\n nodePath: ['content', ...(index === undefined ? [] : [index]), ...rest].join('/'),\n })\n }\n return out\n}\n\n/**\n * EC-188: validate a `blocks` composition field value against the field's `allow`\n * vocabulary + the code-owned component registry (the leash), mapping graph\n * issues into plain CMS findings. Never throws — a malformed value degrades to\n * a single finding, matching the \"validation is first-class, never a crash\"\n * rule.\n */\nexport function validateComposition(value: unknown, field: BlocksFieldDef): CompositionIssue[] {\n if (value == null) return []\n return validateBlockSequence(value, field.allow)\n}\n\n/**\n * EC-189: validate the composition nodes inside a `richText` field value with\n * the SAME leash a `blocks` field uses — since EC-547 literally the same walk\n * over the same shape: the value's `elytra/component` nodes ARE sequence\n * citizens, at the top level and nested in typography content.\n */\nexport function validateRichTextEmbeds(value: unknown, field: RichTextFieldDef): CompositionIssue[] {\n if (value == null) return []\n return validateBlockSequence(value, field.allow)\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cms-composition-validators.js","sourceRoot":"","sources":["../../../src/components/cms/cms-composition-validators.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAA;AAEhG,OAAO,EACL,sBAAsB,EACtB,iBAAiB,EACjB,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,2BAA2B,CAAA;AAElC,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAA;AAElE;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH;;;;;;;;;;;GAWG;AACH,SAAS,qBAAqB,CAC5B,KAAc,EACd,KAAoC;IAEpC,+EAA+E;IAC/E,8EAA8E;IAC9E,8EAA8E;IAC9E,qDAAqD;IACrD,IAAI,CAAC,yBAAyB,CAAC,KAAK,CAAC,EAAE,CAAC;QACtC,OAAO;YACL;gBACE,OAAO,EAAE,0CAA0C,sBAAsB,GAAG;gBAC5E,QAAQ,EAAE,OAAO;aAClB;SACF,CAAA;IACH,CAAC;IACD,gFAAgF;IAChF,gFAAgF;IAChF,+EAA+E;IAC/E,6EAA6E;IAC7E,MAAM,GAAG,GAAuB,sBAAsB,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAC5E,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,QAAQ,EAAE,KAA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AAG,CAAC,IAAI,CAAC;YACP,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,QAAQ,EAAE,CAAC,SAAS,EAAE,GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;SAClF,CAAC,CAAA;IACJ,CAAC;IACD,OAAO,GAAG,CAAA;AACZ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAc,EAAE,KAAqB;IACvE,IAAI,KAAK,IAAI,IAAI;QAAE,OAAO,EAAE,CAAA;IAC5B,OAAO,qBAAqB,CAAC,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,CAAA;AAClD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CAAC,KAAc,EAAE,KAAuB;IAC5E,IAAI,KAAK,IAAI,IAAI;QAAE,OAAO,EAAE,CAAA;IAC5B,OAAO,qBAAqB,CAAC,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,CAAA;AAClD,CAAC","sourcesContent":["import type { BlocksFieldDef, CompositionIssue, RichTextFieldDef } from '@elytracms/core/cms-core'\nimport { legacyNodeMemberIssues, validateCompositionValue } from '@elytracms/core/project-graph'\nimport type { ComponentNode } from '@elytracms/core/project-graph'\nimport {\n BLOCK_SEQUENCE_VERSION,\n classifyBlockNode,\n isBlockSequenceValueShape,\n parseBlockSequenceValue,\n} from '@elytracms/core/rich-text'\nimport type { BlockNode } from '@elytracms/core/rich-text'\nimport { getStudioRegistry } from '@elytracms/studio/lib/registry'\n\n/**\n * Composition validator adapters (EC-326, extracted from `cms-store.tsx`) —\n * injected into `validateDocument`'s `validateComposition`/`validateRichTextEmbeds`\n * options so `@elytracms/core/cms-core` stays free of `@elytracms/core/project-graph`\n * and `@elytracms/core/rich-text`.\n *\n * EC-547 (EC-500 D1/D4): both field types now share ONE stored shape — the v2\n * block sequence `{ version: 2, content: BlockNode[] }` — and therefore ONE\n * validation walk: unwrap the envelope, validate the sequence's component nodes\n * (top-level roots AND nodes nested inside typography content) against the\n * field's `allow` vocabulary + the code-owned component registry. \"`allow`\n * means component ids insertable at this position\" is now literally the same\n * check on the same shape for `blocks` and `richText`.\n *\n * Pre-convergence shapes (the v1 `{ version, doc }` envelope, bare node lists)\n * never reach these adapters: `validateDocument`'s shape pass reports them as\n * the explicit pre-convergence issue and skips the deeper validators (EC-548\n * removed the legacy walks). A retired `componentEmbed` node riding in v2\n * content is a foreign typography node — not rendered, not validated, surfaced\n * by the renderer's unknown-node fallback (render/validate parity, EC-497).\n */\n\n/**\n * Validate the component nodes of a v2 block sequence against the field leash.\n *\n * - Top-level component roots validate in ONE `validateCompositionValue` call,\n * so cross-root checks (duplicate node ids) see the whole sequence. Their\n * `root/<k>` issue paths are re-keyed to the node's actual sequence index\n * (`content/<i>/…`).\n * - A component nested in typography content validates per-node with the SAME\n * leash, its findings prefixed with the typography path\n * (`content/<i>/content/<j>/…`).\n * - A malformed value degrades to a single finding, never a crash.\n */\nfunction validateBlockSequence(\n value: unknown,\n allow: readonly string[] | undefined,\n): CompositionIssue[] {\n // Structural gate FIRST: only the stored `{ version: 2, content }` object is a\n // sequence here. The parser alone would also accept a JSON-string encoding of\n // one — which no delivery reader accepts — and validating that clean would be\n // the invisible divergence EC-390 exists to prevent.\n if (!isBlockSequenceValueShape(value)) {\n return [\n {\n message: `is not a valid block sequence (version ${BLOCK_SEQUENCE_VERSION})`,\n severity: 'error',\n },\n ]\n }\n // EC-574: retired node members (a render `condition`, a `kind: 'binding'` prop)\n // are judged on the value AS STORED, before the parse below — the parser strips\n // a stray `condition` silently and rejects a binding prop only generically, so\n // this is the one place the stored shape is still visible to name precisely.\n const out: CompositionIssue[] = legacyNodeMemberIssues(value).map((issue) => ({\n message: issue.message,\n severity: issue.severity,\n nodePath: issue.path.join('/'),\n }))\n const parsed = parseBlockSequenceValue(value)\n if (!parsed.ok) {\n return [\n ...out,\n {\n message: `is not a valid block sequence (version ${BLOCK_SEQUENCE_VERSION})`,\n severity: 'error',\n },\n ]\n }\n const components = getStudioRegistry().registry.lookup\n const opts = { ...(allow ? { allow } : {}), components }\n\n /** `root/0/<rest>` from a single-node validation call → `<base>/<rest>`. */\n const nestedPath = (base: string, path: ReadonlyArray<string | number>): string => {\n const rest = path.slice(2)\n return rest.length > 0 ? `${base}/${rest.join('/')}` : base\n }\n\n const walkTypography = (nodes: readonly BlockNode[] | undefined, base: string): void => {\n nodes?.forEach((child, i) => {\n const here = `${base}/content/${i}`\n const kind = classifyBlockNode(child)\n if (kind.kind === 'component') {\n for (const issue of validateCompositionValue(kind.node, opts)) {\n out.push({ message: issue.message, severity: issue.severity, nodePath: nestedPath(here, issue.path) })\n }\n } else {\n walkTypography(kind.node.content, here)\n }\n })\n }\n\n const roots: { node: ComponentNode; index: number }[] = []\n parsed.value.content.forEach((node, index) => {\n const kind = classifyBlockNode(node)\n if (kind.kind === 'component') roots.push({ node: kind.node, index })\n else walkTypography(kind.node.content, `content/${index}`)\n })\n\n for (const issue of validateCompositionValue(roots.map((r) => r.node), opts)) {\n // path is `['root', <k>, ...rest]` — re-key <k> to the sequence index.\n const [, k, ...rest] = issue.path\n const index = typeof k === 'number' ? (roots[k]?.index ?? k) : k\n out.push({\n message: issue.message,\n severity: issue.severity,\n nodePath: ['content', ...(index === undefined ? [] : [index]), ...rest].join('/'),\n })\n }\n return out\n}\n\n/**\n * EC-188: validate a `blocks` composition field value against the field's `allow`\n * vocabulary + the code-owned component registry (the leash), mapping graph\n * issues into plain CMS findings. Never throws — a malformed value degrades to\n * a single finding, matching the \"validation is first-class, never a crash\"\n * rule.\n */\nexport function validateComposition(value: unknown, field: BlocksFieldDef): CompositionIssue[] {\n if (value == null) return []\n return validateBlockSequence(value, field.allow)\n}\n\n/**\n * EC-189: validate the composition nodes inside a `richText` field value with\n * the SAME leash a `blocks` field uses — since EC-547 literally the same walk\n * over the same shape: the value's `elytra/component` nodes ARE sequence\n * citizens, at the top level and nested in typography content.\n */\nexport function validateRichTextEmbeds(value: unknown, field: RichTextFieldDef): CompositionIssue[] {\n if (value == null) return []\n return validateBlockSequence(value, field.allow)\n}\n"]}
|