@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
@@ -19,2251 +19,2130 @@
19
19
  -->
20
20
 
21
21
  <script module lang="ts">
22
- /** Declared props contract — export lets below are annotated from it so the
23
- * interface cannot drift from what the component actually reads. */
24
- export interface FontInputControllerProps {
25
- label?: string;
26
- style?: string;
27
- value?: { family: string; weight: string; category: string } | string | null;
28
- onChange?: (newValue: { family: string; weight: string; category: string }) => void;
29
- description?: string;
30
- controllerId: string;
31
- openDropdowns: Writable<Set<string>>;
32
- toggleDropdown: (id: string) => void;
33
- hideRecentFromList?: boolean;
34
- hideTrashIcon?: boolean;
35
- }
22
+ /** Declared props contract — export lets below are annotated from it so the
23
+ * interface cannot drift from what the component actually reads. */
24
+ export interface FontInputControllerProps {
25
+ label?: string;
26
+ style?: string;
27
+ value?: { family: string; weight: string; category: string } | string | null;
28
+ onChange?: (newValue: { family: string; weight: string; category: string }) => void;
29
+ description?: string;
30
+ controllerId: string;
31
+ openDropdowns: Writable<Set<string>>;
32
+ toggleDropdown: (id: string) => void;
33
+ hideRecentFromList?: boolean;
34
+ hideTrashIcon?: boolean;
35
+ }
36
36
  </script>
37
37
 
38
38
  <script lang="ts">
