@panneau/media 0.0.0-stage → 5.0.0-alpha.5

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.
Files changed (84) hide show
  1. package/README.md +133 -2
  2. package/dist/ImageItem.d.ts +23 -0
  3. package/dist/ImageItem.d.ts.map +1 -0
  4. package/dist/ImageItem.js +292 -0
  5. package/dist/ImageItem.js.map +1 -0
  6. package/dist/MediaField.css +177 -0
  7. package/dist/MediaField.d.ts +121 -0
  8. package/dist/MediaField.d.ts.map +1 -0
  9. package/dist/MediaField.js +520 -0
  10. package/dist/MediaField.js.map +1 -0
  11. package/dist/MediaField.module.js +46 -0
  12. package/dist/MediaField.module.js.map +1 -0
  13. package/dist/editor/ImageEditor.css +369 -0
  14. package/dist/editor/ImageEditor.d.ts +13 -0
  15. package/dist/editor/ImageEditor.d.ts.map +1 -0
  16. package/dist/editor/ImageEditor.js +461 -0
  17. package/dist/editor/ImageEditor.js.map +1 -0
  18. package/dist/editor/ImageEditor.module.js +86 -0
  19. package/dist/editor/ImageEditor.module.js.map +1 -0
  20. package/dist/editor/draw.d.ts +37 -0
  21. package/dist/editor/draw.d.ts.map +1 -0
  22. package/dist/editor/draw.js +93 -0
  23. package/dist/editor/draw.js.map +1 -0
  24. package/dist/editor/geometry.d.ts +54 -0
  25. package/dist/editor/geometry.d.ts.map +1 -0
  26. package/dist/editor/geometry.js +227 -0
  27. package/dist/editor/geometry.js.map +1 -0
  28. package/dist/editor/index.d.ts +5 -0
  29. package/dist/editor/index.d.ts.map +1 -0
  30. package/dist/editor/index.js +3 -0
  31. package/dist/editor/tools.d.ts +11 -0
  32. package/dist/editor/tools.d.ts.map +1 -0
  33. package/dist/editor/tools.js +1199 -0
  34. package/dist/editor/tools.js.map +1 -0
  35. package/dist/editor/types.d.ts +111 -0
  36. package/dist/editor/types.d.ts.map +1 -0
  37. package/dist/index.d.ts +5 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +4 -0
  40. package/dist/picker/MediaDetails.d.ts +22 -0
  41. package/dist/picker/MediaDetails.d.ts.map +1 -0
  42. package/dist/picker/MediaDetails.js +368 -0
  43. package/dist/picker/MediaDetails.js.map +1 -0
  44. package/dist/picker/MediaGrid.d.ts +30 -0
  45. package/dist/picker/MediaGrid.d.ts.map +1 -0
  46. package/dist/picker/MediaGrid.js +260 -0
  47. package/dist/picker/MediaGrid.js.map +1 -0
  48. package/dist/picker/MediaPicker.css +642 -0
  49. package/dist/picker/MediaPicker.d.ts +9 -0
  50. package/dist/picker/MediaPicker.d.ts.map +1 -0
  51. package/dist/picker/MediaPicker.js +601 -0
  52. package/dist/picker/MediaPicker.js.map +1 -0
  53. package/dist/picker/MediaPicker.module.js +132 -0
  54. package/dist/picker/MediaPicker.module.js.map +1 -0
  55. package/dist/picker/PickerToolbar.d.ts +19 -0
  56. package/dist/picker/PickerToolbar.d.ts.map +1 -0
  57. package/dist/picker/PickerToolbar.js +266 -0
  58. package/dist/picker/PickerToolbar.js.map +1 -0
  59. package/dist/picker/UploadPanel.d.ts +22 -0
  60. package/dist/picker/UploadPanel.d.ts.map +1 -0
  61. package/dist/picker/UploadPanel.js +186 -0
  62. package/dist/picker/UploadPanel.js.map +1 -0
  63. package/dist/picker/format.d.ts +18 -0
  64. package/dist/picker/format.d.ts.map +1 -0
  65. package/dist/picker/format.js +61 -0
  66. package/dist/picker/format.js.map +1 -0
  67. package/dist/picker/index.d.ts +3 -0
  68. package/dist/picker/index.d.ts.map +1 -0
  69. package/dist/picker/index.js +1 -0
  70. package/dist/picker/types.d.ts +119 -0
  71. package/dist/picker/types.d.ts.map +1 -0
  72. package/dist/picker/useMediaBrowser.d.ts +50 -0
  73. package/dist/picker/useMediaBrowser.d.ts.map +1 -0
  74. package/dist/picker/useMediaBrowser.js +314 -0
  75. package/dist/picker/useMediaBrowser.js.map +1 -0
  76. package/dist/plugin.d.ts +11 -0
  77. package/dist/plugin.d.ts.map +1 -0
  78. package/dist/plugin.js +18 -0
  79. package/dist/plugin.js.map +1 -0
  80. package/dist/resourceSource.d.ts +21 -0
  81. package/dist/resourceSource.d.ts.map +1 -0
  82. package/dist/resourceSource.js +99 -0
  83. package/dist/resourceSource.js.map +1 -0
  84. package/package.json +58 -5
