medusa-product-helper 0.0.28 → 0.0.30

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.
@@ -1,1800 +1,8 @@
1
- import { jsxs, jsx, Fragment } from "react/jsx-runtime";
1
+ import { jsxs, jsx } from "react/jsx-runtime";
2
+ import { useMemo } from "react";
3
+ import { useQuery } from "@tanstack/react-query";
2
4
  import { defineWidgetConfig } from "@medusajs/admin-sdk";
3
- import { Container, Heading, Badge, Text, Skeleton, InlineTip, Button, Switch, Textarea, Input, toast } from "@medusajs/ui";
4
- import { useState, useRef, useEffect, useMemo } from "react";
5
- import { useQuery, useQueryClient } from "@tanstack/react-query";
6
- const METADATA_FIELD_TYPES = ["number", "text", "file", "bool"];
7
- const VALID_FIELD_TYPES = new Set(METADATA_FIELD_TYPES);
8
- const BOOLEAN_TRUES = /* @__PURE__ */ new Set(["true", "1", "yes", "y", "on"]);
9
- const BOOLEAN_FALSES = /* @__PURE__ */ new Set(["false", "0", "no", "n", "off"]);
10
- function normalizeMetadataDescriptors(input) {
11
- if (!Array.isArray(input)) return [];
12
- const seenKeys = /* @__PURE__ */ new Set();
13
- return input.filter(
14
- (item) => item && typeof item === "object"
15
- ).map((item) => {
16
- const key = normalizeKey(item.key);
17
- const type = normalizeType(item.type);
18
- const label = normalizeLabel(item.label);
19
- const filterable = !!item.filterable;
20
- return { key, type, label, filterable };
21
- }).filter(({ key, type }) => key && type && !seenKeys.has(key)).map(({ key, type, label, filterable }) => {
22
- seenKeys.add(key);
23
- return {
24
- key,
25
- type,
26
- ...label && { label },
27
- ...filterable && { filterable: true }
28
- };
29
- });
30
- }
31
- function buildInitialFormState(descriptors, metadata) {
32
- const base = metadata && typeof metadata === "object" ? metadata : {};
33
- return descriptors.reduce((acc, descriptor) => {
34
- acc[descriptor.key] = normalizeFormValue(descriptor, base[descriptor.key]);
35
- return acc;
36
- }, {});
37
- }
38
- function buildMetadataPayload({
39
- descriptors,
40
- values,
41
- originalMetadata
42
- }) {
43
- const base = originalMetadata && typeof originalMetadata === "object" ? { ...originalMetadata } : {};
44
- descriptors.forEach((descriptor) => {
45
- const coerced = coerceMetadataValue(descriptor, values[descriptor.key]);
46
- if (coerced === void 0) {
47
- delete base[descriptor.key];
48
- } else {
49
- base[descriptor.key] = coerced;
50
- }
51
- });
52
- return base;
53
- }
54
- function hasMetadataChanges({
55
- descriptors,
56
- values,
57
- originalMetadata
58
- }) {
59
- const next = buildMetadataPayload({ descriptors, values, originalMetadata });
60
- const prev = originalMetadata && typeof originalMetadata === "object" ? originalMetadata : {};
61
- return descriptors.some(({ key }) => !isDeepEqual(prev[key], next[key]));
62
- }
63
- function validateValueForDescriptor(descriptor, value) {
64
- if (descriptor.type === "number") {
65
- if (value == null || value === "") return void 0;
66
- const num = typeof value === "number" ? value : Number(String(value).trim());
67
- return isNaN(num) ? "Enter a valid number" : void 0;
68
- }
69
- if (descriptor.type === "file") {
70
- if (!value) return void 0;
71
- try {
72
- new URL(String(value).trim());
73
- return void 0;
74
- } catch {
75
- return "Enter a valid URL";
76
- }
77
- }
78
- return void 0;
79
- }
80
- function normalizeFormValue(descriptor, currentValue) {
81
- if (descriptor.type === "bool") return Boolean(currentValue);
82
- if ((descriptor.type === "number" || descriptor.type === "text") && typeof currentValue === "number") {
83
- return currentValue.toString();
84
- }
85
- if (typeof currentValue === "string" || typeof currentValue === "number") {
86
- return String(currentValue);
87
- }
88
- return "";
89
- }
90
- function coerceMetadataValue(descriptor, value) {
91
- if (value == null || value === "") return void 0;
92
- if (descriptor.type === "bool") {
93
- if (typeof value === "boolean") return value;
94
- if (typeof value === "number") return value !== 0;
95
- const normalized = String(value).trim().toLowerCase();
96
- if (!normalized) return void 0;
97
- if (BOOLEAN_TRUES.has(normalized)) return true;
98
- if (BOOLEAN_FALSES.has(normalized)) return false;
99
- return Boolean(value);
100
- }
101
- if (descriptor.type === "number") {
102
- const num = typeof value === "number" ? value : Number(String(value).trim());
103
- return isNaN(num) ? void 0 : num;
104
- }
105
- const trimmed = String(value).trim();
106
- if (!trimmed) return void 0;
107
- return trimmed;
108
- }
109
- function normalizeKey(value) {
110
- return typeof value === "string" ? value.trim() || void 0 : void 0;
111
- }
112
- function normalizeType(value) {
113
- if (typeof value !== "string") return void 0;
114
- const type = value.trim().toLowerCase();
115
- return VALID_FIELD_TYPES.has(type) ? type : void 0;
116
- }
117
- function normalizeLabel(value) {
118
- return typeof value === "string" ? value.trim() || void 0 : void 0;
119
- }
120
- function isDeepEqual(a, b) {
121
- if (a === b) return true;
122
- if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
123
- const aKeys = Object.keys(a);
124
- const bKeys = Object.keys(b);
125
- if (aKeys.length !== bKeys.length) return false;
126
- return aKeys.every(
127
- (key) => isDeepEqual(a[key], b[key])
128
- );
129
- }
130
- const CONFIG_ENDPOINT = "/admin/product-metadata-config";
131
- const QUERY_KEY = ["medusa-product-helper", "metadata-config"];
132
- const useMetadataConfig = (entity) => {
133
- return useQuery({
134
- queryKey: [...QUERY_KEY, entity],
135
- queryFn: async () => {
136
- const response = await fetch(`${CONFIG_ENDPOINT}?entity=${entity}`, {
137
- credentials: "include"
138
- });
139
- if (!response.ok) {
140
- throw new Error("Unable to load metadata configuration");
141
- }
142
- const payload = await response.json();
143
- return normalizeMetadataDescriptors(payload.metadataDescriptors);
144
- },
145
- staleTime: 5 * 60 * 1e3
146
- });
147
- };
148
- const useProductMetadataConfig = () => useMetadataConfig("product");
149
- const useCategoryMetadataConfig = () => useMetadataConfig("category");
150
- const useOrderMetadataConfig = () => useMetadataConfig("order");
151
- const useCollectionMetadataConfig = () => useMetadataConfig("collection");
152
- const CONFIG_DOCS_URL$3 = "https://docs.medusajs.com/admin/extension-points/widgets#product-category-details";
153
- const CategoryMetadataTableWidget = ({ data }) => {
154
- const { data: descriptors = [], isPending, isError } = useCategoryMetadataConfig();
155
- const categoryId = (data == null ? void 0 : data.id) ?? void 0;
156
- const [baselineMetadata, setBaselineMetadata] = useState(
157
- (data == null ? void 0 : data.metadata) ?? {}
158
- );
159
- const queryClient = useQueryClient();
160
- const previousCategoryIdRef = useRef(categoryId);
161
- const isInitializedRef = useRef(false);
162
- const dataRef = useRef(data);
163
- const descriptorsRef = useRef(descriptors);
164
- useEffect(() => {
165
- dataRef.current = data;
166
- descriptorsRef.current = descriptors;
167
- }, [data, descriptors]);
168
- useEffect(() => {
169
- var _a;
170
- if (previousCategoryIdRef.current === categoryId && isInitializedRef.current) {
171
- return;
172
- }
173
- const categoryIdChanged = previousCategoryIdRef.current !== categoryId;
174
- if (categoryIdChanged || !isInitializedRef.current) {
175
- const currentMetadata = (data == null ? void 0 : data.metadata) ?? ((_a = dataRef.current) == null ? void 0 : _a.metadata) ?? {};
176
- const currentDescriptors = descriptorsRef.current.length > 0 ? descriptorsRef.current : descriptors;
177
- if (currentDescriptors.length === 0) {
178
- return;
179
- }
180
- previousCategoryIdRef.current = categoryId;
181
- setBaselineMetadata(currentMetadata);
182
- const newInitialState = buildInitialFormState(currentDescriptors, currentMetadata);
183
- setValues(newInitialState);
184
- isInitializedRef.current = true;
185
- }
186
- }, [categoryId]);
187
- const metadataStringRef = useRef("");
188
- useEffect(() => {
189
- const hasCategoryData = !!data;
190
- const descriptorsLoaded = descriptors.length > 0;
191
- const sameCategory = previousCategoryIdRef.current === categoryId;
192
- const notInitialized = !isInitializedRef.current;
193
- const currentMetadata = (data == null ? void 0 : data.metadata) ?? {};
194
- const currentMetadataString = JSON.stringify(currentMetadata);
195
- const metadataChanged = currentMetadataString !== metadataStringRef.current;
196
- if (hasCategoryData && descriptorsLoaded && sameCategory && (notInitialized || metadataChanged)) {
197
- const newInitialState = buildInitialFormState(descriptors, currentMetadata);
198
- setBaselineMetadata(currentMetadata);
199
- setValues(newInitialState);
200
- metadataStringRef.current = currentMetadataString;
201
- isInitializedRef.current = true;
202
- }
203
- }, [data, descriptors.length, categoryId]);
204
- const initialState = useMemo(
205
- () => buildInitialFormState(descriptors, baselineMetadata),
206
- [descriptors, baselineMetadata]
207
- );
208
- const [values, setValues] = useState({});
209
- const [isSaving, setIsSaving] = useState(false);
210
- const errors = useMemo(() => {
211
- return descriptors.reduce((acc, descriptor) => {
212
- const error = validateValueForDescriptor(descriptor, values[descriptor.key]);
213
- if (error) {
214
- acc[descriptor.key] = error;
215
- }
216
- return acc;
217
- }, {});
218
- }, [descriptors, values]);
219
- const hasErrors = Object.keys(errors).length > 0;
220
- const isDirty = useMemo(() => {
221
- return hasMetadataChanges({
222
- descriptors,
223
- values,
224
- originalMetadata: baselineMetadata
225
- });
226
- }, [descriptors, values, baselineMetadata]);
227
- const handleStringChange = (key, nextValue) => {
228
- setValues((prev) => ({
229
- ...prev,
230
- [key]: nextValue
231
- }));
232
- };
233
- const handleBooleanChange = (key, nextValue) => {
234
- setValues((prev) => ({
235
- ...prev,
236
- [key]: nextValue
237
- }));
238
- };
239
- const handleReset = () => {
240
- setValues(initialState);
241
- };
242
- const handleSubmit = async () => {
243
- if (!(data == null ? void 0 : data.id) || !descriptors.length) {
244
- return;
245
- }
246
- setIsSaving(true);
247
- try {
248
- const metadataPayload = buildMetadataPayload({
249
- descriptors,
250
- values,
251
- originalMetadata: baselineMetadata
252
- });
253
- const response = await fetch(`/admin/product-categories/${data.id}`, {
254
- method: "POST",
255
- credentials: "include",
256
- headers: {
257
- "Content-Type": "application/json"
258
- },
259
- body: JSON.stringify({
260
- metadata: metadataPayload
261
- })
262
- });
263
- if (!response.ok) {
264
- const payload = await response.json().catch(() => null);
265
- throw new Error((payload == null ? void 0 : payload.message) ?? "Unable to save metadata");
266
- }
267
- const updated = await response.json();
268
- const nextMetadata = updated.product_category.metadata;
269
- setBaselineMetadata(nextMetadata);
270
- setValues(buildInitialFormState(descriptors, nextMetadata));
271
- toast.success("Metadata saved");
272
- await queryClient.invalidateQueries({
273
- queryKey: ["product-categories"]
274
- });
275
- await queryClient.invalidateQueries({
276
- queryKey: ["product-category", data.id]
277
- });
278
- if (data.id) {
279
- queryClient.refetchQueries({
280
- queryKey: ["product-category", data.id]
281
- }).catch(() => {
282
- });
283
- }
284
- } catch (error) {
285
- toast.error(error instanceof Error ? error.message : "Save failed");
286
- } finally {
287
- setIsSaving(false);
288
- }
289
- };
290
- return /* @__PURE__ */ jsxs(Container, { className: "flex flex-col gap-y-4", children: [
291
- /* @__PURE__ */ jsxs("header", { className: "flex flex-col gap-y-1", children: [
292
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-3", children: [
293
- /* @__PURE__ */ jsx(Heading, { level: "h2", children: "Metadata" }),
294
- /* @__PURE__ */ jsx(Badge, { size: "2xsmall", rounded: "full", children: descriptors.length })
295
- ] }),
296
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-subtle", children: "Structured metadata mapped to the keys you configured in the plugin options." })
297
- ] }),
298
- isPending || !isInitializedRef.current || Object.keys(values).length === 0 ? /* @__PURE__ */ jsx(Skeleton, { className: "h-[160px] w-full" }) : isError ? /* @__PURE__ */ jsxs(InlineTip, { variant: "error", label: "Configuration unavailable", children: [
299
- "Unable to load metadata configuration for this plugin. Confirm that the plugin is registered with options in ",
300
- /* @__PURE__ */ jsx("code", { children: "medusa-config.ts" }),
301
- "."
302
- ] }) : !descriptors.length ? /* @__PURE__ */ jsxs(InlineTip, { variant: "info", label: "No configured metadata keys", children: [
303
- "Provide a ",
304
- /* @__PURE__ */ jsx("code", { children: "metadataDescriptors" }),
305
- " array in the plugin options to control which keys show up here.",
306
- " ",
307
- /* @__PURE__ */ jsx(
308
- "a",
309
- {
310
- className: "text-ui-fg-interactive underline",
311
- href: CONFIG_DOCS_URL$3,
312
- target: "_blank",
313
- rel: "noreferrer",
314
- children: "Learn how to configure it."
315
- }
316
- )
317
- ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
318
- /* @__PURE__ */ jsx("div", { className: "overflow-hidden rounded-lg border border-ui-border-base", children: /* @__PURE__ */ jsxs("table", { className: "min-w-full divide-y divide-ui-border-base", children: [
319
- /* @__PURE__ */ jsx("thead", { className: "bg-ui-bg-subtle", children: /* @__PURE__ */ jsxs("tr", { children: [
320
- /* @__PURE__ */ jsx(
321
- "th",
322
- {
323
- scope: "col",
324
- className: "txt-compact-xsmall-plus text-left uppercase tracking-wide text-ui-fg-muted px-4 py-3",
325
- children: "Label"
326
- }
327
- ),
328
- /* @__PURE__ */ jsx(
329
- "th",
330
- {
331
- scope: "col",
332
- className: "txt-compact-xsmall-plus text-left uppercase tracking-wide text-ui-fg-muted px-4 py-3",
333
- children: "Value"
334
- }
335
- )
336
- ] }) }),
337
- /* @__PURE__ */ jsx("tbody", { className: "divide-y divide-ui-border-subtle bg-ui-bg-base", children: descriptors.map((descriptor) => {
338
- const value = values[descriptor.key];
339
- const error = errors[descriptor.key];
340
- return /* @__PURE__ */ jsxs("tr", { children: [
341
- /* @__PURE__ */ jsx(
342
- "th",
343
- {
344
- scope: "row",
345
- className: "txt-compact-medium text-ui-fg-base align-top px-4 py-4",
346
- children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-1", children: [
347
- /* @__PURE__ */ jsx("span", { children: descriptor.label ?? descriptor.key }),
348
- /* @__PURE__ */ jsx("span", { className: "txt-compact-xsmall-plus text-ui-fg-muted uppercase tracking-wide", children: descriptor.type })
349
- ] })
350
- }
351
- ),
352
- /* @__PURE__ */ jsx("td", { className: "align-top px-4 py-4", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-2", children: [
353
- /* @__PURE__ */ jsx(
354
- ValueField$3,
355
- {
356
- descriptor,
357
- value,
358
- onStringChange: handleStringChange,
359
- onBooleanChange: handleBooleanChange
360
- }
361
- ),
362
- error && /* @__PURE__ */ jsx(Text, { className: "txt-compact-small text-ui-fg-error", children: error })
363
- ] }) })
364
- ] }, descriptor.key);
365
- }) })
366
- ] }) }),
367
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-3 border-t border-ui-border-subtle pt-3 md:flex-row md:items-center md:justify-between", children: [
368
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted", children: "Changes are stored on the category metadata object. Clearing a field removes the corresponding key on save." }),
369
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
370
- /* @__PURE__ */ jsx(
371
- Button,
372
- {
373
- variant: "secondary",
374
- size: "small",
375
- disabled: !isDirty || isSaving,
376
- onClick: handleReset,
377
- children: "Reset"
378
- }
379
- ),
380
- /* @__PURE__ */ jsx(
381
- Button,
382
- {
383
- size: "small",
384
- onClick: handleSubmit,
385
- disabled: !isDirty || hasErrors || isSaving,
386
- isLoading: isSaving,
387
- children: "Save metadata"
388
- }
389
- )
390
- ] })
391
- ] })
392
- ] })
393
- ] });
394
- };
395
- const ValueField$3 = ({
396
- descriptor,
397
- value,
398
- onStringChange,
399
- onBooleanChange
400
- }) => {
401
- const fileInputRef = useRef(null);
402
- const [isUploading, setIsUploading] = useState(false);
403
- const handleFileUpload = async (event) => {
404
- var _a;
405
- const file = (_a = event.target.files) == null ? void 0 : _a[0];
406
- if (!file) {
407
- return;
408
- }
409
- setIsUploading(true);
410
- try {
411
- const formData = new FormData();
412
- formData.append("files", file);
413
- const response = await fetch("/admin/uploads", {
414
- method: "POST",
415
- credentials: "include",
416
- body: formData
417
- });
418
- if (!response.ok) {
419
- const payload = await response.json().catch(() => null);
420
- throw new Error((payload == null ? void 0 : payload.message) ?? "File upload failed");
421
- }
422
- const result = await response.json();
423
- if (result.files && result.files.length > 0) {
424
- const uploadedFile = result.files[0];
425
- const fileUrl = uploadedFile.url || uploadedFile.key;
426
- if (fileUrl) {
427
- onStringChange(descriptor.key, fileUrl);
428
- toast.success("File uploaded successfully");
429
- } else {
430
- throw new Error("File upload succeeded but no URL returned");
431
- }
432
- } else {
433
- throw new Error("File upload failed - no files returned");
434
- }
435
- } catch (error) {
436
- toast.error(
437
- error instanceof Error ? error.message : "Failed to upload file"
438
- );
439
- } finally {
440
- setIsUploading(false);
441
- if (fileInputRef.current) {
442
- fileInputRef.current.value = "";
443
- }
444
- }
445
- };
446
- if (descriptor.type === "bool") {
447
- return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
448
- /* @__PURE__ */ jsx(
449
- Switch,
450
- {
451
- checked: Boolean(value),
452
- onCheckedChange: (checked) => onBooleanChange(descriptor.key, Boolean(checked)),
453
- "aria-label": `Toggle ${descriptor.label ?? descriptor.key}`
454
- }
455
- ),
456
- /* @__PURE__ */ jsx(Text, { className: "txt-compact-small text-ui-fg-muted", children: Boolean(value) ? "True" : "False" })
457
- ] });
458
- }
459
- if (descriptor.type === "text") {
460
- return /* @__PURE__ */ jsx(
461
- Textarea,
462
- {
463
- value: value ?? "",
464
- placeholder: "Enter text",
465
- rows: 3,
466
- onChange: (event) => onStringChange(descriptor.key, event.target.value)
467
- }
468
- );
469
- }
470
- if (descriptor.type === "number") {
471
- return /* @__PURE__ */ jsx(
472
- Input,
473
- {
474
- type: "text",
475
- inputMode: "decimal",
476
- placeholder: "0.00",
477
- value: value ?? "",
478
- onChange: (event) => onStringChange(descriptor.key, event.target.value)
479
- }
480
- );
481
- }
482
- return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-2", children: [
483
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
484
- /* @__PURE__ */ jsx(
485
- Input,
486
- {
487
- type: "url",
488
- placeholder: "https://example.com/file",
489
- value: value ?? "",
490
- onChange: (event) => onStringChange(descriptor.key, event.target.value),
491
- className: "flex-1"
492
- }
493
- ),
494
- /* @__PURE__ */ jsx(
495
- "input",
496
- {
497
- ref: fileInputRef,
498
- type: "file",
499
- className: "hidden",
500
- onChange: handleFileUpload,
501
- disabled: isUploading,
502
- "aria-label": `Upload file for ${descriptor.label ?? descriptor.key}`
503
- }
504
- ),
505
- /* @__PURE__ */ jsx(
506
- Button,
507
- {
508
- type: "button",
509
- variant: "secondary",
510
- size: "small",
511
- onClick: () => {
512
- var _a;
513
- return (_a = fileInputRef.current) == null ? void 0 : _a.click();
514
- },
515
- disabled: isUploading,
516
- isLoading: isUploading,
517
- children: isUploading ? "Uploading..." : "Upload"
518
- }
519
- )
520
- ] }),
521
- typeof value === "string" && value && /* @__PURE__ */ jsx(
522
- "a",
523
- {
524
- className: "txt-compact-small-plus text-ui-fg-interactive underline",
525
- href: value,
526
- target: "_blank",
527
- rel: "noreferrer",
528
- children: "View file"
529
- }
530
- )
531
- ] });
532
- };
533
- defineWidgetConfig({
534
- zone: "product_category.details.after"
535
- });
536
- const CONFIG_DOCS_URL$2 = "https://docs.medusajs.com/admin/extension-points/widgets#product-collection-details";
537
- const CollectionMetadataTableWidget = ({ data }) => {
538
- const { data: descriptors = [], isPending, isError } = useCollectionMetadataConfig();
539
- const collectionId = (data == null ? void 0 : data.id) ?? void 0;
540
- const [baselineMetadata, setBaselineMetadata] = useState(
541
- (data == null ? void 0 : data.metadata) ?? {}
542
- );
543
- const queryClient = useQueryClient();
544
- const previousCollectionIdRef = useRef(collectionId);
545
- const isInitializedRef = useRef(false);
546
- const dataRef = useRef(data);
547
- const descriptorsRef = useRef(descriptors);
548
- useEffect(() => {
549
- dataRef.current = data;
550
- descriptorsRef.current = descriptors;
551
- }, [data, descriptors]);
552
- useEffect(() => {
553
- var _a;
554
- if (previousCollectionIdRef.current === collectionId && isInitializedRef.current) {
555
- return;
556
- }
557
- const collectionIdChanged = previousCollectionIdRef.current !== collectionId;
558
- if (collectionIdChanged || !isInitializedRef.current) {
559
- const currentMetadata = (data == null ? void 0 : data.metadata) ?? ((_a = dataRef.current) == null ? void 0 : _a.metadata) ?? {};
560
- const currentDescriptors = descriptorsRef.current.length > 0 ? descriptorsRef.current : descriptors;
561
- if (currentDescriptors.length === 0) {
562
- return;
563
- }
564
- previousCollectionIdRef.current = collectionId;
565
- setBaselineMetadata(currentMetadata);
566
- const newInitialState = buildInitialFormState(currentDescriptors, currentMetadata);
567
- setValues(newInitialState);
568
- isInitializedRef.current = true;
569
- }
570
- }, [collectionId]);
571
- const metadataStringRef = useRef("");
572
- useEffect(() => {
573
- const hasCollectionData = !!data;
574
- const descriptorsLoaded = descriptors.length > 0;
575
- const sameCollection = previousCollectionIdRef.current === collectionId;
576
- const notInitialized = !isInitializedRef.current;
577
- const currentMetadata = (data == null ? void 0 : data.metadata) ?? {};
578
- const currentMetadataString = JSON.stringify(currentMetadata);
579
- const metadataChanged = currentMetadataString !== metadataStringRef.current;
580
- if (hasCollectionData && descriptorsLoaded && sameCollection && (notInitialized || metadataChanged)) {
581
- const newInitialState = buildInitialFormState(descriptors, currentMetadata);
582
- setBaselineMetadata(currentMetadata);
583
- setValues(newInitialState);
584
- metadataStringRef.current = currentMetadataString;
585
- isInitializedRef.current = true;
586
- }
587
- }, [data, descriptors.length, collectionId]);
588
- const initialState = useMemo(
589
- () => buildInitialFormState(descriptors, baselineMetadata),
590
- [descriptors, baselineMetadata]
591
- );
592
- const [values, setValues] = useState({});
593
- const [isSaving, setIsSaving] = useState(false);
594
- const errors = useMemo(() => {
595
- return descriptors.reduce((acc, descriptor) => {
596
- const error = validateValueForDescriptor(descriptor, values[descriptor.key]);
597
- if (error) {
598
- acc[descriptor.key] = error;
599
- }
600
- return acc;
601
- }, {});
602
- }, [descriptors, values]);
603
- const hasErrors = Object.keys(errors).length > 0;
604
- const isDirty = useMemo(() => {
605
- return hasMetadataChanges({
606
- descriptors,
607
- values,
608
- originalMetadata: baselineMetadata
609
- });
610
- }, [descriptors, values, baselineMetadata]);
611
- const handleStringChange = (key, nextValue) => {
612
- setValues((prev) => ({
613
- ...prev,
614
- [key]: nextValue
615
- }));
616
- };
617
- const handleBooleanChange = (key, nextValue) => {
618
- setValues((prev) => ({
619
- ...prev,
620
- [key]: nextValue
621
- }));
622
- };
623
- const handleReset = () => {
624
- setValues(initialState);
625
- };
626
- const handleSubmit = async () => {
627
- if (!(data == null ? void 0 : data.id) || !descriptors.length) {
628
- return;
629
- }
630
- setIsSaving(true);
631
- try {
632
- const metadataPayload = buildMetadataPayload({
633
- descriptors,
634
- values,
635
- originalMetadata: baselineMetadata
636
- });
637
- const response = await fetch(`/admin/collections/${data.id}`, {
638
- method: "POST",
639
- credentials: "include",
640
- headers: {
641
- "Content-Type": "application/json"
642
- },
643
- body: JSON.stringify({
644
- metadata: metadataPayload
645
- })
646
- });
647
- if (!response.ok) {
648
- const payload = await response.json().catch(() => null);
649
- throw new Error((payload == null ? void 0 : payload.message) ?? "Unable to save metadata");
650
- }
651
- const updated = await response.json();
652
- const nextMetadata = updated.product_collection.metadata;
653
- setBaselineMetadata(nextMetadata);
654
- setValues(buildInitialFormState(descriptors, nextMetadata));
655
- toast.success("Metadata saved");
656
- await queryClient.invalidateQueries({
657
- queryKey: ["collections"]
658
- });
659
- await queryClient.invalidateQueries({
660
- queryKey: ["collection", data.id]
661
- });
662
- if (data.id) {
663
- queryClient.refetchQueries({
664
- queryKey: ["collection", data.id]
665
- }).catch(() => {
666
- });
667
- }
668
- } catch (error) {
669
- toast.error(error instanceof Error ? error.message : "Save failed");
670
- } finally {
671
- setIsSaving(false);
672
- }
673
- };
674
- return /* @__PURE__ */ jsxs(Container, { className: "flex flex-col gap-y-4", children: [
675
- /* @__PURE__ */ jsxs("header", { className: "flex flex-col gap-y-1", children: [
676
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-3", children: [
677
- /* @__PURE__ */ jsx(Heading, { level: "h2", children: "Metadata" }),
678
- /* @__PURE__ */ jsx(Badge, { size: "2xsmall", rounded: "full", children: descriptors.length })
679
- ] }),
680
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-subtle", children: "Structured metadata mapped to the keys you configured in the plugin options." })
681
- ] }),
682
- isPending || !isInitializedRef.current || Object.keys(values).length === 0 ? /* @__PURE__ */ jsx(Skeleton, { className: "h-[160px] w-full" }) : isError ? /* @__PURE__ */ jsxs(InlineTip, { variant: "error", label: "Configuration unavailable", children: [
683
- "Unable to load metadata configuration for this plugin. Confirm that the plugin is registered with options in ",
684
- /* @__PURE__ */ jsx("code", { children: "medusa-config.ts" }),
685
- "."
686
- ] }) : !descriptors.length ? /* @__PURE__ */ jsxs(InlineTip, { variant: "info", label: "No configured metadata keys", children: [
687
- "Provide a ",
688
- /* @__PURE__ */ jsx("code", { children: "metadataDescriptors" }),
689
- " array in the plugin options to control which keys show up here.",
690
- " ",
691
- /* @__PURE__ */ jsx(
692
- "a",
693
- {
694
- className: "text-ui-fg-interactive underline",
695
- href: CONFIG_DOCS_URL$2,
696
- target: "_blank",
697
- rel: "noreferrer",
698
- children: "Learn how to configure it."
699
- }
700
- )
701
- ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
702
- /* @__PURE__ */ jsx("div", { className: "overflow-hidden rounded-lg border border-ui-border-base", children: /* @__PURE__ */ jsxs("table", { className: "min-w-full divide-y divide-ui-border-base", children: [
703
- /* @__PURE__ */ jsx("thead", { className: "bg-ui-bg-subtle", children: /* @__PURE__ */ jsxs("tr", { children: [
704
- /* @__PURE__ */ jsx(
705
- "th",
706
- {
707
- scope: "col",
708
- className: "txt-compact-xsmall-plus text-left uppercase tracking-wide text-ui-fg-muted px-4 py-3",
709
- children: "Label"
710
- }
711
- ),
712
- /* @__PURE__ */ jsx(
713
- "th",
714
- {
715
- scope: "col",
716
- className: "txt-compact-xsmall-plus text-left uppercase tracking-wide text-ui-fg-muted px-4 py-3",
717
- children: "Value"
718
- }
719
- )
720
- ] }) }),
721
- /* @__PURE__ */ jsx("tbody", { className: "divide-y divide-ui-border-subtle bg-ui-bg-base", children: descriptors.map((descriptor) => {
722
- const value = values[descriptor.key];
723
- const error = errors[descriptor.key];
724
- return /* @__PURE__ */ jsxs("tr", { children: [
725
- /* @__PURE__ */ jsx(
726
- "th",
727
- {
728
- scope: "row",
729
- className: "txt-compact-medium text-ui-fg-base align-top px-4 py-4",
730
- children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-1", children: [
731
- /* @__PURE__ */ jsx("span", { children: descriptor.label ?? descriptor.key }),
732
- /* @__PURE__ */ jsx("span", { className: "txt-compact-xsmall-plus text-ui-fg-muted uppercase tracking-wide", children: descriptor.type })
733
- ] })
734
- }
735
- ),
736
- /* @__PURE__ */ jsx("td", { className: "align-top px-4 py-4", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-2", children: [
737
- /* @__PURE__ */ jsx(
738
- ValueField$2,
739
- {
740
- descriptor,
741
- value,
742
- onStringChange: handleStringChange,
743
- onBooleanChange: handleBooleanChange
744
- }
745
- ),
746
- error && /* @__PURE__ */ jsx(Text, { className: "txt-compact-small text-ui-fg-error", children: error })
747
- ] }) })
748
- ] }, descriptor.key);
749
- }) })
750
- ] }) }),
751
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-3 border-t border-ui-border-subtle pt-3 md:flex-row md:items-center md:justify-between", children: [
752
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted", children: "Changes are stored on the collection metadata object. Clearing a field removes the corresponding key on save." }),
753
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
754
- /* @__PURE__ */ jsx(
755
- Button,
756
- {
757
- variant: "secondary",
758
- size: "small",
759
- disabled: !isDirty || isSaving,
760
- onClick: handleReset,
761
- children: "Reset"
762
- }
763
- ),
764
- /* @__PURE__ */ jsx(
765
- Button,
766
- {
767
- size: "small",
768
- onClick: handleSubmit,
769
- disabled: !isDirty || hasErrors || isSaving,
770
- isLoading: isSaving,
771
- children: "Save metadata"
772
- }
773
- )
774
- ] })
775
- ] })
776
- ] })
777
- ] });
778
- };
779
- const ValueField$2 = ({
780
- descriptor,
781
- value,
782
- onStringChange,
783
- onBooleanChange
784
- }) => {
785
- const fileInputRef = useRef(null);
786
- const [isUploading, setIsUploading] = useState(false);
787
- const handleFileUpload = async (event) => {
788
- var _a;
789
- const file = (_a = event.target.files) == null ? void 0 : _a[0];
790
- if (!file) {
791
- return;
792
- }
793
- setIsUploading(true);
794
- try {
795
- const formData = new FormData();
796
- formData.append("files", file);
797
- const response = await fetch("/admin/uploads", {
798
- method: "POST",
799
- credentials: "include",
800
- body: formData
801
- });
802
- if (!response.ok) {
803
- const payload = await response.json().catch(() => null);
804
- throw new Error((payload == null ? void 0 : payload.message) ?? "File upload failed");
805
- }
806
- const result = await response.json();
807
- if (result.files && result.files.length > 0) {
808
- const uploadedFile = result.files[0];
809
- const fileUrl = uploadedFile.url || uploadedFile.key;
810
- if (fileUrl) {
811
- onStringChange(descriptor.key, fileUrl);
812
- toast.success("File uploaded successfully");
813
- } else {
814
- throw new Error("File upload succeeded but no URL returned");
815
- }
816
- } else {
817
- throw new Error("File upload failed - no files returned");
818
- }
819
- } catch (error) {
820
- toast.error(
821
- error instanceof Error ? error.message : "Failed to upload file"
822
- );
823
- } finally {
824
- setIsUploading(false);
825
- if (fileInputRef.current) {
826
- fileInputRef.current.value = "";
827
- }
828
- }
829
- };
830
- if (descriptor.type === "bool") {
831
- return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
832
- /* @__PURE__ */ jsx(
833
- Switch,
834
- {
835
- checked: Boolean(value),
836
- onCheckedChange: (checked) => onBooleanChange(descriptor.key, Boolean(checked)),
837
- "aria-label": `Toggle ${descriptor.label ?? descriptor.key}`
838
- }
839
- ),
840
- /* @__PURE__ */ jsx(Text, { className: "txt-compact-small text-ui-fg-muted", children: Boolean(value) ? "True" : "False" })
841
- ] });
842
- }
843
- if (descriptor.type === "text") {
844
- return /* @__PURE__ */ jsx(
845
- Textarea,
846
- {
847
- value: value ?? "",
848
- placeholder: "Enter text",
849
- rows: 3,
850
- onChange: (event) => onStringChange(descriptor.key, event.target.value)
851
- }
852
- );
853
- }
854
- if (descriptor.type === "number") {
855
- return /* @__PURE__ */ jsx(
856
- Input,
857
- {
858
- type: "text",
859
- inputMode: "decimal",
860
- placeholder: "0.00",
861
- value: value ?? "",
862
- onChange: (event) => onStringChange(descriptor.key, event.target.value)
863
- }
864
- );
865
- }
866
- return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-2", children: [
867
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
868
- /* @__PURE__ */ jsx(
869
- Input,
870
- {
871
- type: "url",
872
- placeholder: "https://example.com/file",
873
- value: value ?? "",
874
- onChange: (event) => onStringChange(descriptor.key, event.target.value),
875
- className: "flex-1"
876
- }
877
- ),
878
- /* @__PURE__ */ jsx(
879
- "input",
880
- {
881
- ref: fileInputRef,
882
- type: "file",
883
- className: "hidden",
884
- onChange: handleFileUpload,
885
- disabled: isUploading,
886
- "aria-label": `Upload file for ${descriptor.label ?? descriptor.key}`
887
- }
888
- ),
889
- /* @__PURE__ */ jsx(
890
- Button,
891
- {
892
- type: "button",
893
- variant: "secondary",
894
- size: "small",
895
- onClick: () => {
896
- var _a;
897
- return (_a = fileInputRef.current) == null ? void 0 : _a.click();
898
- },
899
- disabled: isUploading,
900
- isLoading: isUploading,
901
- children: isUploading ? "Uploading..." : "Upload"
902
- }
903
- )
904
- ] }),
905
- typeof value === "string" && value && /* @__PURE__ */ jsx(
906
- "a",
907
- {
908
- className: "txt-compact-small-plus text-ui-fg-interactive underline",
909
- href: value,
910
- target: "_blank",
911
- rel: "noreferrer",
912
- children: "View file"
913
- }
914
- )
915
- ] });
916
- };
917
- defineWidgetConfig({
918
- zone: "product_collection.details.after"
919
- });
920
- const HideCategoryDefaultMetadataWidget = () => {
921
- useEffect(() => {
922
- const hideMetadataSection = () => {
923
- const headings = document.querySelectorAll("h2");
924
- headings.forEach((heading) => {
925
- var _a;
926
- if (((_a = heading.textContent) == null ? void 0 : _a.trim()) === "Metadata") {
927
- let container = heading.parentElement;
928
- while (container && container !== document.body) {
929
- const hasContainerClass = container.classList.toString().includes("Container");
930
- const isInSidebar = container.closest('[class*="Sidebar"]') || container.closest('[class*="sidebar"]');
931
- if (hasContainerClass || isInSidebar) {
932
- const editLink = container.querySelector('a[href*="metadata/edit"]');
933
- const badge = container.querySelector('div[class*="Badge"]');
934
- if (editLink && badge) {
935
- container.style.display = "none";
936
- container.setAttribute("data-category-metadata-hidden", "true");
937
- return;
938
- }
939
- }
940
- container = container.parentElement;
941
- }
942
- }
943
- });
944
- };
945
- const runHide = () => {
946
- setTimeout(hideMetadataSection, 100);
947
- };
948
- runHide();
949
- const observer = new MutationObserver(() => {
950
- const alreadyHidden = document.querySelector(
951
- '[data-category-metadata-hidden="true"]'
952
- );
953
- if (!alreadyHidden) {
954
- runHide();
955
- }
956
- });
957
- observer.observe(document.body, {
958
- childList: true,
959
- subtree: true
960
- });
961
- return () => {
962
- observer.disconnect();
963
- const hidden = document.querySelector(
964
- '[data-category-metadata-hidden="true"]'
965
- );
966
- if (hidden) {
967
- hidden.style.display = "";
968
- hidden.removeAttribute("data-category-metadata-hidden");
969
- }
970
- };
971
- }, []);
972
- return null;
973
- };
974
- defineWidgetConfig({
975
- zone: "product_category.details.side.before"
976
- });
977
- const HideDefaultMetadataWidget = () => {
978
- useEffect(() => {
979
- const hideMetadataSection = () => {
980
- const headings = document.querySelectorAll("h2");
981
- headings.forEach((heading) => {
982
- var _a;
983
- if (((_a = heading.textContent) == null ? void 0 : _a.trim()) === "Metadata") {
984
- let container = heading.parentElement;
985
- while (container && container !== document.body) {
986
- const hasContainerClass = container.classList.toString().includes("Container");
987
- const isInSidebar = container.closest('[class*="Sidebar"]') || container.closest('[class*="sidebar"]');
988
- if (hasContainerClass || isInSidebar) {
989
- const editLink = container.querySelector('a[href*="metadata/edit"]');
990
- const badge = container.querySelector('div[class*="Badge"]');
991
- if (editLink && badge) {
992
- container.style.display = "none";
993
- container.setAttribute("data-metadata-hidden", "true");
994
- return;
995
- }
996
- }
997
- container = container.parentElement;
998
- }
999
- }
1000
- });
1001
- };
1002
- const runHide = () => {
1003
- setTimeout(hideMetadataSection, 100);
1004
- };
1005
- runHide();
1006
- const observer = new MutationObserver(() => {
1007
- const alreadyHidden = document.querySelector('[data-metadata-hidden="true"]');
1008
- if (!alreadyHidden) {
1009
- runHide();
1010
- }
1011
- });
1012
- observer.observe(document.body, {
1013
- childList: true,
1014
- subtree: true
1015
- });
1016
- return () => {
1017
- observer.disconnect();
1018
- const hidden = document.querySelector('[data-metadata-hidden="true"]');
1019
- if (hidden) {
1020
- hidden.style.display = "";
1021
- hidden.removeAttribute("data-metadata-hidden");
1022
- }
1023
- };
1024
- }, []);
1025
- return null;
1026
- };
1027
- defineWidgetConfig({
1028
- zone: "product.details.side.before"
1029
- });
1030
- const CONFIG_DOCS_URL$1 = "https://docs.medusajs.com/admin/extension-points/widgets#order-details";
1031
- const OrderMetadataTableWidget = ({ data }) => {
1032
- const { data: descriptors = [], isPending, isError } = useOrderMetadataConfig();
1033
- const orderId = (data == null ? void 0 : data.id) ?? void 0;
1034
- const [baselineMetadata, setBaselineMetadata] = useState(
1035
- (data == null ? void 0 : data.metadata) ?? {}
1036
- );
1037
- const queryClient = useQueryClient();
1038
- const previousOrderIdRef = useRef(orderId);
1039
- const isInitializedRef = useRef(false);
1040
- const dataRef = useRef(data);
1041
- const descriptorsRef = useRef(descriptors);
1042
- useEffect(() => {
1043
- dataRef.current = data;
1044
- descriptorsRef.current = descriptors;
1045
- }, [data, descriptors]);
1046
- useEffect(() => {
1047
- var _a;
1048
- if (previousOrderIdRef.current === orderId && isInitializedRef.current) {
1049
- return;
1050
- }
1051
- const orderIdChanged = previousOrderIdRef.current !== orderId;
1052
- if (orderIdChanged || !isInitializedRef.current) {
1053
- const currentMetadata = (data == null ? void 0 : data.metadata) ?? ((_a = dataRef.current) == null ? void 0 : _a.metadata) ?? {};
1054
- const currentDescriptors = descriptorsRef.current.length > 0 ? descriptorsRef.current : descriptors;
1055
- if (currentDescriptors.length === 0) {
1056
- return;
1057
- }
1058
- previousOrderIdRef.current = orderId;
1059
- setBaselineMetadata(currentMetadata);
1060
- const newInitialState = buildInitialFormState(currentDescriptors, currentMetadata);
1061
- setValues(newInitialState);
1062
- isInitializedRef.current = true;
1063
- }
1064
- }, [orderId]);
1065
- const metadataStringRef = useRef("");
1066
- useEffect(() => {
1067
- const hasOrderData = !!data;
1068
- const descriptorsLoaded = descriptors.length > 0;
1069
- const sameOrder = previousOrderIdRef.current === orderId;
1070
- const notInitialized = !isInitializedRef.current;
1071
- const currentMetadata = (data == null ? void 0 : data.metadata) ?? {};
1072
- const currentMetadataString = JSON.stringify(currentMetadata);
1073
- const metadataChanged = currentMetadataString !== metadataStringRef.current;
1074
- if (hasOrderData && descriptorsLoaded && sameOrder && (notInitialized || metadataChanged)) {
1075
- const newInitialState = buildInitialFormState(descriptors, currentMetadata);
1076
- setBaselineMetadata(currentMetadata);
1077
- setValues(newInitialState);
1078
- metadataStringRef.current = currentMetadataString;
1079
- isInitializedRef.current = true;
1080
- }
1081
- }, [data, descriptors.length, orderId]);
1082
- const initialState = useMemo(
1083
- () => buildInitialFormState(descriptors, baselineMetadata),
1084
- [descriptors, baselineMetadata]
1085
- );
1086
- const [values, setValues] = useState({});
1087
- const [isSaving, setIsSaving] = useState(false);
1088
- const errors = useMemo(() => {
1089
- return descriptors.reduce((acc, descriptor) => {
1090
- const error = validateValueForDescriptor(descriptor, values[descriptor.key]);
1091
- if (error) {
1092
- acc[descriptor.key] = error;
1093
- }
1094
- return acc;
1095
- }, {});
1096
- }, [descriptors, values]);
1097
- const hasErrors = Object.keys(errors).length > 0;
1098
- const isDirty = useMemo(() => {
1099
- return hasMetadataChanges({
1100
- descriptors,
1101
- values,
1102
- originalMetadata: baselineMetadata
1103
- });
1104
- }, [descriptors, values, baselineMetadata]);
1105
- const handleStringChange = (key, nextValue) => {
1106
- setValues((prev) => ({
1107
- ...prev,
1108
- [key]: nextValue
1109
- }));
1110
- };
1111
- const handleBooleanChange = (key, nextValue) => {
1112
- setValues((prev) => ({
1113
- ...prev,
1114
- [key]: nextValue
1115
- }));
1116
- };
1117
- const handleReset = () => {
1118
- setValues(initialState);
1119
- };
1120
- const handleSubmit = async () => {
1121
- if (!(data == null ? void 0 : data.id) || !descriptors.length) {
1122
- return;
1123
- }
1124
- setIsSaving(true);
1125
- try {
1126
- const metadataPayload = buildMetadataPayload({
1127
- descriptors,
1128
- values,
1129
- originalMetadata: baselineMetadata
1130
- });
1131
- const response = await fetch(`/admin/orders/${data.id}`, {
1132
- method: "POST",
1133
- credentials: "include",
1134
- headers: {
1135
- "Content-Type": "application/json"
1136
- },
1137
- body: JSON.stringify({
1138
- metadata: metadataPayload
1139
- })
1140
- });
1141
- if (!response.ok) {
1142
- const payload = await response.json().catch(() => null);
1143
- throw new Error((payload == null ? void 0 : payload.message) ?? "Unable to save metadata");
1144
- }
1145
- const updated = await response.json();
1146
- const nextMetadata = updated.order.metadata;
1147
- setBaselineMetadata(nextMetadata);
1148
- setValues(buildInitialFormState(descriptors, nextMetadata));
1149
- toast.success("Metadata saved");
1150
- await queryClient.invalidateQueries({
1151
- queryKey: ["orders"]
1152
- });
1153
- await queryClient.invalidateQueries({
1154
- queryKey: ["order", data.id]
1155
- });
1156
- if (data.id) {
1157
- queryClient.refetchQueries({
1158
- queryKey: ["order", data.id]
1159
- }).catch(() => {
1160
- });
1161
- }
1162
- } catch (error) {
1163
- toast.error(error instanceof Error ? error.message : "Save failed");
1164
- } finally {
1165
- setIsSaving(false);
1166
- }
1167
- };
1168
- return /* @__PURE__ */ jsxs(Container, { className: "flex flex-col gap-y-4", children: [
1169
- /* @__PURE__ */ jsxs("header", { className: "flex flex-col gap-y-1", children: [
1170
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-3", children: [
1171
- /* @__PURE__ */ jsx(Heading, { level: "h2", children: "Metadata" }),
1172
- /* @__PURE__ */ jsx(Badge, { size: "2xsmall", rounded: "full", children: descriptors.length })
1173
- ] }),
1174
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-subtle", children: "Structured metadata mapped to the keys you configured in the plugin options." })
1175
- ] }),
1176
- isPending || !isInitializedRef.current || Object.keys(values).length === 0 ? /* @__PURE__ */ jsx(Skeleton, { className: "h-[160px] w-full" }) : isError ? /* @__PURE__ */ jsxs(InlineTip, { variant: "error", label: "Configuration unavailable", children: [
1177
- "Unable to load metadata configuration for this plugin. Confirm that the plugin is registered with options in ",
1178
- /* @__PURE__ */ jsx("code", { children: "medusa-config.ts" }),
1179
- "."
1180
- ] }) : !descriptors.length ? /* @__PURE__ */ jsxs(InlineTip, { variant: "info", label: "No configured metadata keys", children: [
1181
- "Provide a ",
1182
- /* @__PURE__ */ jsx("code", { children: "metadataDescriptors" }),
1183
- " array in the plugin options to control which keys show up here.",
1184
- " ",
1185
- /* @__PURE__ */ jsx(
1186
- "a",
1187
- {
1188
- className: "text-ui-fg-interactive underline",
1189
- href: CONFIG_DOCS_URL$1,
1190
- target: "_blank",
1191
- rel: "noreferrer",
1192
- children: "Learn how to configure it."
1193
- }
1194
- )
1195
- ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1196
- /* @__PURE__ */ jsx("div", { className: "overflow-hidden rounded-lg border border-ui-border-base", children: /* @__PURE__ */ jsxs("table", { className: "min-w-full divide-y divide-ui-border-base", children: [
1197
- /* @__PURE__ */ jsx("thead", { className: "bg-ui-bg-subtle", children: /* @__PURE__ */ jsxs("tr", { children: [
1198
- /* @__PURE__ */ jsx(
1199
- "th",
1200
- {
1201
- scope: "col",
1202
- className: "txt-compact-xsmall-plus text-left uppercase tracking-wide text-ui-fg-muted px-4 py-3",
1203
- children: "Label"
1204
- }
1205
- ),
1206
- /* @__PURE__ */ jsx(
1207
- "th",
1208
- {
1209
- scope: "col",
1210
- className: "txt-compact-xsmall-plus text-left uppercase tracking-wide text-ui-fg-muted px-4 py-3",
1211
- children: "Value"
1212
- }
1213
- )
1214
- ] }) }),
1215
- /* @__PURE__ */ jsx("tbody", { className: "divide-y divide-ui-border-subtle bg-ui-bg-base", children: descriptors.map((descriptor) => {
1216
- const value = values[descriptor.key];
1217
- const error = errors[descriptor.key];
1218
- return /* @__PURE__ */ jsxs("tr", { children: [
1219
- /* @__PURE__ */ jsx(
1220
- "th",
1221
- {
1222
- scope: "row",
1223
- className: "txt-compact-medium text-ui-fg-base align-top px-4 py-4",
1224
- children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-1", children: [
1225
- /* @__PURE__ */ jsx("span", { children: descriptor.label ?? descriptor.key }),
1226
- /* @__PURE__ */ jsx("span", { className: "txt-compact-xsmall-plus text-ui-fg-muted uppercase tracking-wide", children: descriptor.type })
1227
- ] })
1228
- }
1229
- ),
1230
- /* @__PURE__ */ jsx("td", { className: "align-top px-4 py-4", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-2", children: [
1231
- /* @__PURE__ */ jsx(
1232
- ValueField$1,
1233
- {
1234
- descriptor,
1235
- value,
1236
- onStringChange: handleStringChange,
1237
- onBooleanChange: handleBooleanChange
1238
- }
1239
- ),
1240
- error && /* @__PURE__ */ jsx(Text, { className: "txt-compact-small text-ui-fg-error", children: error })
1241
- ] }) })
1242
- ] }, descriptor.key);
1243
- }) })
1244
- ] }) }),
1245
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-3 border-t border-ui-border-subtle pt-3 md:flex-row md:items-center md:justify-between", children: [
1246
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted", children: "Changes are stored on the order metadata object. Clearing a field removes the corresponding key on save." }),
1247
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
1248
- /* @__PURE__ */ jsx(
1249
- Button,
1250
- {
1251
- variant: "secondary",
1252
- size: "small",
1253
- disabled: !isDirty || isSaving,
1254
- onClick: handleReset,
1255
- children: "Reset"
1256
- }
1257
- ),
1258
- /* @__PURE__ */ jsx(
1259
- Button,
1260
- {
1261
- size: "small",
1262
- onClick: handleSubmit,
1263
- disabled: !isDirty || hasErrors || isSaving,
1264
- isLoading: isSaving,
1265
- children: "Save metadata"
1266
- }
1267
- )
1268
- ] })
1269
- ] })
1270
- ] })
1271
- ] });
1272
- };
1273
- const ValueField$1 = ({
1274
- descriptor,
1275
- value,
1276
- onStringChange,
1277
- onBooleanChange
1278
- }) => {
1279
- const fileInputRef = useRef(null);
1280
- const [isUploading, setIsUploading] = useState(false);
1281
- const handleFileUpload = async (event) => {
1282
- var _a;
1283
- const file = (_a = event.target.files) == null ? void 0 : _a[0];
1284
- if (!file) {
1285
- return;
1286
- }
1287
- setIsUploading(true);
1288
- try {
1289
- const formData = new FormData();
1290
- formData.append("files", file);
1291
- const response = await fetch("/admin/uploads", {
1292
- method: "POST",
1293
- credentials: "include",
1294
- body: formData
1295
- });
1296
- if (!response.ok) {
1297
- const payload = await response.json().catch(() => null);
1298
- throw new Error((payload == null ? void 0 : payload.message) ?? "File upload failed");
1299
- }
1300
- const result = await response.json();
1301
- if (result.files && result.files.length > 0) {
1302
- const uploadedFile = result.files[0];
1303
- const fileUrl = uploadedFile.url || uploadedFile.key;
1304
- if (fileUrl) {
1305
- onStringChange(descriptor.key, fileUrl);
1306
- toast.success("File uploaded successfully");
1307
- } else {
1308
- throw new Error("File upload succeeded but no URL returned");
1309
- }
1310
- } else {
1311
- throw new Error("File upload failed - no files returned");
1312
- }
1313
- } catch (error) {
1314
- toast.error(
1315
- error instanceof Error ? error.message : "Failed to upload file"
1316
- );
1317
- } finally {
1318
- setIsUploading(false);
1319
- if (fileInputRef.current) {
1320
- fileInputRef.current.value = "";
1321
- }
1322
- }
1323
- };
1324
- if (descriptor.type === "bool") {
1325
- return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
1326
- /* @__PURE__ */ jsx(
1327
- Switch,
1328
- {
1329
- checked: Boolean(value),
1330
- onCheckedChange: (checked) => onBooleanChange(descriptor.key, Boolean(checked)),
1331
- "aria-label": `Toggle ${descriptor.label ?? descriptor.key}`
1332
- }
1333
- ),
1334
- /* @__PURE__ */ jsx(Text, { className: "txt-compact-small text-ui-fg-muted", children: Boolean(value) ? "True" : "False" })
1335
- ] });
1336
- }
1337
- if (descriptor.type === "text") {
1338
- return /* @__PURE__ */ jsx(
1339
- Textarea,
1340
- {
1341
- value: value ?? "",
1342
- placeholder: "Enter text",
1343
- rows: 3,
1344
- onChange: (event) => onStringChange(descriptor.key, event.target.value)
1345
- }
1346
- );
1347
- }
1348
- if (descriptor.type === "number") {
1349
- return /* @__PURE__ */ jsx(
1350
- Input,
1351
- {
1352
- type: "text",
1353
- inputMode: "decimal",
1354
- placeholder: "0.00",
1355
- value: value ?? "",
1356
- onChange: (event) => onStringChange(descriptor.key, event.target.value)
1357
- }
1358
- );
1359
- }
1360
- return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-2", children: [
1361
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
1362
- /* @__PURE__ */ jsx(
1363
- Input,
1364
- {
1365
- type: "url",
1366
- placeholder: "https://example.com/file",
1367
- value: value ?? "",
1368
- onChange: (event) => onStringChange(descriptor.key, event.target.value),
1369
- className: "flex-1"
1370
- }
1371
- ),
1372
- /* @__PURE__ */ jsx(
1373
- "input",
1374
- {
1375
- ref: fileInputRef,
1376
- type: "file",
1377
- className: "hidden",
1378
- onChange: handleFileUpload,
1379
- disabled: isUploading,
1380
- "aria-label": `Upload file for ${descriptor.label ?? descriptor.key}`
1381
- }
1382
- ),
1383
- /* @__PURE__ */ jsx(
1384
- Button,
1385
- {
1386
- type: "button",
1387
- variant: "secondary",
1388
- size: "small",
1389
- onClick: () => {
1390
- var _a;
1391
- return (_a = fileInputRef.current) == null ? void 0 : _a.click();
1392
- },
1393
- disabled: isUploading,
1394
- isLoading: isUploading,
1395
- children: isUploading ? "Uploading..." : "Upload"
1396
- }
1397
- )
1398
- ] }),
1399
- typeof value === "string" && value && /* @__PURE__ */ jsx(
1400
- "a",
1401
- {
1402
- className: "txt-compact-small-plus text-ui-fg-interactive underline",
1403
- href: value,
1404
- target: "_blank",
1405
- rel: "noreferrer",
1406
- children: "View file"
1407
- }
1408
- )
1409
- ] });
1410
- };
1411
- defineWidgetConfig({
1412
- zone: "order.details.after"
1413
- });
1414
- const CONFIG_DOCS_URL = "https://docs.medusajs.com/admin/extension-points/widgets#product-details";
1415
- const ProductMetadataTableWidget = ({ data }) => {
1416
- const { data: descriptors = [], isPending, isError } = useProductMetadataConfig();
1417
- const productId = (data == null ? void 0 : data.id) ?? void 0;
1418
- const [baselineMetadata, setBaselineMetadata] = useState(
1419
- (data == null ? void 0 : data.metadata) ?? {}
1420
- );
1421
- const queryClient = useQueryClient();
1422
- const previousProductIdRef = useRef(productId);
1423
- const isInitializedRef = useRef(false);
1424
- const dataRef = useRef(data);
1425
- const descriptorsRef = useRef(descriptors);
1426
- useEffect(() => {
1427
- dataRef.current = data;
1428
- descriptorsRef.current = descriptors;
1429
- }, [data, descriptors]);
1430
- useEffect(() => {
1431
- var _a;
1432
- if (previousProductIdRef.current === productId && isInitializedRef.current) {
1433
- return;
1434
- }
1435
- const productIdChanged = previousProductIdRef.current !== productId;
1436
- if (productIdChanged || !isInitializedRef.current) {
1437
- const currentMetadata = (data == null ? void 0 : data.metadata) ?? ((_a = dataRef.current) == null ? void 0 : _a.metadata) ?? {};
1438
- const currentDescriptors = descriptorsRef.current.length > 0 ? descriptorsRef.current : descriptors;
1439
- if (currentDescriptors.length === 0) {
1440
- return;
1441
- }
1442
- previousProductIdRef.current = productId;
1443
- setBaselineMetadata(currentMetadata);
1444
- const newInitialState = buildInitialFormState(currentDescriptors, currentMetadata);
1445
- setValues(newInitialState);
1446
- isInitializedRef.current = true;
1447
- }
1448
- }, [productId]);
1449
- const metadataStringRef = useRef("");
1450
- useEffect(() => {
1451
- const hasProductData = !!data;
1452
- const descriptorsLoaded = descriptors.length > 0;
1453
- const sameProduct = previousProductIdRef.current === productId;
1454
- const notInitialized = !isInitializedRef.current;
1455
- const currentMetadata = (data == null ? void 0 : data.metadata) ?? {};
1456
- const currentMetadataString = JSON.stringify(currentMetadata);
1457
- const metadataChanged = currentMetadataString !== metadataStringRef.current;
1458
- if (hasProductData && descriptorsLoaded && sameProduct && (notInitialized || metadataChanged)) {
1459
- const newInitialState = buildInitialFormState(descriptors, currentMetadata);
1460
- setBaselineMetadata(currentMetadata);
1461
- setValues(newInitialState);
1462
- metadataStringRef.current = currentMetadataString;
1463
- isInitializedRef.current = true;
1464
- }
1465
- }, [data, descriptors.length, productId]);
1466
- const initialState = useMemo(
1467
- () => buildInitialFormState(descriptors, baselineMetadata),
1468
- [descriptors, baselineMetadata]
1469
- );
1470
- const [values, setValues] = useState({});
1471
- const [isSaving, setIsSaving] = useState(false);
1472
- const errors = useMemo(() => {
1473
- return descriptors.reduce((acc, descriptor) => {
1474
- const error = validateValueForDescriptor(descriptor, values[descriptor.key]);
1475
- if (error) {
1476
- acc[descriptor.key] = error;
1477
- }
1478
- return acc;
1479
- }, {});
1480
- }, [descriptors, values]);
1481
- const hasErrors = Object.keys(errors).length > 0;
1482
- const isDirty = useMemo(() => {
1483
- return hasMetadataChanges({
1484
- descriptors,
1485
- values,
1486
- originalMetadata: baselineMetadata
1487
- });
1488
- }, [descriptors, values, baselineMetadata]);
1489
- const handleStringChange = (key, nextValue) => {
1490
- setValues((prev) => ({
1491
- ...prev,
1492
- [key]: nextValue
1493
- }));
1494
- };
1495
- const handleBooleanChange = (key, nextValue) => {
1496
- setValues((prev) => ({
1497
- ...prev,
1498
- [key]: nextValue
1499
- }));
1500
- };
1501
- const handleReset = () => {
1502
- setValues(initialState);
1503
- };
1504
- const handleSubmit = async () => {
1505
- if (!(data == null ? void 0 : data.id) || !descriptors.length) {
1506
- return;
1507
- }
1508
- setIsSaving(true);
1509
- try {
1510
- const metadataPayload = buildMetadataPayload({
1511
- descriptors,
1512
- values,
1513
- originalMetadata: baselineMetadata
1514
- });
1515
- const response = await fetch(`/admin/products/${data.id}`, {
1516
- method: "POST",
1517
- credentials: "include",
1518
- headers: {
1519
- "Content-Type": "application/json"
1520
- },
1521
- body: JSON.stringify({
1522
- metadata: metadataPayload
1523
- })
1524
- });
1525
- if (!response.ok) {
1526
- const payload = await response.json().catch(() => null);
1527
- throw new Error((payload == null ? void 0 : payload.message) ?? "Unable to save metadata");
1528
- }
1529
- const updated = await response.json();
1530
- const nextMetadata = updated.product.metadata;
1531
- setBaselineMetadata(nextMetadata);
1532
- setValues(buildInitialFormState(descriptors, nextMetadata));
1533
- toast.success("Metadata saved");
1534
- await queryClient.invalidateQueries({
1535
- queryKey: ["products"]
1536
- });
1537
- await queryClient.invalidateQueries({
1538
- queryKey: ["product", data.id]
1539
- });
1540
- if (data.id) {
1541
- queryClient.refetchQueries({
1542
- queryKey: ["product", data.id]
1543
- }).catch(() => {
1544
- });
1545
- }
1546
- } catch (error) {
1547
- toast.error(error instanceof Error ? error.message : "Save failed");
1548
- } finally {
1549
- setIsSaving(false);
1550
- }
1551
- };
1552
- return /* @__PURE__ */ jsxs(Container, { className: "flex flex-col gap-y-4", children: [
1553
- /* @__PURE__ */ jsxs("header", { className: "flex flex-col gap-y-1", children: [
1554
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-3", children: [
1555
- /* @__PURE__ */ jsx(Heading, { level: "h2", children: "Metadata" }),
1556
- /* @__PURE__ */ jsx(Badge, { size: "2xsmall", rounded: "full", children: descriptors.length })
1557
- ] }),
1558
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-subtle", children: "Structured metadata mapped to the keys you configured in the plugin options." })
1559
- ] }),
1560
- isPending || !isInitializedRef.current || Object.keys(values).length === 0 ? /* @__PURE__ */ jsx(Skeleton, { className: "h-[160px] w-full" }) : isError ? /* @__PURE__ */ jsxs(InlineTip, { variant: "error", label: "Configuration unavailable", children: [
1561
- "Unable to load metadata configuration for this plugin. Confirm that the plugin is registered with options in ",
1562
- /* @__PURE__ */ jsx("code", { children: "medusa-config.ts" }),
1563
- "."
1564
- ] }) : !descriptors.length ? /* @__PURE__ */ jsxs(InlineTip, { variant: "info", label: "No configured metadata keys", children: [
1565
- "Provide a ",
1566
- /* @__PURE__ */ jsx("code", { children: "metadataDescriptors" }),
1567
- " array in the plugin options to control which keys show up here.",
1568
- " ",
1569
- /* @__PURE__ */ jsx(
1570
- "a",
1571
- {
1572
- className: "text-ui-fg-interactive underline",
1573
- href: CONFIG_DOCS_URL,
1574
- target: "_blank",
1575
- rel: "noreferrer",
1576
- children: "Learn how to configure it."
1577
- }
1578
- )
1579
- ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1580
- /* @__PURE__ */ jsx("div", { className: "overflow-hidden rounded-lg border border-ui-border-base", children: /* @__PURE__ */ jsxs("table", { className: "min-w-full divide-y divide-ui-border-base", children: [
1581
- /* @__PURE__ */ jsx("thead", { className: "bg-ui-bg-subtle", children: /* @__PURE__ */ jsxs("tr", { children: [
1582
- /* @__PURE__ */ jsx(
1583
- "th",
1584
- {
1585
- scope: "col",
1586
- className: "txt-compact-xsmall-plus text-left uppercase tracking-wide text-ui-fg-muted px-4 py-3",
1587
- children: "Label"
1588
- }
1589
- ),
1590
- /* @__PURE__ */ jsx(
1591
- "th",
1592
- {
1593
- scope: "col",
1594
- className: "txt-compact-xsmall-plus text-left uppercase tracking-wide text-ui-fg-muted px-4 py-3",
1595
- children: "Value"
1596
- }
1597
- )
1598
- ] }) }),
1599
- /* @__PURE__ */ jsx("tbody", { className: "divide-y divide-ui-border-subtle bg-ui-bg-base", children: descriptors.map((descriptor) => {
1600
- const value = values[descriptor.key];
1601
- const error = errors[descriptor.key];
1602
- return /* @__PURE__ */ jsxs("tr", { children: [
1603
- /* @__PURE__ */ jsx(
1604
- "th",
1605
- {
1606
- scope: "row",
1607
- className: "txt-compact-medium text-ui-fg-base align-top px-4 py-4",
1608
- children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-1", children: [
1609
- /* @__PURE__ */ jsx("span", { children: descriptor.label ?? descriptor.key }),
1610
- /* @__PURE__ */ jsx("span", { className: "txt-compact-xsmall-plus text-ui-fg-muted uppercase tracking-wide", children: descriptor.type })
1611
- ] })
1612
- }
1613
- ),
1614
- /* @__PURE__ */ jsx("td", { className: "align-top px-4 py-4", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-2", children: [
1615
- /* @__PURE__ */ jsx(
1616
- ValueField,
1617
- {
1618
- descriptor,
1619
- value,
1620
- onStringChange: handleStringChange,
1621
- onBooleanChange: handleBooleanChange
1622
- }
1623
- ),
1624
- error && /* @__PURE__ */ jsx(Text, { className: "txt-compact-small text-ui-fg-error", children: error })
1625
- ] }) })
1626
- ] }, descriptor.key);
1627
- }) })
1628
- ] }) }),
1629
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-3 border-t border-ui-border-subtle pt-3 md:flex-row md:items-center md:justify-between", children: [
1630
- /* @__PURE__ */ jsx(Text, { className: "text-ui-fg-muted", children: "Changes are stored on the product metadata object. Clearing a field removes the corresponding key on save." }),
1631
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
1632
- /* @__PURE__ */ jsx(
1633
- Button,
1634
- {
1635
- variant: "secondary",
1636
- size: "small",
1637
- disabled: !isDirty || isSaving,
1638
- onClick: handleReset,
1639
- children: "Reset"
1640
- }
1641
- ),
1642
- /* @__PURE__ */ jsx(
1643
- Button,
1644
- {
1645
- size: "small",
1646
- onClick: handleSubmit,
1647
- disabled: !isDirty || hasErrors || isSaving,
1648
- isLoading: isSaving,
1649
- children: "Save metadata"
1650
- }
1651
- )
1652
- ] })
1653
- ] })
1654
- ] })
1655
- ] });
1656
- };
1657
- const ValueField = ({
1658
- descriptor,
1659
- value,
1660
- onStringChange,
1661
- onBooleanChange
1662
- }) => {
1663
- const fileInputRef = useRef(null);
1664
- const [isUploading, setIsUploading] = useState(false);
1665
- const handleFileUpload = async (event) => {
1666
- var _a;
1667
- const file = (_a = event.target.files) == null ? void 0 : _a[0];
1668
- if (!file) {
1669
- return;
1670
- }
1671
- setIsUploading(true);
1672
- try {
1673
- const formData = new FormData();
1674
- formData.append("files", file);
1675
- const response = await fetch("/admin/uploads", {
1676
- method: "POST",
1677
- credentials: "include",
1678
- body: formData
1679
- });
1680
- if (!response.ok) {
1681
- const payload = await response.json().catch(() => null);
1682
- throw new Error((payload == null ? void 0 : payload.message) ?? "File upload failed");
1683
- }
1684
- const result = await response.json();
1685
- if (result.files && result.files.length > 0) {
1686
- const uploadedFile = result.files[0];
1687
- const fileUrl = uploadedFile.url || uploadedFile.key;
1688
- if (fileUrl) {
1689
- onStringChange(descriptor.key, fileUrl);
1690
- toast.success("File uploaded successfully");
1691
- } else {
1692
- throw new Error("File upload succeeded but no URL returned");
1693
- }
1694
- } else {
1695
- throw new Error("File upload failed - no files returned");
1696
- }
1697
- } catch (error) {
1698
- toast.error(
1699
- error instanceof Error ? error.message : "Failed to upload file"
1700
- );
1701
- } finally {
1702
- setIsUploading(false);
1703
- if (fileInputRef.current) {
1704
- fileInputRef.current.value = "";
1705
- }
1706
- }
1707
- };
1708
- if (descriptor.type === "bool") {
1709
- return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
1710
- /* @__PURE__ */ jsx(
1711
- Switch,
1712
- {
1713
- checked: Boolean(value),
1714
- onCheckedChange: (checked) => onBooleanChange(descriptor.key, Boolean(checked)),
1715
- "aria-label": `Toggle ${descriptor.label ?? descriptor.key}`
1716
- }
1717
- ),
1718
- /* @__PURE__ */ jsx(Text, { className: "txt-compact-small text-ui-fg-muted", children: Boolean(value) ? "True" : "False" })
1719
- ] });
1720
- }
1721
- if (descriptor.type === "text") {
1722
- return /* @__PURE__ */ jsx(
1723
- Textarea,
1724
- {
1725
- value: value ?? "",
1726
- placeholder: "Enter text",
1727
- rows: 3,
1728
- onChange: (event) => onStringChange(descriptor.key, event.target.value)
1729
- }
1730
- );
1731
- }
1732
- if (descriptor.type === "number") {
1733
- return /* @__PURE__ */ jsx(
1734
- Input,
1735
- {
1736
- type: "text",
1737
- inputMode: "decimal",
1738
- placeholder: "0.00",
1739
- value: value ?? "",
1740
- onChange: (event) => onStringChange(descriptor.key, event.target.value)
1741
- }
1742
- );
1743
- }
1744
- return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-2", children: [
1745
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-2", children: [
1746
- /* @__PURE__ */ jsx(
1747
- Input,
1748
- {
1749
- type: "url",
1750
- placeholder: "https://example.com/file",
1751
- value: value ?? "",
1752
- onChange: (event) => onStringChange(descriptor.key, event.target.value),
1753
- className: "flex-1"
1754
- }
1755
- ),
1756
- /* @__PURE__ */ jsx(
1757
- "input",
1758
- {
1759
- ref: fileInputRef,
1760
- type: "file",
1761
- className: "hidden",
1762
- onChange: handleFileUpload,
1763
- disabled: isUploading,
1764
- "aria-label": `Upload file for ${descriptor.label ?? descriptor.key}`
1765
- }
1766
- ),
1767
- /* @__PURE__ */ jsx(
1768
- Button,
1769
- {
1770
- type: "button",
1771
- variant: "secondary",
1772
- size: "small",
1773
- onClick: () => {
1774
- var _a;
1775
- return (_a = fileInputRef.current) == null ? void 0 : _a.click();
1776
- },
1777
- disabled: isUploading,
1778
- isLoading: isUploading,
1779
- children: isUploading ? "Uploading..." : "Upload"
1780
- }
1781
- )
1782
- ] }),
1783
- typeof value === "string" && value && /* @__PURE__ */ jsx(
1784
- "a",
1785
- {
1786
- className: "txt-compact-small-plus text-ui-fg-interactive underline",
1787
- href: value,
1788
- target: "_blank",
1789
- rel: "noreferrer",
1790
- children: "View file"
1791
- }
1792
- )
1793
- ] });
1794
- };
1795
- defineWidgetConfig({
1796
- zone: "product.details.after"
1797
- });
5
+ import { Container, Heading, Text, InlineTip, Skeleton, Badge } from "@medusajs/ui";
1798
6
  const fetchJson = async (path) => {
1799
7
  const response = await fetch(path, {
1800
8
  credentials: "include"
@@ -1920,30 +128,6 @@ defineWidgetConfig({
1920
128
  });
1921
129
  const i18nTranslations0 = {};
1922
130
  const widgetModule = { widgets: [
1923
- {
1924
- Component: CategoryMetadataTableWidget,
1925
- zone: ["product_category.details.after"]
1926
- },
1927
- {
1928
- Component: CollectionMetadataTableWidget,
1929
- zone: ["product_collection.details.after"]
1930
- },
1931
- {
1932
- Component: HideCategoryDefaultMetadataWidget,
1933
- zone: ["product_category.details.side.before"]
1934
- },
1935
- {
1936
- Component: HideDefaultMetadataWidget,
1937
- zone: ["product.details.side.before"]
1938
- },
1939
- {
1940
- Component: OrderMetadataTableWidget,
1941
- zone: ["order.details.after"]
1942
- },
1943
- {
1944
- Component: ProductMetadataTableWidget,
1945
- zone: ["product.details.after"]
1946
- },
1947
131
  {
1948
132
  Component: ProductWishlistStatsWidget,
1949
133
  zone: ["product.details.side.after"]