@conloca/cms-spa 0.2.2 → 0.2.4
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/README.md +26 -0
- package/dist/spa/main.css +229 -1
- package/dist/ts/.build-inputs.json +187 -0
- package/dist/ts/App.d.ts +5 -1
- package/dist/ts/App.d.ts.map +1 -1
- package/dist/ts/App.js +13 -6
- package/dist/ts/App.js.map +1 -1
- package/dist/ts/CmsSpaApp.d.ts.map +1 -1
- package/dist/ts/CmsSpaApp.js +4 -1
- package/dist/ts/CmsSpaApp.js.map +1 -1
- package/dist/ts/components/CMSDashboard.d.ts.map +1 -1
- package/dist/ts/components/CMSDashboard.js +2 -1
- package/dist/ts/components/CMSDashboard.js.map +1 -1
- package/dist/ts/components/cards/DataEntryCard.d.ts +1 -1
- package/dist/ts/components/cards/DataEntryCard.d.ts.map +1 -1
- package/dist/ts/components/cards/SectionCard.d.ts +1 -1
- package/dist/ts/components/cards/SectionCard.d.ts.map +1 -1
- package/dist/ts/components/dialogs/DeleteConfirmDialog.d.ts +6 -1
- package/dist/ts/components/dialogs/DeleteConfirmDialog.d.ts.map +1 -1
- package/dist/ts/components/dialogs/DeleteConfirmDialog.js +2 -2
- package/dist/ts/components/dialogs/DeleteConfirmDialog.js.map +1 -1
- package/dist/ts/components/dialogs/FragmentPropertiesDialog.d.ts +1 -1
- package/dist/ts/components/dialogs/FragmentPropertiesDialog.d.ts.map +1 -1
- package/dist/ts/components/dialogs/MakePagesEditableDialog.d.ts +10 -0
- package/dist/ts/components/dialogs/MakePagesEditableDialog.d.ts.map +1 -0
- package/dist/ts/components/dialogs/MakePagesEditableDialog.js +35 -0
- package/dist/ts/components/dialogs/MakePagesEditableDialog.js.map +1 -0
- package/dist/ts/components/dialogs/MoveFolderDialog.d.ts +6 -1
- package/dist/ts/components/dialogs/MoveFolderDialog.d.ts.map +1 -1
- package/dist/ts/components/dialogs/MoveFolderDialog.js +3 -3
- package/dist/ts/components/dialogs/MoveFolderDialog.js.map +1 -1
- package/dist/ts/components/editor/CMSMDXEditor.d.ts.map +1 -1
- package/dist/ts/components/editor/CMSMDXEditor.js +53 -62
- package/dist/ts/components/editor/CMSMDXEditor.js.map +1 -1
- package/dist/ts/components/editor/DocsPreviewButton.d.ts +6 -0
- package/dist/ts/components/editor/DocsPreviewButton.d.ts.map +1 -0
- package/dist/ts/components/editor/DocsPreviewButton.js +15 -0
- package/dist/ts/components/editor/DocsPreviewButton.js.map +1 -0
- package/dist/ts/components/editor/ImagePickerDialog.js +2 -2
- package/dist/ts/components/editor/ImagePickerDialog.js.map +1 -1
- package/dist/ts/components/editor/LocaleSelector.d.ts +1 -1
- package/dist/ts/components/editor/LocaleSelector.d.ts.map +1 -1
- package/dist/ts/components/editor/MdxPageEditor.d.ts.map +1 -1
- package/dist/ts/components/editor/MdxPageEditor.js +2 -1
- package/dist/ts/components/editor/MdxPageEditor.js.map +1 -1
- package/dist/ts/components/editor/PageEditor.d.ts +1 -1
- package/dist/ts/components/editor/PageEditor.d.ts.map +1 -1
- package/dist/ts/components/editor/PageEditor.js +47 -19
- package/dist/ts/components/editor/PageEditor.js.map +1 -1
- package/dist/ts/components/editor/PageEditorHeaderActions.d.ts +1 -1
- package/dist/ts/components/editor/PageEditorHeaderActions.d.ts.map +1 -1
- package/dist/ts/components/editor/PageEditorWrapper.js +31 -5
- package/dist/ts/components/editor/PageEditorWrapper.js.map +1 -1
- package/dist/ts/components/editor/draft-media-config.d.ts +32 -2
- package/dist/ts/components/editor/draft-media-config.d.ts.map +1 -1
- package/dist/ts/components/editor/draft-media-config.js +194 -39
- package/dist/ts/components/editor/draft-media-config.js.map +1 -1
- package/dist/ts/components/editor/page-setting-targets.d.ts +1 -1
- package/dist/ts/components/editor/page-setting-targets.d.ts.map +1 -1
- package/dist/ts/components/editor/preview-availability.d.ts +8 -5
- package/dist/ts/components/editor/preview-availability.d.ts.map +1 -1
- package/dist/ts/components/editor/preview-availability.js +8 -5
- package/dist/ts/components/editor/preview-availability.js.map +1 -1
- package/dist/ts/components/editors/DataEditor.d.ts +6 -2
- package/dist/ts/components/editors/DataEditor.d.ts.map +1 -1
- package/dist/ts/components/editors/DataEditor.js +46 -19
- package/dist/ts/components/editors/DataEditor.js.map +1 -1
- package/dist/ts/components/fields/ImageField.js +2 -2
- package/dist/ts/components/fields/ImageField.js.map +1 -1
- package/dist/ts/components/media/AssetCard.d.ts +1 -1
- package/dist/ts/components/media/AssetCard.d.ts.map +1 -1
- package/dist/ts/components/media/AssetCard.js +3 -2
- package/dist/ts/components/media/AssetCard.js.map +1 -1
- package/dist/ts/components/media/AssetDetailSidebar.d.ts +1 -1
- package/dist/ts/components/media/AssetDetailSidebar.d.ts.map +1 -1
- package/dist/ts/components/media/AssetDetailSidebar.js +7 -2
- package/dist/ts/components/media/AssetDetailSidebar.js.map +1 -1
- package/dist/ts/components/media/AssetUsageList.d.ts +13 -0
- package/dist/ts/components/media/AssetUsageList.d.ts.map +1 -0
- package/dist/ts/components/media/AssetUsageList.js +35 -0
- package/dist/ts/components/media/AssetUsageList.js.map +1 -0
- package/dist/ts/components/media/MediaLibrary.d.ts +1 -1
- package/dist/ts/components/media/MediaLibrary.d.ts.map +1 -1
- package/dist/ts/components/media/MediaLibrary.js +6 -4
- package/dist/ts/components/media/MediaLibrary.js.map +1 -1
- package/dist/ts/components/media/MediaToolbar.d.ts +1 -1
- package/dist/ts/components/media/MediaToolbar.d.ts.map +1 -1
- package/dist/ts/components/media/index.d.ts +1 -0
- package/dist/ts/components/media/index.d.ts.map +1 -1
- package/dist/ts/components/media/index.js +1 -0
- package/dist/ts/components/media/index.js.map +1 -1
- package/dist/ts/components/pages/DataList.d.ts.map +1 -1
- package/dist/ts/components/pages/DataList.js +48 -31
- package/dist/ts/components/pages/DataList.js.map +1 -1
- package/dist/ts/components/pages/MediaPage.d.ts.map +1 -1
- package/dist/ts/components/pages/MediaPage.js +7 -5
- package/dist/ts/components/pages/MediaPage.js.map +1 -1
- package/dist/ts/components/pages/NoPagesYet.d.ts +5 -0
- package/dist/ts/components/pages/NoPagesYet.d.ts.map +1 -0
- package/dist/ts/components/pages/NoPagesYet.js +16 -0
- package/dist/ts/components/pages/NoPagesYet.js.map +1 -0
- package/dist/ts/components/pages/PageList.d.ts.map +1 -1
- package/dist/ts/components/pages/PageList.js +19 -8
- package/dist/ts/components/pages/PageList.js.map +1 -1
- package/dist/ts/components/sandbox/ContentSandbox.d.ts +1 -1
- package/dist/ts/components/sandbox/ContentSandbox.d.ts.map +1 -1
- package/dist/ts/components/sandbox/ContentSandbox.js +36 -5
- package/dist/ts/components/sandbox/ContentSandbox.js.map +1 -1
- package/dist/ts/components/ui/IconButton.d.ts +1 -1
- package/dist/ts/components/ui/IconButton.d.ts.map +1 -1
- package/dist/ts/content-wrapper.d.ts +65 -0
- package/dist/ts/content-wrapper.d.ts.map +1 -0
- package/dist/ts/content-wrapper.js +190 -0
- package/dist/ts/content-wrapper.js.map +1 -0
- package/dist/ts/convert-pages.d.ts +30 -0
- package/dist/ts/convert-pages.d.ts.map +1 -0
- package/dist/ts/convert-pages.js +85 -0
- package/dist/ts/convert-pages.js.map +1 -0
- package/dist/ts/data-schemas.d.ts.map +1 -1
- package/dist/ts/frame/channel.d.ts +40 -0
- package/dist/ts/frame/channel.d.ts.map +1 -0
- package/dist/ts/frame/channel.js +233 -0
- package/dist/ts/frame/channel.js.map +1 -0
- package/dist/ts/frame/editor-frame.d.ts +23 -0
- package/dist/ts/frame/editor-frame.d.ts.map +1 -0
- package/dist/ts/frame/editor-frame.js +159 -0
- package/dist/ts/frame/editor-frame.js.map +1 -0
- package/dist/ts/frame/media-cache.d.ts +37 -0
- package/dist/ts/frame/media-cache.d.ts.map +1 -0
- package/dist/ts/frame/media-cache.js +138 -0
- package/dist/ts/frame/media-cache.js.map +1 -0
- package/dist/ts/frame/memory-router.d.ts +10 -0
- package/dist/ts/frame/memory-router.d.ts.map +1 -0
- package/dist/ts/frame/memory-router.js +39 -0
- package/dist/ts/frame/memory-router.js.map +1 -0
- package/dist/ts/frame/parent-hello.d.ts +11 -0
- package/dist/ts/frame/parent-hello.d.ts.map +1 -0
- package/dist/ts/frame/parent-hello.js +53 -0
- package/dist/ts/frame/parent-hello.js.map +1 -0
- package/dist/ts/frame/protocol.d.ts +209 -0
- package/dist/ts/frame/protocol.d.ts.map +1 -0
- package/dist/ts/frame/protocol.js +200 -0
- package/dist/ts/frame/protocol.js.map +1 -0
- package/dist/ts/frame/rpc-content-client.d.ts +10 -0
- package/dist/ts/frame/rpc-content-client.d.ts.map +1 -0
- package/dist/ts/frame/rpc-content-client.js +51 -0
- package/dist/ts/frame/rpc-content-client.js.map +1 -0
- package/dist/ts/frame/save-shortcut.d.ts +8 -0
- package/dist/ts/frame/save-shortcut.d.ts.map +1 -0
- package/dist/ts/frame/save-shortcut.js +26 -0
- package/dist/ts/frame/save-shortcut.js.map +1 -0
- package/dist/ts/hooks/index.d.ts +2 -0
- package/dist/ts/hooks/index.d.ts.map +1 -1
- package/dist/ts/hooks/index.js +1 -0
- package/dist/ts/hooks/index.js.map +1 -1
- package/dist/ts/hooks/usePageConversion.d.ts +11 -0
- package/dist/ts/hooks/usePageConversion.d.ts.map +1 -0
- package/dist/ts/hooks/usePageConversion.js +47 -0
- package/dist/ts/hooks/usePageConversion.js.map +1 -0
- package/dist/ts/hooks/useUploadFlow.d.ts.map +1 -1
- package/dist/ts/hooks/useUploadFlow.js +41 -7
- package/dist/ts/hooks/useUploadFlow.js.map +1 -1
- package/dist/ts/host-style-probe.d.ts +32 -37
- package/dist/ts/host-style-probe.d.ts.map +1 -1
- package/dist/ts/host-style-probe.js +86 -68
- package/dist/ts/host-style-probe.js.map +1 -1
- package/dist/ts/index.d.ts +6 -2
- package/dist/ts/index.d.ts.map +1 -1
- package/dist/ts/index.js +9 -2
- package/dist/ts/index.js.map +1 -1
- package/dist/ts/main-spa.d.ts.map +1 -1
- package/dist/ts/main-spa.js +2 -1
- package/dist/ts/main-spa.js.map +1 -1
- package/dist/ts/media/prepare-image-upload.d.ts +19 -0
- package/dist/ts/media/prepare-image-upload.d.ts.map +1 -0
- package/dist/ts/media/prepare-image-upload.js +93 -0
- package/dist/ts/media/prepare-image-upload.js.map +1 -0
- package/dist/ts/media/use-asset-serve-src.d.ts +7 -0
- package/dist/ts/media/use-asset-serve-src.d.ts.map +1 -0
- package/dist/ts/media/use-asset-serve-src.js +17 -0
- package/dist/ts/media/use-asset-serve-src.js.map +1 -0
- package/dist/ts/page-schemas.d.ts.map +1 -1
- package/dist/ts/prose-surface-css.d.ts +3 -5
- package/dist/ts/prose-surface-css.d.ts.map +1 -1
- package/dist/ts/prose-surface-css.js +3 -5
- package/dist/ts/prose-surface-css.js.map +1 -1
- package/dist/ts/puck-config.d.ts.map +1 -1
- package/dist/ts/selected-block.d.ts.map +1 -1
- package/dist/ts/site-styles.d.ts +4 -21
- package/dist/ts/site-styles.d.ts.map +1 -1
- package/dist/ts/site-styles.js.map +1 -1
- package/dist/ts/ui-config.d.ts +62 -3
- package/dist/ts/ui-config.d.ts.map +1 -1
- package/dist/ts/ui-config.js +18 -0
- package/dist/ts/ui-config.js.map +1 -1
- package/dist/ts/utils/asset-url.d.ts +3 -0
- package/dist/ts/utils/asset-url.d.ts.map +1 -1
- package/dist/ts/utils/asset-url.js +4 -0
- package/dist/ts/utils/asset-url.js.map +1 -1
- package/dist/ts/utils/data-entry-validation.d.ts +11 -0
- package/dist/ts/utils/data-entry-validation.d.ts.map +1 -0
- package/dist/ts/utils/data-entry-validation.js +15 -0
- package/dist/ts/utils/data-entry-validation.js.map +1 -0
- package/package.json +20 -11
- package/src/App.tsx +22 -10
- package/src/CmsSpaApp.tsx +5 -1
- package/src/components/CMSDashboard.tsx +16 -8
- package/src/components/dialogs/DeleteConfirmDialog.tsx +14 -1
- package/src/components/dialogs/MakePagesEditableDialog.tsx +112 -0
- package/src/components/dialogs/MoveFolderDialog.tsx +9 -2
- package/src/components/editor/CMSMDXEditor.tsx +56 -76
- package/src/components/editor/DocsPreviewButton.tsx +25 -0
- package/src/components/editor/ImagePickerDialog.tsx +2 -2
- package/src/components/editor/MdxPageEditor.tsx +2 -0
- package/src/components/editor/PageEditor.tsx +46 -22
- package/src/components/editor/PageEditorWrapper.tsx +34 -5
- package/src/components/editor/draft-media-config.ts +199 -41
- package/src/components/editor/preview-availability.ts +9 -5
- package/src/components/editors/DataEditor.tsx +65 -32
- package/src/components/fields/ImageField.tsx +2 -2
- package/src/components/media/AssetCard.tsx +12 -9
- package/src/components/media/AssetDetailSidebar.tsx +38 -25
- package/src/components/media/AssetUsageList.tsx +84 -0
- package/src/components/media/MediaLibrary.tsx +6 -4
- package/src/components/media/index.ts +1 -0
- package/src/components/pages/DataList.tsx +53 -29
- package/src/components/pages/MediaPage.tsx +14 -5
- package/src/components/pages/NoPagesYet.tsx +41 -0
- package/src/components/pages/PageList.tsx +40 -27
- package/src/components/sandbox/ContentSandbox.tsx +34 -5
- package/src/content-wrapper.ts +284 -0
- package/src/convert-pages.ts +110 -0
- package/src/frame/channel.ts +258 -0
- package/src/frame/editor-frame.ts +184 -0
- package/src/frame/media-cache.ts +157 -0
- package/src/frame/memory-router.ts +39 -0
- package/src/frame/parent-hello.ts +62 -0
- package/src/frame/protocol.ts +332 -0
- package/src/frame/rpc-content-client.ts +58 -0
- package/src/frame/save-shortcut.ts +25 -0
- package/src/hooks/index.ts +2 -0
- package/src/hooks/usePageConversion.ts +55 -0
- package/src/hooks/useUploadFlow.ts +44 -7
- package/src/host-style-probe.ts +104 -90
- package/src/index.ts +10 -2
- package/src/main-spa.tsx +2 -0
- package/src/main.css +2 -1
- package/src/media/prepare-image-upload.ts +118 -0
- package/src/media/use-asset-serve-src.ts +22 -0
- package/src/prose-surface-css.ts +3 -5
- package/src/site-styles.ts +4 -22
- package/src/ui-config.ts +74 -3
- package/src/utils/asset-url.ts +6 -0
- package/src/utils/data-entry-validation.ts +16 -0
- package/dist/ts/host-discovery.d.ts +0 -40
- package/dist/ts/host-discovery.d.ts.map +0 -1
- package/dist/ts/host-discovery.js +0 -39
- package/dist/ts/host-discovery.js.map +0 -1
- package/src/host-discovery.ts +0 -77
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- the channel carries content values of any shape; the methods on either side give them their types. */
|
|
2
|
+
import { APIClientError, ErrorCodes, StaleWriteError } from '@conloca/content-api-client';
|
|
3
|
+
import { ContentWriteRefusedError } from '../write-access.js';
|
|
4
|
+
import {
|
|
5
|
+
type Call,
|
|
6
|
+
type ControlMessage,
|
|
7
|
+
type FrameEvent,
|
|
8
|
+
type Result,
|
|
9
|
+
type RpcErrorCode,
|
|
10
|
+
readControlMessage,
|
|
11
|
+
type WireError,
|
|
12
|
+
} from './protocol.js';
|
|
13
|
+
|
|
14
|
+
/** The part of a `MessagePort` the channel uses, so tests can hand it a fake. */
|
|
15
|
+
export type FramePort = Pick<
|
|
16
|
+
MessagePort,
|
|
17
|
+
'postMessage' | 'addEventListener' | 'removeEventListener' | 'start' | 'close'
|
|
18
|
+
>;
|
|
19
|
+
|
|
20
|
+
/** An error the channel itself raises, such as a call the other side does not answer. */
|
|
21
|
+
export class RpcError extends Error {
|
|
22
|
+
readonly code: RpcErrorCode;
|
|
23
|
+
|
|
24
|
+
constructor(message: string, code: RpcErrorCode) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = 'RpcError';
|
|
27
|
+
this.code = code;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Turns anything thrown into a cloneable description the other side rebuilds with {@link decodeWireError}. */
|
|
32
|
+
export function encodeWireError(error: unknown): WireError {
|
|
33
|
+
if (error instanceof ContentWriteRefusedError) {
|
|
34
|
+
return {
|
|
35
|
+
name: error.name,
|
|
36
|
+
message: error.message,
|
|
37
|
+
method: error.method,
|
|
38
|
+
refusal: { reason: error.refusal.reason },
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
if (error instanceof StaleWriteError) {
|
|
42
|
+
return { name: error.name, message: error.message, code: error.code, details: error.details, data: error.data };
|
|
43
|
+
}
|
|
44
|
+
if (error instanceof APIClientError) {
|
|
45
|
+
return { name: error.name, message: error.message, code: error.code, details: error.details };
|
|
46
|
+
}
|
|
47
|
+
if (error instanceof RpcError) return { name: error.name, message: error.message, code: error.code };
|
|
48
|
+
if (error instanceof Error) return { name: error.name, message: error.message };
|
|
49
|
+
return { name: 'Error', message: String(error) };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const ERROR_CODES: ReadonlySet<string> = new Set(Object.values(ErrorCodes));
|
|
53
|
+
|
|
54
|
+
function isErrorCode(code: string | undefined): code is APIClientError['code'] {
|
|
55
|
+
return code !== undefined && ERROR_CODES.has(code);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function isRpcErrorCode(code: string | undefined): code is RpcErrorCode {
|
|
59
|
+
return code === 'method_not_allowed' || code === 'bad_arguments' || code === 'rate_limited';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Rebuilds the error class {@link encodeWireError} described, so `instanceof` checks keep working. */
|
|
63
|
+
export function decodeWireError(wire: WireError): Error {
|
|
64
|
+
const { message } = wire;
|
|
65
|
+
// A code this side does not know still rebuilds the class; it only loses the code.
|
|
66
|
+
const code = isErrorCode(wire.code) ? wire.code : ErrorCodes.INTERNAL_ERROR;
|
|
67
|
+
switch (wire.name) {
|
|
68
|
+
case 'ContentWriteRefusedError':
|
|
69
|
+
return new ContentWriteRefusedError(wire.method ?? '', { reason: wire.refusal?.reason ?? message });
|
|
70
|
+
case 'StaleWriteError': {
|
|
71
|
+
const { data } = wire;
|
|
72
|
+
const currentEtag =
|
|
73
|
+
isPlainObject(data) && 'currentEtag' in data && typeof data.currentEtag === 'string'
|
|
74
|
+
? data.currentEtag
|
|
75
|
+
: undefined;
|
|
76
|
+
return new StaleWriteError({ code, message, currentEtag });
|
|
77
|
+
}
|
|
78
|
+
case 'APIClientError':
|
|
79
|
+
return new APIClientError(message, code, wire.details);
|
|
80
|
+
case 'RpcError':
|
|
81
|
+
if (isRpcErrorCode(wire.code)) return new RpcError(message, wire.code);
|
|
82
|
+
break;
|
|
83
|
+
default:
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
const error = new Error(message);
|
|
87
|
+
error.name = wire.name;
|
|
88
|
+
return error;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function isPlainObject(value: unknown): value is object {
|
|
92
|
+
if (typeof value !== 'object' || value === null) return false;
|
|
93
|
+
const proto = Object.getPrototypeOf(value);
|
|
94
|
+
return proto === Object.prototype || proto === null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Reads a {@link WireError} that arrived on the port; `undefined` when `value` is not one. */
|
|
98
|
+
function readWireError(value: unknown): WireError | undefined {
|
|
99
|
+
if (!isPlainObject(value) || !('name' in value) || !('message' in value)) return undefined;
|
|
100
|
+
const { name, message } = value;
|
|
101
|
+
if (typeof name !== 'string' || typeof message !== 'string') return undefined;
|
|
102
|
+
const wire: WireError = { name, message };
|
|
103
|
+
if ('code' in value && typeof value.code === 'string') wire.code = value.code;
|
|
104
|
+
if ('details' in value) wire.details = value.details;
|
|
105
|
+
if ('data' in value) wire.data = value.data;
|
|
106
|
+
if ('method' in value && typeof value.method === 'string') wire.method = value.method;
|
|
107
|
+
if ('refusal' in value && isPlainObject(value.refusal) && 'reason' in value.refusal) {
|
|
108
|
+
const { reason } = value.refusal;
|
|
109
|
+
if (typeof reason === 'string') wire.refusal = { reason };
|
|
110
|
+
}
|
|
111
|
+
return wire;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/* oxlint-disable no-underscore-dangle -- `__wireError` is the protocol's marker for an error inside a value. */
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Swaps every `Error` inside a value for `{ __wireError }`, walking only arrays and plain objects, so a Blob or File
|
|
118
|
+
* travels untouched. Structured cloning would otherwise flatten the errors' classes.
|
|
119
|
+
* shortcut: no cycle detection, values are content-API results; add a seen-set if a cyclic value ever crosses.
|
|
120
|
+
*/
|
|
121
|
+
export function encodeWireValue(value: unknown): unknown {
|
|
122
|
+
if (value instanceof Error) {
|
|
123
|
+
// oxlint-disable-next-line anti-slop/no-known-value-widening -- an encoded value is opaque on the wire; the receiving side decodes it.
|
|
124
|
+
return { __wireError: encodeWireError(value) };
|
|
125
|
+
}
|
|
126
|
+
if (Array.isArray(value)) return value.map(encodeWireValue);
|
|
127
|
+
if (isPlainObject(value)) {
|
|
128
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, encodeWireValue(item)]));
|
|
129
|
+
}
|
|
130
|
+
return value;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Reverses {@link encodeWireValue}. */
|
|
134
|
+
export function decodeWireValue(value: unknown): unknown {
|
|
135
|
+
if (Array.isArray(value)) return value.map(decodeWireValue);
|
|
136
|
+
if (isPlainObject(value)) {
|
|
137
|
+
const wire = '__wireError' in value ? readWireError(value.__wireError) : undefined;
|
|
138
|
+
if (wire) return decodeWireError(wire);
|
|
139
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, decodeWireValue(item)]));
|
|
140
|
+
}
|
|
141
|
+
return value;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/* oxlint-enable no-underscore-dangle */
|
|
145
|
+
|
|
146
|
+
export interface FrameChannelHandlers {
|
|
147
|
+
/** Answers a call from the other side; without it every call answers `method_not_allowed`. */
|
|
148
|
+
call?(method: string, args: unknown[]): Promise<unknown>;
|
|
149
|
+
event?(name: string, payload: unknown): void;
|
|
150
|
+
control?(message: ControlMessage): void;
|
|
151
|
+
/** Receives every message whose shape the channel does not recognise. */
|
|
152
|
+
malformed?(data: unknown): void;
|
|
153
|
+
/** Receives the error of an `emit` or `post` the port could not send; without it the error goes to `console.error`. */
|
|
154
|
+
sendFailed?(error: unknown): void;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export interface FrameChannel {
|
|
158
|
+
call(method: string, args?: unknown[]): Promise<unknown>;
|
|
159
|
+
emit(name: string, payload?: unknown): void;
|
|
160
|
+
post(message: ControlMessage): void;
|
|
161
|
+
/** Stops listening and closes the port; calls still waiting for a result never settle. */
|
|
162
|
+
close(): void;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Carries calls, results, events and control messages over one port between the editor frame and its parent. */
|
|
166
|
+
export function openFrameChannel(port: FramePort, handlers: FrameChannelHandlers): FrameChannel {
|
|
167
|
+
let nextId = 1;
|
|
168
|
+
const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
|
|
169
|
+
|
|
170
|
+
async function answer(id: number, method: string, args: unknown[]): Promise<void> {
|
|
171
|
+
let reply: Result;
|
|
172
|
+
try {
|
|
173
|
+
if (!handlers.call) throw new RpcError(`Method not allowed: ${method}`, 'method_not_allowed');
|
|
174
|
+
reply = { kind: 'result', id, ok: true, value: encodeWireValue(await handlers.call(method, args)) };
|
|
175
|
+
} catch (error) {
|
|
176
|
+
reply = { kind: 'result', id, ok: false, error: encodeWireError(error) };
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
port.postMessage(reply);
|
|
180
|
+
} catch (error) {
|
|
181
|
+
// The value or error could not be cloned; the caller still needs an answer. A plain Error keeps the call error
|
|
182
|
+
// codes to the protocol's own.
|
|
183
|
+
const message = `Result of ${method} could not be sent: ${error instanceof Error ? error.message : String(error)}`;
|
|
184
|
+
port.postMessage({ kind: 'result', id, ok: false, error: { name: 'Error', message } } satisfies Result);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Handles `data` and returns whether it was a message the channel knows. */
|
|
189
|
+
function receive(data: unknown): boolean {
|
|
190
|
+
if (!isPlainObject(data) || !('kind' in data)) return false;
|
|
191
|
+
const { kind } = data;
|
|
192
|
+
const id = 'id' in data ? data.id : undefined;
|
|
193
|
+
if (kind === 'call' && typeof id === 'number' && 'method' in data && 'args' in data) {
|
|
194
|
+
const { method, args } = data;
|
|
195
|
+
if (typeof method !== 'string' || !Array.isArray(args)) return false;
|
|
196
|
+
void answer(id, method, args);
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
if (kind === 'result' && typeof id === 'number' && 'ok' in data) {
|
|
200
|
+
const error = data.ok === false && 'error' in data ? readWireError(data.error) : undefined;
|
|
201
|
+
if (data.ok !== true && !error) return false;
|
|
202
|
+
const entry = pending.get(id);
|
|
203
|
+
pending.delete(id);
|
|
204
|
+
if (error) entry?.reject(decodeWireError(error));
|
|
205
|
+
else entry?.resolve(decodeWireValue('value' in data ? data.value : undefined));
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
208
|
+
if (kind === 'event' && 'name' in data && typeof data.name === 'string') {
|
|
209
|
+
handlers.event?.(data.name, 'payload' in data ? data.payload : undefined);
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
const control = readControlMessage(data);
|
|
213
|
+
if (control) handlers.control?.(control);
|
|
214
|
+
return control !== undefined;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const listener = (event: MessageEvent) => {
|
|
218
|
+
const { data } = event;
|
|
219
|
+
if (!receive(data)) handlers.malformed?.(data);
|
|
220
|
+
};
|
|
221
|
+
port.addEventListener('message', listener);
|
|
222
|
+
port.start();
|
|
223
|
+
|
|
224
|
+
/** Sends a message nobody waits on, so a failure goes to `sendFailed` instead of the code that happened to send. */
|
|
225
|
+
function send(message: FrameEvent | ControlMessage): void {
|
|
226
|
+
try {
|
|
227
|
+
port.postMessage(message);
|
|
228
|
+
} catch (error) {
|
|
229
|
+
if (handlers.sendFailed) handlers.sendFailed(error);
|
|
230
|
+
else console.error('[conloca] frame message could not be sent', error);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return {
|
|
235
|
+
call(method, args = []) {
|
|
236
|
+
const id = nextId++;
|
|
237
|
+
const promise = new Promise<unknown>((resolve, reject) => pending.set(id, { resolve, reject }));
|
|
238
|
+
try {
|
|
239
|
+
port.postMessage({ kind: 'call', id, method, args } satisfies Call);
|
|
240
|
+
} catch (error) {
|
|
241
|
+
pending.delete(id);
|
|
242
|
+
return Promise.reject(error);
|
|
243
|
+
}
|
|
244
|
+
return promise;
|
|
245
|
+
},
|
|
246
|
+
emit(name, payload) {
|
|
247
|
+
send({ kind: 'event', name, payload } satisfies FrameEvent);
|
|
248
|
+
},
|
|
249
|
+
post(message) {
|
|
250
|
+
send(message);
|
|
251
|
+
},
|
|
252
|
+
close() {
|
|
253
|
+
port.removeEventListener('message', listener);
|
|
254
|
+
port.close();
|
|
255
|
+
pending.clear();
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { readPageConversionFacts } from '../convert-pages.js';
|
|
2
|
+
import { EDITOR_DIRTY_CHANGED_EVENT, flushOpenEditor, isOpenEditorDirty } from '../editor-flush.js';
|
|
3
|
+
import type { AssetScope, MediaIssue } from '../media/types.js';
|
|
4
|
+
import { THEME_CHANGED_EVENT, THEME_STORAGE_KEY } from '../theme.js';
|
|
5
|
+
import { setEditorReadOnly, setPageConversion, setPreviewCapability, type UIConfig } from '../ui-config.js';
|
|
6
|
+
import { type FrameChannel, type FramePort, openFrameChannel, RpcError } from './channel.js';
|
|
7
|
+
import {
|
|
8
|
+
EDITOR_FLUSH_METHOD,
|
|
9
|
+
type FrameEventPayloads,
|
|
10
|
+
type FrameMethod,
|
|
11
|
+
type Init,
|
|
12
|
+
isFramePath,
|
|
13
|
+
isPreviewCapability,
|
|
14
|
+
isThemePreference,
|
|
15
|
+
isWriteRefusal,
|
|
16
|
+
type PreviewOpenResult,
|
|
17
|
+
} from './protocol.js';
|
|
18
|
+
import { RpcContentClient } from './rpc-content-client.js';
|
|
19
|
+
import { isSaveCombo } from './save-shortcut.js';
|
|
20
|
+
|
|
21
|
+
/** The editor page's side of its connection to the parent frame, once the parent's settings arrived. */
|
|
22
|
+
export interface EditorFrame {
|
|
23
|
+
/** The parent's settings. */
|
|
24
|
+
init: Init;
|
|
25
|
+
/** The `UIConfig` part the page mounts with: content client, memory router, preview and media through the parent. */
|
|
26
|
+
config: Partial<UIConfig>;
|
|
27
|
+
/** Tells the parent the editor is mounted. */
|
|
28
|
+
ready(): void;
|
|
29
|
+
/** Tells the parent this page is out of date and should be reloaded. */
|
|
30
|
+
reportStale(): void;
|
|
31
|
+
/** Tells the parent the page could not load; `message` is for logs, the parent shows its own text. */
|
|
32
|
+
reportLoadFailed(stage: FrameEventPayloads['load.failed']['stage'], message: string): void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function isPreviewOpenResult(value: unknown): value is PreviewOpenResult {
|
|
36
|
+
if (typeof value !== 'object' || value === null || !('ok' in value)) return false;
|
|
37
|
+
if (value.ok === true) return true;
|
|
38
|
+
if (value.ok !== false || !('reason' in value)) return false;
|
|
39
|
+
if (value.reason === 'popup-blocked') return true;
|
|
40
|
+
return value.reason === 'not-deployed' && 'message' in value && typeof value.message === 'string';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isAssetScope(value: unknown): value is AssetScope | null {
|
|
44
|
+
return value === null || value === 'branch' || value === 'published';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function isMediaIssue(value: unknown): value is MediaIssue | null {
|
|
48
|
+
if (value === null) return true;
|
|
49
|
+
if (typeof value !== 'object' || !('filename' in value) || typeof value.filename !== 'string') return false;
|
|
50
|
+
if (!('kind' in value)) return false;
|
|
51
|
+
if (value.kind === 'blocked') return 'reason' in value && typeof value.reason === 'string';
|
|
52
|
+
return (
|
|
53
|
+
value.kind === 'oversized' &&
|
|
54
|
+
'sizeBytes' in value &&
|
|
55
|
+
typeof value.sizeBytes === 'number' &&
|
|
56
|
+
'limitBytes' in value &&
|
|
57
|
+
typeof value.limitBytes === 'number'
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isBlob(value: unknown): value is Blob {
|
|
62
|
+
return value instanceof Blob;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Calls the parent and rejects an answer that is not the shape the method promises. */
|
|
66
|
+
async function checkedCall<T>(
|
|
67
|
+
channel: FrameChannel,
|
|
68
|
+
method: FrameMethod,
|
|
69
|
+
input: unknown,
|
|
70
|
+
isAnswer: (value: unknown) => value is T,
|
|
71
|
+
): Promise<T> {
|
|
72
|
+
const answer = await channel.call(method, [input]);
|
|
73
|
+
if (!isAnswer(answer)) throw new Error(`${method} answered with an unexpected value`);
|
|
74
|
+
return answer;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Opens the channel on the port the parent handed over and resolves on the parent's first `init`; later ones are
|
|
79
|
+
* ignored. From then on the parent can flush the open editor, and dirty state and Cmd/Ctrl+S go to the parent.
|
|
80
|
+
* Route, read-only, preview capability, theme and page conversion facts follow the parent's events.
|
|
81
|
+
*/
|
|
82
|
+
export function connectEditorFrame(port: FramePort): Promise<EditorFrame> {
|
|
83
|
+
const routeListeners = new Set<(path: string) => void>();
|
|
84
|
+
// Executor form: the package's production lib predates Promise.withResolvers.
|
|
85
|
+
return new Promise((resolve) => {
|
|
86
|
+
let connected = false;
|
|
87
|
+
const channel = openFrameChannel(port, {
|
|
88
|
+
control(message) {
|
|
89
|
+
if (message.kind !== 'init' || connected) return;
|
|
90
|
+
connected = true;
|
|
91
|
+
resolve(start(channel, message, routeListeners));
|
|
92
|
+
},
|
|
93
|
+
async call(method) {
|
|
94
|
+
if (method === EDITOR_FLUSH_METHOD) return flushOpenEditor();
|
|
95
|
+
throw new RpcError(`Method not allowed: ${method}`, 'method_not_allowed');
|
|
96
|
+
},
|
|
97
|
+
event(name, payload) {
|
|
98
|
+
if (typeof payload !== 'object' || payload === null) return;
|
|
99
|
+
if (name === 'route.navigate' && 'path' in payload) {
|
|
100
|
+
const { path } = payload;
|
|
101
|
+
if (typeof path === 'string' && isFramePath(path)) for (const listener of routeListeners) listener(path);
|
|
102
|
+
} else if (
|
|
103
|
+
name === 'readOnly.changed' &&
|
|
104
|
+
'readOnly' in payload &&
|
|
105
|
+
(payload.readOnly === null || isWriteRefusal(payload.readOnly))
|
|
106
|
+
) {
|
|
107
|
+
setEditorReadOnly(payload.readOnly);
|
|
108
|
+
} else if (name === 'pageConversion.changed' && 'pageConversion' in payload) {
|
|
109
|
+
setPageConversion(readPageConversionFacts(payload.pageConversion) ?? null);
|
|
110
|
+
} else if (
|
|
111
|
+
name === 'previewCapability.changed' &&
|
|
112
|
+
'previewCapability' in payload &&
|
|
113
|
+
isPreviewCapability(payload.previewCapability)
|
|
114
|
+
) {
|
|
115
|
+
setPreviewCapability(payload.previewCapability);
|
|
116
|
+
} else if (name === 'theme.changed' && 'theme' in payload && isThemePreference(payload.theme)) {
|
|
117
|
+
localStorage.setItem(THEME_STORAGE_KEY, payload.theme);
|
|
118
|
+
window.dispatchEvent(new Event(THEME_CHANGED_EVENT));
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function start(channel: FrameChannel, init: Init, routeListeners: Set<(path: string) => void>): EditorFrame {
|
|
126
|
+
const emit = <K extends keyof FrameEventPayloads>(name: K, payload: FrameEventPayloads[K]) =>
|
|
127
|
+
channel.emit(name, payload);
|
|
128
|
+
|
|
129
|
+
localStorage.setItem(THEME_STORAGE_KEY, init.theme);
|
|
130
|
+
let dirty = false;
|
|
131
|
+
window.addEventListener(EDITOR_DIRTY_CHANGED_EVENT, () => {
|
|
132
|
+
const next = isOpenEditorDirty();
|
|
133
|
+
if (next === dirty) return;
|
|
134
|
+
dirty = next;
|
|
135
|
+
emit('editor.dirty', { dirty });
|
|
136
|
+
});
|
|
137
|
+
window.addEventListener('keydown', (event) => {
|
|
138
|
+
if (!isSaveCombo(event)) return;
|
|
139
|
+
event.preventDefault();
|
|
140
|
+
emit('shortcut.save', null);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
const config: Partial<UIConfig> = {
|
|
144
|
+
contentClient: new RpcContentClient(channel),
|
|
145
|
+
// Always present, so `configureUI` replaces a refusal left from before.
|
|
146
|
+
readOnly: init.readOnly ?? undefined,
|
|
147
|
+
previewCapability: init.previewCapability,
|
|
148
|
+
...(init.locales ? { locales: init.locales } : {}),
|
|
149
|
+
...(init.pageConversion ? { pageConversion: init.pageConversion } : {}),
|
|
150
|
+
previewTab: 'parent',
|
|
151
|
+
openSiteUrl: async (input) => {
|
|
152
|
+
await channel.call('site.open', [input]);
|
|
153
|
+
},
|
|
154
|
+
openPreview: (input) => checkedCall(channel, 'preview.open', input, isPreviewOpenResult),
|
|
155
|
+
memoryRouter: {
|
|
156
|
+
initialPath: init.initialPath,
|
|
157
|
+
onNavigate: (path, replace) => {
|
|
158
|
+
// The parent refuses any other route, so it is not sent.
|
|
159
|
+
if (isFramePath(path)) emit('route.changed', { path, replace });
|
|
160
|
+
},
|
|
161
|
+
subscribe: (navigate) => {
|
|
162
|
+
routeListeners.add(navigate);
|
|
163
|
+
return () => routeListeners.delete(navigate);
|
|
164
|
+
},
|
|
165
|
+
},
|
|
166
|
+
...(init.mediaEnabled
|
|
167
|
+
? {
|
|
168
|
+
mediaBridge: {
|
|
169
|
+
getAssetScope: (input) => checkedCall(channel, 'mediaBridge.getAssetScope', input, isAssetScope),
|
|
170
|
+
getMediaIssue: (input) => checkedCall(channel, 'mediaBridge.getMediaIssue', input, isMediaIssue),
|
|
171
|
+
},
|
|
172
|
+
loadMedia: (input) => checkedCall(channel, 'media.load', input, isBlob),
|
|
173
|
+
}
|
|
174
|
+
: {}),
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
init,
|
|
179
|
+
config,
|
|
180
|
+
ready: () => channel.post({ kind: 'ready' }),
|
|
181
|
+
reportStale: () => emit('editor.stale', null),
|
|
182
|
+
reportLoadFailed: (stage, message) => emit('load.failed', { stage, message }),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/** Object URLs of media bytes loaded through `UIConfig.loadMedia`, for surfaces that cannot point `<img>` at a media route. */
|
|
2
|
+
import { useRef, useSyncExternalStore } from 'react';
|
|
3
|
+
import { getUIConfig } from '../ui-config.js';
|
|
4
|
+
import type { MediaLoadInput } from './protocol.js';
|
|
5
|
+
|
|
6
|
+
/** shortcut: count cap, not bytes; switch to a byte budget if large libraries show memory pressure. */
|
|
7
|
+
export const MEDIA_CACHE_LIMIT = 300;
|
|
8
|
+
|
|
9
|
+
/** A failed load is tried again on the first read after this long, so a busy or briefly missing image recovers. */
|
|
10
|
+
export const MEDIA_RETRY_AFTER_MS = 30_000;
|
|
11
|
+
|
|
12
|
+
/** Where the bytes of a path stand. */
|
|
13
|
+
export type MediaLoadState = { status: 'loaded'; url: string } | { status: 'loading' } | { status: 'failed' };
|
|
14
|
+
|
|
15
|
+
/** No `url` means loading, or failed when `failedAt` is set. */
|
|
16
|
+
interface MediaEntry {
|
|
17
|
+
url?: string;
|
|
18
|
+
blob?: Blob;
|
|
19
|
+
failedAt?: number;
|
|
20
|
+
/** Settles when the load does, whether it loaded, failed or was discarded. */
|
|
21
|
+
loaded?: Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Map order is recency: a read moves its entry to the end, eviction takes from the front.
|
|
25
|
+
const entries = new Map<string, MediaEntry>();
|
|
26
|
+
const listeners = new Set<() => void>();
|
|
27
|
+
let version = 0;
|
|
28
|
+
// Bumped by every clear, so a mounted hook stops holding on to a URL from before the clear.
|
|
29
|
+
let generation = 0;
|
|
30
|
+
|
|
31
|
+
function notify() {
|
|
32
|
+
version += 1;
|
|
33
|
+
for (const listener of listeners) listener();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function subscribe(listener: () => void) {
|
|
37
|
+
listeners.add(listener);
|
|
38
|
+
return () => {
|
|
39
|
+
listeners.delete(listener);
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function currentVersion() {
|
|
44
|
+
return version;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The entry for `key`, moved to most recently used when it holds a URL. */
|
|
48
|
+
function touch(key: string): MediaEntry | undefined {
|
|
49
|
+
const entry = entries.get(key);
|
|
50
|
+
if (entry?.url) {
|
|
51
|
+
entries.delete(key);
|
|
52
|
+
entries.set(key, entry);
|
|
53
|
+
}
|
|
54
|
+
return entry;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function evict() {
|
|
58
|
+
let held = 0;
|
|
59
|
+
for (const entry of entries.values()) if (entry.url) held += 1;
|
|
60
|
+
for (const [key, entry] of entries) {
|
|
61
|
+
if (held <= MEDIA_CACHE_LIMIT) return;
|
|
62
|
+
if (!entry.url) continue;
|
|
63
|
+
URL.revokeObjectURL(entry.url);
|
|
64
|
+
entries.delete(key);
|
|
65
|
+
held -= 1;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The entry of `path` on `route`: a hit refreshes its recency; a miss, or a failure older than
|
|
71
|
+
* `MEDIA_RETRY_AFTER_MS`, starts its one load. `undefined` without a loader.
|
|
72
|
+
*/
|
|
73
|
+
function entryFor(route: MediaLoadInput['route'], path: string): MediaEntry | undefined {
|
|
74
|
+
const key = `${route}:${path}`;
|
|
75
|
+
const entry = touch(key);
|
|
76
|
+
if (entry && (entry.failedAt === undefined || Date.now() - entry.failedAt < MEDIA_RETRY_AFTER_MS)) return entry;
|
|
77
|
+
const loadMedia = getUIConfig().loadMedia;
|
|
78
|
+
if (!loadMedia) return undefined;
|
|
79
|
+
const pending: MediaEntry = {};
|
|
80
|
+
entries.set(key, pending);
|
|
81
|
+
pending.loaded = loadMedia({ route, path }).then(
|
|
82
|
+
(blob) => {
|
|
83
|
+
// Cleared (or replaced) while loading: these bytes may be stale.
|
|
84
|
+
if (entries.get(key) !== pending) return;
|
|
85
|
+
pending.url = URL.createObjectURL(blob);
|
|
86
|
+
pending.blob = blob;
|
|
87
|
+
touch(key);
|
|
88
|
+
evict();
|
|
89
|
+
notify();
|
|
90
|
+
},
|
|
91
|
+
() => {
|
|
92
|
+
if (entries.get(key) !== pending) return;
|
|
93
|
+
pending.failedAt = Date.now();
|
|
94
|
+
notify();
|
|
95
|
+
// Mounted images read again when the retry is due.
|
|
96
|
+
setTimeout(notify, MEDIA_RETRY_AFTER_MS);
|
|
97
|
+
},
|
|
98
|
+
);
|
|
99
|
+
return pending;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Where the bytes of `path` on `route` stand; starts the load on a miss. `undefined` without a loader. */
|
|
103
|
+
export function mediaLoadState(route: MediaLoadInput['route'], path: string): MediaLoadState | undefined {
|
|
104
|
+
const entry = entryFor(route, path);
|
|
105
|
+
if (entry === undefined) return undefined;
|
|
106
|
+
if (entry.url) return { status: 'loaded', url: entry.url };
|
|
107
|
+
return entry.failedAt === undefined ? { status: 'loading' } : { status: 'failed' };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The object URL of `path` on `route`: a hit refreshes its recency; a miss starts one load and
|
|
112
|
+
* returns `undefined` (so does a key that is loading or failed, and every key without a loader).
|
|
113
|
+
*/
|
|
114
|
+
export function mediaObjectUrl(route: MediaLoadInput['route'], path: string): string | undefined {
|
|
115
|
+
return entryFor(route, path)?.url;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The object URL and bytes of `path` on `route` once loaded through the same cache; `undefined` if that fails or there is no loader. */
|
|
119
|
+
export async function loadedMedia(
|
|
120
|
+
route: MediaLoadInput['route'],
|
|
121
|
+
path: string,
|
|
122
|
+
): Promise<{ url: string; blob: Blob } | undefined> {
|
|
123
|
+
const entry = entryFor(route, path);
|
|
124
|
+
await entry?.loaded;
|
|
125
|
+
return entry?.url && entry.blob ? { url: entry.url, blob: entry.blob } : undefined;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Revokes every URL and forgets every key, failed ones included; loads still running are discarded when they land. */
|
|
129
|
+
export function clearMediaCache(): void {
|
|
130
|
+
for (const entry of entries.values()) if (entry.url) URL.revokeObjectURL(entry.url);
|
|
131
|
+
entries.clear();
|
|
132
|
+
generation += 1;
|
|
133
|
+
notify();
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** A number that changes whenever a URL arrives or the cache is cleared; re-renders the caller then. */
|
|
137
|
+
export function useMediaCacheVersion(): number {
|
|
138
|
+
return useSyncExternalStore(subscribe, currentVersion, currentVersion);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The object URL of `path` on `route`, re-rendering when it arrives. Once shown, a URL stays
|
|
143
|
+
* for the same key until the cache is cleared, even if eviction drops its entry meanwhile, so
|
|
144
|
+
* a mounted thumbnail neither flickers nor loads again.
|
|
145
|
+
*/
|
|
146
|
+
export function useMediaObjectUrl(route: MediaLoadInput['route'], path: string): string | undefined {
|
|
147
|
+
useMediaCacheVersion();
|
|
148
|
+
const key = `${route}:${path}`;
|
|
149
|
+
const shown = useRef<{ key: string; url: string; generation: number } | undefined>(undefined);
|
|
150
|
+
if (shown.current?.key === key && shown.current.generation === generation) {
|
|
151
|
+
touch(key);
|
|
152
|
+
return shown.current.url;
|
|
153
|
+
}
|
|
154
|
+
const url = mediaObjectUrl(route, path);
|
|
155
|
+
if (url) shown.current = { key, url, generation };
|
|
156
|
+
return url;
|
|
157
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { createPath, type DataRouter, NavigationType, parsePath } from 'react-router-dom';
|
|
2
|
+
import type { MemoryRouterConfig } from '../ui-config.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Mirrors the editor's in-memory route to a parent frame: each committed route
|
|
6
|
+
* (`pathname + search`) goes to `onNavigate`, and each route the parent asks for
|
|
7
|
+
* is navigated to without being reported back. Returns the function that stops
|
|
8
|
+
* both directions.
|
|
9
|
+
*/
|
|
10
|
+
export function syncMemoryRouter(router: DataRouter, options: MemoryRouterConfig): () => void {
|
|
11
|
+
const { location } = router.state;
|
|
12
|
+
let current = location.pathname + location.search;
|
|
13
|
+
let parentPath: string | undefined;
|
|
14
|
+
|
|
15
|
+
const stopRouter = router.subscribe((state) => {
|
|
16
|
+
if (state.navigation.state !== 'idle') return;
|
|
17
|
+
const path = state.location.pathname + state.location.search;
|
|
18
|
+
if (path === current) return;
|
|
19
|
+
current = path;
|
|
20
|
+
// Any commit settles the parent's request, so an interrupted one cannot swallow a later route.
|
|
21
|
+
const fromParent = path === parentPath;
|
|
22
|
+
parentPath = undefined;
|
|
23
|
+
if (!fromParent) options.onNavigate(path, state.historyAction === NavigationType.Replace);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const stopParent = options.subscribe((path) => {
|
|
27
|
+
// In the router's own spelling (`/media?` is `/media`), or the commit would not match and be echoed back.
|
|
28
|
+
const normalized = createPath(parsePath(path));
|
|
29
|
+
// Already there: navigating would only push a duplicate entry.
|
|
30
|
+
if (normalized === current) return;
|
|
31
|
+
parentPath = normalized;
|
|
32
|
+
void router.navigate(path);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
return () => {
|
|
36
|
+
stopRouter();
|
|
37
|
+
stopParent();
|
|
38
|
+
};
|
|
39
|
+
}
|