39
- // Svelte imports
40
- import { onMount, onDestroy, tick } from 'svelte';
41
- const browser = typeof window !== 'undefined';
42
-
43
- // Shadcn Compound Components
44
- import { Popover, Command, EmptyState } from '@widgetic/design-system/components';
45
-
46
- // Tabler Icons
47
- import { Check, IconCloudUpload, IconCaretDownFilled, IconArrowDown, IconArrowUp } from '@widgetic/design-system/icons';
48
-
49
- // Asset imports
50
- import icTrash from '../../assets/icons/trash.svg?url';
51
- import fontsJsonUrl from '../../assets/fonts.json?url';
52
-
53
- // Config imports
54
- import { config as appConfig } from '../../config';
55
- import {
56
- fontUtils,
57
- fontCategories,
58
- type FontItem,
59
- type RecentFont,
60
- recentFontsStore
61
- } from '../../utils/fontUtils';
62
- import type { FontData } from '../../utils/FontManager';
63
- import FontManager, { mapGoogleVariantIdsToWeightNames } from '../../utils/FontManager';
64
-
65
- import { shouldSkipFont } from '../../utils/skipFonts';
66
- import { escapeHtml, cssQuotedString } from '../../utils/htmlSafety';
67
- import { acquirePortalHost, releasePortalHost, listenForScroll, queryInTreeOf } from '../../utils/shadowDom';
68
- import { readEditorStorageValue, writeEditorStorageValue } from '../../utils/editorStorage';
69
- import type { Writable } from 'svelte/store';
70
-
71
- import { InputControllerHeader } from './index';
72
-
73
- // Import shared components
74
- import { SearchInput } from '@widgetic/design-system/components';
75
- import CategoryTabs from './shared/CategoryTabs.svelte';
76
- import { RecentItemsSection, ItemGrid } from './shared';
77
- import { useEditorLanguage } from '../../i18n/language';
78
- import { categoryLabel, fontWeightLabel } from '../../i18n/labels';
79
-
80
- // The words of the editor in the language of the page.
81
- const { t } = useEditorLanguage();
82
-
83
-
84
- const FONT_FILTER_KEY = (id: string) => `font-specific-filter-state-${id}`;
85
- const FONT_WEIGHT_KEY = (id: string) => `font-weight-state-${id}`;
86
- const MAX_RECENT_FONTS = 3;
87
-
88
- // Then continue with the rest of the declarations
89
- type FilterType = typeof fontCategories.types[number];
90
- let currentFilter: FilterType = 'All'; // Default to 'All'
91
- let lastActiveFilter: FilterType = 'All'; // Add this declaration
92
- let filterOptions: FilterType[] = [...fontCategories.types];
93
-
94
- /**
95
- * Component Props
96
- * @prop {string} label - Display label for the font selector
97
- * @prop {string} value - Currently selected font family
98
- * @prop {Function} onChange - Callback when font selection changes
99
- * @prop {InputControllerConfig} config - Configuration options
100
- * @prop {string} description - Optional help text
101
- * @prop {string} controllerId - Unique identifier for this controller
102
- * @prop {any} openDropdowns - Store tracking open dropdown states
103
- * @prop {Function} toggleDropdown - Function to toggle dropdown state
104
- * @prop {Function} onFocus - Optional focus handler
105
- */
106
- export let label: FontInputControllerProps['label'] = '';
107
- let className = '';
108
- export { className as class };
109
- export let style: FontInputControllerProps['style'] = '';
110
- export let value: FontInputControllerProps['value'] = null;
111
- export let onChange: FontInputControllerProps['onChange'] = undefined;
112
- export let description: FontInputControllerProps['description'] = undefined;
113
- export let controllerId: FontInputControllerProps['controllerId'];
114
- export let openDropdowns: FontInputControllerProps['openDropdowns'];
115
- export let toggleDropdown: FontInputControllerProps['toggleDropdown'];
116
-
117
- // Initialize timeouts
118
- let scrollTimeout: ReturnType<typeof setTimeout> | null = null;
119
-
120
-
121
- // Font weight state - remove localStorage check on init
122
- let selectedWeight = `${controllerId}-Regular`;
123
- let availableWeights: string[] = ['Regular', 'Medium', 'SemiBold', 'Bold'];
124
- let fontCatalogFallbackWarned = false;
125
-
126
- // Font search and filter state
127
- let allFonts: FontItem[] = [];
128
- let recentFonts: FontItem[] = [];
129
- let filteredFonts: FontData[] = [];
130
- let searchTerm = '';
131
- let initialFontNumber = FontManager.initialFontNumber;
132
- const SEARCH_BATCH_SIZE = FontManager.BATCH_SIZE;
133
-
134
- // Font loading optimization
135
- let fontListContainer: HTMLElement;
136
- // The control's own element: it says which tree (the page or a module's shadow root) to listen for scrolling in
137
- let controllerElement: HTMLDivElement | undefined;
138
- let familyTriggerEl: HTMLDivElement | undefined;
139
- let familyPopoverStyle = '';
140
- let familyPopoverSide: 'top' | 'bottom' = 'bottom';
141
- let fontObserver = new IntersectionObserver(() => {});
142
-
143
- // Initialize FontManager instance
144
- let fontManagerInstance: FontManager;
145
- let buttonWidth = 0;
146
-
147
- // Add these variables for search
148
- let activeSearchIndex = -1;
149
-
150
- // Add loading state
151
- let isLoadingBatch = false;
152
- let isInitialLoading = true; // Start with loading state true
153
-
154
- // Add new prop for controlling font list behavior
155
- export let hideRecentFromList: FontInputControllerProps['hideRecentFromList'] = false;
156
- export let hideTrashIcon: FontInputControllerProps['hideTrashIcon'] = true;
157
-
158
- function updateFamilyPopoverBox() {
159
- if (!familyTriggerEl || typeof window === 'undefined') return;
160
- const rect = familyTriggerEl.getBoundingClientRect();
161
- const pad = 12;
162
- const viewportH = window.visualViewport?.height ?? window.innerHeight;
163
- const below = viewportH - rect.bottom - pad;
164
- const above = rect.top - pad;
165
- const openAbove = above > below;
166
- familyPopoverSide = openAbove ? 'top' : 'bottom';
167
- const available = Math.max(0, openAbove ? above : below);
168
- const height = Math.min(565, available);
169
- const width = Math.min(374, Math.max(240, window.innerWidth - 16));
170
- familyPopoverStyle = `width: ${width}px; height: ${height}px; max-width: calc(100vw - 16px); max-height: ${height}px;`;
171
- }
172
-
173
- function handleFamilyPopoverViewportChange() {
174
- if ($openDropdowns?.has(controllerId)) {
175
- updateFamilyPopoverBox();
176
- }
177
- }
178
-
179
- function coerceFontValue(raw: typeof value): { family: string; weight: string; category: string } | null {
180
- if (!raw) return null;
181
- if (typeof raw === 'object' && raw.family) {
182
- return {
183
- family: raw.family,
184
- weight: raw.weight || 'Regular',
185
- category: raw.category || 'Sans Serif',
186
- };
187
- }
188
- if (typeof raw === 'string' && raw.trim()) {
189
- const family = raw.split(',')[0].replace(/['"]/g, '').trim();
190
- if (!family) return null;
191
- return { family, weight: 'Regular', category: 'Sans Serif' };
192
- }
193
- return null;
194
- }
195
-
196
- $: resolvedFont = coerceFontValue(value);
197
-
198
- // Add scroll state tracking
199
- let isScrolled = false;
200
-
201
- // Add a timeout to track long-running initial loads
202
- let initialLoadTimeout: ReturnType<typeof setTimeout> | null = null;
203
-
204
- /**
205
- * The sticky header of the font list. It is looked up in the tree the list lives in (inside a module that is a
206
- * shadow root, which `document.querySelector` cannot see into), and the id is escaped so that one with dots or
207
- * brackets in it is found too.
208
- */
209
- function findStickyHeader(): Element | null {
210
- return queryInTreeOf(fontListContainer, `#${CSS.escape(`font-header-${controllerId}`)}`);
211
- }
212
-
213
- // Function to update scroll state
214
- function updateScrollState() {
215
- if (fontListContainer) {
216
- const wasScrolled = isScrolled;
217
- isScrolled = fontListContainer.scrollTop > 10;
218
-
219
- // If we're transitioning from scrolled to not scrolled, remove transition
220
- if (wasScrolled && !isScrolled) {
221
- const stickyHeader = findStickyHeader();
222
- if (stickyHeader) {
223
- stickyHeader.classList.remove('transition-border');
224
- // Force a reflow to ensure the transition class removal takes effect
225
- void (stickyHeader as HTMLElement).offsetWidth;
226
- }
227
- } else if (!wasScrolled && isScrolled) {
228
- // Add transition class when starting to scroll
229
- const stickyHeader = findStickyHeader();
230
- if (stickyHeader) {
231
- stickyHeader.classList.add('transition-border');
232
- }
233
- }
234
- }
235
- }
236
-
237
- // Subscribe to store changes
238
- $: {
239
- recentFonts = $recentFontsStore
240
- .filter(font => !shouldSkipFont(font.family))
241
- .map(font => ({
242
- family: font.family,
243
- category: normalizeCategory(font.category) as FontItem['category'],
244
- isCustom: font.isCustom
245
- }));
246
-
247
- // Update filtered fonts when recent fonts change
248
- if (hideRecentFromList) {
249
- updateFilteredFonts();
250
- }
251
- }
252
-
253
- // Add debounce function at the top of the script section
254
- function debounce<T extends (...args: any[]) => Promise<void>>(
255
- func: T,
256
- wait: number
257
- ): (...args: Parameters<T>) => void {
258
- let timeout: ReturnType<typeof setTimeout> | null = null;
259
- return function(this: any, ...args: Parameters<T>): void {
260
- const context = this;
261
- if (timeout) clearTimeout(timeout);
262
- timeout = setTimeout(() => {
263
- timeout = null;
264
- func.apply(context, args);
265
- }, wait);
266
- };
267
- }
268
-
269
- // Add a variable to store the debounced search function
270
- let debouncedSearch: (event: Event) => void;
271
-
272
- let fontPickerReadyAt = 0;
273
-
274
- /**
275
- * The layer the font popovers are drawn in: one of their own, above everything else, in the tree this input lives
276
- * in. On a page that is a node at the end of the body; inside a module it is a node in the module's portal layer,
277
- * because a popover drawn in the customer's body would lose the module's styles and leave a node behind in the
278
- * customer's page. The input has to be on the page to tell which tree it is in, so until it is (a short moment,
279
- * and a popover is never open by then) the popovers go where the design system's portal configuration sends them.
280
- */
281
- let fontPickerPortalHost: HTMLElement | undefined;
282
-
283
- function ensureFontPickerPortal() {
284
- if (!browser || fontPickerPortalHost) return;
285
- fontPickerPortalHost = acquirePortalHost(familyTriggerEl, 'widgetic-font-picker-portal') ?? undefined;
286
- }
287
-
288
- onMount(async () => {
289
- try {
290
- if (browser) {
291
- fontPickerReadyAt = Date.now() + 400;
292
- ensureFontPickerPortal();
293
- const coerced = coerceFontValue(value);
294
- if (coerced?.weight) {
295
- selectedWeight = `${controllerId}-${coerced.weight}`;
296
- }
297
- if (typeof value === 'string' && coerced && onChange) {
298
- onChange(coerced);
299
- }
300
-
301
- // Load saved filter
302
- const savedFilter = readEditorStorageValue(FONT_FILTER_KEY(controllerId));
303
- if (savedFilter) {
304
- currentFilter = savedFilter as FilterType;
305
- }
306
-
307
- // Load saved weight
308
- const savedWeight = readEditorStorageValue(FONT_WEIGHT_KEY(controllerId));
309
- if (savedWeight) {
310
- selectedWeight = savedWeight;
311
- }
312
- }
313
-
314
- // console.log('🚀 [FontInput] Initializing controller:', {
315
- // controllerId,
316
- // initialFilter: currentFilter
317
- // });
318
-
319
- // Initialize the debounced search function early
320
- debouncedSearch = debounce(async (event: Event) => {
321
- await handleSearch(event);
322
- }, 300); // 300ms debounce time
323
-
324
- // Start font manager initialization in parallel
325
- const fontManagerPromise = FontManager.getInstance(appConfig.GOOGLE_FONTS_API_KEY);
326
-
327
- // Load and verify recent fonts while waiting for font manager
328
- const loadedRecentFonts = fontUtils.getRecentFonts();
329
- // console.log('📝 [FontInput] Loading recent fonts:', loadedRecentFonts);
330
-
331
- // Filter and validate recent fonts
332
- const validRecentFonts = loadedRecentFonts
333
- .filter(font => !shouldSkipFont(font.family))
334
- .slice(0, MAX_RECENT_FONTS);
335
-
336
- // Update store with validated fonts
337
- recentFontsStore.set(validRecentFonts);
338
-
339
- // Update local state
340
- recentFonts = validRecentFonts.map(font => ({
341
- family: font.family,
342
- category: normalizeCategory(font.category) as FontItem['category'],
343
- isCustom: font.isCustom
344
- }));
345
-
346
- // console.log('✅ [FontInput] Recent fonts initialized:', {
347
- // loaded: loadedRecentFonts.length,
348
- // valid: validRecentFonts.length,
349
- // fonts: validRecentFonts.map(f => f.family)
350
- // });
351
-
352
- // Now wait for font manager to be ready
353
- fontManagerInstance = await fontManagerPromise;
354
-
355
- // Try to get preloaded fonts immediately
356
- let preloadedFonts: FontData[] = [];
357
-
358
- // Check if we can get preloaded fonts for the current category
359
- if (currentFilter !== 'All' && currentFilter !== 'Mine') {
360
- // console.log(`🔍 [FontInput:${controllerId}] Getting preloaded fonts for category:`, currentFilter);
361
- preloadedFonts = fontManagerInstance.getPreloadedFonts(currentFilter as FontItem['category']);
362
-
363
- if (preloadedFonts.length > 0) {
364
- // console.log(`✅ [FontInput:${controllerId}] Using preloaded fonts for initial display:`, {
365
- // category: currentFilter,
366
- // count: preloadedFonts.length,
367
- // fonts: preloadedFonts.slice(0, 3).map(f => f.family)
368
- // });
369
-
370
- // Filter out fonts that should be skipped
371
- const filteredPreloadedFonts = preloadedFonts.filter(font => !shouldSkipFont(font.family));
372
-
373
- // Update allFonts with preloaded fonts
374
- allFonts = filteredPreloadedFonts;
375
-
376
- // Update filtered fonts immediately
377
- updateFilteredFonts();
378
-
379
- // Only set loading to false if we have fonts to display
380
- if (filteredFonts.length > 0) {
381
- isInitialLoading = false;
382
- // console.log(`✅ [FontInput:${controllerId}] Initial loading complete with preloaded fonts:`, {
383
- // filteredFonts: filteredFonts.length,
384
- // category: currentFilter
385
- // });
386
-
387
- // Clear the timeout since we've loaded successfully
388
- if (initialLoadTimeout) {
389
- clearTimeout(initialLoadTimeout);
390
- initialLoadTimeout = null;
391
- }
392
- }
393
- } else {
394
- // console.log(`⚠️ [FontInput:${controllerId}] No preloaded fonts available for category:`, currentFilter);
395
- }
396
- } else if (currentFilter === 'All') {
397
- // console.log(`🔍 [FontInput:${controllerId}] Getting initial batch for All category`);
398
- // For All category, get the first batch
399
- preloadedFonts = fontManagerInstance.getNextBatch(controllerId, 'All');
400
-
401
- if (preloadedFonts.length > 0) {
402
- // console.log(`✅ [FontInput:${controllerId}] Using initial batch for All category:`, {
403
- // count: preloadedFonts.length,
404
- // fonts: preloadedFonts.slice(0, 3).map(f => f.family)
405
- // });
406
-
407
- // Filter out fonts that should be skipped
408
- const filteredPreloadedFonts = preloadedFonts.filter(font => !shouldSkipFont(font.family));
409
-
410
- // Update allFonts with preloaded fonts
411
- allFonts = filteredPreloadedFonts;
412
-
413
- // Update filtered fonts immediately
414
- updateFilteredFonts();
415
-
416
- // Only set loading to false if we have fonts to display
417
- if (filteredFonts.length > 0) {
418
- isInitialLoading = false;
419
- // console.log(`✅ [FontInput:${controllerId}] Initial loading complete for All category:`, {
420
- // filteredFonts: filteredFonts.length
421
- // });
422
-
423
- // Clear the timeout since we've loaded successfully
424
- if (initialLoadTimeout) {
425
- clearTimeout(initialLoadTimeout);
426
- initialLoadTimeout = null;
427
- }
428
- }
429
- }
430
- } else if (currentFilter === 'Mine') {
431
- // console.log(`🔍 [FontInput:${controllerId}] Getting custom fonts for Mine category`);
432
- // For Mine category, first check if we already have preloaded fonts
433
- preloadedFonts = fontManagerInstance.getPreloadedFonts('Mine');
434
-
435
- if (preloadedFonts.length > 0) {
436
- // console.log(`✅ [FontInput:${controllerId}] Using preloaded custom fonts for Mine category:`, {
437
- // count: preloadedFonts.length,
438
- // fonts: preloadedFonts.slice(0, 3).map(f => f.family)
439
- // });
440
- } else {
441
- // If no preloaded fonts found, load them now
442
- // console.log(`📚 [FontInput:${controllerId}] No preloaded custom fonts found, loading them now...`);
443
- preloadedFonts = await fontManagerInstance.loadCustomFonts();
444
- }
445
-
446
- if (preloadedFonts.length > 0) {
447
- // Update allFonts with custom fonts
448
- allFonts = preloadedFonts;
449
-
450
- // Update filtered fonts immediately
451
- updateFilteredFonts();
452
-
453
- // Only set loading to false if we have fonts to display
454
- if (filteredFonts.length > 0) {
455
- isInitialLoading = false;
456
- // console.log(`✅ [FontInput:${controllerId}] Initial loading complete for Mine category:`, {
457
- // filteredFonts: filteredFonts.length
458
- // });
459
-
460
- // Clear the timeout since we've loaded successfully
461
- if (initialLoadTimeout) {
462
- clearTimeout(initialLoadTimeout);
463
- initialLoadTimeout = null;
464
- }
465
- }
466
- }
467
- }
468
-
469
- // Only set loading state if we couldn't get preloaded fonts
470
- if (preloadedFonts.length === 0) {
471
- // console.log(`⚠️ [FontInput:${controllerId}] No preloaded fonts available, will load asynchronously`);
472
- // Keep isInitialLoading as true
473
-
474
- // Set a timeout to show loading indicator if initialization takes too long
475
- initialLoadTimeout = setTimeout(() => {
476
- // If we're still loading after 1 second, show the loading indicator
477
- if (isInitialLoading) {
478
- // console.log(`⚠️ [FontInput:${controllerId}] Initial font loading taking longer than expected`);
479
- }
480
- }, 1000); // Reduced from 2000ms to 1000ms
481
- }
482
-
483
- // Initialize fonts list with saved filter - use a separate async function
484
- // to avoid blocking the UI
485
- const initializeFontsAsync = async () => {
486
- try {
487
- // console.log(`🔄 [FontInput:${controllerId}] Starting font initialization for controller:`, controllerId);
488
-
489
- // First, ensure the FontManager is fully initialized
490
- if (!FontManager.isInitialized) {
491
- // console.log(`⏳ [FontInput:${controllerId}] Waiting for FontManager to initialize...`);
492
- // This will wait for the initialization promise to resolve
493
- await FontManager.getInstance(appConfig.GOOGLE_FONTS_API_KEY);
494
- }
495
-
496
- // Skip loading if we already have preloaded fonts
497
- if (allFonts.length === 0) {
498
- // console.log(`🔍 [FontInput:${controllerId}] No fonts loaded yet, loading initial batch for ${currentFilter}`);
499
- // Instead of loading all fonts, just get the first batch
500
- let initialFonts: FontData[] = [];
501
-
502
- if (currentFilter === 'Mine') {
503
- // For Mine category, first check if we have preloaded fonts
504
- initialFonts = fontManagerInstance.getPreloadedFonts('Mine');
505
-
506
- if (initialFonts.length > 0) {
507
- // console.log(`📚 [FontInput:${controllerId}] Using preloaded custom fonts:`, {
508
- // count: initialFonts.length,
509
- // fonts: initialFonts.slice(0, 3).map(f => f.family)
510
- // });
511
- } else {
512
- // If no preloaded fonts, load them now
513
- // console.log(`📚 [FontInput:${controllerId}] No preloaded custom fonts found, loading them now...`);
514
- initialFonts = await fontManagerInstance.loadCustomFonts();
515
- }
516
- } else if (currentFilter === 'All') {
517
- // For All category, get the first batch
518
- initialFonts = fontManagerInstance.getNextBatch(controllerId, 'All');
519
- // console.log(`📚 [FontInput:${controllerId}] Loaded initial batch for All:`, {
520
- // count: initialFonts.length,
521
- // fonts: initialFonts.slice(0, 3).map(f => f.family)
522
- // });
523
- } else {
524
- // For specific categories, first try to get preloaded fonts
525
- initialFonts = fontManagerInstance.getPreloadedFonts(currentFilter as FontItem['category']);
526
-
527
- if (initialFonts.length === 0) {
528
- // If no preloaded fonts, get the first batch filtered by category
529
- // console.log(`📚 [FontInput:${controllerId}] No preloaded fonts for ${currentFilter}, getting batch`);
530
- initialFonts = fontManagerInstance.getNextBatch(controllerId, currentFilter);
531
- } else {
532
- // console.log(`📚 [FontInput:${controllerId}] Using preloaded fonts for ${currentFilter}:`, {
533
- // count: initialFonts.length,
534
- // fonts: initialFonts.slice(0, 3).map(f => f.family)
535
- // });
536
- }
537
- }
538
-
539
- // Filter out fonts that should be skipped
540
- const filteredFonts = initialFonts.filter(font => !shouldSkipFont(font.family));
541
- // console.log(`🔍 [FontInput:${controllerId}] Filtered initial fonts:`, {
542
- // before: initialFonts.length,
543
- // after: filteredFonts.length,
544
- // skipped: initialFonts.length - filteredFonts.length
545
- // });
546
-
547
- // Update allFonts with just the initial batch
548
- allFonts = filteredFonts;
549
-
550
- // Update filtered fonts immediately
551
- updateFilteredFonts();
552
- } else {
553
- // console.log(`✅ [FontInput:${controllerId}] Already have fonts loaded:`, {
554
- // count: allFonts.length,
555
- // category: currentFilter
556
- // });
557
- }
558
-
559
- // Set loading to false after fonts are loaded
560
- // Only set loading to false if we have fonts to display
561
- if (filteredFonts.length > 0) {
562
- isInitialLoading = false;
563
- // console.log(`✅ [FontInput:${controllerId}] Initialization complete with fonts:`, {
564
- // count: filteredFonts.length,
565
- // category: currentFilter
566
- // });
567
- } else {
568
- // console.log(`⚠️ [FontInput:${controllerId}] No fonts found after initialization`);
569
- // Still set loading to false to show empty state
570
- isInitialLoading = false;
571
- }
572
-
573
- // Clear the timeout since we've loaded successfully
574
- if (initialLoadTimeout) {
575
- clearTimeout(initialLoadTimeout);
576
- initialLoadTimeout = null;
577
- }
578
-
579
- // console.log(`✅ [FontInput:${controllerId}] Controller initialized with fonts:`, {
580
- // controllerId,
581
- // allFonts: allFonts.length,
582
- // filteredFonts: filteredFonts.length,
583
- // recentFonts: recentFonts.length,
584
- // currentFilter,
585
- // customFonts: allFonts.filter(f => f.category === 'Mine').length
586
- // });
587
- } catch (error) {
588
- console.error(`❌ [FontInput:${controllerId}] Error during async font initialization:`, error);
589
- isInitialLoading = false; // Make sure to set loading to false even on error
590
-
591
- // Clear the timeout on error
592
- if (initialLoadTimeout) {
593
- clearTimeout(initialLoadTimeout);
594
- initialLoadTimeout = null;
595
- }
596
- }
597
- };
598
-
599
- // Start the async initialization without waiting for it
600
- initializeFontsAsync();
601
-
602
- } catch (error) {
603
- console.error('❌ [FontInput] Error during initialization:', error);
604
- isInitialLoading = false; // Make sure to set loading to false even on error
605
-
606
- // Clear the timeout on error
607
- if (initialLoadTimeout) {
608
- clearTimeout(initialLoadTimeout);
609
- initialLoadTimeout = null;
610
- }
611
- }
612
- });
613
-
614
- /**
615
- * Initialize fonts based on the current filter
616
- */
617
- async function initializeFonts() {
618
- if (currentFilter === 'Mine') {
619
- // First check if we have preloaded fonts
620
- const preloadedCustomFonts = fontManagerInstance.getPreloadedFonts('Mine');
621
-
622
- if (preloadedCustomFonts.length > 0) {
623
- // console.log(`📚 [FontInput:${controllerId}] Using preloaded custom fonts in initializeFonts:`, {
624
- // count: preloadedCustomFonts.length,
625
- // fonts: preloadedCustomFonts.slice(0, 3).map(f => f.family)
626
- // });
627
- return preloadedCustomFonts;
628
- } else {
629
- // If no preloaded fonts, load them now
630
- // console.log(`📚 [FontInput:${controllerId}] No preloaded custom fonts found in initializeFonts, loading them now...`);
631
- const customFonts = await fontManagerInstance.loadCustomFonts();
632
- return customFonts;
633
- }
634
- }
635
-
636
- // For All category, load Google Fonts first, then get custom fonts (already preloaded or load them)
637
- const googleFonts = await fontManagerInstance.getInitialFontList();
638
-
639
- // First check if we have preloaded custom fonts
640
- let customFonts = fontManagerInstance.getPreloadedFonts('Mine');
641
-
642
- if (customFonts.length === 0) {
643
- // If no preloaded custom fonts, load them now
644
- customFonts = await fontManagerInstance.loadCustomFonts();
645
- }
646
-
647
- if (currentFilter === 'All') {
648
- return [
649
- ...googleFonts.filter(font => !font.isCustom),
650
- ...customFonts
651
- ];
652
- }
653
-
654
- // For other categories, filter out custom fonts
655
- return googleFonts.filter(font => !font.isCustom);
656
- }
657
-
658
- /**
659
- * Fetches available fonts from Google Fonts API
660
- */
661
- async function fetchGoogleFonts() {
662
- try {
663
- // console.log('🔍 [FontInput] Fetching Google Fonts...');
664
- fontManagerInstance = await FontManager.getInstance(appConfig.GOOGLE_FONTS_API_KEY);
665
- allFonts = await fontManagerInstance.getCompleteFontList();
666
- updateFilteredFonts();
667
-
668
- // console.log('✅ [FontInput] Fonts available:', allFonts.length);
669
- } catch (error) {
670
- console.error('❌ [FontInput] Error getting Google Fonts:', error);
671
- }
672
- }
673
-
674
- /**
675
- * Opens the file browser for font selection
676
- * Receives font files in the format matching fonts
677
- */
678
- async function openFileBrowser() {
679
-
680
- // console.log('🔍 [FontInput] Opening file browser for fonts:');
681
-
682
- // try {
683
- // // Get the current font's ID if it exists in our custom fonts
684
- // const selectedId = resolvedFont?.family ?
685
- // fontManagerInstance?.getCachedFontList()
686
- // .find(f => f.family === value.family && f.category === 'Mine')?.id
687
- // : undefined;
688
-
689
- // console.log('🔍 [FontInput] Opening file browser for fonts:', {
690
- // fileTypes: ['font'],
691
- // selectedId
692
- // });
693
-
694
- // const result = await window.uiSDK?.mountComponent('file-browser', {
695
- // container: '#file-browser',
696
- // config: {
697
- // fileTypes: ['font'],
698
- // selectedId,
699
- // batch: 1000 // allow for a large number of fonts to be selected
700
- // },
701
- // callbacks: {
702
- // onSelect: async (fontData: any) => {
703
- // if (!fontData) return;
704
-
705
- // const fontValue = {
706
- // family: fontData.family,
707
- // weight: fontData.weight,
708
- // category: 'Mine' // Set category to Mine for uploaded fonts
709
- // };
710
-
711
- // console.log('✅ [FontInput] Font selected:', {
712
- // ...fontValue,
713
- // format: fontData.url.split('.').pop()
714
- // });
715
-
716
- // if (onChange) {
717
- // onChange(fontValue);
718
- // }
719
- // },
720
- // onError: (error: Error) => {
721
- // console.error('❌ [FontInput] File Browser error:', error);
722
- // }
723
- // }
724
- // });
725
-
726
- // } catch (error) {
727
- // console.error('❌ [FontInput] Error opening file browser:', error);
728
- // }
729
- }
730
-
731
-
732
- /**
733
- * Updates the filtered fonts list based on search term and category
734
- * Also handles setting up the observer after updating
735
- *
736
- * Logic flow:
737
- * 1. Start with all fonts
738
- * 2. Apply search filter if term exists
739
- * 3. Apply category filter if not 'All'
740
- */
741
- function updateFilteredFonts() {
742
- let fonts = [...allFonts];
743
-
744
- // Clear both filters when search is active
745
- if (searchTerm) {
746
- const term = searchTerm.toLowerCase();
747
- fonts = fonts.filter(font =>
748
- font.family.toLowerCase().includes(term)
749
- );
750
-
751
- // Force category to All when searching
752
- currentFilter = 'All';
753
- } else {
754
- if (currentFilter !== 'All') {
755
- fonts = fonts.filter(font => {
756
- if (currentFilter === 'Mine') return font.category === 'Mine';
757
- return normalizeCategory(font.category) === currentFilter;
758
- });
759
- }
760
- }
761
-
762
- // Optionally filter out recent fonts
763
- if (hideRecentFromList) {
764
- const beforeRecent = fonts.length;
765
- fonts = fonts.filter(font =>
766
- !recentFonts.some(recent => recent.family === font.family)
767
- );
768
- // console.log(`🔍 [FontInput:${controllerId}] Filtered out recent fonts:`, {
769
- // beforeFilter: beforeRecent,
770
- // afterFilter: fonts.length,
771
- // recentFontsRemoved: beforeRecent - fonts.length
772
- // });
773
- }
774
-
775
- // Update filtered fonts
776
- filteredFonts = fonts;
777
-
778
- // console.log(`✅ [FontInput:${controllerId}] Filtered fonts result:`, {
779
- // total: fonts.length,
780
- // filter: currentFilter,
781
- // searchTerm,
782
- // hideRecentFromList,
783
- // recentFontsHidden: hideRecentFromList ? recentFonts.length : 0,
784
- // initialFontNumber
785
- // });
786
-
787
- // Setup observer after updating filtered fonts
788
- // Use a small timeout to ensure the DOM has updated
789
- if (scrollTimeout) {
790
- clearTimeout(scrollTimeout);
791
- }
792
-
793
- scrollTimeout = setTimeout(() => {
794
- setupFontObserver();
795
- }, 50);
796
- }
797
-
798
- /**
799
- * Handles font selection and updates recent fonts
800
- */
801
- function handleFontSelect(font: FontItem | RecentFont) {
802
- if (onChange) {
803
- // The family has to reach the card even when the weight catalog fails.
804
- onChange({
805
- family: font.family,
806
- weight: 'Regular',
807
- category: font.category
808
- });
809
- // Reset weight to Regular or first available weight
810
- fetchFontWeights(font.family).then(async () => {
811
- const newWeight = availableWeights.includes('Regular') ?
812
- 'Regular' : availableWeights[0];
813
-
814
- selectedWeight = `${controllerId}-${newWeight}`;
815
- if (browser) {
816
- writeEditorStorageValue(FONT_WEIGHT_KEY(controllerId), selectedWeight);
817
- }
818
-
819
- // Load the full font when selected
820
- if (!fontManagerInstance?.isCustomFont(font.family)) {
821
- await fontManagerInstance?.loadFullFont(font.family);
822
- }
823
-
824
- // Create the font value object with reset weight
825
- const fontValue = {
826
- family: font.family,
827
- weight: newWeight,
828
- category: font.category
829
- };
830
-
831
- // Pass the font value object to onChange
832
- onChange(fontValue);
833
-
834
- // console.log('✅ [FontInput] Font selected:', {
835
- // font: fontValue
836
- // });
837
- }).catch((error) => {
838
- console.error('[FontInput] Weight lookup failed after the family was applied:', error);
839
- });
840
- }
841
- }
842
-
843
- /**
844
- * Manages real-time search functionality
845
- * Prioritizes recent fonts in search results
846
- * Enhanced to better handle partial matches
847
- */
848
- async function handleSearch(event: Event) {
849
- const input = event.target as HTMLInputElement;
850
- const newSearchTerm = input.value;
851
-
852
- // Skip processing if the search term hasn't changed
853
- if (newSearchTerm === searchTerm) return;
854
-
855
- // Use debounced version only for typing
856
- debouncedSearch(event);
857
- }
858
-
859
- // Add paste handler
860
- function handlePaste(event: ClipboardEvent) {
861
- const pastedText = event.clipboardData?.getData('text/plain') || '';
862
-
863
- // Don't prevent default - let the paste happen naturally
864
- // Then trigger an immediate search update with the pasted content
865
- // searchTerm will be updated through binding
866
-
867
- // Schedule the handleSearchImmediate for the next tick to ensure
868
- // the input value is updated with the pasted content first
869
- setTimeout(() => {
870
- handleSearchImmediate(pastedText);
871
- }, 0);
872
- }
873
-
874
- // Separate immediate search handler (keep this)
875
- async function handleSearchImmediate(value: string) {
876
- // Store current filter before overriding it
877
- if (!searchTerm && value) {
878
- lastActiveFilter = currentFilter;
879
- currentFilter = 'All';
880
- writeEditorStorageValue(FONT_FILTER_KEY(controllerId), 'All');
881
- }
882
-
883
- // Apply filtering with the new search term
884
- updateFilteredFonts();
885
-
886
- // Reset scroll position if needed
887
- if (fontListContainer) {
888
- fontListContainer.scrollTop = 0;
889
- }
890
- }
891
-
892
- // Add a derived store for search results
893
- let currentSearchResults: FontData[] = [];
894
-
895
- // Update the reactive statement for search
896
- $: if (searchTerm) {
897
- const searchValue = searchTerm.toLowerCase().trim();
898
- // Only process if the search value is not empty
899
- if (searchValue) {
900
- // Get both Google Fonts and custom fonts from cache
901
- const googleFonts = fontManagerInstance?.getCachedFontList().filter(font => !font.isCustom) || [];
902
- const customFonts = fontManagerInstance?.getCachedFontList().filter(font => font.isCustom) || [];
903
-
904
- // Merge both lists
905
- const allCachedFonts = [...googleFonts, ...customFonts];
906
-
907
- // Modified search algorithm to use exact matching
908
- const newSearchResults = allCachedFonts
909
- .filter(font => {
910
- const familyLower = font.family.toLowerCase().trim();
911
-
912
- // Skip fonts that should be excluded
913
- if (shouldSkipFont(font.family)) {
914
- return false;
915
- }
916
-
917
- // Check if the search value is found in the font family
918
- return familyLower.includes(searchValue);
919
- })
920
- .sort((a, b) => {
921
- const aFamily = a.family.toLowerCase();
922
- const bFamily = b.family.toLowerCase();
923
-
924
- // Prioritize fonts that start with the search term
925
- const aStartsWith = aFamily.startsWith(searchValue);
926
- const bStartsWith = bFamily.startsWith(searchValue);
927
-
928
- if (aStartsWith && !bStartsWith) return -1;
929
- if (!aStartsWith && bStartsWith) return 1;
930
-
931
- // Then prioritize fonts where search term appears earlier
932
- const aIndex = aFamily.indexOf(searchValue);
933
- const bIndex = bFamily.indexOf(searchValue);
934
-
935
- if (aIndex !== -1 && bIndex !== -1) {
936
- return aIndex - bIndex;
937
- }
938
-
939
- // Fall back to alphabetical sorting
940
- return aFamily.localeCompare(bFamily);
941
- });
942
-
943
- // Only update results if they've changed
944
- if (JSON.stringify(newSearchResults) !== JSON.stringify(currentSearchResults)) {
945
- // Store all search results for batching
946
- currentSearchResults = newSearchResults;
947
-
948
- // Select first item automatically only if we have results and no item is currently selected
949
- if (currentSearchResults.length > 0 && activeSearchIndex === -1) {
950
- activeSearchIndex = 0;
951
- }
952
-
953
- // Show more initial results (double the default)
954
- const initialResultsCount = Math.min(FontManager.initialFontNumber * 2, currentSearchResults.length);
955
- filteredFonts = currentSearchResults.slice(0, initialResultsCount);
956
-
957
- // Reset scroll position
958
- if (fontListContainer) {
959
- fontListContainer.scrollTop = 0;
960
- }
961
-
962
- // Preload only the first batch of fonts
963
- filteredFonts.forEach(font => {
964
- fontManagerInstance?.loadFullFont(font.family);
965
- });
966
-
967
- // console.log('📝 [FontSearch] Updated results:', {
968
- // searchValue,
969
- // totalMatches: currentSearchResults.length,
970
- // displayedResults: filteredFonts.length,
971
- // activeIndex: activeSearchIndex
972
- // });
973
- }
974
- }
975
- }
976
-
977
- // Handle empty search term separately to avoid reactivity loop
978
- $: if (searchTerm === '') {
979
- // Only reset if we actually had search results before or if we have no filtered fonts
980
- if (currentSearchResults.length > 0 || filteredFonts.length === 0) {
981
- // console.log('🔄 [FontSearch] Handling empty search term');
982
-
983
- // Reset search state
984
- currentSearchResults = [];
985
- activeSearchIndex = -1; // Reset active index
986
-
987
- // Reset batch index to start fresh
988
- if (fontManagerInstance) {
989
- fontManagerInstance.resetBatchIndex(controllerId);
990
-
991
- // Get fonts for current category
992
- let fonts: FontData[] = [];
993
-
994
- if (currentFilter === 'All') {
995
- // Get initial batch of fonts instead of all fonts
996
- fonts = fontManagerInstance.getNextBatch(controllerId, currentFilter);
997
- // Update all fonts
998
- allFonts = fonts;
999
- // Update filtered fonts
1000
- filteredFonts = [];
1001
- updateFilteredFonts();
1002
- } else if (currentFilter === 'Mine') {
1003
- // For Mine category, first check if we have preloaded fonts
1004
- const preloadedCustomFonts = fontManagerInstance.getPreloadedFonts('Mine');
1005
-
1006
- if (preloadedCustomFonts.length > 0) {
1007
- // Use preloaded custom fonts
1008
- // console.log(`📚 [FontInput:${controllerId}] Using preloaded custom fonts for empty search:`, {
1009
- // count: preloadedCustomFonts.length,
1010
- // fonts: preloadedCustomFonts.slice(0, 3).map(f => f.family)
1011
- // });
1012
- allFonts = preloadedCustomFonts;
1013
- filteredFonts = [];
1014
- updateFilteredFonts();
1015
- } else {
1016
- // If no preloaded fonts, load them asynchronously
1017
- // console.log(`📚 [FontInput:${controllerId}] No preloaded custom fonts found for empty search, loading them now...`);
1018
- fontManagerInstance.loadCustomFonts().then(customFonts => {
1019
- allFonts = customFonts || [];
1020
- filteredFonts = [];
1021
- updateFilteredFonts();
1022
- });
1023
- }
1024
- } else {
1025
- // For other categories (Serif, Sans Serif, etc.), get initial batch by category
1026
- fonts = fontManagerInstance.getNextBatch(controllerId, currentFilter);
1027
- // Update all fonts
1028
- allFonts = fonts;
1029
- // Update filtered fonts
1030
- filteredFonts = [];
1031
- updateFilteredFonts();
1032
- }
1033
- }
1034
-
1035
- // Reset scroll position when clearing search (for non-Mine categories)
1036
- if (currentFilter !== 'Mine' && fontListContainer) {
1037
- fontListContainer.scrollTop = 0;
1038
- }
1039
-
1040
- // Setup observer in next tick for non-Mine categories
1041
- if (currentFilter !== 'Mine') {
1042
- if (scrollTimeout) {
1043
- clearTimeout(scrollTimeout);
1044
- }
1045
-
1046
- scrollTimeout = setTimeout(() => {
1047
- if (fontListContainer) {
1048
- setupFontObserver();
1049
- }
1050
- }, 50);
1051
- }
1052
-
1053
- // console.log('🔄 [FontSearch] Reset search state:', {
1054
- // currentFilter,
1055
- // allFonts: allFonts.length,
1056
- // filteredFonts: filteredFonts.length
1057
- // });
1058
- }
1059
- }
1060
-
1061
- // Update keyboard navigation to use filteredFonts
1062
- function handleSearchKeydown(event: KeyboardEvent | CustomEvent<KeyboardEvent>) {
1063
- // Ensure we have a KeyboardEvent
1064
- const keyEvent = event instanceof KeyboardEvent ? event : event.detail;
1065
-
1066
- // Prevent handling backspace when search is already empty
1067
- if (keyEvent.key === 'Backspace' && !searchTerm) {
1068
- keyEvent.preventDefault();
1069
- return;
1070
- }
1071
-
1072
- if (!filteredFonts.length) return;
1073
-
1074
- if (keyEvent.key === 'ArrowDown') {
1075
- keyEvent.preventDefault();
1076
- handleArrowClick('down');
1077
- } else if (keyEvent.key === 'ArrowUp') {
1078
- keyEvent.preventDefault();
1079
- handleArrowClick('up');
1080
- } else if (keyEvent.key === 'Enter' && activeSearchIndex !== -1) {
1081
- keyEvent.preventDefault();
1082
- handleFontSelect(filteredFonts[activeSearchIndex]);
1083
- }
1084
- }
1085
-
1086
- async function handleFilterChange(filter: FilterType) {
1087
- if (currentFilter !== filter) {
1088
- lastActiveFilter = filter; // Store the new filter as last active
1089
- currentFilter = filter;
1090
-
1091
- if (browser) {
1092
- writeEditorStorageValue(FONT_FILTER_KEY(controllerId), filter);
1093
- }
1094
-
1095
- if (fontManagerInstance) {
1096
- fontManagerInstance.resetBatchIndex(controllerId);
1097
-
1098
- try {
1099
- // console.log(`🔄 [FontInput:${controllerId}] Category changed to:`, filter);
1100
- let fonts: FontData[] = [];
1101
-
1102
- if (filter === 'All') {
1103
- // Get initial batch of fonts instead of all fonts
1104
- fonts = fontManagerInstance.getNextBatch(controllerId, filter);
1105
- // console.log(`📚 [FontInput:${controllerId}] Loaded initial batch for All category:`, {
1106
- // count: fonts.length,
1107
- // fonts: fonts.slice(0, 3).map(f => f.family)
1108
- // });
1109
- } else if (filter === 'Mine') {
1110
- // Check if custom fonts are already loaded by getting them from the FontManager instance
1111
- fonts = fontManagerInstance.getPreloadedFonts('Mine');
1112
-
1113
- if (fonts.length === 0) {
1114
- // If no preloaded custom fonts found, load them
1115
- // console.log(`📚 [FontInput:${controllerId}] No preloaded custom fonts found, loading them now...`);
1116
- fonts = await fontManagerInstance.loadCustomFonts();
1117
- } else {
1118
- // console.log(`📚 [FontInput:${controllerId}] Using preloaded custom fonts:`, {
1119
- // count: fonts.length,
1120
- // fonts: fonts.slice(0, 3).map(f => f.family)
1121
- // });
1122
- }
1123
- } else {
1124
- // For other categories, first try to get preloaded fonts
1125
- fonts = fontManagerInstance.getPreloadedFonts(filter as FontItem['category']);
1126
-
1127
- if (fonts.length > 0) {
1128
- // console.log(`📚 [FontInput:${controllerId}] Using preloaded fonts for ${filter}:`, {
1129
- // count: fonts.length,
1130
- // fonts: fonts.slice(0, 3).map(f => f.family)
1131
- // });
1132
- } else {
1133
- // If no preloaded fonts, get the first batch filtered by category
1134
- // console.log(`📚 [FontInput:${controllerId}] No preloaded fonts for ${filter}, getting batch`);
1135
- fonts = fontManagerInstance.getNextBatch(controllerId, filter);
1136
- }
1137
- }
1138
-
1139
- // Filter out fonts that should be skipped
1140
- const filteredFonts = fonts.filter(font => !shouldSkipFont(font.family));
1141
- // console.log(`🔍 [FontInput:${controllerId}] Filtered fonts after category change:`, {
1142
- // before: fonts.length,
1143
- // after: filteredFonts.length,
1144
- // skipped: fonts.length - filteredFonts.length
1145
- // });
1146
-
1147
- allFonts = filteredFonts;
1148
- updateFilteredFonts();
1149
-
1150
- // Setup observer in next tick
1151
- scrollTimeout = setTimeout(() => {
1152
- if (fontListContainer) {
1153
- setupFontObserver();
1154
- }
1155
- }, 0);
1156
-
1157
- if (fontListContainer) {
1158
- fontListContainer.scrollTop = 0;
1159
- }
1160
-
1161
- // console.log(`✅ [FontInput:${controllerId}] Category change complete:`, {
1162
- // filter,
1163
- // fonts: allFonts.length,
1164
- // filteredFonts: filteredFonts.length,
1165
- // customFonts: allFonts.filter(f => f.isCustom).length
1166
- // });
1167
- } catch (error) {
1168
- console.error(`❌ [FontInput:${controllerId}] Error changing category:`, error);
1169
- }
1170
- }
1171
- }
1172
- }
1173
- /**
1174
- * Manages intersection observer for lazy loading fonts
1175
- * Only loads fonts when they become visible in viewport
1176
- */
1177
- function setupFontObserver() {
1178
- if (!fontListContainer) {
1179
- // console.log(`⚠️ [FontInput:${controllerId}] Font list container not found, retrying...`);
1180
- return scrollTimeout = setTimeout(() => {
1181
- if (fontListContainer) {
1182
- setupFontObserver();
1183
- }
1184
- }, 50);
1185
- }
1186
-
1187
- // If we have no fonts to observe, try to update filtered fonts first
1188
- if (!filteredFonts.length) {
1189
- // console.log(`⚠️ [FontInput:${controllerId}] No fonts available to observe, updating filtered fonts`);
1190
- updateFilteredFonts();
1191
-
1192
- // If we still have no fonts, log a warning and return
1193
- if (!filteredFonts.length) {
1194
- // console.warn(`❌ [FontInput:${controllerId}] No fonts available to observe after update`);
1195
- return;
1196
- }
1197
- }
1198
-
1199
- // console.log(`🔍 [FontInput:${controllerId}] Setting up font observer for`, filteredFonts.length, 'fonts');
1200
-
1201
- // Get the observer from FontManager
1202
- const observer = fontManagerInstance?.getObserver(fontListContainer);
1203
- if (!observer) {
1204
- // console.warn(`❌ [FontInput:${controllerId}] Failed to create observer`);
1205
- return;
1206
- }
1207
-
1208
- // Disconnect existing observer if it exists
1209
- if (fontObserver) {
1210
- fontObserver.disconnect();
1211
- }
1212
-
1213
- fontObserver = observer;
1214
-
1215
- // Use a more efficient approach to observe elements
1216
- // First, get all font elements that need to be observed
1217
- const fontElements = fontListContainer.querySelectorAll('[data-font]');
1218
-
1219
- // If there are no elements to observe, try again after a short delay
1220
- if (fontElements.length === 0) {
1221
- // console.log(`⚠️ [FontInput:${controllerId}] No font elements found to observe, will retry`);
1222
- return scrollTimeout = setTimeout(() => {
1223
- setupFontObserver();
1224
- }, 100);
1225
- }
1226
-
1227
- // console.log(`📝 [FontInput:${controllerId}] Observing`, fontElements.length, 'font elements');
1228
-
1229
- // Use a more efficient approach to observe elements
1230
- // Batch the observation process to reduce performance impact
1231
- const batchSize = 20; // Process 20 elements at a time
1232
- let currentIndex = 0;
1233
-
1234
- const observeBatch = () => {
1235
- const endIndex = Math.min(currentIndex + batchSize, fontElements.length);
1236
-
1237
- for (let i = currentIndex; i < endIndex; i++) {
1238
- observer.observe(fontElements[i]);
1239
- }
1240
-
1241
- currentIndex = endIndex;
1242
-
1243
- if (currentIndex < fontElements.length) {
1244
- // Process next batch in the next animation frame
1245
- requestAnimationFrame(observeBatch);
1246
- } else {
1247
- // console.log(`✅ [FontInput:${controllerId}] Finished observing all font elements:`, {
1248
- // total: fontElements.length,
1249
- // batchSize,
1250
- // batches: Math.ceil(fontElements.length / batchSize)
1251
- // });
1252
- }
1253
- };
1254
-
1255
- // Start the batched observation process
1256
- observeBatch();
1257
- }
1258
-
1259
- /**
1260
- * Handles font list scrolling
1261
- */
1262
- function handleFontListScroll(event: Event) {
1263
- // Ensure target is an HTMLElement
1264
- if (!(event.target instanceof HTMLElement)) {
1265
- return;
1266
- }
1267
-
1268
- // Prevent event propagation to stop global scroll handler from closing the modal
1269
- event.stopPropagation();
1270
-
1271
- // Handle font loading for visible fonts
1272
- fontManagerInstance?.handleScroll();
1273
-
1274
- const container = event.target;
1275
- const { scrollTop, scrollHeight, clientHeight } = container;
1276
- // Increase the threshold to detect when we're closer to the bottom
1277
- const scrolledToBottom = (scrollHeight - (scrollTop + clientHeight)) <= 100;
1278
-
1279
- // Add debug log to help diagnose scrolling issues
1280
- // console.log(`📜 [FontInput:${controllerId}] Scroll position:`, {
1281
- // scrollTop,
1282
- // scrollHeight,
1283
- // clientHeight,
1284
- // remainingScroll: scrollHeight - (scrollTop + clientHeight),
1285
- // scrolledToBottom,
1286
- // hasSearchTerm: Boolean(searchTerm),
1287
- // searchResultsCount: currentSearchResults.length,
1288
- // displayedResults: filteredFonts.length,
1289
- // currentFilter
1290
- // });
1291
-
1292
- if (scrolledToBottom) {
1293
- if (searchTerm && currentSearchResults.length > 0) {
1294
- // Calculate next batch using SEARCH_BATCH_SIZE
1295
- const nextBatchStart = filteredFonts.length;
1296
- const nextBatch = currentSearchResults.slice(
1297
- nextBatchStart,
1298
- nextBatchStart + SEARCH_BATCH_SIZE
1299
- );
1300
-
1301
- if (nextBatch.length > 0) {
1302
- // console.log(`🔄 [FontInput:${controllerId}] Loading next search batch:`, {
1303
- // batchSize: nextBatch.length,
1304
- // startIndex: nextBatchStart,
1305
- // endIndex: nextBatchStart + nextBatch.length,
1306
- // totalSearchResults: currentSearchResults.length
1307
- // });
1308
-
1309
- // Add new batch to filtered fonts
1310
- filteredFonts = [...filteredFonts, ...nextBatch];
1311
-
1312
- // Setup observer for new fonts
1313
- scrollTimeout = setTimeout(() => {
1314
- if (fontListContainer) {
1315
- setupFontObserver();
1316
- }
1317
- }, 0);
1318
-
1319
- // console.log(`📝 [FontInput:${controllerId}] Loaded next search batch:`, {
1320
- // batchSize: nextBatch.length,
1321
- // totalDisplayed: filteredFonts.length,
1322
- // remainingFonts: currentSearchResults.length - filteredFonts.length,
1323
- // nextBatchSize: SEARCH_BATCH_SIZE
1324
- // });
1325
- } else {
1326
- // console.log(`ℹ️ [FontInput:${controllerId}] No more search results to load`);
1327
- }
1328
- } else {
1329
- // Normal font list scrolling
1330
- if (!isLoadingBatch && fontManagerInstance?.hasMoreFonts(controllerId, currentFilter)) {
1331
- // console.log(`🔄 [FontInput:${controllerId}] Reached bottom, loading next batch for ${currentFilter}`);
1332
- loadNextBatch();
1333
- } else if (isLoadingBatch) {
1334
- // console.log(`⏳ [FontInput:${controllerId}] Already loading a batch, skipping`);
1335
- } else if (!fontManagerInstance?.hasMoreFonts(controllerId, currentFilter)) {
1336
- // console.log(`ℹ️ [FontInput:${controllerId}] No more fonts to load for ${currentFilter}`);
1337
- }
1338
- }
1339
- }
1340
- }
1341
-
1342
- /**
1343
- * Loads the next batch of fonts
1344
- */
1345
- async function loadNextBatch() {
1346
- if (isLoadingBatch) return;
1347
-
1348
- try {
1349
- isLoadingBatch = true;
1350
- // console.log(`🔄 [FontInput:${controllerId}] Loading next batch for ${currentFilter}`);
1351
-
1352
- // Get next batch for this controller
1353
- const newFonts = fontManagerInstance.getNextBatch(controllerId, currentFilter);
1354
- // console.log(`📚 [FontInput:${controllerId}] Received next batch:`, {
1355
- // count: newFonts.length,
1356
- // category: currentFilter,
1357
- // fonts: newFonts.slice(0, 3).map(f => f.family)
1358
- // });
1359
-
1360
- // Add to existing fonts, ensuring uniqueness
1361
- const combinedFonts = [...allFonts, ...newFonts];
1362
- allFonts = Array.from(
1363
- new Map(combinedFonts.map(font => [font.family, font])).values()
1364
- );
1365
-
1366
- // Update filtered fonts while preserving current filter
1367
- updateFilteredFonts();
1368
-
1369
- // console.log(`✅ [FontInput:${controllerId}] Loaded new batch:`, {
1370
- // controllerId,
1371
- // filter: currentFilter,
1372
- // newFonts: newFonts.length,
1373
- // totalFonts: allFonts.length,
1374
- // filteredFonts: filteredFonts.length,
1375
- // hasMoreFonts: fontManagerInstance.hasMoreFonts(controllerId, currentFilter)
1376
- // });
1377
-
1378
- } catch (error) {
1379
- console.error(`❌ [FontInput:${controllerId}] Error loading font batch:`, error);
1380
- } finally {
1381
- isLoadingBatch = false;
1382
- }
1383
- }
1384
-
1385
- function handleToggle() {
1386
- // console.log('Font dropdown toggled:', controllerId);
1387
- toggleDropdown(controllerId);
1388
- }
1389
-
1390
- function closeDropdown() {
1391
- if (open) {
1392
- handleToggle();
1393
- }
1394
- }
1395
-
1396
- // Create a custom action for font observation
1397
- function observeFont(node: HTMLElement) {
1398
- if (fontObserver) {
1399
- fontObserver.observe(node);
1400
- }
1401
-
1402
- return {
1403
- destroy() {
1404
- if (fontObserver) {
1405
- fontObserver.unobserve(node);
1406
- }
1407
- }
1408
- };
1409
- }
1410
-
1411
- $: open = $openDropdowns.has(controllerId);
1412
-
1413
- // Add a reactive statement to set up observer when fonts are loaded
1414
- $: if (filteredFonts.length > 0 && fontListContainer) {
1415
- // console.log('📝 [FontInput] Fonts loaded, setting up observer...');
1416
- setupFontObserver();
1417
- }
1418
-
1419
- $: popoverStyle = `width: ${buttonWidth}px`;
1420
-
1421
- /**
1422
- * Fetches and processes font weights from Google Fonts API
1423
- * or from fonts.json for custom fonts
1424
- */
1425
- function keepWeightIfListed() {
1426
- const currentName = selectedWeight.startsWith(`${controllerId}-`)
1427
- ? selectedWeight.slice(controllerId.length + 1)
1428
- : '';
1429
- if (!availableWeights.includes(currentName)) {
1430
- selectedWeight = `${controllerId}-${availableWeights.includes('Regular') ? 'Regular' : availableWeights[0]}`;
1431
- }
1432
- }
1433
-
1434
- async function fetchFontWeights(fontFamily: string) {
1435
- try {
1436
- // Wait for FontManager init — reactive weight fetch can race ahead of onMount.
1437
- fontManagerInstance = await FontManager.getInstance(appConfig.GOOGLE_FONTS_API_KEY);
1438
-
1439
- // First check if it's a custom font using FontManager
1440
- if (fontManagerInstance?.isCustomFont(fontFamily)) {
1441
- // Get custom font data
1442
- const customFontResponse = await fetch(fontsJsonUrl);
1443
- if (customFontResponse.ok) {
1444
- const customFontsData = await customFontResponse.json();
1445
- const customFont = customFontsData.fontFamilies.find(
1446
- (f: any) => f.family === fontFamily
1447
- );
1448
-
1449
- if (customFont) {
1450
- // For custom fonts, get all variants from fonts.json
1451
- availableWeights = customFont.variants
1452
- .map((v: any) => v.weight)
1453
- // Remove duplicates if any
1454
- .filter((weight: string, index: number, self: string[]) =>
1455
- self.indexOf(weight) === index
1456
- )
1457
- // Sort with Regular first, then alphabetically
1458
- .sort((a: string, b: string) => {
1459
- if (a === 'Regular') return -1;
1460
- if (b === 'Regular') return 1;
1461
- return a.localeCompare(b);
1462
- });
1463
-
1464
- // Set default weight only if not already set for this controller
1465
- if (!selectedWeight.startsWith(controllerId)) {
1466
- selectedWeight = `${controllerId}-${availableWeights.includes('Regular') ?
1467
- 'Regular' : availableWeights[0]}`;
1468
- }
1469
-
1470
- return;
1471
- }
1472
- }
1473
- }
1474
-
1475
- // Google font: use catalog cached by FontManager (no extra API call per font)
1476
- let variantIds = fontManagerInstance?.getGoogleFontVariantIds(fontFamily);
1477
- if (!variantIds?.length) {
1478
- // Catalog may still be empty right after init edge cases — force list load once.
1479
- try {
1480
- await fontManagerInstance.getInitialFontList();
1481
- } catch (catalogError) {
1482
- console.warn('[FontInput] Catalog refresh failed before weight lookup:', catalogError);
1483
- }
1484
- variantIds = fontManagerInstance?.getGoogleFontVariantIds(fontFamily);
1485
- }
1486
- if (variantIds?.length) {
1487
- availableWeights = mapGoogleVariantIdsToWeightNames(variantIds);
1488
- if (!availableWeights.includes(selectedWeight.replace(`${controllerId}-`, ''))) {
1489
- selectedWeight = `${controllerId}-${availableWeights.includes('Regular') ? 'Regular' : availableWeights[0]}`;
1490
- }
1491
- return;
1492
- }
1493
-
1494
- // API unavailable (403 / no catalog): sensible defaults, still loads via fonts.googleapis.com CSS
1495
- // Warn once — not on every reactive re-run during catalog race.
1496
- if (!fontCatalogFallbackWarned) {
1497
- fontCatalogFallbackWarned = true;
1498
- console.warn('[FontInput] Using default weights (Google catalog not loaded). Later fonts will use the same fallback silently.');
1499
- }
1500
- availableWeights = ['Regular', 'Italic', 'Bold', 'Bold Italic'];
1501
- keepWeightIfListed();
1502
- } catch (error) {
1503
- console.error('Error fetching font weights:', error);
1504
- availableWeights = ['Regular', 'Italic', 'Bold', 'Bold Italic'];
1505
- keepWeightIfListed();
1506
- }
1507
- }
1508
-
1509
- $: if (resolvedFont?.family) {
1510
- fetchFontWeights(resolvedFont.family);
1511
- }
1512
-
1513
- /**
1514
- * Highlights search term matches in font names
1515
- * @param name Font name
1516
- * @param term Search term
1517
- * @returns HTML string with highlighted match
1518
- *
1519
- * Note: The result goes to {@html}, so every piece of the font name is escaped as it is put in (a name such as
1520
- * `<img src=x onerror=...>` must show as text, not run in the page the editor is on).
1521
- */
1522
- function highlightMatch(name: string, term: string) {
1523
- // Check if this font is the selected one
1524
- const isSelected = resolvedFont?.family === name;
1525
-
1526
- if (!term) {
1527
- // If no search term, just return the name with appropriate color
1528
- return isSelected
1529
- ? `<span style="color: white">${escapeHtml(name)}</span>`
1530
- : `<span style="color: hsl(var(--grey7))">${escapeHtml(name)}</span>`;
1531
- }
1532
-
1533
- const nameLower = name.toLowerCase();
1534
- const termLower = term.toLowerCase().trim();
1535
-
1536
- // If the name contains the search term, highlight that part
1537
- if (nameLower.includes(termLower)) {
1538
- const index = nameLower.indexOf(termLower);
1539
- const beforeMatch = escapeHtml(name.slice(0, index));
1540
- const match = escapeHtml(name.slice(index, index + termLower.length));
1541
- const afterMatch = escapeHtml(name.slice(index + termLower.length));
1542
-
1543
- if (isSelected) {
1544
- // For selected items: text is white, highlight is grey7
1545
- return `<span style="color: white">${beforeMatch}<span style="color: hsl(var(--grey7))">${match}</span>${afterMatch}</span>`;
1546
- } else {
1547
- // For non-selected items: text is grey7, highlight is sage-green
1548
- return `<span style="color: hsl(var(--grey7))">${beforeMatch}<span style="color: hsl(var(--sage-green))">${match}</span>${afterMatch}</span>`;
1549
- }
1550
- }
1551
-
1552
- // Default case - just return the name with appropriate color
1553
- return isSelected
1554
- ? `<span style="color: white">${escapeHtml(name)}</span>`
1555
- : `<span style="color: hsl(var(--grey7))">${escapeHtml(name)}</span>`;
1556
- }
1557
-
1558
- /**
1559
- * Handles global scroll events
1560
- */
1561
- function handleGlobalScroll(event: Event) {
1562
- // Ensure target is an HTMLElement before using closest
1563
- if (!(event.target instanceof HTMLElement)) {
1564
- return;
1565
- }
1566
-
1567
- const target = event.target;
1568
-
1569
- // Check if scroll happened inside our containers
1570
- const isInsideFontList = target === fontListContainer;
1571
- const isInsidePopover = target.closest('.font-popover-content');
1572
- const isInsideCommand = target.closest('[cmdk-root]');
1573
-
1574
- // If scrolling is inside any of our containers, don't close
1575
- if (isInsideFontList || isInsidePopover || isInsideCommand) {
1576
- return;
1577
- }
1578
-
1579
- // If scrolling outside our containers, close dropdowns
1580
- if ($openDropdowns?.has(controllerId)) {
1581
- toggleDropdown(controllerId);
1582
- }
1583
- if ($openDropdowns?.has('weight-' + controllerId)) {
1584
- toggleDropdown('weight-' + controllerId);
1585
- }
1586
- }
1587
-
1588
- // Stops listening for scrolling (the page and, inside a module, the module's own panels: a scroll never leaves a
1589
- // shadow root, so a listener on the window alone does not hear about those)
1590
- let stopListeningForScroll: () => void = () => {};
1591
-
1592
- // Update onMount to add the scroll listener with passive option
1593
- onMount(() => {
1594
- // Add scroll listener with passive option
1595
- stopListeningForScroll = listenForScroll(controllerElement, handleGlobalScroll, { passive: true });
1596
- window.addEventListener('resize', handleFamilyPopoverViewportChange);
1597
- window.visualViewport?.addEventListener('resize', handleFamilyPopoverViewportChange);
1598
-
1599
- // (Two touchstart/touchmove listeners that did nothing used to be added to the window here, and could never be
1600
- // removed: each input left two more on the customer's page every time it was shown. They did nothing, so they are
1601
- // gone.)
1602
- });
1603
-
1604
- // Update onDestroy to remove all listeners
1605
- onDestroy(() => {
1606
- stopListeningForScroll();
1607
- window.removeEventListener('resize', handleFamilyPopoverViewportChange);
1608
- window.visualViewport?.removeEventListener('resize', handleFamilyPopoverViewportChange);
1609
-
1610
- // Give the popover layer back (the last input to leave removes it from the page).
1611
- releasePortalHost(fontPickerPortalHost);
1612
- fontPickerPortalHost = undefined;
1613
-
1614
- if (fontObserver) {
1615
- fontObserver.disconnect();
1616
- }
1617
- // Clear any timeouts
1618
- if (scrollTimeout) {
1619
- clearTimeout(scrollTimeout);
1620
- }
1621
- if (initialLoadTimeout) {
1622
- clearTimeout(initialLoadTimeout);
1623
- }
1624
-
1625
- // console.log('🧹 [FontInput] Cleanup complete:', {
1626
- // controllerId,
1627
- // lastFilter: currentFilter
1628
- // });
1629
- });
1630
-
1631
- // Add this function to the script section
1632
- function handleDeleteCustomFont(font: FontItem | RecentFont, event: Event) {
1633
- event.stopPropagation();
1634
- // Convert returned RecentFonts to FontItems
1635
- recentFonts = fontUtils.removeCustomFont(font.family).map(font => ({
1636
- family: font.family,
1637
- category: font.category as FontItem['category'],
1638
- isCustom: font.isCustom
1639
- }));
1640
- updateFilteredFonts();
1641
- }
1642
-
1643
- // Add this function after the script tag
1644
- function normalizeCategory(category: string): FontItem['category'] {
1645
- return fontCategories.normalize(category);
1646
- }
1647
-
1648
- async function removeFont(fontFamily: string) {
1649
- try {
1650
- // Remove from manager
1651
- await fontManagerInstance?.removeCustomFont(fontFamily);
1652
-
1653
- // If the removed font was selected, clear the selection
1654
- if (resolvedFont?.family === fontFamily && onChange) {
1655
- onChange({
1656
- family: '',
1657
- weight: 'Regular',
1658
- category: ''
1659
- });
1660
- }
1661
-
1662
- // Remove from recent fonts if present
1663
- const updatedRecentFonts = recentFonts.filter(f => f.family !== fontFamily);
1664
- recentFonts = updatedRecentFonts;
1665
-
1666
- // Add lastUsed property before updating store
1667
- const recentFontsWithLastUsed = updatedRecentFonts.map(f => ({
1668
- ...f,
1669
- lastUsed: Date.now()
1670
- }));
1671
- recentFontsStore.set(recentFontsWithLastUsed);
1672
-
1673
- // Remove from all fonts
1674
- allFonts = allFonts.filter(f => f.family !== fontFamily);
1675
-
1676
- // Update filtered fonts
1677
- updateFilteredFonts();
1678
-
1679
- // console.log('✅ [FontInput] Font removed:', {
1680
- // fontFamily,
1681
- // remainingFonts: allFonts.length,
1682
- // filteredFonts: filteredFonts.length,
1683
- // recentFonts: recentFonts.length
1684
- // });
1685
- } catch (error) {
1686
- console.error('❌ [FontInput] Error removing font:', error);
1687
- }
1688
- }
1689
-
1690
- // Update the weight selection handler
1691
- function handleWeightSelect(weight: string) {
1692
- selectedWeight = `${controllerId}-${weight}`;
1693
- if (browser) {
1694
- writeEditorStorageValue(FONT_WEIGHT_KEY(controllerId), selectedWeight);
1695
- }
1696
- const current = coerceFontValue(value);
1697
- if (onChange) {
1698
- onChange({
1699
- family: current?.family || '',
1700
- weight: weight,
1701
- category: current?.category || 'Sans Serif'
1702
- });
1703
- }
1704
- }
1705
-
1706
- // Update the template to use the modified weight
1707
- $: displayWeight = selectedWeight.replace(`${controllerId}-`, '');
1708
-
1709
- // Update arrow click handler to use filteredFonts
1710
- function handleArrowClick(direction: 'up' | 'down') {
1711
- if (!filteredFonts.length) return;
1712
-
1713
- if (direction === 'down') {
1714
- activeSearchIndex = (activeSearchIndex + 1) % filteredFonts.length;
1715
- } else {
1716
- activeSearchIndex = activeSearchIndex <= 0 ? filteredFonts.length - 1 : activeSearchIndex - 1;
1717
- }
1718
-
1719
- // Ensure the selected item is visible
1720
- // (The family goes through CSS.escape: a name with a quote in it must not end the selector.)
1721
- const selectedElement = fontListContainer?.querySelector(`[data-font="${CSS.escape(filteredFonts[activeSearchIndex].family)}"]`);
1722
- selectedElement?.scrollIntoView({ block: 'nearest' });
1723
- }
1724
-
1725
- // Add a function to handle mouse enter events on font items
1726
- function handleMouseEnter(index: number) {
1727
- // Update the active index to the hovered item
1728
- activeSearchIndex = index;
1729
- }
1730
-
1731
- // Functions for RecentItemsSection
1732
- function renderFontItem(font: FontItem) {
1733
- // The result is used as HTML by RecentItemsSection: the family is quoted for CSS and escaped for HTML where it is
1734
- // a rule, and escaped for HTML where it is the text.
1735
- return {
1736
- html: `
39
+ // Svelte imports
40
+ import { onMount, onDestroy, tick } from 'svelte';
41
+ const browser = typeof window !== 'undefined';
42
+
43
+ // Shadcn Compound Components
44
+ import {
45
+ Popover,
46
+ Command,
47
+ EmptyState,
48
+ IconButton,
49
+ Skeleton
50
+ } from '@widgetic/design-system/components';
51
+
52
+ import {
53
+ IconCheck,
54
+ IconCloudUpload,
55
+ IconChevronDown,
56
+ IconChevronUp,
57
+ IconTrash
58
+ } from '@widgetic/design-system/icons';
59
+ import fontsJsonUrl from '../../assets/fonts.json?url';
60
+
61
+ // Config imports
62
+ import { config as appConfig } from '../../config';
63
+ import {
64
+ fontUtils,
65
+ fontCategories,
66
+ type FontItem,
67
+ type RecentFont,
68
+ recentFontsStore
69
+ } from '../../utils/fontUtils';
70
+ import type { FontData } from '../../utils/FontManager';
71
+ import FontManager, { mapGoogleVariantIdsToWeightNames } from '../../utils/FontManager';
72
+
73
+ import { shouldSkipFont } from '../../utils/skipFonts';
74
+ import { escapeHtml, cssQuotedString } from '../../utils/htmlSafety';
75
+ import {
76
+ acquirePortalHost,
77
+ releasePortalHost,
78
+ listenForScroll,
79
+ queryInTreeOf
80
+ } from '../../utils/shadowDom';
81
+ import { readEditorStorageValue, writeEditorStorageValue } from '../../utils/editorStorage';
82
+ import type { Writable } from 'svelte/store';
83
+
84
+ import InputControllerRow from './InputControllerRow.svelte';
85
+
86
+ // Import shared components
87
+ import { SearchInput } from '@widgetic/design-system/components';
88
+ import CategoryTabs from './shared/CategoryTabs.svelte';
89
+ import { RecentItemsSection, ItemGrid } from './shared';
90
+ import { useEditorLanguage } from '../../i18n/language';
91
+ import { categoryLabel, fontWeightLabel } from '../../i18n/labels';
92
+
93
+ // The words of the editor in the language of the page.
94
+ const { t } = useEditorLanguage();
95
+
96
+ const FONT_FILTER_KEY = (id: string) => `font-specific-filter-state-${id}`;
97
+ const FONT_WEIGHT_KEY = (id: string) => `font-weight-state-${id}`;
98
+ const MAX_RECENT_FONTS = 3;
99
+
100
+ // Then continue with the rest of the declarations
101
+ type FilterType = (typeof fontCategories.types)[number];
102
+ let currentFilter: FilterType = 'All'; // Default to 'All'
103
+ let lastActiveFilter: FilterType = 'All'; // Add this declaration
104
+ let filterOptions: FilterType[] = [...fontCategories.types];
105
+
106
+ /**
107
+ * Component Props
108
+ * @prop {string} label - Display label for the font selector
109
+ * @prop {string} value - Currently selected font family
110
+ * @prop {Function} onChange - Callback when font selection changes
111
+ * @prop {InputControllerConfig} config - Configuration options
112
+ * @prop {string} description - Optional help text
113
+ * @prop {string} controllerId - Unique identifier for this controller
114
+ * @prop {any} openDropdowns - Store tracking open dropdown states
115
+ * @prop {Function} toggleDropdown - Function to toggle dropdown state
116
+ * @prop {Function} onFocus - Optional focus handler
117
+ */
118
+ export let label: FontInputControllerProps['label'] = '';
119
+ let className = '';
120
+ export { className as class };
121
+ export let style: FontInputControllerProps['style'] = '';
122
+ export let value: FontInputControllerProps['value'] = null;
123
+ export let onChange: FontInputControllerProps['onChange'] = undefined;
124
+ export let description: FontInputControllerProps['description'] = undefined;
125
+ export let controllerId: FontInputControllerProps['controllerId'];
126
+ export let openDropdowns: FontInputControllerProps['openDropdowns'];
127
+ export let toggleDropdown: FontInputControllerProps['toggleDropdown'];
128
+
129
+ // Initialize timeouts
130
+ let scrollTimeout: ReturnType<typeof setTimeout> | null = null;
131
+
132
+ // Font weight state - remove localStorage check on init
133
+ let selectedWeight = `${controllerId}-Regular`;
134
+ let availableWeights: string[] = ['Regular', 'Medium', 'SemiBold', 'Bold'];
135
+ let fontCatalogFallbackWarned = false;
136
+
137
+ // Font search and filter state
138
+ let allFonts: FontItem[] = [];
139
+ let recentFonts: FontItem[] = [];
140
+ let filteredFonts: FontData[] = [];
141
+ let searchTerm = '';
142
+ let initialFontNumber = FontManager.initialFontNumber;
143
+ const SEARCH_BATCH_SIZE = FontManager.BATCH_SIZE;
144
+
145
+ // Font loading optimization
146
+ let fontListContainer: HTMLElement;
147
+ // The control's own element: it says which tree (the page or a module's shadow root) to listen for scrolling in
148
+ let controllerElement: HTMLDivElement | undefined;
149
+ let familyTriggerEl: HTMLDivElement | undefined;
150
+ let familyPopoverStyle = '';
151
+ let familyPopoverSide: 'top' | 'bottom' = 'bottom';
152
+ let fontObserver = new IntersectionObserver(() => {});
153
+
154
+ // Initialize FontManager instance
155
+ let fontManagerInstance: FontManager;
156
+ let buttonWidth = 0;
157
+
158
+ // Add these variables for search
159
+ let activeSearchIndex = -1;
160
+
161
+ // Add loading state
162
+ let isLoadingBatch = false;
163
+ let isInitialLoading = true; // Start with loading state true
164
+
165
+ // Add new prop for controlling font list behavior
166
+ export let hideRecentFromList: FontInputControllerProps['hideRecentFromList'] = false;
167
+ export let hideTrashIcon: FontInputControllerProps['hideTrashIcon'] = true;
168
+
169
+ function updateFamilyPopoverBox() {
170
+ if (!familyTriggerEl || typeof window === 'undefined') return;
171
+ const rect = familyTriggerEl.getBoundingClientRect();
172
+ const pad = 12;
173
+ const viewportH = window.visualViewport?.height ?? window.innerHeight;
174
+ const below = viewportH - rect.bottom - pad;
175
+ const above = rect.top - pad;
176
+ const openAbove = above > below;
177
+ familyPopoverSide = openAbove ? 'top' : 'bottom';
178
+ const available = Math.max(0, openAbove ? above : below);
179
+ const height = Math.min(565, available);
180
+ const width = Math.min(374, Math.max(240, window.innerWidth - 16));
181
+ familyPopoverStyle = `width: ${width}px; height: ${height}px; max-width: calc(100vw - 16px); max-height: ${height}px;`;
182
+ }
183
+
184
+ function handleFamilyPopoverViewportChange() {
185
+ if ($openDropdowns?.has(controllerId)) {
186
+ updateFamilyPopoverBox();
187
+ }
188
+ }
189
+
190
+ function coerceFontValue(
191
+ raw: typeof value
192
+ ): { family: string; weight: string; category: string } | null {
193
+ if (!raw) return null;
194
+ if (typeof raw === 'object' && raw.family) {
195
+ return {
196
+ family: raw.family,
197
+ weight: raw.weight || 'Regular',
198
+ category: raw.category || 'Sans Serif'
199
+ };
200
+ }
201
+ if (typeof raw === 'string' && raw.trim()) {
202
+ const family = raw.split(',')[0].replace(/['"]/g, '').trim();
203
+ if (!family) return null;
204
+ return { family, weight: 'Regular', category: 'Sans Serif' };
205
+ }
206
+ return null;
207
+ }
208
+
209
+ $: resolvedFont = coerceFontValue(value);
210
+
211
+ // Add scroll state tracking
212
+ let isScrolled = false;
213
+
214
+ // Add a timeout to track long-running initial loads
215
+ let initialLoadTimeout: ReturnType<typeof setTimeout> | null = null;
216
+
217
+ /**
218
+ * The sticky header of the font list. It is looked up in the tree the list lives in (inside a module that is a
219
+ * shadow root, which `document.querySelector` cannot see into), and the id is escaped so that one with dots or
220
+ * brackets in it is found too.
221
+ */
222
+ function findStickyHeader(): Element | null {
223
+ return queryInTreeOf(fontListContainer, `#${CSS.escape(`font-header-${controllerId}`)}`);
224
+ }
225
+
226
+ // Function to update scroll state
227
+ function updateScrollState() {
228
+ if (fontListContainer) {
229
+ const wasScrolled = isScrolled;
230
+ isScrolled = fontListContainer.scrollTop > 10;
231
+
232
+ // If we're transitioning from scrolled to not scrolled, remove transition
233
+ if (wasScrolled && !isScrolled) {
234
+ const stickyHeader = findStickyHeader();
235
+ if (stickyHeader) {
236
+ stickyHeader.classList.remove('transition-border');
237
+ // Force a reflow to ensure the transition class removal takes effect
238
+ void (stickyHeader as HTMLElement).offsetWidth;
239
+ }
240
+ } else if (!wasScrolled && isScrolled) {
241
+ // Add transition class when starting to scroll
242
+ const stickyHeader = findStickyHeader();
243
+ if (stickyHeader) {
244
+ stickyHeader.classList.add('transition-border');
245
+ }
246
+ }
247
+ }
248
+ }
249
+
250
+ // Subscribe to store changes
251
+ $: {
252
+ recentFonts = $recentFontsStore
253
+ .filter((font) => !shouldSkipFont(font.family))
254
+ .map((font) => ({
255
+ family: font.family,
256
+ category: normalizeCategory(font.category) as FontItem['category'],
257
+ isCustom: font.isCustom
258
+ }));
259
+
260
+ // Update filtered fonts when recent fonts change
261
+ if (hideRecentFromList) {
262
+ updateFilteredFonts();
263
+ }
264
+ }
265
+
266
+ // Add debounce function at the top of the script section
267
+ function debounce<T extends (...args: any[]) => Promise<void>>(
268
+ func: T,
269
+ wait: number
270
+ ): (...args: Parameters<T>) => void {
271
+ let timeout: ReturnType<typeof setTimeout> | null = null;
272
+ return function (this: any, ...args: Parameters<T>): void {
273
+ const context = this;
274
+ if (timeout) clearTimeout(timeout);
275
+ timeout = setTimeout(() => {
276
+ timeout = null;
277
+ func.apply(context, args);
278
+ }, wait);
279
+ };
280
+ }
281
+
282
+ // Add a variable to store the debounced search function
283
+ let debouncedSearch: (event: Event) => void;
284
+
285
+ let fontPickerReadyAt = 0;
286
+
287
+ /**
288
+ * The layer the font popovers are drawn in: one of their own, above everything else, in the tree this input lives
289
+ * in. On a page that is a node at the end of the body; inside a module it is a node in the module's portal layer,
290
+ * because a popover drawn in the customer's body would lose the module's styles and leave a node behind in the
291
+ * customer's page. The input has to be on the page to tell which tree it is in, so until it is (a short moment,
292
+ * and a popover is never open by then) the popovers go where the design system's portal configuration sends them.
293
+ */
294
+ let fontPickerPortalHost: HTMLElement | undefined;
295
+
296
+ function ensureFontPickerPortal() {
297
+ if (!browser || fontPickerPortalHost) return;
298
+ fontPickerPortalHost =
299
+ acquirePortalHost(familyTriggerEl, 'widgetic-font-picker-portal') ?? undefined;
300
+ }
301
+
302
+ onMount(async () => {
303
+ try {
304
+ if (browser) {
305
+ fontPickerReadyAt = Date.now() + 400;
306
+ ensureFontPickerPortal();
307
+ const coerced = coerceFontValue(value);
308
+ if (coerced?.weight) {
309
+ selectedWeight = `${controllerId}-${coerced.weight}`;
310
+ }
311
+ if (typeof value === 'string' && coerced && onChange) {
312
+ onChange(coerced);
313
+ }
314
+
315
+ // Load saved filter
316
+ const savedFilter = readEditorStorageValue(FONT_FILTER_KEY(controllerId));
317
+ if (savedFilter) {
318
+ currentFilter = savedFilter as FilterType;
319
+ }
320
+
321
+ // Load saved weight
322
+ const savedWeight = readEditorStorageValue(FONT_WEIGHT_KEY(controllerId));
323
+ if (savedWeight) {
324
+ selectedWeight = savedWeight;
325
+ }
326
+ }
327
+
328
+ // console.log('🚀 [FontInput] Initializing controller:', {
329
+ // controllerId,
330
+ // initialFilter: currentFilter
331
+ // });
332
+
333
+ // Initialize the debounced search function early
334
+ debouncedSearch = debounce(async (event: Event) => {
335
+ await handleSearch(event);
336
+ }, 300); // 300ms debounce time
337
+
338
+ // Start font manager initialization in parallel
339
+ const fontManagerPromise = FontManager.getInstance(appConfig.GOOGLE_FONTS_API_KEY);
340
+
341
+ // Load and verify recent fonts while waiting for font manager
342
+ const loadedRecentFonts = fontUtils.getRecentFonts();
343
+ // console.log('📝 [FontInput] Loading recent fonts:', loadedRecentFonts);
344
+
345
+ // Filter and validate recent fonts
346
+ const validRecentFonts = loadedRecentFonts
347
+ .filter((font) => !shouldSkipFont(font.family))
348
+ .slice(0, MAX_RECENT_FONTS);
349
+
350
+ // Update store with validated fonts
351
+ recentFontsStore.set(validRecentFonts);
352
+
353
+ // Update local state
354
+ recentFonts = validRecentFonts.map((font) => ({
355
+ family: font.family,
356
+ category: normalizeCategory(font.category) as FontItem['category'],
357
+ isCustom: font.isCustom
358
+ }));
359
+
360
+ // console.log('✅ [FontInput] Recent fonts initialized:', {
361
+ // loaded: loadedRecentFonts.length,
362
+ // valid: validRecentFonts.length,
363
+ // fonts: validRecentFonts.map(f => f.family)
364
+ // });
365
+
366
+ // Now wait for font manager to be ready
367
+ fontManagerInstance = await fontManagerPromise;
368
+
369
+ // Try to get preloaded fonts immediately
370
+ let preloadedFonts: FontData[] = [];
371
+
372
+ // Check if we can get preloaded fonts for the current category
373
+ if (currentFilter !== 'All' && currentFilter !== 'Mine') {
374
+ // console.log(`🔍 [FontInput:${controllerId}] Getting preloaded fonts for category:`, currentFilter);
375
+ preloadedFonts = fontManagerInstance.getPreloadedFonts(
376
+ currentFilter as FontItem['category']
377
+ );
378
+
379
+ if (preloadedFonts.length > 0) {
380
+ // console.log(`✅ [FontInput:${controllerId}] Using preloaded fonts for initial display:`, {
381
+ // category: currentFilter,
382
+ // count: preloadedFonts.length,
383
+ // fonts: preloadedFonts.slice(0, 3).map(f => f.family)
384
+ // });
385
+
386
+ // Filter out fonts that should be skipped
387
+ const filteredPreloadedFonts = preloadedFonts.filter(
388
+ (font) => !shouldSkipFont(font.family)
389
+ );
390
+
391
+ // Update allFonts with preloaded fonts
392
+ allFonts = filteredPreloadedFonts;
393
+
394
+ // Update filtered fonts immediately
395
+ updateFilteredFonts();
396
+
397
+ // Only set loading to false if we have fonts to display
398
+ if (filteredFonts.length > 0) {
399
+ isInitialLoading = false;
400
+ // console.log(`✅ [FontInput:${controllerId}] Initial loading complete with preloaded fonts:`, {
401
+ // filteredFonts: filteredFonts.length,
402
+ // category: currentFilter
403
+ // });
404
+
405
+ // Clear the timeout since we've loaded successfully
406
+ if (initialLoadTimeout) {
407
+ clearTimeout(initialLoadTimeout);
408
+ initialLoadTimeout = null;
409
+ }
410
+ }
411
+ } else {
412
+ // console.log(`⚠️ [FontInput:${controllerId}] No preloaded fonts available for category:`, currentFilter);
413
+ }
414
+ } else if (currentFilter === 'All') {
415
+ // console.log(`🔍 [FontInput:${controllerId}] Getting initial batch for All category`);
416
+ // For All category, get the first batch
417
+ preloadedFonts = fontManagerInstance.getNextBatch(controllerId, 'All');
418
+
419
+ if (preloadedFonts.length > 0) {
420
+ // console.log(`✅ [FontInput:${controllerId}] Using initial batch for All category:`, {
421
+ // count: preloadedFonts.length,
422
+ // fonts: preloadedFonts.slice(0, 3).map(f => f.family)
423
+ // });
424
+
425
+ // Filter out fonts that should be skipped
426
+ const filteredPreloadedFonts = preloadedFonts.filter(
427
+ (font) => !shouldSkipFont(font.family)
428
+ );
429
+
430
+ // Update allFonts with preloaded fonts
431
+ allFonts = filteredPreloadedFonts;
432
+
433
+ // Update filtered fonts immediately
434
+ updateFilteredFonts();
435
+
436
+ // Only set loading to false if we have fonts to display
437
+ if (filteredFonts.length > 0) {
438
+ isInitialLoading = false;
439
+ // console.log(`✅ [FontInput:${controllerId}] Initial loading complete for All category:`, {
440
+ // filteredFonts: filteredFonts.length
441
+ // });
442
+
443
+ // Clear the timeout since we've loaded successfully
444
+ if (initialLoadTimeout) {
445
+ clearTimeout(initialLoadTimeout);
446
+ initialLoadTimeout = null;
447
+ }
448
+ }
449
+ }
450
+ } else if (currentFilter === 'Mine') {
451
+ // console.log(`🔍 [FontInput:${controllerId}] Getting custom fonts for Mine category`);
452
+ // For Mine category, first check if we already have preloaded fonts
453
+ preloadedFonts = fontManagerInstance.getPreloadedFonts('Mine');
454
+
455
+ if (preloadedFonts.length > 0) {
456
+ // console.log(`✅ [FontInput:${controllerId}] Using preloaded custom fonts for Mine category:`, {
457
+ // count: preloadedFonts.length,
458
+ // fonts: preloadedFonts.slice(0, 3).map(f => f.family)
459
+ // });
460
+ } else {
461
+ // If no preloaded fonts found, load them now
462
+ // console.log(`📚 [FontInput:${controllerId}] No preloaded custom fonts found, loading them now...`);
463
+ preloadedFonts = await fontManagerInstance.loadCustomFonts();
464
+ }
465
+
466
+ if (preloadedFonts.length > 0) {
467
+ // Update allFonts with custom fonts
468
+ allFonts = preloadedFonts;
469
+
470
+ // Update filtered fonts immediately
471
+ updateFilteredFonts();
472
+
473
+ // Only set loading to false if we have fonts to display
474
+ if (filteredFonts.length > 0) {
475
+ isInitialLoading = false;
476
+ // console.log(`✅ [FontInput:${controllerId}] Initial loading complete for Mine category:`, {
477
+ // filteredFonts: filteredFonts.length
478
+ // });
479
+
480
+ // Clear the timeout since we've loaded successfully
481
+ if (initialLoadTimeout) {
482
+ clearTimeout(initialLoadTimeout);
483
+ initialLoadTimeout = null;
484
+ }
485
+ }
486
+ }
487
+ }
488
+
489
+ // Only set loading state if we couldn't get preloaded fonts
490
+ if (preloadedFonts.length === 0) {
491
+ // console.log(`⚠️ [FontInput:${controllerId}] No preloaded fonts available, will load asynchronously`);
492
+ // Keep isInitialLoading as true
493
+
494
+ // Set a timeout to show loading indicator if initialization takes too long
495
+ initialLoadTimeout = setTimeout(() => {
496
+ // If we're still loading after 1 second, show the loading indicator
497
+ if (isInitialLoading) {
498
+ // console.log(`⚠️ [FontInput:${controllerId}] Initial font loading taking longer than expected`);
499
+ }
500
+ }, 1000); // Reduced from 2000ms to 1000ms
501
+ }
502
+
503
+ // Initialize fonts list with saved filter - use a separate async function
504
+ // to avoid blocking the UI
505
+ const initializeFontsAsync = async () => {
506
+ try {
507
+ // console.log(`🔄 [FontInput:${controllerId}] Starting font initialization for controller:`, controllerId);
508
+
509
+ // First, ensure the FontManager is fully initialized
510
+ if (!FontManager.isInitialized) {
511
+ // console.log(`⏳ [FontInput:${controllerId}] Waiting for FontManager to initialize...`);
512
+ // This will wait for the initialization promise to resolve
513
+ await FontManager.getInstance(appConfig.GOOGLE_FONTS_API_KEY);
514
+ }
515
+
516
+ // Skip loading if we already have preloaded fonts
517
+ if (allFonts.length === 0) {
518
+ // console.log(`🔍 [FontInput:${controllerId}] No fonts loaded yet, loading initial batch for ${currentFilter}`);
519
+ // Instead of loading all fonts, just get the first batch
520
+ let initialFonts: FontData[] = [];
521
+
522
+ if (currentFilter === 'Mine') {
523
+ // For Mine category, first check if we have preloaded fonts
524
+ initialFonts = fontManagerInstance.getPreloadedFonts('Mine');
525
+
526
+ if (initialFonts.length > 0) {
527
+ // console.log(`📚 [FontInput:${controllerId}] Using preloaded custom fonts:`, {
528
+ // count: initialFonts.length,
529
+ // fonts: initialFonts.slice(0, 3).map(f => f.family)
530
+ // });
531
+ } else {
532
+ // If no preloaded fonts, load them now
533
+ // console.log(`📚 [FontInput:${controllerId}] No preloaded custom fonts found, loading them now...`);
534
+ initialFonts = await fontManagerInstance.loadCustomFonts();
535
+ }
536
+ } else if (currentFilter === 'All') {
537
+ // For All category, get the first batch
538
+ initialFonts = fontManagerInstance.getNextBatch(controllerId, 'All');
539
+ // console.log(`📚 [FontInput:${controllerId}] Loaded initial batch for All:`, {
540
+ // count: initialFonts.length,
541
+ // fonts: initialFonts.slice(0, 3).map(f => f.family)
542
+ // });
543
+ } else {
544
+ // For specific categories, first try to get preloaded fonts
545
+ initialFonts = fontManagerInstance.getPreloadedFonts(
546
+ currentFilter as FontItem['category']
547
+ );
548
+
549
+ if (initialFonts.length === 0) {
550
+ // If no preloaded fonts, get the first batch filtered by category
551
+ // console.log(`📚 [FontInput:${controllerId}] No preloaded fonts for ${currentFilter}, getting batch`);
552
+ initialFonts = fontManagerInstance.getNextBatch(controllerId, currentFilter);
553
+ } else {
554
+ // console.log(`📚 [FontInput:${controllerId}] Using preloaded fonts for ${currentFilter}:`, {
555
+ // count: initialFonts.length,
556
+ // fonts: initialFonts.slice(0, 3).map(f => f.family)
557
+ // });
558
+ }
559
+ }
560
+
561
+ // Filter out fonts that should be skipped
562
+ const filteredFonts = initialFonts.filter((font) => !shouldSkipFont(font.family));
563
+ // console.log(`🔍 [FontInput:${controllerId}] Filtered initial fonts:`, {
564
+ // before: initialFonts.length,
565
+ // after: filteredFonts.length,
566
+ // skipped: initialFonts.length - filteredFonts.length
567
+ // });
568
+
569
+ // Update allFonts with just the initial batch
570
+ allFonts = filteredFonts;
571
+
572
+ // Update filtered fonts immediately
573
+ updateFilteredFonts();
574
+ } else {
575
+ // console.log(`✅ [FontInput:${controllerId}] Already have fonts loaded:`, {
576
+ // count: allFonts.length,
577
+ // category: currentFilter
578
+ // });
579
+ }
580
+
581
+ // Set loading to false after fonts are loaded
582
+ // Only set loading to false if we have fonts to display
583
+ if (filteredFonts.length > 0) {
584
+ isInitialLoading = false;
585
+ // console.log(`✅ [FontInput:${controllerId}] Initialization complete with fonts:`, {
586
+ // count: filteredFonts.length,
587
+ // category: currentFilter
588
+ // });
589
+ } else {
590
+ // console.log(`⚠️ [FontInput:${controllerId}] No fonts found after initialization`);
591
+ // Still set loading to false to show empty state
592
+ isInitialLoading = false;
593
+ }
594
+
595
+ // Clear the timeout since we've loaded successfully
596
+ if (initialLoadTimeout) {
597
+ clearTimeout(initialLoadTimeout);
598
+ initialLoadTimeout = null;
599
+ }
600
+
601
+ // console.log(`✅ [FontInput:${controllerId}] Controller initialized with fonts:`, {
602
+ // controllerId,
603
+ // allFonts: allFonts.length,
604
+ // filteredFonts: filteredFonts.length,
605
+ // recentFonts: recentFonts.length,
606
+ // currentFilter,
607
+ // customFonts: allFonts.filter(f => f.category === 'Mine').length
608
+ // });
609
+ } catch (error) {
610
+ console.error(
611
+ `❌ [FontInput:${controllerId}] Error during async font initialization:`,
612
+ error
613
+ );
614
+ isInitialLoading = false; // Make sure to set loading to false even on error
615
+
616
+ // Clear the timeout on error
617
+ if (initialLoadTimeout) {
618
+ clearTimeout(initialLoadTimeout);
619
+ initialLoadTimeout = null;
620
+ }
621
+ }
622
+ };
623
+
624
+ // Start the async initialization without waiting for it
625
+ initializeFontsAsync();
626
+ } catch (error) {
627
+ console.error('❌ [FontInput] Error during initialization:', error);
628
+ isInitialLoading = false; // Make sure to set loading to false even on error
629
+
630
+ // Clear the timeout on error
631
+ if (initialLoadTimeout) {
632
+ clearTimeout(initialLoadTimeout);
633
+ initialLoadTimeout = null;
634
+ }
635
+ }
636
+ });
637
+
638
+ /**
639
+ * Initialize fonts based on the current filter
640
+ */
641
+ async function initializeFonts() {
642
+ if (currentFilter === 'Mine') {
643
+ // First check if we have preloaded fonts
644
+ const preloadedCustomFonts = fontManagerInstance.getPreloadedFonts('Mine');
645
+
646
+ if (preloadedCustomFonts.length > 0) {
647
+ // console.log(`📚 [FontInput:${controllerId}] Using preloaded custom fonts in initializeFonts:`, {
648
+ // count: preloadedCustomFonts.length,
649
+ // fonts: preloadedCustomFonts.slice(0, 3).map(f => f.family)
650
+ // });
651
+ return preloadedCustomFonts;
652
+ } else {
653
+ // If no preloaded fonts, load them now
654
+ // console.log(`📚 [FontInput:${controllerId}] No preloaded custom fonts found in initializeFonts, loading them now...`);
655
+ const customFonts = await fontManagerInstance.loadCustomFonts();
656
+ return customFonts;
657
+ }
658
+ }
659
+
660
+ // For All category, load Google Fonts first, then get custom fonts (already preloaded or load them)
661
+ const googleFonts = await fontManagerInstance.getInitialFontList();
662
+
663
+ // First check if we have preloaded custom fonts
664
+ let customFonts = fontManagerInstance.getPreloadedFonts('Mine');
665
+
666
+ if (customFonts.length === 0) {
667
+ // If no preloaded custom fonts, load them now
668
+ customFonts = await fontManagerInstance.loadCustomFonts();
669
+ }
670
+
671
+ if (currentFilter === 'All') {
672
+ return [...googleFonts.filter((font) => !font.isCustom), ...customFonts];
673
+ }
674
+
675
+ // For other categories, filter out custom fonts
676
+ return googleFonts.filter((font) => !font.isCustom);
677
+ }
678
+
679
+ /**
680
+ * Fetches available fonts from Google Fonts API
681
+ */
682
+ async function fetchGoogleFonts() {
683
+ try {
684
+ // console.log('🔍 [FontInput] Fetching Google Fonts...');
685
+ fontManagerInstance = await FontManager.getInstance(appConfig.GOOGLE_FONTS_API_KEY);
686
+ allFonts = await fontManagerInstance.getCompleteFontList();
687
+ updateFilteredFonts();
688
+
689
+ // console.log('✅ [FontInput] Fonts available:', allFonts.length);
690
+ } catch (error) {
691
+ console.error('❌ [FontInput] Error getting Google Fonts:', error);
692
+ }
693
+ }
694
+
695
+ /**
696
+ * Opens the file browser for font selection
697
+ * Receives font files in the format matching fonts
698
+ */
699
+ async function openFileBrowser() {
700
+ // console.log('🔍 [FontInput] Opening file browser for fonts:');
701
+ // try {
702
+ // // Get the current font's ID if it exists in our custom fonts
703
+ // const selectedId = resolvedFont?.family ?
704
+ // fontManagerInstance?.getCachedFontList()
705
+ // .find(f => f.family === value.family && f.category === 'Mine')?.id
706
+ // : undefined;
707
+ // console.log('🔍 [FontInput] Opening file browser for fonts:', {
708
+ // fileTypes: ['font'],
709
+ // selectedId
710
+ // });
711
+ // const result = await window.uiSDK?.mountComponent('file-browser', {
712
+ // container: '#file-browser',
713
+ // config: {
714
+ // fileTypes: ['font'],
715
+ // selectedId,
716
+ // batch: 1000 // allow for a large number of fonts to be selected
717
+ // },
718
+ // callbacks: {
719
+ // onSelect: async (fontData: any) => {
720
+ // if (!fontData) return;
721
+ // const fontValue = {
722
+ // family: fontData.family,
723
+ // weight: fontData.weight,
724
+ // category: 'Mine' // Set category to Mine for uploaded fonts
725
+ // };
726
+ // console.log('✅ [FontInput] Font selected:', {
727
+ // ...fontValue,
728
+ // format: fontData.url.split('.').pop()
729
+ // });
730
+ // if (onChange) {
731
+ // onChange(fontValue);
732
+ // }
733
+ // },
734
+ // onError: (error: Error) => {
735
+ // console.error('❌ [FontInput] File Browser error:', error);
736
+ // }
737
+ // });
738
+ // } catch (error) {
739
+ // console.error('❌ [FontInput] Error opening file browser:', error);
740
+ // }
741
+ }
742
+
743
+ /**
744
+ * Updates the filtered fonts list based on search term and category
745
+ * Also handles setting up the observer after updating
746
+ *
747
+ * Logic flow:
748
+ * 1. Start with all fonts
749
+ * 2. Apply search filter if term exists
750
+ * 3. Apply category filter if not 'All'
751
+ */
752
+ function updateFilteredFonts() {
753
+ let fonts = [...allFonts];
754
+
755
+ // Clear both filters when search is active
756
+ if (searchTerm) {
757
+ const term = searchTerm.toLowerCase();
758
+ fonts = fonts.filter((font) => font.family.toLowerCase().includes(term));
759
+
760
+ // Force category to All when searching
761
+ currentFilter = 'All';
762
+ } else {
763
+ if (currentFilter !== 'All') {
764
+ fonts = fonts.filter((font) => {
765
+ if (currentFilter === 'Mine') return font.category === 'Mine';
766
+ return normalizeCategory(font.category) === currentFilter;
767
+ });
768
+ }
769
+ }
770
+
771
+ // Optionally filter out recent fonts
772
+ if (hideRecentFromList) {
773
+ const beforeRecent = fonts.length;
774
+ fonts = fonts.filter((font) => !recentFonts.some((recent) => recent.family === font.family));
775
+ // console.log(`🔍 [FontInput:${controllerId}] Filtered out recent fonts:`, {
776
+ // beforeFilter: beforeRecent,
777
+ // afterFilter: fonts.length,
778
+ // recentFontsRemoved: beforeRecent - fonts.length
779
+ // });
780
+ }
781
+
782
+ // Update filtered fonts
783
+ filteredFonts = fonts;
784
+
785
+ // console.log(`✅ [FontInput:${controllerId}] Filtered fonts result:`, {
786
+ // total: fonts.length,
787
+ // filter: currentFilter,
788
+ // searchTerm,
789
+ // hideRecentFromList,
790
+ // recentFontsHidden: hideRecentFromList ? recentFonts.length : 0,
791
+ // initialFontNumber
792
+ // });
793
+
794
+ // Setup observer after updating filtered fonts
795
+ // Use a small timeout to ensure the DOM has updated
796
+ if (scrollTimeout) {
797
+ clearTimeout(scrollTimeout);
798
+ }
799
+
800
+ scrollTimeout = setTimeout(() => {
801
+ setupFontObserver();
802
+ }, 50);
803
+ }
804
+
805
+ /**
806
+ * Handles font selection and updates recent fonts
807
+ */
808
+ function handleFontSelect(font: FontItem | RecentFont) {
809
+ if (onChange) {
810
+ // The family has to reach the card even when the weight catalog fails.
811
+ onChange({
812
+ family: font.family,
813
+ weight: 'Regular',
814
+ category: font.category
815
+ });
816
+ // Reset weight to Regular or first available weight
817
+ fetchFontWeights(font.family)
818
+ .then(async () => {
819
+ const newWeight = availableWeights.includes('Regular') ? 'Regular' : availableWeights[0];
820
+
821
+ selectedWeight = `${controllerId}-${newWeight}`;
822
+ if (browser) {
823
+ writeEditorStorageValue(FONT_WEIGHT_KEY(controllerId), selectedWeight);
824
+ }
825
+
826
+ // Load the full font when selected
827
+ if (!fontManagerInstance?.isCustomFont(font.family)) {
828
+ await fontManagerInstance?.loadFullFont(font.family);
829
+ }
830
+
831
+ // Create the font value object with reset weight
832
+ const fontValue = {
833
+ family: font.family,
834
+ weight: newWeight,
835
+ category: font.category
836
+ };
837
+
838
+ // Pass the font value object to onChange
839
+ onChange(fontValue);
840
+
841
+ // console.log('✅ [FontInput] Font selected:', {
842
+ // font: fontValue
843
+ // });
844
+ })
845
+ .catch((error) => {
846
+ console.error('[FontInput] Weight lookup failed after the family was applied:', error);
847
+ });
848
+ }
849
+ }
850
+
851
+ /**
852
+ * Manages real-time search functionality
853
+ * Prioritizes recent fonts in search results
854
+ * Enhanced to better handle partial matches
855
+ */
856
+ async function handleSearch(event: Event) {
857
+ const input = event.target as HTMLInputElement;
858
+ const newSearchTerm = input.value;
859
+
860
+ // Skip processing if the search term hasn't changed
861
+ if (newSearchTerm === searchTerm) return;
862
+
863
+ // Use debounced version only for typing
864
+ debouncedSearch(event);
865
+ }
866
+
867
+ // Add paste handler
868
+ function handlePaste(event: ClipboardEvent) {
869
+ const pastedText = event.clipboardData?.getData('text/plain') || '';
870
+
871
+ // Don't prevent default - let the paste happen naturally
872
+ // Then trigger an immediate search update with the pasted content
873
+ // searchTerm will be updated through binding
874
+
875
+ // Schedule the handleSearchImmediate for the next tick to ensure
876
+ // the input value is updated with the pasted content first
877
+ setTimeout(() => {
878
+ handleSearchImmediate(pastedText);
879
+ }, 0);
880
+ }
881
+
882
+ // Separate immediate search handler (keep this)
883
+ async function handleSearchImmediate(value: string) {
884
+ // Store current filter before overriding it
885
+ if (!searchTerm && value) {
886
+ lastActiveFilter = currentFilter;
887
+ currentFilter = 'All';
888
+ writeEditorStorageValue(FONT_FILTER_KEY(controllerId), 'All');
889
+ }
890
+
891
+ // Apply filtering with the new search term
892
+ updateFilteredFonts();
893
+
894
+ // Reset scroll position if needed
895
+ if (fontListContainer) {
896
+ fontListContainer.scrollTop = 0;
897
+ }
898
+ }
899
+
900
+ // Add a derived store for search results
901
+ let currentSearchResults: FontData[] = [];
902
+
903
+ // Update the reactive statement for search
904
+ $: if (searchTerm) {
905
+ const searchValue = searchTerm.toLowerCase().trim();
906
+ // Only process if the search value is not empty
907
+ if (searchValue) {
908
+ // Get both Google Fonts and custom fonts from cache
909
+ const googleFonts =
910
+ fontManagerInstance?.getCachedFontList().filter((font) => !font.isCustom) || [];
911
+ const customFonts =
912
+ fontManagerInstance?.getCachedFontList().filter((font) => font.isCustom) || [];
913
+
914
+ // Merge both lists
915
+ const allCachedFonts = [...googleFonts, ...customFonts];
916
+
917
+ // Modified search algorithm to use exact matching
918
+ const newSearchResults = allCachedFonts
919
+ .filter((font) => {
920
+ const familyLower = font.family.toLowerCase().trim();
921
+
922
+ // Skip fonts that should be excluded
923
+ if (shouldSkipFont(font.family)) {
924
+ return false;
925
+ }
926
+
927
+ // Check if the search value is found in the font family
928
+ return familyLower.includes(searchValue);
929
+ })
930
+ .sort((a, b) => {
931
+ const aFamily = a.family.toLowerCase();
932
+ const bFamily = b.family.toLowerCase();
933
+
934
+ // Prioritize fonts that start with the search term
935
+ const aStartsWith = aFamily.startsWith(searchValue);
936
+ const bStartsWith = bFamily.startsWith(searchValue);
937
+
938
+ if (aStartsWith && !bStartsWith) return -1;
939
+ if (!aStartsWith && bStartsWith) return 1;
940
+
941
+ // Then prioritize fonts where search term appears earlier
942
+ const aIndex = aFamily.indexOf(searchValue);
943
+ const bIndex = bFamily.indexOf(searchValue);
944
+
945
+ if (aIndex !== -1 && bIndex !== -1) {
946
+ return aIndex - bIndex;
947
+ }
948
+
949
+ // Fall back to alphabetical sorting
950
+ return aFamily.localeCompare(bFamily);
951
+ });
952
+
953
+ // Only update results if they've changed
954
+ if (JSON.stringify(newSearchResults) !== JSON.stringify(currentSearchResults)) {
955
+ // Store all search results for batching
956
+ currentSearchResults = newSearchResults;
957
+
958
+ // Select first item automatically only if we have results and no item is currently selected
959
+ if (currentSearchResults.length > 0 && activeSearchIndex === -1) {
960
+ activeSearchIndex = 0;
961
+ }
962
+
963
+ // Show more initial results (double the default)
964
+ const initialResultsCount = Math.min(
965
+ FontManager.initialFontNumber * 2,
966
+ currentSearchResults.length
967
+ );
968
+ filteredFonts = currentSearchResults.slice(0, initialResultsCount);
969
+
970
+ // Reset scroll position
971
+ if (fontListContainer) {
972
+ fontListContainer.scrollTop = 0;
973
+ }
974
+
975
+ // Preload only the first batch of fonts
976
+ filteredFonts.forEach((font) => {
977
+ fontManagerInstance?.loadFullFont(font.family);
978
+ });
979
+
980
+ // console.log('📝 [FontSearch] Updated results:', {
981
+ // searchValue,
982
+ // totalMatches: currentSearchResults.length,
983
+ // displayedResults: filteredFonts.length,
984
+ // activeIndex: activeSearchIndex
985
+ // });
986
+ }
987
+ }
988
+ }
989
+
990
+ // Handle empty search term separately to avoid reactivity loop
991
+ $: if (searchTerm === '') {
992
+ // Only reset if we actually had search results before or if we have no filtered fonts
993
+ if (currentSearchResults.length > 0 || filteredFonts.length === 0) {
994
+ // console.log('🔄 [FontSearch] Handling empty search term');
995
+
996
+ // Reset search state
997
+ currentSearchResults = [];
998
+ activeSearchIndex = -1; // Reset active index
999
+
1000
+ // Reset batch index to start fresh
1001
+ if (fontManagerInstance) {
1002
+ fontManagerInstance.resetBatchIndex(controllerId);
1003
+
1004
+ // Get fonts for current category
1005
+ let fonts: FontData[] = [];
1006
+
1007
+ if (currentFilter === 'All') {
1008
+ // Get initial batch of fonts instead of all fonts
1009
+ fonts = fontManagerInstance.getNextBatch(controllerId, currentFilter);
1010
+ // Update all fonts
1011
+ allFonts = fonts;
1012
+ // Update filtered fonts
1013
+ filteredFonts = [];
1014
+ updateFilteredFonts();
1015
+ } else if (currentFilter === 'Mine') {
1016
+ // For Mine category, first check if we have preloaded fonts
1017
+ const preloadedCustomFonts = fontManagerInstance.getPreloadedFonts('Mine');
1018
+
1019
+ if (preloadedCustomFonts.length > 0) {
1020
+ // Use preloaded custom fonts
1021
+ // console.log(`📚 [FontInput:${controllerId}] Using preloaded custom fonts for empty search:`, {
1022
+ // count: preloadedCustomFonts.length,
1023
+ // fonts: preloadedCustomFonts.slice(0, 3).map(f => f.family)
1024
+ // });
1025
+ allFonts = preloadedCustomFonts;
1026
+ filteredFonts = [];
1027
+ updateFilteredFonts();
1028
+ } else {
1029
+ // If no preloaded fonts, load them asynchronously
1030
+ // console.log(`📚 [FontInput:${controllerId}] No preloaded custom fonts found for empty search, loading them now...`);
1031
+ fontManagerInstance.loadCustomFonts().then((customFonts) => {
1032
+ allFonts = customFonts || [];
1033
+ filteredFonts = [];
1034
+ updateFilteredFonts();
1035
+ });
1036
+ }
1037
+ } else {
1038
+ // For other categories (Serif, Sans Serif, etc.), get initial batch by category
1039
+ fonts = fontManagerInstance.getNextBatch(controllerId, currentFilter);
1040
+ // Update all fonts
1041
+ allFonts = fonts;
1042
+ // Update filtered fonts
1043
+ filteredFonts = [];
1044
+ updateFilteredFonts();
1045
+ }
1046
+ }
1047
+
1048
+ // Reset scroll position when clearing search (for non-Mine categories)
1049
+ if (currentFilter !== 'Mine' && fontListContainer) {
1050
+ fontListContainer.scrollTop = 0;
1051
+ }
1052
+
1053
+ // Setup observer in next tick for non-Mine categories
1054
+ if (currentFilter !== 'Mine') {
1055
+ if (scrollTimeout) {
1056
+ clearTimeout(scrollTimeout);
1057
+ }
1058
+
1059
+ scrollTimeout = setTimeout(() => {
1060
+ if (fontListContainer) {
1061
+ setupFontObserver();
1062
+ }
1063
+ }, 50);
1064
+ }
1065
+
1066
+ // console.log('🔄 [FontSearch] Reset search state:', {
1067
+ // currentFilter,
1068
+ // allFonts: allFonts.length,
1069
+ // filteredFonts: filteredFonts.length
1070
+ // });
1071
+ }
1072
+ }
1073
+
1074
+ // Update keyboard navigation to use filteredFonts
1075
+ function handleSearchKeydown(event: KeyboardEvent | CustomEvent<KeyboardEvent>) {
1076
+ // Ensure we have a KeyboardEvent
1077
+ const keyEvent = event instanceof KeyboardEvent ? event : event.detail;
1078
+
1079
+ // Prevent handling backspace when search is already empty
1080
+ if (keyEvent.key === 'Backspace' && !searchTerm) {
1081
+ keyEvent.preventDefault();
1082
+ return;
1083
+ }
1084
+
1085
+ if (!filteredFonts.length) return;
1086
+
1087
+ if (keyEvent.key === 'ArrowDown') {
1088
+ keyEvent.preventDefault();
1089
+ handleArrowClick('down');
1090
+ } else if (keyEvent.key === 'ArrowUp') {
1091
+ keyEvent.preventDefault();
1092
+ handleArrowClick('up');
1093
+ } else if (keyEvent.key === 'Enter' && activeSearchIndex !== -1) {
1094
+ keyEvent.preventDefault();
1095
+ handleFontSelect(filteredFonts[activeSearchIndex]);
1096
+ }
1097
+ }
1098
+
1099
+ async function handleFilterChange(filter: FilterType) {
1100
+ if (currentFilter !== filter) {
1101
+ lastActiveFilter = filter; // Store the new filter as last active
1102
+ currentFilter = filter;
1103
+
1104
+ if (browser) {
1105
+ writeEditorStorageValue(FONT_FILTER_KEY(controllerId), filter);
1106
+ }
1107
+
1108
+ if (fontManagerInstance) {
1109
+ fontManagerInstance.resetBatchIndex(controllerId);
1110
+
1111
+ try {
1112
+ // console.log(`🔄 [FontInput:${controllerId}] Category changed to:`, filter);
1113
+ let fonts: FontData[] = [];
1114
+
1115
+ if (filter === 'All') {
1116
+ // Get initial batch of fonts instead of all fonts
1117
+ fonts = fontManagerInstance.getNextBatch(controllerId, filter);
1118
+ // console.log(`📚 [FontInput:${controllerId}] Loaded initial batch for All category:`, {
1119
+ // count: fonts.length,
1120
+ // fonts: fonts.slice(0, 3).map(f => f.family)
1121
+ // });
1122
+ } else if (filter === 'Mine') {
1123
+ // Check if custom fonts are already loaded by getting them from the FontManager instance
1124
+ fonts = fontManagerInstance.getPreloadedFonts('Mine');
1125
+
1126
+ if (fonts.length === 0) {
1127
+ // If no preloaded custom fonts found, load them
1128
+ // console.log(`📚 [FontInput:${controllerId}] No preloaded custom fonts found, loading them now...`);
1129
+ fonts = await fontManagerInstance.loadCustomFonts();
1130
+ } else {
1131
+ // console.log(`📚 [FontInput:${controllerId}] Using preloaded custom fonts:`, {
1132
+ // count: fonts.length,
1133
+ // fonts: fonts.slice(0, 3).map(f => f.family)
1134
+ // });
1135
+ }
1136
+ } else {
1137
+ // For other categories, first try to get preloaded fonts
1138
+ fonts = fontManagerInstance.getPreloadedFonts(filter as FontItem['category']);
1139
+
1140
+ if (fonts.length > 0) {
1141
+ // console.log(`📚 [FontInput:${controllerId}] Using preloaded fonts for ${filter}:`, {
1142
+ // count: fonts.length,
1143
+ // fonts: fonts.slice(0, 3).map(f => f.family)
1144
+ // });
1145
+ } else {
1146
+ // If no preloaded fonts, get the first batch filtered by category
1147
+ // console.log(`📚 [FontInput:${controllerId}] No preloaded fonts for ${filter}, getting batch`);
1148
+ fonts = fontManagerInstance.getNextBatch(controllerId, filter);
1149
+ }
1150
+ }
1151
+
1152
+ // Filter out fonts that should be skipped
1153
+ const filteredFonts = fonts.filter((font) => !shouldSkipFont(font.family));
1154
+ // console.log(`🔍 [FontInput:${controllerId}] Filtered fonts after category change:`, {
1155
+ // before: fonts.length,
1156
+ // after: filteredFonts.length,
1157
+ // skipped: fonts.length - filteredFonts.length
1158
+ // });
1159
+
1160
+ allFonts = filteredFonts;
1161
+ updateFilteredFonts();
1162
+
1163
+ // Setup observer in next tick
1164
+ scrollTimeout = setTimeout(() => {
1165
+ if (fontListContainer) {
1166
+ setupFontObserver();
1167
+ }
1168
+ }, 0);
1169
+
1170
+ if (fontListContainer) {
1171
+ fontListContainer.scrollTop = 0;
1172
+ }
1173
+
1174
+ // console.log(`✅ [FontInput:${controllerId}] Category change complete:`, {
1175
+ // filter,
1176
+ // fonts: allFonts.length,
1177
+ // filteredFonts: filteredFonts.length,
1178
+ // customFonts: allFonts.filter(f => f.isCustom).length
1179
+ // });
1180
+ } catch (error) {
1181
+ console.error(`❌ [FontInput:${controllerId}] Error changing category:`, error);
1182
+ }
1183
+ }
1184
+ }
1185
+ }
1186
+ /**
1187
+ * Manages intersection observer for lazy loading fonts
1188
+ * Only loads fonts when they become visible in viewport
1189
+ */
1190
+ function setupFontObserver() {
1191
+ if (!fontListContainer) {
1192
+ // console.log(`⚠️ [FontInput:${controllerId}] Font list container not found, retrying...`);
1193
+ return (scrollTimeout = setTimeout(() => {
1194
+ if (fontListContainer) {
1195
+ setupFontObserver();
1196
+ }
1197
+ }, 50));
1198
+ }
1199
+
1200
+ // If we have no fonts to observe, try to update filtered fonts first
1201
+ if (!filteredFonts.length) {
1202
+ // console.log(`⚠️ [FontInput:${controllerId}] No fonts available to observe, updating filtered fonts`);
1203
+ updateFilteredFonts();
1204
+
1205
+ // If we still have no fonts, log a warning and return
1206
+ if (!filteredFonts.length) {
1207
+ // console.warn(`❌ [FontInput:${controllerId}] No fonts available to observe after update`);
1208
+ return;
1209
+ }
1210
+ }
1211
+
1212
+ // console.log(`🔍 [FontInput:${controllerId}] Setting up font observer for`, filteredFonts.length, 'fonts');
1213
+
1214
+ // Get the observer from FontManager
1215
+ const observer = fontManagerInstance?.getObserver(fontListContainer);
1216
+ if (!observer) {
1217
+ // console.warn(`❌ [FontInput:${controllerId}] Failed to create observer`);
1218
+ return;
1219
+ }
1220
+
1221
+ // Disconnect existing observer if it exists
1222
+ if (fontObserver) {
1223
+ fontObserver.disconnect();
1224
+ }
1225
+
1226
+ fontObserver = observer;
1227
+
1228
+ // Use a more efficient approach to observe elements
1229
+ // First, get all font elements that need to be observed
1230
+ const fontElements = fontListContainer.querySelectorAll('[data-font]');
1231
+
1232
+ // If there are no elements to observe, try again after a short delay
1233
+ if (fontElements.length === 0) {
1234
+ // console.log(`⚠️ [FontInput:${controllerId}] No font elements found to observe, will retry`);
1235
+ return (scrollTimeout = setTimeout(() => {
1236
+ setupFontObserver();
1237
+ }, 100));
1238
+ }
1239
+
1240
+ // console.log(`📝 [FontInput:${controllerId}] Observing`, fontElements.length, 'font elements');
1241
+
1242
+ // Use a more efficient approach to observe elements
1243
+ // Batch the observation process to reduce performance impact
1244
+ const batchSize = 20; // Process 20 elements at a time
1245
+ let currentIndex = 0;
1246
+
1247
+ const observeBatch = () => {
1248
+ const endIndex = Math.min(currentIndex + batchSize, fontElements.length);
1249
+
1250
+ for (let i = currentIndex; i < endIndex; i++) {
1251
+ observer.observe(fontElements[i]);
1252
+ }
1253
+
1254
+ currentIndex = endIndex;
1255
+
1256
+ if (currentIndex < fontElements.length) {
1257
+ // Process next batch in the next animation frame
1258
+ requestAnimationFrame(observeBatch);
1259
+ } else {
1260
+ // console.log(`✅ [FontInput:${controllerId}] Finished observing all font elements:`, {
1261
+ // total: fontElements.length,
1262
+ // batchSize,
1263
+ // batches: Math.ceil(fontElements.length / batchSize)
1264
+ // });
1265
+ }
1266
+ };
1267
+
1268
+ // Start the batched observation process
1269
+ observeBatch();
1270
+ }
1271
+
1272
+ /**
1273
+ * Handles font list scrolling
1274
+ */
1275
+ function handleFontListScroll(event: Event) {
1276
+ // Ensure target is an HTMLElement
1277
+ if (!(event.target instanceof HTMLElement)) {
1278
+ return;
1279
+ }
1280
+
1281
+ // Prevent event propagation to stop global scroll handler from closing the modal
1282
+ event.stopPropagation();
1283
+
1284
+ // Handle font loading for visible fonts
1285
+ fontManagerInstance?.handleScroll();
1286
+
1287
+ const container = event.target;
1288
+ const { scrollTop, scrollHeight, clientHeight } = container;
1289
+ // Increase the threshold to detect when we're closer to the bottom
1290
+ const scrolledToBottom = scrollHeight - (scrollTop + clientHeight) <= 100;
1291
+
1292
+ // Add debug log to help diagnose scrolling issues
1293
+ // console.log(`📜 [FontInput:${controllerId}] Scroll position:`, {
1294
+ // scrollTop,
1295
+ // scrollHeight,
1296
+ // clientHeight,
1297
+ // remainingScroll: scrollHeight - (scrollTop + clientHeight),
1298
+ // scrolledToBottom,
1299
+ // hasSearchTerm: Boolean(searchTerm),
1300
+ // searchResultsCount: currentSearchResults.length,
1301
+ // displayedResults: filteredFonts.length,
1302
+ // currentFilter
1303
+ // });
1304
+
1305
+ if (scrolledToBottom) {
1306
+ if (searchTerm && currentSearchResults.length > 0) {
1307
+ // Calculate next batch using SEARCH_BATCH_SIZE
1308
+ const nextBatchStart = filteredFonts.length;
1309
+ const nextBatch = currentSearchResults.slice(
1310
+ nextBatchStart,
1311
+ nextBatchStart + SEARCH_BATCH_SIZE
1312
+ );
1313
+
1314
+ if (nextBatch.length > 0) {
1315
+ // console.log(`🔄 [FontInput:${controllerId}] Loading next search batch:`, {
1316
+ // batchSize: nextBatch.length,
1317
+ // startIndex: nextBatchStart,
1318
+ // endIndex: nextBatchStart + nextBatch.length,
1319
+ // totalSearchResults: currentSearchResults.length
1320
+ // });
1321
+
1322
+ // Add new batch to filtered fonts
1323
+ filteredFonts = [...filteredFonts, ...nextBatch];
1324
+
1325
+ // Setup observer for new fonts
1326
+ scrollTimeout = setTimeout(() => {
1327
+ if (fontListContainer) {
1328
+ setupFontObserver();
1329
+ }
1330
+ }, 0);
1331
+
1332
+ // console.log(`📝 [FontInput:${controllerId}] Loaded next search batch:`, {
1333
+ // batchSize: nextBatch.length,
1334
+ // totalDisplayed: filteredFonts.length,
1335
+ // remainingFonts: currentSearchResults.length - filteredFonts.length,
1336
+ // nextBatchSize: SEARCH_BATCH_SIZE
1337
+ // });
1338
+ } else {
1339
+ // console.log(`ℹ️ [FontInput:${controllerId}] No more search results to load`);
1340
+ }
1341
+ } else {
1342
+ // Normal font list scrolling
1343
+ if (!isLoadingBatch && fontManagerInstance?.hasMoreFonts(controllerId, currentFilter)) {
1344
+ // console.log(`🔄 [FontInput:${controllerId}] Reached bottom, loading next batch for ${currentFilter}`);
1345
+ loadNextBatch();
1346
+ } else if (isLoadingBatch) {
1347
+ // console.log(`⏳ [FontInput:${controllerId}] Already loading a batch, skipping`);
1348
+ } else if (!fontManagerInstance?.hasMoreFonts(controllerId, currentFilter)) {
1349
+ // console.log(`ℹ️ [FontInput:${controllerId}] No more fonts to load for ${currentFilter}`);
1350
+ }
1351
+ }
1352
+ }
1353
+ }
1354
+
1355
+ /**
1356
+ * Loads the next batch of fonts
1357
+ */
1358
+ async function loadNextBatch() {
1359
+ if (isLoadingBatch) return;
1360
+
1361
+ try {
1362
+ isLoadingBatch = true;
1363
+ // console.log(`🔄 [FontInput:${controllerId}] Loading next batch for ${currentFilter}`);
1364
+
1365
+ // Get next batch for this controller
1366
+ const newFonts = fontManagerInstance.getNextBatch(controllerId, currentFilter);
1367
+ // console.log(`📚 [FontInput:${controllerId}] Received next batch:`, {
1368
+ // count: newFonts.length,
1369
+ // category: currentFilter,
1370
+ // fonts: newFonts.slice(0, 3).map(f => f.family)
1371
+ // });
1372
+
1373
+ // Add to existing fonts, ensuring uniqueness
1374
+ const combinedFonts = [...allFonts, ...newFonts];
1375
+ allFonts = Array.from(new Map(combinedFonts.map((font) => [font.family, font])).values());
1376
+
1377
+ // Update filtered fonts while preserving current filter
1378
+ updateFilteredFonts();
1379
+
1380
+ // console.log(`✅ [FontInput:${controllerId}] Loaded new batch:`, {
1381
+ // controllerId,
1382
+ // filter: currentFilter,
1383
+ // newFonts: newFonts.length,
1384
+ // totalFonts: allFonts.length,
1385
+ // filteredFonts: filteredFonts.length,
1386
+ // hasMoreFonts: fontManagerInstance.hasMoreFonts(controllerId, currentFilter)
1387
+ // });
1388
+ } catch (error) {
1389
+ console.error(`❌ [FontInput:${controllerId}] Error loading font batch:`, error);
1390
+ } finally {
1391
+ isLoadingBatch = false;
1392
+ }
1393
+ }
1394
+
1395
+ function handleToggle() {
1396
+ // console.log('Font dropdown toggled:', controllerId);
1397
+ toggleDropdown(controllerId);
1398
+ }
1399
+
1400
+ function closeDropdown() {
1401
+ if (open) {
1402
+ handleToggle();
1403
+ }
1404
+ }
1405
+
1406
+ // Create a custom action for font observation
1407
+ function observeFont(node: HTMLElement) {
1408
+ if (fontObserver) {
1409
+ fontObserver.observe(node);
1410
+ }
1411
+
1412
+ return {
1413
+ destroy() {
1414
+ if (fontObserver) {
1415
+ fontObserver.unobserve(node);
1416
+ }
1417
+ }
1418
+ };
1419
+ }
1420
+
1421
+ $: open = $openDropdowns.has(controllerId);
1422
+
1423
+ // Add a reactive statement to set up observer when fonts are loaded
1424
+ $: if (filteredFonts.length > 0 && fontListContainer) {
1425
+ // console.log('📝 [FontInput] Fonts loaded, setting up observer...');
1426
+ setupFontObserver();
1427
+ }
1428
+
1429
+ $: popoverStyle = `width: ${buttonWidth}px`;
1430
+
1431
+ /**
1432
+ * Fetches and processes font weights from Google Fonts API
1433
+ * or from fonts.json for custom fonts
1434
+ */
1435
+ function keepWeightIfListed() {
1436
+ const currentName = selectedWeight.startsWith(`${controllerId}-`)
1437
+ ? selectedWeight.slice(controllerId.length + 1)
1438
+ : '';
1439
+ if (!availableWeights.includes(currentName)) {
1440
+ selectedWeight = `${controllerId}-${availableWeights.includes('Regular') ? 'Regular' : availableWeights[0]}`;
1441
+ }
1442
+ }
1443
+
1444
+ async function fetchFontWeights(fontFamily: string) {
1445
+ try {
1446
+ // Wait for FontManager init — reactive weight fetch can race ahead of onMount.
1447
+ fontManagerInstance = await FontManager.getInstance(appConfig.GOOGLE_FONTS_API_KEY);
1448
+
1449
+ // First check if it's a custom font using FontManager
1450
+ if (fontManagerInstance?.isCustomFont(fontFamily)) {
1451
+ // Get custom font data
1452
+ const customFontResponse = await fetch(fontsJsonUrl);
1453
+ if (customFontResponse.ok) {
1454
+ const customFontsData = await customFontResponse.json();
1455
+ const customFont = customFontsData.fontFamilies.find((f: any) => f.family === fontFamily);
1456
+
1457
+ if (customFont) {
1458
+ // For custom fonts, get all variants from fonts.json
1459
+ availableWeights = customFont.variants
1460
+ .map((v: any) => v.weight)
1461
+ // Remove duplicates if any
1462
+ .filter(
1463
+ (weight: string, index: number, self: string[]) => self.indexOf(weight) === index
1464
+ )
1465
+ // Sort with Regular first, then alphabetically
1466
+ .sort((a: string, b: string) => {
1467
+ if (a === 'Regular') return -1;
1468
+ if (b === 'Regular') return 1;
1469
+ return a.localeCompare(b);
1470
+ });
1471
+
1472
+ // Set default weight only if not already set for this controller
1473
+ if (!selectedWeight.startsWith(controllerId)) {
1474
+ selectedWeight = `${controllerId}-${
1475
+ availableWeights.includes('Regular') ? 'Regular' : availableWeights[0]
1476
+ }`;
1477
+ }
1478
+
1479
+ return;
1480
+ }
1481
+ }
1482
+ }
1483
+
1484
+ // Google font: use catalog cached by FontManager (no extra API call per font)
1485
+ let variantIds = fontManagerInstance?.getGoogleFontVariantIds(fontFamily);
1486
+ if (!variantIds?.length) {
1487
+ // Catalog may still be empty right after init edge cases — force list load once.
1488
+ try {
1489
+ await fontManagerInstance.getInitialFontList();
1490
+ } catch (catalogError) {
1491
+ console.warn('[FontInput] Catalog refresh failed before weight lookup:', catalogError);
1492
+ }
1493
+ variantIds = fontManagerInstance?.getGoogleFontVariantIds(fontFamily);
1494
+ }
1495
+ if (variantIds?.length) {
1496
+ availableWeights = mapGoogleVariantIdsToWeightNames(variantIds);
1497
+ if (!availableWeights.includes(selectedWeight.replace(`${controllerId}-`, ''))) {
1498
+ selectedWeight = `${controllerId}-${availableWeights.includes('Regular') ? 'Regular' : availableWeights[0]}`;
1499
+ }
1500
+ return;
1501
+ }
1502
+
1503
+ // API unavailable (403 / no catalog): sensible defaults, still loads via fonts.googleapis.com CSS
1504
+ // Warn once — not on every reactive re-run during catalog race.
1505
+ if (!fontCatalogFallbackWarned) {
1506
+ fontCatalogFallbackWarned = true;
1507
+ console.warn(
1508
+ '[FontInput] Using default weights (Google catalog not loaded). Later fonts will use the same fallback silently.'
1509
+ );
1510
+ }
1511
+ availableWeights = ['Regular', 'Italic', 'Bold', 'Bold Italic'];
1512
+ keepWeightIfListed();
1513
+ } catch (error) {
1514
+ console.error('Error fetching font weights:', error);
1515
+ availableWeights = ['Regular', 'Italic', 'Bold', 'Bold Italic'];
1516
+ keepWeightIfListed();
1517
+ }
1518
+ }
1519
+
1520
+ $: if (resolvedFont?.family) {
1521
+ fetchFontWeights(resolvedFont.family);
1522
+ }
1523
+
1524
+ /**
1525
+ * Highlights search term matches in font names
1526
+ * @param name Font name
1527
+ * @param term Search term
1528
+ * @returns HTML string with highlighted match
1529
+ *
1530
+ * Note: The result goes to {@html}, so every piece of the font name is escaped as it is put in (a name such as
1531
+ * `<img src=x onerror=...>` must show as text, not run in the page the editor is on).
1532
+ */
1533
+ function highlightMatch(name: string, term: string) {
1534
+ // Check if this font is the selected one
1535
+ const isSelected = resolvedFont?.family === name;
1536
+
1537
+ if (!term) {
1538
+ return `<span style="color: var(--foreground)">${escapeHtml(name)}</span>`;
1539
+ }
1540
+
1541
+ const nameLower = name.toLowerCase();
1542
+ const termLower = term.toLowerCase().trim();
1543
+
1544
+ // If the name contains the search term, highlight that part
1545
+ if (nameLower.includes(termLower)) {
1546
+ const index = nameLower.indexOf(termLower);
1547
+ const beforeMatch = escapeHtml(name.slice(0, index));
1548
+ const match = escapeHtml(name.slice(index, index + termLower.length));
1549
+ const afterMatch = escapeHtml(name.slice(index + termLower.length));
1550
+
1551
+ return `<span style="color: var(--foreground)">${beforeMatch}<span class="search-result-highlight" style="color: var(--brand)">${match}</span>${afterMatch}</span>`;
1552
+ }
1553
+
1554
+ return `<span style="color: var(--foreground)">${escapeHtml(name)}</span>`;
1555
+ }
1556
+
1557
+ /**
1558
+ * Handles global scroll events
1559
+ */
1560
+ function handleGlobalScroll(event: Event) {
1561
+ // Ensure target is an HTMLElement before using closest
1562
+ if (!(event.target instanceof HTMLElement)) {
1563
+ return;
1564
+ }
1565
+
1566
+ const target = event.target;
1567
+
1568
+ // Check if scroll happened inside our containers
1569
+ const isInsideFontList = target === fontListContainer;
1570
+ const isInsidePopover = target.closest('.font-popover-content');
1571
+ const isInsideCommand = target.closest('[cmdk-root]');
1572
+
1573
+ // If scrolling is inside any of our containers, don't close
1574
+ if (isInsideFontList || isInsidePopover || isInsideCommand) {
1575
+ return;
1576
+ }
1577
+
1578
+ // If scrolling outside our containers, close dropdowns
1579
+ if ($openDropdowns?.has(controllerId)) {
1580
+ toggleDropdown(controllerId);
1581
+ }
1582
+ if ($openDropdowns?.has('weight-' + controllerId)) {
1583
+ toggleDropdown('weight-' + controllerId);
1584
+ }
1585
+ }
1586
+
1587
+ // Stops listening for scrolling (the page and, inside a module, the module's own panels: a scroll never leaves a
1588
+ // shadow root, so a listener on the window alone does not hear about those)
1589
+ let stopListeningForScroll: () => void = () => {};
1590
+
1591
+ // Update onMount to add the scroll listener with passive option
1592
+ onMount(() => {
1593
+ // Add scroll listener with passive option
1594
+ stopListeningForScroll = listenForScroll(controllerElement, handleGlobalScroll, {
1595
+ passive: true
1596
+ });
1597
+ window.addEventListener('resize', handleFamilyPopoverViewportChange);
1598
+ window.visualViewport?.addEventListener('resize', handleFamilyPopoverViewportChange);
1599
+
1600
+ // (Two touchstart/touchmove listeners that did nothing used to be added to the window here, and could never be
1601
+ // removed: each input left two more on the customer's page every time it was shown. They did nothing, so they are
1602
+ // gone.)
1603
+ });
1604
+
1605
+ // Update onDestroy to remove all listeners
1606
+ onDestroy(() => {
1607
+ stopListeningForScroll();
1608
+ window.removeEventListener('resize', handleFamilyPopoverViewportChange);
1609
+ window.visualViewport?.removeEventListener('resize', handleFamilyPopoverViewportChange);
1610
+
1611
+ // Give the popover layer back (the last input to leave removes it from the page).
1612
+ releasePortalHost(fontPickerPortalHost);
1613
+ fontPickerPortalHost = undefined;
1614
+
1615
+ if (fontObserver) {
1616
+ fontObserver.disconnect();
1617
+ }
1618
+ // Clear any timeouts
1619
+ if (scrollTimeout) {
1620
+ clearTimeout(scrollTimeout);
1621
+ }
1622
+ if (initialLoadTimeout) {
1623
+ clearTimeout(initialLoadTimeout);
1624
+ }
1625
+
1626
+ // console.log('🧹 [FontInput] Cleanup complete:', {
1627
+ // controllerId,
1628
+ // lastFilter: currentFilter
1629
+ // });
1630
+ });
1631
+
1632
+ // Add this function to the script section
1633
+ function handleDeleteCustomFont(font: FontItem | RecentFont, event: Event) {
1634
+ event.stopPropagation();
1635
+ // Convert returned RecentFonts to FontItems
1636
+ recentFonts = fontUtils.removeCustomFont(font.family).map((font) => ({
1637
+ family: font.family,
1638
+ category: font.category as FontItem['category'],
1639
+ isCustom: font.isCustom
1640
+ }));
1641
+ updateFilteredFonts();
1642
+ }
1643
+
1644
+ // Add this function after the script tag
1645
+ function normalizeCategory(category: string): FontItem['category'] {
1646
+ return fontCategories.normalize(category);
1647
+ }
1648
+
1649
+ async function removeFont(fontFamily: string) {
1650
+ try {
1651
+ // Remove from manager
1652
+ await fontManagerInstance?.removeCustomFont(fontFamily);
1653
+
1654
+ // If the removed font was selected, clear the selection
1655
+ if (resolvedFont?.family === fontFamily && onChange) {
1656
+ onChange({
1657
+ family: '',
1658
+ weight: 'Regular',
1659
+ category: ''
1660
+ });
1661
+ }
1662
+
1663
+ // Remove from recent fonts if present
1664
+ const updatedRecentFonts = recentFonts.filter((f) => f.family !== fontFamily);
1665
+ recentFonts = updatedRecentFonts;
1666
+
1667
+ // Add lastUsed property before updating store
1668
+ const recentFontsWithLastUsed = updatedRecentFonts.map((f) => ({
1669
+ ...f,
1670
+ lastUsed: Date.now()
1671
+ }));
1672
+ recentFontsStore.set(recentFontsWithLastUsed);
1673
+
1674
+ // Remove from all fonts
1675
+ allFonts = allFonts.filter((f) => f.family !== fontFamily);
1676
+
1677
+ // Update filtered fonts
1678
+ updateFilteredFonts();
1679
+
1680
+ // console.log('✅ [FontInput] Font removed:', {
1681
+ // fontFamily,
1682
+ // remainingFonts: allFonts.length,
1683
+ // filteredFonts: filteredFonts.length,
1684
+ // recentFonts: recentFonts.length
1685
+ // });
1686
+ } catch (error) {
1687
+ console.error('❌ [FontInput] Error removing font:', error);
1688
+ }
1689
+ }
1690
+
1691
+ // Update the weight selection handler
1692
+ function handleWeightSelect(weight: string) {
1693
+ selectedWeight = `${controllerId}-${weight}`;
1694
+ if (browser) {
1695
+ writeEditorStorageValue(FONT_WEIGHT_KEY(controllerId), selectedWeight);
1696
+ }
1697
+ const current = coerceFontValue(value);
1698
+ if (onChange) {
1699
+ onChange({
1700
+ family: current?.family || '',
1701
+ weight: weight,
1702
+ category: current?.category || 'Sans Serif'
1703
+ });
1704
+ }
1705
+ }
1706
+
1707
+ // Update the template to use the modified weight
1708
+ $: displayWeight = selectedWeight.replace(`${controllerId}-`, '');
1709
+
1710
+ // Update arrow click handler to use filteredFonts
1711
+ function handleArrowClick(direction: 'up' | 'down') {
1712
+ if (!filteredFonts.length) return;
1713
+
1714
+ if (direction === 'down') {
1715
+ activeSearchIndex = (activeSearchIndex + 1) % filteredFonts.length;
1716
+ } else {
1717
+ activeSearchIndex = activeSearchIndex <= 0 ? filteredFonts.length - 1 : activeSearchIndex - 1;
1718
+ }
1719
+
1720
+ // Ensure the selected item is visible
1721
+ // (The family goes through CSS.escape: a name with a quote in it must not end the selector.)
1722
+ const selectedElement = fontListContainer?.querySelector(
1723
+ `[data-font="${CSS.escape(filteredFonts[activeSearchIndex].family)}"]`
1724
+ );
1725
+ selectedElement?.scrollIntoView({ block: 'nearest' });
1726
+ }
1727
+
1728
+ // Add a function to handle mouse enter events on font items
1729
+ function handleMouseEnter(index: number) {
1730
+ // Update the active index to the hovered item
1731
+ activeSearchIndex = index;
1732
+ }
1733
+
1734
+ // Functions for RecentItemsSection
1735
+ function renderFontItem(font: FontItem) {
1736
+ // The result is used as HTML by RecentItemsSection: the family is quoted for CSS and escaped for HTML where it is
1737
+ // a rule, and escaped for HTML where it is the text.
1738
+ return {
1739
+ html: `
1737
1740
  <div class="flex items-center flex-1 min-w-0">
1738
1741
  <span
1739
- class="text-[24px] truncate"
1742
+ class="text-body truncate"
1740
1743
  style="font-family: ${escapeHtml(cssQuotedString(font.family))}, sans-serif; font-display: swap; color: inherit; -webkit-text-fill-color: currentColor;"
1741
1744
  >
1742
1745
  ${escapeHtml(font.family)}
1743
1746
  </span>
1744
1747
  </div>
1745
1748
  `
1746
- };
1747
- }
1748
-
1749
- function isFontSelected(font: FontItem) {
1750
- return resolvedFont?.family === font.family;
1751
- }
1752
-
1753
- function isCustomFont(font: FontItem) {
1754
- return font.category === 'Mine' && Boolean(font.isCustom);
1755
- }
1756
-
1757
- function getFontKey(font: FontItem) {
1758
- // Create a unique key by combining family with category
1759
- // This prevents duplicate keys when two fonts have the same family name
1760
- return `${font.family}-${font.category}`;
1761
- }
1762
-
1763
- function handleFontDelete(font: FontItem, event: Event) {
1764
- event.stopPropagation();
1765
- event.preventDefault();
1766
- removeFont(font.family);
1767
- }
1749
+ };
1750
+ }
1751
+
1752
+ function isFontSelected(font: FontItem) {
1753
+ return resolvedFont?.family === font.family;
1754
+ }
1755
+
1756
+ function isCustomFont(font: FontItem) {
1757
+ return font.category === 'Mine' && Boolean(font.isCustom);
1758
+ }
1759
+
1760
+ function getFontKey(font: FontItem) {
1761
+ // Create a unique key by combining family with category
1762
+ // This prevents duplicate keys when two fonts have the same family name
1763
+ return `${font.family}-${font.category}`;
1764
+ }
1765
+
1766
+ function handleFontDelete(font: FontItem, event: Event) {
1767
+ event.stopPropagation();
1768
+ event.preventDefault();
1769
+ removeFont(font.family);
1770
+ }
1768
1771
  </script>
1769
1772
 
1770
- <!-- Dual IC: header zone always on the left (even if label is empty); 185px inputs on the right. -->
1771
- <div bind:this={controllerElement} class="font-ic flex flex-col gap-2 w-full min-w-0 widgetic-colors {className}" style={style}>
1772
- <div class="font-family-row flex items-center justify-between w-full min-w-0 gap-2" style="min-height: 48px;">
1773
- <div class="font-family-label-ct flex-1 min-w-0">
1774
- <InputControllerHeader label={label || ''} />
1775
- </div>
1776
- <div
1777
- class="font-family-input-ct h-12 shrink-0 rounded-large border border-grey2 flex items-center bg-grey1 transition-colors duration-200 hover:border-forest-green"
1778
- style="width: 185px; max-width: 185px; min-width: 185px;"
1779
- bind:this={familyTriggerEl}
1780
- >
1781
- <!-- Font Family Button -->
1782
- <Popover.Root
1783
- open={$openDropdowns?.has(controllerId)}
1784
- onOpenChange={(isOpen) => {
1785
- if (isOpen && Date.now() < fontPickerReadyAt) return;
1786
- const wasOpen = !!$openDropdowns?.has(controllerId);
1787
- if (isOpen === wasOpen) return;
1788
- if (!isOpen && resolvedFont?.family && !shouldSkipFont(resolvedFont.family)) {
1789
- fontUtils.addRecentFont({
1790
- family: resolvedFont.family,
1791
- category: normalizeCategory(resolvedFont.category) as FontItem['category'],
1792
- isCustom: fontManagerInstance?.isCustomFont(resolvedFont.family) || false
1793
- });
1794
- } else if (isOpen) {
1795
- activeSearchIndex = -1;
1796
- void tick().then(() => {
1797
- updateFamilyPopoverBox();
1798
- requestAnimationFrame(updateFamilyPopoverBox);
1799
- });
1800
- if (filteredFonts.length === 0 && allFonts.length > 0) {
1801
- updateFilteredFonts();
1802
- }
1803
- setTimeout(() => {
1804
- if (fontListContainer) {
1805
- setupFontObserver();
1806
- }
1807
- }, 50);
1808
- }
1809
- toggleDropdown(controllerId);
1810
- }}
1811
- >
1812
- <Popover.Trigger tabindex={-1} class="w-full h-full flex items-center border-0 bg-transparent hover:bg-transparent focus:bg-transparent ps-3 pe-[16px] group"
1813
- onmouseenter={() => {
1814
- // Preload fonts when hovering over the button
1815
- // This reduces the delay when actually clicking to open
1816
- if (!$openDropdowns?.has(controllerId) && filteredFonts.length === 0 && allFonts.length > 0) {
1817
- updateFilteredFonts();
1818
- }
1819
- }}
1820
- >
1821
- <span
1822
- class="truncate flex-1 text-start subtext text-grey7"
1823
- style="font-family: {cssQuotedString(resolvedFont?.family || 'system-ui')}, sans-serif; font-display: swap;"
1824
- >
1825
- {resolvedFont?.family || $t('editor.font.select')}
1826
- </span>
1827
- <IconCaretDownFilled class="w-5 h-5 shrink-0 text-grey5 group-hover:text-grey7" />
1828
- </Popover.Trigger>
1829
-
1830
- <Popover.Content
1831
- collisionPadding={12}
1832
- side={familyPopoverSide}
1833
- sideOffset={4}
1834
- tabindex={-1}
1835
- onOpenAutoFocus={(event) => event.preventDefault()}
1836
- portalProps={{ to: fontPickerPortalHost }}
1837
- class="font-input-popover !p-0 widgetic-colors widgetic-radius rounded-medium modal-shadow border border-grey2 outline-none"
1838
- style={familyPopoverStyle}
1839
- >
1840
- <div class="flex flex-col h-full min-h-0 font-popover-content">
1841
- <!-- Title and upload icon -->
1842
- <div class="font-popover-header shrink-0 relative pt-6 pb-[11px] px-5">
1843
- <div class="h5 text-grey7 widgetic-colors">{$t('editor.font.title')}</div>
1844
- <button
1845
- type="button"
1846
- tabindex="-1"
1847
- class="absolute end-6 top-[26px] bg-transparent border-0 cursor-pointer p-0 rounded-full hover:bg-grey3 transition-all duration-300"
1848
- onclick={() => {
1849
- try {
1850
- openFileBrowser();
1851
- } catch (error) {
1852
- console.error('Error opening file browser:', error);
1853
- }
1854
- }}
1855
- >
1856
- <IconCloudUpload class="w-6 h-6 text-grey7 hover:text-grey7 transition-colors duration-300 widgetic-colors" />
1857
- </button>
1858
- </div>
1859
-
1860
- {#if description}
1861
- <p class="px-4 -mt-2 mb-2 subtext text-grey5">{description}</p>
1862
- {/if}
1863
-
1864
- <!-- Search input -->
1865
- <div class="font-popover-search shrink-0 relative px-4">
1866
- <SearchInput
1867
- placeholder={$t('editor.font.search')}
1868
- bind:value={searchTerm}
1869
- onInput={(e: Event) => {
1870
- // Use debounced search only for typing
1871
- debouncedSearch(e);
1872
- }}
1873
- onPaste={handlePaste}
1874
- onKeydown={handleSearchKeydown}
1875
- onClear={() => {
1876
- searchTerm = ''; // Reset search term
1877
-
1878
- // Restore the previous filter when clearing search
1879
- currentFilter = lastActiveFilter;
1880
- if (browser) {
1881
- writeEditorStorageValue(FONT_FILTER_KEY(controllerId), lastActiveFilter);
1882
- }
1883
-
1884
- // ... rest of your onClear code ...
1885
- }}
1886
- />
1887
- </div>
1888
- <!-- Filter toggle group - sticky header -->
1889
- {#if !searchTerm}
1890
- <div class="font-popover-tabs shrink-0 sticky top-0 bg-white z-10">
1891
- <CategoryTabs
1892
- categories={filterOptions}
1893
- activeCategory={currentFilter}
1894
- onCategorySelect={handleFilterChange}
1895
- getCategoryLabel={(category) => categoryLabel(category, $t)}
1896
- filterVisible={!searchTerm}
1897
- />
1898
- </div>
1899
- {/if}
1900
-
1901
- <!-- Scrollable content -->
1902
- <div
1903
- class="flex-1 {filteredFonts.length > 0 ? 'overflow-y-auto' : 'overflow-hidden'} min-h-0 font-list-container"
1904
- bind:this={fontListContainer}
1905
- onscroll={(e) => {
1906
- e.stopPropagation();
1907
- handleFontListScroll(e);
1908
- updateScrollState();
1909
- }}
1910
- id={`font-list-${controllerId}`}
1911
- role="listbox"
1912
- aria-label={$t('editor.font.list')}
1913
- >
1914
- <div class="space-y-0">
1915
- <!-- Recently used section - only show when not searching -->
1916
- {#if recentFonts.length > 0 && !searchTerm}
1917
- <RecentItemsSection
1918
- recentItems={recentFonts}
1919
- onItemSelect={handleFontSelect}
1920
- onItemDelete={handleFontDelete}
1921
- isItemSelected={isFontSelected}
1922
- renderItem={renderFontItem}
1923
- isCustomItem={isCustomFont}
1924
- getItemKey={getFontKey}
1925
- observeItem={observeFont}
1926
- displayMode="list"
1927
- hideTrashIcon={hideTrashIcon}
1928
- itemType="font"
1929
- selectionToken={resolvedFont?.family || ''}
1930
- />
1931
- {/if}
1932
-
1933
- <!-- All fonts section -->
1934
- <div class="mt-6 px-4">
1935
- {#if filteredFonts.length > 0}
1936
- <div id="font-header-{controllerId}" class="sticky top-0 -mt-2 bg-white z-10 pt-2 {isScrolled ? 'border-b border-grey2' : 'border-b border-transparent'} transition-border">
1937
- <h3 class="subtext text-grey7 pb-2 flex items-center">
1938
- {#if isInitialLoading}
1939
- <div class="w-4 h-4 border-2 border-t-sage-green border-e-sage-green border-b-grey2 border-s-grey2 rounded-full animate-spin me-2"></div>
1940
- {/if}
1941
- {searchTerm ? $t('editor.list.searchResults') : $t('editor.list.more')}
1942
- </h3>
1943
- </div>
1944
- {/if}
1945
-
1946
- {#if filteredFonts.length === 0}
1947
- <div class="empty-state-wrapper">
1948
- {#if isInitialLoading}
1949
- <!-- Show compact loading indicator while fonts are loading -->
1950
- <div class="flex items-center">
1951
- <div class="text-grey5 subtext me-2">{$t('editor.font.loading')}</div>
1952
- <div class="w-4 h-4 border-2 border-t-sage-green border-e-sage-green border-b-grey2 border-s-grey2 rounded-full animate-spin"></div>
1953
- </div>
1954
- {:else}
1955
- <!-- Only show empty state when loading is complete and no fonts were found -->
1956
- <EmptyState
1957
- message={searchTerm ? $t('editor.font.noneFound') : $t('editor.font.noneAvailable')}
1958
- height="auto"
1959
- />
1960
- {/if}
1961
- </div>
1962
- {:else}
1963
- <div class="pb-4"> <!-- Add a container with bottom padding -->
1964
- {#each filteredFonts as font, index (`${font.family}-${searchTerm ? 'search' : currentFilter}-${index}`)}
1965
- <!-- svelte-ignore a11y_click_events_have_key_events -->
1966
- <div
1967
- class="font-list-row w-full py-1 px-4 cursor-pointer overflow-hidden relative rounded-small h-[42px] flex items-center
1968
- {isFontSelected(font) ? 'bg-sage-green selected-item' :
1969
- index === activeSearchIndex && searchTerm ? 'bg-light-green' :
1970
- 'hover:bg-light-green'}"
1971
- data-font={font.family}
1972
- use:observeFont
1973
- onclick={() => handleFontSelect(font)}
1974
- onmouseenter={() => handleMouseEnter(index)}
1975
- role="button"
1976
- tabindex="-1"
1977
- style="color: {isFontSelected(font) ? '#ffffff' : 'hsl(var(--grey7))'};"
1978
- >
1979
- <div class="flex items-center flex-1 min-w-0 group">
1980
- <Check class="me-2 h-6 w-6 flex-shrink-0 {isFontSelected(font) ? 'text-white' : 'text-sage-green opacity-0'}"/>
1981
- <span
1982
- class="text-[24px] truncate {index === activeSearchIndex && searchTerm ? 'font-medium' : ''}"
1983
- style="font-family: {cssQuotedString(font.family)}, sans-serif; font-display: swap; color: inherit; -webkit-text-fill-color: currentColor;"
1984
- >
1985
- {@html highlightMatch(font.family, searchTerm)}
1986
- </span>
1987
-
1988
- {#if font.category === 'Mine' && font.isCustom && !hideTrashIcon}
1989
- <div
1990
- role="button"
1991
- tabindex="-1"
1992
- class="ms-auto transition-opacity {resolvedFont?.family === font.family ? 'opacity-0 pointer-events-none' : 'opacity-0 group-hover:opacity-100'}"
1993
- onclick={(e) => {
1994
- e.stopPropagation();
1995
- e.preventDefault();
1996
- removeFont(font.family);
1997
- }}
1998
- >
1999
- <img
2000
- src={icTrash}
2001
- alt={$t('editor.font.remove')}
2002
- class="w-4 h-4 text-grey5 hover:text-error"
2003
- draggable="false"
2004
- />
2005
- <span class="sr-only">{$t('editor.font.remove')}</span>
2006
- </div>
2007
- {/if}
2008
- </div>
2009
- </div>
2010
- {/each}
2011
- </div>
2012
- {/if}
2013
- </div>
2014
- </div>
2015
- </div>
2016
- </div>
2017
- </Popover.Content>
2018
- </Popover.Root>
2019
- </div>
2020
- </div>
2021
-
2022
- <div class="font-weight-row flex items-center justify-between w-full min-w-0 gap-2" style="min-height: 48px;">
2023
- <div class="font-weight-label-ct flex-1 min-w-0">
2024
- <InputControllerHeader label={label ? $t('editor.font.weight') : ''} />
2025
- </div>
2026
- <div class="font-weight-input-ct h-12 shrink-0 rounded-large border border-grey2 flex items-center bg-grey1 transition-colors duration-200 hover:border-forest-green" style="width: 185px; max-width: 185px; min-width: 185px;">
2027
- <Popover.Root
2028
- open={$openDropdowns?.has('weight-' + controllerId)}
2029
- onOpenChange={(isOpen) => {
2030
- if (isOpen && Date.now() < fontPickerReadyAt) return;
2031
- if (isOpen !== $openDropdowns?.has('weight-' + controllerId)) {
2032
- toggleDropdown('weight-' + controllerId);
2033
- }
2034
- }}
2035
- >
2036
- <Popover.Trigger tabindex={-1} class="w-full h-full flex items-center border-0 bg-transparent hover:bg-transparent focus:bg-transparent ps-3 pe-[16px] group">
2037
- <span class="truncate flex-1 text-start subtext text-grey7">
2038
- {fontWeightLabel(displayWeight || 'Regular', $t)}
2039
- </span>
2040
- <IconCaretDownFilled class="w-5 h-5 shrink-0 text-grey5 group-hover:text-grey7" />
2041
- </Popover.Trigger>
2042
- <Popover.Content
2043
- class="font-input-popover p-0 w-[150px] outline-none"
2044
- tabindex={-1}
2045
- onOpenAutoFocus={(event) => event.preventDefault()}
2046
- portalProps={{ to: fontPickerPortalHost }}
2047
- >
2048
- <Command.Root>
2049
- <Command.List aria-label={$t('editor.font.weightList')}>
2050
- <Command.Group>
2051
- {#each availableWeights as weight}
2052
- <Command.Item
2053
- value={weight}
2054
- tabindex={-1}
2055
- onSelect={() => handleWeightSelect(weight)}
2056
- class="px-2 py-2 outline-none"
2057
- >
2058
- <Check
2059
- class="me-1 h-4 w-4 {displayWeight === weight ? 'opacity-100' : 'opacity-0'}"
2060
- />
2061
- <span class="truncate">{fontWeightLabel(weight, $t)}</span>
2062
- </Command.Item>
2063
- {/each}
2064
- </Command.Group>
2065
- </Command.List>
2066
- </Command.Root>
2067
- </Popover.Content>
2068
- </Popover.Root>
2069
- </div>
2070
- </div>
2071
-
2072
- {#if description}
2073
- <p class="subtext text-grey5">{description}</p>
2074
- {/if}
1773
+ <div bind:this={controllerElement} class="font-ic flex w-full min-w-0 flex-col {className}" {style}>
1774
+ <InputControllerRow label={label || ''}>
1775
+ <div class="font-family-input-ct w-full" bind:this={familyTriggerEl}>
1776
+ <!-- Font Family Button -->
1777
+ <Popover.Root
1778
+ open={$openDropdowns?.has(controllerId)}
1779
+ onOpenChange={(isOpen) => {
1780
+ if (isOpen && Date.now() < fontPickerReadyAt) return;
1781
+ const wasOpen = !!$openDropdowns?.has(controllerId);
1782
+ if (isOpen === wasOpen) return;
1783
+ if (!isOpen && resolvedFont?.family && !shouldSkipFont(resolvedFont.family)) {
1784
+ fontUtils.addRecentFont({
1785
+ family: resolvedFont.family,
1786
+ category: normalizeCategory(resolvedFont.category) as FontItem['category'],
1787
+ isCustom: fontManagerInstance?.isCustomFont(resolvedFont.family) || false
1788
+ });
1789
+ } else if (isOpen) {
1790
+ activeSearchIndex = -1;
1791
+ void tick().then(() => {
1792
+ updateFamilyPopoverBox();
1793
+ requestAnimationFrame(updateFamilyPopoverBox);
1794
+ });
1795
+ if (filteredFonts.length === 0 && allFonts.length > 0) {
1796
+ updateFilteredFonts();
1797
+ }
1798
+ setTimeout(() => {
1799
+ if (fontListContainer) {
1800
+ setupFontObserver();
1801
+ }
1802
+ }, 50);
1803
+ }
1804
+ toggleDropdown(controllerId);
1805
+ }}
1806
+ >
1807
+ <Popover.Trigger
1808
+ tabindex={-1}
1809
+ class="font-ic-trigger group flex h-9 w-full items-center gap-2 rounded-lg bg-accent px-3 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"
1810
+ onmouseenter={() => {
1811
+ if (
1812
+ !$openDropdowns?.has(controllerId) &&
1813
+ filteredFonts.length === 0 &&
1814
+ allFonts.length > 0
1815
+ ) {
1816
+ updateFilteredFonts();
1817
+ }
1818
+ }}
1819
+ >
1820
+ <span
1821
+ class="truncate flex-1 text-start text-body text-foreground"
1822
+ style="font-family: {cssQuotedString(
1823
+ resolvedFont?.family || 'system-ui'
1824
+ )}, sans-serif; font-display: swap;"
1825
+ >
1826
+ {resolvedFont?.family || $t('editor.font.select')}
1827
+ </span>
1828
+ {#if $openDropdowns?.has(controllerId)}
1829
+ <IconChevronUp class="size-4 shrink-0 stroke-[1.333] text-muted-foreground" />
1830
+ {:else}
1831
+ <IconChevronDown class="size-4 shrink-0 stroke-[1.333] text-muted-foreground" />
1832
+ {/if}
1833
+ </Popover.Trigger>
1834
+
1835
+ <Popover.Content
1836
+ collisionPadding={12}
1837
+ side={familyPopoverSide}
1838
+ align="end"
1839
+ sideOffset={8}
1840
+ tabindex={-1}
1841
+ onOpenAutoFocus={(event) => event.preventDefault()}
1842
+ portalProps={{ to: fontPickerPortalHost }}
1843
+ class="font-input-popover z-50 flex w-picker max-w-[calc(100vw-16px)] flex-col overflow-hidden rounded-xl border border-border bg-popover p-0 text-popover-foreground outline-none"
1844
+ style={familyPopoverStyle}
1845
+ >
1846
+ <div class="flex h-full min-h-0 flex-col font-popover-content">
1847
+ <div class="font-popover-header flex shrink-0 flex-col gap-3 px-4 pt-4 pb-3">
1848
+ <!-- Title and upload icon -->
1849
+ <div class="flex items-center gap-2">
1850
+ <h2 class="min-w-0 flex-1 text-heading-section text-foreground">
1851
+ {$t('editor.font.title')}
1852
+ </h2>
1853
+ <IconButton
1854
+ variant="ghost"
1855
+ label={$t('editor.file.addFile')}
1856
+ tabindex={-1}
1857
+ onclick={() => {
1858
+ try {
1859
+ openFileBrowser();
1860
+ } catch (error) {
1861
+ console.error('Error opening file browser:', error);
1862
+ }
1863
+ }}
1864
+ >
1865
+ <IconCloudUpload class="size-4 stroke-[1.333]" />
1866
+ </IconButton>
1867
+ </div>
1868
+ <!-- Search input -->
1869
+ <SearchInput
1870
+ placeholder={$t('editor.font.search')}
1871
+ bind:value={searchTerm}
1872
+ onInput={(e: Event) => {
1873
+ // Use debounced search only for typing
1874
+ debouncedSearch(e);
1875
+ }}
1876
+ onPaste={handlePaste}
1877
+ onKeydown={handleSearchKeydown}
1878
+ onClear={() => {
1879
+ searchTerm = ''; // Reset search term
1880
+
1881
+ // Restore the previous filter when clearing search
1882
+ currentFilter = lastActiveFilter;
1883
+ if (browser) {
1884
+ writeEditorStorageValue(FONT_FILTER_KEY(controllerId), lastActiveFilter);
1885
+ }
1886
+
1887
+ // ... rest of your onClear code ...
1888
+ }}
1889
+ />
1890
+ </div>
1891
+ {#if !searchTerm}
1892
+ <!-- Filter toggle group - sticky header -->
1893
+ <div class="font-popover-tabs shrink-0 sticky top-0 z-10 bg-popover">
1894
+ <CategoryTabs
1895
+ categories={filterOptions}
1896
+ activeCategory={currentFilter}
1897
+ onCategorySelect={handleFilterChange}
1898
+ getCategoryLabel={(category) => categoryLabel(category, $t)}
1899
+ filterVisible={!searchTerm}
1900
+ />
1901
+ </div>
1902
+ {/if}
1903
+
1904
+ <!-- Scrollable content -->
1905
+ <div
1906
+ class="flex-1 {filteredFonts.length > 0
1907
+ ? 'overflow-y-auto'
1908
+ : 'overflow-hidden'} min-h-0 font-list-container"
1909
+ bind:this={fontListContainer}
1910
+ onscroll={(e) => {
1911
+ e.stopPropagation();
1912
+ handleFontListScroll(e);
1913
+ updateScrollState();
1914
+ }}
1915
+ id={`font-list-${controllerId}`}
1916
+ role="listbox"
1917
+ aria-label={$t('editor.font.list')}
1918
+ >
1919
+ <div class="space-y-0">
1920
+ <!-- Recently used section — only when not searching -->
1921
+ {#if recentFonts.length > 0 && !searchTerm}
1922
+ <RecentItemsSection
1923
+ recentItems={recentFonts}
1924
+ title={currentFilter === 'Mine' ? $t('editor.list.uploadedByYou') : undefined}
1925
+ onItemSelect={handleFontSelect}
1926
+ onItemDelete={handleFontDelete}
1927
+ isItemSelected={isFontSelected}
1928
+ renderItem={renderFontItem}
1929
+ isCustomItem={isCustomFont}
1930
+ getItemKey={getFontKey}
1931
+ observeItem={observeFont}
1932
+ displayMode="list"
1933
+ {hideTrashIcon}
1934
+ itemType="font"
1935
+ selectionToken={resolvedFont?.family || ''}
1936
+ />
1937
+ {/if}
1938
+
1939
+ <!-- All fonts / search results section -->
1940
+ <div class="mt-4 px-4 pb-4">
1941
+ {#if filteredFonts.length > 0}
1942
+ <div
1943
+ id="font-header-{controllerId}"
1944
+ class="sticky top-0 z-10 -mt-2 bg-popover pt-2 {isScrolled
1945
+ ? 'border-b border-border transition-border'
1946
+ : 'border-b border-transparent'}"
1947
+ >
1948
+ <h3 class="flex items-center pb-2 text-caption-medium text-muted-foreground">
1949
+ {#if isInitialLoading}
1950
+ <span
1951
+ class="me-2 size-4 animate-spin rounded-full border-2 border-border border-t-brand"
1952
+ aria-hidden="true"
1953
+ ></span>
1954
+ {/if}
1955
+ {searchTerm ? $t('editor.list.searchResults') : $t('editor.list.more')}
1956
+ </h3>
1957
+ </div>
1958
+ {/if}
1959
+
1960
+ {#if filteredFonts.length === 0}
1961
+ <div class="empty-state-wrapper">
1962
+ {#if isInitialLoading}
1963
+ <!-- Show compact loading indicator while fonts are loading -->
1964
+ <div class="flex w-full max-w-[342px] flex-col gap-2 px-0" aria-busy="true">
1965
+ <span class="sr-only">{$t('editor.font.loading')}</span>
1966
+ {#each [1, 2, 3, 4, 5] as _ (_)}
1967
+ <Skeleton class="h-8 w-full rounded-lg" />
1968
+ {/each}
1969
+ </div>
1970
+ {:else}
1971
+ <EmptyState
1972
+ message={searchTerm
1973
+ ? $t('editor.font.noneFound')
1974
+ : $t('editor.font.noneAvailable')}
1975
+ height="auto"
1976
+ />
1977
+ {/if}
1978
+ </div>
1979
+ {:else}
1980
+ <div class="flex flex-col gap-0.5">
1981
+ {#each filteredFonts as font, index (`${font.family}-${searchTerm ? 'search' : currentFilter}-${index}`)}
1982
+ {@const selected = isFontSelected(font)}
1983
+ {@const keyboardActive = index === activeSearchIndex && searchTerm}
1984
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
1985
+ <div
1986
+ class="font-list-row group flex h-8 w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 transition-colors duration-fast {selected
1987
+ ? 'bg-brand-subtle selected-item'
1988
+ : keyboardActive
1989
+ ? 'bg-accent'
1990
+ : 'hover:bg-accent'}"
1991
+ data-font={font.family}
1992
+ use:observeFont
1993
+ onclick={() => handleFontSelect(font)}
1994
+ onmouseenter={() => handleMouseEnter(index)}
1995
+ role="option"
1996
+ aria-selected={selected}
1997
+ tabindex="-1"
1998
+ >
1999
+ <IconCheck
2000
+ class="size-4 shrink-0 stroke-[1.333] {selected
2001
+ ? 'text-foreground opacity-100'
2002
+ : 'opacity-0'}"
2003
+ />
2004
+ <span
2005
+ class="min-w-0 flex-1 truncate text-body {keyboardActive
2006
+ ? 'text-body-medium'
2007
+ : ''}"
2008
+ style="font-family: {cssQuotedString(
2009
+ font.family
2010
+ )}, sans-serif; font-display: swap;"
2011
+ >
2012
+ {@html highlightMatch(font.family, searchTerm)}
2013
+ </span>
2014
+
2015
+ {#if font.category === 'Mine' && font.isCustom && !hideTrashIcon}
2016
+ <button
2017
+ type="button"
2018
+ tabindex="-1"
2019
+ class="ms-auto shrink-0 rounded-lg p-1 opacity-0 transition-opacity hover:bg-accent group-hover:opacity-100 [@media(hover:none)]:opacity-100 {selected
2020
+ ? 'pointer-events-none'
2021
+ : ''}"
2022
+ aria-label={$t('editor.font.remove')}
2023
+ onclick={(e) => {
2024
+ e.stopPropagation();
2025
+ e.preventDefault();
2026
+ removeFont(font.family);
2027
+ }}
2028
+ >
2029
+ <IconTrash class="size-4 stroke-[1.333] text-muted-foreground" />
2030
+ </button>
2031
+ {/if}
2032
+ </div>
2033
+ {/each}
2034
+ </div>
2035
+ {/if}
2036
+ </div>
2037
+ </div>
2038
+ </div>
2039
+ </div>
2040
+ </Popover.Content>
2041
+ </Popover.Root>
2042
+ </div>
2043
+ </InputControllerRow>
2044
+
2045
+ <InputControllerRow label={label ? $t('editor.font.weight') : ''}>
2046
+ <div class="font-weight-input-ct w-full">
2047
+ <Popover.Root
2048
+ open={$openDropdowns?.has('weight-' + controllerId)}
2049
+ onOpenChange={(isOpen) => {
2050
+ if (isOpen && Date.now() < fontPickerReadyAt) return;
2051
+ if (isOpen !== $openDropdowns?.has('weight-' + controllerId)) {
2052
+ toggleDropdown('weight-' + controllerId);
2053
+ }
2054
+ }}
2055
+ >
2056
+ <Popover.Trigger
2057
+ tabindex={-1}
2058
+ class="font-ic-trigger group flex h-9 w-full items-center gap-2 rounded-lg bg-accent px-3 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"
2059
+ >
2060
+ <span class="truncate flex-1 text-start text-body text-foreground">
2061
+ {fontWeightLabel(displayWeight || 'Regular', $t)}
2062
+ </span>
2063
+ {#if $openDropdowns?.has('weight-' + controllerId)}
2064
+ <IconChevronUp class="size-4 shrink-0 stroke-[1.333] text-muted-foreground" />
2065
+ {:else}
2066
+ <IconChevronDown class="size-4 shrink-0 stroke-[1.333] text-muted-foreground" />
2067
+ {/if}
2068
+ </Popover.Trigger>
2069
+ <Popover.Content
2070
+ align="end"
2071
+ sideOffset={8}
2072
+ class="font-weight-popover z-50 w-[200px] overflow-hidden rounded-xl border border-border bg-popover p-1 text-popover-foreground outline-none"
2073
+ tabindex={-1}
2074
+ onOpenAutoFocus={(event) => event.preventDefault()}
2075
+ portalProps={{ to: fontPickerPortalHost }}
2076
+ >
2077
+ <Command.Root>
2078
+ <Command.List aria-label={$t('editor.font.weightList')}>
2079
+ <Command.Group>
2080
+ {#each availableWeights as weight}
2081
+ {@const selected = displayWeight === weight}
2082
+ <Command.Item
2083
+ value={weight}
2084
+ tabindex={-1}
2085
+ onSelect={() => handleWeightSelect(weight)}
2086
+ class="flex h-8 cursor-pointer items-center gap-2 rounded-lg px-2 text-body outline-none data-[selected=true]:bg-brand-subtle hover:bg-accent"
2087
+ >
2088
+ <IconCheck
2089
+ class="size-4 shrink-0 stroke-[1.333] {selected
2090
+ ? 'opacity-100'
2091
+ : 'opacity-0'}"
2092
+ />
2093
+ <span class="truncate">{fontWeightLabel(weight, $t)}</span>
2094
+ </Command.Item>
2095
+ {/each}
2096
+ </Command.Group>
2097
+ </Command.List>
2098
+ </Command.Root>
2099
+ </Popover.Content>
2100
+ </Popover.Root>
2101
+ </div>
2102
+ </InputControllerRow>
2103
+
2104
+ {#if description}
2105
+ <p class="text-caption text-muted-foreground px-0 py-0">{description}</p>
2106
+ {/if}
2075
2107
  </div>
2076
2108
 
2077
2109
  <style>
2078
- .font-family-row,
2079
- .font-weight-row {
2080
- display: flex;
2081
- align-items: center;
2082
- justify-content: space-between;
2083
- width: 100%;
2084
- }
2085
-
2086
- .font-family-label-ct,
2087
- .font-weight-label-ct {
2088
- flex: 1 1 auto;
2089
- min-width: 0;
2090
- }
2091
-
2092
- .font-family-input-ct,
2093
- .font-weight-input-ct {
2094
- width: 185px !important;
2095
- max-width: 185px !important;
2096
- min-width: 185px !important;
2097
- margin-inline-start: auto;
2098
- flex-shrink: 0;
2099
- position: relative;
2100
- }
2101
-
2102
- /* Update button styles */
2103
- :global(button.bg-transparent) {
2104
- background: transparent !important;
2105
- border: none !important;
2106
- }
2107
-
2108
- :global(button.bg-transparent:hover),
2109
- :global(button.bg-transparent:focus) {
2110
- background-color: transparent !important;
2111
- }
2112
-
2113
- /* Keep scrollbar styles */
2114
- :global(.overflow-y-auto) {
2115
- -webkit-overflow-scrolling: touch;
2116
- scrollbar-width: thin;
2117
- scrollbar-color: hsl(var(--grey3)) transparent;
2118
- }
2119
-
2120
- /* Trigger fills the 185px column only — do not leak width:100% to other ICs */
2121
- .font-family-input-ct :global(.popover-trigger),
2122
- .font-family-input-ct :global(.popover-trigger button),
2123
- .font-weight-input-ct :global(.popover-trigger),
2124
- .font-weight-input-ct :global(.popover-trigger button) {
2125
- width: 100% !important;
2126
- height: 100% !important;
2127
- }
2128
-
2129
- /* Custom styling for font items in RecentItemsSection */
2130
- :global([data-item]) {
2131
- border-radius: var(--radius-small) !important;
2132
- }
2133
-
2134
- :global([data-item].bg-\[hsl\(var\(--forest-green-10\)\)\]) {
2135
- background-color: hsl(var(--light-green)) !important;
2136
- color: hsl(var(--sage-green)) !important;
2137
- }
2138
-
2139
- :global([data-item]:hover) {
2140
- background-color: hsl(var(--light-green)) !important;
2141
- }
2142
-
2143
- .font-family-input-ct :global(button:focus),
2144
- .font-family-input-ct :global(button:focus-visible),
2145
- .font-weight-input-ct :global(button:focus),
2146
- .font-weight-input-ct :global(button:focus-visible),
2147
- :global(.font-input-popover:focus),
2148
- :global(.font-input-popover:focus-visible),
2149
- :global(.font-input-popover *:focus),
2150
- :global(.font-input-popover *:focus-visible) {
2151
- outline: none !important;
2152
- outline-offset: 0 !important;
2153
- }
2154
-
2155
- /* Clamp to the viewport so the Fonts header and list stay on screen */
2156
- :global(.font-input-popover) {
2157
- z-index: 100000000 !important;
2158
- will-change: transform;
2159
- transform: translateZ(0);
2160
- backface-visibility: hidden;
2161
- max-width: calc(100vw - 16px) !important;
2162
- overflow: hidden;
2163
- }
2164
-
2165
- :global(.font-popover-content) {
2166
- will-change: transform;
2167
- transform: translateZ(0);
2168
- backface-visibility: hidden;
2169
- }
2170
-
2171
- /* Optimize font list container scrolling */
2172
- :global(.font-list-container) {
2173
- -webkit-overflow-scrolling: touch;
2174
- scrollbar-width: thin;
2175
- scrollbar-color: hsl(var(--grey3)) transparent;
2176
- will-change: transform;
2177
- transform: translateZ(0);
2178
- backface-visibility: hidden;
2179
- }
2180
-
2181
- /* Add transition only for border appearance */
2182
- :global(.transition-border) {
2183
- transition: border-color 0.2s ease-in;
2184
- }
2185
-
2186
- /* Prevent scrolling when showing empty state */
2187
- .empty-state-wrapper {
2188
- position: absolute;
2189
- top: 0;
2190
- left: 0;
2191
- right: 0;
2192
- bottom: 0;
2193
- display: flex;
2194
- align-items: center;
2195
- justify-content: center;
2196
- overflow: hidden;
2197
- padding-top: 60px; /* Add padding to account for the header */
2198
- padding-bottom: 60px; /* Balance the padding */
2199
- z-index: 10; /* Ensure it appears above other content */
2200
- }
2201
-
2202
- /* Selected row only — never leave white text on a white (deselected) row. */
2203
- :global(.font-list-row.selected-item),
2204
- :global([data-item].selected-item) {
2205
- color: white !important;
2206
- }
2207
- :global(.font-list-row:not(.selected-item)),
2208
- :global([data-item]:not(.selected-item)) {
2209
- color: hsl(var(--grey7)) !important;
2210
- }
2211
-
2212
- /* Prevent hover from keeping sage+white on a row that is no longer selected. */
2213
- :global(.font-list-row.selected-item:hover),
2214
- :global([data-item].selected-item:hover) {
2215
- background-color: hsl(var(--sage-green)) !important;
2216
- color: white !important;
2217
- }
2218
-
2219
- /* Style for search result highlighting */
2220
- :global(.search-result-highlight) {
2221
- color: hsl(var(--sage-green)) !important;
2222
- }
2223
-
2224
- /* Style for active search item */
2225
- :global(.active-search-item) {
2226
- background-color: hsl(var(--light-green)) !important;
2227
- color: hsl(var(--sage-green)) !important;
2228
- }
2229
-
2230
- /* Style for selected item text */
2231
- :global(.selected-item-text) {
2232
- color: white !important;
2233
- }
2234
-
2235
- /* Style for selected item highlight */
2236
- :global(.selected-item-highlight) {
2237
- color: hsl(var(--grey7)) !important;
2238
- }
2239
-
2240
- /* Style for checkmark icon */
2241
- :global(.checkmark-icon) {
2242
- margin-inline-start: 12px !important;
2243
- }
2244
-
2245
- /* Style for font item padding */
2246
- :global(.font-item) {
2247
- padding-inline-start: 48px !important;
2248
- }
2249
-
2250
- /* Style for font item height */
2251
- :global(.font-item) {
2252
- height: 42px !important;
2253
- display: flex !important;
2254
- align-items: center !important;
2255
- }
2256
-
2257
- /* Style for font item text */
2258
- :global(.font-item-text) {
2259
- font-size: 24px !important;
2260
- }
2261
-
2262
- /* Style for font item padding */
2263
- :global(.font-item) {
2264
- padding: 8px !important;
2265
- }
2110
+ .font-family-input-ct :global(.popover-trigger),
2111
+ .font-family-input-ct :global(.popover-trigger button),
2112
+ .font-weight-input-ct :global(.popover-trigger),
2113
+ .font-weight-input-ct :global(.popover-trigger button) {
2114
+ width: 100%;
2115
+ height: 100%;
2116
+ }
2117
+
2118
+ :global(.font-input-popover) {
2119
+ z-index: 100000000;
2120
+ max-width: calc(100vw - 16px);
2121
+ }
2122
+
2123
+ :global(.font-list-container) {
2124
+ -webkit-overflow-scrolling: touch;
2125
+ scrollbar-width: thin;
2126
+ scrollbar-color: var(--border) transparent;
2127
+ }
2128
+
2129
+ :global(.transition-border) {
2130
+ transition: border-color 0.2s ease-in;
2131
+ }
2132
+
2133
+ .empty-state-wrapper {
2134
+ position: absolute;
2135
+ inset: 0;
2136
+ z-index: 10;
2137
+ display: flex;
2138
+ align-items: center;
2139
+ justify-content: center;
2140
+ overflow: hidden;
2141
+ padding-top: 60px;
2142
+ padding-bottom: 60px;
2143
+ }
2144
+
2145
+ :global(.search-result-highlight) {
2146
+ color: var(--brand);
2147
+ }
2266
2148
  </style>
2267
-
2268
-
2269
-