@@ -0,0 +1,121 @@
1
+ import type { DataAdapter } from '@panneau/data';
2
+ import { type FieldEntryProps, type FieldProps, type UploadSource } from '@panneau/fields';
3
+ import type { Definition, Field, MediaReference } from '@panneau/protocol';
4
+ import type { MediaSource } from './picker/types';
5
+ /** What the media field needs from an adapter: `@panneau/data`'s `DataAdapter` has it. */
6
+ export type MediaAdapter = Pick<DataAdapter, 'create' | 'get'>;
7
+ export interface MediaFieldBaseProps extends Omit<FieldProps<never>, 'value' | 'onChange'> {
8
+ /**
9
+ * The library the field uploads to: a resource of kind `media`. References without a
10
+ * `resource` are media of it.
11
+ */
12
+ resource: string;
13
+ /** The field that titles the media of the library, for the label of new references. Defaults to `name`. */
14
+ itemTitle?: string;
15
+ /**
16
+ * Creates media in the library from uploads (`create(resource, { file })`), and reads them
17
+ * again until they are processed (`get()`). Defaults to the adapter of `DataAdapterProvider`.
18
+ * Without one, the field is read-only.
19
+ */
20
+ adapter?: MediaAdapter | null;
21
+ /**
22
+ * Where files are uploaded directly to storage. Defaults to the one of the fields context.
23
+ * Without one, files are sent in `multipart/form-data` when the media is created.
24
+ */
25
+ uploadSource?: UploadSource | null;
26
+ accept?: readonly string[] | null;
27
+ maxSize?: number | null;
28
+ /** How often to read a media again until it is ready, in milliseconds. Defaults to 3 s. */
29
+ refreshInterval?: number;
30
+ /**
31
+ * The libraries the media picker browses, in the order of its switcher ("Choose media",
32
+ * "Add media"). Without any, the field only uploads.
33
+ */
34
+ sources?: readonly MediaSource[];
35
+ /** Keeps what the user browsed in the picker between openings (see `MediaPicker`). */
36
+ stateKey?: string;
37
+ /**
38
+ * Makes it an `image` field (decision 0031): its images as they are rendered for this use,
39
+ * the image editor to edit their transform, and the editor as the step after a pick when a
40
+ * crop is required. `ImageField` sets it.
41
+ */
42
+ image?: ImageOptions | null;
43
+ }
44
+ /** The options of an `image` field (decision 0031). */
45
+ export interface ImageOptions {
46
+ /** The ratios the editor offers, as `width:height`. */
47
+ ratios?: readonly string[];
48
+ /** Whether a crop must have one of `ratios`: the `crop` rule. */
49
+ enforceRatios?: boolean;
50
+ /** Whether each image needs a crop for this use: the `crop` rule. */
51
+ cropRequired?: boolean;
52
+ /** Whether the editor offers rotation and flips. Defaults to true. */
53
+ rotate?: boolean;
54
+ /** Whether the editor offers the focal point. Defaults to true. */
55
+ focalPoint?: boolean;
56
+ /**
57
+ * What a transform for one use starts from: the media's own transform (the default), the
58
+ * original file, or the user's choice in the editor.
59
+ */
60
+ transformBase?: 'media' | 'original' | 'choose';
61
+ }
62
+ export interface SingleMediaFieldProps extends MediaFieldBaseProps {
63
+ multiple?: false;
64
+ value?: MediaReference | null;
65
+ onChange?: (value: MediaReference | null) => void;
66
+ }
67
+ export interface MultipleMediaFieldProps extends MediaFieldBaseProps {
68
+ multiple: true;
69
+ value?: readonly MediaReference[] | null;
70
+ /** Called with the media. An empty list is `null`. */
71
+ onChange?: (value: MediaReference[] | null) => void;
72
+ }
73
+ export type MediaFieldProps = SingleMediaFieldProps | MultipleMediaFieldProps;
74
+ /**
75
+ * The reference of a value: a reference, a media item (its `media` and title), or an id, as a
76
+ * product's own API may give them.
77
+ */
78
+ export declare function toMediaReference(value: unknown, itemTitle?: string): MediaReference | null;
79
+ /** The references of a value, single or multiple. */
80
+ export declare function toMediaReferences(value: unknown, itemTitle?: string): MediaReference[];
81
+ /** Whether the file of a media is still being processed. */
82
+ export declare function isProcessing(reference: MediaReference): boolean;
83
+ /**
84
+ * The first library a `media` field allows (decision 0027): the one its `resource` names, the
85
+ * first one it lists, or the first resource of kind `media` of the definition when it names none.
86
+ * The field uploads to it.
87
+ */
88
+ export declare function getLibrary(definition: Pick<Definition, 'resources'> | null, resource: string | readonly string[] | undefined): Definition['resources'][number] | null;
89
+ /**
90
+ * Media of libraries (the `media` type, decisions 0026 and 0027). "Choose media" ("Add media"
91
+ * with `multiple`) opens the media picker on the `sources`, and a file chosen or dropped becomes
92
+ * a media of the library, an item of its resource (`create(resource, { file })`), sent directly
93
+ * to storage first when there is an upload source. Values are references to the media, with
94
+ * their library, their `media` and their `transform` for this use. The field shows each media
95
+ * with its thumbnail and its status, and reads it again until its file is processed.
96
+ */
97
+ export declare function MediaField(props: MediaFieldProps): import("react").JSX.Element;
98
+ /** The props of `ImageField`: those of `MediaField`, with the options of an `image` field. */
99
+ export type ImageFieldProps = MediaFieldProps & ImageOptions;
100
+ /**
101
+ * An `image` field (decision 0031): a `media` field for images, with the image editor. It accepts
102
+ * `image/*` by default. Each image shows as it is rendered for this use, with Edit, which opens
103
+ * the editor on its transform. When a crop is required, the editor is the step right after the
104
+ * pick of one image.
105
+ */
106
+ export declare function ImageField(props: ImageFieldProps): import("react").JSX.Element;
107
+ /**
108
+ * The options of an `image` field of a definition: its `crop` rule (enforced ratios, a required
109
+ * crop), its suggested `ratios`, and the tools and base of its editor.
110
+ */
111
+ export declare function getImageOptions(field: Field): ImageOptions;
112
+ /**
113
+ * The registry entry of the `media` and `image` types: the picker on the libraries the field allows
114
+ * (`getMediaLibraries()`), uploads to the first one (`getLibrary()`), `multiple`, `accept` (or
115
+ * its `accept` rule) and `maxSize` rule, with the adapter of `@panneau/data` and the upload source
116
+ * of the fields context. The picker opens again where the user left it in the same libraries.
117
+ * Without a library, the field shows its media and can't add any. An `image` field also gets its
118
+ * options (`getImageOptions()`), and accepts `image/*` by default.
119
+ */
120
+ export declare function MediaFieldEntry(props: FieldEntryProps): import("react").JSX.Element;
121
+ //# sourceMappingURL=MediaField.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MediaField.d.ts","sourceRoot":"","sources":["../src/MediaField.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAEjD,OAAO,EACH,KAAK,eAAe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,+BAobhD;AAED,8FAA8F;AAC9F,MAAM,MAAM,eAAe,GAAG,eAAe,GAAG,YAAY,CAAC;AAE7D;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,eAAe,+BAoBhD;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,KAAK,GAAG,YAAY,CAoB1D;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,eAAe,+BA+BrD"}
@@ -0,0 +1,520 @@
1
+ import MediaField_module_default from "./MediaField.module.js";
2
+ import { ImageItem, editedImageOf } from "./ImageItem.js";
3
+ import { useImageEditorTools } from "./editor/tools.js";
4
+ import { ImageEditorDialog } from "./editor/ImageEditor.js";
5
+ import { MediaPicker } from "./picker/MediaPicker.js";
6
+ import { createResourceMediaSource } from "./resourceSource.js";
7
+ import { c } from "react/compiler-runtime";
8
+ import { FileImage, Images, X } from "lucide-react";
9
+ import { useEffect, useRef, useState } from "react";
10
+ import { usePanneau } from "@panneau/core";
11
+ import { useOptionalDataAdapter } from "@panneau/data/query";
12
+ import { FilePicker, UploadList, formatSize, getAccept, getFieldProps, getMaxSize, useFieldsContext, useRejectionMessage, useUploads } from "@panneau/fields";
13
+ import { fieldsMessages, mediaMessages } from "@panneau/intl";
14
+ import { getMediaLibraries } from "@panneau/protocol/runtime";
15
+ import { Badge, Button, Fieldset, IconButton, Spinner, usePanneauIntl } from "@panneau/ui";
16
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
17
+ //#region src/MediaField.tsx
18
+ /**
19
+ * The reference of a value: a reference, a media item (its `media` and title), or an id, as a
20
+ * product's own API may give them.
21
+ */
22
+ function toMediaReference(value, itemTitle = "name") {
23
+ if (typeof value === "string" || typeof value === "number") return { id: String(value) };
24
+ if (typeof value !== "object" || value === null) return null;
25
+ const { id, resource, label, media, transform } = value;
26
+ if (typeof id !== "string" && typeof id !== "number") return null;
27
+ const title = value[itemTitle];
28
+ const reference = { id: String(id) };
29
+ if (typeof resource === "string") reference.resource = resource;
30
+ if (typeof label === "string") reference.label = label;
31
+ else if (typeof title === "string") reference.label = title;
32
+ if (typeof media === "object" && media !== null) reference.media = media;
33
+ if (typeof transform === "object") reference.transform = transform;
34
+ return reference;
35
+ }
36
+ /** The references of a value, single or multiple. */
37
+ function toMediaReferences(value, itemTitle) {
38
+ return (Array.isArray(value) ? value : [value]).map((entry) => toMediaReference(entry, itemTitle)).filter((reference) => reference !== null);
39
+ }
40
+ /** The key of a reference: its library and its id, which are unique only together. */
41
+ var keyOf = (reference, resource) => `${reference.resource ?? resource}\n${reference.id}`;
42
+ /** Whether the file of a media is still being processed. */
43
+ function isProcessing(reference) {
44
+ const status = reference.media?.status;
45
+ return status === "pending" || status === "processing";
46
+ }
47
+ /**
48
+ * The first library a `media` field allows (decision 0027): the one its `resource` names, the
49
+ * first one it lists, or the first resource of kind `media` of the definition when it names none.
50
+ * The field uploads to it.
51
+ */
52
+ function getLibrary(definition, resource) {
53
+ const [first] = getMediaLibraries(definition, { resource });
54
+ return definition?.resources.find((candidate) => candidate.id === first) ?? null;
55
+ }
56
+ /**
57
+ * Reads media again while they are being ingested, until they are ready or failed, and calls
58
+ * `onRefresh` with the media that changed.
59
+ */
60
+ function useMediaRefresh(media, resource, adapter, interval, onRefresh) {
61
+ const $ = c(16);
62
+ const latest = useRef(onRefresh);
63
+ let t0;
64
+ if ($[0] !== onRefresh) {
65
+ t0 = () => {
66
+ latest.current = onRefresh;
67
+ };
68
+ $[0] = onRefresh;
69
+ $[1] = t0;
70
+ } else t0 = $[1];
71
+ useEffect(t0);
72
+ let t1;
73
+ if ($[2] !== media || $[3] !== resource) {
74
+ let t2;
75
+ if ($[5] !== resource) {
76
+ t2 = (item) => JSON.stringify([
77
+ item.resource ?? resource,
78
+ item.id,
79
+ item.media?.status ?? ""
80
+ ]);
81
+ $[5] = resource;
82
+ $[6] = t2;
83
+ } else t2 = $[6];
84
+ t1 = media.filter(isProcessing).map(t2).join("\n");
85
+ $[2] = media;
86
+ $[3] = resource;
87
+ $[4] = t1;
88
+ } else t1 = $[4];
89
+ const key = t1;
90
+ let t2;
91
+ if ($[7] !== adapter || $[8] !== interval || $[9] !== key) {
92
+ t2 = () => {
93
+ if (adapter === null || key === "") return;
94
+ const entries = key.split("\n").map(_temp);
95
+ const controller = new AbortController();
96
+ const timer = setTimeout(() => {
97
+ Promise.all(entries.map((t3) => {
98
+ const { library: library_0, id: id_0 } = t3;
99
+ return adapter.get(library_0, id_0, { signal: controller.signal }).then((item_0) => ({
100
+ resource: library_0,
101
+ item: item_0
102
+ }));
103
+ })).then((refreshed) => {
104
+ if (!controller.signal.aborted) latest.current(refreshed);
105
+ }).catch(_temp2);
106
+ }, interval);
107
+ return () => {
108
+ clearTimeout(timer);
109
+ controller.abort();
110
+ };
111
+ };
112
+ $[7] = adapter;
113
+ $[8] = interval;
114
+ $[9] = key;
115
+ $[10] = t2;
116
+ } else t2 = $[10];
117
+ let t3;
118
+ if ($[11] !== adapter || $[12] !== interval || $[13] !== key || $[14] !== resource) {
119
+ t3 = [
120
+ adapter,
121
+ resource,
122
+ key,
123
+ interval
124
+ ];
125
+ $[11] = adapter;
126
+ $[12] = interval;
127
+ $[13] = key;
128
+ $[14] = resource;
129
+ $[15] = t3;
130
+ } else t3 = $[15];
131
+ useEffect(t2, t3);
132
+ }
133
+ /**
134
+ * Media of libraries (the `media` type, decisions 0026 and 0027). "Choose media" ("Add media"
135
+ * with `multiple`) opens the media picker on the `sources`, and a file chosen or dropped becomes
136
+ * a media of the library, an item of its resource (`create(resource, { file })`), sent directly
137
+ * to storage first when there is an upload source. Values are references to the media, with
138
+ * their library, their `media` and their `transform` for this use. The field shows each media
139
+ * with its thumbnail and its status, and reads it again until its file is processed.
140
+ */
141
+ function _temp2() {}
142
+ function _temp(entry) {
143
+ const [library, id] = JSON.parse(entry);
144
+ return {
145
+ library,
146
+ id
147
+ };
148
+ }
149
+ function MediaField(props) {
150
+ const intl = usePanneauIntl();
151
+ const contextAdapter = useOptionalDataAdapter();
152
+ const context = useFieldsContext();
153
+ const { adapter = contextAdapter, uploadSource = context.uploadSource, accept = null, maxSize = null, refreshInterval = 3e3, resource, itemTitle = "name", sources = [], stateKey, label, description, errors = [], disabled, readOnly, required, className, labelClassName, descriptionClassName, errorsClassName } = props;
154
+ const multiple = props.multiple === true;
155
+ const media = toMediaReferences(props.value, itemTitle);
156
+ const enabled = disabled !== true && readOnly !== true;
157
+ const canUpload = adapter !== null && enabled;
158
+ const canPick = sources.length > 0 && enabled;
159
+ const [picking, setPicking] = useState(false);
160
+ const imageOptions = props.image ?? null;
161
+ const [editing, setEditing] = useState(null);
162
+ const editorTools = useImageEditorTools();
163
+ const [problems, setProblems] = useState([]);
164
+ const [creating, setCreating] = useState([]);
165
+ const rejectionMessage = useRejectionMessage(maxSize);
166
+ const latest = useRef(media);
167
+ useEffect(() => {
168
+ latest.current = media;
169
+ });
170
+ const set = (next) => {
171
+ latest.current = next;
172
+ if (props.multiple === true) props.onChange?.(next.length > 0 ? next : null);
173
+ else props.onChange?.(next[0] ?? null);
174
+ };
175
+ /** Adds picked media: a single pick replaces the media, several are added to the list, once. */
176
+ const add = (picked) => {
177
+ const known = new Set(latest.current.map((entry) => keyOf(entry, resource)));
178
+ set(multiple ? [...latest.current, ...picked.filter((entry_0) => !known.has(keyOf(entry_0, resource)))] : picked.slice(0, 1));
179
+ };
180
+ useMediaRefresh(media, resource, adapter, refreshInterval, (refreshed) => set(latest.current.map((reference) => {
181
+ const item = refreshed.find((candidate) => candidate.item.id === reference.id && candidate.resource === (reference.resource ?? resource))?.item;
182
+ const fresh = item !== void 0 ? toMediaReference(item, itemTitle) : null;
183
+ return fresh !== null ? {
184
+ ...reference,
185
+ ...fresh,
186
+ transform: reference.transform
187
+ } : reference;
188
+ })));
189
+ const upload = useUploads({
190
+ source: uploadSource,
191
+ accept,
192
+ maxSize,
193
+ onUploaded: (file) => {
194
+ if (adapter === null) return;
195
+ const name = file.name;
196
+ setCreating((current) => [...current, name]);
197
+ adapter.create(resource, { file: file instanceof File ? file : { upload: file.upload } }).then((item_0) => {
198
+ const created = {
199
+ ...toMediaReference(item_0, itemTitle) ?? { id: item_0.id },
200
+ resource
201
+ };
202
+ set(multiple ? [...latest.current, created] : [created]);
203
+ }).catch((error) => setProblems((current_0) => [...current_0, intl.formatMessage(fieldsMessages.uploadFailed, { error: `${name}: ${error instanceof Error ? error.message : String(error)}` })])).finally(() => setCreating((current_1) => {
204
+ const at = current_1.indexOf(name);
205
+ return at === -1 ? current_1 : current_1.filter((_, index) => index !== at);
206
+ }));
207
+ },
208
+ onRejected: (file_0, reason) => setProblems((current_2) => [...current_2, rejectionMessage(file_0, reason)])
209
+ });
210
+ const statusBadge = (item_1) => {
211
+ if (item_1.media?.status === "failed") return /* @__PURE__ */ jsx(Badge, {
212
+ tone: "danger",
213
+ children: intl.formatMessage(mediaMessages.statusFailed)
214
+ });
215
+ if (isProcessing(item_1)) return /* @__PURE__ */ jsx(Badge, {
216
+ tone: "warning",
217
+ children: intl.formatMessage(item_1.media?.status === "pending" ? mediaMessages.statusPending : mediaMessages.statusProcessing)
218
+ });
219
+ return null;
220
+ };
221
+ const imageRatios = imageOptions?.ratios ?? [];
222
+ const constraints = imageOptions === null ? [] : [...imageRatios.length > 0 ? [intl.formatMessage(imageOptions.enforceRatios === true ? mediaMessages.imageRatios : mediaMessages.imageSuggestedRatios, { ratios: intl.formatList(imageRatios, { type: "disjunction" }) })] : [], ...imageOptions.cropRequired === true ? [intl.formatMessage(mediaMessages.imageCropRequired)] : []];
223
+ const edited = editing === null ? null : "key" in editing ? media.find((entry_1) => keyOf(entry_1, resource) === editing.key) ?? null : editing.picked;
224
+ const editedImage = edited !== null ? editedImageOf(edited) : null;
225
+ const tools = [
226
+ editorTools.crop,
227
+ ...imageOptions?.rotate === false ? [] : [editorTools.rotate],
228
+ ...imageOptions?.focalPoint === false ? [] : [editorTools.focalPoint]
229
+ ];
230
+ const unavailable = adapter === null && disabled !== true && readOnly !== true;
231
+ const chooseLabel = imageOptions !== null ? multiple ? mediaMessages.addImages : mediaMessages.chooseImage : multiple ? mediaMessages.addMedia : mediaMessages.chooseMedia;
232
+ const cropStep = imageOptions?.cropRequired === true && !multiple;
233
+ const withTransform = (reference_0, transform) => {
234
+ const { transform: _previous, ...rest } = reference_0;
235
+ return transform === null || transform === void 0 ? rest : {
236
+ ...rest,
237
+ transform
238
+ };
239
+ };
240
+ return /* @__PURE__ */ jsxs(Fieldset, {
241
+ legend: label,
242
+ description: description !== void 0 || unavailable || constraints.length > 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
243
+ description,
244
+ unavailable ? `${description !== void 0 ? " " : ""}${intl.formatMessage(mediaMessages.unavailable)}` : null,
245
+ constraints.length > 0 ? /* @__PURE__ */ jsx("span", {
246
+ className: MediaField_module_default.constraints,
247
+ children: constraints.map((constraint) => /* @__PURE__ */ jsx(Badge, { children: constraint }, constraint))
248
+ }) : null
249
+ ] }) : void 0,
250
+ errors: [...errors, ...problems],
251
+ isRequired: required,
252
+ isDisabled: disabled,
253
+ className,
254
+ legendClassName: labelClassName,
255
+ descriptionClassName,
256
+ errorsClassName,
257
+ children: [
258
+ /* @__PURE__ */ jsxs("div", {
259
+ className: MediaField_module_default.field,
260
+ children: [
261
+ media.length > 0 && imageOptions !== null ? /* @__PURE__ */ jsx("ul", {
262
+ className: multiple ? MediaField_module_default.gallery : MediaField_module_default.media,
263
+ children: media.map((item_2) => /* @__PURE__ */ jsx(ImageItem, {
264
+ reference: item_2,
265
+ tile: multiple,
266
+ cropRequired: imageOptions.cropRequired === true,
267
+ status: statusBadge(item_2),
268
+ onEdit: enabled ? () => setEditing({ key: keyOf(item_2, resource) }) : null,
269
+ onRemove: canUpload || canPick ? () => set(latest.current.filter((entry_2) => keyOf(entry_2, resource) !== keyOf(item_2, resource))) : null
270
+ }, keyOf(item_2, resource)))
271
+ }) : media.length > 0 ? /* @__PURE__ */ jsx("ul", {
272
+ className: MediaField_module_default.media,
273
+ children: media.map((item_3) => {
274
+ const name_0 = item_3.label ?? item_3.id;
275
+ const size = item_3.media?.size;
276
+ return /* @__PURE__ */ jsxs("li", {
277
+ className: MediaField_module_default.item,
278
+ children: [
279
+ /* @__PURE__ */ jsx("span", {
280
+ className: MediaField_module_default.thumbnail,
281
+ children: typeof item_3.media?.thumbnailUrl === "string" ? /* @__PURE__ */ jsx("img", {
282
+ src: item_3.media.thumbnailUrl,
283
+ alt: ""
284
+ }) : /* @__PURE__ */ jsx(FileImage, { "aria-hidden": true })
285
+ }),
286
+ /* @__PURE__ */ jsxs("span", {
287
+ className: MediaField_module_default.details,
288
+ children: [/* @__PURE__ */ jsx("span", {
289
+ className: MediaField_module_default.name,
290
+ children: name_0
291
+ }), /* @__PURE__ */ jsxs("span", {
292
+ className: MediaField_module_default.meta,
293
+ children: [
294
+ item_3.media !== void 0 ? /* @__PURE__ */ jsx("span", { children: item_3.media.type }) : null,
295
+ typeof size === "number" ? /* @__PURE__ */ jsx("span", { children: formatSize(size, intl.locale) }) : null,
296
+ statusBadge(item_3)
297
+ ]
298
+ })]
299
+ }),
300
+ canUpload || canPick ? /* @__PURE__ */ jsx(IconButton, {
301
+ icon: X,
302
+ size: "sm",
303
+ label: intl.formatMessage(fieldsMessages.removeFile, { name: name_0 }),
304
+ onPress: () => set(latest.current.filter((entry_3) => keyOf(entry_3, resource) !== keyOf(item_3, resource)))
305
+ }) : null
306
+ ]
307
+ }, keyOf(item_3, resource));
308
+ })
309
+ }) : creating.length === 0 && upload.items.length === 0 ? /* @__PURE__ */ jsx("span", {
310
+ className: MediaField_module_default.none,
311
+ children: intl.formatMessage(imageOptions !== null ? mediaMessages.noImage : mediaMessages.noMedia)
312
+ }) : null,
313
+ /* @__PURE__ */ jsx(UploadList, {
314
+ items: upload.items,
315
+ onPause: upload.pause,
316
+ onResume: upload.resume,
317
+ onCancel: upload.cancel,
318
+ onRetry: upload.retry
319
+ }),
320
+ creating.length > 0 ? /* @__PURE__ */ jsxs("span", {
321
+ className: MediaField_module_default.meta,
322
+ role: "status",
323
+ children: [
324
+ /* @__PURE__ */ jsx(Spinner, { size: "sm" }),
325
+ intl.formatMessage(fieldsMessages.uploadCompleting),
326
+ " ",
327
+ creating.join(", ")
328
+ ]
329
+ }) : null,
330
+ canPick || canUpload ? /* @__PURE__ */ jsxs("div", {
331
+ className: MediaField_module_default.actions,
332
+ children: [canPick ? /* @__PURE__ */ jsx(Button, {
333
+ size: "sm",
334
+ appearance: "outline",
335
+ icon: Images,
336
+ onPress: () => setPicking(true),
337
+ children: intl.formatMessage(chooseLabel)
338
+ }) : null, canUpload ? /* @__PURE__ */ jsx(FilePicker, {
339
+ accept,
340
+ multiple,
341
+ className: MediaField_module_default.upload,
342
+ ...canPick ? { label: intl.formatMessage(imageOptions !== null ? multiple ? mediaMessages.uploadImages : mediaMessages.uploadImage : multiple ? mediaMessages.uploadFiles : mediaMessages.uploadFile) } : {},
343
+ onSelect: (selected) => {
344
+ setProblems([]);
345
+ upload.add(selected);
346
+ }
347
+ }) : null]
348
+ }) : null
349
+ ]
350
+ }),
351
+ canPick ? /* @__PURE__ */ jsx(MediaPicker, {
352
+ isOpen: picking,
353
+ onOpenChange: setPicking,
354
+ sources,
355
+ multiple,
356
+ accept,
357
+ maxSize,
358
+ value: media,
359
+ title: intl.formatMessage(chooseLabel),
360
+ ...cropStep ? { confirmLabel: intl.formatMessage(mediaMessages.imageNextCrop) } : {},
361
+ uploadSource,
362
+ refreshInterval,
363
+ ...stateKey !== void 0 ? { stateKey } : {},
364
+ onSelect: (picked_0) => {
365
+ setProblems([]);
366
+ const [first] = picked_0;
367
+ if (cropStep && picked_0.length === 1 && first !== void 0 && editedImageOf(first) !== null) {
368
+ setEditing({ picked: first });
369
+ return;
370
+ }
371
+ add(picked_0);
372
+ }
373
+ }) : null,
374
+ imageOptions !== null && edited !== null && editedImage !== null && editing !== null ? /* @__PURE__ */ jsx(ImageEditorDialog, {
375
+ isOpen: true,
376
+ onOpenChange: (isOpen) => {
377
+ if (!isOpen) setEditing(null);
378
+ },
379
+ image: editedImage,
380
+ value: "key" in editing ? edited.transform ?? null : null,
381
+ base: imageOptions.transformBase === "original" ? "original" : "media",
382
+ canChooseBase: imageOptions.transformBase === "choose",
383
+ tools,
384
+ ratios: imageRatios,
385
+ enforceRatios: imageOptions.enforceRatios === true,
386
+ cropRequired: imageOptions.cropRequired === true,
387
+ ..."picked" in editing ? {
388
+ title: intl.formatMessage(mediaMessages.imageCropForUse),
389
+ applyLabel: intl.formatMessage(mediaMessages.imageUseCrop),
390
+ onBack: () => {
391
+ setEditing(null);
392
+ setPicking(true);
393
+ }
394
+ } : {},
395
+ onApply: (transform_0) => {
396
+ const next_0 = withTransform(edited, transform_0);
397
+ if ("picked" in editing) add([next_0]);
398
+ else set(latest.current.map((entry_4) => keyOf(entry_4, resource) === editing.key ? next_0 : entry_4));
399
+ }
400
+ }) : null
401
+ ]
402
+ });
403
+ }
404
+ /**
405
+ * An `image` field (decision 0031): a `media` field for images, with the image editor. It accepts
406
+ * `image/*` by default. Each image shows as it is rendered for this use, with Edit, which opens
407
+ * the editor on its transform. When a crop is required, the editor is the step right after the
408
+ * pick of one image.
409
+ */
410
+ function ImageField(props) {
411
+ const { ratios, enforceRatios, cropRequired, rotate, focalPoint, transformBase, accept = ["image/*"], ...rest } = props;
412
+ const image = {
413
+ ...ratios !== void 0 ? { ratios } : {},
414
+ ...enforceRatios !== void 0 ? { enforceRatios } : {},
415
+ ...cropRequired !== void 0 ? { cropRequired } : {},
416
+ ...rotate !== void 0 ? { rotate } : {},
417
+ ...focalPoint !== void 0 ? { focalPoint } : {},
418
+ ...transformBase !== void 0 ? { transformBase } : {}
419
+ };
420
+ return /* @__PURE__ */ jsx(MediaField, {
421
+ ...rest,
422
+ accept,
423
+ image
424
+ });
425
+ }
426
+ /**
427
+ * The options of an `image` field of a definition: its `crop` rule (enforced ratios, a required
428
+ * crop), its suggested `ratios`, and the tools and base of its editor.
429
+ */
430
+ function getImageOptions(field) {
431
+ const rule = field.rules?.find((candidate) => candidate.rule === "crop");
432
+ const value = rule !== void 0 && "value" in rule && typeof rule.value === "object" && rule.value !== null ? rule.value : {};
433
+ const enforced = Array.isArray(value.ratios) ? value.ratios.filter((ratio) => typeof ratio === "string") : [];
434
+ return {
435
+ ratios: enforced.length > 0 ? enforced : field.ratios ?? [],
436
+ enforceRatios: enforced.length > 0,
437
+ cropRequired: value.required === true,
438
+ rotate: field.rotate !== false,
439
+ focalPoint: field.focalPoint !== false,
440
+ transformBase: field.transformBase ?? "media"
441
+ };
442
+ }
443
+ /**
444
+ * The registry entry of the `media` and `image` types: the picker on the libraries the field allows
445
+ * (`getMediaLibraries()`), uploads to the first one (`getLibrary()`), `multiple`, `accept` (or
446
+ * its `accept` rule) and `maxSize` rule, with the adapter of `@panneau/data` and the upload source
447
+ * of the fields context. The picker opens again where the user left it in the same libraries.
448
+ * Without a library, the field shows its media and can't add any. An `image` field also gets its
449
+ * options (`getImageOptions()`), and accepts `image/*` by default.
450
+ */
451
+ function MediaFieldEntry(props) {
452
+ const $ = c(14);
453
+ const { field, value, onChange } = props;
454
+ const { definition } = usePanneau();
455
+ const adapter = useOptionalDataAdapter();
456
+ let common;
457
+ let t0;
458
+ if ($[0] !== adapter || $[1] !== definition || $[2] !== field || $[3] !== props || $[4] !== value) {
459
+ const library = getLibrary(definition, field.resource);
460
+ const itemTitle = library?.itemTitle ?? "name";
461
+ let t1;
462
+ if ($[7] !== definition?.resources) {
463
+ t1 = (id) => definition?.resources.find((candidate) => candidate.id === id) ?? [];
464
+ $[7] = definition?.resources;
465
+ $[8] = t1;
466
+ } else t1 = $[8];
467
+ const libraries = getMediaLibraries(definition, field).flatMap(t1);
468
+ const sources = adapter !== null ? libraries.map((candidate_0) => createResourceMediaSource(adapter, candidate_0)) : [];
469
+ const image = field.type === "image" ? getImageOptions(field) : null;
470
+ common = {
471
+ ...getFieldProps(props),
472
+ resource: library?.id ?? (typeof field.resource === "string" ? field.resource : ""),
473
+ itemTitle,
474
+ accept: getAccept(field) ?? (image !== null ? ["image/*"] : null),
475
+ maxSize: getMaxSize(field),
476
+ sources,
477
+ image,
478
+ stateKey: `panneau.media.${libraries.map(_temp3).join(",")}`,
479
+ ...library === null ? { adapter: null } : {}
480
+ };
481
+ t0 = toMediaReferences(value, itemTitle);
482
+ $[0] = adapter;
483
+ $[1] = definition;
484
+ $[2] = field;
485
+ $[3] = props;
486
+ $[4] = value;
487
+ $[5] = common;
488
+ $[6] = t0;
489
+ } else {
490
+ common = $[5];
491
+ t0 = $[6];
492
+ }
493
+ const references = t0;
494
+ let t1;
495
+ if ($[9] !== common || $[10] !== field.multiple || $[11] !== onChange || $[12] !== references) {
496
+ t1 = field.multiple === true ? /* @__PURE__ */ jsx(MediaField, {
497
+ ...common,
498
+ multiple: true,
499
+ value: references,
500
+ onChange
501
+ }) : /* @__PURE__ */ jsx(MediaField, {
502
+ ...common,
503
+ value: references[0] ?? null,
504
+ onChange
505
+ });
506
+ $[9] = common;
507
+ $[10] = field.multiple;
508
+ $[11] = onChange;
509
+ $[12] = references;
510
+ $[13] = t1;
511
+ } else t1 = $[13];
512
+ return t1;
513
+ }
514
+ function _temp3(candidate_1) {
515
+ return candidate_1.id;
516
+ }
517
+ //#endregion
518
+ export { ImageField, MediaField, MediaFieldEntry, getImageOptions, getLibrary, isProcessing, toMediaReference, toMediaReferences };
519
+
520
+ //# sourceMappingURL=MediaField.js.map