@widgetic/editor 4.1.14 → 4.1.16

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 (76) hide show
  1. package/dist/components/PreviewChromeControls.svelte +15 -21
  2. package/dist/components/WidgetPreview.svelte +136 -105
  3. package/dist/components/color-select/ColorSelect.svelte +203 -224
  4. package/dist/components/color-select/constants.d.ts +4 -2
  5. package/dist/components/color-select/constants.js +4 -2
  6. package/dist/components/color-select/render.js +10 -9
  7. package/dist/components/editors/CompositionEditorApp.svelte +47 -40
  8. package/dist/components/editors/EditLeaseNotice.svelte +44 -33
  9. package/dist/components/editors/EmbedEditor.svelte +133 -259
  10. package/dist/components/editors/PropsEditor.svelte +418 -1338
  11. package/dist/components/editors/props-editor.css +5 -68
  12. package/dist/components/ic/AngleInputController.svelte +202 -277
  13. package/dist/components/ic/BrowserInputController.svelte +813 -803
  14. package/dist/components/ic/CheckboxInputController.svelte +92 -169
  15. package/dist/components/ic/CheckboxInputController.svelte.d.ts +2 -8
  16. package/dist/components/ic/ColorPickerInputController.svelte +1589 -1587
  17. package/dist/components/ic/ColorPickerInputController.svelte.d.ts +3 -3
  18. package/dist/components/ic/DateFieldInputController.svelte +455 -465
  19. package/dist/components/ic/DatePickerInputController.svelte +355 -368
  20. package/dist/components/ic/DatePickerInputController.svelte.d.ts +1 -1
  21. package/dist/components/ic/DropdownInputController.svelte +130 -200
  22. package/dist/components/ic/FixedPositionInputController.svelte +255 -276
  23. package/dist/components/ic/FixedPositionInputController.svelte.d.ts +5 -1
  24. package/dist/components/ic/FontInputController.svelte +2110 -2231
  25. package/dist/components/ic/FontInputController.svelte.d.ts +11 -11
  26. package/dist/components/ic/InputControllerHeader.svelte +141 -147
  27. package/dist/components/ic/InputControllerRow.svelte +74 -0
  28. package/dist/components/ic/InputControllerRow.svelte.d.ts +14 -0
  29. package/dist/components/ic/KnowledgeDocumentsInputController.svelte +84 -47
  30. package/dist/components/ic/KnowledgeTextForm.svelte +35 -33
  31. package/dist/components/ic/NumberControls.svelte +303 -269
  32. package/dist/components/ic/NumberControls.svelte.d.ts +4 -1
  33. package/dist/components/ic/NumberInputController.svelte +361 -301
  34. package/dist/components/ic/NumberInputController.svelte.d.ts +2 -0
  35. package/dist/components/ic/PositionInputController.svelte +253 -176
  36. package/dist/components/ic/PositionInputController.svelte.d.ts +2 -0
  37. package/dist/components/ic/RadioGroupInputController.svelte +71 -137
  38. package/dist/components/ic/RadioGroupInputController.svelte.d.ts +2 -8
  39. package/dist/components/ic/RangeCalendarInputController.svelte +233 -270
  40. package/dist/components/ic/RangeCalendarInputController.svelte.d.ts +2 -2
  41. package/dist/components/ic/RoundedCornersInputController.svelte +412 -435
  42. package/dist/components/ic/RoundedCornersInputController.svelte.d.ts +2 -0
  43. package/dist/components/ic/SliderInputController.svelte +263 -332
  44. package/dist/components/ic/SliderInputController.svelte.d.ts +1 -1
  45. package/dist/components/ic/SliderRangeInputController.svelte +140 -144
  46. package/dist/components/ic/SliderRangeInputController.svelte.d.ts +3 -3
  47. package/dist/components/ic/SwitchInputController.svelte +47 -109
  48. package/dist/components/ic/TagsInputController.svelte +95 -110
  49. package/dist/components/ic/TextAreaInputController.svelte +1794 -1935
  50. package/dist/components/ic/TextAreaPreviewInputController.svelte +436 -438
  51. package/dist/components/ic/TextAreaPreviewInputController.svelte.d.ts +2 -2
  52. package/dist/components/ic/TextInputController.svelte +65 -75
  53. package/dist/components/ic/TextInputController.svelte.d.ts +2 -0
  54. package/dist/components/ic/TimeInputController.svelte +433 -431
  55. package/dist/components/ic/VectorInputController.svelte +1833 -1831
  56. package/dist/components/ic/VectorInputController.svelte.d.ts +10 -10
  57. package/dist/components/ic/index.d.ts +1 -0
  58. package/dist/components/ic/index.js +1 -0
  59. package/dist/components/ic/shared/CategoryTabs.svelte +28 -35
  60. package/dist/components/ic/shared/ItemGrid.svelte +145 -179
  61. package/dist/components/ic/shared/RecentItemsSection.svelte +208 -271
  62. package/dist/components/ic/shared/RecentItemsSection.svelte.d.ts +1 -1
  63. package/dist/components/ui/arrows/OpacitySliderArrows.svelte +23 -38
  64. package/dist/components/ui/arrows/OpacitySliderArrows.svelte.d.ts +1 -4
  65. package/dist/components/ui/calendar-editor-fit/EditorCalendarStyles.svelte +45 -0
  66. package/dist/components/ui/calendar-editor-fit/EditorCalendarStyles.svelte.d.ts +26 -0
  67. package/dist/components/ui/checkerboard-background/CheckerboardBackground.svelte +20 -12
  68. package/dist/components/ui/shadow-picker-host/ShadowPickerHost.svelte +39 -0
  69. package/dist/components/ui/shadow-picker-host/ShadowPickerHost.svelte.d.ts +10 -0
  70. package/dist/i18n/language.d.ts +44 -281
  71. package/dist/i18n/messages.d.ts +41 -34
  72. package/dist/i18n/messages.js +47 -34
  73. package/dist/i18n/translate.d.ts +1 -1
  74. package/dist/utils.d.ts +7 -0
  75. package/dist/utils.js +26 -2
  76. package/package.json +5 -5
@@ -1,818 +1,828 @@
1
1
  <script module lang="ts">
2
- import type { InputControllerConfig } from './index';
3
-
4
- interface FileValue {
5
- id: string;
6
- file: string;
7
- url: string;
8
- hash?: string; // Add hash property for ThumbHash
9
- }
10
-
11
- /** Declared props contract — export lets below are annotated from it so the
12
- * interface cannot drift from what the component actually reads. */
13
- export interface BrowserInputControllerProps {
14
- header?: { label: string; helpText?: string };
15
- label?: string;
16
- value?: string | FileValue;
17
- onChange?: (newValue: string | FileValue) => void;
18
- portalTarget?: string | HTMLElement;
19
- config?: InputControllerConfig;
20
- }
2
+ import type { InputControllerConfig } from './index';
3
+
4
+ interface FileValue {
5
+ id: string;
6
+ file: string;
7
+ url: string;
8
+ hash?: string; // Add hash property for ThumbHash
9
+ }
10
+
11
+ /** Declared props contract — export lets below are annotated from it so the
12
+ * interface cannot drift from what the component actually reads. */
13
+ export interface BrowserInputControllerProps {
14
+ header?: { label: string; helpText?: string };
15
+ label?: string;
16
+ value?: string | FileValue;
17
+ onChange?: (newValue: string | FileValue) => void;
18
+ portalTarget?: string | HTMLElement;
19
+ config?: InputControllerConfig;
20
+ }
21
21
  </script>
22
22
 
23
23
  <script lang="ts">
