@wordpress/media-editor 0.23.0 → 0.24.0
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/CHANGELOG.md +16 -0
- package/build/components/media-editor/index.cjs +157 -107
- package/build/components/media-editor/index.cjs.map +1 -1
- package/build/components/media-editor/use-save-media-editor.cjs +18 -8
- package/build/components/media-editor/use-save-media-editor.cjs.map +1 -1
- package/build/components/media-editor-canvas/index.cjs +9 -7
- package/build/components/media-editor-canvas/index.cjs.map +1 -1
- package/build/components/media-editor-crop-panel/index.cjs +9 -7
- package/build/components/media-editor-crop-panel/index.cjs.map +1 -1
- package/build/components/media-editor-fine-rotation/index.cjs +9 -7
- package/build/components/media-editor-fine-rotation/index.cjs.map +1 -1
- package/build/components/media-editor-keyboard-shortcuts-modal/index.cjs +32 -33
- package/build/components/media-editor-keyboard-shortcuts-modal/index.cjs.map +1 -1
- package/build/components/media-editor-modal/index.cjs +10 -7
- package/build/components/media-editor-modal/index.cjs.map +1 -1
- package/build/components/media-editor-panel/error-boundary.cjs +68 -0
- package/build/components/media-editor-panel/error-boundary.cjs.map +1 -0
- package/build/components/media-editor-panel/index.cjs +158 -0
- package/build/components/media-editor-panel/index.cjs.map +1 -0
- package/build/components/media-preview/index.cjs +143 -36
- package/build/components/media-preview/index.cjs.map +1 -1
- package/build/components/rotation-ruler/index.cjs +9 -7
- package/build/components/rotation-ruler/index.cjs.map +1 -1
- package/build/components/rotation-ruler/use-ruler-drag.cjs.map +1 -1
- package/build/hooks/use-crop-gesture-handlers.cjs.map +1 -1
- package/build/index.cjs +10 -8
- package/build/private-apis.cjs.map +1 -1
- package/build/state/aspect-ratio-presets.cjs +2 -2
- package/build/state/aspect-ratio-presets.cjs.map +1 -1
- package/build/state/composite-reducer.cjs +9 -7
- package/build/state/composite-reducer.cjs.map +1 -1
- package/build/state/use-media-editor-state.cjs.map +1 -1
- package/build/store/index.cjs +11 -9
- package/build/store/index.cjs.map +1 -1
- package/build/utils/get-media-type.cjs +8 -0
- package/build/utils/get-media-type.cjs.map +1 -1
- package/build/utils/index.cjs +6 -0
- package/build-module/components/media-editor/index.mjs +142 -95
- package/build-module/components/media-editor/index.mjs.map +1 -1
- package/build-module/components/media-editor/use-save-media-editor.mjs +9 -1
- package/build-module/components/media-editor/use-save-media-editor.mjs.map +1 -1
- package/build-module/components/media-editor-keyboard-shortcuts-modal/index.mjs +32 -33
- package/build-module/components/media-editor-keyboard-shortcuts-modal/index.mjs.map +1 -1
- package/build-module/components/media-editor-modal/index.mjs +1 -0
- package/build-module/components/media-editor-modal/index.mjs.map +1 -1
- package/build-module/components/media-editor-panel/error-boundary.mjs +63 -0
- package/build-module/components/media-editor-panel/error-boundary.mjs.map +1 -0
- package/build-module/components/media-editor-panel/index.mjs +123 -0
- package/build-module/components/media-editor-panel/index.mjs.map +1 -0
- package/build-module/components/media-preview/index.mjs +123 -40
- package/build-module/components/media-preview/index.mjs.map +1 -1
- package/build-module/state/aspect-ratio-presets.mjs +2 -2
- package/build-module/state/aspect-ratio-presets.mjs.map +1 -1
- package/build-module/state/use-media-editor-state.mjs.map +1 -1
- package/build-module/utils/get-media-type.mjs +8 -1
- package/build-module/utils/get-media-type.mjs.map +1 -1
- package/build-module/utils/index.mjs +1 -1
- package/build-style/style-rtl.css +18 -30
- package/build-style/style.css +18 -30
- package/build-types/components/media-editor/index.d.ts +8 -0
- package/build-types/components/media-editor/index.d.ts.map +1 -1
- package/build-types/components/media-editor-keyboard-shortcuts-modal/index.d.ts.map +1 -1
- package/build-types/components/media-editor-modal/index.d.ts.map +1 -1
- package/build-types/components/media-editor-panel/error-boundary.d.ts +23 -0
- package/build-types/components/media-editor-panel/error-boundary.d.ts.map +1 -0
- package/build-types/components/media-editor-panel/index.d.ts +46 -0
- package/build-types/components/media-editor-panel/index.d.ts.map +1 -0
- package/build-types/components/media-preview/index.d.ts.map +1 -1
- package/build-types/state/use-media-editor-state.d.ts +7 -2
- package/build-types/state/use-media-editor-state.d.ts.map +1 -1
- package/build-types/utils/get-media-type.d.ts +3 -1
- package/build-types/utils/get-media-type.d.ts.map +1 -1
- package/build-types/utils/index.d.ts +1 -1
- package/build-types/utils/index.d.ts.map +1 -1
- package/package.json +26 -22
- package/src/components/media-editor/index.tsx +209 -114
- package/src/components/media-editor/style.scss +21 -1
- package/src/components/media-editor-keyboard-shortcuts-modal/index.tsx +55 -63
- package/src/components/media-editor-modal/index.tsx +3 -0
- package/src/components/media-editor-panel/error-boundary.tsx +88 -0
- package/src/components/media-editor-panel/index.tsx +211 -0
- package/src/components/media-preview/index.tsx +195 -36
- package/src/components/media-preview/style.scss +11 -32
- package/src/state/README.md +3 -1
- package/src/state/use-media-editor-state.ts +7 -2
- package/src/utils/get-media-type.ts +9 -1
- package/src/utils/index.ts +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-boundary.mjs","names":[],"sources":["../../../src/components/media-editor-panel/error-boundary.tsx"],"sourcesContent":["import { Component } from '@wordpress/element';\nimport { speak } from '@wordpress/a11y';\nimport { useCopyToClipboard } from '@wordpress/compose';\nimport { __, _x, sprintf } from '@wordpress/i18n';\nimport { Notice } from '@wordpress/ui';\nimport type { ReactNode } from 'react';\n\ninterface Props {\n\ttitle: string;\n\tchildren: ReactNode;\n}\n\ninterface State {\n\t/** Separate from `error`: a panel can throw a falsy value. */\n\thasError: boolean;\n\terror: unknown;\n}\n\nfunction getMessage( title: string ) {\n\treturn {\n\t\ttitle: sprintf(\n\t\t\t/* translators: %s: the panel's title. */\n\t\t\t__( 'The \"%s\" panel could not be shown' ),\n\t\t\ttitle\n\t\t),\n\t\tdescription: __(\n\t\t\t'An unknown error occurred. Reload your browser to try again, or copy the error to report the problem or search.'\n\t\t),\n\t};\n}\n\n// A component, because the copy hook cannot run in the class below.\nfunction CopyErrorButton( { error }: { error: unknown } ) {\n\tconst ref = useCopyToClipboard< HTMLButtonElement >( () => {\n\t\t// A boundary catches whatever was thrown, which is not always an `Error`.\n\t\tconst { message, stack } = ( error ?? {} ) as {\n\t\t\tmessage?: unknown;\n\t\t\tstack?: unknown;\n\t\t};\n\t\tconst text = [ error, message ].find(\n\t\t\t( part ) => typeof part === 'string' && part\n\t\t);\n\t\treturn [ text ?? 'An unknown error occurred.', stack ]\n\t\t\t.filter( ( part ) => typeof part === 'string' && part )\n\t\t\t.join( '\\n\\n' );\n\t} );\n\treturn (\n\t\t<Notice.ActionButton variant=\"outline\" ref={ ref }>\n\t\t\t{ _x( 'Copy error', 'button label' ) }\n\t\t</Notice.ActionButton>\n\t);\n}\n\n/**\n * Keeps a panel's failure inside its tab, so the rest of the editor stays\n * usable.\n */\nexport default class MediaEditorPanelErrorBoundary extends Component<\n\tProps,\n\tState\n> {\n\tstate: State = { hasError: false, error: null };\n\n\tstatic getDerivedStateFromError( error: unknown ): State {\n\t\treturn { hasError: true, error };\n\t}\n\n\tcomponentDidCatch() {\n\t\tconst { title, description } = getMessage( this.props.title );\n\t\tspeak( `${ title }. ${ description }`, 'assertive' );\n\t}\n\n\trender() {\n\t\tif ( ! this.state.hasError ) {\n\t\t\treturn this.props.children;\n\t\t}\n\t\tconst { title, description } = getMessage( this.props.title );\n\t\treturn (\n\t\t\t<Notice.Root intent=\"error\">\n\t\t\t\t<Notice.Title>{ title }</Notice.Title>\n\t\t\t\t<Notice.Description>{ description }</Notice.Description>\n\t\t\t\t<Notice.Actions>\n\t\t\t\t\t<CopyErrorButton error={ this.state.error } />\n\t\t\t\t</Notice.Actions>\n\t\t\t</Notice.Root>\n\t\t);\n\t}\n}\n"],"mappings":";;;;;;;AAkBA,SAAS,WAAY,OAAgB;CACpC,OAAO;EACN,OAAO;;GAEN,GAAI,qCAAoC;GACxC;EACD;EACA,aAAa,GACZ,iHACD;CACD;AACD;AAGA,SAAS,gBAAiB,EAAE,SAA8B;CACzD,MAAM,MAAM,yBAA+C;EAE1D,MAAM,EAAE,SAAS,UAAY,SAAS,CAAC;EAOvC,OAAO,CAHM,CAAE,OAAO,OAAQ,CAAC,CAAC,MAC7B,SAAU,OAAO,SAAS,YAAY,IAEhC,KAAQ,8BAA8B,KAAM,CAAA,CACnD,QAAU,SAAU,OAAO,SAAS,YAAY,IAAK,CAAA,CACrD,KAAM,MAAO;CAChB,CAAE;CACF,OACC,oBAAC,OAAO,cAAR;EAAqB,SAAQ;EAAgB;EAC1C,UAAA,GAAI,cAAc,cAAe;CACf,CAAA;AAEvB;;;;;AAMA,IAAqB,gCAArB,cAA2D,UAGzD;CACD,QAAe;EAAE,UAAU;EAAO,OAAO;CAAK;CAE9C,OAAO,yBAA0B,OAAwB;EACxD,OAAO;GAAE,UAAU;GAAM;EAAM;CAChC;CAEA,oBAAoB;EACnB,MAAM,EAAE,OAAO,gBAAgB,WAAY,KAAK,MAAM,KAAM;EAC5D,MAAO,GAAI,MAAO,IAAK,eAAgB,WAAY;CACpD;CAEA,SAAS;EACR,IAAK,CAAE,KAAK,MAAM,UACjB,OAAO,KAAK,MAAM;EAEnB,MAAM,EAAE,OAAO,gBAAgB,WAAY,KAAK,MAAM,KAAM;EAC5D,OACC,qBAAC,OAAO,MAAR;GAAa,QAAO;GAApB,UAAA;IACC,oBAAC,OAAO,OAAR,EAAA,UAAgB,MAAqB,CAAA;IACrC,oBAAC,OAAO,aAAR,EAAA,UAAsB,YAAiC,CAAA;IACvD,oBAAC,OAAO,SAAR,EAAA,UACC,oBAAC,iBAAD,EAAiB,OAAQ,KAAK,MAAM,MAAS,CAAA,EAC9B,CAAA;GACJ;;CAEf;AACD"}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import fastDeepEqual from "fast-deep-equal/es6/index.js";
|
|
2
|
+
import { Fill } from "@wordpress/components";
|
|
3
|
+
import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState } from "@wordpress/element";
|
|
4
|
+
import warning from "@wordpress/warning";
|
|
5
|
+
import { MEDIA_TYPES } from "../../utils/index.mjs";
|
|
6
|
+
import MediaEditorPanelErrorBoundary from "./error-boundary.mjs";
|
|
7
|
+
import { jsx } from "react/jsx-runtime";
|
|
8
|
+
// packages/media-editor/src/components/media-editor-panel/index.tsx
|
|
9
|
+
const MediaEditorPanelsContext = createContext(null);
|
|
10
|
+
const MediaEditorPanelsProvider = MediaEditorPanelsContext.Provider;
|
|
11
|
+
/** The `registerPlugin` scope the editor mounts. */
|
|
12
|
+
const MEDIA_EDITOR_PLUGIN_SCOPE = "media-editor";
|
|
13
|
+
/** `vendor/panel`: lowercase letters, digits and dashes, with one slash. */
|
|
14
|
+
const PANEL_NAME_PATTERN = /^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/;
|
|
15
|
+
function getPanelSlotName(name) {
|
|
16
|
+
return `MediaEditorPanel/${name}`;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The mounted panels of one editor.
|
|
20
|
+
*
|
|
21
|
+
* @return The panels, in the order they mounted, and the context value to provide to them.
|
|
22
|
+
*/
|
|
23
|
+
function useMediaEditorPanels() {
|
|
24
|
+
const [panels, setPanels] = useState({});
|
|
25
|
+
const ownersRef = useRef(/* @__PURE__ */ new Map());
|
|
26
|
+
const register = useCallback((panel, instance) => {
|
|
27
|
+
const owner = ownersRef.current.get(panel.name);
|
|
28
|
+
if (owner && owner !== instance) {
|
|
29
|
+
warning(`A media editor panel named "${panel.name}" is already registered, so this one is not shown. Give each panel a unique name.`);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
ownersRef.current.set(panel.name, instance);
|
|
33
|
+
setPanels((current) => {
|
|
34
|
+
const entry = current[panel.name];
|
|
35
|
+
if (entry?.owner === instance && fastDeepEqual(entry.registration, panel)) return current;
|
|
36
|
+
return {
|
|
37
|
+
...current,
|
|
38
|
+
[panel.name]: {
|
|
39
|
+
registration: panel,
|
|
40
|
+
owner: instance
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
});
|
|
44
|
+
}, []);
|
|
45
|
+
const unregister = useCallback((name, instance) => {
|
|
46
|
+
if (ownersRef.current.get(name) !== instance) return;
|
|
47
|
+
ownersRef.current.delete(name);
|
|
48
|
+
setPanels((current) => {
|
|
49
|
+
if (!Object.hasOwn(current, name)) return current;
|
|
50
|
+
const next = { ...current };
|
|
51
|
+
delete next[name];
|
|
52
|
+
return next;
|
|
53
|
+
});
|
|
54
|
+
}, []);
|
|
55
|
+
const owners = useMemo(() => Object.fromEntries(Object.entries(panels).map(([name, { owner }]) => [name, owner])), [panels]);
|
|
56
|
+
const contextValue = useMemo(() => ({
|
|
57
|
+
register,
|
|
58
|
+
unregister,
|
|
59
|
+
owners
|
|
60
|
+
}), [
|
|
61
|
+
register,
|
|
62
|
+
unregister,
|
|
63
|
+
owners
|
|
64
|
+
]);
|
|
65
|
+
return {
|
|
66
|
+
panels: useMemo(() => Object.values(panels).map(({ registration }) => registration), [panels]),
|
|
67
|
+
contextValue
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** A tab in the media editor's sidebar, filled with its children. */
|
|
71
|
+
function MediaEditorPanel({ name, title, mediaTypes, children }) {
|
|
72
|
+
const context = useContext(MediaEditorPanelsContext);
|
|
73
|
+
if (!context) throw new Error("MediaEditorPanel is rendered outside the media editor.");
|
|
74
|
+
const { register, unregister, owners } = context;
|
|
75
|
+
const [instance] = useState(() => ({}));
|
|
76
|
+
const owner = owners[name];
|
|
77
|
+
useLayoutEffect(() => {
|
|
78
|
+
if (!PANEL_NAME_PATTERN.test(name)) warning(`The media editor panel name "${name}" should be namespaced, like "my-plugin/my-panel": lowercase letters, digits and dashes, with one slash.`);
|
|
79
|
+
mediaTypes?.forEach((type) => {
|
|
80
|
+
if (!MEDIA_TYPES.includes(type)) warning(`The media editor panel "${name}" lists the media type "${type}", which the editor does not know, so the panel would never show for it. Known types: ${MEDIA_TYPES.join(", ")}.`);
|
|
81
|
+
});
|
|
82
|
+
register({
|
|
83
|
+
name,
|
|
84
|
+
title,
|
|
85
|
+
mediaTypes
|
|
86
|
+
}, instance);
|
|
87
|
+
}, [
|
|
88
|
+
name,
|
|
89
|
+
title,
|
|
90
|
+
mediaTypes,
|
|
91
|
+
register,
|
|
92
|
+
owner,
|
|
93
|
+
instance
|
|
94
|
+
]);
|
|
95
|
+
useLayoutEffect(() => {
|
|
96
|
+
return () => unregister(name, instance);
|
|
97
|
+
}, [
|
|
98
|
+
name,
|
|
99
|
+
unregister,
|
|
100
|
+
instance
|
|
101
|
+
]);
|
|
102
|
+
if (owner !== instance) return null;
|
|
103
|
+
return /* @__PURE__ */ jsx(Fill, {
|
|
104
|
+
name: getPanelSlotName(name),
|
|
105
|
+
children: (fillProps) => /* @__PURE__ */ jsx(MediaEditorPanelErrorBoundary, {
|
|
106
|
+
title,
|
|
107
|
+
children: /* @__PURE__ */ jsx(MediaEditorPanelContent, {
|
|
108
|
+
fillProps,
|
|
109
|
+
children
|
|
110
|
+
})
|
|
111
|
+
})
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Calls a function child inside the error boundary, so one that throws is
|
|
116
|
+
* caught there.
|
|
117
|
+
*/
|
|
118
|
+
function MediaEditorPanelContent({ fillProps, children }) {
|
|
119
|
+
return typeof children === "function" ? children(fillProps) : children;
|
|
120
|
+
}
|
|
121
|
+
export { MEDIA_EDITOR_PLUGIN_SCOPE, MediaEditorPanelsProvider, MediaEditorPanel as default, getPanelSlotName, useMediaEditorPanels };
|
|
122
|
+
|
|
123
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/components/media-editor-panel/index.tsx"],"sourcesContent":["import fastDeepEqual from 'fast-deep-equal/es6/index.js';\nimport { Fill } from '@wordpress/components';\nimport {\n\tcreateContext,\n\tuseCallback,\n\tuseContext,\n\tuseLayoutEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState,\n} from '@wordpress/element';\nimport warning from '@wordpress/warning';\nimport type { ReactNode } from 'react';\nimport { MEDIA_TYPES, type MediaType } from '../../utils';\nimport MediaEditorPanelErrorBoundary from './error-boundary';\n\nexport interface MediaEditorPanelFillProps {\n\t/** `true` while a save is running. */\n\tdisabled: boolean;\n}\n\nexport interface MediaEditorPanelRegistration {\n\t/** Unique, namespaced name, for example `core/crop`. */\n\tname: string;\n\t/** Tab label. */\n\ttitle: string;\n\t/** Omitted means every type. */\n\tmediaTypes?: readonly MediaType[ 'type' ][];\n}\n\nexport interface MediaEditorPanelProps extends MediaEditorPanelRegistration {\n\tchildren:\n\t\tReactNode | ( ( fillProps: MediaEditorPanelFillProps ) => ReactNode );\n}\n\ninterface MediaEditorPanelsContextValue {\n\tregister: ( panel: MediaEditorPanelRegistration, instance: object ) => void;\n\tunregister: ( name: string, instance: object ) => void;\n\t/** Panel name to the mounted panel that has it. */\n\towners: Record< string, object >;\n}\n\nconst MediaEditorPanelsContext =\n\tcreateContext< MediaEditorPanelsContextValue | null >( null );\n\nexport const MediaEditorPanelsProvider = MediaEditorPanelsContext.Provider;\n\n/** The `registerPlugin` scope the editor mounts. */\nexport const MEDIA_EDITOR_PLUGIN_SCOPE = 'media-editor';\n\n/** `vendor/panel`: lowercase letters, digits and dashes, with one slash. */\nconst PANEL_NAME_PATTERN = /^[a-z][a-z0-9-]*\\/[a-z][a-z0-9-]*$/;\n\nexport function getPanelSlotName( name: string ) {\n\treturn `MediaEditorPanel/${ name }`;\n}\n\n/**\n * The mounted panels of one editor.\n *\n * @return The panels, in the order they mounted, and the context value to provide to them.\n */\nexport function useMediaEditorPanels() {\n\tconst [ panels, setPanels ] = useState<\n\t\tRecord<\n\t\t\tstring,\n\t\t\t{ registration: MediaEditorPanelRegistration; owner: object }\n\t\t>\n\t>( {} );\n\t// The first panel to announce a name keeps it. A ref, so panels\n\t// announcing in the same commit see each other.\n\tconst ownersRef = useRef( new Map< string, object >() );\n\tconst register = useCallback(\n\t\t( panel: MediaEditorPanelRegistration, instance: object ) => {\n\t\t\tconst owner = ownersRef.current.get( panel.name );\n\t\t\tif ( owner && owner !== instance ) {\n\t\t\t\twarning(\n\t\t\t\t\t`A media editor panel named \"${ panel.name }\" is already registered, so this one is not shown. Give each panel a unique name.`\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\townersRef.current.set( panel.name, instance );\n\t\t\tsetPanels( ( current ) => {\n\t\t\t\t// Skip unchanged details: an inline `mediaTypes` array would\n\t\t\t\t// otherwise re-render the editor and the panel in a loop.\n\t\t\t\tconst entry = current[ panel.name ];\n\t\t\t\tif (\n\t\t\t\t\tentry?.owner === instance &&\n\t\t\t\t\tfastDeepEqual( entry.registration, panel )\n\t\t\t\t) {\n\t\t\t\t\treturn current;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\t...current,\n\t\t\t\t\t[ panel.name ]: { registration: panel, owner: instance },\n\t\t\t\t};\n\t\t\t} );\n\t\t},\n\t\t[]\n\t);\n\tconst unregister = useCallback( ( name: string, instance: object ) => {\n\t\tif ( ownersRef.current.get( name ) !== instance ) {\n\t\t\treturn;\n\t\t}\n\t\townersRef.current.delete( name );\n\t\tsetPanels( ( current ) => {\n\t\t\tif ( ! Object.hasOwn( current, name ) ) {\n\t\t\t\treturn current;\n\t\t\t}\n\t\t\tconst next = { ...current };\n\t\t\tdelete next[ name ];\n\t\t\treturn next;\n\t\t} );\n\t}, [] );\n\tconst owners = useMemo(\n\t\t() =>\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries( panels ).map( ( [ name, { owner } ] ) => [\n\t\t\t\t\tname,\n\t\t\t\t\towner,\n\t\t\t\t] )\n\t\t\t),\n\t\t[ panels ]\n\t);\n\tconst contextValue = useMemo(\n\t\t() => ( { register, unregister, owners } ),\n\t\t[ register, unregister, owners ]\n\t);\n\tconst registrations = useMemo(\n\t\t() =>\n\t\t\tObject.values( panels ).map( ( { registration } ) => registration ),\n\t\t[ panels ]\n\t);\n\treturn { panels: registrations, contextValue };\n}\n\n/** A tab in the media editor's sidebar, filled with its children. */\nexport default function MediaEditorPanel( {\n\tname,\n\ttitle,\n\tmediaTypes,\n\tchildren,\n}: MediaEditorPanelProps ) {\n\tconst context = useContext( MediaEditorPanelsContext );\n\tif ( ! context ) {\n\t\tthrow new Error(\n\t\t\t'MediaEditorPanel is rendered outside the media editor.'\n\t\t);\n\t}\n\tconst { register, unregister, owners } = context;\n\t// Identifies this mounted panel.\n\tconst [ instance ] = useState( () => ( {} ) );\n\tconst owner = owners[ name ];\n\t// Layout effects, so the tab exists before the sidebar paints. Two of\n\t// them: details may change on any render, but the tab only goes when\n\t// the panel unmounts or changes its name.\n\tuseLayoutEffect( () => {\n\t\tif ( ! PANEL_NAME_PATTERN.test( name ) ) {\n\t\t\twarning(\n\t\t\t\t`The media editor panel name \"${ name }\" should be namespaced, like \"my-plugin/my-panel\": lowercase letters, digits and dashes, with one slash.`\n\t\t\t);\n\t\t}\n\t\tmediaTypes?.forEach( ( type ) => {\n\t\t\tif ( ! MEDIA_TYPES.includes( type ) ) {\n\t\t\t\twarning(\n\t\t\t\t\t`The media editor panel \"${ name }\" lists the media type \"${ type }\", which the editor does not know, so the panel would never show for it. Known types: ${ MEDIA_TYPES.join( ', ' ) }.`\n\t\t\t\t);\n\t\t\t}\n\t\t} );\n\t\tregister( { name, title, mediaTypes }, instance );\n\t\t// When two panels share a name, the second waits for the first to\n\t\t// unmount. `owner` changes at that point, which re-runs this effect\n\t\t// and gives the second panel the tab.\n\t}, [ name, title, mediaTypes, register, owner, instance ] );\n\tuseLayoutEffect( () => {\n\t\treturn () => unregister( name, instance );\n\t}, [ name, unregister, instance ] );\n\n\tif ( owner !== instance ) {\n\t\treturn null;\n\t}\n\n\treturn (\n\t\t<Fill name={ getPanelSlotName( name ) }>\n\t\t\t{ ( fillProps ) => (\n\t\t\t\t<MediaEditorPanelErrorBoundary title={ title }>\n\t\t\t\t\t<MediaEditorPanelContent\n\t\t\t\t\t\t// The slot passes exactly these props; `Fill` types them loosely.\n\t\t\t\t\t\tfillProps={ fillProps as MediaEditorPanelFillProps }\n\t\t\t\t\t>\n\t\t\t\t\t\t{ children }\n\t\t\t\t\t</MediaEditorPanelContent>\n\t\t\t\t</MediaEditorPanelErrorBoundary>\n\t\t\t) }\n\t\t</Fill>\n\t);\n}\n\n/**\n * Calls a function child inside the error boundary, so one that throws is\n * caught there.\n */\nfunction MediaEditorPanelContent( {\n\tfillProps,\n\tchildren,\n}: {\n\tfillProps: MediaEditorPanelFillProps;\n\tchildren: MediaEditorPanelProps[ 'children' ];\n} ) {\n\treturn typeof children === 'function' ? children( fillProps ) : children;\n}\n"],"mappings":";;;;;;;;AA0CA,MAAM,2BACL,cAAuD,IAAK;AAE7D,MAAa,4BAA4B,yBAAyB;;AAGlE,MAAa,4BAA4B;;AAGzC,MAAM,qBAAqB;AAE3B,SAAgB,iBAAkB,MAAe;CAChD,OAAO,oBAAqB;AAC7B;;;;;;AAOA,SAAgB,uBAAuB;CACtC,MAAM,CAAE,QAAQ,aAAc,SAK3B,CAAC,CAAE;CAGN,MAAM,YAAY,uBAAQ,IAAI,IAAsB,CAAE;CACtD,MAAM,WAAW,aACd,OAAqC,aAAsB;EAC5D,MAAM,QAAQ,UAAU,QAAQ,IAAK,MAAM,IAAK;EAChD,IAAK,SAAS,UAAU,UAAW;GAClC,QACC,+BAAgC,MAAM,KAAM,kFAC7C;GACA;EACD;EACA,UAAU,QAAQ,IAAK,MAAM,MAAM,QAAS;EAC5C,WAAa,YAAa;GAGzB,MAAM,QAAQ,QAAS,MAAM;GAC7B,IACC,OAAO,UAAU,YACjB,cAAe,MAAM,cAAc,KAAM,GAEzC,OAAO;GAER,OAAO;IACN,GAAG;KACD,MAAM,OAAQ;KAAE,cAAc;KAAO,OAAO;IAAS;GACxD;EACD,CAAE;CACH,GACA,CAAC,CACF;CACA,MAAM,aAAa,aAAe,MAAc,aAAsB;EACrE,IAAK,UAAU,QAAQ,IAAK,IAAK,MAAM,UACtC;EAED,UAAU,QAAQ,OAAQ,IAAK;EAC/B,WAAa,YAAa;GACzB,IAAK,CAAE,OAAO,OAAQ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AC/B,WAAA,cACH,oBAAC,+BAAD;GAAuC;GACtC,UAAA,oBAAC,yBAAD;IAEa;IAEV;GACsB,CAAA;EACK,CAAA;CAE3B,CAAA;AAER;;;;;AAMA,SAAS,wBAAyB,EACjC,WACA,YAIG;CACH,OAAO,OAAO,aAAa,aAAa,SAAU,SAAU,IAAI;AACjE"}
|
|
@@ -1,32 +1,98 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import clsx from "clsx";
|
|
2
|
+
import { speak } from "@wordpress/a11y";
|
|
3
|
+
import { Button, Spinner } from "@wordpress/components";
|
|
4
|
+
import { useCopyToClipboard } from "@wordpress/compose";
|
|
5
|
+
import { useEffect, useState } from "@wordpress/element";
|
|
6
|
+
import { __, _x, sprintf } from "@wordpress/i18n";
|
|
7
|
+
import { check, copy, download, error, folder } from "@wordpress/icons";
|
|
8
|
+
import { EmptyState } from "@wordpress/ui";
|
|
4
9
|
import { useMediaEditorContext } from "../media-editor-provider/index.mjs";
|
|
5
10
|
import { getMediaTypeFromMimeType } from "../../utils/index.mjs";
|
|
6
|
-
import { jsx, jsxs } from "react/jsx-runtime";
|
|
11
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
7
12
|
// packages/media-editor/src/components/media-preview/index.tsx
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
13
|
+
/**
|
|
14
|
+
* Returns the value of one of the attachment fields for the media, or an
|
|
15
|
+
* empty string if the field isn't available.
|
|
16
|
+
*
|
|
17
|
+
* @param fields The attachment fields.
|
|
18
|
+
* @param fieldId The id of the field to read.
|
|
19
|
+
* @param media The media record.
|
|
20
|
+
*/
|
|
21
|
+
function getFieldValue(fields, fieldId, media) {
|
|
22
|
+
const value = fields.find(({ id }) => id === fieldId)?.getValue?.({ item: media });
|
|
23
|
+
return typeof value === "string" ? value : "";
|
|
24
|
+
}
|
|
25
|
+
const COPY_FEEDBACK_TIMEOUT = 2e3;
|
|
26
|
+
const COPY_RESULT_ICONS = {
|
|
27
|
+
idle: copy,
|
|
28
|
+
copied: check,
|
|
29
|
+
error
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Copies the text and shows the result on the copy button, following the
|
|
33
|
+
* Copy to Clipboard design system pattern.
|
|
34
|
+
*
|
|
35
|
+
* @param text The text to copy.
|
|
36
|
+
*/
|
|
37
|
+
function useCopyWithFeedback(text) {
|
|
38
|
+
const [feedback, setFeedback] = useState({
|
|
39
|
+
result: "idle",
|
|
40
|
+
id: 0
|
|
27
41
|
});
|
|
42
|
+
useEffect(() => {
|
|
43
|
+
if (feedback.result === "idle") return;
|
|
44
|
+
const timeoutId = setTimeout(() => setFeedback({
|
|
45
|
+
result: "idle",
|
|
46
|
+
id: 0
|
|
47
|
+
}), COPY_FEEDBACK_TIMEOUT);
|
|
48
|
+
return () => clearTimeout(timeoutId);
|
|
49
|
+
}, [feedback]);
|
|
50
|
+
function report(result, message) {
|
|
51
|
+
setFeedback((current) => ({
|
|
52
|
+
result,
|
|
53
|
+
id: current.id + 1
|
|
54
|
+
}));
|
|
55
|
+
speak(message);
|
|
56
|
+
}
|
|
57
|
+
const ref = useCopyToClipboard(text, () => report("copied", __("Copied URL to clipboard.")), () => report("error", __("Couldn't copy URL to clipboard.")));
|
|
58
|
+
return {
|
|
59
|
+
result: feedback.result,
|
|
60
|
+
ref
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function MediaPreviewFileActions({ mediaUrl }) {
|
|
64
|
+
const { result, ref } = useCopyWithFeedback(mediaUrl);
|
|
65
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Button, {
|
|
66
|
+
__next40pxDefaultSize: true,
|
|
67
|
+
variant: "primary",
|
|
68
|
+
href: mediaUrl,
|
|
69
|
+
target: "_blank",
|
|
70
|
+
download: true,
|
|
71
|
+
icon: download,
|
|
72
|
+
children: __("Download")
|
|
73
|
+
}), /* @__PURE__ */ jsx(Button, {
|
|
74
|
+
__next40pxDefaultSize: true,
|
|
75
|
+
variant: "secondary",
|
|
76
|
+
ref,
|
|
77
|
+
icon: COPY_RESULT_ICONS[result],
|
|
78
|
+
children: __("Copy URL")
|
|
79
|
+
})] });
|
|
28
80
|
}
|
|
29
|
-
function
|
|
81
|
+
function MediaPreviewFileInfo({ mediaUrl, fileName, fileDetails }) {
|
|
82
|
+
return /* @__PURE__ */ jsxs(EmptyState.Root, { children: [
|
|
83
|
+
/* @__PURE__ */ jsx(EmptyState.Icon, { icon: folder }),
|
|
84
|
+
!!fileName && /* @__PURE__ */ jsx(EmptyState.Title, {
|
|
85
|
+
className: "media-editor-preview__file-name",
|
|
86
|
+
children: fileName
|
|
87
|
+
}),
|
|
88
|
+
!!fileDetails && /* @__PURE__ */ jsx(EmptyState.Description, { children: fileDetails }),
|
|
89
|
+
/* @__PURE__ */ jsx(EmptyState.Actions, {
|
|
90
|
+
className: "media-editor-preview__actions",
|
|
91
|
+
children: /* @__PURE__ */ jsx(MediaPreviewFileActions, { mediaUrl })
|
|
92
|
+
})
|
|
93
|
+
] });
|
|
94
|
+
}
|
|
95
|
+
function MediaPreviewContent({ previewType, mediaUrl, altText, displayTitle, fileName, fileDetails, onLoad, onError, loadingState }) {
|
|
30
96
|
switch (previewType) {
|
|
31
97
|
case "image": return /* @__PURE__ */ jsx("img", {
|
|
32
98
|
className: loadingState === "loaded" ? "loaded" : "",
|
|
@@ -54,14 +120,14 @@ function MediaPreviewContent({ previewType, mediaUrl, altText, displayTitle, mim
|
|
|
54
120
|
"aria-label": __("Embed of the selected PDF file."),
|
|
55
121
|
children: /* @__PURE__ */ jsx(MediaPreviewFileInfo, {
|
|
56
122
|
mediaUrl,
|
|
57
|
-
|
|
58
|
-
|
|
123
|
+
fileName,
|
|
124
|
+
fileDetails
|
|
59
125
|
})
|
|
60
126
|
});
|
|
61
127
|
default: return /* @__PURE__ */ jsx(MediaPreviewFileInfo, {
|
|
62
128
|
mediaUrl,
|
|
63
|
-
|
|
64
|
-
|
|
129
|
+
fileName,
|
|
130
|
+
fileDetails
|
|
65
131
|
});
|
|
66
132
|
}
|
|
67
133
|
}
|
|
@@ -74,25 +140,41 @@ function MediaPreviewContent({ previewType, mediaUrl, altText, displayTitle, mim
|
|
|
74
140
|
*/
|
|
75
141
|
function MediaPreview(props) {
|
|
76
142
|
const [loadingState, setLoadingState] = useState("loading");
|
|
77
|
-
const { media } = useMediaEditorContext();
|
|
143
|
+
const { media, fields } = useMediaEditorContext();
|
|
78
144
|
const { source_url: mediaUrl, mime_type: mimeType, alt_text: altText, title } = media || {};
|
|
79
145
|
const mediaType = getMediaTypeFromMimeType(mimeType);
|
|
80
146
|
const previewType = mimeType === "application/pdf" && window.navigator.pdfViewerEnabled ? "pdf" : mediaType.type;
|
|
81
147
|
if (!mediaUrl) return /* @__PURE__ */ jsx("div", {
|
|
82
|
-
className: "media-editor-preview media-editor-preview--empty",
|
|
83
|
-
children: /* @__PURE__ */ jsx(
|
|
84
|
-
});
|
|
85
|
-
if (loadingState === "error") return /* @__PURE__ */ jsxs("div", {
|
|
86
|
-
className: "media-editor-preview media-editor-preview--error",
|
|
87
|
-
children: [/* @__PURE__ */ jsx("p", { children: __("Failed to load media file.") }), /* @__PURE__ */ jsx("p", {
|
|
88
|
-
className: "media-editor-preview__url",
|
|
89
|
-
children: mediaUrl
|
|
90
|
-
})]
|
|
148
|
+
className: "media-editor-preview media-editor-preview--empty is-placeholder",
|
|
149
|
+
children: /* @__PURE__ */ jsxs(EmptyState.Root, { children: [/* @__PURE__ */ jsx(EmptyState.Icon, { icon: folder }), /* @__PURE__ */ jsx(EmptyState.Title, { children: __("No media file available.") })] })
|
|
91
150
|
});
|
|
92
151
|
const displayTitle = typeof title === "string" ? title : title?.rendered || title?.raw;
|
|
152
|
+
const fileName = media && getFieldValue(fields, "filename", media) || displayTitle;
|
|
153
|
+
const fileSize = media ? getFieldValue(fields, "filesize", media) : "";
|
|
154
|
+
const fileDetails = mimeType && fileSize ? sprintf(
|
|
155
|
+
/** translators: 1: File type, e.g. "application/zip". 2: File size, e.g. "2.4 MB". */
|
|
156
|
+
_x("%1$s · %2$s", "file type and size"),
|
|
157
|
+
mimeType,
|
|
158
|
+
fileSize
|
|
159
|
+
) : mimeType || fileSize;
|
|
160
|
+
if (loadingState === "error") return /* @__PURE__ */ jsx("div", {
|
|
161
|
+
className: "media-editor-preview media-editor-preview--error is-placeholder",
|
|
162
|
+
children: /* @__PURE__ */ jsxs(EmptyState.Root, { children: [
|
|
163
|
+
/* @__PURE__ */ jsx(EmptyState.Icon, { icon: folder }),
|
|
164
|
+
/* @__PURE__ */ jsx(EmptyState.Title, { children: __("Failed to load media file.") }),
|
|
165
|
+
!!fileName && /* @__PURE__ */ jsx(EmptyState.Description, {
|
|
166
|
+
className: "media-editor-preview__file-name",
|
|
167
|
+
children: fileName
|
|
168
|
+
}),
|
|
169
|
+
/* @__PURE__ */ jsx(EmptyState.Actions, {
|
|
170
|
+
className: "media-editor-preview__actions",
|
|
171
|
+
children: /* @__PURE__ */ jsx(MediaPreviewFileActions, { mediaUrl })
|
|
172
|
+
})
|
|
173
|
+
] })
|
|
174
|
+
});
|
|
93
175
|
return /* @__PURE__ */ jsxs("div", {
|
|
94
176
|
...props,
|
|
95
|
-
className:
|
|
177
|
+
className: clsx("media-editor-preview", `media-editor-preview--${previewType}`, { "is-placeholder": previewType === "application" }),
|
|
96
178
|
children: [previewType === "image" && loadingState === "loading" && /* @__PURE__ */ jsx("div", {
|
|
97
179
|
className: "media-editor-preview__spinner",
|
|
98
180
|
children: /* @__PURE__ */ jsx(Spinner, {})
|
|
@@ -101,7 +183,8 @@ function MediaPreview(props) {
|
|
|
101
183
|
mediaUrl,
|
|
102
184
|
altText,
|
|
103
185
|
displayTitle,
|
|
104
|
-
|
|
186
|
+
fileName,
|
|
187
|
+
fileDetails,
|
|
105
188
|
onLoad: () => setLoadingState("loaded"),
|
|
106
189
|
onError: () => setLoadingState("error"),
|
|
107
190
|
loadingState
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["WCSpinner"],"sources":["../../../src/components/media-preview/index.tsx"],"sourcesContent":["import { Spinner as WCSpinner } from '@wordpress/components';\nimport { useState } from '@wordpress/element';\nimport { __ } from '@wordpress/i18n';\nimport { useMediaEditorContext } from '../media-editor-provider';\nimport { getMediaTypeFromMimeType } from '../../utils';\n\n/**\n * Props for MediaPreview component.\n */\nexport interface MediaPreviewProps {\n\t[ key: string ]: any; // TODO: Define specific props as needed, this will likely be for click handlers, accessibility attributes, etc.\n}\n\n/**\n * Props for MediaPreviewContent component.\n */\ninterface MediaPreviewContentProps {\n\tpreviewType: string;\n\tmediaUrl: string;\n\taltText?: string;\n\tdisplayTitle?: string;\n\tmimeType?: string;\n\tonLoad: () => void;\n\tonError: () => void;\n\tloadingState: 'loading' | 'loaded' | 'error';\n}\n\ninterface MediaPreviewFileInfoProps {\n\tmediaUrl: string;\n\tdisplayTitle?: string;\n\tmimeType?: string;\n}\n\nfunction MediaPreviewFileInfo( {\n\tmediaUrl,\n\tdisplayTitle,\n\tmimeType,\n}: MediaPreviewFileInfoProps ) {\n\treturn (\n\t\t<div className=\"media-editor-preview__file-info\">\n\t\t\t<p className=\"media-editor-preview__file-name\">{ displayTitle }</p>\n\t\t\t<p className=\"media-editor-preview__mime-type\">{ mimeType }</p>\n\t\t\t{ /* eslint-disable-next-line react/jsx-no-target-blank */ }\n\t\t\t<a\n\t\t\t\thref={ mediaUrl }\n\t\t\t\ttarget=\"_blank\"\n\t\t\t\tclassName=\"media-editor-preview__download-link\"\n\t\t\t>\n\t\t\t\t{ __( 'View file' ) }\n\t\t\t</a>\n\t\t</div>\n\t);\n}\n\nfunction MediaPreviewContent( {\n\tpreviewType,\n\tmediaUrl,\n\taltText,\n\tdisplayTitle,\n\tmimeType,\n\tonLoad,\n\tonError,\n\tloadingState,\n}: MediaPreviewContentProps ) {\n\tswitch ( previewType ) {\n\t\tcase 'image':\n\t\t\treturn (\n\t\t\t\t<img\n\t\t\t\t\tclassName={ loadingState === 'loaded' ? 'loaded' : '' }\n\t\t\t\t\tsrc={ mediaUrl }\n\t\t\t\t\talt={ altText || '' }\n\t\t\t\t\tonLoad={ onLoad }\n\t\t\t\t\tonError={ onError }\n\t\t\t\t/>\n\t\t\t);\n\t\tcase 'video':\n\t\t\treturn (\n\t\t\t\t<video src={ mediaUrl } controls onError={ onError }>\n\t\t\t\t\t{ displayTitle }\n\t\t\t\t</video>\n\t\t\t);\n\t\tcase 'audio':\n\t\t\treturn (\n\t\t\t\t<audio src={ mediaUrl } controls onError={ onError }>\n\t\t\t\t\t{ displayTitle }\n\t\t\t\t</audio>\n\t\t\t);\n\t\tcase 'pdf':\n\t\t\t// The browser renders the children instead of the PDF when it\n\t\t\t// can't display it, e.g. when the request fails.\n\t\t\treturn (\n\t\t\t\t<object\n\t\t\t\t\tclassName=\"media-editor-preview__pdf\"\n\t\t\t\t\t// Ask the viewer to fit the whole page rather than the\n\t\t\t\t\t// width. Chrome reads `view`, Firefox reads `zoom`, and\n\t\t\t\t\t// Safari ignores both.\n\t\t\t\t\tdata={ `${ mediaUrl }#view=Fit&zoom=page-fit` }\n\t\t\t\t\ttype=\"application/pdf\"\n\t\t\t\t\taria-label={ __( 'Embed of the selected PDF file.' ) }\n\t\t\t\t>\n\t\t\t\t\t<MediaPreviewFileInfo\n\t\t\t\t\t\tmediaUrl={ mediaUrl }\n\t\t\t\t\t\tdisplayTitle={ displayTitle }\n\t\t\t\t\t\tmimeType={ mimeType }\n\t\t\t\t\t/>\n\t\t\t\t</object>\n\t\t\t);\n\t\tdefault:\n\t\t\treturn (\n\t\t\t\t<MediaPreviewFileInfo\n\t\t\t\t\tmediaUrl={ mediaUrl }\n\t\t\t\t\tdisplayTitle={ displayTitle }\n\t\t\t\t\tmimeType={ mimeType }\n\t\t\t\t/>\n\t\t\t);\n\t}\n}\n\n/**\n * MediaPreview component displays the media file in the editor canvas.\n * Supports images, videos, audio files, and generic file displays.\n *\n * @param props - Component props including click handlers and accessibility attributes.\n * @return The MediaPreview component.\n */\nexport default function MediaPreview( props: MediaPreviewProps ) {\n\tconst [ loadingState, setLoadingState ] = useState<\n\t\t'loading' | 'loaded' | 'error'\n\t>( 'loading' );\n\tconst { media } = useMediaEditorContext();\n\n\tconst {\n\t\tsource_url: mediaUrl,\n\t\tmime_type: mimeType,\n\t\talt_text: altText,\n\t\ttitle,\n\t} = media || {};\n\n\tconst mediaType = getMediaTypeFromMimeType( mimeType );\n\n\t// Without a built-in PDF viewer (e.g. on most mobile browsers), show\n\t// the file info instead of an embed that can't render.\n\tconst previewType =\n\t\tmimeType === 'application/pdf' && window.navigator.pdfViewerEnabled\n\t\t\t? 'pdf'\n\t\t\t: mediaType.type;\n\n\tif ( ! mediaUrl ) {\n\t\treturn (\n\t\t\t<div className=\"media-editor-preview media-editor-preview--empty\">\n\t\t\t\t<p>{ __( 'No media file available.' ) }</p>\n\t\t\t</div>\n\t\t);\n\t}\n\n\tif ( loadingState === 'error' ) {\n\t\treturn (\n\t\t\t<div className=\"media-editor-preview media-editor-preview--error\">\n\t\t\t\t<p>{ __( 'Failed to load media file.' ) }</p>\n\t\t\t\t<p className=\"media-editor-preview__url\">{ mediaUrl }</p>\n\t\t\t</div>\n\t\t);\n\t}\n\n\tconst displayTitle =\n\t\ttypeof title === 'string' ? title : title?.rendered || title?.raw;\n\n\treturn (\n\t\t<div\n\t\t\t{ ...props }\n\t\t\tclassName={ `media-editor-preview media-editor-preview--${ previewType }` }\n\t\t>\n\t\t\t{ previewType === 'image' && loadingState === 'loading' && (\n\t\t\t\t<div className=\"media-editor-preview__spinner\">\n\t\t\t\t\t<WCSpinner />\n\t\t\t\t</div>\n\t\t\t) }\n\t\t\t<MediaPreviewContent\n\t\t\t\tpreviewType={ previewType }\n\t\t\t\tmediaUrl={ mediaUrl }\n\t\t\t\taltText={ altText }\n\t\t\t\tdisplayTitle={ displayTitle }\n\t\t\t\tmimeType={ mimeType }\n\t\t\t\tonLoad={ () => setLoadingState( 'loaded' ) }\n\t\t\t\tonError={ () => setLoadingState( 'error' ) }\n\t\t\t\tloadingState={ loadingState }\n\t\t\t/>\n\t\t</div>\n\t);\n}\n"],"mappings":";;;;;;;AAiCA,SAAS,qBAAsB,EAC9B,UACA,cACA,YAC8B;CAC9B,OACC,qBAAC,OAAD;EAAK,WAAU;EAAf,UAAA;GACC,oBAAC,KAAD;IAAG,WAAU;IAAoC,UAAA;GAAiB,CAAA;GAClE,oBAAC,KAAD;IAAG,WAAU;IAAoC,UAAA;GAAa,CAAA;GAE9D,oBAAC,KAAD;IACC,MAAO;IACP,QAAO;IACP,WAAU;IAER,UAAA,GAAI,WAAY;GAChB,CAAA;EACC;;AAEP;AAEA,SAAS,oBAAqB,EAC7B,aACA,UACA,SACA,cACA,UACA,QACA,SACA,gBAC6B;CAC7B,QAAS,aAAT;EACC,KAAK,SACJ,OACC,oBAAC,OAAD;GACC,WAAY,iBAAiB,WAAW,WAAW;GACnD,KAAM;GACN,KAAM,WAAW;GACR;GACC;EACV,CAAA;EAEH,KAAK,SACJ,OACC,oBAAC,SAAD;GAAO,KAAM;GAAW,UAAA;GAAmB;GACxC,UAAA;EACI,CAAA;EAET,KAAK,SACJ,OACC,oBAAC,SAAD;GAAO,KAAM;GAAW,UAAA;GAAmB;GACxC,UAAA;EACI,CAAA;EAET,KAAK,OAGJ,OACC,oBAAC,UAAD;GACC,WAAU;GAIV,MAAO,GAAI,SAAU;GACrB,MAAK;GACL,cAAa,GAAI,iCAAkC;GAEnD,UAAA,oBAAC,sBAAD;IACY;IACI;IACJ;GACX,CAAA;EACM,CAAA;EAEV,SACC,OACC,oBAAC,sBAAD;GACY;GACI;GACJ;EACX,CAAA;CAEJ;AACD;;;;;;;;AASA,SAAwB,aAAc,OAA2B;CAChE,MAAM,CAAE,cAAc,mBAAoB,SAEvC,SAAU;CACb,MAAM,EAAE,UAAU,sBAAsB;CAExC,MAAM,EACL,YAAY,UACZ,WAAW,UACX,UAAU,SACV,UACG,SAAS,CAAC;CAEd,MAAM,YAAY,yBAA0B,QAAS;CAIrD,MAAM,cACL,aAAa,qBAAqB,OAAO,UAAU,mBAChD,QACA,UAAU;CAEd,IAAK,CAAE,UACN,OACC,oBAAC,OAAD;EAAK,WAAU;EACd,UAAA,oBAAC,KAAD,EAAA,UAAK,GAAI,0BAA2B,EAAM,CAAA;CACtC,CAAA;CAIP,IAAK,iBAAiB,SACrB,OACC,qBAAC,OAAD;EAAK,WAAU;EAAf,UAAA,CACC,oBAAC,KAAD,EAAA,UAAK,GAAI,4BAA6B,EAAM,CAAA,GAC5C,oBAAC,KAAD;GAAG,WAAU;GAA8B,UAAA;EAAa,CAAA,CACpD;;CAIP,MAAM,eACL,OAAO,UAAU,WAAW,QAAQ,OAAO,YAAY,OAAO;CAE/D,OACC,qBAAC,OAAD;EACC,GAAK;EACL,WAAY,8CAA+C;EAF5D,UAAA,CAIG,gBAAgB,WAAW,iBAAiB,aAC7C,oBAAC,OAAD;GAAK,WAAU;GACd,UAAA,oBAACA,SAAD,CAAY,CAAA;EACR,CAAA,GAEN,oBAAC,qBAAD;GACe;GACH;GACD;GACK;GACJ;GACX,cAAe,gBAAiB,QAAS;GACzC,eAAgB,gBAAiB,OAAQ;GAC1B;EACf,CAAA,CACG;;AAEP"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["errorIcon","WCSpinner"],"sources":["../../../src/components/media-preview/index.tsx"],"sourcesContent":["import clsx from 'clsx';\nimport { speak } from '@wordpress/a11y';\nimport { Button, Spinner as WCSpinner } from '@wordpress/components';\nimport { useCopyToClipboard } from '@wordpress/compose';\nimport { useEffect, useState } from '@wordpress/element';\nimport { __, _x, sprintf } from '@wordpress/i18n';\nimport {\n\tcheck,\n\tcopy,\n\tdownload,\n\terror as errorIcon,\n\tfolder,\n} from '@wordpress/icons';\nimport { EmptyState } from '@wordpress/ui';\nimport { useMediaEditorContext } from '../media-editor-provider';\nimport type { Media } from '../media-editor-provider';\nimport { getMediaTypeFromMimeType } from '../../utils';\n\n/**\n * Props for MediaPreview component.\n */\nexport interface MediaPreviewProps {\n\t[ key: string ]: any; // TODO: Define specific props as needed, this will likely be for click handlers, accessibility attributes, etc.\n}\n\n/**\n * Props for MediaPreviewContent component.\n */\ninterface MediaPreviewContentProps {\n\tpreviewType: string;\n\tmediaUrl: string;\n\taltText?: string;\n\tdisplayTitle?: string;\n\tfileName?: string;\n\tfileDetails?: string;\n\tonLoad: () => void;\n\tonError: () => void;\n\tloadingState: 'loading' | 'loaded' | 'error';\n}\n\n/**\n * Returns the value of one of the attachment fields for the media, or an\n * empty string if the field isn't available.\n *\n * @param fields The attachment fields.\n * @param fieldId The id of the field to read.\n * @param media The media record.\n */\nfunction getFieldValue(\n\tfields: Array< {\n\t\tid: string;\n\t\tgetValue?: ( args: { item: Media } ) => unknown;\n\t} >,\n\tfieldId: string,\n\tmedia: Media\n): string {\n\tconst field = fields.find( ( { id } ) => id === fieldId );\n\tconst value = field?.getValue?.( { item: media } );\n\treturn typeof value === 'string' ? value : '';\n}\n\nconst COPY_FEEDBACK_TIMEOUT = 2000;\n\ntype CopyResult = 'idle' | 'copied' | 'error';\n\nconst COPY_RESULT_ICONS = {\n\tidle: copy,\n\tcopied: check,\n\terror: errorIcon,\n};\n\n/**\n * Copies the text and shows the result on the copy button, following the\n * Copy to Clipboard design system pattern.\n *\n * @param text The text to copy.\n */\nfunction useCopyWithFeedback( text: string ) {\n\t// Bump the id on every result, so a repeat of the same result restarts\n\t// the time the icon stays visible.\n\tconst [ feedback, setFeedback ] = useState< {\n\t\tresult: CopyResult;\n\t\tid: number;\n\t} >( { result: 'idle', id: 0 } );\n\n\tuseEffect( () => {\n\t\tif ( feedback.result === 'idle' ) {\n\t\t\treturn;\n\t\t}\n\t\tconst timeoutId = setTimeout(\n\t\t\t() => setFeedback( { result: 'idle', id: 0 } ),\n\t\t\tCOPY_FEEDBACK_TIMEOUT\n\t\t);\n\t\treturn () => clearTimeout( timeoutId );\n\t}, [ feedback ] );\n\n\tfunction report( result: Exclude< CopyResult, 'idle' >, message: string ) {\n\t\tsetFeedback( ( current ) => ( { result, id: current.id + 1 } ) );\n\t\tspeak( message );\n\t}\n\n\tconst ref = useCopyToClipboard(\n\t\ttext,\n\t\t() => report( 'copied', __( 'Copied URL to clipboard.' ) ),\n\t\t() => report( 'error', __( \"Couldn't copy URL to clipboard.\" ) )\n\t);\n\n\treturn { result: feedback.result, ref };\n}\n\nfunction MediaPreviewFileActions( { mediaUrl }: { mediaUrl: string } ) {\n\tconst { result, ref } = useCopyWithFeedback( mediaUrl );\n\n\treturn (\n\t\t<>\n\t\t\t{ /*\n\t\t\t * Browsers ignore `download` for cross-origin URLs, e.g. media\n\t\t\t * offloaded to a CDN, and show the file instead. Open it in a new\n\t\t\t * tab so it doesn't replace the editor.\n\t\t\t */ }\n\t\t\t<Button\n\t\t\t\t__next40pxDefaultSize\n\t\t\t\tvariant=\"primary\"\n\t\t\t\thref={ mediaUrl }\n\t\t\t\ttarget=\"_blank\"\n\t\t\t\tdownload\n\t\t\t\ticon={ download }\n\t\t\t>\n\t\t\t\t{ __( 'Download' ) }\n\t\t\t</Button>\n\t\t\t{ /* The label stays the same, and the icon shows the result. */ }\n\t\t\t<Button\n\t\t\t\t__next40pxDefaultSize\n\t\t\t\tvariant=\"secondary\"\n\t\t\t\tref={ ref }\n\t\t\t\ticon={ COPY_RESULT_ICONS[ result ] }\n\t\t\t>\n\t\t\t\t{ __( 'Copy URL' ) }\n\t\t\t</Button>\n\t\t</>\n\t);\n}\n\ninterface MediaPreviewFileInfoProps {\n\tmediaUrl: string;\n\tfileName?: string;\n\tfileDetails?: string;\n}\n\nfunction MediaPreviewFileInfo( {\n\tmediaUrl,\n\tfileName,\n\tfileDetails,\n}: MediaPreviewFileInfoProps ) {\n\treturn (\n\t\t<EmptyState.Root>\n\t\t\t<EmptyState.Icon icon={ folder } />\n\t\t\t{ !! fileName && (\n\t\t\t\t<EmptyState.Title className=\"media-editor-preview__file-name\">\n\t\t\t\t\t{ fileName }\n\t\t\t\t</EmptyState.Title>\n\t\t\t) }\n\t\t\t{ !! fileDetails && (\n\t\t\t\t<EmptyState.Description>{ fileDetails }</EmptyState.Description>\n\t\t\t) }\n\t\t\t<EmptyState.Actions className=\"media-editor-preview__actions\">\n\t\t\t\t<MediaPreviewFileActions mediaUrl={ mediaUrl } />\n\t\t\t</EmptyState.Actions>\n\t\t</EmptyState.Root>\n\t);\n}\n\nfunction MediaPreviewContent( {\n\tpreviewType,\n\tmediaUrl,\n\taltText,\n\tdisplayTitle,\n\tfileName,\n\tfileDetails,\n\tonLoad,\n\tonError,\n\tloadingState,\n}: MediaPreviewContentProps ) {\n\tswitch ( previewType ) {\n\t\tcase 'image':\n\t\t\treturn (\n\t\t\t\t<img\n\t\t\t\t\tclassName={ loadingState === 'loaded' ? 'loaded' : '' }\n\t\t\t\t\tsrc={ mediaUrl }\n\t\t\t\t\talt={ altText || '' }\n\t\t\t\t\tonLoad={ onLoad }\n\t\t\t\t\tonError={ onError }\n\t\t\t\t/>\n\t\t\t);\n\t\tcase 'video':\n\t\t\treturn (\n\t\t\t\t<video src={ mediaUrl } controls onError={ onError }>\n\t\t\t\t\t{ displayTitle }\n\t\t\t\t</video>\n\t\t\t);\n\t\tcase 'audio':\n\t\t\treturn (\n\t\t\t\t<audio src={ mediaUrl } controls onError={ onError }>\n\t\t\t\t\t{ displayTitle }\n\t\t\t\t</audio>\n\t\t\t);\n\t\tcase 'pdf':\n\t\t\t// The browser renders the children instead of the PDF when it\n\t\t\t// can't display it, e.g. when the request fails.\n\t\t\treturn (\n\t\t\t\t<object\n\t\t\t\t\tclassName=\"media-editor-preview__pdf\"\n\t\t\t\t\t// Ask the viewer to fit the whole page rather than the\n\t\t\t\t\t// width. Chrome reads `view`, Firefox reads `zoom`, and\n\t\t\t\t\t// Safari ignores both.\n\t\t\t\t\tdata={ `${ mediaUrl }#view=Fit&zoom=page-fit` }\n\t\t\t\t\ttype=\"application/pdf\"\n\t\t\t\t\taria-label={ __( 'Embed of the selected PDF file.' ) }\n\t\t\t\t>\n\t\t\t\t\t<MediaPreviewFileInfo\n\t\t\t\t\t\tmediaUrl={ mediaUrl }\n\t\t\t\t\t\tfileName={ fileName }\n\t\t\t\t\t\tfileDetails={ fileDetails }\n\t\t\t\t\t/>\n\t\t\t\t</object>\n\t\t\t);\n\t\tdefault:\n\t\t\treturn (\n\t\t\t\t<MediaPreviewFileInfo\n\t\t\t\t\tmediaUrl={ mediaUrl }\n\t\t\t\t\tfileName={ fileName }\n\t\t\t\t\tfileDetails={ fileDetails }\n\t\t\t\t/>\n\t\t\t);\n\t}\n}\n\n/**\n * MediaPreview component displays the media file in the editor canvas.\n * Supports images, videos, audio files, and generic file displays.\n *\n * @param props - Component props including click handlers and accessibility attributes.\n * @return The MediaPreview component.\n */\nexport default function MediaPreview( props: MediaPreviewProps ) {\n\tconst [ loadingState, setLoadingState ] = useState<\n\t\t'loading' | 'loaded' | 'error'\n\t>( 'loading' );\n\tconst { media, fields } = useMediaEditorContext();\n\n\tconst {\n\t\tsource_url: mediaUrl,\n\t\tmime_type: mimeType,\n\t\talt_text: altText,\n\t\ttitle,\n\t} = media || {};\n\n\tconst mediaType = getMediaTypeFromMimeType( mimeType );\n\n\t// Without a built-in PDF viewer (e.g. on most mobile browsers), show\n\t// the file info instead of an embed that can't render.\n\tconst previewType =\n\t\tmimeType === 'application/pdf' && window.navigator.pdfViewerEnabled\n\t\t\t? 'pdf'\n\t\t\t: mediaType.type;\n\n\tif ( ! mediaUrl ) {\n\t\treturn (\n\t\t\t<div className=\"media-editor-preview media-editor-preview--empty is-placeholder\">\n\t\t\t\t<EmptyState.Root>\n\t\t\t\t\t<EmptyState.Icon icon={ folder } />\n\t\t\t\t\t<EmptyState.Title>\n\t\t\t\t\t\t{ __( 'No media file available.' ) }\n\t\t\t\t\t</EmptyState.Title>\n\t\t\t\t</EmptyState.Root>\n\t\t\t</div>\n\t\t);\n\t}\n\n\tconst displayTitle =\n\t\ttypeof title === 'string' ? title : title?.rendered || title?.raw;\n\n\t// Read through the attachment fields, so the values match the Details\n\t// panel. Without a filename field, fall back to the title.\n\tconst fileName =\n\t\t( media && getFieldValue( fields, 'filename', media ) ) || displayTitle;\n\tconst fileSize = media ? getFieldValue( fields, 'filesize', media ) : '';\n\tconst fileDetails =\n\t\tmimeType && fileSize\n\t\t\t? sprintf(\n\t\t\t\t\t/* translators: 1: File type, e.g. \"application/zip\". 2: File size, e.g. \"2.4 MB\". */\n\t\t\t\t\t_x( '%1$s · %2$s', 'file type and size' ),\n\t\t\t\t\tmimeType,\n\t\t\t\t\tfileSize\n\t\t\t\t)\n\t\t\t: mimeType || fileSize;\n\n\tif ( loadingState === 'error' ) {\n\t\treturn (\n\t\t\t<div className=\"media-editor-preview media-editor-preview--error is-placeholder\">\n\t\t\t\t<EmptyState.Root>\n\t\t\t\t\t<EmptyState.Icon icon={ folder } />\n\t\t\t\t\t<EmptyState.Title>\n\t\t\t\t\t\t{ __( 'Failed to load media file.' ) }\n\t\t\t\t\t</EmptyState.Title>\n\t\t\t\t\t{ !! fileName && (\n\t\t\t\t\t\t<EmptyState.Description className=\"media-editor-preview__file-name\">\n\t\t\t\t\t\t\t{ fileName }\n\t\t\t\t\t\t</EmptyState.Description>\n\t\t\t\t\t) }\n\t\t\t\t\t<EmptyState.Actions className=\"media-editor-preview__actions\">\n\t\t\t\t\t\t<MediaPreviewFileActions mediaUrl={ mediaUrl } />\n\t\t\t\t\t</EmptyState.Actions>\n\t\t\t\t</EmptyState.Root>\n\t\t\t</div>\n\t\t);\n\t}\n\n\treturn (\n\t\t<div\n\t\t\t{ ...props }\n\t\t\tclassName={ clsx(\n\t\t\t\t'media-editor-preview',\n\t\t\t\t`media-editor-preview--${ previewType }`,\n\t\t\t\t{\n\t\t\t\t\t// Media with no preview of its own shows the file info.\n\t\t\t\t\t'is-placeholder': previewType === 'application',\n\t\t\t\t}\n\t\t\t) }\n\t\t>\n\t\t\t{ previewType === 'image' && loadingState === 'loading' && (\n\t\t\t\t<div className=\"media-editor-preview__spinner\">\n\t\t\t\t\t<WCSpinner />\n\t\t\t\t</div>\n\t\t\t) }\n\t\t\t<MediaPreviewContent\n\t\t\t\tpreviewType={ previewType }\n\t\t\t\tmediaUrl={ mediaUrl }\n\t\t\t\taltText={ altText }\n\t\t\t\tdisplayTitle={ displayTitle }\n\t\t\t\tfileName={ fileName }\n\t\t\t\tfileDetails={ fileDetails }\n\t\t\t\tonLoad={ () => setLoadingState( 'loaded' ) }\n\t\t\t\tonError={ () => setLoadingState( 'error' ) }\n\t\t\t\tloadingState={ loadingState }\n\t\t\t/>\n\t\t</div>\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgDA,SAAS,cACR,QAIA,SACA,OACS;CAET,MAAM,QADQ,OAAO,MAAQ,EAAE,SAAU,OAAO,OAClC,CAAK,EAAE,WAAY,EAAE,MAAM,MAAM,CAAE;CACjD,OAAO,OAAO,UAAU,WAAW,QAAQ;AAC5C;AAEA,MAAM,wBAAwB;AAI9B,MAAM,oBAAoB;CACzB,MAAM;CACN,QAAQ;CACDA;AACR;;;;;;;AAQA,SAAS,oBAAqB,MAAe;CAG5C,MAAM,CAAE,UAAU,eAAgB,SAG7B;EAAE,QAAQ;EAAQ,IAAI;CAAE,CAAE;CAE/B,gBAAiB;EAChB,IAAK,SAAS,WAAW,QACxB;EAED,MAAM,YAAY,iBACX,YAAa;GAAE,QAAQ;GAAQ,IAAI;EAAE,CAAE,GAC7C,qBACD;EACA,aAAa,aAAc,SAAU;CACtC,GAAG,CAAE,QAAS,CAAE;CAEhB,SAAS,OAAQ,QAAuC,SAAkB;EACzE,aAAe,aAAe;GAAE;GAAQ,IAA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A,qBAAC,WAAW,MAAZ,EAAA,UAAA;GACC,oBAAC,WAAW,MAAZ,EAAiB,MAAO,OAAU,CAAA;GAClC,oBAAC,WAAW,OAAZ,EAAA,UACG,GAAI,4BAA6B,EAClB,CAAA;GAChB,CAAC,CAAE,YACJ,oBAAC,WAAW,aAAZ;IAAwB,WAAU;IAC/B,UAAA;GACqB,CAAA;GAEzB,oBAAC,WAAW,SAAZ;IAAoB,WAAU;IAC7B,UAAA,oBAAC,yBAAD,EAAoC,SAAY,CAAA;GAC7B,CAAA;EACJ,EAAA,CAAA;CACb,CAAA;CAIP,OACC,qBAAC,OAAD;EACC,GAAK;EACL,WAAY,KACX,wBACA,yBAA0B,eAC1B,EAEC,kBAAkB,gBAAgB,cACnC,CACD;EATD,UAAA,CAWG,gBAAgB,WAAW,iBAAiB,aAC7C,oBAAC,OAAD;GAAK,WAAU;GACd,UAAA,oBAACC,SAAD,CAAY,CAAA;EACR,CAAA,GAEN,oBAAC,qBAAD;GACe;GACH;GACD;GACK;GACJ;GACG;GACd,cAAe,gBAAiB,QAAS;GACzC,eAAgB,gBAAiB,OAAQ;GAC1B;EACf,CAAA,CACG;;AAEP"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aspect-ratio-presets.mjs","names":[],"sources":["../../src/state/aspect-ratio-presets.ts"],"sourcesContent":["import { __ } from '@wordpress/i18n';\n\n/**\n * An aspect ratio preset with a human-readable label.\n */\nexport interface AspectRatioPreset {\n\t/** Display label (e.g., \"Square (1:1)\"). */\n\tlabel: string;\n\t/**\n\t * The aspect ratio value (width / height). 0 = free,\n\t * `ORIGINAL_ASPECT_RATIO` = the image's own ratio.\n\t */\n\tvalue: number;\n}\n\n/**\n * Sentinel value for \"Original\" aspect ratio — resolved at runtime\n * to the image's natural width / height.\n */\nexport const ORIGINAL_ASPECT_RATIO = -1;\n\n/**\n * The presets the editor offers by default. They live here rather than\n * in the image editor package, because which ratios to offer, and what\n * to call them, is a product choice. The package takes a plain number.\n */\nexport const DEFAULT_ASPECT_RATIOS: AspectRatioPreset[] = [\n\t{ label: __( 'Free' ), value: 0 },\n\t{ label: __( 'Original' ), value: ORIGINAL_ASPECT_RATIO },\n\t{ label: __( 'Square (1:1)' ), value: 1 },\n\t{ label: __( 'Landscape (16:9)' ), value: 16 / 9 },\n\t{ label: __( 'Portrait (9:16)' ), value: 9 / 16 },\n\t{ label: __( 'Classic (4:3)' ), value: 4 / 3 },\n\t{ label: __( 'Classic portrait (3:4)' ), value: 3 / 4 },\n\t{ label: __( 'Photo (3:2)' ), value: 3 / 2 },\n\t{ label: __( 'Photo portrait (2:3)' ), value: 2 / 3 },\n];\n"],"mappings":";;;;;;AAmBA,MAAa,wBAAwB;;;;;;AAOrC,MAAa,wBAA6C;CACzD;EAAE,OAAO,GAAI,MAAO;EAAG,OAAO;CAAE;CAChC;EAAE,OAAO,GAAI,UAAW;EAAG,OAAA;CAA6B;CACxD;EAAE,OAAO,GAAI,cAAe;EAAG,OAAO;CAAE;CACxC;EAAE,OAAO,GAAI,kBAAmB;EAAG,OAAO,KAAK;CAAE;CACjD;EAAE,OAAO,GAAI,iBAAkB;EAAG,OAAO,IAAI;CAAG;CAChD;EAAE,OAAO,GAAI,eAAgB;EAAG,OAAO,IAAI;CAAE;CAC7C;EAAE,OAAO,GAAI,wBAAyB;EAAG,OAAO
|
|
1
|
+
{"version":3,"file":"aspect-ratio-presets.mjs","names":[],"sources":["../../src/state/aspect-ratio-presets.ts"],"sourcesContent":["import { __ } from '@wordpress/i18n';\n\n/**\n * An aspect ratio preset with a human-readable label.\n */\nexport interface AspectRatioPreset {\n\t/** Display label (e.g., \"Square (1:1)\"). */\n\tlabel: string;\n\t/**\n\t * The aspect ratio value (width / height). 0 = free,\n\t * `ORIGINAL_ASPECT_RATIO` = the image's own ratio.\n\t */\n\tvalue: number;\n}\n\n/**\n * Sentinel value for \"Original\" aspect ratio — resolved at runtime\n * to the image's natural width / height.\n */\nexport const ORIGINAL_ASPECT_RATIO = -1;\n\n/**\n * The presets the editor offers by default. They live here rather than\n * in the image editor package, because which ratios to offer, and what\n * to call them, is a product choice. The package takes a plain number.\n */\nexport const DEFAULT_ASPECT_RATIOS: AspectRatioPreset[] = [\n\t{ label: __( 'Free' ), value: 0 },\n\t{ label: __( 'Original' ), value: ORIGINAL_ASPECT_RATIO },\n\t{ label: __( 'Square (1:1)' ), value: 1 },\n\t{ label: __( 'Landscape (16:9)' ), value: 16 / 9 },\n\t{ label: __( 'Portrait (9:16)' ), value: 9 / 16 },\n\t{ label: __( 'Classic (4:3)' ), value: 4 / 3 },\n\t{ label: __( 'Classic portrait (3:4)' ), value: 3 / 4 },\n\t{ label: __( 'Photo (3:2)' ), value: 3 / 2 },\n\t{ label: __( 'Photo portrait (2:3)' ), value: 2 / 3 },\n];\n"],"mappings":";;;;;;AAmBA,MAAa,wBAAwB;;;;;;AAOrC,MAAa,wBAA6C;CACzD;EAAE,OAAO,GAAI,MAAO;EAAG,OAAO;CAAE;CAChC;EAAE,OAAO,GAAI,UAAW;EAAG,OAAA;CAA6B;CACxD;EAAE,OAAO,GAAI,cAAe;EAAG,OAAO;CAAE;CACxC;EAAE,OAAO,GAAI,kBAAmB;EAAG,OAAO,KAAK;CAAE;CACjD;EAAE,OAAO,GAAI,iBAAkB;EAAG,OAAO,IAAI;CAAG;CAChD;EAAE,OAAO,GAAI,eAAgB;EAAG,OAAO,IAAI;CAAE;CAC7C;EAAE,OAAO,GAAI,wBAAyB;EAAG,OAAO;CAAM;CACtD;EAAE,OAAO,GAAI,aAAc;EAAG,OAAO;CAAM;CAC3C;EAAE,OAAO,GAAI,sBAAuB;EAAG,OAAO,IAAI;CAAE;AACrD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-media-editor-state.mjs","names":[],"sources":["../../src/state/use-media-editor-state.ts"],"sourcesContent":["import {\n\tuseCallback,\n\tuseMemo,\n\tuseReducer,\n\tuseRef,\n\tuseState,\n} from '@wordpress/element';\nimport {\n\tcreateImageEditorState,\n\tuseImageEditor,\n\ttype ImageEditorController,\n\ttype ImageEditorState,\n} from '@wordpress/image-editor';\nimport { ORIGINAL_ASPECT_RATIO } from './aspect-ratio-presets';\nimport {\n\tmediaEditorReducer,\n\tareMediaEditorStatesEqual,\n\tbuildInitialMediaEditorState,\n} from './composite-reducer';\nimport type {\n\tCropOptionsSlice,\n\tEditsSlice,\n\tEditValue,\n\tMediaEditorAction,\n\tMediaEditorState,\n} from './types';\n\n/**\n * Resolve an aspect-ratio preset value (the string the dropdown\n * round-trips) into a numeric width/height ratio for the image editor.\n *\n * - `'0'` → `undefined` (Free; no lock)\n * - `'-1'` (Original) → image's natural width / height, or `undefined`\n * if no image is loaded.\n * - Any positive decimal → the parsed number.\n *\n * @param presetKey Preset value from the dropdown.\n * @param image The image editor's loaded image, or `null`.\n * @return The resolved ratio, or `undefined` for Free / unresolvable.\n */\nfunction resolveAspectRatio(\n\tpresetKey: string,\n\timage: ImageEditorState[ 'image' ] | null\n): number | undefined {\n\tconst num = parseFloat( presetKey );\n\tif ( num === 0 || Number.isNaN( num ) ) {\n\t\treturn undefined;\n\t}\n\tif ( num === ORIGINAL_ASPECT_RATIO ) {\n\t\tif ( image && image.naturalWidth > 0 && image.naturalHeight > 0 ) {\n\t\t\treturn image.naturalWidth / image.naturalHeight;\n\t\t}\n\t\treturn undefined;\n\t}\n\tif ( num > 0 ) {\n\t\treturn num;\n\t}\n\treturn undefined;\n}\n\nfunction areImagesEqual(\n\ta: ImageEditorState[ 'image' ],\n\tb: ImageEditorState[ 'image' ]\n): boolean {\n\treturn (\n\t\ta?.src === b?.src &&\n\t\ta?.naturalWidth === b?.naturalWidth &&\n\t\ta?.naturalHeight === b?.naturalHeight\n\t);\n}\n\n/**\n * The media editor session exposed by `useMediaEditorState`.\n *\n * The session owns what is being edited and how: the source image,\n * every editing slice, the shared undo/redo history, gesture\n * boundaries, and whether the edits change the saved image. The\n * image editor is one participant in the session — `imageEditor` is the\n * controller an `<ImageEditorCanvas>` takes via its `controller` prop — rather\n * than the session itself.\n */\nexport interface MediaEditorSession {\n\t/**\n\t * Controller for the image editor. Its setters record history in the\n\t * session; its `isDirty` covers the crop only. Its `setImage` is\n\t * `setSourceImage`, so the `<ImageEditorCanvas>` reporting a newly loaded\n\t * image starts a fresh session.\n\t */\n\timageEditor: ImageEditorController;\n\t/** The cropOptions slice. */\n\tcropOptions: CropOptionsSlice;\n\t/** Set the aspect-ratio preset and reshape the crop in one undo entry. */\n\tsetAspectRatioValue: ( presetKey: string ) => void;\n\t/**\n\t * Put every slice back to its starting state in one undo entry:\n\t * default crop and crop options, no edits. Keeps the image.\n\t */\n\treset: () => void;\n\t/** The named edits other than crop, keyed by edit name. */\n\tedits: EditsSlice;\n\t/**\n\t * Set a named edit, or remove it by passing `undefined`. Recorded\n\t * in the session history like any crop change. Setting a value\n\t * equal in content to the current one is a no-op.\n\t */\n\tsetEdit: ( name: string, value: EditValue | undefined ) => void;\n\t/**\n\t * Replace the image being edited. A different image starts a\n\t * fresh session: default crop and crop options, a clean baseline,\n\t * and no history. Reporting the same image again is a no-op.\n\t */\n\tsetSourceImage: ( image: ImageEditorState[ 'image' ] ) => void;\n\t/**\n\t * Whether anything in the session differs from its baseline,\n\t * including editor-only state such as the aspect-ratio preset.\n\t */\n\tisDirty: boolean;\n\t/**\n\t * Whether the edits change the saved image, so saving has to\n\t * produce new image output rather than only metadata.\n\t */\n\thasOutputEdits: boolean;\n\t/** Whether there's an undoable change in history. */\n\thasUndo: boolean;\n\t/** Whether there's a redoable change in history. */\n\thasRedo: boolean;\n\t/** Undo the last committed change across all slices. */\n\tundo: () => void;\n\t/** Redo the last undone change across all slices. */\n\tredo: () => void;\n\t/**\n\t * Open a gesture boundary. During a gesture all changes coalesce\n\t * into one undo entry — the snapshot taken at `beginGesture`. Pair\n\t * with `endGesture` on pointer-up / key-up.\n\t */\n\tbeginGesture: () => void;\n\t/** Close a gesture boundary and commit the pre-gesture snapshot. */\n\tendGesture: () => void;\n}\n\n/**\n * The media editor session.\n *\n * Owns the only undo/redo history for the editor. The image editor's state,\n * the sidebar crop options and named edits are slices of one state, so\n * one history stack covers them all. The image editor works out its own\n * changes and reports each next state through `onChange`.\n *\n * History semantics:\n * - Each change pushes its pre-state to the undo stack, unless a\n * gesture is open or the change is a no-op (post-state value-equal\n * to pre-state).\n * - During a gesture (`beginGesture` → `endGesture`) changes coalesce:\n * only the pre-gesture snapshot is pushed, at gesture end. Undo and\n * redo close an open gesture first.\n * - Changes the image editor marks as not edits (an image loading, a refit\n * after a window resize) are never recorded.\n *\n * `isDirty` tracks the full session, including undoable UI state. Use\n * `hasOutputEdits` when deciding whether the image output needs saving.\n *\n * The session starts empty. Call `setSourceImage` to load an image.\n *\n * @return The media editor session.\n */\nexport function useMediaEditorState(): MediaEditorSession {\n\tconst [ state, dispatch ] = useReducer( mediaEditorReducer, null, () =>\n\t\tbuildInitialMediaEditorState( createImageEditorState() )\n\t);\n\n\t// The \"clean\" snapshot the current state is compared against for\n\t// `isDirty`. `setSourceImage` refreshes it when a new image starts a\n\t// fresh session.\n\tconst [ initialBaseline, setInitialBaseline ] =\n\t\tuseState< MediaEditorState >( () => state );\n\n\t// Latest state, so several actions in one event see each other's\n\t// output before React commits. Every mutation path writes it\n\t// synchronously.\n\tconst stateRef = useRef( state );\n\n\t// History stacks: full snapshots. Refs avoid re-renders on every\n\t// push; a boolean state pair drives the undo/redo indicators.\n\tconst historyRef = useRef< MediaEditorState[] >( [] );\n\tconst redoStackRef = useRef< MediaEditorState[] >( [] );\n\tconst [ hasUndo, setHasUndo ] = useState( false );\n\tconst [ hasRedo, setHasRedo ] = useState( false );\n\n\t// Gesture state. While open, the first change captures the\n\t// pre-gesture snapshot; later changes don't push.\n\tconst isGestureOpenRef = useRef( false );\n\tconst gestureSnapshotRef = useRef< MediaEditorState | null >( null );\n\n\tconst pushSnapshot = useCallback( ( snapshot: MediaEditorState ) => {\n\t\tconst last = historyRef.current[ historyRef.current.length - 1 ];\n\t\tif ( last && areMediaEditorStatesEqual( last, snapshot ) ) {\n\t\t\treturn;\n\t\t}\n\t\thistoryRef.current = [ ...historyRef.current, snapshot ];\n\t\tredoStackRef.current = [];\n\t\tsetHasUndo( true );\n\t\tsetHasRedo( false );\n\t}, [] );\n\n\tconst dispatchWithHistory = useCallback(\n\t\t( action: MediaEditorAction, recordHistory = true ) => {\n\t\t\tconst preState = stateRef.current;\n\t\t\tconst postState = mediaEditorReducer( preState, action );\n\t\t\tif (\n\t\t\t\trecordHistory &&\n\t\t\t\t! areMediaEditorStatesEqual( preState, postState )\n\t\t\t) {\n\t\t\t\tif ( isGestureOpenRef.current ) {\n\t\t\t\t\tif ( gestureSnapshotRef.current === null ) {\n\t\t\t\t\t\tgestureSnapshotRef.current = preState;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpushSnapshot( preState );\n\t\t\t\t}\n\t\t\t}\n\t\t\tstateRef.current = postState;\n\t\t\tdispatch( action );\n\t\t},\n\t\t[ pushSnapshot ]\n\t);\n\n\tconst beginGesture = useCallback( () => {\n\t\tif ( isGestureOpenRef.current ) {\n\t\t\treturn;\n\t\t}\n\t\tisGestureOpenRef.current = true;\n\t\tgestureSnapshotRef.current = null;\n\t}, [] );\n\n\t// Close a gesture (or flush a pending one before undo/redo). Pushes\n\t// the pre-gesture snapshot only if it differs from the current\n\t// state. Safe to call when no gesture is open.\n\tconst endGesture = useCallback( () => {\n\t\tconst snapshot = gestureSnapshotRef.current;\n\t\tif (\n\t\t\tsnapshot &&\n\t\t\t! areMediaEditorStatesEqual( snapshot, stateRef.current )\n\t\t) {\n\t\t\tpushSnapshot( snapshot );\n\t\t}\n\t\tgestureSnapshotRef.current = null;\n\t\tisGestureOpenRef.current = false;\n\t}, [ pushSnapshot ] );\n\n\t// Run several changes as one undo entry, unless a gesture is already\n\t// open, which groups them anyway.\n\tconst asOneUndoEntry = useCallback(\n\t\t( run: () => void ) => {\n\t\t\tif ( isGestureOpenRef.current ) {\n\t\t\t\trun();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbeginGesture();\n\t\t\trun();\n\t\t\tendGesture();\n\t\t},\n\t\t[ beginGesture, endGesture ]\n\t);\n\n\tconst setSourceImage = useCallback(\n\t\t( image: ImageEditorState[ 'image' ] ) => {\n\t\t\tif ( areImagesEqual( stateRef.current.imageEditor.image, image ) ) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// New image = fresh session: default crop and crop options, a\n\t\t\t// clean baseline, and no history. Edits made against one\n\t\t\t// image must not survive onto another.\n\t\t\tconst next = buildInitialMediaEditorState(\n\t\t\t\tcreateImageEditorState( { image } )\n\t\t\t);\n\t\t\tstateRef.current = next;\n\t\t\tdispatch( { type: 'RESTORE_SNAPSHOT', payload: next } );\n\t\t\tsetInitialBaseline( next );\n\t\t\tisGestureOpenRef.current = false;\n\t\t\tgestureSnapshotRef.current = null;\n\t\t\thistoryRef.current = [];\n\t\t\tredoStackRef.current = [];\n\t\t\tsetHasUndo( false );\n\t\t\tsetHasRedo( false );\n\t\t},\n\t\t[]\n\t);\n\n\tconst handleImageEditorChange = useCallback(\n\t\t( nextState: ImageEditorState, { isEdit }: { isEdit: boolean } ) => {\n\t\t\tif (\n\t\t\t\t! areImagesEqual(\n\t\t\t\t\tstateRef.current.imageEditor.image,\n\t\t\t\t\tnextState.image\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tsetSourceImage( nextState.image );\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdispatchWithHistory(\n\t\t\t\t{ type: 'SET_IMAGE_EDITOR', payload: nextState },\n\t\t\t\tisEdit\n\t\t\t);\n\t\t},\n\t\t[ dispatchWithHistory, setSourceImage ]\n\t);\n\n\tconst imageEditorController = useImageEditor( {\n\t\tstate: state.imageEditor,\n\t\tonChange: handleImageEditorChange,\n\t} );\n\n\t// The locked ratio has two owners: the preset the sidebar shows, and\n\t// the number the image editor holds. This is the only path that sets\n\t// both, so call it rather than `imageEditor.setAspectRatio`, which\n\t// would leave the sidebar showing a ratio the crop no longer has.\n\tconst setAspectRatioValue = useCallback(\n\t\t( presetKey: string ) => {\n\t\t\tasOneUndoEntry( () => {\n\t\t\t\tdispatchWithHistory( {\n\t\t\t\t\ttype: 'SET_ASPECT_RATIO_VALUE',\n\t\t\t\t\tpayload: presetKey,\n\t\t\t\t} );\n\t\t\t\timageEditorController.setAspectRatio(\n\t\t\t\t\tresolveAspectRatio(\n\t\t\t\t\t\tpresetKey,\n\t\t\t\t\t\tstateRef.current.imageEditor.image\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t} );\n\t\t},\n\t\t[ asOneUndoEntry, dispatchWithHistory, imageEditorController ]\n\t);\n\n\tconst reset = useCallback( () => {\n\t\tdispatchWithHistory( { type: 'RESET' } );\n\t}, [ dispatchWithHistory ] );\n\n\tconst setEdit = useCallback(\n\t\t( name: string, value: EditValue | undefined ) => {\n\t\t\tdispatchWithHistory( {\n\t\t\t\ttype: 'SET_EDIT',\n\t\t\t\tpayload: { name, value },\n\t\t\t} );\n\t\t},\n\t\t[ dispatchWithHistory ]\n\t);\n\n\tconst undo = useCallback( () => {\n\t\tendGesture();\n\t\tconst prev = historyRef.current[ historyRef.current.length - 1 ];\n\t\tif ( ! prev ) {\n\t\t\treturn;\n\t\t}\n\t\tredoStackRef.current = [ stateRef.current, ...redoStackRef.current ];\n\t\thistoryRef.current = historyRef.current.slice( 0, -1 );\n\t\tsetHasUndo( historyRef.current.length > 0 );\n\t\tsetHasRedo( true );\n\t\tstateRef.current = prev;\n\t\tdispatch( { type: 'RESTORE_SNAPSHOT', payload: prev } );\n\t}, [ endGesture ] );\n\n\tconst redo = useCallback( () => {\n\t\tendGesture();\n\t\tconst next = redoStackRef.current[ 0 ];\n\t\tif ( ! next ) {\n\t\t\treturn;\n\t\t}\n\t\thistoryRef.current = [ ...historyRef.current, stateRef.current ];\n\t\tredoStackRef.current = redoStackRef.current.slice( 1 );\n\t\tsetHasUndo( true );\n\t\tsetHasRedo( redoStackRef.current.length > 0 );\n\t\tstateRef.current = next;\n\t\tdispatch( { type: 'RESTORE_SNAPSHOT', payload: next } );\n\t}, [ endGesture ] );\n\n\tconst imageEditor = useMemo< ImageEditorController >(\n\t\t() => ( { ...imageEditorController, setImage: setSourceImage } ),\n\t\t[ imageEditorController, setSourceImage ]\n\t);\n\n\tconst isDirty = ! areMediaEditorStatesEqual( state, initialBaseline );\n\n\treturn useMemo(\n\t\t() => ( {\n\t\t\timageEditor,\n\t\t\tcropOptions: state.cropOptions,\n\t\t\tsetAspectRatioValue,\n\t\t\tedits: state.edits,\n\t\t\tsetEdit,\n\t\t\tsetSourceImage,\n\t\t\treset,\n\t\t\tisDirty,\n\t\t\t// Only the crop changes the saved image so far.\n\t\t\t//\n\t\t\t// This reads the image editor's own clean state, not the\n\t\t\t// session's. The two agree because the session only ever\n\t\t\t// replaces the editor's slice with a state the editor handed\n\t\t\t// out, and because a fresh state for an image matches the\n\t\t\t// default one on every field `isDirty` compares. Change\n\t\t\t// either and this has to compare against the session's\n\t\t\t// baseline instead.\n\t\t\thasOutputEdits: imageEditor.isDirty,\n\t\t\thasUndo,\n\t\t\thasRedo,\n\t\t\tundo,\n\t\t\tredo,\n\t\t\tbeginGesture,\n\t\t\tendGesture,\n\t\t} ),\n\t\t[\n\t\t\timageEditor,\n\t\t\tstate.cropOptions,\n\t\t\tsetAspectRatioValue,\n\t\t\tstate.edits,\n\t\t\tsetEdit,\n\t\t\tsetSourceImage,\n\t\t\treset,\n\t\t\tisDirty,\n\t\t\thasUndo,\n\t\t\thasRedo,\n\t\t\tundo,\n\t\t\tredo,\n\t\t\tbeginGesture,\n\t\t\tendGesture,\n\t\t]\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwCA,SAAS,mBACR,WACA,OACqB;CACrB,MAAM,MAAM,WAAY,SAAU;CAClC,IAAK,QAAQ,KAAK,OAAO,MAAO,GAAI,GACnC;CAED,IAAK,QAAQ,uBAAwB;EACpC,IAAK,SAAS,MAAM,eAAe,KAA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AAO,eACE;EACP;EACA,aAAa,MAAM;EACnB;EACA,OAAO,MAAM;EACb;EACA;EACA;EACA;EAUA,gBAAgB,YAAY;EAC5B;EACA;EACA;EACA;EACA;EACA;CACD,IACA;EACC;EACA,MAAM;EACN;EACA,MAAM;EACN;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"use-media-editor-state.mjs","names":[],"sources":["../../src/state/use-media-editor-state.ts"],"sourcesContent":["import {\n\tuseCallback,\n\tuseMemo,\n\tuseReducer,\n\tuseRef,\n\tuseState,\n} from '@wordpress/element';\nimport {\n\tcreateImageEditorState,\n\tuseImageEditor,\n\ttype ImageEditorController,\n\ttype ImageEditorState,\n} from '@wordpress/image-editor';\nimport { ORIGINAL_ASPECT_RATIO } from './aspect-ratio-presets';\nimport {\n\tmediaEditorReducer,\n\tareMediaEditorStatesEqual,\n\tbuildInitialMediaEditorState,\n} from './composite-reducer';\nimport type {\n\tCropOptionsSlice,\n\tEditsSlice,\n\tEditValue,\n\tMediaEditorAction,\n\tMediaEditorState,\n} from './types';\n\n/**\n * Resolve an aspect-ratio preset value (the string the dropdown\n * round-trips) into a numeric width/height ratio for the image editor.\n *\n * - `'0'` → `undefined` (Free; no lock)\n * - `'-1'` (Original) → image's natural width / height, or `undefined`\n * if no image is loaded.\n * - Any positive decimal → the parsed number.\n *\n * @param presetKey Preset value from the dropdown.\n * @param image The image editor's loaded image, or `null`.\n * @return The resolved ratio, or `undefined` for Free / unresolvable.\n */\nfunction resolveAspectRatio(\n\tpresetKey: string,\n\timage: ImageEditorState[ 'image' ] | null\n): number | undefined {\n\tconst num = parseFloat( presetKey );\n\tif ( num === 0 || Number.isNaN( num ) ) {\n\t\treturn undefined;\n\t}\n\tif ( num === ORIGINAL_ASPECT_RATIO ) {\n\t\tif ( image && image.naturalWidth > 0 && image.naturalHeight > 0 ) {\n\t\t\treturn image.naturalWidth / image.naturalHeight;\n\t\t}\n\t\treturn undefined;\n\t}\n\tif ( num > 0 ) {\n\t\treturn num;\n\t}\n\treturn undefined;\n}\n\nfunction areImagesEqual(\n\ta: ImageEditorState[ 'image' ],\n\tb: ImageEditorState[ 'image' ]\n): boolean {\n\treturn (\n\t\ta?.src === b?.src &&\n\t\ta?.naturalWidth === b?.naturalWidth &&\n\t\ta?.naturalHeight === b?.naturalHeight\n\t);\n}\n\n/**\n * The media editor session exposed by `useMediaEditorState`.\n *\n * The session owns what is being edited and how: the source image,\n * every editing slice, the shared undo/redo history, gesture\n * boundaries, and whether the edits change the saved image. The\n * image editor is one participant in the session — `imageEditor` is the\n * controller an `<ImageEditorCanvas>` takes via its `controller` prop — rather\n * than the session itself.\n */\nexport interface MediaEditorSession {\n\t/**\n\t * Controller for the image editor. Its setters record history in the\n\t * session; its `isDirty` covers the crop only. Its `setImage` is\n\t * `setSourceImage`, so the `<ImageEditorCanvas>` reporting a newly loaded\n\t * image starts a fresh session.\n\t */\n\timageEditor: ImageEditorController;\n\t/** The cropOptions slice. */\n\tcropOptions: CropOptionsSlice;\n\t/** Set the aspect-ratio preset and reshape the crop in one undo entry. */\n\tsetAspectRatioValue: ( presetKey: string ) => void;\n\t/**\n\t * Put every slice back to its starting state in one undo entry:\n\t * default crop and crop options, no edits. Keeps the image.\n\t */\n\treset: () => void;\n\t/**\n\t * The named edits other than crop, keyed by edit name. Not an\n\t * extension API: undoable and cleared by `reset`, but not counted by\n\t * `hasOutputEdits` and not saved.\n\t */\n\tedits: EditsSlice;\n\t/**\n\t * Set a named edit, or remove it by passing `undefined`. Recorded\n\t * in the session history like any crop change. Setting a value\n\t * equal in content to the current one is a no-op.\n\t */\n\tsetEdit: ( name: string, value: EditValue | undefined ) => void;\n\t/**\n\t * Replace the image being edited. A different image starts a\n\t * fresh session: default crop and crop options, a clean baseline,\n\t * and no history. Reporting the same image again is a no-op.\n\t */\n\tsetSourceImage: ( image: ImageEditorState[ 'image' ] ) => void;\n\t/**\n\t * Whether anything in the session differs from its baseline,\n\t * including editor-only state such as the aspect-ratio preset.\n\t */\n\tisDirty: boolean;\n\t/**\n\t * Whether the edits change the saved image, so saving has to\n\t * produce new image output rather than only metadata. Geometry\n\t * counts; named edits do not.\n\t */\n\thasOutputEdits: boolean;\n\t/** Whether there's an undoable change in history. */\n\thasUndo: boolean;\n\t/** Whether there's a redoable change in history. */\n\thasRedo: boolean;\n\t/** Undo the last committed change across all slices. */\n\tundo: () => void;\n\t/** Redo the last undone change across all slices. */\n\tredo: () => void;\n\t/**\n\t * Open a gesture boundary. During a gesture all changes coalesce\n\t * into one undo entry — the snapshot taken at `beginGesture`. Pair\n\t * with `endGesture` on pointer-up / key-up.\n\t */\n\tbeginGesture: () => void;\n\t/** Close a gesture boundary and commit the pre-gesture snapshot. */\n\tendGesture: () => void;\n}\n\n/**\n * The media editor session.\n *\n * Owns the only undo/redo history for the editor. The image editor's state,\n * the sidebar crop options and named edits are slices of one state, so\n * one history stack covers them all. The image editor works out its own\n * changes and reports each next state through `onChange`.\n *\n * History semantics:\n * - Each change pushes its pre-state to the undo stack, unless a\n * gesture is open or the change is a no-op (post-state value-equal\n * to pre-state).\n * - During a gesture (`beginGesture` → `endGesture`) changes coalesce:\n * only the pre-gesture snapshot is pushed, at gesture end. Undo and\n * redo close an open gesture first.\n * - Changes the image editor marks as not edits (an image loading, a refit\n * after a window resize) are never recorded.\n *\n * `isDirty` tracks the full session, including undoable UI state. Use\n * `hasOutputEdits` when deciding whether the image output needs saving.\n *\n * The session starts empty. Call `setSourceImage` to load an image.\n *\n * @return The media editor session.\n */\nexport function useMediaEditorState(): MediaEditorSession {\n\tconst [ state, dispatch ] = useReducer( mediaEditorReducer, null, () =>\n\t\tbuildInitialMediaEditorState( createImageEditorState() )\n\t);\n\n\t// The \"clean\" snapshot the current state is compared against for\n\t// `isDirty`. `setSourceImage` refreshes it when a new image starts a\n\t// fresh session.\n\tconst [ initialBaseline, setInitialBaseline ] =\n\t\tuseState< MediaEditorState >( () => state );\n\n\t// Latest state, so several actions in one event see each other's\n\t// output before React commits. Every mutation path writes it\n\t// synchronously.\n\tconst stateRef = useRef( state );\n\n\t// History stacks: full snapshots. Refs avoid re-renders on every\n\t// push; a boolean state pair drives the undo/redo indicators.\n\tconst historyRef = useRef< MediaEditorState[] >( [] );\n\tconst redoStackRef = useRef< MediaEditorState[] >( [] );\n\tconst [ hasUndo, setHasUndo ] = useState( false );\n\tconst [ hasRedo, setHasRedo ] = useState( false );\n\n\t// Gesture state. While open, the first change captures the\n\t// pre-gesture snapshot; later changes don't push.\n\tconst isGestureOpenRef = useRef( false );\n\tconst gestureSnapshotRef = useRef< MediaEditorState | null >( null );\n\n\tconst pushSnapshot = useCallback( ( snapshot: MediaEditorState ) => {\n\t\tconst last = historyRef.current[ historyRef.current.length - 1 ];\n\t\tif ( last && areMediaEditorStatesEqual( last, snapshot ) ) {\n\t\t\treturn;\n\t\t}\n\t\thistoryRef.current = [ ...historyRef.current, snapshot ];\n\t\tredoStackRef.current = [];\n\t\tsetHasUndo( true );\n\t\tsetHasRedo( false );\n\t}, [] );\n\n\tconst dispatchWithHistory = useCallback(\n\t\t( action: MediaEditorAction, recordHistory = true ) => {\n\t\t\tconst preState = stateRef.current;\n\t\t\tconst postState = mediaEditorReducer( preState, action );\n\t\t\tif (\n\t\t\t\trecordHistory &&\n\t\t\t\t! areMediaEditorStatesEqual( preState, postState )\n\t\t\t) {\n\t\t\t\tif ( isGestureOpenRef.current ) {\n\t\t\t\t\tif ( gestureSnapshotRef.current === null ) {\n\t\t\t\t\t\tgestureSnapshotRef.current = preState;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpushSnapshot( preState );\n\t\t\t\t}\n\t\t\t}\n\t\t\tstateRef.current = postState;\n\t\t\tdispatch( action );\n\t\t},\n\t\t[ pushSnapshot ]\n\t);\n\n\tconst beginGesture = useCallback( () => {\n\t\tif ( isGestureOpenRef.current ) {\n\t\t\treturn;\n\t\t}\n\t\tisGestureOpenRef.current = true;\n\t\tgestureSnapshotRef.current = null;\n\t}, [] );\n\n\t// Close a gesture (or flush a pending one before undo/redo). Pushes\n\t// the pre-gesture snapshot only if it differs from the current\n\t// state. Safe to call when no gesture is open.\n\tconst endGesture = useCallback( () => {\n\t\tconst snapshot = gestureSnapshotRef.current;\n\t\tif (\n\t\t\tsnapshot &&\n\t\t\t! areMediaEditorStatesEqual( snapshot, stateRef.current )\n\t\t) {\n\t\t\tpushSnapshot( snapshot );\n\t\t}\n\t\tgestureSnapshotRef.current = null;\n\t\tisGestureOpenRef.current = false;\n\t}, [ pushSnapshot ] );\n\n\t// Run several changes as one undo entry, unless a gesture is already\n\t// open, which groups them anyway.\n\tconst asOneUndoEntry = useCallback(\n\t\t( run: () => void ) => {\n\t\t\tif ( isGestureOpenRef.current ) {\n\t\t\t\trun();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbeginGesture();\n\t\t\trun();\n\t\t\tendGesture();\n\t\t},\n\t\t[ beginGesture, endGesture ]\n\t);\n\n\tconst setSourceImage = useCallback(\n\t\t( image: ImageEditorState[ 'image' ] ) => {\n\t\t\tif ( areImagesEqual( stateRef.current.imageEditor.image, image ) ) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// New image = fresh session: default crop and crop options, a\n\t\t\t// clean baseline, and no history. Edits made against one\n\t\t\t// image must not survive onto another.\n\t\t\tconst next = buildInitialMediaEditorState(\n\t\t\t\tcreateImageEditorState( { image } )\n\t\t\t);\n\t\t\tstateRef.current = next;\n\t\t\tdispatch( { type: 'RESTORE_SNAPSHOT', payload: next } );\n\t\t\tsetInitialBaseline( next );\n\t\t\tisGestureOpenRef.current = false;\n\t\t\tgestureSnapshotRef.current = null;\n\t\t\thistoryRef.current = [];\n\t\t\tredoStackRef.current = [];\n\t\t\tsetHasUndo( false );\n\t\t\tsetHasRedo( false );\n\t\t},\n\t\t[]\n\t);\n\n\tconst handleImageEditorChange = useCallback(\n\t\t( nextState: ImageEditorState, { isEdit }: { isEdit: boolean } ) => {\n\t\t\tif (\n\t\t\t\t! areImagesEqual(\n\t\t\t\t\tstateRef.current.imageEditor.image,\n\t\t\t\t\tnextState.image\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tsetSourceImage( nextState.image );\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdispatchWithHistory(\n\t\t\t\t{ type: 'SET_IMAGE_EDITOR', payload: nextState },\n\t\t\t\tisEdit\n\t\t\t);\n\t\t},\n\t\t[ dispatchWithHistory, setSourceImage ]\n\t);\n\n\tconst imageEditorController = useImageEditor( {\n\t\tstate: state.imageEditor,\n\t\tonChange: handleImageEditorChange,\n\t} );\n\n\t// The locked ratio has two owners: the preset the sidebar shows, and\n\t// the number the image editor holds. This is the only path that sets\n\t// both, so call it rather than `imageEditor.setAspectRatio`, which\n\t// would leave the sidebar showing a ratio the crop no longer has.\n\tconst setAspectRatioValue = useCallback(\n\t\t( presetKey: string ) => {\n\t\t\tasOneUndoEntry( () => {\n\t\t\t\tdispatchWithHistory( {\n\t\t\t\t\ttype: 'SET_ASPECT_RATIO_VALUE',\n\t\t\t\t\tpayload: presetKey,\n\t\t\t\t} );\n\t\t\t\timageEditorController.setAspectRatio(\n\t\t\t\t\tresolveAspectRatio(\n\t\t\t\t\t\tpresetKey,\n\t\t\t\t\t\tstateRef.current.imageEditor.image\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t} );\n\t\t},\n\t\t[ asOneUndoEntry, dispatchWithHistory, imageEditorController ]\n\t);\n\n\tconst reset = useCallback( () => {\n\t\tdispatchWithHistory( { type: 'RESET' } );\n\t}, [ dispatchWithHistory ] );\n\n\tconst setEdit = useCallback(\n\t\t( name: string, value: EditValue | undefined ) => {\n\t\t\tdispatchWithHistory( {\n\t\t\t\ttype: 'SET_EDIT',\n\t\t\t\tpayload: { name, value },\n\t\t\t} );\n\t\t},\n\t\t[ dispatchWithHistory ]\n\t);\n\n\tconst undo = useCallback( () => {\n\t\tendGesture();\n\t\tconst prev = historyRef.current[ historyRef.current.length - 1 ];\n\t\tif ( ! prev ) {\n\t\t\treturn;\n\t\t}\n\t\tredoStackRef.current = [ stateRef.current, ...redoStackRef.current ];\n\t\thistoryRef.current = historyRef.current.slice( 0, -1 );\n\t\tsetHasUndo( historyRef.current.length > 0 );\n\t\tsetHasRedo( true );\n\t\tstateRef.current = prev;\n\t\tdispatch( { type: 'RESTORE_SNAPSHOT', payload: prev } );\n\t}, [ endGesture ] );\n\n\tconst redo = useCallback( () => {\n\t\tendGesture();\n\t\tconst next = redoStackRef.current[ 0 ];\n\t\tif ( ! next ) {\n\t\t\treturn;\n\t\t}\n\t\thistoryRef.current = [ ...historyRef.current, stateRef.current ];\n\t\tredoStackRef.current = redoStackRef.current.slice( 1 );\n\t\tsetHasUndo( true );\n\t\tsetHasRedo( redoStackRef.current.length > 0 );\n\t\tstateRef.current = next;\n\t\tdispatch( { type: 'RESTORE_SNAPSHOT', payload: next } );\n\t}, [ endGesture ] );\n\n\tconst imageEditor = useMemo< ImageEditorController >(\n\t\t() => ( { ...imageEditorController, setImage: setSourceImage } ),\n\t\t[ imageEditorController, setSourceImage ]\n\t);\n\n\tconst isDirty = ! areMediaEditorStatesEqual( state, initialBaseline );\n\n\treturn useMemo(\n\t\t() => ( {\n\t\t\timageEditor,\n\t\t\tcropOptions: state.cropOptions,\n\t\t\tsetAspectRatioValue,\n\t\t\tedits: state.edits,\n\t\t\tsetEdit,\n\t\t\tsetSourceImage,\n\t\t\treset,\n\t\t\tisDirty,\n\t\t\t// Only the crop changes the saved image so far.\n\t\t\t//\n\t\t\t// This reads the image editor's own clean state, not the\n\t\t\t// session's. The two agree because the session only ever\n\t\t\t// replaces the editor's slice with a state the editor handed\n\t\t\t// out, and because a fresh state for an image matches the\n\t\t\t// default one on every field `isDirty` compares. Change\n\t\t\t// either and this has to compare against the session's\n\t\t\t// baseline instead.\n\t\t\thasOutputEdits: imageEditor.isDirty,\n\t\t\thasUndo,\n\t\t\thasRedo,\n\t\t\tundo,\n\t\t\tredo,\n\t\t\tbeginGesture,\n\t\t\tendGesture,\n\t\t} ),\n\t\t[\n\t\t\timageEditor,\n\t\t\tstate.cropOptions,\n\t\t\tsetAspectRatioValue,\n\t\t\tstate.edits,\n\t\t\tsetEdit,\n\t\t\tsetSourceImage,\n\t\t\treset,\n\t\t\tisDirty,\n\t\t\thasUndo,\n\t\t\thasRedo,\n\t\t\tundo,\n\t\t\tredo,\n\t\t\tbeginGesture,\n\t\t\tendGesture,\n\t\t]\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwCA,SAAS,mBACR,WACA,OACqB;CACrB,MAAM,MAAM,WAAY,SAAU;CAClC,IAAK,QAAQ,KAAK,OAAO,MAAO,GAAI,GACnC;CAED,IAAK,QAAQ,uBAAwB;EACpC,IAAK,SAAS,MAAM,eAAe,KAAK,MAAM,gBAAgB,GAC7D,OAAO,MAAM,eAAe,MAAM;EAEnC;CACD;CACA,IAAK,MAAM,GACV,OAAO;AAGT;AAEA,SAAS,eACR,GACA,GACU;CACV,OACC,GAAG,QAAQ,GAAG,OACd,GAAG,iBAAiB,GAAG,gBACvB,GAAG,kBAAkB,GAAG;AAE1B;;;;;;;;;;;;;;;;;;;;;;;;;;AAqGA,SAAgB,sBAA0C;CACzD,MAAM,CAAE,OAAO,YAAa,WAAY,oBAAoB,YAC3D,6BAA8B,uBAAuB,CAAE,CACxD;CAKA,MAAM,CAAE,iBAAiB,sBACxB,eAAoC,KAAM;CAK3C,MAAM,WAAW,OAAQ,KAAM;CAI/B,MAAM,aAAa,OAA8B,CAAC,CAAE;CACpD,MAAM,eAAe,OAA8B,CAAC,CAAE;CACtD,MAAM,CAAE,SAAS,cAAe,SAAU,KAAM;CAChD,MAAM,CAAE,SAAS,cAAe,SAAU,KAAM;CAIhD,MAAM,mBAAmB,OAAQ,KAAM;CACvC,MAAM,qBAAqB,OAAmC,IAAK;CAEnE,MAAM,eAAe,aAAe,aAAgC;EACnE,MAAM,OAAO,WAAW,QAAS,WAAW,QAAQ,SAAS;EAC7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W,CAAE;CAElB,MAAM,OAAO,kBAAmB;EAC/B,WAAW;EACX,MAAM,OAAO,aAAa,QAAS;EACnC,IAAK,CAAE,MACN;EAED,WAAW,UAAU,CAAE,GAAG,WAAW,SAAS,SAAS,OAAQ;EAC/D,aAAa,UAAU,aAAa,QAAQ,MAAO,CAAE;EACrD,WAAY,IAAK;EACjB,WAAY,aAAa,QAAQ,SAAS,CAAE;EAC5C,SAAS,UAAU;EACnB,SAAU;GAAE,MAAM;GAAoB,SAAS;EAAK,CAAE;CACvD,GAAG,CAAE,UAAW,CAAE;CAElB,MAAM,cAAc,eACX;EAAE,GAAG;EAAuB,UAAU;CAAe,IAC7D,CAAE,uBAAuB,cAAe,CACzC;CAEA,MAAM,UAAU,CAAE,0BAA2B,OAAO,eAAgB;CAEpE,OAAO,eACE;EACP;EACA,aAAa,MAAM;EACnB;EACA,OAAO,MAAM;EACb;EACA;EACA;EACA;EAUA,gBAAgB,YAAY;EAC5B;EACA;EACA;EACA;EACA;EACA;CACD,IACA;EACC;EACA,MAAM;EACN;EACA,MAAM;EACN;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,CACD;AACD"}
|
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
// packages/media-editor/src/utils/get-media-type.ts
|
|
2
|
+
/** The media types the editor tells apart, by MIME type prefix. */
|
|
3
|
+
const MEDIA_TYPES = [
|
|
4
|
+
"image",
|
|
5
|
+
"video",
|
|
6
|
+
"audio",
|
|
7
|
+
"application"
|
|
8
|
+
];
|
|
2
9
|
/**
|
|
3
10
|
* Determines the media type from a MIME type string.
|
|
4
11
|
*
|
|
@@ -12,6 +19,6 @@ function getMediaTypeFromMimeType(mimeType) {
|
|
|
12
19
|
if (mimeType.startsWith("audio/")) return { type: "audio" };
|
|
13
20
|
return { type: "application" };
|
|
14
21
|
}
|
|
15
|
-
export { getMediaTypeFromMimeType };
|
|
22
|
+
export { MEDIA_TYPES, getMediaTypeFromMimeType };
|
|
16
23
|
|
|
17
24
|
//# sourceMappingURL=get-media-type.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-media-type.mjs","names":[],"sources":["../../src/utils/get-media-type.ts"],"sourcesContent":["/**\n * Media type result.\n */\nexport interface MediaType {\n\ttype:
|
|
1
|
+
{"version":3,"file":"get-media-type.mjs","names":[],"sources":["../../src/utils/get-media-type.ts"],"sourcesContent":["/** The media types the editor tells apart, by MIME type prefix. */\nexport const MEDIA_TYPES = [\n\t'image',\n\t'video',\n\t'audio',\n\t'application',\n] as const;\n\n/**\n * Media type result.\n */\nexport interface MediaType {\n\ttype: ( typeof MEDIA_TYPES )[ number ];\n}\n\n/**\n * Determines the media type from a MIME type string.\n *\n * @param mimeType - The MIME type to check.\n * @return Object with type property ('image', 'video', 'audio', or 'application').\n */\nexport function getMediaTypeFromMimeType( mimeType?: string ): MediaType {\n\tif ( ! mimeType ) {\n\t\treturn { type: 'application' };\n\t}\n\n\tif ( mimeType.startsWith( 'image/' ) ) {\n\t\treturn { type: 'image' };\n\t}\n\tif ( mimeType.startsWith( 'video/' ) ) {\n\t\treturn { type: 'video' };\n\t}\n\tif ( mimeType.startsWith( 'audio/' ) ) {\n\t\treturn { type: 'audio' };\n\t}\n\treturn { type: 'application' };\n}\n"],"mappings":";;AACA,MAAa,cAAc;CAC1B;CACA;CACA;CACA;AACD;;;;;;;AAeA,SAAgB,yBAA0B,UAA+B;CACxE,IAAK,CAAE,UACN,OAAO,EAAE,MAAM,cAAc;CAG9B,IAAK,SAAS,WAAY,QAAS,GAClC,OAAO,EAAE,MAAM,QAAQ;CAExB,IAAK,SAAS,WAAY,QAAS,GAClC,OAAO,EAAE,MAAM,QAAQ;CAExB,IAAK,SAAS,WAAY,QAAS,GAClC,OAAO,EAAE,MAAM,QAAQ;CAExB,OAAO,EAAE,MAAM,cAAc;AAC9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { getMediaTypeFromMimeType } from "./get-media-type.mjs";
|
|
1
|
+
export { MEDIA_TYPES, getMediaTypeFromMimeType } from "./get-media-type.mjs";
|