24
- /**
25
- * BrowserInputController Component
26
- * A specialized input controller for file browsing and media preview functionality.
27
- * Handles various file types (image, video, audio, document) with appropriate previews
28
- * and playback controls.
29
- */
30
-
31
- // Svelte imports
32
- import { onDestroy, tick } from 'svelte';
33
-
34
- // Shadcn UI Components
35
- import { Portal, Tooltip, showToast } from '@widgetic/design-system/components';
36
- import { ThumbHashImage } from "@widgetic/design-system/components";
37
- import { FileBrowser, setFileBrowserUploadConfig, persistentSelectStore } from '@widgetic/file-browser';
38
- import { useEditorMediaLibrary } from '../../mediaLibraryContext';
39
- import { useEditorPickFile, type PartnerPickFile } from '../../pickFileContext';
40
- import { useEditorStoreFileUrl } from '../../fileStorageUrlContext';
41
- import { useEditorLanguage } from '../../i18n/language';
42
- import type { EditorMessageKey } from '../../i18n/messages';
43
- import type { Translate } from '@widgetic/design-system/i18n';
44
- import X from '../icons/x.svelte';
45
- // console.log("BrowserInputController - Tooltip:", Tooltip);
46
-
47
-
48
- // utils imports
49
- import MediaManager from '../../utils/MediaManager';
50
- import { queryInTreeOf } from '../../utils/shadowDom';
51
-
52
- // Static asset imports (bundled via Vite, works when imported as library)
53
- import icAudio from '../../assets/icons/ic-browser/audio.svg?url';
54
- import icDocument from '../../assets/icons/ic-browser/document.svg?url';
55
- import icError from '../../assets/icons/ic-browser/error.svg?url';
56
- import icFolder from '../../assets/icons/ic-browser/folder.svg?url';
57
- import icPlayerPause from '../../assets/icons/ic-browser/player-pause.svg?url';
58
- import icPlayerPlay from '../../assets/icons/ic-browser/player-play.svg?url';
59
-
60
- import { InputControllerHeader } from './index';
61
-
62
- // Component props with default values
63
- export let header: BrowserInputControllerProps['header'] = undefined;
64
- export let label: BrowserInputControllerProps['label'] = '';
65
- export let value: BrowserInputControllerProps['value'] = '';
66
- export let onChange: BrowserInputControllerProps['onChange'] = () => {};
67
- export let portalTarget: BrowserInputControllerProps['portalTarget'] = 'portal-element';
68
-
69
- /** Full-panel overlay when portaled to props-editor panel (not document body). */
70
- $: fillEditorPanel =
71
- portalTarget === 'props-editor-file-browser-portal' ||
72
- (portalTarget instanceof HTMLElement &&
73
- portalTarget.id === 'props-editor-file-browser-portal');
74
- export let config: BrowserInputControllerProps['config'] = {};
75
-
76
- // The media library the editor above was given (a partner's own storage, for instance), read through a getter
77
- // because it reaches this component through context.
78
- const getEditorMediaLibrary = useEditorMediaLibrary();
79
- const getEditorPickFile = useEditorPickFile();
80
- const getEditorStoreFileUrl = useEditorStoreFileUrl();
81
- let pickAbortController: AbortController | null = null;
82
-
83
- // The words of the editor in the language of the page, and the share of them that belongs to the File Browser inside it.
84
- const { t, fileBrowser: fileBrowserLanguage } = useEditorLanguage();
85
-
86
- // Extract allowed file types from config or default to all files
87
- const fileTypes = config.fileTypes || ['*'];
88
-
89
- // The control's own element, to find the editor's panel from (see getPortalHost)
90
- let controllerElement: HTMLDivElement | undefined;
91
-
92
- // Media element references for audio/video playback
93
- let audioElement: HTMLAudioElement | null = null;
94
- let videoElement: HTMLVideoElement | null = null;
95
- let isPlaying = false;
96
-
97
- // Add loading state
98
- let isChecking = true;
99
- let hasError = false;
100
- let isFileBrowserOpen = false;
101
-
102
- let mouseX = 0;
103
- let mouseY = 0;
104
- let showHelp = false;
105
- let showHelpTimeout: ReturnType<typeof setTimeout>;
106
-
107
- function handleMouseEnter(event: MouseEvent) {
108
- mouseX = event.clientX;
109
- mouseY = event.clientY;
110
- showHelpTimeout = setTimeout(() => {
111
- showHelp = true;
112
- }, 250);
113
- }
114
-
115
- function handleMouseMove(event: MouseEvent) {
116
- mouseX = event.clientX;
117
- mouseY = event.clientY;
118
- }
119
-
120
- function handleMouseLeave() {
121
- clearTimeout(showHelpTimeout);
122
- showHelp = false;
123
- }
124
-
125
-
126
- /**
127
- * Extracts filename from file value
128
- * @param value - String path or FileValue object
129
- * @returns Filename or empty string if invalid
130
- */
131
- function getFileName(value: string | FileValue | null | undefined): string {
132
- if (!value) return '';
133
- if (typeof value === 'object' && value.file) {
134
- return value.file;
135
- }
136
- if (typeof value === 'string') {
137
- try {
138
- const parts = value.split('/');
139
- return parts[parts.length - 1] || '';
140
- } catch (error) {
141
- console.error('Error extracting filename:', error);
142
- return '';
143
- }
144
- }
145
- return '';
146
- }
147
-
148
- /**
149
- * Gets the URL for preview from the value
150
- * @param value - String path or FileValue object
151
- * @returns URL for preview
152
- */
153
- function getPreviewUrl(value: string | FileValue | null | undefined): string {
154
- if (!value) return '';
155
- if (typeof value === 'object' && value.url) {
156
- return value.url;
157
- }
158
- return typeof value === 'string' ? value : '';
159
- }
160
-
161
- /**
162
- * Gets the thumbnail URL for a video
163
- * @param videoUrl - URL of the video file
164
- * @returns URL of the thumbnail
165
- */
166
- function getVideoThumbnailUrl(videoUrl: string): string {
167
- return videoUrl.replace(/\.[^/.]+$/, '.png');
168
- }
169
-
170
- /**
171
- * Determines the type of file based on its extension
172
- * @param path - File path to analyze
173
- * @returns File type category or 'unknown'
174
- */
175
- function getFileType(path: string | null | undefined): 'image' | 'video' | 'audio' | 'document' | 'unknown' {
176
- if (!path || typeof path !== 'string') return 'unknown';
177
-
178
- const ext = path.split('.').pop()?.toLowerCase() || '';
179
- if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(ext)) return 'image';
180
- if (['mp4', 'webm', 'ogg'].includes(ext)) return 'video';
181
- if (['mp3', 'wav', 'ogg'].includes(ext)) return 'audio';
182
- if (['pdf', 'doc', 'docx', 'txt'].includes(ext)) return 'document';
183
- return 'unknown';
184
- }
185
-
186
- /** Only embedded iframe mode (URL params) sets upload config here; standalone uses parent +page sync. */
187
- function syncFileBrowserUploadConfigIfEmbedded() {
188
- if (typeof window === 'undefined') return;
189
- // With a media library the File Browser takes its files from it and never reads the upload configuration, and the
190
- // address of the page this editor sits in (which can be a partner's) is none of the editor's business.
191
- if (getEditorMediaLibrary()) return;
192
- const params = new URLSearchParams(window.location.search);
193
- const apiUrl = params.get('apiUrl');
194
- const token = params.get('token');
195
- if (!apiUrl || !token) return;
196
- const widgetId = params.get('widgetId');
197
- const apiBase = apiUrl.replace(/\/+$/, '');
198
- setFileBrowserUploadConfig({
199
- apiBasePath: `${apiBase}/v1`,
200
- accessToken: token.replace(/^Bearer\s+/i, ''),
201
- contextType: 'content-property',
202
- source: 'file-browser-upload',
203
- widgetId: widgetId || undefined,
204
- });
205
- }
206
-
207
- /**
208
- * Opens the shared FileBrowser package and lets the user select one file.
209
- */
210
- function getPortalHost(): HTMLElement | null {
211
- if (portalTarget instanceof HTMLElement) return portalTarget;
212
- if (typeof document === 'undefined') return null;
213
- // Looked for in the tree this control is in: inside a module that is a shadow root, which `document` cannot see into
214
- const portalHost = queryInTreeOf(controllerElement, '#props-editor-file-browser-portal');
215
- return portalHost instanceof HTMLElement ? portalHost : null;
216
- }
217
-
218
- function setPortalHostInteractive(active: boolean) {
219
- const host = getPortalHost();
220
- if (host) {
221
- host.classList.toggle('pointer-events-none', !active);
222
- host.classList.toggle('pointer-events-auto', active);
223
- }
224
- }
225
-
226
- function acceptPatternsForField(): string[] {
227
- if (!fileTypes?.length || fileTypes.includes('*')) return ['*/*'];
228
- return fileTypes;
229
- }
230
-
231
- async function storedUrlFor(file: PartnerPickFile): Promise<string> {
232
- const storeFileUrl = getEditorStoreFileUrl();
233
- if (!storeFileUrl) return file.url;
234
- try {
235
- return await storeFileUrl(file);
236
- } catch (error) {
237
- console.warn('[editor] storeFileUrl failed; using the file url.', error);
238
- return file.url;
239
- }
240
- }
241
-
242
- async function applyPickedFile(selectedFile: PartnerPickFile) {
243
- const url = await storedUrlFor(selectedFile);
244
- const nextValue: FileValue = {
245
- id: selectedFile.id,
246
- file: selectedFile.name || '',
247
- url,
248
- hash: selectedFile.hash
249
- };
250
- value = nextValue;
251
- onChange(nextValue);
252
- }
253
-
254
- async function openFileBrowser() {
255
- const pickFile = getEditorPickFile();
256
- if (pickFile) {
257
- pickAbortController?.abort();
258
- pickAbortController = new AbortController();
259
- const signal = pickAbortController.signal;
260
- try {
261
- const picked = await pickFile({ accept: acceptPatternsForField(), multiple: false, signal });
262
- if (signal.aborted) return;
263
- const selectedFile = picked?.[0];
264
- if (!selectedFile) return;
265
- await applyPickedFile(selectedFile);
266
- } catch (error) {
267
- if (signal.aborted) return;
268
- const name = error instanceof Error ? error.name : '';
269
- if (name === 'AbortError') return;
270
- console.error('[editor] pickFile failed:', error);
271
- showToast('error', $t('editor.file.pickFailed'));
272
- }
273
- return;
274
- }
275
-
276
- try {
277
- syncFileBrowserUploadConfigIfEmbedded();
278
- // console.log('BrowserInputController: opening file browser', {
279
- // fileTypes,
280
- // id: typeof value === 'object' ? value.id : undefined,
281
- // batch: 1
282
- // });
283
- isFileBrowserOpen = true;
284
- await tick();
285
- syncFileBrowserInitialSelection();
286
- setPortalHostInteractive(true);
287
- } catch (error) {
288
- console.error('Error opening file browser:', error);
289
- }
290
- }
291
-
292
- function closeFileBrowser() {
293
- isFileBrowserOpen = false;
294
- setPortalHostInteractive(false);
295
- }
296
-
297
- async function handleFileBrowserSelect(event: CustomEvent<{ files?: Array<FileValue & { name?: string; thumbnail?: string }> }>) {
298
- try {
299
- const selectedFile = event.detail?.files?.[0];
300
- if (!selectedFile) {
301
- // console.log('BrowserInputController: file browser selection skipped, no file selected');
302
- return;
303
- }
304
-
305
- await applyPickedFile({
306
- id: selectedFile.id,
307
- name: selectedFile.name || selectedFile.file || '',
308
- url: selectedFile.url,
309
- hash: selectedFile.hash
310
- });
311
- closeFileBrowser();
312
- } catch (error) {
313
- console.error('BrowserInputController: failed to select file', error);
314
- }
315
- }
316
-
317
- /**
318
- * Toggles playback for audio/video elements
319
- * Uses MediaManager to ensure only one plays at a time
320
- */
321
- function togglePlayback() {
322
- if (audioElement) {
323
- if (isPlaying) {
324
- MediaManager.pause(audioElement);
325
- } else {
326
- MediaManager.play(audioElement);
327
- }
328
- isPlaying = !isPlaying;
329
- } else if (videoElement) {
330
- if (isPlaying) {
331
- MediaManager.pause(videoElement);
332
- } else {
333
- MediaManager.play(videoElement);
334
- }
335
- isPlaying = !isPlaying;
336
- }
337
- }
338
-
339
- onDestroy(() => {
340
- pickAbortController?.abort();
341
- pickAbortController = null;
342
- clearTimeout(showHelpTimeout);
343
- setPortalHostInteractive(false);
344
- if (audioElement) {
345
- MediaManager.cleanup(audioElement);
346
- audioElement = null;
347
- }
348
- if (videoElement) {
349
- MediaManager.cleanup(videoElement);
350
- videoElement = null;
351
- }
352
- });
353
-
354
- /**
355
- * Checks if an image URL is accessible using Image() constructor
356
- * to avoid CORS issues with external services (picsum.photos, etc.)
357
- */
358
- async function checkFileExists(url: string): Promise<boolean> {
359
- return new Promise((resolve) => {
360
- const img = new Image();
361
- img.onload = () => resolve(true);
362
- img.onerror = () => resolve(false);
363
- img.src = url;
364
- setTimeout(() => resolve(false), 5000);
365
- });
366
- }
367
-
368
- // Update error state handling
369
- async function updateErrorState(url: string) {
370
- isChecking = true;
371
- if (!url) {
372
- hasError = true;
373
- isChecking = false;
374
- return;
375
- }
376
- hasError = !(await checkFileExists(url));
377
- isChecking = false;
378
- }
379
-
380
- // Watch previewUrl changes
381
- $: if (previewUrl) {
382
- updateErrorState(previewUrl);
383
- } else {
384
- hasError = false;
385
- isChecking = false;
386
- }
387
-
388
- /**
389
- * Trims a string to a maximum length and adds ellipsis if needed
390
- * @param str - String to trim
391
- * @param maxLength - Maximum length before trimming
392
- * @returns Trimmed string with ellipsis if needed
393
- */
394
- function trimString(str: string, maxLength: number = 30): string {
395
- if (str.length <= maxLength) return str;
396
- return str.substring(0, maxLength - 3) + '...';
397
- }
398
-
399
- // Update the reactive statement to use trimString
400
- $: displayLabel = value ? trimString(getFileName(value)) : (header?.label || label);
401
- $: previewUrl = getPreviewUrl(value);
402
-
403
- // Add hash extraction helper
404
- function getThumbHash(value: string | FileValue | null | undefined): string | undefined {
405
- if (!value) return undefined;
406
- if (typeof value === 'object' && 'hash' in value) {
407
- return value.hash;
408
- }
409
- return undefined;
410
- }
411
-
412
- // Update the reactive statement to use getThumbHash
413
- $: thumbHash = getThumbHash(value);
414
-
415
- // Add event listeners for media elements
416
- function setupMediaElement(element: HTMLMediaElement) {
417
- if (!element) return;
418
-
419
- element.addEventListener('play', () => {
420
- // console.log('Media started playing');
421
- isPlaying = true;
422
- });
423
-
424
- element.addEventListener('pause', () => {
425
- // console.log('Media paused');
426
- isPlaying = false;
427
- });
428
-
429
- element.addEventListener('ended', () => {
430
- // console.log('Media ended');
431
- isPlaying = false;
432
- });
433
-
434
- // Add listener for when the media is stopped externally
435
- element.addEventListener('timeupdate', () => {
436
- if (element.paused && isPlaying) {
437
- isPlaying = false;
438
- }
439
- });
440
- }
441
-
442
- // Update bindings to setup media elements
443
- $: if (audioElement) setupMediaElement(audioElement);
444
- $: if (videoElement) setupMediaElement(videoElement);
445
-
446
- // Add placeholder text logic
447
- function getAddToEditorLabelSingular(fileTypes: string[], translate: Translate<EditorMessageKey>): string {
448
- if (!fileTypes || fileTypes.includes('*')) return translate('editor.file.useFile');
449
- const type = fileTypes[0].split('/')[0];
450
- switch (type) {
451
- case 'image': return translate('editor.file.useImage');
452
- case 'video': return translate('editor.file.useVideo');
453
- case 'audio': return translate('editor.file.useAudio');
454
- case 'document': return translate('editor.file.useDocument');
455
- default: return translate('editor.file.useFile');
456
- }
457
- }
458
-
459
- function getCurrentFileId(): string | null {
460
- if (value && typeof value === 'object' && value.id) return value.id;
461
- return null;
462
- }
463
-
464
- function syncFileBrowserInitialSelection() {
465
- const fileId = getCurrentFileId();
466
- persistentSelectStore.clearSelections(fileBrowserFilter);
467
- if (fileId) {
468
- persistentSelectStore.setSelections(fileBrowserFilter, [fileId]);
469
- if (fileBrowserFilter !== 'all') {
470
- persistentSelectStore.setSelections('all', [fileId]);
471
- }
472
- }
473
- }
474
-
475
- function getPlaceholderText(fileTypes: string[], translate: Translate<EditorMessageKey>): string {
476
- if (!fileTypes || fileTypes.includes('*')) return translate('editor.file.addFile');
477
- const type = fileTypes[0].split('/')[0];
478
- switch (type) {
479
- case 'image': return translate('editor.file.addImage');
480
- case 'video': return translate('editor.file.addVideo');
481
- case 'audio': return translate('editor.file.addAudio');
482
- case 'document': return translate('editor.file.addDocument');
483
- default: return translate('editor.file.addFile');
484
- }
485
- }
486
-
487
- function getInitialFileBrowserFilter(fileTypes: string[]): 'all' | 'image' | 'video' | 'audio' | 'document' | 'font' | 'svg' {
488
- if (!fileTypes || fileTypes.includes('*')) return 'all';
489
- const type = fileTypes[0].split('/')[0];
490
- if (fileTypes[0] === 'image/svg+xml') return 'svg';
491
- if (type === 'font') return 'font';
492
- if (['image', 'video', 'audio'].includes(type)) return type as 'image' | 'video' | 'audio';
493
- if (type === 'application' || type === 'text') return 'document';
494
- return 'all';
495
- }
496
-
497
- $: fileBrowserFilter = getInitialFileBrowserFilter(fileTypes);
498
- $: fileBrowserRestrictUpload = fileBrowserFilter !== 'all';
499
- $: fileBrowserAddToEditorLabelSingular = getAddToEditorLabelSingular(fileTypes, $t);
500
-
501
- function handleContentRemoval(e: MouseEvent) {
502
- e.stopPropagation();
503
- e.preventDefault();
504
- value = '';
505
- onChange('');
506
- isPlaying = false;
507
- hasError = false;
508
-
509
- if (audioElement) {
510
- MediaManager.pause(audioElement);
511
- MediaManager.cleanup(audioElement);
512
- audioElement = null;
513
- }
514
- if (videoElement) {
515
- MediaManager.pause(videoElement);
516
- MediaManager.cleanup(videoElement);
517
- videoElement = null;
518
- }
519
-
520
- onChange('');
521
- }
522
-
523
- function handleControllerClick(e: MouseEvent) {
524
- const target = e.target as HTMLElement;
525
- if (target.closest('.browser-ic-clear-btn')) return;
526
- openFileBrowser();
527
- }
24
+ /**
25
+ * BrowserInputController Component
26
+ * A specialized input controller for file browsing and media preview functionality.
27
+ * Handles various file types (image, video, audio, document) with appropriate previews
28
+ * and playback controls.
29
+ */
30
+
31
+ // Svelte imports
32
+ import { onDestroy, tick } from 'svelte';
33
+
34
+ // Shadcn UI Components
35
+ import { Portal, Tooltip, showToast } from '@widgetic/design-system/components';
36
+ import { ThumbHashImage } from '@widgetic/design-system/components';
37
+ import {
38
+ FileBrowser,
39
+ setFileBrowserUploadConfig,
40
+ persistentSelectStore
41
+ } from '@widgetic/file-browser';
42
+ import { useEditorMediaLibrary } from '../../mediaLibraryContext';
43
+ import { useEditorPickFile, type PartnerPickFile } from '../../pickFileContext';
44
+ import { useEditorStoreFileUrl } from '../../fileStorageUrlContext';
45
+ import { useEditorLanguage } from '../../i18n/language';
46
+ import type { EditorMessageKey } from '../../i18n/messages';
47
+ import type { Translate } from '@widgetic/design-system/i18n';
48
+ import {
49
+ IconFolderOpen,
50
+ IconMusic,
51
+ IconPlayerPause,
52
+ IconVideo,
53
+ IconFileText,
54
+ IconAlertTriangle,
55
+ IconX
56
+ } from '@widgetic/design-system/icons';
57
+ import MediaManager from '../../utils/MediaManager';
58
+ import { queryInTreeOf } from '../../utils/shadowDom';
59
+
60
+ import InputControllerRow from './InputControllerRow.svelte';
61
+
62
+ // Component props with default values
63
+ export let header: BrowserInputControllerProps['header'] = undefined;
64
+ export let label: BrowserInputControllerProps['label'] = '';
65
+ export let value: BrowserInputControllerProps['value'] = '';
66
+ export let onChange: BrowserInputControllerProps['onChange'] = () => {};
67
+ export let portalTarget: BrowserInputControllerProps['portalTarget'] = 'portal-element';
68
+
69
+ /** Full-panel overlay when portaled to props-editor panel (not document body). */
70
+ $: fillEditorPanel =
71
+ portalTarget === 'props-editor-file-browser-portal' ||
72
+ (portalTarget instanceof HTMLElement && portalTarget.id === 'props-editor-file-browser-portal');
73
+ export let config: BrowserInputControllerProps['config'] = {};
74
+
75
+ // The media library the editor above was given (a partner's own storage, for instance), read through a getter
76
+ // because it reaches this component through context.
77
+ const getEditorMediaLibrary = useEditorMediaLibrary();
78
+ const getEditorPickFile = useEditorPickFile();
79
+ const getEditorStoreFileUrl = useEditorStoreFileUrl();
80
+ let pickAbortController: AbortController | null = null;
81
+
82
+ // The words of the editor in the language of the page, and the share of them that belongs to the File Browser inside it.
83
+ const { t, fileBrowser: fileBrowserLanguage } = useEditorLanguage();
84
+
85
+ // Extract allowed file types from config or default to all files
86
+ const fileTypes = config.fileTypes || ['*'];
87
+
88
+ // The control's own element, to find the editor's panel from (see getPortalHost)
89
+ let controllerElement: HTMLDivElement | undefined;
90
+
91
+ // Media element references for audio/video playback
92
+ let audioElement: HTMLAudioElement | null = null;
93
+ let videoElement: HTMLVideoElement | null = null;
94
+ let isPlaying = false;
95
+
96
+ // Add loading state
97
+ let isChecking = true;
98
+ let hasError = false;
99
+ let isFileBrowserOpen = false;
100
+
101
+ let mouseX = 0;
102
+ let mouseY = 0;
103
+ let showHelp = false;
104
+ let showHelpTimeout: ReturnType<typeof setTimeout>;
105
+
106
+ function handleMouseEnter(event: MouseEvent) {
107
+ mouseX = event.clientX;
108
+ mouseY = event.clientY;
109
+ showHelpTimeout = setTimeout(() => {
110
+ showHelp = true;
111
+ }, 250);
112
+ }
113
+
114
+ function handleMouseMove(event: MouseEvent) {
115
+ mouseX = event.clientX;
116
+ mouseY = event.clientY;
117
+ }
118
+
119
+ function handleMouseLeave() {
120
+ clearTimeout(showHelpTimeout);
121
+ showHelp = false;
122
+ }
123
+
124
+ /**
125
+ * Extracts filename from file value
126
+ * @param value - String path or FileValue object
127
+ * @returns Filename or empty string if invalid
128
+ */
129
+ function getFileName(value: string | FileValue | null | undefined): string {
130
+ if (!value) return '';
131
+ if (typeof value === 'object' && value.file) {
132
+ return value.file;
133
+ }
134
+ if (typeof value === 'string') {
135
+ try {
136
+ const parts = value.split('/');
137
+ return parts[parts.length - 1] || '';
138
+ } catch (error) {
139
+ console.error('Error extracting filename:', error);
140
+ return '';
141
+ }
142
+ }
143
+ return '';
144
+ }
145
+
146
+ /**
147
+ * Gets the URL for preview from the value
148
+ * @param value - String path or FileValue object
149
+ * @returns URL for preview
150
+ */
151
+ function getPreviewUrl(value: string | FileValue | null | undefined): string {
152
+ if (!value) return '';
153
+ if (typeof value === 'object' && value.url) {
154
+ return value.url;
155
+ }
156
+ return typeof value === 'string' ? value : '';
157
+ }
158
+
159
+ /**
160
+ * Determines the type of file based on its extension
161
+ * @param path - File path to analyze
162
+ * @returns File type category or 'unknown'
163
+ */
164
+ function getFileType(
165
+ path: string | null | undefined
166
+ ): 'image' | 'video' | 'audio' | 'document' | 'unknown' {
167
+ if (!path || typeof path !== 'string') return 'unknown';
168
+
169
+ const ext = path.split('.').pop()?.toLowerCase() || '';
170
+ if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(ext)) return 'image';
171
+ if (['mp4', 'webm', 'ogg'].includes(ext)) return 'video';
172
+ if (['mp3', 'wav', 'ogg'].includes(ext)) return 'audio';
173
+ if (['pdf', 'doc', 'docx', 'txt'].includes(ext)) return 'document';
174
+ return 'unknown';
175
+ }
176
+
177
+ /** Only embedded iframe mode (URL params) sets upload config here; standalone uses parent +page sync. */
178
+ function syncFileBrowserUploadConfigIfEmbedded() {
179
+ if (typeof window === 'undefined') return;
180
+ // With a media library the File Browser takes its files from it and never reads the upload configuration, and the
181
+ // address of the page this editor sits in (which can be a partner's) is none of the editor's business.
182
+ if (getEditorMediaLibrary()) return;
183
+ const params = new URLSearchParams(window.location.search);
184
+ const apiUrl = params.get('apiUrl');
185
+ const token = params.get('token');
186
+ if (!apiUrl || !token) return;
187
+ const widgetId = params.get('widgetId');
188
+ const apiBase = apiUrl.replace(/\/+$/, '');
189
+ setFileBrowserUploadConfig({
190
+ apiBasePath: `${apiBase}/v1`,
191
+ accessToken: token.replace(/^Bearer\s+/i, ''),
192
+ contextType: 'content-property',
193
+ source: 'file-browser-upload',
194
+ widgetId: widgetId || undefined
195
+ });
196
+ }
197
+
198
+ /**
199
+ * Opens the shared FileBrowser package and lets the user select one file.
200
+ */
201
+ function getPortalHost(): HTMLElement | null {
202
+ if (portalTarget instanceof HTMLElement) return portalTarget;
203
+ if (typeof document === 'undefined') return null;
204
+ // Looked for in the tree this control is in: inside a module that is a shadow root, which `document` cannot see into
205
+ const portalHost = queryInTreeOf(controllerElement, '#props-editor-file-browser-portal');
206
+ return portalHost instanceof HTMLElement ? portalHost : null;
207
+ }
208
+
209
+ function setPortalHostInteractive(active: boolean) {
210
+ const host = getPortalHost();
211
+ if (host) {
212
+ host.classList.toggle('pointer-events-none', !active);
213
+ host.classList.toggle('pointer-events-auto', active);
214
+ }
215
+ }
216
+
217
+ function acceptPatternsForField(): string[] {
218
+ if (!fileTypes?.length || fileTypes.includes('*')) return ['*/*'];
219
+ return fileTypes;
220
+ }
221
+
222
+ async function storedUrlFor(file: PartnerPickFile): Promise<string> {
223
+ const storeFileUrl = getEditorStoreFileUrl();
224
+ if (!storeFileUrl) return file.url;
225
+ try {
226
+ return await storeFileUrl(file);
227
+ } catch (error) {
228
+ console.warn('[editor] storeFileUrl failed; using the file url.', error);
229
+ return file.url;
230
+ }
231
+ }
232
+
233
+ async function applyPickedFile(selectedFile: PartnerPickFile) {
234
+ const url = await storedUrlFor(selectedFile);
235
+ const nextValue: FileValue = {
236
+ id: selectedFile.id,
237
+ file: selectedFile.name || '',
238
+ url,
239
+ hash: selectedFile.hash
240
+ };
241
+ value = nextValue;
242
+ onChange(nextValue);
243
+ }
244
+
245
+ async function openFileBrowser() {
246
+ const pickFile = getEditorPickFile();
247
+ if (pickFile) {
248
+ pickAbortController?.abort();
249
+ pickAbortController = new AbortController();
250
+ const signal = pickAbortController.signal;
251
+ try {
252
+ const picked = await pickFile({
253
+ accept: acceptPatternsForField(),
254
+ multiple: false,
255
+ signal
256
+ });
257
+ if (signal.aborted) return;
258
+ const selectedFile = picked?.[0];
259
+ if (!selectedFile) return;
260
+ await applyPickedFile(selectedFile);
261
+ } catch (error) {
262
+ if (signal.aborted) return;
263
+ const name = error instanceof Error ? error.name : '';
264
+ if (name === 'AbortError') return;
265
+ console.error('[editor] pickFile failed:', error);
266
+ showToast('error', $t('editor.file.pickFailed'));
267
+ }
268
+ return;
269
+ }
270
+
271
+ try {
272
+ syncFileBrowserUploadConfigIfEmbedded();
273
+ // console.log('BrowserInputController: opening file browser', {
274
+ // fileTypes,
275
+ // id: typeof value === 'object' ? value.id : undefined,
276
+ // batch: 1
277
+ // });
278
+ isFileBrowserOpen = true;
279
+ await tick();
280
+ syncFileBrowserInitialSelection();
281
+ setPortalHostInteractive(true);
282
+ } catch (error) {
283
+ console.error('Error opening file browser:', error);
284
+ }
285
+ }
286
+
287
+ function closeFileBrowser() {
288
+ isFileBrowserOpen = false;
289
+ setPortalHostInteractive(false);
290
+ }
291
+
292
+ async function handleFileBrowserSelect(
293
+ event: CustomEvent<{ files?: Array<FileValue & { name?: string; thumbnail?: string }> }>
294
+ ) {
295
+ try {
296
+ const selectedFile = event.detail?.files?.[0];
297
+ if (!selectedFile) {
298
+ // console.log('BrowserInputController: file browser selection skipped, no file selected');
299
+ return;
300
+ }
301
+
302
+ await applyPickedFile({
303
+ id: selectedFile.id,
304
+ name: selectedFile.name || selectedFile.file || '',
305
+ url: selectedFile.url,
306
+ hash: selectedFile.hash
307
+ });
308
+ closeFileBrowser();
309
+ } catch (error) {
310
+ console.error('BrowserInputController: failed to select file', error);
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Toggles playback for audio/video elements
316
+ * Uses MediaManager to ensure only one plays at a time
317
+ */
318
+ function togglePlayback() {
319
+ if (audioElement) {
320
+ if (isPlaying) {
321
+ MediaManager.pause(audioElement);
322
+ } else {
323
+ MediaManager.play(audioElement);
324
+ }
325
+ isPlaying = !isPlaying;
326
+ } else if (videoElement) {
327
+ if (isPlaying) {
328
+ MediaManager.pause(videoElement);
329
+ } else {
330
+ MediaManager.play(videoElement);
331
+ }
332
+ isPlaying = !isPlaying;
333
+ }
334
+ }
335
+
336
+ onDestroy(() => {
337
+ pickAbortController?.abort();
338
+ pickAbortController = null;
339
+ clearTimeout(showHelpTimeout);
340
+ setPortalHostInteractive(false);
341
+ if (audioElement) {
342
+ MediaManager.cleanup(audioElement);
343
+ audioElement = null;
344
+ }
345
+ if (videoElement) {
346
+ MediaManager.cleanup(videoElement);
347
+ videoElement = null;
348
+ }
349
+ });
350
+
351
+ /**
352
+ * Checks if the file of a URL is accessible. The check follows the kind of file: an image is loaded with the
353
+ * Image() constructor to avoid CORS issues with external services (picsum.photos, etc.), audio and video are asked
354
+ * for their metadata (an image load always fails on them, which showed every sound and film as missing), and a
355
+ * document has no check that works across origins, so it counts as there (its tile opens it in a new tab).
356
+ */
357
+ async function checkFileExists(url: string): Promise<boolean> {
358
+ const fileType = getFileType(url);
359
+ if (fileType === 'document') return true;
360
+
361
+ return new Promise((resolve) => {
362
+ // A file that answers nothing within 5 seconds counts as missing
363
+ const timeoutId = setTimeout(() => resolve(false), 5000);
364
+ const finish = (exists: boolean) => {
365
+ clearTimeout(timeoutId);
366
+ resolve(exists);
367
+ };
368
+
369
+ if (fileType === 'audio' || fileType === 'video') {
370
+ const probe = document.createElement(fileType);
371
+ probe.preload = 'metadata';
372
+ probe.onloadedmetadata = () => finish(true);
373
+ probe.onerror = () => finish(false);
374
+ probe.src = url;
375
+ return;
376
+ }
377
+
378
+ const img = new Image();
379
+ img.onload = () => finish(true);
380
+ img.onerror = () => finish(false);
381
+ img.src = url;
382
+ });
383
+ }
384
+
385
+ // Update error state handling
386
+ async function updateErrorState(url: string) {
387
+ isChecking = true;
388
+ if (!url) {
389
+ hasError = true;
390
+ isChecking = false;
391
+ return;
392
+ }
393
+ hasError = !(await checkFileExists(url));
394
+ isChecking = false;
395
+ }
396
+
397
+ // Watch previewUrl changes
398
+ $: if (previewUrl) {
399
+ updateErrorState(previewUrl);
400
+ } else {
401
+ hasError = false;
402
+ isChecking = false;
403
+ }
404
+
405
+ /**
406
+ * Trims a string to a maximum length and adds ellipsis if needed
407
+ * @param str - String to trim
408
+ * @param maxLength - Maximum length before trimming
409
+ * @returns Trimmed string with ellipsis if needed
410
+ */
411
+ function trimString(str: string, maxLength: number = 30): string {
412
+ if (str.length <= maxLength) return str;
413
+ return str.substring(0, maxLength - 3) + '...';
414
+ }
415
+
416
+ // Update the reactive statement to use trimString
417
+ $: displayLabel = value ? trimString(getFileName(value)) : header?.label || label;
418
+ $: previewUrl = getPreviewUrl(value);
419
+
420
+ // Add hash extraction helper
421
+ function getThumbHash(value: string | FileValue | null | undefined): string | undefined {
422
+ if (!value) return undefined;
423
+ if (typeof value === 'object' && 'hash' in value) {
424
+ return value.hash;
425
+ }
426
+ return undefined;
427
+ }
428
+
429
+ // Update the reactive statement to use getThumbHash
430
+ $: thumbHash = getThumbHash(value);
431
+
432
+ // Add event listeners for media elements
433
+ function setupMediaElement(element: HTMLMediaElement) {
434
+ if (!element) return;
435
+
436
+ element.addEventListener('play', () => {
437
+ // console.log('Media started playing');
438
+ isPlaying = true;
439
+ });
440
+
441
+ element.addEventListener('pause', () => {
442
+ // console.log('Media paused');
443
+ isPlaying = false;
444
+ });
445
+
446
+ element.addEventListener('ended', () => {
447
+ // console.log('Media ended');
448
+ isPlaying = false;
449
+ });
450
+
451
+ // Add listener for when the media is stopped externally
452
+ element.addEventListener('timeupdate', () => {
453
+ if (element.paused && isPlaying) {
454
+ isPlaying = false;
455
+ }
456
+ });
457
+ }
458
+
459
+ // Update bindings to setup media elements
460
+ $: if (audioElement) setupMediaElement(audioElement);
461
+ $: if (videoElement) setupMediaElement(videoElement);
462
+
463
+ // Add placeholder text logic
464
+ function getAddToEditorLabelSingular(
465
+ fileTypes: string[],
466
+ translate: Translate<EditorMessageKey>
467
+ ): string {
468
+ if (!fileTypes || fileTypes.includes('*')) return translate('editor.file.useFile');
469
+ const type = fileTypes[0].split('/')[0];
470
+ switch (type) {
471
+ case 'image':
472
+ return translate('editor.file.useImage');
473
+ case 'video':
474
+ return translate('editor.file.useVideo');
475
+ case 'audio':
476
+ return translate('editor.file.useAudio');
477
+ case 'document':
478
+ return translate('editor.file.useDocument');
479
+ default:
480
+ return translate('editor.file.useFile');
481
+ }
482
+ }
483
+
484
+ function getCurrentFileId(): string | null {
485
+ if (value && typeof value === 'object' && value.id) return value.id;
486
+ return null;
487
+ }
488
+
489
+ function syncFileBrowserInitialSelection() {
490
+ const fileId = getCurrentFileId();
491
+ persistentSelectStore.clearSelections(fileBrowserFilter);
492
+ if (fileId) {
493
+ persistentSelectStore.setSelections(fileBrowserFilter, [fileId]);
494
+ if (fileBrowserFilter !== 'all') {
495
+ persistentSelectStore.setSelections('all', [fileId]);
496
+ }
497
+ }
498
+ }
499
+
500
+ function getPlaceholderText(fileTypes: string[], translate: Translate<EditorMessageKey>): string {
501
+ if (!fileTypes || fileTypes.includes('*')) return translate('editor.file.addFile');
502
+ const type = fileTypes[0].split('/')[0];
503
+ switch (type) {
504
+ case 'image':
505
+ return translate('editor.file.addImage');
506
+ case 'video':
507
+ return translate('editor.file.addVideo');
508
+ case 'audio':
509
+ return translate('editor.file.addAudio');
510
+ case 'document':
511
+ return translate('editor.file.addDocument');
512
+ default:
513
+ return translate('editor.file.addFile');
514
+ }
515
+ }
516
+
517
+ function getInitialFileBrowserFilter(
518
+ fileTypes: string[]
519
+ ): 'all' | 'image' | 'video' | 'audio' | 'document' | 'font' | 'svg' {
520
+ if (!fileTypes || fileTypes.includes('*')) return 'all';
521
+ const type = fileTypes[0].split('/')[0];
522
+ if (fileTypes[0] === 'image/svg+xml') return 'svg';
523
+ if (type === 'font') return 'font';
524
+ if (['image', 'video', 'audio'].includes(type)) return type as 'image' | 'video' | 'audio';
525
+ if (type === 'application' || type === 'text') return 'document';
526
+ return 'all';
527
+ }
528
+
529
+ $: fileBrowserFilter = getInitialFileBrowserFilter(fileTypes);
530
+ $: fileBrowserRestrictUpload = fileBrowserFilter !== 'all';
531
+ $: fileBrowserAddToEditorLabelSingular = getAddToEditorLabelSingular(fileTypes, $t);
532
+
533
+ function handleContentRemoval(e: MouseEvent) {
534
+ e.stopPropagation();
535
+ e.preventDefault();
536
+ value = '';
537
+ onChange('');
538
+ isPlaying = false;
539
+ hasError = false;
540
+
541
+ if (audioElement) {
542
+ MediaManager.pause(audioElement);
543
+ MediaManager.cleanup(audioElement);
544
+ audioElement = null;
545
+ }
546
+ if (videoElement) {
547
+ MediaManager.pause(videoElement);
548
+ MediaManager.cleanup(videoElement);
549
+ videoElement = null;
550
+ }
551
+
552
+ onChange('');
553
+ }
554
+
555
+ function handleControllerClick(e: MouseEvent) {
556
+ const target = e.target as HTMLElement;
557
+ if (target.closest('.browser-ic-clear-btn')) return;
558
+ openFileBrowser();
559
+ }
528
560
  </script>
529
561
 
530
- <!-- Main container with updated styling -->
531
- <div bind:this={controllerElement} class="flex flex-col gap-2 widgetic-colors">
532
- <div class="flex items-center w-full relative">
533
- <div class="flex-1 min-w-0">
534
- <InputControllerHeader label={header?.label || label} helpText={header?.helpText} />
535
- </div>
536
-
537
- <div class="absolute end-0">
538
- <!-- svelte-ignore a11y_click_events_have_key_events -->
539
- <!-- svelte-ignore a11y_no_static_element_interactions -->
540
- <!-- svelte-ignore a11y_click_events_have_key_events -->
541
- <!-- svelte-ignore a11y_no_static_element_interactions -->
542
- <div
543
- class="browser-input-controller-field cursor-pointer h-[48px] w-[185px] rounded-large border border-grey2 flex items-center bg-grey1 transition-colors duration-200 hover:border-forest-green relative"
544
- on:click={handleControllerClick}
545
- on:keydown={(e) => e.key === 'Enter' && openFileBrowser()}
546
- role="button"
547
- tabindex={0}
548
- >
549
- <!-- File name or placeholder -->
550
- <div class="browser-input-controller-label flex-1 min-w-0 px-4 flex items-center h-full">
551
- <span class="subtext {value ? 'text-grey7' : 'text-grey3'} truncate inline-block">
552
- {value ? getFileName(value) : getPlaceholderText(fileTypes, $t)}
553
- </span>
554
- </div>
555
-
556
- <!-- Preview area -->
557
- <div class="flex-none h-full flex items-center pe-[16px]">
558
- {#if isChecking}
559
- <!-- Loading state -->
560
- <div class="w-8 h-7 bg-gray-100 rounded-lg"></div>
561
- {:else if previewUrl && !hasError}
562
- <!-- File preview content -->
563
- <!-- svelte-ignore a11y_click_events_have_key_events -->
564
- {#if getFileType(previewUrl) === 'image'}
565
- <div
566
- class="w-8 h-7 overflow-hidden rounded-lg bg-gray-100 cursor-pointer hover:opacity-80 transition-opacity"
567
- on:click|stopPropagation={() => window.open(previewUrl, '_blank')}
568
- role="button"
569
- tabindex={0}
570
- >
571
- {#if thumbHash}
572
- <div on:error={() => hasError = true}>
573
- <ThumbHashImage
574
- src={previewUrl || ''}
575
- alt={displayLabel || ''}
576
- thumbhash={thumbHash}
577
- class_="w-full h-full object-cover"
578
- />
579
- </div>
580
- {:else}
581
- <img
582
- src={previewUrl}
583
- alt={displayLabel || ''}
584
- class="w-full h-full object-cover"
585
- on:error={() => hasError = true}
586
- />
587
- {/if}
588
- </div>
589
- {:else if getFileType(previewUrl) === 'video'}
590
- <div
591
- class="relative w-8 h-7 overflow-hidden rounded-lg cursor-pointer"
592
- on:click|stopPropagation={togglePlayback}
593
- role="button"
594
- tabindex={0}
595
- >
596
- <!-- Video element always present -->
597
- <!-- svelte-ignore a11y-media-has-caption -->
598
- <video
599
- bind:this={videoElement}
600
- src={previewUrl}
601
- class="absolute inset-0 w-full h-full object-cover {!isPlaying ? 'opacity-0' : 'opacity-100'}"
602
- on:error={() => hasError = true}
603
- >
604
- <track kind="captions" />
605
- </video>
606
-
607
- <!-- Thumbnail image shown when not playing -->
608
- {#if !isPlaying}
609
- {#if thumbHash}
610
- <div on:error={() => hasError = true}>
611
- <ThumbHashImage
612
- src={getVideoThumbnailUrl(previewUrl) || ''}
613
- alt={displayLabel || ''}
614
- thumbhash={thumbHash}
615
- class_="w-full h-full object-cover hover:opacity-80 transition-opacity"
616
- />
617
- </div>
618
- {:else}
619
- <img
620
- src={getVideoThumbnailUrl(previewUrl)}
621
- alt={getFileName(value)}
622
- class="w-full h-full object-cover hover:opacity-80 transition-opacity"
623
- on:error={() => hasError = true}
624
- />
625
- {/if}
626
- {/if}
627
-
628
- <!-- Controls overlay -->
629
- <div
630
- class="absolute inset-0 flex items-center justify-center {!isPlaying ? 'bg-black bg-opacity-30' : 'bg-transparent hover:bg-black hover:bg-opacity-30'}"
631
- >
632
- <img
633
- src={isPlaying ? icPlayerPause : icPlayerPlay}
634
- alt={isPlaying ? $t('editor.file.pause') : $t('editor.file.play')}
635
- class="w-5 h-5 {isPlaying ? 'opacity-0 hover:opacity-100' : 'opacity-100'} transition-opacity"
636
- />
637
- </div>
638
- </div>
639
- {:else if getFileType(previewUrl) === 'audio'}
640
- <div
641
- class="relative w-8 h-7 cursor-pointer"
642
- on:click|stopPropagation={togglePlayback}
643
- role="button"
644
- tabindex={0}
645
- >
646
- <!-- Audio icon -->
647
- <img
648
- src={icAudio}
649
- alt={getFileName(value)}
650
- class="w-full h-full object-contain"
651
- />
652
-
653
- <!-- Audio element hidden but needed for playback -->
654
- <!-- svelte-ignore a11y-media-has-caption -->
655
- <audio
656
- bind:this={audioElement}
657
- src={previewUrl}
658
- class="hidden"
659
- on:error={() => hasError = true}
660
- >
661
- <track kind="captions" />
662
- </audio>
663
-
664
- <!-- Controls overlay -->
665
- <div
666
- class="absolute inset-0 flex items-center justify-center"
667
- >
668
- <img
669
- src={isPlaying ? icPlayerPause : icPlayerPlay}
670
- alt={isPlaying ? $t('editor.file.pause') : $t('editor.file.play')}
671
- class="w-5 h-5"
672
- />
673
- </div>
674
- </div>
675
- {:else if getFileType(previewUrl) === 'document'}
676
- <div
677
- class="cursor-pointer hover:opacity-80 transition-opacity"
678
- on:click|stopPropagation={() => window.open(previewUrl, '_blank')}
679
- role="button"
680
- tabindex={0}
681
- >
682
- <img
683
- src={icDocument}
684
- alt={displayLabel}
685
- class="w-8 h-7 object-contain"
686
- />
687
- </div>
688
- {:else}
689
- <img
690
- src={icFolder}
691
- alt={displayLabel}
692
- class="w-8 h-7 object-contain"
693
- />
694
- {/if}
695
- {:else if previewUrl}
696
- <!-- Error state -->
697
- <img
698
- src={icError}
699
- alt={$t('editor.file.notFound')}
700
- class="w-8 h-7 object-contain"
701
- />
702
- {:else}
703
- <!-- Empty state -->
704
- <img
705
- src={icFolder}
706
- alt={$t('editor.file.emptyFolder')}
707
- class="w-8 h-7 object-contain"
708
- />
709
- {/if}
710
-
711
- <!-- Close button - moved outside the content conditions -->
712
- {#if value}
713
- <button
714
- type="button"
715
- class="browser-ic-clear-btn absolute top-[-4px] end-[-4px] w-4 h-4 rounded-full hover:bg-grey2 transition-colors flex items-center justify-center"
716
- on:click={handleContentRemoval}
717
- aria-label={$t('editor.file.clear')}
718
- >
719
- <div class="w-4 h-4 flex items-center justify-center">
720
- <X class="w-4! h-4!" />
721
- </div>
722
- </button>
723
- {/if}
724
- </div>
725
- </div>
726
- </div>
727
- </div>
562
+ <!-- IC Browser row: 185×36, one horizontal line (text → thumbnail → remove, or placeholder → browse). -->
563
+ <div bind:this={controllerElement} class="browser-ic w-full">
564
+ <InputControllerRow label={header?.label || label} helpText={header?.helpText}>
565
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
566
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
567
+ <div
568
+ class="browser-input-controller-field flex h-9 w-full min-w-0 cursor-pointer items-center gap-2 rounded-lg bg-accent ps-3 pe-1 transition-colors duration-fast hover:bg-accent-hover focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background {hasError &&
569
+ previewUrl
570
+ ? 'border border-destructive'
571
+ : ''}"
572
+ on:click={handleControllerClick}
573
+ on:keydown={(e) => e.key === 'Enter' && openFileBrowser()}
574
+ role="button"
575
+ tabindex={0}
576
+ >
577
+ <!-- File name or placeholder -->
578
+ <span
579
+ class="browser-input-controller-label truncate text-body {value
580
+ ? 'w-[101px] shrink-0 text-foreground'
581
+ : 'min-w-0 flex-1 text-muted-foreground'}"
582
+ >
583
+ {value ? getFileName(value) : getPlaceholderText(fileTypes, $t)}
584
+ </span>
585
+
586
+ {#if value}
587
+ {#if isChecking}
588
+ <!-- Loading state -->
589
+ <div class="size-7 shrink-0 animate-pulse rounded-lg bg-muted"></div>
590
+ {:else if previewUrl && !hasError}
591
+ <!-- File preview content (28×28 thumbnail) -->
592
+ {#if getFileType(previewUrl) === 'image'}
593
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
594
+ <div
595
+ class="browser-input-controller-thumbnail size-7 shrink-0 overflow-hidden rounded-lg border border-border bg-background"
596
+ on:click|stopPropagation={() => window.open(previewUrl, '_blank')}
597
+ role="button"
598
+ tabindex={0}
599
+ >
600
+ {#if thumbHash}
601
+ <div on:error={() => (hasError = true)}>
602
+ <ThumbHashImage
603
+ src={previewUrl || ''}
604
+ alt={displayLabel || ''}
605
+ thumbhash={thumbHash}
606
+ class_="size-full object-cover"
607
+ />
608
+ </div>
609
+ {:else}
610
+ <img
611
+ src={previewUrl}
612
+ alt={displayLabel || ''}
613
+ class="size-full object-cover"
614
+ on:error={() => (hasError = true)}
615
+ />
616
+ {/if}
617
+ </div>
618
+ {:else if getFileType(previewUrl) === 'video'}
619
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
620
+ <div
621
+ class="browser-input-controller-thumbnail relative flex size-7 shrink-0 items-center justify-center overflow-hidden rounded-lg border border-border bg-background"
622
+ on:click|stopPropagation={togglePlayback}
623
+ role="button"
624
+ tabindex={0}
625
+ aria-label={isPlaying ? $t('editor.file.pause') : $t('editor.file.play')}
626
+ >
627
+ {#if !isPlaying}
628
+ <IconVideo class="size-4 stroke-[1.333] text-muted-foreground" />
629
+ {/if}
630
+ <!-- The video plays inside the tile (it is see-through while paused, the camera icon shows) -->
631
+ <!-- svelte-ignore a11y-media-has-caption -->
632
+ <video
633
+ bind:this={videoElement}
634
+ src={previewUrl}
635
+ class="absolute inset-0 size-full object-cover {isPlaying
636
+ ? 'opacity-100'
637
+ : 'opacity-0'}"
638
+ on:error={() => (hasError = true)}
639
+ >
640
+ <track kind="captions" />
641
+ </video>
642
+ {#if isPlaying}
643
+ <!-- Playing: a pause icon lies over the frame on hover -->
644
+ <span
645
+ class="absolute inset-0 flex items-center justify-center bg-transparent opacity-0 transition-opacity duration-fast hover:bg-foreground/40 hover:opacity-100"
646
+ aria-hidden="true"
647
+ >
648
+ <IconPlayerPause class="size-4 stroke-[1.333] text-primary-foreground" />
649
+ </span>
650
+ {/if}
651
+ </div>
652
+ {:else if getFileType(previewUrl) === 'audio'}
653
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
654
+ <div
655
+ class="browser-input-controller-thumbnail relative flex size-7 shrink-0 items-center justify-center rounded-lg border border-border bg-background"
656
+ on:click|stopPropagation={togglePlayback}
657
+ role="button"
658
+ tabindex={0}
659
+ aria-label={isPlaying ? $t('editor.file.pause') : $t('editor.file.play')}
660
+ >
661
+ <!-- While the sound plays the tile shows a pause icon, so the state is seen as well as heard -->
662
+ {#if isPlaying}
663
+ <IconPlayerPause class="size-4 stroke-[1.333] text-foreground" />
664
+ {:else}
665
+ <IconMusic class="size-4 stroke-[1.333] text-muted-foreground" />
666
+ {/if}
667
+ <!-- Audio element hidden but needed for playback -->
668
+ <!-- svelte-ignore a11y-media-has-caption -->
669
+ <audio
670
+ bind:this={audioElement}
671
+ src={previewUrl}
672
+ class="hidden"
673
+ on:error={() => (hasError = true)}
674
+ >
675
+ <track kind="captions" />
676
+ </audio>
677
+ </div>
678
+ {:else if getFileType(previewUrl) === 'document'}
679
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
680
+ <div
681
+ class="browser-input-controller-thumbnail flex size-7 shrink-0 items-center justify-center rounded-lg border border-border bg-background"
682
+ on:click|stopPropagation={() => window.open(previewUrl, '_blank')}
683
+ role="button"
684
+ tabindex={0}
685
+ >
686
+ <IconFileText class="size-4 stroke-[1.333] text-muted-foreground" />
687
+ </div>
688
+ {:else}
689
+ <div
690
+ class="browser-input-controller-thumbnail flex size-7 shrink-0 items-center justify-center rounded-lg border border-border bg-background"
691
+ >
692
+ <IconFolderOpen class="size-4 stroke-[1.333] text-muted-foreground" />
693
+ </div>
694
+ {/if}
695
+ {:else if previewUrl && hasError}
696
+ <!-- Error state thumbnail -->
697
+ <div
698
+ class="browser-input-controller-thumbnail flex size-7 shrink-0 items-center justify-center rounded-lg border border-destructive bg-background"
699
+ aria-label={$t('editor.file.notFound')}
700
+ >
701
+ <IconAlertTriangle class="size-4 stroke-[1.333] text-destructive" />
702
+ </div>
703
+ {:else}
704
+ <div
705
+ class="browser-input-controller-thumbnail flex size-7 shrink-0 items-center justify-center rounded-lg border border-border bg-background"
706
+ >
707
+ <IconFolderOpen class="size-4 stroke-[1.333] text-muted-foreground" />
708
+ </div>
709
+ {/if}
710
+
711
+ <!-- Remove control (24×24), inline at the end of the row -->
712
+ <button
713
+ type="button"
714
+ class="browser-ic-clear-btn flex size-6 shrink-0 items-center justify-center rounded-lg transition-colors duration-fast hover:bg-accent-hover"
715
+ on:click|stopPropagation={handleContentRemoval}
716
+ aria-label={$t('editor.file.clear')}
717
+ >
718
+ <IconX class="size-4 stroke-[1.333] text-muted-foreground" />
719
+ </button>
720
+ {:else if isChecking}
721
+ <div class="ms-auto size-7 shrink-0 animate-pulse rounded-lg bg-muted"></div>
722
+ {:else}
723
+ <!-- Empty state: browse affordance (28×28) at the end -->
724
+ <button
725
+ type="button"
726
+ class="browser-input-controller-browse ms-auto flex size-7 shrink-0 items-center justify-center rounded-lg"
727
+ on:click|stopPropagation={openFileBrowser}
728
+ aria-label={$t('editor.file.emptyFolder')}
729
+ >
730
+ <IconFolderOpen class="size-4 stroke-[1.333] text-muted-foreground" />
731
+ </button>
732
+ {/if}
733
+ </div>
734
+ </InputControllerRow>
728
735
  </div>
729
736
 
730
737
  {#if isFileBrowserOpen}
731
- <Portal target={portalTarget}>
732
- <div
733
- class="browser-input-file-browser-overlay pointer-events-auto absolute inset-0 z-[999999] flex flex-col overflow-hidden bg-black/40 p-0"
734
- >
735
- <!-- svelte-ignore a11y_click_events_have_key_events -->
736
- <!-- svelte-ignore a11y_no_static_element_interactions -->
737
- <div class="browser-input-file-browser-backdrop absolute inset-0" on:click={closeFileBrowser}></div>
738
-
739
- <div
740
- class="browser-input-file-browser-dialog browser-input-file-browser-dialog-animate relative z-[999999] flex min-h-0 w-full flex-col overflow-hidden bg-white"
741
- class:absolute={fillEditorPanel}
742
- class:inset-0={fillEditorPanel}
743
- class:h-full={fillEditorPanel}
744
- class:max-w-none={fillEditorPanel}
745
- class:rounded-none={fillEditorPanel}
746
- class:shadow-none={fillEditorPanel}
747
- class:max-w-[520px]={!fillEditorPanel}
748
- class:flex-1={!fillEditorPanel}
749
- class:min-h-[550px]={fillEditorPanel}
750
- class:self-center={!fillEditorPanel}
751
- class:mx-auto={!fillEditorPanel}
752
- class:rounded-large={!fillEditorPanel}
753
- class:shadow-2xl={!fillEditorPanel}
754
- >
755
- <div class="browser-input-file-browser-header relative flex h-[48px] shrink-0 items-center border-b border-grey2 ps-4 pe-8">
756
- <span class="body-medium text-grey7">{$t('editor.file.dialogTitle')}</span>
757
- <button
758
- type="button"
759
- class="browser-input-file-browser-close inline-flex h-6 w-6 items-center justify-center p-0"
760
- style="position:absolute;top:4px;inset-inline-end:4px;"
761
- on:click={closeFileBrowser}
762
- aria-label={$t('editor.file.closeDialog')}
763
- >
764
- <X class="h-6! w-6!" />
765
- </button>
766
- </div>
767
-
768
- <div class="browser-input-file-browser-body flex min-h-0 flex-1 flex-col overflow-hidden">
769
- <!-- With a media library the File Browser keeps nothing about this visit (the filter it was left on, the
738
+ <Portal target={portalTarget}>
739
+ <div
740
+ class="browser-input-file-browser-overlay pointer-events-auto absolute inset-0 z-[999999] flex flex-col overflow-hidden bg-muted-foreground/80 p-0 backdrop-blur-[3px]"
741
+ >
742
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
743
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
744
+ <div
745
+ class="browser-input-file-browser-backdrop absolute inset-0"
746
+ on:click={closeFileBrowser}
747
+ ></div>
748
+
749
+ <div
750
+ class="browser-input-file-browser-dialog browser-input-file-browser-dialog-animate relative z-[999999] flex min-h-0 w-full flex-col overflow-hidden border border-border bg-background"
751
+ class:absolute={fillEditorPanel}
752
+ class:inset-0={fillEditorPanel}
753
+ class:h-full={fillEditorPanel}
754
+ class:max-w-none={fillEditorPanel}
755
+ class:rounded-none={fillEditorPanel}
756
+ class:shadow-none={fillEditorPanel}
757
+ class:max-w-[520px]={!fillEditorPanel}
758
+ class:flex-1={!fillEditorPanel}
759
+ class:min-h-[550px]={fillEditorPanel}
760
+ class:self-center={!fillEditorPanel}
761
+ class:mx-auto={!fillEditorPanel}
762
+ class:rounded-xl={!fillEditorPanel}
763
+ >
764
+ <div
765
+ class="browser-input-file-browser-header relative flex h-12 shrink-0 items-center border-b border-border ps-4 pe-8"
766
+ >
767
+ <span class="text-body-medium text-foreground">{$t('editor.file.dialogTitle')}</span>
768
+ <button
769
+ type="button"
770
+ class="browser-input-file-browser-close inline-flex h-6 w-6 items-center justify-center p-0"
771
+ style="position:absolute;top:4px;inset-inline-end:4px;"
772
+ on:click={closeFileBrowser}
773
+ aria-label={$t('editor.file.closeDialog')}
774
+ >
775
+ <IconX class="size-4 stroke-[1.333]" />
776
+ </button>
777
+ </div>
778
+
779
+ <div class="browser-input-file-browser-body flex min-h-0 flex-1 flex-col overflow-hidden">
780
+ <!-- With a media library the File Browser keeps nothing about this visit (the filter it was left on, the
770
781
  folder it was left in) in the page's localStorage: that storage belongs to the page this editor sits in,
771
782
  which can be a partner's. Without one (the Widgetic site) it remembers them, as it always did. -->
772
- <FileBrowser
773
- class="h-full min-h-0 flex-1"
774
- instanceId={`props-editor-browser-input-${fileBrowserFilter}`}
775
- initialFilter={fileBrowserFilter}
776
- restrictUpload={fileBrowserRestrictUpload}
777
- useDemoContent={false}
778
- mediaLibrary={getEditorMediaLibrary()}
779
- persistHistory={!getEditorMediaLibrary()}
780
- allowSelecting={true}
781
- showAddToEditor={true}
782
- maxSelections={1}
783
- activeFileId={getCurrentFileId()}
784
- addToEditorLabel={fileBrowserAddToEditorLabelSingular}
785
- locale={$fileBrowserLanguage.locale ?? undefined}
786
- messages={$fileBrowserLanguage.messages ?? null}
787
- on:select={handleFileBrowserSelect}
788
- />
789
- </div>
790
- </div>
791
- </div>
792
- </Portal>
783
+ <FileBrowser
784
+ class="h-full min-h-0 flex-1"
785
+ instanceId={`props-editor-browser-input-${fileBrowserFilter}`}
786
+ initialFilter={fileBrowserFilter}
787
+ restrictUpload={fileBrowserRestrictUpload}
788
+ useDemoContent={false}
789
+ mediaLibrary={getEditorMediaLibrary()}
790
+ persistHistory={!getEditorMediaLibrary()}
791
+ allowSelecting={true}
792
+ showAddToEditor={true}
793
+ maxSelections={1}
794
+ activeFileId={getCurrentFileId()}
795
+ addToEditorLabel={fileBrowserAddToEditorLabelSingular}
796
+ locale={$fileBrowserLanguage.locale ?? undefined}
797
+ messages={$fileBrowserLanguage.messages ?? null}
798
+ on:select={handleFileBrowserSelect}
799
+ />
800
+ </div>
801
+ </div>
802
+ </div>
803
+ </Portal>
793
804
  {/if}
794
805
 
795
806
  <style>
796
- .browser-input-file-browser-close {
797
- position: absolute;
798
- top: 4px;
799
- inset-inline-end: 4px;
800
- }
801
-
802
- .browser-input-file-browser-dialog-animate {
803
- transform-origin: center center;
804
- animation: browser-input-fb-scale-in 0.22s cubic-bezier(0.4, 0, 0.2, 1);
805
- }
806
-
807
- @keyframes browser-input-fb-scale-in {
808
- from {
809
- transform: scale(0.94);
810
- opacity: 0;
811
- }
812
- to {
813
- transform: scale(1);
814
- opacity: 1;
815
- }
816
- }
807
+ .browser-input-file-browser-close {
808
+ position: absolute;
809
+ top: 4px;
810
+ inset-inline-end: 4px;
811
+ }
812
+
813
+ .browser-input-file-browser-dialog-animate {
814
+ transform-origin: center center;
815
+ animation: browser-input-fb-scale-in 0.22s cubic-bezier(0.4, 0, 0.2, 1);
816
+ }
817
+
818
+ @keyframes browser-input-fb-scale-in {
819
+ from {
820
+ transform: scale(0.94);
821
+ opacity: 0;
822
+ }
823
+ to {
824
+ transform: scale(1);
825
+ opacity: 1;
826
+ }
827
+ }
817
828
  </style>
818
-