@widgetic/editor 4.1.13 → 4.1.15

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 (89) 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 +55 -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 +426 -1333
  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/InputControllerRenderer.svelte +5 -1
  28. package/dist/components/ic/InputControllerRenderer.svelte.d.ts +2 -1
  29. package/dist/components/ic/InputControllerRow.svelte +74 -0
  30. package/dist/components/ic/InputControllerRow.svelte.d.ts +14 -0
  31. package/dist/components/ic/KnowledgeDocumentsInputController.svelte +401 -0
  32. package/dist/components/ic/KnowledgeDocumentsInputController.svelte.d.ts +11 -0
  33. package/dist/components/ic/KnowledgeTextForm.svelte +109 -0
  34. package/dist/components/ic/KnowledgeTextForm.svelte.d.ts +15 -0
  35. package/dist/components/ic/NumberControls.svelte +303 -269
  36. package/dist/components/ic/NumberControls.svelte.d.ts +4 -1
  37. package/dist/components/ic/NumberInputController.svelte +361 -301
  38. package/dist/components/ic/NumberInputController.svelte.d.ts +2 -0
  39. package/dist/components/ic/PositionInputController.svelte +253 -176
  40. package/dist/components/ic/PositionInputController.svelte.d.ts +2 -0
  41. package/dist/components/ic/RadioGroupInputController.svelte +71 -137
  42. package/dist/components/ic/RadioGroupInputController.svelte.d.ts +2 -8
  43. package/dist/components/ic/RangeCalendarInputController.svelte +233 -270
  44. package/dist/components/ic/RangeCalendarInputController.svelte.d.ts +2 -2
  45. package/dist/components/ic/RoundedCornersInputController.svelte +412 -435
  46. package/dist/components/ic/RoundedCornersInputController.svelte.d.ts +2 -0
  47. package/dist/components/ic/SliderInputController.svelte +263 -332
  48. package/dist/components/ic/SliderInputController.svelte.d.ts +1 -1
  49. package/dist/components/ic/SliderRangeInputController.svelte +140 -144
  50. package/dist/components/ic/SliderRangeInputController.svelte.d.ts +3 -3
  51. package/dist/components/ic/SwitchInputController.svelte +47 -109
  52. package/dist/components/ic/TagsInputController.svelte +95 -110
  53. package/dist/components/ic/TextAreaInputController.svelte +1794 -1935
  54. package/dist/components/ic/TextAreaPreviewInputController.svelte +436 -438
  55. package/dist/components/ic/TextAreaPreviewInputController.svelte.d.ts +2 -2
  56. package/dist/components/ic/TextInputController.svelte +65 -75
  57. package/dist/components/ic/TextInputController.svelte.d.ts +2 -0
  58. package/dist/components/ic/TimeInputController.svelte +433 -431
  59. package/dist/components/ic/VectorInputController.svelte +1833 -1831
  60. package/dist/components/ic/VectorInputController.svelte.d.ts +10 -10
  61. package/dist/components/ic/index.d.ts +2 -0
  62. package/dist/components/ic/index.js +2 -0
  63. package/dist/components/ic/shared/CategoryTabs.svelte +28 -35
  64. package/dist/components/ic/shared/ItemGrid.svelte +145 -179
  65. package/dist/components/ic/shared/RecentItemsSection.svelte +208 -271
  66. package/dist/components/ic/shared/RecentItemsSection.svelte.d.ts +1 -1
  67. package/dist/components/ui/arrows/OpacitySliderArrows.svelte +23 -38
  68. package/dist/components/ui/arrows/OpacitySliderArrows.svelte.d.ts +1 -4
  69. package/dist/components/ui/calendar-editor-fit/EditorCalendarStyles.svelte +45 -0
  70. package/dist/components/ui/calendar-editor-fit/EditorCalendarStyles.svelte.d.ts +26 -0
  71. package/dist/components/ui/checkerboard-background/CheckerboardBackground.svelte +20 -12
  72. package/dist/components/ui/shadow-picker-host/ShadowPickerHost.svelte +39 -0
  73. package/dist/components/ui/shadow-picker-host/ShadowPickerHost.svelte.d.ts +10 -0
  74. package/dist/composition/compositionApi.d.ts +21 -1
  75. package/dist/composition/compositionApi.js +64 -5
  76. package/dist/composition/knowledgeDocuments.d.ts +90 -0
  77. package/dist/composition/knowledgeDocuments.js +94 -0
  78. package/dist/composition/knowledgeDocumentsPanel.d.ts +152 -0
  79. package/dist/composition/knowledgeDocumentsPanel.js +443 -0
  80. package/dist/i18n/language.d.ts +86 -36
  81. package/dist/i18n/messages.d.ts +97 -34
  82. package/dist/i18n/messages.js +104 -34
  83. package/dist/i18n/translate.d.ts +1 -1
  84. package/dist/index.d.ts +1 -0
  85. package/dist/knowledgeDocumentsContext.d.ts +10 -0
  86. package/dist/knowledgeDocumentsContext.js +31 -0
  87. package/dist/utils.d.ts +7 -0
  88. package/dist/utils.js +26 -2
  89. package/package.json +4 -4
@@ -17,1860 +17,1862 @@
17
17
 
18
18
  -->
19
19
  <script module lang="ts">
20
- import type { Writable } from 'svelte/store';
21
-
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 VectorInputControllerProps {
25
- label: string;
26
- value?: { name: string; category: string; url: string } | null;
27
- onChange?: (newValue: { name: string; category: string; url: string } | null) => void;
28
- description?: string;
29
- controllerId: string;
30
- openDropdowns: Writable<Set<string>>;
31
- toggleDropdown: (id: string) => void;
32
- onFocus?: () => void;
33
- hideRecentFromList?: boolean;
34
- hideTrashIcon?: boolean;
35
- }
20
+ import type { Writable } from 'svelte/store';
21
+
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 VectorInputControllerProps {
25
+ label: string;
26
+ value?: { name: string; category: string; url: string } | null;
27
+ onChange?: (newValue: { name: string; category: string; url: string } | null) => void;
28
+ description?: string;
29
+ controllerId: string;
30
+ openDropdowns: Writable<Set<string>>;
31
+ toggleDropdown: (id: string) => void;
32
+ onFocus?: () => 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
- /** COMPONENTS IMPORTS */
44
- // Shadcn UI components imports from design-system
45
- import { Popover, EmptyState } from '@widgetic/design-system/components';
46
-
47
- // Import Tabler Icons from design-system
48
- import { Check, IconCloudUpload, IconCaretDownFilled, IconAlertTriangle } from '@widgetic/design-system/icons';
49
-
50
- // Import InputControllerHeader
51
- import { InputControllerHeader } from './index';
52
-
53
- // Import shared components
54
- // import { SearchInput } from './shared';
55
- import { SearchInput } from '@widgetic/design-system/components';
56
- import CategoryTabs from './shared/CategoryTabs.svelte';
57
- import { RecentItemsSection, ItemGrid } from './shared';
58
- import { useEditorLanguage } from '../../i18n/language';
59
- import { categoryLabel } from '../../i18n/labels';
60
-
61
- // The words of the editor in the language of the page.
62
- const { t } = useEditorLanguage();
63
-
64
- // Utils imports
65
- import {
66
- vectorUtils,
67
- vectorCategories,
68
- type VectorItem,
69
- type RecentVector,
70
- recentVectorsStore
71
- } from '../../utils/vectorUtils';
72
- import type { VectorData } from '../../utils/VectorManager';
73
- import VectorManager from '../../utils/VectorManager';
74
- import { escapeHtml } from '../../utils/htmlSafety';
75
- import { listenForScroll, queryInTreeOf } from '../../utils/shadowDom';
76
- import { readEditorStorageValue, writeEditorStorageValue } from '../../utils/editorStorage';
77
-
78
- // Constants
79
- const VECTOR_FILTER_KEY = (id: string) => `vector-specific-filter-state-${id}`;
80
- const MAX_RECENT_VECTORS = 3;
81
-
82
- type FilterType = typeof vectorCategories.types[number];
83
- let currentFilter: FilterType = 'All'; // Default to 'All'
84
- let lastActiveFilter: FilterType = 'All'; // Add this to track the last active filter
85
- let filterOptions: FilterType[] = [...vectorCategories.types];
86
-
87
- /**
88
- * Component Props
89
- * @prop {string} label - Display label for the vector selector
90
- * @prop {string} value - Currently selected vector
91
- * @prop {Function} onChange - Callback when vector selection changes
92
- * @prop {string} description - Optional help text
93
- * @prop {string} controllerId - Unique identifier for this controller
94
- * @prop {any} openDropdowns - Store tracking open dropdown states
95
- * @prop {Function} toggleDropdown - Function to toggle dropdown state
96
- * @prop {Function} onFocus - Optional focus handler
97
- */
98
- export let label: VectorInputControllerProps['label'];
99
- export let value: VectorInputControllerProps['value'] = null;
100
- export let onChange: VectorInputControllerProps['onChange'] = undefined;
101
- export let description: VectorInputControllerProps['description'] = undefined;
102
- export let controllerId: VectorInputControllerProps['controllerId'];
103
- export let openDropdowns: VectorInputControllerProps['openDropdowns'];
104
- export let toggleDropdown: VectorInputControllerProps['toggleDropdown'];
105
- export let onFocus: VectorInputControllerProps['onFocus'] = () => {};
106
-
107
- // Vector modal state
108
- let showVectorModal = false;
109
-
110
- // Vector search and filter state
111
- let allVectors: VectorItem[] = [];
112
- let recentVectors: VectorItem[] = [];
113
- let filteredVectors: VectorData[] = [];
114
- let searchTerm = '';
115
- let searchBatchIndex = VectorManager.initialVectorNumber;
116
- const SEARCH_BATCH_SIZE = VectorManager.BATCH_SIZE;
117
-
118
- // Vector loading optimization
119
- let vectorListContainer: HTMLElement;
120
- // The control's own element: it says which tree (the page or a module's shadow root) to listen for scrolling in
121
- let controllerElement: HTMLDivElement | undefined;
122
- let vectorObserver = new IntersectionObserver(() => {});
123
-
124
- // Initialize VectorManager instance
125
- let vectorManagerInstance: VectorManager;
126
- let buttonWidth = 0;
127
-
128
- let scrollTimeout: ReturnType<typeof setTimeout>;
129
-
130
- // Add these variables for search
131
- let activeSearchIndex = -1;
132
-
133
- // Add loading state
134
- let isLoadingBatch = false;
135
-
136
- // Add new prop for controlling vector list behavior
137
- export let hideRecentFromList: VectorInputControllerProps['hideRecentFromList'] = false;
138
- export let hideTrashIcon: VectorInputControllerProps['hideTrashIcon'] = true;
139
-
140
- // Add scroll state tracking
141
- let isScrolled = false;
142
-
143
- // Add loading state variables for ItemGrid
144
- let loadingMoreVectors = false;
145
- let hasMoreVectors = false;
146
-
147
- // Add state to track SVG loading errors
148
- let svgLoadErrors = new Map<string, boolean>();
149
-
150
- // Function to handle SVG loading errors
151
- function handleSvgError(vectorName: string, event: Event): void {
152
- // Extract more information about the error source
153
- let errorUrl = 'unknown';
154
- if (event && event.target instanceof HTMLImageElement) {
155
- errorUrl = event.target.src || 'unknown';
156
- event.target.style.display = 'none';
157
- }
158
-
159
- console.error(`❌ [VectorInput] Failed to load SVG: "${vectorName}" from URL: ${errorUrl}`);
160
- svgLoadErrors.set(vectorName, true);
161
- // Force component update by reassigning the Map
162
- svgLoadErrors = new Map(svgLoadErrors);
163
- }
164
-
165
- // Function to check if a vector has a loading error
166
- function hasSvgLoadError(vectorName: string): boolean {
167
- return svgLoadErrors.has(vectorName);
168
- }
169
-
170
- // Function to render fallback for failed SVG loads
171
- function renderSvgFallback(vectorName: string): string {
172
- return `
173
- <div class="flex items-center justify-center w-full h-full bg-grey1 rounded-large widgetic-radius">
174
- <div class="flex flex-col items-center justify-center gap-1 p-2 text-center">
175
- <span class="text-error">
176
- <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
39
+ // Svelte imports
40
+ import { onMount, onDestroy, tick } from 'svelte';
41
+ const browser = typeof window !== 'undefined';
42
+
43
+ /** COMPONENTS IMPORTS */
44
+ // Shadcn UI components imports from design-system
45
+ import { Popover, EmptyState, IconButton } from '@widgetic/design-system/components';
46
+
47
+ import {
48
+ IconCloudUpload,
49
+ IconChevronDown,
50
+ IconChevronUp,
51
+ IconAlertTriangle
52
+ } from '@widgetic/design-system/icons';
53
+
54
+ import InputControllerRow from './InputControllerRow.svelte';
55
+
56
+ // Import shared components
57
+ // import { SearchInput } from './shared';
58
+ import { SearchInput } from '@widgetic/design-system/components';
59
+ import CategoryTabs from './shared/CategoryTabs.svelte';
60
+ import { RecentItemsSection, ItemGrid } from './shared';
61
+ import { useEditorLanguage } from '../../i18n/language';
62
+ import { categoryLabel } from '../../i18n/labels';
63
+
64
+ // The words of the editor in the language of the page.
65
+ const { t } = useEditorLanguage();
66
+
67
+ $: vectorLoadFailedLabel = $t('editor.vector.loadFailed');
68
+
69
+ // Utils imports
70
+ import {
71
+ vectorUtils,
72
+ vectorCategories,
73
+ type VectorItem,
74
+ type RecentVector,
75
+ recentVectorsStore
76
+ } from '../../utils/vectorUtils';
77
+ import type { VectorData } from '../../utils/VectorManager';
78
+ import VectorManager from '../../utils/VectorManager';
79
+ import { escapeHtml } from '../../utils/htmlSafety';
80
+ import { listenForScroll, queryInTreeOf } from '../../utils/shadowDom';
81
+ import { readEditorStorageValue, writeEditorStorageValue } from '../../utils/editorStorage';
82
+
83
+ // Constants
84
+ const VECTOR_FILTER_KEY = (id: string) => `vector-specific-filter-state-${id}`;
85
+ const MAX_RECENT_VECTORS = 3;
86
+
87
+ type FilterType = (typeof vectorCategories.types)[number];
88
+ let currentFilter: FilterType = 'All'; // Default to 'All'
89
+ let lastActiveFilter: FilterType = 'All'; // Add this to track the last active filter
90
+ let filterOptions: FilterType[] = [...vectorCategories.types];
91
+
92
+ /**
93
+ * Component Props
94
+ * @prop {string} label - Display label for the vector selector
95
+ * @prop {string} value - Currently selected vector
96
+ * @prop {Function} onChange - Callback when vector selection changes
97
+ * @prop {string} description - Optional help text
98
+ * @prop {string} controllerId - Unique identifier for this controller
99
+ * @prop {any} openDropdowns - Store tracking open dropdown states
100
+ * @prop {Function} toggleDropdown - Function to toggle dropdown state
101
+ * @prop {Function} onFocus - Optional focus handler
102
+ */
103
+ export let label: VectorInputControllerProps['label'];
104
+ export let value: VectorInputControllerProps['value'] = null;
105
+ export let onChange: VectorInputControllerProps['onChange'] = undefined;
106
+ export let description: VectorInputControllerProps['description'] = undefined;
107
+ export let controllerId: VectorInputControllerProps['controllerId'];
108
+ export let openDropdowns: VectorInputControllerProps['openDropdowns'];
109
+ export let toggleDropdown: VectorInputControllerProps['toggleDropdown'];
110
+ export let onFocus: VectorInputControllerProps['onFocus'] = () => {};
111
+
112
+ // Vector modal state
113
+ let showVectorModal = false;
114
+
115
+ // Vector search and filter state
116
+ let allVectors: VectorItem[] = [];
117
+ let recentVectors: VectorItem[] = [];
118
+ let filteredVectors: VectorData[] = [];
119
+ let searchTerm = '';
120
+ let searchBatchIndex = VectorManager.initialVectorNumber;
121
+ const SEARCH_BATCH_SIZE = VectorManager.BATCH_SIZE;
122
+
123
+ // Vector loading optimization
124
+ let vectorListContainer: HTMLElement;
125
+ // The control's own element: it says which tree (the page or a module's shadow root) to listen for scrolling in
126
+ let controllerElement: HTMLDivElement | undefined;
127
+ let vectorObserver = new IntersectionObserver(() => {});
128
+
129
+ // Initialize VectorManager instance
130
+ let vectorManagerInstance: VectorManager;
131
+ let buttonWidth = 0;
132
+
133
+ let scrollTimeout: ReturnType<typeof setTimeout>;
134
+
135
+ // Add these variables for search
136
+ let activeSearchIndex = -1;
137
+
138
+ // Add loading state
139
+ let isLoadingBatch = false;
140
+
141
+ // Add new prop for controlling vector list behavior
142
+ export let hideRecentFromList: VectorInputControllerProps['hideRecentFromList'] = false;
143
+ export let hideTrashIcon: VectorInputControllerProps['hideTrashIcon'] = true;
144
+
145
+ // Add scroll state tracking
146
+ let isScrolled = false;
147
+
148
+ // Add loading state variables for ItemGrid
149
+ let loadingMoreVectors = false;
150
+ let hasMoreVectors = false;
151
+
152
+ // Add state to track SVG loading errors
153
+ let svgLoadErrors = new Map<string, boolean>();
154
+
155
+ // Function to handle SVG loading errors
156
+ function handleSvgError(vectorName: string, event: Event): void {
157
+ // Extract more information about the error source
158
+ let errorUrl = 'unknown';
159
+ if (event && event.target instanceof HTMLImageElement) {
160
+ errorUrl = event.target.src || 'unknown';
161
+ event.target.style.display = 'none';
162
+ }
163
+
164
+ console.error(`❌ [VectorInput] Failed to load SVG: "${vectorName}" from URL: ${errorUrl}`);
165
+ svgLoadErrors.set(vectorName, true);
166
+ // Force component update by reassigning the Map
167
+ svgLoadErrors = new Map(svgLoadErrors);
168
+ }
169
+
170
+ // Function to check if a vector has a loading error
171
+ function hasSvgLoadError(vectorName: string): boolean {
172
+ return svgLoadErrors.has(vectorName);
173
+ }
174
+
175
+ // Function to render fallback for failed SVG loads
176
+ function renderSvgFallback(): string {
177
+ return `
178
+ <div class="flex size-full items-center justify-center rounded-lg bg-muted">
179
+ <div class="flex flex-col items-center justify-center gap-1 p-1 text-center">
180
+ <span class="text-destructive">
181
+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
177
182
  <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"></path>
178
183
  <path d="M12 9v4"></path>
179
184
  <path d="M12 17h.01"></path>
180
185
  </svg>
181
186
  </span>
182
- <span class="caption text-grey5">Failed to load</span>
187
+ <span class="text-caption text-muted-foreground">${escapeHtml(vectorLoadFailedLabel)}</span>
183
188
  </div>
184
189
  </div>
185
190
  `;
186
- }
187
-
188
- /**
189
- * The sticky header of the vector list. It is looked up in the tree the list lives in (inside a module that is a
190
- * shadow root, which `document.querySelector` cannot see into), and the id is escaped so that one with dots or
191
- * brackets in it is found too.
192
- */
193
- function findStickyHeader(): Element | null {
194
- return queryInTreeOf(vectorListContainer, `#${CSS.escape(`vector-header-${controllerId}`)}`);
195
- }
196
-
197
- // Function to update scroll state
198
- function updateScrollState() {
199
- if (vectorListContainer) {
200
- const wasScrolled = isScrolled;
201
- isScrolled = vectorListContainer.scrollTop > 10;
202
-
203
- // If we're transitioning from scrolled to not scrolled, remove transition
204
- if (wasScrolled && !isScrolled) {
205
- const stickyHeader = findStickyHeader();
206
- if (stickyHeader) {
207
- stickyHeader.classList.remove('transition-border');
208
- // Force a reflow to ensure the transition class removal takes effect
209
- void (stickyHeader as HTMLElement).offsetWidth;
210
- }
211
- } else if (!wasScrolled && isScrolled) {
212
- // Add transition class when starting to scroll
213
- const stickyHeader = findStickyHeader();
214
- if (stickyHeader) {
215
- stickyHeader.classList.add('transition-border');
216
- }
217
- }
218
- }
219
- }
220
-
221
- // Subscribe to store changes
222
- $: {
223
- recentVectors = $recentVectorsStore
224
- .map(vector => ({
225
- name: vector.name,
226
- category: vectorCategories.normalize(vector.category) as VectorItem['category'],
227
- url: vector.url,
228
- isCustom: vector.isCustom
229
- }));
230
-
231
- // Update filtered vectors when recent vectors change
232
- if (hideRecentFromList) {
233
- updateFilteredVectors();
234
- }
235
- }
236
-
237
- // Add debounce function at the top of the script section
238
- function debounce<T extends (...args: any[]) => Promise<void>>(
239
- func: T,
240
- wait: number
241
- ): (...args: Parameters<T>) => void {
242
- let timeout: ReturnType<typeof setTimeout> | null = null;
243
- return function(this: any, ...args: Parameters<T>): void {
244
- const context = this;
245
-
246
- // Ensure we have a valid event with a target
247
- const event = args[0] as Event;
248
- if (!event || !event.target) {
249
- console.warn('❌ [VectorSearch] Debounced function called with invalid event:', event);
250
- return;
251
- }
252
-
253
- if (timeout) clearTimeout(timeout);
254
- timeout = setTimeout(() => {
255
- timeout = null;
256
- func.apply(context, args);
257
- }, wait);
258
- };
259
- };
260
-
261
- // Add a variable to store the debounced search function
262
- let debouncedSearch: (event: Event) => void;
263
-
264
- /**
265
- * Updates the filtered vectors list based on search term and category
266
- * Also handles setting up the observer after updating
267
- */
268
- function updateFilteredVectors() {
269
- let vectors = [...allVectors];
270
-
271
- // console.log('🔄 [VectorInput] Updating filtered vectors:', {
272
- // allVectors: allVectors.length,
273
- // currentFilter,
274
- // searchTerm,
275
- // hideRecentFromList,
276
- // recentVectors: recentVectors.length
277
- // });
278
-
279
- // Apply search filter
280
- if (searchTerm) {
281
- const term = searchTerm.toLowerCase();
282
- vectors = vectors.filter(vector =>
283
- vector.name.toLowerCase().includes(term)
284
- );
285
- }
286
-
287
- // Apply category filter
288
- if (currentFilter !== 'All') {
289
- vectors = vectors.filter(vector => {
290
- // For Mine category, check exact match
291
- if (currentFilter === 'Mine') {
292
- return vector.category === 'Mine';
293
- }
294
- // For other categories, use normalization
295
- const normalizedCategory = vectorCategories.normalize(vector.category);
296
- return normalizedCategory === currentFilter;
297
- });
298
- }
299
-
300
- // Optionally filter out recent vectors
301
- if (hideRecentFromList) {
302
- vectors = vectors.filter(vector =>
303
- !recentVectors.some(recent => recent.name === vector.name)
304
- );
305
- }
306
-
307
- // Update filtered vectors
308
- filteredVectors = vectors;
309
-
310
- // console.log('✅ [VectorInput] Filtered vectors result:', {
311
- // total: vectors.length,
312
- // filter: currentFilter,
313
- // searchTerm,
314
- // hideRecentFromList,
315
- // recentVectorsHidden: hideRecentFromList ? recentVectors.length : 0
316
- // });
317
-
318
- // Setup observer after updating filtered vectors
319
- // Use a small timeout to ensure the DOM has updated
320
- if (scrollTimeout) {
321
- clearTimeout(scrollTimeout);
322
- }
323
-
324
- scrollTimeout = setTimeout(() => {
325
- setupVectorObserver();
326
- }, 50);
327
- }
328
-
329
- // Initialize the debounced search function in onMount
330
- onMount(async () => {
331
- // Initialize the debounced search function
332
- debouncedSearch = debounce(async (event: Event) => {
333
- await handleSearch(event);
334
- }, 300); // 300ms debounce time
335
-
336
- // SVG loading errors are noticed by the watchVectorImageErrors action on the list of pictures. They used to be
337
- // announced on `document` by an inline onerror handler and caught here; with the editor inside a partner's page
338
- // that was an event on the partner's document and a handler stored on the partner's `window`.
339
-
340
- try {
341
- if (browser) {
342
- // Load saved filter
343
- const savedFilter = readEditorStorageValue(VECTOR_FILTER_KEY(controllerId));
344
- if (savedFilter) {
345
- currentFilter = savedFilter as FilterType;
346
- }
347
-
348
- // Check if the current selected vector exists/loads
349
- if (value?.name && value.url) {
350
- const testImg = new Image();
351
- testImg.onload = () => {
352
- // Vector loads successfully
353
- // console.log(`✅ [VectorInput] Current vector loads successfully: ${value.name}`);
354
- };
355
- testImg.onerror = () => {
356
- // Mark as error if it fails to load
357
- console.error(`❌ [VectorInput] Current vector failed to load: ${value.name}, URL: ${value.url}`);
358
- svgLoadErrors.set(value.name, true);
359
- svgLoadErrors = new Map(svgLoadErrors);
360
- };
361
- testImg.src = value.url;
362
- }
363
- }
364
-
365
- // console.log('🚀 [VectorInput] Initializing controller:', {
366
- // controllerId,
367
- // initialFilter: currentFilter
368
- // });
369
-
370
- vectorManagerInstance = await VectorManager.getInstance();
371
-
372
- // Load and verify recent vectors
373
- const loadedRecentVectors = vectorUtils.getRecentVectors();
374
- // console.log('📝 [VectorInput] Loading recent vectors:', loadedRecentVectors);
375
-
376
- // Filter and validate recent vectors
377
- const validRecentVectors = loadedRecentVectors
378
- .slice(0, MAX_RECENT_VECTORS);
379
-
380
- // Update store with validated vectors
381
- recentVectorsStore.set(validRecentVectors);
382
-
383
- // Update local state
384
- recentVectors = validRecentVectors.map(vector => ({
385
- name: vector.name,
386
- category: vectorCategories.normalize(vector.category) as VectorItem['category'],
387
- url: vector.url,
388
- isCustom: vector.isCustom
389
- }));
390
-
391
- // console.log('✅ [VectorInput] Recent vectors initialized:', {
392
- // loaded: loadedRecentVectors.length,
393
- // valid: validRecentVectors.length,
394
- // vectors: validRecentVectors.map(v => v.name)
395
- // });
396
-
397
- // Initialize vectors list with saved filter
398
- const initializeVectors = async () => {
399
- if (currentFilter === 'Mine') {
400
- const customVectors = await vectorManagerInstance.loadCustomVectors();
401
- return customVectors;
402
- }
403
-
404
- // For All category, load standard vectors first, then append custom vectors
405
- const standardVectors = await vectorManagerInstance.getInitialVectorList();
406
- const customVectors = await vectorManagerInstance.loadCustomVectors();
407
-
408
- if (currentFilter === 'All') {
409
- return [
410
- ...standardVectors.filter(vector => !vector.isCustom),
411
- ...customVectors
412
- ];
413
- }
414
-
415
- // For other categories, filter out custom vectors
416
- return standardVectors.filter(vector => !vector.isCustom);
417
- };
418
-
419
- const initialVectors = await initializeVectors();
420
-
421
- // Force a fresh batch for this controller
422
- vectorManagerInstance.resetBatchIndex(controllerId);
423
-
424
- // For Mine category, use all custom vectors
425
- if (currentFilter === 'Mine') {
426
- allVectors = initialVectors;
427
- } else {
428
- // For other categories, use normal filtering
429
- if (currentFilter !== 'All') {
430
- const categoryVectors = initialVectors.filter(vector =>
431
- vectorCategories.normalize(vector.category) === currentFilter
432
- );
433
- allVectors = categoryVectors.slice(0, searchBatchIndex);
434
- } else {
435
- allVectors = initialVectors.slice(0, searchBatchIndex);
436
- }
437
- }
438
-
439
- // Update filtered vectors immediately
440
- updateFilteredVectors();
441
-
442
- // Preload the vectors to detect missing files early
443
- if (filteredVectors.length > 0) {
444
- // console.log(`🔍 [VectorInput] Preloading ${filteredVectors.length} vectors to detect missing files...`);
445
- preloadVectors(filteredVectors);
446
- }
447
-
448
- // Also preload recent vectors
449
- if (recentVectors.length > 0) {
450
- // console.log(`🔍 [VectorInput] Preloading ${recentVectors.length} recent vectors...`);
451
- preloadVectors(recentVectors);
452
- }
453
-
454
- // Setup observer after vectors are loaded
455
- scrollTimeout = setTimeout(() => {
456
- setupVectorObserver();
457
- }, 0);
458
-
459
- // console.log('✅ [VectorInput] Controller initialized:', {
460
- // controllerId,
461
- // initialVectors: allVectors.length,
462
- // filteredVectors: filteredVectors.length,
463
- // recentVectors: recentVectors.length,
464
- // currentFilter,
465
- // customVectors: allVectors.filter(v => v.category === 'Mine').length
466
- // });
467
- } catch (error) {
468
- console.error('❌ [VectorInput] Error during initialization:', error);
469
- }
470
- });
471
-
472
- /**
473
- * Manages real-time search functionality
474
- * Prioritizes recent vectors in search results
475
- * Enhanced to better handle partial matches
476
- */
477
- async function handleSearch(event: Event) {
478
- try {
479
- const input = event.target as HTMLInputElement;
480
- // Add null check for input element
481
- if (!input) {
482
- console.warn('❌ [VectorSearch] Search input element is null');
483
- return;
484
- }
485
-
486
- const newSearchTerm = input.value;
487
-
488
- // Skip processing if the search term hasn't changed
489
- if (newSearchTerm === searchTerm) {
490
- return;
491
- }
492
-
493
- // If this is a new search (was empty before), save the current filter
494
- if (!searchTerm && newSearchTerm) {
495
- lastActiveFilter = currentFilter;
496
- currentFilter = 'All'; // Reset to All when starting a search
497
- if (browser) {
498
- writeEditorStorageValue(VECTOR_FILTER_KEY(controllerId), 'All');
499
- }
500
- }
501
-
502
- searchTerm = newSearchTerm;
503
-
504
- // console.log('🔍 [VectorSearch] Search input:', { searchTerm });
505
-
506
- if (!searchTerm.trim()) {
507
- // Reset to normal view if search is empty
508
- searchTerm = '';
509
-
510
- // Reset batch index to start fresh
511
- if (vectorManagerInstance) {
512
- vectorManagerInstance.resetBatchIndex(controllerId);
513
-
514
- // Reload vectors for the current category
515
- await tick(); // Ensure the UI updates first
516
-
517
- // The reactive statement for empty search term will handle reloading
518
- }
519
-
520
- if (vectorListContainer) {
521
- vectorListContainer.scrollTop = 0;
522
- }
523
- return; // Let reactivity handle the reset
524
- }
525
-
526
- // Just load the complete vector list if we're searching
527
- const completeVectorList = await vectorManagerInstance?.getCompleteVectorList(true) || [];
528
- allVectors = completeVectorList;
529
-
530
- // Reset scroll position
531
- if (vectorListContainer) {
532
- vectorListContainer.scrollTop = 0;
533
- }
534
-
535
- // Ensure the UI updates to show "Search Results" instead of "More"
536
- await tick();
537
- } catch (error) {
538
- console.error('❌ [VectorSearch] Error:', error);
539
- }
540
- }
541
-
542
- // Add a derived store for search results
543
- let currentSearchResults: VectorData[] = [];
544
-
545
- // Update the reactive statement for search
546
- $: if (searchTerm) {
547
- const searchValue = searchTerm.toLowerCase().trim();
548
- // Only process if the search value is not empty
549
- if (searchValue) {
550
- try {
551
- // Get both standard and custom vectors from cache - add null checks
552
- const standardVectors = vectorManagerInstance?.getCachedVectorList()?.filter(vector => !vector.isCustom) || [];
553
- const customVectors = vectorManagerInstance?.getCachedVectorList()?.filter(vector => vector.isCustom) || [];
554
-
555
- // Merge both lists
556
- const allCachedVectors = [...standardVectors, ...customVectors];
557
-
558
- // Enhanced search algorithm
559
- const newSearchResults = allCachedVectors
560
- .filter(vector => {
561
- const nameLower = vector.name.toLowerCase().trim();
562
-
563
- // Use exact matching for search term instead of splitting by spaces
564
- return nameLower.includes(searchValue);
565
- })
566
- .sort((a, b) => {
567
- const aName = a.name.toLowerCase();
568
- const bName = b.name.toLowerCase();
569
-
570
- // Prioritize vectors that start with the search term
571
- const aStartsWith = aName.startsWith(searchValue);
572
- const bStartsWith = bName.startsWith(searchValue);
573
-
574
- if (aStartsWith && !bStartsWith) return -1;
575
- if (!aStartsWith && bStartsWith) return 1;
576
-
577
- // Then prioritize vectors where search term appears earlier
578
- const aIndex = aName.indexOf(searchValue);
579
- const bIndex = bName.indexOf(searchValue);
580
-
581
- if (aIndex !== -1 && bIndex !== -1) {
582
- return aIndex - bIndex;
583
- }
584
-
585
- // Fall back to alphabetical sorting
586
- return aName.localeCompare(bName);
587
- });
588
-
589
- // Only update results if they've changed
590
- if (JSON.stringify(newSearchResults) !== JSON.stringify(currentSearchResults)) {
591
- // Store all search results for batching
592
- currentSearchResults = newSearchResults;
593
-
594
- // Select first item automatically if we have results
595
- activeSearchIndex = currentSearchResults.length > 0 ? 0 : -1;
596
-
597
- // Show more initial results (double the default)
598
- const initialResultsCount = Math.min(VectorManager.initialVectorNumber * 2, currentSearchResults.length);
599
- filteredVectors = currentSearchResults.slice(0, initialResultsCount);
600
-
601
- // Reset scroll position
602
- if (vectorListContainer) {
603
- vectorListContainer.scrollTop = 0;
604
- }
605
-
606
- // console.log('📝 [VectorSearch] Updated results:', {
607
- // searchValue,
608
- // totalMatches: currentSearchResults.length,
609
- // displayedResults: filteredVectors.length,
610
- // activeIndex: activeSearchIndex
611
- // });
612
- }
613
- } catch (error) {
614
- console.error('❌ [VectorSearch] Error processing search:', error);
615
- }
616
- }
617
- }
618
-
619
- // Handle empty search term separately to avoid reactivity loop
620
- $: if (searchTerm === '') {
621
- // Only reset if we actually had search results before or if we have no filtered vectors
622
- if (currentSearchResults.length > 0 || filteredVectors.length === 0) {
623
- // console.log('🔄 [VectorSearch] Handling empty search term');
624
-
625
- // Reset search state
626
- currentSearchResults = [];
627
- activeSearchIndex = -1; // Reset active index
628
-
629
- // Reset batch index to start fresh
630
- if (vectorManagerInstance) {
631
- vectorManagerInstance.resetBatchIndex(controllerId);
632
-
633
- // Get vectors for current category
634
- let vectors: VectorData[] = [];
635
-
636
- if (currentFilter === 'All') {
637
- try {
638
- // Get standard vectors first - add null check
639
- const standardVectors = vectorManagerInstance.getCachedVectorList()
640
- ?.filter(vector => !vector.isCustom)
641
- ?.slice(0, VectorManager.initialVectorNumber) || [];
642
-
643
- // Get custom vectors - add null check
644
- const customVectors = vectorManagerInstance.getCachedVectorList()
645
- ?.filter(vector => vector.isCustom) || [];
646
-
647
- // Combine them with custom vectors at the end
648
- vectors = [...standardVectors, ...customVectors];
649
- } catch (error) {
650
- console.error('❌ [VectorSearch] Error getting cached vectors:', error);
651
- vectors = [];
652
- }
653
- } else if (currentFilter === 'Mine') {
654
- vectors = vectorManagerInstance.getPreloadedVectors(currentFilter as VectorItem['category']);
655
- } else {
656
- // For other categories, filter out custom vectors
657
- vectors = vectorManagerInstance.getPreloadedVectors(currentFilter as VectorItem['category'])
658
- .filter(vector => !vector.isCustom);
659
- }
660
-
661
- // Update all vectors
662
- allVectors = vectors;
663
-
664
- // Update filtered vectors directly to ensure UI updates
665
- updateFilteredVectors();
666
- }
667
-
668
- // Reset scroll position
669
- if (vectorListContainer) {
670
- vectorListContainer.scrollTop = 0;
671
- }
672
-
673
- // Ensure the observer is set up after the DOM updates
674
- setTimeout(() => {
675
- setupVectorObserver();
676
- // console.log('🔄 [VectorSearch] Observer setup after search clear');
677
- }, 50);
678
- }
679
- }
680
-
681
- /**
682
- * Manages intersection observer for lazy loading vectors
683
- * Only loads vectors when they become visible in viewport
684
- */
685
- function setupVectorObserver() {
686
- if (!vectorListContainer) {
687
- // console.log('⚠️ [VectorInput] Vector list container not found, retrying...');
688
- return scrollTimeout = setTimeout(() => {
689
- if (vectorListContainer) {
690
- setupVectorObserver();
691
- }
692
- }, 50);
693
- }
694
-
695
- // If we have no vectors to observe, try to update filtered vectors first
696
- if (!filteredVectors.length) {
697
- // console.log('⚠️ [VectorInput] No vectors available to observe, updating filtered vectors');
698
- updateFilteredVectors();
699
-
700
- // If we still have no vectors, log a warning and return
701
- if (!filteredVectors.length) {
702
- // console.warn('❌ [VectorInput] No vectors available to observe after update');
703
-
704
- // If we're in a category that should have vectors, try to reload them
705
- if (vectorManagerInstance) {
706
- // console.log('🔄 [VectorInput] Attempting to reload vectors for category:', currentFilter);
707
-
708
- // Reset batch index
709
- vectorManagerInstance.resetBatchIndex(controllerId);
710
-
711
- // Get vectors for current category
712
- let vectors: VectorData[] = [];
713
-
714
- try {
715
- if (currentFilter === 'All') {
716
- // Get standard vectors first - add null check
717
- const standardVectors = vectorManagerInstance.getCachedVectorList()
718
- ?.filter(vector => !vector.isCustom)
719
- ?.slice(0, VectorManager.initialVectorNumber) || [];
720
-
721
- // Get custom vectors - add null check
722
- const customVectors = vectorManagerInstance.getCachedVectorList()
723
- ?.filter(vector => vector.isCustom) || [];
724
-
725
- // Combine them with custom vectors at the end
726
- vectors = [...standardVectors, ...customVectors];
727
- } else if (currentFilter === 'Mine') {
728
- vectors = vectorManagerInstance.getPreloadedVectors(currentFilter as VectorItem['category']);
729
- } else {
730
- // For other categories, filter out custom vectors
731
- vectors = vectorManagerInstance.getPreloadedVectors(currentFilter as VectorItem['category'])
732
- .filter(vector => !vector.isCustom);
733
- }
734
- } catch (error) {
735
- console.error('❌ [VectorInput] Error getting cached vectors:', error);
736
- vectors = [];
737
- }
738
-
739
- // Update all vectors
740
- allVectors = vectors;
741
- updateFilteredVectors();
742
- }
743
-
744
- return;
745
- }
746
- }
747
-
748
- // console.log('🔍 [VectorInput] Setting up vector observer for', filteredVectors.length, 'vectors');
749
-
750
- // Get the observer from VectorManager
751
- const observer = vectorManagerInstance?.getObserver(vectorListContainer);
752
- if (!observer) {
753
- // console.warn('❌ [VectorInput] Failed to create observer');
754
- return;
755
- }
756
-
757
- // Disconnect existing observer if it exists
758
- if (vectorObserver) {
759
- vectorObserver.disconnect();
760
- }
761
-
762
- vectorObserver = observer;
763
-
764
- // Observe all existing vector elements - add null check
765
- if (vectorListContainer) {
766
- const vectorElements = vectorListContainer.querySelectorAll('[data-vector]');
767
- // console.log('📝 [VectorInput] Observing', vectorElements.length, 'vector elements');
768
-
769
- // Use a more efficient approach to observe elements
770
- // Batch the observation process to reduce performance impact
771
- const batchSize = 20; // Process 20 elements at a time
772
- let currentIndex = 0;
773
-
774
- const observeBatch = () => {
775
- const endIndex = Math.min(currentIndex + batchSize, vectorElements.length);
776
-
777
- for (let i = currentIndex; i < endIndex; i++) {
778
- observer.observe(vectorElements[i]);
779
- }
780
-
781
- currentIndex = endIndex;
782
-
783
- if (currentIndex < vectorElements.length) {
784
- // Process next batch in the next animation frame
785
- requestAnimationFrame(observeBatch);
786
- }
787
- };
788
-
789
- // Start the batched observation process
790
- observeBatch();
791
- }
792
- }
793
-
794
- /**
795
- * Handles keyboard navigation in search results
796
- */
797
- function handleSearchKeydown(event: KeyboardEvent | CustomEvent<KeyboardEvent>) {
798
- // Ensure we have a KeyboardEvent
799
- const keyEvent = event instanceof KeyboardEvent ? event : event.detail;
800
-
801
- // Prevent handling backspace when search is already empty
802
- if (keyEvent.key === 'Backspace' && !searchTerm) {
803
- keyEvent.preventDefault();
804
- return;
805
- }
806
-
807
- if (!filteredVectors.length) return;
808
-
809
- if (keyEvent.key === 'ArrowDown') {
810
- keyEvent.preventDefault();
811
- handleArrowClick('down');
812
- } else if (keyEvent.key === 'ArrowUp') {
813
- keyEvent.preventDefault();
814
- handleArrowClick('up');
815
- } else if (keyEvent.key === 'Enter' && activeSearchIndex !== -1) {
816
- keyEvent.preventDefault();
817
- handleVectorSelect(filteredVectors[activeSearchIndex]);
818
- }
819
- }
820
-
821
- /**
822
- * Updates arrow navigation in search results
823
- */
824
- function handleArrowClick(direction: 'up' | 'down') {
825
- if (!filteredVectors.length) return;
826
-
827
- if (direction === 'down') {
828
- activeSearchIndex = (activeSearchIndex + 1) % filteredVectors.length;
829
- } else {
830
- activeSearchIndex = activeSearchIndex <= 0 ? filteredVectors.length - 1 : activeSearchIndex - 1;
831
- }
832
-
833
- // Ensure the selected item is visible and add null check for vectorListContainer
834
- if (vectorListContainer && activeSearchIndex >= 0 && activeSearchIndex < filteredVectors.length) {
835
- const selectedElement = vectorListContainer.querySelector(`[data-vector="${filteredVectors[activeSearchIndex].name}"]`);
836
- selectedElement?.scrollIntoView({ block: 'nearest' });
837
- }
838
- }
839
-
840
- /**
841
- * Handles vector selection and updates recent vectors
842
- */
843
- function handleVectorSelect(vector: VectorItem | RecentVector) {
844
- // First check if the vector has a loading error
845
- if (hasSvgLoadError(vector.name)) {
846
- console.warn(`⚠️ [VectorInput] Prevented selection of vector with loading error: ${vector.name}`);
847
- return; // Don't select vectors that failed to load
848
- }
849
-
850
- if (onChange) {
851
- const vectorValue = {
852
- name: vector.name,
853
- category: vector.category,
854
- url: vector.url
855
- };
856
-
857
- // Pass the vector value object to onChange
858
- onChange(vectorValue);
859
-
860
- // console.log('✅ [VectorInput] Vector selected:', {
861
- // vector: vectorValue
862
- // });
863
- }
864
- }
865
-
866
- /**
867
- * Handles vector list scrolling
868
- */
869
- function handleVectorListScroll(event: Event) {
870
- // Ensure target is an HTMLElement
871
- if (!(event.target instanceof HTMLElement)) {
872
- return;
873
- }
874
-
875
- // Prevent event propagation to stop global scroll handler from closing the modal
876
- event.stopPropagation();
877
-
878
- // Handle vector loading for visible vectors
879
- vectorManagerInstance?.handleScroll();
880
-
881
- const container = event.target;
882
- const { scrollTop, scrollHeight, clientHeight } = container;
883
- // Increase the threshold to detect when we're closer to the bottom
884
- const scrolledToBottom = (scrollHeight - (scrollTop + clientHeight)) <= 100;
885
-
886
- // Add debug log to help diagnose scrolling issues
887
- // console.log('📜 [VectorScroll] Scroll position:', {
888
- // scrollTop,
889
- // scrollHeight,
890
- // clientHeight,
891
- // remainingScroll: scrollHeight - (scrollTop + clientHeight),
892
- // scrolledToBottom,
893
- // hasSearchTerm: Boolean(searchTerm),
894
- // searchResultsCount: currentSearchResults.length,
895
- // displayedResults: filteredVectors.length
896
- // });
897
-
898
- // Use requestAnimationFrame to optimize scroll handling
899
- if (scrolledToBottom) {
900
- // Use requestAnimationFrame to avoid blocking the UI thread
901
- requestAnimationFrame(() => {
902
- if (searchTerm && currentSearchResults.length > 0) {
903
- // Calculate next batch using SEARCH_BATCH_SIZE
904
- const nextBatchStart = filteredVectors.length;
905
- const nextBatch = currentSearchResults.slice(
906
- nextBatchStart,
907
- nextBatchStart + SEARCH_BATCH_SIZE
908
- );
909
-
910
- if (nextBatch.length > 0) {
911
- // Add new batch to filtered vectors
912
- filteredVectors = [...filteredVectors, ...nextBatch];
913
-
914
- // Setup observer for new vectors
915
- scrollTimeout = setTimeout(() => {
916
- if (vectorListContainer) {
917
- setupVectorObserver();
918
- }
919
- }, 0);
920
-
921
- // console.log('📝 [VectorSearch] Loaded next batch:', {
922
- // batchSize: nextBatch.length,
923
- // totalDisplayed: filteredVectors.length,
924
- // remainingVectors: currentSearchResults.length - filteredVectors.length,
925
- // nextBatchSize: SEARCH_BATCH_SIZE
926
- // });
927
- }
928
- } else {
929
- // Normal vector list scrolling
930
- if (!isLoadingBatch && vectorManagerInstance?.hasMoreVectors(controllerId, currentFilter)) {
931
- loadNextBatch();
932
- }
933
- }
934
- });
935
- }
936
- }
937
-
938
- /**
939
- * Loads the next batch of vectors
940
- */
941
- async function loadNextBatch() {
942
- if (isLoadingBatch) return;
943
-
944
- try {
945
- isLoadingBatch = true;
946
-
947
- // Get next batch for this controller
948
- const newVectors = vectorManagerInstance.getNextBatch(controllerId, currentFilter);
949
-
950
- // Add to existing vectors, ensuring uniqueness
951
- const combinedVectors = [...allVectors, ...newVectors];
952
- allVectors = Array.from(
953
- new Map(combinedVectors.map(vector => [vector.name, vector])).values()
954
- );
955
-
956
- // Update filtered vectors while preserving current filter
957
- updateFilteredVectors();
958
-
959
- // console.log('🔄 [VectorInput] Loaded new batch:', {
960
- // controllerId,
961
- // filter: currentFilter,
962
- // newVectors: newVectors.length,
963
- // totalVectors: allVectors.length,
964
- // filteredVectors: filteredVectors.length
965
- // });
966
-
967
- } catch (error) {
968
- console.error('❌ [VectorInput] Error loading vector batch:', error);
969
- } finally {
970
- isLoadingBatch = false;
971
- }
972
- }
973
-
974
- onDestroy(() => {
975
- stopListeningForScroll();
976
-
977
- if (vectorObserver) {
978
- vectorObserver.disconnect();
979
- }
980
- // Clear any timeouts
981
- if (scrollTimeout) {
982
- clearTimeout(scrollTimeout);
983
- }
984
- showVectorModal = false;
985
-
986
- // console.log('🧹 [VectorInput] Cleanup complete:', {
987
- // controllerId,
988
- // lastFilter: currentFilter
989
- // });
990
- });
991
-
992
- /**
993
- * Opens the file browser for vector selection
994
- */
995
- async function openFileBrowser() {
996
- // console.log('🔍 [VectorInput] Opening file browser for vectors');
997
-
998
- try {
999
- // Get the current vector's ID if it exists in our custom vectors
1000
- const selectedId = value?.name ?
1001
- vectorManagerInstance?.getCachedVectorList()
1002
- .find(v => v.name === value.name && v.category === 'Mine')?.name
1003
- : undefined;
1004
-
1005
- // console.log('🔍 [VectorInput] Opening file browser:', {
1006
- // fileTypes: ['svg'],
1007
- // selectedId
1008
- // });
1009
-
1010
- // TODO: Implement file browser functionality
1011
- // This will be similar to FontInputController but for SVG files
1012
- } catch (error) {
1013
- console.error('❌ [VectorInput] Error opening file browser:', error);
1014
- }
1015
- }
1016
-
1017
- /**
1018
- * Handles category filter changes
1019
- */
1020
- async function handleFilterChange(filter: FilterType) {
1021
- if (currentFilter !== filter) {
1022
- currentFilter = filter;
1023
- lastActiveFilter = filter; // Remember the last active filter
1024
-
1025
- if (browser) {
1026
- writeEditorStorageValue(VECTOR_FILTER_KEY(controllerId), filter);
1027
- }
1028
-
1029
- if (vectorManagerInstance) {
1030
- vectorManagerInstance.resetBatchIndex(controllerId);
1031
-
1032
- try {
1033
- let vectors: VectorData[] = [];
1034
-
1035
- if (filter === 'All') {
1036
- // Get standard vectors first - add null check
1037
- const standardVectors = vectorManagerInstance.getCachedVectorList()
1038
- ?.filter(vector => !vector.isCustom)
1039
- ?.slice(0, searchBatchIndex) || [];
1040
-
1041
- // Get custom vectors - add null check
1042
- const customVectors = vectorManagerInstance.getCachedVectorList()
1043
- ?.filter(vector => vector.isCustom) || [];
1044
-
1045
- // Combine them with custom vectors at the end
1046
- vectors = [...standardVectors, ...customVectors];
1047
- } else if (filter === 'Mine') {
1048
- vectors = vectorManagerInstance.getPreloadedVectors(filter as VectorItem['category']);
1049
- } else {
1050
- // For other categories, filter out custom vectors
1051
- vectors = vectorManagerInstance.getPreloadedVectors(filter as VectorItem['category'])
1052
- .filter(vector => !vector.isCustom);
1053
- }
1054
-
1055
- allVectors = vectors;
1056
- updateFilteredVectors();
1057
-
1058
- // Setup observer in next tick
1059
- scrollTimeout = setTimeout(() => {
1060
- if (vectorListContainer) {
1061
- setupVectorObserver();
1062
- }
1063
- }, 0);
1064
-
1065
- if (vectorListContainer) {
1066
- vectorListContainer.scrollTop = 0;
1067
- }
1068
-
1069
- // console.log('🔄 [VectorInput] Category changed:', {
1070
- // filter,
1071
- // vectors: allVectors.length,
1072
- // filteredVectors: filteredVectors.length,
1073
- // customVectors: allVectors.filter(v => v.isCustom).length
1074
- // });
1075
- } catch (error) {
1076
- console.error('❌ [VectorInput] Error changing category:', error);
1077
- }
1078
- }
1079
- }
1080
- }
1081
-
1082
- /**
1083
- * Creates a custom action for vector observation
1084
- */
1085
- function observeVector(node: HTMLElement) {
1086
- if (vectorObserver) {
1087
- vectorObserver.observe(node);
1088
- }
1089
-
1090
- return {
1091
- destroy() {
1092
- if (vectorObserver) {
1093
- vectorObserver.unobserve(node);
1094
- }
1095
- }
1096
- };
1097
- }
1098
-
1099
- /**
1100
- * Highlights search term matches in vector names.
1101
- * The result is meant for {@html}, so every piece of the name is escaped as it is put in.
1102
- */
1103
- function highlightMatch(name: string, term: string) {
1104
- if (!term) return escapeHtml(name);
1105
- const nameLower = name.toLowerCase();
1106
- const termLower = term.toLowerCase().trim();
1107
-
1108
- // If the name contains the search term, highlight that part in blue
1109
- if (termLower && nameLower.includes(termLower)) {
1110
- const index = nameLower.indexOf(termLower);
1111
- const beforeMatch = escapeHtml(name.slice(0, index));
1112
- const match = escapeHtml(name.slice(index, index + termLower.length));
1113
- const afterMatch = escapeHtml(name.slice(index + termLower.length));
1114
-
1115
- return `<span style="color: hsl(var(--grey7))">${beforeMatch}<span style="color: #45BCFE">${match}</span>${afterMatch}</span>`;
1116
- }
1117
-
1118
- // Default case - just return the name in grey7 color
1119
- return `<span style="color: hsl(var(--grey7))">${escapeHtml(name)}</span>`;
1120
- }
1121
-
1122
-
1123
- /**
1124
- * Removes a custom vector
1125
- */
1126
- async function removeVector(name: string) {
1127
- try {
1128
- // Remove from manager
1129
- await vectorManagerInstance?.removeCustomVector(name);
1130
-
1131
- // If the removed vector was selected, clear the selection
1132
- if (value?.name === name && onChange) {
1133
- onChange(null);
1134
- }
1135
-
1136
- // Remove from recent vectors if present
1137
- const updatedRecentVectors = recentVectors.filter(v => v.name !== name);
1138
- recentVectors = updatedRecentVectors;
1139
-
1140
- // Add lastUsed property before updating store
1141
- const recentVectorsWithLastUsed = updatedRecentVectors.map(v => ({
1142
- ...v,
1143
- lastUsed: Date.now()
1144
- }));
1145
- recentVectorsStore.set(recentVectorsWithLastUsed);
1146
-
1147
- // Remove from all vectors
1148
- allVectors = allVectors.filter(v => v.name !== name);
1149
-
1150
- // Update filtered vectors
1151
- updateFilteredVectors();
1152
-
1153
- // Wait for DOM update
1154
- await tick();
1155
-
1156
- // Re-setup observer for remaining vectors
1157
- setupVectorObserver();
1158
-
1159
- // console.log('✅ [VectorInput] Vector removed:', {
1160
- // name,
1161
- // remainingVectors: allVectors.length,
1162
- // filteredVectors: filteredVectors.length,
1163
- // recentVectors: recentVectors.length
1164
- // });
1165
- } catch (error) {
1166
- console.error('❌ [VectorInput] Error removing vector:', error);
1167
- }
1168
- }
1169
-
1170
- // Add scroll listener with passive option. It listens to the page and, inside a module, to the module's own panels
1171
- // (a scroll never leaves a shadow root, so a listener on the window alone does not hear about those).
1172
- let stopListeningForScroll: () => void = () => {};
1173
- onMount(() => {
1174
- stopListeningForScroll = listenForScroll(controllerElement, handleGlobalScroll, { passive: true });
1175
- });
1176
-
1177
- // (Two touchstart/touchmove listeners that did nothing used to be added to the window here, and could never be
1178
- // removed: each input left two more on the customer's page every time it was shown. They did nothing, so they are
1179
- // gone.)
1180
-
1181
- // Add to VectorInputController.svelte
1182
- function handleToggle() {
1183
- const beforeState = $openDropdowns?.has(controllerId);
1184
- // console.log('🟡 [VectorInput] Toggle start:', {
1185
- // controllerId,
1186
- // beforeState,
1187
- // openDropdowns: Array.from($openDropdowns || new Set())
1188
- // });
1189
-
1190
- toggleDropdown(controllerId);
1191
-
1192
- const afterState = $openDropdowns?.has(controllerId);
1193
- // console.log('🟢 [VectorInput] Toggle complete:', {
1194
- // controllerId,
1195
- // beforeState,
1196
- // afterState,
1197
- // openDropdowns: Array.from($openDropdowns || new Set())
1198
- // });
1199
- }
1200
-
1201
- function closeDropdown() {
1202
- if (open) {
1203
- handleToggle();
1204
- }
1205
- }
1206
-
1207
- function handleGlobalScroll(event: Event) {
1208
- // Don't close if scrolling happens within our containers
1209
- if ((event.target instanceof HTMLElement)) {
1210
- const target = event.target;
1211
-
1212
- // Check if scroll happened inside our containers
1213
- const isInsideVectorList = target === vectorListContainer || target.closest(`#vector-list-${controllerId}`);
1214
- const isInsidePopover = target.closest('.vector-popover-content') || target.closest('.vector-input-popover');
1215
- const isInsideCommand = target.closest('[cmdk-root]');
1216
-
1217
- // Log scroll event for debugging
1218
- // console.log('🔍 [VectorInput] Scroll event:', {
1219
- // target: target.id || target.className,
1220
- // isInsideVectorList,
1221
- // isInsidePopover,
1222
- // isInsideCommand,
1223
- // shouldStayOpen: isInsideVectorList || isInsidePopover || isInsideCommand
1224
- // });
1225
-
1226
- // If scrolling is inside any of our containers, don't close
1227
- if (isInsideVectorList || isInsidePopover || isInsideCommand) {
1228
- return;
1229
- }
1230
-
1231
- // If scrolling outside our containers, close dropdowns
1232
- if ($openDropdowns?.has(controllerId)) {
1233
- // console.log('🔴 [VectorInput] Closing dropdown due to external scroll');
1234
- toggleDropdown(controllerId);
1235
- }
1236
- }
1237
- }
1238
-
1239
- // Add to VectorInputController.svelte
1240
- $: open = $openDropdowns.has(controllerId) || false;
1241
-
1242
- // Add after filteredVectors.length > 0 check
1243
- $: if (filteredVectors.length > 0 && vectorListContainer) {
1244
- // console.log('📝 [VectorInput] Vectors loaded, setting up observer...');
1245
- setupVectorObserver();
1246
- }
1247
-
1248
- // Add these event handlers
1249
- function handleButtonClick() {
1250
- const currentState = $openDropdowns?.has(controllerId);
1251
- // console.log('🔵 [VectorInput] Button click start:', {
1252
- // controllerId,
1253
- // currentState,
1254
- // openDropdowns: Array.from($openDropdowns || new Set()),
1255
- // source: 'button'
1256
- // });
1257
-
1258
- if (!currentState) {
1259
- // console.log('🎯 [VectorInput] Triggering focus');
1260
- onFocus();
1261
- }
1262
- // toggleDropdown(controllerId);
1263
- }
1264
-
1265
- function handleKeyDown(event: KeyboardEvent) {
1266
- if (event.key === 'Enter' || event.key === ' ') {
1267
- event.preventDefault();
1268
- handleButtonClick();
1269
- }
1270
- }
1271
-
1272
- // Add this function
1273
- function measureWidth(node: HTMLElement) {
1274
- const resizeObserver = new ResizeObserver(() => {
1275
- buttonWidth = node.offsetWidth;
1276
- });
1277
-
1278
- resizeObserver.observe(node);
1279
-
1280
- return {
1281
- destroy() {
1282
- resizeObserver.disconnect();
1283
- }
1284
- };
1285
- }
1286
-
1287
- // Add this reactive statement
1288
- $: popoverStyle = `width: ${buttonWidth}px`;
1289
-
1290
- // Update the trash click handler
1291
- function handleTrashClick(vector: VectorItem, event: MouseEvent) {
1292
- event.preventDefault();
1293
- event.stopPropagation();
1294
- removeVector(vector.name);
1295
- }
1296
-
1297
- /**
1298
- * Svelte action for the list that holds the vector pictures: notices a picture that does not load and shows the
1299
- * "Failed to load" state for that vector. `error` events do not bubble, so it listens in the capture phase; a
1300
- * picture is found by its data-vector-name (see renderVectorItem). It replaces an inline onerror attribute that
1301
- * reported through `document`, which is the partner's page when the editor runs inside one.
1302
- */
1303
- function watchVectorImageErrors(node: HTMLElement) {
1304
- const onImageError = (event: Event) => {
1305
- const image = event.target;
1306
- if (!(image instanceof HTMLImageElement)) return;
1307
- const vectorName = image.dataset.vectorName;
1308
- if (!vectorName) return;
1309
- image.style.display = 'none';
1310
- // Reported once per vector, however many pictures of it are on screen.
1311
- if (hasSvgLoadError(vectorName)) return;
1312
- const vectorData = allVectors.find(vector => vector.name === vectorName);
1313
- console.error(`❌ [VectorInput] Failed to load SVG: "${vectorName}" from URL: ${vectorData?.url || image.src || 'unknown'}`);
1314
- svgLoadErrors.set(vectorName, true);
1315
- // Force component update
1316
- svgLoadErrors = new Map(svgLoadErrors);
1317
- };
1318
-
1319
- node.addEventListener('error', onImageError, true);
1320
-
1321
- return {
1322
- destroy() {
1323
- node.removeEventListener('error', onImageError, true);
1324
- }
1325
- };
1326
- }
1327
-
1328
- // Create a Svelte action to handle image error events
1329
- function handleImageError(node: HTMLElement, vectorName: string) {
1330
- const errorHandler = (event: Event) => {
1331
- // console.log(`❌ [VectorInput] Image failed to load: ${vectorName}`);
1332
- svgLoadErrors.set(vectorName, true);
1333
- svgLoadErrors = new Map(svgLoadErrors);
1334
-
1335
- if (node instanceof HTMLImageElement) {
1336
- node.style.display = 'none';
1337
- }
1338
- };
1339
-
1340
- node.addEventListener('error', errorHandler);
1341
-
1342
- return {
1343
- destroy() {
1344
- node.removeEventListener('error', errorHandler);
1345
- },
1346
- update(newVectorName: string) {
1347
- vectorName = newVectorName;
1348
- }
1349
- };
1350
- }
1351
-
1352
- // Functions for RecentItemsSection and ItemGrid
1353
- function renderVectorItem(vector: VectorItem) {
1354
- // If we already know this SVG has a load error, show fallback
1355
- if (hasSvgLoadError(vector.name)) {
1356
- return {
1357
- html: `
1358
- <div class="flex items-center justify-center w-full h-full bg-grey1 rounded-large widgetic-radius">
1359
- <div class="flex flex-col items-center justify-center gap-1 p-2 text-center">
1360
- <span class="text-error">
1361
- <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1362
- <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"></path>
1363
- <path d="M12 9v4"></path>
1364
- <path d="M12 17h.01"></path>
1365
- </svg>
1366
- </span>
1367
- <span class="caption text-grey5">Failed to load</span>
1368
- </div>
1369
- </div>
1370
- `
1371
- };
1372
- }
1373
-
1374
- // The result is used as HTML by RecentItemsSection and ItemGrid: the name and the address of a vector (a custom
1375
- // one is named after the person's own file) are escaped as they are put in. A picture that does not load is
1376
- // noticed by watchVectorImageErrors, which finds it by data-vector-name; an inline onerror="..." would not run
1377
- // under a strict Content-Security-Policy.
1378
- return {
1379
- html: `
191
+ }
192
+
193
+ /**
194
+ * The sticky header of the vector list. It is looked up in the tree the list lives in (inside a module that is a
195
+ * shadow root, which `document.querySelector` cannot see into), and the id is escaped so that one with dots or
196
+ * brackets in it is found too.
197
+ */
198
+ function findStickyHeader(): Element | null {
199
+ return queryInTreeOf(vectorListContainer, `#${CSS.escape(`vector-header-${controllerId}`)}`);
200
+ }
201
+
202
+ // Function to update scroll state
203
+ function updateScrollState() {
204
+ if (vectorListContainer) {
205
+ const wasScrolled = isScrolled;
206
+ isScrolled = vectorListContainer.scrollTop > 10;
207
+
208
+ // If we're transitioning from scrolled to not scrolled, remove transition
209
+ if (wasScrolled && !isScrolled) {
210
+ const stickyHeader = findStickyHeader();
211
+ if (stickyHeader) {
212
+ stickyHeader.classList.remove('transition-border');
213
+ // Force a reflow to ensure the transition class removal takes effect
214
+ void (stickyHeader as HTMLElement).offsetWidth;
215
+ }
216
+ } else if (!wasScrolled && isScrolled) {
217
+ // Add transition class when starting to scroll
218
+ const stickyHeader = findStickyHeader();
219
+ if (stickyHeader) {
220
+ stickyHeader.classList.add('transition-border');
221
+ }
222
+ }
223
+ }
224
+ }
225
+
226
+ // Subscribe to store changes
227
+ $: {
228
+ recentVectors = $recentVectorsStore.map((vector) => ({
229
+ name: vector.name,
230
+ category: vectorCategories.normalize(vector.category) as VectorItem['category'],
231
+ url: vector.url,
232
+ isCustom: vector.isCustom
233
+ }));
234
+
235
+ // Update filtered vectors when recent vectors change
236
+ if (hideRecentFromList) {
237
+ updateFilteredVectors();
238
+ }
239
+ }
240
+
241
+ // Add debounce function at the top of the script section
242
+ function debounce<T extends (...args: any[]) => Promise<void>>(
243
+ func: T,
244
+ wait: number
245
+ ): (...args: Parameters<T>) => void {
246
+ let timeout: ReturnType<typeof setTimeout> | null = null;
247
+ return function (this: any, ...args: Parameters<T>): void {
248
+ const context = this;
249
+
250
+ // Ensure we have a valid event with a target
251
+ const event = args[0] as Event;
252
+ if (!event || !event.target) {
253
+ console.warn('❌ [VectorSearch] Debounced function called with invalid event:', event);
254
+ return;
255
+ }
256
+
257
+ if (timeout) clearTimeout(timeout);
258
+ timeout = setTimeout(() => {
259
+ timeout = null;
260
+ func.apply(context, args);
261
+ }, wait);
262
+ };
263
+ }
264
+
265
+ // Add a variable to store the debounced search function
266
+ let debouncedSearch: (event: Event) => void;
267
+
268
+ /**
269
+ * Updates the filtered vectors list based on search term and category
270
+ * Also handles setting up the observer after updating
271
+ */
272
+ function updateFilteredVectors() {
273
+ let vectors = [...allVectors];
274
+
275
+ // console.log('🔄 [VectorInput] Updating filtered vectors:', {
276
+ // allVectors: allVectors.length,
277
+ // currentFilter,
278
+ // searchTerm,
279
+ // hideRecentFromList,
280
+ // recentVectors: recentVectors.length
281
+ // });
282
+
283
+ // Apply search filter
284
+ if (searchTerm) {
285
+ const term = searchTerm.toLowerCase();
286
+ vectors = vectors.filter((vector) => vector.name.toLowerCase().includes(term));
287
+ }
288
+
289
+ // Apply category filter
290
+ if (currentFilter !== 'All') {
291
+ vectors = vectors.filter((vector) => {
292
+ // For Mine category, check exact match
293
+ if (currentFilter === 'Mine') {
294
+ return vector.category === 'Mine';
295
+ }
296
+ // For other categories, use normalization
297
+ const normalizedCategory = vectorCategories.normalize(vector.category);
298
+ return normalizedCategory === currentFilter;
299
+ });
300
+ }
301
+
302
+ // Optionally filter out recent vectors
303
+ if (hideRecentFromList) {
304
+ vectors = vectors.filter(
305
+ (vector) => !recentVectors.some((recent) => recent.name === vector.name)
306
+ );
307
+ }
308
+
309
+ // Update filtered vectors
310
+ filteredVectors = vectors;
311
+
312
+ // console.log('✅ [VectorInput] Filtered vectors result:', {
313
+ // total: vectors.length,
314
+ // filter: currentFilter,
315
+ // searchTerm,
316
+ // hideRecentFromList,
317
+ // recentVectorsHidden: hideRecentFromList ? recentVectors.length : 0
318
+ // });
319
+
320
+ // Setup observer after updating filtered vectors
321
+ // Use a small timeout to ensure the DOM has updated
322
+ if (scrollTimeout) {
323
+ clearTimeout(scrollTimeout);
324
+ }
325
+
326
+ scrollTimeout = setTimeout(() => {
327
+ setupVectorObserver();
328
+ }, 50);
329
+ }
330
+
331
+ // Initialize the debounced search function in onMount
332
+ onMount(async () => {
333
+ // Initialize the debounced search function
334
+ debouncedSearch = debounce(async (event: Event) => {
335
+ await handleSearch(event);
336
+ }, 300); // 300ms debounce time
337
+
338
+ // SVG loading errors are noticed by the watchVectorImageErrors action on the list of pictures. They used to be
339
+ // announced on `document` by an inline onerror handler and caught here; with the editor inside a partner's page
340
+ // that was an event on the partner's document and a handler stored on the partner's `window`.
341
+
342
+ try {
343
+ if (browser) {
344
+ // Load saved filter
345
+ const savedFilter = readEditorStorageValue(VECTOR_FILTER_KEY(controllerId));
346
+ if (savedFilter) {
347
+ currentFilter = savedFilter as FilterType;
348
+ }
349
+
350
+ // Check if the current selected vector exists/loads
351
+ if (value?.name && value.url) {
352
+ const testImg = new Image();
353
+ testImg.onload = () => {
354
+ // Vector loads successfully
355
+ // console.log(`✅ [VectorInput] Current vector loads successfully: ${value.name}`);
356
+ };
357
+ testImg.onerror = () => {
358
+ // Mark as error if it fails to load
359
+ console.error(
360
+ `❌ [VectorInput] Current vector failed to load: ${value.name}, URL: ${value.url}`
361
+ );
362
+ svgLoadErrors.set(value.name, true);
363
+ svgLoadErrors = new Map(svgLoadErrors);
364
+ };
365
+ testImg.src = value.url;
366
+ }
367
+ }
368
+
369
+ // console.log('🚀 [VectorInput] Initializing controller:', {
370
+ // controllerId,
371
+ // initialFilter: currentFilter
372
+ // });
373
+
374
+ vectorManagerInstance = await VectorManager.getInstance();
375
+
376
+ // Load and verify recent vectors
377
+ const loadedRecentVectors = vectorUtils.getRecentVectors();
378
+ // console.log('📝 [VectorInput] Loading recent vectors:', loadedRecentVectors);
379
+
380
+ // Filter and validate recent vectors
381
+ const validRecentVectors = loadedRecentVectors.slice(0, MAX_RECENT_VECTORS);
382
+
383
+ // Update store with validated vectors
384
+ recentVectorsStore.set(validRecentVectors);
385
+
386
+ // Update local state
387
+ recentVectors = validRecentVectors.map((vector) => ({
388
+ name: vector.name,
389
+ category: vectorCategories.normalize(vector.category) as VectorItem['category'],
390
+ url: vector.url,
391
+ isCustom: vector.isCustom
392
+ }));
393
+
394
+ // console.log('✅ [VectorInput] Recent vectors initialized:', {
395
+ // loaded: loadedRecentVectors.length,
396
+ // valid: validRecentVectors.length,
397
+ // vectors: validRecentVectors.map(v => v.name)
398
+ // });
399
+
400
+ // Initialize vectors list with saved filter
401
+ const initializeVectors = async () => {
402
+ if (currentFilter === 'Mine') {
403
+ const customVectors = await vectorManagerInstance.loadCustomVectors();
404
+ return customVectors;
405
+ }
406
+
407
+ // For All category, load standard vectors first, then append custom vectors
408
+ const standardVectors = await vectorManagerInstance.getInitialVectorList();
409
+ const customVectors = await vectorManagerInstance.loadCustomVectors();
410
+
411
+ if (currentFilter === 'All') {
412
+ return [...standardVectors.filter((vector) => !vector.isCustom), ...customVectors];
413
+ }
414
+
415
+ // For other categories, filter out custom vectors
416
+ return standardVectors.filter((vector) => !vector.isCustom);
417
+ };
418
+
419
+ const initialVectors = await initializeVectors();
420
+
421
+ // Force a fresh batch for this controller
422
+ vectorManagerInstance.resetBatchIndex(controllerId);
423
+
424
+ // For Mine category, use all custom vectors
425
+ if (currentFilter === 'Mine') {
426
+ allVectors = initialVectors;
427
+ } else {
428
+ // For other categories, use normal filtering
429
+ if (currentFilter !== 'All') {
430
+ const categoryVectors = initialVectors.filter(
431
+ (vector) => vectorCategories.normalize(vector.category) === currentFilter
432
+ );
433
+ allVectors = categoryVectors.slice(0, searchBatchIndex);
434
+ } else {
435
+ allVectors = initialVectors.slice(0, searchBatchIndex);
436
+ }
437
+ }
438
+
439
+ // Update filtered vectors immediately
440
+ updateFilteredVectors();
441
+
442
+ // Preload the vectors to detect missing files early
443
+ if (filteredVectors.length > 0) {
444
+ // console.log(`🔍 [VectorInput] Preloading ${filteredVectors.length} vectors to detect missing files...`);
445
+ preloadVectors(filteredVectors);
446
+ }
447
+
448
+ // Also preload recent vectors
449
+ if (recentVectors.length > 0) {
450
+ // console.log(`🔍 [VectorInput] Preloading ${recentVectors.length} recent vectors...`);
451
+ preloadVectors(recentVectors);
452
+ }
453
+
454
+ // Setup observer after vectors are loaded
455
+ scrollTimeout = setTimeout(() => {
456
+ setupVectorObserver();
457
+ }, 0);
458
+
459
+ // console.log('✅ [VectorInput] Controller initialized:', {
460
+ // controllerId,
461
+ // initialVectors: allVectors.length,
462
+ // filteredVectors: filteredVectors.length,
463
+ // recentVectors: recentVectors.length,
464
+ // currentFilter,
465
+ // customVectors: allVectors.filter(v => v.category === 'Mine').length
466
+ // });
467
+ } catch (error) {
468
+ console.error('❌ [VectorInput] Error during initialization:', error);
469
+ }
470
+ });
471
+
472
+ /**
473
+ * Manages real-time search functionality
474
+ * Prioritizes recent vectors in search results
475
+ * Enhanced to better handle partial matches
476
+ */
477
+ async function handleSearch(event: Event) {
478
+ try {
479
+ const input = event.target as HTMLInputElement;
480
+ // Add null check for input element
481
+ if (!input) {
482
+ console.warn('❌ [VectorSearch] Search input element is null');
483
+ return;
484
+ }
485
+
486
+ const newSearchTerm = input.value;
487
+
488
+ // Skip processing if the search term hasn't changed
489
+ if (newSearchTerm === searchTerm) {
490
+ return;
491
+ }
492
+
493
+ // If this is a new search (was empty before), save the current filter
494
+ if (!searchTerm && newSearchTerm) {
495
+ lastActiveFilter = currentFilter;
496
+ currentFilter = 'All'; // Reset to All when starting a search
497
+ if (browser) {
498
+ writeEditorStorageValue(VECTOR_FILTER_KEY(controllerId), 'All');
499
+ }
500
+ }
501
+
502
+ searchTerm = newSearchTerm;
503
+
504
+ // console.log('🔍 [VectorSearch] Search input:', { searchTerm });
505
+
506
+ if (!searchTerm.trim()) {
507
+ // Reset to normal view if search is empty
508
+ searchTerm = '';
509
+
510
+ // Reset batch index to start fresh
511
+ if (vectorManagerInstance) {
512
+ vectorManagerInstance.resetBatchIndex(controllerId);
513
+
514
+ // Reload vectors for the current category
515
+ await tick(); // Ensure the UI updates first
516
+
517
+ // The reactive statement for empty search term will handle reloading
518
+ }
519
+
520
+ if (vectorListContainer) {
521
+ vectorListContainer.scrollTop = 0;
522
+ }
523
+ return; // Let reactivity handle the reset
524
+ }
525
+
526
+ // Just load the complete vector list if we're searching
527
+ const completeVectorList = (await vectorManagerInstance?.getCompleteVectorList(true)) || [];
528
+ allVectors = completeVectorList;
529
+
530
+ // Reset scroll position
531
+ if (vectorListContainer) {
532
+ vectorListContainer.scrollTop = 0;
533
+ }
534
+
535
+ // Ensure the UI updates to show "Search Results" instead of "More"
536
+ await tick();
537
+ } catch (error) {
538
+ console.error('❌ [VectorSearch] Error:', error);
539
+ }
540
+ }
541
+
542
+ // Add a derived store for search results
543
+ let currentSearchResults: VectorData[] = [];
544
+
545
+ // Update the reactive statement for search
546
+ $: if (searchTerm) {
547
+ const searchValue = searchTerm.toLowerCase().trim();
548
+ // Only process if the search value is not empty
549
+ if (searchValue) {
550
+ try {
551
+ // Get both standard and custom vectors from cache - add null checks
552
+ const standardVectors =
553
+ vectorManagerInstance?.getCachedVectorList()?.filter((vector) => !vector.isCustom) || [];
554
+ const customVectors =
555
+ vectorManagerInstance?.getCachedVectorList()?.filter((vector) => vector.isCustom) || [];
556
+
557
+ // Merge both lists
558
+ const allCachedVectors = [...standardVectors, ...customVectors];
559
+
560
+ // Enhanced search algorithm
561
+ const newSearchResults = allCachedVectors
562
+ .filter((vector) => {
563
+ const nameLower = vector.name.toLowerCase().trim();
564
+
565
+ // Use exact matching for search term instead of splitting by spaces
566
+ return nameLower.includes(searchValue);
567
+ })
568
+ .sort((a, b) => {
569
+ const aName = a.name.toLowerCase();
570
+ const bName = b.name.toLowerCase();
571
+
572
+ // Prioritize vectors that start with the search term
573
+ const aStartsWith = aName.startsWith(searchValue);
574
+ const bStartsWith = bName.startsWith(searchValue);
575
+
576
+ if (aStartsWith && !bStartsWith) return -1;
577
+ if (!aStartsWith && bStartsWith) return 1;
578
+
579
+ // Then prioritize vectors where search term appears earlier
580
+ const aIndex = aName.indexOf(searchValue);
581
+ const bIndex = bName.indexOf(searchValue);
582
+
583
+ if (aIndex !== -1 && bIndex !== -1) {
584
+ return aIndex - bIndex;
585
+ }
586
+
587
+ // Fall back to alphabetical sorting
588
+ return aName.localeCompare(bName);
589
+ });
590
+
591
+ // Only update results if they've changed
592
+ if (JSON.stringify(newSearchResults) !== JSON.stringify(currentSearchResults)) {
593
+ // Store all search results for batching
594
+ currentSearchResults = newSearchResults;
595
+
596
+ // Select first item automatically if we have results
597
+ activeSearchIndex = currentSearchResults.length > 0 ? 0 : -1;
598
+
599
+ // Show more initial results (double the default)
600
+ const initialResultsCount = Math.min(
601
+ VectorManager.initialVectorNumber * 2,
602
+ currentSearchResults.length
603
+ );
604
+ filteredVectors = currentSearchResults.slice(0, initialResultsCount);
605
+
606
+ // Reset scroll position
607
+ if (vectorListContainer) {
608
+ vectorListContainer.scrollTop = 0;
609
+ }
610
+
611
+ // console.log('📝 [VectorSearch] Updated results:', {
612
+ // searchValue,
613
+ // totalMatches: currentSearchResults.length,
614
+ // displayedResults: filteredVectors.length,
615
+ // activeIndex: activeSearchIndex
616
+ // });
617
+ }
618
+ } catch (error) {
619
+ console.error('❌ [VectorSearch] Error processing search:', error);
620
+ }
621
+ }
622
+ }
623
+
624
+ // Handle empty search term separately to avoid reactivity loop
625
+ $: if (searchTerm === '') {
626
+ // Only reset if we actually had search results before or if we have no filtered vectors
627
+ if (currentSearchResults.length > 0 || filteredVectors.length === 0) {
628
+ // console.log('🔄 [VectorSearch] Handling empty search term');
629
+
630
+ // Reset search state
631
+ currentSearchResults = [];
632
+ activeSearchIndex = -1; // Reset active index
633
+
634
+ // Reset batch index to start fresh
635
+ if (vectorManagerInstance) {
636
+ vectorManagerInstance.resetBatchIndex(controllerId);
637
+
638
+ // Get vectors for current category
639
+ let vectors: VectorData[] = [];
640
+
641
+ if (currentFilter === 'All') {
642
+ try {
643
+ // Get standard vectors first - add null check
644
+ const standardVectors =
645
+ vectorManagerInstance
646
+ .getCachedVectorList()
647
+ ?.filter((vector) => !vector.isCustom)
648
+ ?.slice(0, VectorManager.initialVectorNumber) || [];
649
+
650
+ // Get custom vectors - add null check
651
+ const customVectors =
652
+ vectorManagerInstance.getCachedVectorList()?.filter((vector) => vector.isCustom) ||
653
+ [];
654
+
655
+ // Combine them with custom vectors at the end
656
+ vectors = [...standardVectors, ...customVectors];
657
+ } catch (error) {
658
+ console.error('❌ [VectorSearch] Error getting cached vectors:', error);
659
+ vectors = [];
660
+ }
661
+ } else if (currentFilter === 'Mine') {
662
+ vectors = vectorManagerInstance.getPreloadedVectors(
663
+ currentFilter as VectorItem['category']
664
+ );
665
+ } else {
666
+ // For other categories, filter out custom vectors
667
+ vectors = vectorManagerInstance
668
+ .getPreloadedVectors(currentFilter as VectorItem['category'])
669
+ .filter((vector) => !vector.isCustom);
670
+ }
671
+
672
+ // Update all vectors
673
+ allVectors = vectors;
674
+
675
+ // Update filtered vectors directly to ensure UI updates
676
+ updateFilteredVectors();
677
+ }
678
+
679
+ // Reset scroll position
680
+ if (vectorListContainer) {
681
+ vectorListContainer.scrollTop = 0;
682
+ }
683
+
684
+ // Ensure the observer is set up after the DOM updates
685
+ setTimeout(() => {
686
+ setupVectorObserver();
687
+ // console.log('🔄 [VectorSearch] Observer setup after search clear');
688
+ }, 50);
689
+ }
690
+ }
691
+
692
+ /**
693
+ * Manages intersection observer for lazy loading vectors
694
+ * Only loads vectors when they become visible in viewport
695
+ */
696
+ function setupVectorObserver() {
697
+ if (!vectorListContainer) {
698
+ // console.log('⚠️ [VectorInput] Vector list container not found, retrying...');
699
+ return (scrollTimeout = setTimeout(() => {
700
+ if (vectorListContainer) {
701
+ setupVectorObserver();
702
+ }
703
+ }, 50));
704
+ }
705
+
706
+ // If we have no vectors to observe, try to update filtered vectors first
707
+ if (!filteredVectors.length) {
708
+ // console.log('⚠️ [VectorInput] No vectors available to observe, updating filtered vectors');
709
+ updateFilteredVectors();
710
+
711
+ // If we still have no vectors, log a warning and return
712
+ if (!filteredVectors.length) {
713
+ // console.warn('❌ [VectorInput] No vectors available to observe after update');
714
+
715
+ // If we're in a category that should have vectors, try to reload them
716
+ if (vectorManagerInstance) {
717
+ // console.log('🔄 [VectorInput] Attempting to reload vectors for category:', currentFilter);
718
+
719
+ // Reset batch index
720
+ vectorManagerInstance.resetBatchIndex(controllerId);
721
+
722
+ // Get vectors for current category
723
+ let vectors: VectorData[] = [];
724
+
725
+ try {
726
+ if (currentFilter === 'All') {
727
+ // Get standard vectors first - add null check
728
+ const standardVectors =
729
+ vectorManagerInstance
730
+ .getCachedVectorList()
731
+ ?.filter((vector) => !vector.isCustom)
732
+ ?.slice(0, VectorManager.initialVectorNumber) || [];
733
+
734
+ // Get custom vectors - add null check
735
+ const customVectors =
736
+ vectorManagerInstance.getCachedVectorList()?.filter((vector) => vector.isCustom) ||
737
+ [];
738
+
739
+ // Combine them with custom vectors at the end
740
+ vectors = [...standardVectors, ...customVectors];
741
+ } else if (currentFilter === 'Mine') {
742
+ vectors = vectorManagerInstance.getPreloadedVectors(
743
+ currentFilter as VectorItem['category']
744
+ );
745
+ } else {
746
+ // For other categories, filter out custom vectors
747
+ vectors = vectorManagerInstance
748
+ .getPreloadedVectors(currentFilter as VectorItem['category'])
749
+ .filter((vector) => !vector.isCustom);
750
+ }
751
+ } catch (error) {
752
+ console.error('❌ [VectorInput] Error getting cached vectors:', error);
753
+ vectors = [];
754
+ }
755
+
756
+ // Update all vectors
757
+ allVectors = vectors;
758
+ updateFilteredVectors();
759
+ }
760
+
761
+ return;
762
+ }
763
+ }
764
+
765
+ // console.log('🔍 [VectorInput] Setting up vector observer for', filteredVectors.length, 'vectors');
766
+
767
+ // Get the observer from VectorManager
768
+ const observer = vectorManagerInstance?.getObserver(vectorListContainer);
769
+ if (!observer) {
770
+ // console.warn('❌ [VectorInput] Failed to create observer');
771
+ return;
772
+ }
773
+
774
+ // Disconnect existing observer if it exists
775
+ if (vectorObserver) {
776
+ vectorObserver.disconnect();
777
+ }
778
+
779
+ vectorObserver = observer;
780
+
781
+ // Observe all existing vector elements - add null check
782
+ if (vectorListContainer) {
783
+ const vectorElements = vectorListContainer.querySelectorAll('[data-vector]');
784
+ // console.log('📝 [VectorInput] Observing', vectorElements.length, 'vector elements');
785
+
786
+ // Use a more efficient approach to observe elements
787
+ // Batch the observation process to reduce performance impact
788
+ const batchSize = 20; // Process 20 elements at a time
789
+ let currentIndex = 0;
790
+
791
+ const observeBatch = () => {
792
+ const endIndex = Math.min(currentIndex + batchSize, vectorElements.length);
793
+
794
+ for (let i = currentIndex; i < endIndex; i++) {
795
+ observer.observe(vectorElements[i]);
796
+ }
797
+
798
+ currentIndex = endIndex;
799
+
800
+ if (currentIndex < vectorElements.length) {
801
+ // Process next batch in the next animation frame
802
+ requestAnimationFrame(observeBatch);
803
+ }
804
+ };
805
+
806
+ // Start the batched observation process
807
+ observeBatch();
808
+ }
809
+ }
810
+
811
+ /**
812
+ * Handles keyboard navigation in search results
813
+ */
814
+ function handleSearchKeydown(event: KeyboardEvent | CustomEvent<KeyboardEvent>) {
815
+ // Ensure we have a KeyboardEvent
816
+ const keyEvent = event instanceof KeyboardEvent ? event : event.detail;
817
+
818
+ // Prevent handling backspace when search is already empty
819
+ if (keyEvent.key === 'Backspace' && !searchTerm) {
820
+ keyEvent.preventDefault();
821
+ return;
822
+ }
823
+
824
+ if (!filteredVectors.length) return;
825
+
826
+ if (keyEvent.key === 'ArrowDown') {
827
+ keyEvent.preventDefault();
828
+ handleArrowClick('down');
829
+ } else if (keyEvent.key === 'ArrowUp') {
830
+ keyEvent.preventDefault();
831
+ handleArrowClick('up');
832
+ } else if (keyEvent.key === 'Enter' && activeSearchIndex !== -1) {
833
+ keyEvent.preventDefault();
834
+ handleVectorSelect(filteredVectors[activeSearchIndex]);
835
+ }
836
+ }
837
+
838
+ /**
839
+ * Updates arrow navigation in search results
840
+ */
841
+ function handleArrowClick(direction: 'up' | 'down') {
842
+ if (!filteredVectors.length) return;
843
+
844
+ if (direction === 'down') {
845
+ activeSearchIndex = (activeSearchIndex + 1) % filteredVectors.length;
846
+ } else {
847
+ activeSearchIndex =
848
+ activeSearchIndex <= 0 ? filteredVectors.length - 1 : activeSearchIndex - 1;
849
+ }
850
+
851
+ // Ensure the selected item is visible and add null check for vectorListContainer
852
+ if (
853
+ vectorListContainer &&
854
+ activeSearchIndex >= 0 &&
855
+ activeSearchIndex < filteredVectors.length
856
+ ) {
857
+ const selectedElement = vectorListContainer.querySelector(
858
+ `[data-vector="${filteredVectors[activeSearchIndex].name}"]`
859
+ );
860
+ selectedElement?.scrollIntoView({ block: 'nearest' });
861
+ }
862
+ }
863
+
864
+ /**
865
+ * Handles vector selection and updates recent vectors
866
+ */
867
+ function handleVectorSelect(vector: VectorItem | RecentVector) {
868
+ // First check if the vector has a loading error
869
+ if (hasSvgLoadError(vector.name)) {
870
+ console.warn(
871
+ `⚠️ [VectorInput] Prevented selection of vector with loading error: ${vector.name}`
872
+ );
873
+ return; // Don't select vectors that failed to load
874
+ }
875
+
876
+ if (onChange) {
877
+ const vectorValue = {
878
+ name: vector.name,
879
+ category: vector.category,
880
+ url: vector.url
881
+ };
882
+
883
+ // Pass the vector value object to onChange
884
+ onChange(vectorValue);
885
+
886
+ // console.log('✅ [VectorInput] Vector selected:', {
887
+ // vector: vectorValue
888
+ // });
889
+ }
890
+ }
891
+
892
+ /**
893
+ * Handles vector list scrolling
894
+ */
895
+ function handleVectorListScroll(event: Event) {
896
+ // Ensure target is an HTMLElement
897
+ if (!(event.target instanceof HTMLElement)) {
898
+ return;
899
+ }
900
+
901
+ // Prevent event propagation to stop global scroll handler from closing the modal
902
+ event.stopPropagation();
903
+
904
+ // Handle vector loading for visible vectors
905
+ vectorManagerInstance?.handleScroll();
906
+
907
+ const container = event.target;
908
+ const { scrollTop, scrollHeight, clientHeight } = container;
909
+ // Increase the threshold to detect when we're closer to the bottom
910
+ const scrolledToBottom = scrollHeight - (scrollTop + clientHeight) <= 100;
911
+
912
+ // Add debug log to help diagnose scrolling issues
913
+ // console.log('📜 [VectorScroll] Scroll position:', {
914
+ // scrollTop,
915
+ // scrollHeight,
916
+ // clientHeight,
917
+ // remainingScroll: scrollHeight - (scrollTop + clientHeight),
918
+ // scrolledToBottom,
919
+ // hasSearchTerm: Boolean(searchTerm),
920
+ // searchResultsCount: currentSearchResults.length,
921
+ // displayedResults: filteredVectors.length
922
+ // });
923
+
924
+ // Use requestAnimationFrame to optimize scroll handling
925
+ if (scrolledToBottom) {
926
+ // Use requestAnimationFrame to avoid blocking the UI thread
927
+ requestAnimationFrame(() => {
928
+ if (searchTerm && currentSearchResults.length > 0) {
929
+ // Calculate next batch using SEARCH_BATCH_SIZE
930
+ const nextBatchStart = filteredVectors.length;
931
+ const nextBatch = currentSearchResults.slice(
932
+ nextBatchStart,
933
+ nextBatchStart + SEARCH_BATCH_SIZE
934
+ );
935
+
936
+ if (nextBatch.length > 0) {
937
+ // Add new batch to filtered vectors
938
+ filteredVectors = [...filteredVectors, ...nextBatch];
939
+
940
+ // Setup observer for new vectors
941
+ scrollTimeout = setTimeout(() => {
942
+ if (vectorListContainer) {
943
+ setupVectorObserver();
944
+ }
945
+ }, 0);
946
+
947
+ // console.log('📝 [VectorSearch] Loaded next batch:', {
948
+ // batchSize: nextBatch.length,
949
+ // totalDisplayed: filteredVectors.length,
950
+ // remainingVectors: currentSearchResults.length - filteredVectors.length,
951
+ // nextBatchSize: SEARCH_BATCH_SIZE
952
+ // });
953
+ }
954
+ } else {
955
+ // Normal vector list scrolling
956
+ if (
957
+ !isLoadingBatch &&
958
+ vectorManagerInstance?.hasMoreVectors(controllerId, currentFilter)
959
+ ) {
960
+ loadNextBatch();
961
+ }
962
+ }
963
+ });
964
+ }
965
+ }
966
+
967
+ /**
968
+ * Loads the next batch of vectors
969
+ */
970
+ async function loadNextBatch() {
971
+ if (isLoadingBatch) return;
972
+
973
+ try {
974
+ isLoadingBatch = true;
975
+
976
+ // Get next batch for this controller
977
+ const newVectors = vectorManagerInstance.getNextBatch(controllerId, currentFilter);
978
+
979
+ // Add to existing vectors, ensuring uniqueness
980
+ const combinedVectors = [...allVectors, ...newVectors];
981
+ allVectors = Array.from(
982
+ new Map(combinedVectors.map((vector) => [vector.name, vector])).values()
983
+ );
984
+
985
+ // Update filtered vectors while preserving current filter
986
+ updateFilteredVectors();
987
+
988
+ // console.log('🔄 [VectorInput] Loaded new batch:', {
989
+ // controllerId,
990
+ // filter: currentFilter,
991
+ // newVectors: newVectors.length,
992
+ // totalVectors: allVectors.length,
993
+ // filteredVectors: filteredVectors.length
994
+ // });
995
+ } catch (error) {
996
+ console.error('❌ [VectorInput] Error loading vector batch:', error);
997
+ } finally {
998
+ isLoadingBatch = false;
999
+ }
1000
+ }
1001
+
1002
+ onDestroy(() => {
1003
+ stopListeningForScroll();
1004
+
1005
+ if (vectorObserver) {
1006
+ vectorObserver.disconnect();
1007
+ }
1008
+ // Clear any timeouts
1009
+ if (scrollTimeout) {
1010
+ clearTimeout(scrollTimeout);
1011
+ }
1012
+ showVectorModal = false;
1013
+
1014
+ // console.log('🧹 [VectorInput] Cleanup complete:', {
1015
+ // controllerId,
1016
+ // lastFilter: currentFilter
1017
+ // });
1018
+ });
1019
+
1020
+ /**
1021
+ * Opens the file browser for vector selection
1022
+ */
1023
+ async function openFileBrowser() {
1024
+ // console.log('🔍 [VectorInput] Opening file browser for vectors');
1025
+
1026
+ try {
1027
+ // Get the current vector's ID if it exists in our custom vectors
1028
+ const selectedId = value?.name
1029
+ ? vectorManagerInstance
1030
+ ?.getCachedVectorList()
1031
+ .find((v) => v.name === value.name && v.category === 'Mine')?.name
1032
+ : undefined;
1033
+
1034
+ // console.log('🔍 [VectorInput] Opening file browser:', {
1035
+ // fileTypes: ['svg'],
1036
+ // selectedId
1037
+ // });
1038
+
1039
+ // TODO: Implement file browser functionality
1040
+ // This will be similar to FontInputController but for SVG files
1041
+ } catch (error) {
1042
+ console.error('❌ [VectorInput] Error opening file browser:', error);
1043
+ }
1044
+ }
1045
+
1046
+ /**
1047
+ * Handles category filter changes
1048
+ */
1049
+ async function handleFilterChange(filter: FilterType) {
1050
+ if (currentFilter !== filter) {
1051
+ currentFilter = filter;
1052
+ lastActiveFilter = filter; // Remember the last active filter
1053
+
1054
+ if (browser) {
1055
+ writeEditorStorageValue(VECTOR_FILTER_KEY(controllerId), filter);
1056
+ }
1057
+
1058
+ if (vectorManagerInstance) {
1059
+ vectorManagerInstance.resetBatchIndex(controllerId);
1060
+
1061
+ try {
1062
+ let vectors: VectorData[] = [];
1063
+
1064
+ if (filter === 'All') {
1065
+ // Get standard vectors first - add null check
1066
+ const standardVectors =
1067
+ vectorManagerInstance
1068
+ .getCachedVectorList()
1069
+ ?.filter((vector) => !vector.isCustom)
1070
+ ?.slice(0, searchBatchIndex) || [];
1071
+
1072
+ // Get custom vectors - add null check
1073
+ const customVectors =
1074
+ vectorManagerInstance.getCachedVectorList()?.filter((vector) => vector.isCustom) ||
1075
+ [];
1076
+
1077
+ // Combine them with custom vectors at the end
1078
+ vectors = [...standardVectors, ...customVectors];
1079
+ } else if (filter === 'Mine') {
1080
+ vectors = vectorManagerInstance.getPreloadedVectors(filter as VectorItem['category']);
1081
+ } else {
1082
+ // For other categories, filter out custom vectors
1083
+ vectors = vectorManagerInstance
1084
+ .getPreloadedVectors(filter as VectorItem['category'])
1085
+ .filter((vector) => !vector.isCustom);
1086
+ }
1087
+
1088
+ allVectors = vectors;
1089
+ updateFilteredVectors();
1090
+
1091
+ // Setup observer in next tick
1092
+ scrollTimeout = setTimeout(() => {
1093
+ if (vectorListContainer) {
1094
+ setupVectorObserver();
1095
+ }
1096
+ }, 0);
1097
+
1098
+ if (vectorListContainer) {
1099
+ vectorListContainer.scrollTop = 0;
1100
+ }
1101
+
1102
+ // console.log('🔄 [VectorInput] Category changed:', {
1103
+ // filter,
1104
+ // vectors: allVectors.length,
1105
+ // filteredVectors: filteredVectors.length,
1106
+ // customVectors: allVectors.filter(v => v.isCustom).length
1107
+ // });
1108
+ } catch (error) {
1109
+ console.error('❌ [VectorInput] Error changing category:', error);
1110
+ }
1111
+ }
1112
+ }
1113
+ }
1114
+
1115
+ /**
1116
+ * Creates a custom action for vector observation
1117
+ */
1118
+ function observeVector(node: HTMLElement) {
1119
+ if (vectorObserver) {
1120
+ vectorObserver.observe(node);
1121
+ }
1122
+
1123
+ return {
1124
+ destroy() {
1125
+ if (vectorObserver) {
1126
+ vectorObserver.unobserve(node);
1127
+ }
1128
+ }
1129
+ };
1130
+ }
1131
+
1132
+ /**
1133
+ * Highlights search term matches in vector names.
1134
+ * The result is meant for {@html}, so every piece of the name is escaped as it is put in.
1135
+ */
1136
+ function highlightMatch(name: string, term: string) {
1137
+ if (!term) return escapeHtml(name);
1138
+ const nameLower = name.toLowerCase();
1139
+ const termLower = term.toLowerCase().trim();
1140
+
1141
+ // If the name contains the search term, highlight that part in blue
1142
+ if (termLower && nameLower.includes(termLower)) {
1143
+ const index = nameLower.indexOf(termLower);
1144
+ const beforeMatch = escapeHtml(name.slice(0, index));
1145
+ const match = escapeHtml(name.slice(index, index + termLower.length));
1146
+ const afterMatch = escapeHtml(name.slice(index + termLower.length));
1147
+
1148
+ return `<span style="color: var(--foreground)">${beforeMatch}<span class="search-result-highlight" style="color: var(--brand)">${match}</span>${afterMatch}</span>`;
1149
+ }
1150
+
1151
+ return `<span style="color: var(--foreground)">${escapeHtml(name)}</span>`;
1152
+ }
1153
+
1154
+ /**
1155
+ * Removes a custom vector
1156
+ */
1157
+ async function removeVector(name: string) {
1158
+ try {
1159
+ // Remove from manager
1160
+ await vectorManagerInstance?.removeCustomVector(name);
1161
+
1162
+ // If the removed vector was selected, clear the selection
1163
+ if (value?.name === name && onChange) {
1164
+ onChange(null);
1165
+ }
1166
+
1167
+ // Remove from recent vectors if present
1168
+ const updatedRecentVectors = recentVectors.filter((v) => v.name !== name);
1169
+ recentVectors = updatedRecentVectors;
1170
+
1171
+ // Add lastUsed property before updating store
1172
+ const recentVectorsWithLastUsed = updatedRecentVectors.map((v) => ({
1173
+ ...v,
1174
+ lastUsed: Date.now()
1175
+ }));
1176
+ recentVectorsStore.set(recentVectorsWithLastUsed);
1177
+
1178
+ // Remove from all vectors
1179
+ allVectors = allVectors.filter((v) => v.name !== name);
1180
+
1181
+ // Update filtered vectors
1182
+ updateFilteredVectors();
1183
+
1184
+ // Wait for DOM update
1185
+ await tick();
1186
+
1187
+ // Re-setup observer for remaining vectors
1188
+ setupVectorObserver();
1189
+
1190
+ // console.log('✅ [VectorInput] Vector removed:', {
1191
+ // name,
1192
+ // remainingVectors: allVectors.length,
1193
+ // filteredVectors: filteredVectors.length,
1194
+ // recentVectors: recentVectors.length
1195
+ // });
1196
+ } catch (error) {
1197
+ console.error('❌ [VectorInput] Error removing vector:', error);
1198
+ }
1199
+ }
1200
+
1201
+ // Add scroll listener with passive option. It listens to the page and, inside a module, to the module's own panels
1202
+ // (a scroll never leaves a shadow root, so a listener on the window alone does not hear about those).
1203
+ let stopListeningForScroll: () => void = () => {};
1204
+ onMount(() => {
1205
+ stopListeningForScroll = listenForScroll(controllerElement, handleGlobalScroll, {
1206
+ passive: true
1207
+ });
1208
+ });
1209
+
1210
+ // (Two touchstart/touchmove listeners that did nothing used to be added to the window here, and could never be
1211
+ // removed: each input left two more on the customer's page every time it was shown. They did nothing, so they are
1212
+ // gone.)
1213
+
1214
+ // Add to VectorInputController.svelte
1215
+ function handleToggle() {
1216
+ const beforeState = $openDropdowns?.has(controllerId);
1217
+ // console.log('🟡 [VectorInput] Toggle start:', {
1218
+ // controllerId,
1219
+ // beforeState,
1220
+ // openDropdowns: Array.from($openDropdowns || new Set())
1221
+ // });
1222
+
1223
+ toggleDropdown(controllerId);
1224
+
1225
+ const afterState = $openDropdowns?.has(controllerId);
1226
+ // console.log('🟢 [VectorInput] Toggle complete:', {
1227
+ // controllerId,
1228
+ // beforeState,
1229
+ // afterState,
1230
+ // openDropdowns: Array.from($openDropdowns || new Set())
1231
+ // });
1232
+ }
1233
+
1234
+ function closeDropdown() {
1235
+ if (open) {
1236
+ handleToggle();
1237
+ }
1238
+ }
1239
+
1240
+ function handleGlobalScroll(event: Event) {
1241
+ // Don't close if scrolling happens within our containers
1242
+ if (event.target instanceof HTMLElement) {
1243
+ const target = event.target;
1244
+
1245
+ // Check if scroll happened inside our containers
1246
+ const isInsideVectorList =
1247
+ target === vectorListContainer || target.closest(`#vector-list-${controllerId}`);
1248
+ const isInsidePopover =
1249
+ target.closest('.vector-popover-content') || target.closest('.vector-input-popover');
1250
+ const isInsideCommand = target.closest('[cmdk-root]');
1251
+
1252
+ // Log scroll event for debugging
1253
+ // console.log('🔍 [VectorInput] Scroll event:', {
1254
+ // target: target.id || target.className,
1255
+ // isInsideVectorList,
1256
+ // isInsidePopover,
1257
+ // isInsideCommand,
1258
+ // shouldStayOpen: isInsideVectorList || isInsidePopover || isInsideCommand
1259
+ // });
1260
+
1261
+ // If scrolling is inside any of our containers, don't close
1262
+ if (isInsideVectorList || isInsidePopover || isInsideCommand) {
1263
+ return;
1264
+ }
1265
+
1266
+ // If scrolling outside our containers, close dropdowns
1267
+ if ($openDropdowns?.has(controllerId)) {
1268
+ // console.log('🔴 [VectorInput] Closing dropdown due to external scroll');
1269
+ toggleDropdown(controllerId);
1270
+ }
1271
+ }
1272
+ }
1273
+
1274
+ // Add to VectorInputController.svelte
1275
+ $: open = $openDropdowns.has(controllerId) || false;
1276
+
1277
+ // Add after filteredVectors.length > 0 check
1278
+ $: if (filteredVectors.length > 0 && vectorListContainer) {
1279
+ // console.log('📝 [VectorInput] Vectors loaded, setting up observer...');
1280
+ setupVectorObserver();
1281
+ }
1282
+
1283
+ // Add these event handlers
1284
+ function handleButtonClick() {
1285
+ const currentState = $openDropdowns?.has(controllerId);
1286
+ // console.log('🔵 [VectorInput] Button click start:', {
1287
+ // controllerId,
1288
+ // currentState,
1289
+ // openDropdowns: Array.from($openDropdowns || new Set()),
1290
+ // source: 'button'
1291
+ // });
1292
+
1293
+ if (!currentState) {
1294
+ // console.log('🎯 [VectorInput] Triggering focus');
1295
+ onFocus();
1296
+ }
1297
+ // toggleDropdown(controllerId);
1298
+ }
1299
+
1300
+ function handleKeyDown(event: KeyboardEvent) {
1301
+ if (event.key === 'Enter' || event.key === ' ') {
1302
+ event.preventDefault();
1303
+ handleButtonClick();
1304
+ }
1305
+ }
1306
+
1307
+ // Add this function
1308
+ function measureWidth(node: HTMLElement) {
1309
+ const resizeObserver = new ResizeObserver(() => {
1310
+ buttonWidth = node.offsetWidth;
1311
+ });
1312
+
1313
+ resizeObserver.observe(node);
1314
+
1315
+ return {
1316
+ destroy() {
1317
+ resizeObserver.disconnect();
1318
+ }
1319
+ };
1320
+ }
1321
+
1322
+ // Add this reactive statement
1323
+ $: popoverStyle = `width: ${buttonWidth}px`;
1324
+
1325
+ // Update the trash click handler
1326
+ function handleTrashClick(vector: VectorItem, event: MouseEvent) {
1327
+ event.preventDefault();
1328
+ event.stopPropagation();
1329
+ removeVector(vector.name);
1330
+ }
1331
+
1332
+ /**
1333
+ * Svelte action for the list that holds the vector pictures: notices a picture that does not load and shows the
1334
+ * "Failed to load" state for that vector. `error` events do not bubble, so it listens in the capture phase; a
1335
+ * picture is found by its data-vector-name (see renderVectorItem). It replaces an inline onerror attribute that
1336
+ * reported through `document`, which is the partner's page when the editor runs inside one.
1337
+ */
1338
+ function watchVectorImageErrors(node: HTMLElement) {
1339
+ const onImageError = (event: Event) => {
1340
+ const image = event.target;
1341
+ if (!(image instanceof HTMLImageElement)) return;
1342
+ const vectorName = image.dataset.vectorName;
1343
+ if (!vectorName) return;
1344
+ image.style.display = 'none';
1345
+ // Reported once per vector, however many pictures of it are on screen.
1346
+ if (hasSvgLoadError(vectorName)) return;
1347
+ const vectorData = allVectors.find((vector) => vector.name === vectorName);
1348
+ console.error(
1349
+ `❌ [VectorInput] Failed to load SVG: "${vectorName}" from URL: ${vectorData?.url || image.src || 'unknown'}`
1350
+ );
1351
+ svgLoadErrors.set(vectorName, true);
1352
+ // Force component update
1353
+ svgLoadErrors = new Map(svgLoadErrors);
1354
+ };
1355
+
1356
+ node.addEventListener('error', onImageError, true);
1357
+
1358
+ return {
1359
+ destroy() {
1360
+ node.removeEventListener('error', onImageError, true);
1361
+ }
1362
+ };
1363
+ }
1364
+
1365
+ // Create a Svelte action to handle image error events
1366
+ function handleImageError(node: HTMLElement, vectorName: string) {
1367
+ const errorHandler = (event: Event) => {
1368
+ // console.log(`❌ [VectorInput] Image failed to load: ${vectorName}`);
1369
+ svgLoadErrors.set(vectorName, true);
1370
+ svgLoadErrors = new Map(svgLoadErrors);
1371
+
1372
+ if (node instanceof HTMLImageElement) {
1373
+ node.style.display = 'none';
1374
+ }
1375
+ };
1376
+
1377
+ node.addEventListener('error', errorHandler);
1378
+
1379
+ return {
1380
+ destroy() {
1381
+ node.removeEventListener('error', errorHandler);
1382
+ },
1383
+ update(newVectorName: string) {
1384
+ vectorName = newVectorName;
1385
+ }
1386
+ };
1387
+ }
1388
+
1389
+ // Functions for RecentItemsSection and ItemGrid
1390
+ function renderVectorItem(vector: VectorItem) {
1391
+ // If we already know this SVG has a load error, show fallback
1392
+ if (hasSvgLoadError(vector.name)) {
1393
+ return { html: renderSvgFallback() };
1394
+ }
1395
+
1396
+ // The result is used as HTML by RecentItemsSection and ItemGrid: the name and the address of a vector (a custom
1397
+ // one is named after the person's own file) are escaped as they are put in. A picture that does not load is
1398
+ // noticed by watchVectorImageErrors, which finds it by data-vector-name; an inline onerror="..." would not run
1399
+ // under a strict Content-Security-Policy.
1400
+ return {
1401
+ html: `
1380
1402
  <div class="flex items-center justify-center w-full h-full vector-img-container">
1381
1403
  <img
1382
1404
  src="${escapeHtml(vector.url)}"
1383
1405
  alt="${escapeHtml(vector.name)}"
1384
1406
  data-vector-name="${escapeHtml(vector.name)}"
1385
- class="w-[72px] h-[72px] object-contain"
1407
+ class="size-8 object-contain"
1386
1408
  draggable="false"
1387
1409
  />
1388
1410
  </div>
1389
1411
  `
1390
- };
1391
- }
1392
-
1393
- function isVectorSelected(vector: VectorItem) {
1394
- return Boolean(value?.name === vector.name);
1395
- }
1396
-
1397
- function isCustomVector(vector: VectorItem) {
1398
- return vector.category === 'Mine' && Boolean(vector.isCustom);
1399
- }
1400
-
1401
- function getVectorKey(vector: VectorItem) {
1402
- // Create a unique key by combining name with URL or category
1403
- // This prevents duplicate keys when two vectors have the same name
1404
- return vector.url ? `${vector.name}-${vector.url}` : `${vector.name}-${vector.category}`;
1405
- }
1406
-
1407
- function handleVectorDelete(vector: VectorItem, event: Event) {
1408
- // Convert Event to MouseEvent or create a synthetic one if needed
1409
- const mouseEvent = event instanceof MouseEvent
1410
- ? event
1411
- : new MouseEvent('click', {
1412
- bubbles: true,
1413
- cancelable: true,
1414
- view: window
1415
- });
1416
-
1417
- handleTrashClick(vector, mouseEvent);
1418
- }
1419
-
1420
- // Update when vector manager changes
1421
- $: if (vectorManagerInstance) {
1422
- hasMoreVectors = vectorManagerInstance.hasMoreVectors(controllerId, currentFilter);
1423
- }
1424
-
1425
- // Add a handleSearchImmediate function to process search terms immediately without debounce
1426
- async function handleSearchImmediate(value: string) {
1427
- if (!searchTerm && value) {
1428
- // If this is a new search, save current filter
1429
- lastActiveFilter = currentFilter;
1430
- currentFilter = 'All'; // Reset to All when starting a search
1431
- if (browser) {
1432
- writeEditorStorageValue(VECTOR_FILTER_KEY(controllerId), 'All');
1433
- }
1434
- }
1435
-
1436
- // Just load the complete vector list if we're searching
1437
- const completeVectorList = await vectorManagerInstance?.getCompleteVectorList(true) || [];
1438
- allVectors = completeVectorList;
1439
-
1440
- // Apply filtering with the new search term
1441
- updateFilteredVectors();
1442
-
1443
- // Reset scroll position
1444
- if (vectorListContainer) {
1445
- vectorListContainer.scrollTop = 0;
1446
- }
1447
- }
1448
-
1449
- // Update the paste handler to use handleSearchImmediate for immediate processing
1450
- function handlePaste(event: ClipboardEvent) {
1451
- const pastedText = event.clipboardData?.getData('text/plain') || '';
1452
-
1453
- // Don't prevent default - let the paste happen naturally
1454
- // Then trigger an immediate search update with the pasted content
1455
- // searchTerm will be updated through binding
1456
-
1457
- // Schedule the handleSearchImmediate for the next tick to ensure
1458
- // the input value is updated with the pasted content first
1459
- setTimeout(() => {
1460
- handleSearchImmediate(pastedText);
1461
- }, 0);
1462
- }
1463
-
1464
- /**
1465
- * Preloads a batch of vectors to detect loading errors early
1466
- */
1467
- async function preloadVectors(vectors: VectorItem[]) {
1468
- const batchSize = 10;
1469
- const preloadChunks = (chunks: VectorItem[][]) => {
1470
- if (chunks.length === 0) return;
1471
-
1472
- const chunk = chunks.shift()!;
1473
-
1474
- // Process this chunk
1475
- chunk.forEach(vector => {
1476
- const img = new Image();
1477
- img.onload = () => {
1478
- // Successfully loaded
1479
- };
1480
- img.onerror = () => {
1481
- console.error(`❌ [VectorInput] Preload failed for vector: "${vector.name}" URL: ${vector.url}`);
1482
- svgLoadErrors.set(vector.name, true);
1483
- svgLoadErrors = new Map(svgLoadErrors);
1484
- };
1485
- img.src = vector.url;
1486
- });
1487
-
1488
- // Process next chunk after a small delay
1489
- if (chunks.length > 0) {
1490
- setTimeout(() => preloadChunks(chunks), 100);
1491
- }
1492
- };
1493
-
1494
- // Split vectors into batches to avoid overwhelming the browser
1495
- const chunks: VectorItem[][] = [];
1496
- for (let i = 0; i < vectors.length; i += batchSize) {
1497
- chunks.push(vectors.slice(i, i + batchSize));
1498
- }
1499
-
1500
- // Start preloading
1501
- preloadChunks(chunks);
1502
- }
1412
+ };
1413
+ }
1414
+
1415
+ function isVectorSelected(vector: VectorItem) {
1416
+ return Boolean(value?.name === vector.name);
1417
+ }
1418
+
1419
+ function isCustomVector(vector: VectorItem) {
1420
+ return vector.category === 'Mine' && Boolean(vector.isCustom);
1421
+ }
1422
+
1423
+ function getVectorKey(vector: VectorItem) {
1424
+ // Create a unique key by combining name with URL or category
1425
+ // This prevents duplicate keys when two vectors have the same name
1426
+ return vector.url ? `${vector.name}-${vector.url}` : `${vector.name}-${vector.category}`;
1427
+ }
1428
+
1429
+ function handleVectorDelete(vector: VectorItem, event: Event) {
1430
+ // Convert Event to MouseEvent or create a synthetic one if needed
1431
+ const mouseEvent =
1432
+ event instanceof MouseEvent
1433
+ ? event
1434
+ : new MouseEvent('click', {
1435
+ bubbles: true,
1436
+ cancelable: true,
1437
+ view: window
1438
+ });
1439
+
1440
+ handleTrashClick(vector, mouseEvent);
1441
+ }
1442
+
1443
+ // Update when vector manager changes
1444
+ $: if (vectorManagerInstance) {
1445
+ hasMoreVectors = vectorManagerInstance.hasMoreVectors(controllerId, currentFilter);
1446
+ }
1447
+
1448
+ // Add a handleSearchImmediate function to process search terms immediately without debounce
1449
+ async function handleSearchImmediate(value: string) {
1450
+ if (!searchTerm && value) {
1451
+ // If this is a new search, save current filter
1452
+ lastActiveFilter = currentFilter;
1453
+ currentFilter = 'All'; // Reset to All when starting a search
1454
+ if (browser) {
1455
+ writeEditorStorageValue(VECTOR_FILTER_KEY(controllerId), 'All');
1456
+ }
1457
+ }
1458
+
1459
+ // Just load the complete vector list if we're searching
1460
+ const completeVectorList = (await vectorManagerInstance?.getCompleteVectorList(true)) || [];
1461
+ allVectors = completeVectorList;
1462
+
1463
+ // Apply filtering with the new search term
1464
+ updateFilteredVectors();
1465
+
1466
+ // Reset scroll position
1467
+ if (vectorListContainer) {
1468
+ vectorListContainer.scrollTop = 0;
1469
+ }
1470
+ }
1471
+
1472
+ // Update the paste handler to use handleSearchImmediate for immediate processing
1473
+ function handlePaste(event: ClipboardEvent) {
1474
+ const pastedText = event.clipboardData?.getData('text/plain') || '';
1475
+
1476
+ // Don't prevent default - let the paste happen naturally
1477
+ // Then trigger an immediate search update with the pasted content
1478
+ // searchTerm will be updated through binding
1479
+
1480
+ // Schedule the handleSearchImmediate for the next tick to ensure
1481
+ // the input value is updated with the pasted content first
1482
+ setTimeout(() => {
1483
+ handleSearchImmediate(pastedText);
1484
+ }, 0);
1485
+ }
1486
+
1487
+ /**
1488
+ * Preloads a batch of vectors to detect loading errors early
1489
+ */
1490
+ async function preloadVectors(vectors: VectorItem[]) {
1491
+ const batchSize = 10;
1492
+ const preloadChunks = (chunks: VectorItem[][]) => {
1493
+ if (chunks.length === 0) return;
1494
+
1495
+ const chunk = chunks.shift()!;
1496
+
1497
+ // Process this chunk
1498
+ chunk.forEach((vector) => {
1499
+ const img = new Image();
1500
+ img.onload = () => {
1501
+ // Successfully loaded
1502
+ };
1503
+ img.onerror = () => {
1504
+ console.error(
1505
+ `❌ [VectorInput] Preload failed for vector: "${vector.name}" URL: ${vector.url}`
1506
+ );
1507
+ svgLoadErrors.set(vector.name, true);
1508
+ svgLoadErrors = new Map(svgLoadErrors);
1509
+ };
1510
+ img.src = vector.url;
1511
+ });
1512
+
1513
+ // Process next chunk after a small delay
1514
+ if (chunks.length > 0) {
1515
+ setTimeout(() => preloadChunks(chunks), 100);
1516
+ }
1517
+ };
1518
+
1519
+ // Split vectors into batches to avoid overwhelming the browser
1520
+ const chunks: VectorItem[][] = [];
1521
+ for (let i = 0; i < vectors.length; i += batchSize) {
1522
+ chunks.push(vectors.slice(i, i + batchSize));
1523
+ }
1524
+
1525
+ // Start preloading
1526
+ preloadChunks(chunks);
1527
+ }
1503
1528
  </script>
1504
1529
 
1505
- <div bind:this={controllerElement} class="flex flex-col gap-2 widgetic-colors">
1506
- <div class="flex items-center w-full relative">
1507
- <div class="w-[185px] flex-shrink-0 ms-auto">
1508
- <InputControllerHeader
1509
- label={label}
1510
- helpText={description}
1511
- />
1512
- </div>
1513
-
1514
- <div class="absolute end-0">
1515
- <div
1516
- class="h-[48px] w-[185px] rounded-large border border-grey2 flex items-center bg-grey1 transition-colors duration-200 hover:border-forest-green"
1517
- onfocusin={onFocus}
1518
- >
1519
- <Popover.Root
1520
- open={$openDropdowns?.has(controllerId)}
1521
- onOpenChange={(isOpen) => {
1522
- if (isOpen !== $openDropdowns?.has(controllerId)) {
1523
- if (isOpen) {
1524
- // Check if the selected vector image is valid
1525
- if (value?.name && value.url) {
1526
- // Create a temporary image to test if it loads
1527
- const testImg = new Image();
1528
- testImg.onload = () => {
1529
- // Remove from error list if it was there
1530
- if (hasSvgLoadError(value.name)) {
1531
- svgLoadErrors.delete(value.name);
1532
- svgLoadErrors = new Map(svgLoadErrors);
1533
- // console.log(`✅ [VectorInput] Vector now loads successfully: ${value.name}`);
1534
- }
1535
- };
1536
- testImg.onerror = () => {
1537
- // Mark as error if it fails to load
1538
- if (!hasSvgLoadError(value.name)) {
1539
- svgLoadErrors.set(value.name, true);
1540
- svgLoadErrors = new Map(svgLoadErrors);
1541
- console.error(`❌ [VectorInput] Current vector failed to load: ${value.name}, URL: ${value.url}`);
1542
- }
1543
- };
1544
- testImg.src = value.url;
1545
- }
1546
- } else if (!isOpen && value?.name) {
1547
- vectorUtils.addRecentVector({
1548
- name: value.name,
1549
- category: vectorCategories.normalize(value.category) as VectorItem['category'],
1550
- url: value.url,
1551
- isCustom: vectorManagerInstance?.isCustomVector(value.name) || false
1552
- });
1553
- }
1554
-
1555
- toggleDropdown(controllerId);
1556
- }
1557
- }}
1558
- >
1559
- <Popover.Trigger
1560
- class="w-full h-full flex items-center border-0 bg-transparent hover:bg-transparent focus:bg-transparent ps-3 pe-[16px] group"
1561
- onclick={handleButtonClick}
1562
- onkeydown={handleKeyDown}
1563
- onmouseenter={() => {
1564
- // Preload vectors when hovering over the button
1565
- // This reduces the delay when actually clicking to open
1566
- if (!$openDropdowns?.has(controllerId) && filteredVectors.length === 0 && allVectors.length > 0) {
1567
- updateFilteredVectors();
1568
- // console.log('🔄 [VectorInput] Preloading vectors on hover');
1569
- }
1570
- }}
1571
- aria-expanded={open}
1572
- aria-haspopup="listbox"
1573
- aria-controls={`vector-list-${controllerId}`}
1574
- >
1575
- <div class="flex items-center gap-2 truncate flex-1">
1576
- {#if value?.url}
1577
- {#if hasSvgLoadError(value.name)}
1578
- <div class="w-5 h-5 flex items-center justify-center">
1579
- <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-error">
1580
- <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"></path>
1581
- <path d="M12 9v4"></path>
1582
- <path d="M12 17h.01"></path>
1583
- </svg>
1584
- </div>
1585
- <span class="truncate text-start capitalize subtext text-grey7">
1586
- {value?.name || $t('editor.vector.select')}
1587
- </span>
1588
- {:else}
1589
- <!-- Use a simple img tag with Svelte action for error handling -->
1590
- <img
1591
- src={value.url}
1592
- alt={value.name}
1593
- class="w-5 h-5 object-contain"
1594
- use:handleImageError={value.name}
1595
- />
1596
- <span class="truncate text-start capitalize subtext text-grey7">
1597
- {value?.name || $t('editor.vector.select')}
1598
- </span>
1599
- {/if}
1600
- {:else}
1601
- <span class="truncate text-start subtext text-grey7">
1602
- {$t('editor.vector.select')}
1603
- </span>
1604
- {/if}
1605
- </div>
1606
- <IconCaretDownFilled class="w-5 h-5 shrink-0 text-grey5 group-hover:text-grey7" />
1607
- </Popover.Trigger>
1608
-
1609
- <Popover.Content class="vector-input-popover w-[374px] h-[565px] !p-0 widgetic-colors widgetic-radius rounded-medium modal-shadow border border-grey2">
1610
- <div class="flex flex-col h-full vector-popover-content">
1611
- <!-- Title and upload icon -->
1612
- <div class="relative pt-6 pb-[8px] px-4">
1613
- <div class="h5 text-grey7 widgetic-colors">{$t('editor.vector.title')}</div>
1614
- <button
1615
- type="button"
1616
- class="absolute end-6 top-[26px] bg-transparent border-0 cursor-pointer p-0 rounded-full hover:bg-grey3 transition-all duration-300"
1617
- onclick={() => {
1618
- try {
1619
- openFileBrowser();
1620
- } catch (error) {
1621
- console.error('Error opening file browser:', error);
1622
- }
1623
- }}
1624
- >
1625
- <IconCloudUpload class="w-6 h-6 text-grey7 hover:text-grey7 transition-colors duration-300 widgetic-colors" />
1626
- </button>
1627
- </div>
1628
-
1629
- {#if description}
1630
- <p class="px-4 -mt-2 mb-2 subtext text-grey5">{description}</p>
1631
- {/if}
1632
-
1633
- <!-- Search input -->
1634
- <div class="relative px-4">
1635
- <SearchInput
1636
- placeholder={$t('editor.vector.search')}
1637
- bind:value={searchTerm}
1638
- onInput={(e: Event) => {
1639
- // Use debounced search for better performance
1640
- debouncedSearch(e);
1641
- }}
1642
- onKeydown={handleSearchKeydown}
1643
- onPaste={handlePaste}
1644
- onClear={() => {
1645
- searchTerm = ''; // Reset search term
1646
-
1647
- // Restore the previous filter when clearing search
1648
- currentFilter = lastActiveFilter;
1649
- if (browser) {
1650
- writeEditorStorageValue(VECTOR_FILTER_KEY(controllerId), lastActiveFilter);
1651
- }
1652
-
1653
- // Reset batch index to start fresh
1654
- if (vectorManagerInstance) {
1655
- vectorManagerInstance.resetBatchIndex(controllerId);
1656
-
1657
- // Get vectors for current category
1658
- let vectors: VectorData[] = [];
1659
-
1660
- try {
1661
- if (currentFilter === 'All') {
1662
- // Get standard vectors first - add null check
1663
- const standardVectors = vectorManagerInstance.getCachedVectorList()
1664
- ?.filter(vector => !vector.isCustom)
1665
- ?.slice(0, VectorManager.initialVectorNumber) || [];
1666
-
1667
- // Get custom vectors - add null check
1668
- const customVectors = vectorManagerInstance.getCachedVectorList()
1669
- ?.filter(vector => vector.isCustom) || [];
1670
-
1671
- // Combine them with custom vectors at the end
1672
- vectors = [...standardVectors, ...customVectors];
1673
- } else if (currentFilter === 'Mine') {
1674
- vectors = vectorManagerInstance.getPreloadedVectors(currentFilter as VectorItem['category']);
1675
- } else {
1676
- // For other categories, filter out custom vectors
1677
- vectors = vectorManagerInstance.getPreloadedVectors(currentFilter as VectorItem['category'])
1678
- .filter(vector => !vector.isCustom);
1679
- }
1680
- } catch (error) {
1681
- console.error('❌ [VectorSearch] Error getting cached vectors:', error);
1682
- vectors = [];
1683
- }
1684
-
1685
- // Update all vectors
1686
- allVectors = vectors;
1687
-
1688
- // Update filtered vectors directly to ensure UI updates
1689
- updateFilteredVectors();
1690
- }
1691
-
1692
- // Reset scroll position
1693
- if (vectorListContainer) {
1694
- vectorListContainer.scrollTop = 0;
1695
- }
1696
-
1697
- // Ensure the observer is set up after the DOM updates
1698
- setTimeout(() => {
1699
- setupVectorObserver();
1700
- // console.log('🔄 [VectorSearch] Observer setup after search clear');
1701
- }, 50);
1702
-
1703
- // console.log('🔄 [VectorSearch] Search cleared');
1704
- }}
1705
- />
1706
- </div>
1707
-
1708
- <!-- Filter toggle group - sticky header -->
1709
- {#if !searchTerm}
1710
- <div class="sticky top-0 bg-white z-10">
1711
- <CategoryTabs
1712
- categories={filterOptions}
1713
- activeCategory={currentFilter}
1714
- onCategorySelect={handleFilterChange}
1715
- getCategoryLabel={(category) => categoryLabel(category, $t)}
1716
- filterVisible={!searchTerm}
1717
- />
1718
- </div>
1719
- {/if}
1720
-
1721
- <!-- Scrollable content -->
1722
- <div
1723
- class="flex-1 {filteredVectors.length > 0 ? 'overflow-y-auto' : 'overflow-hidden'} min-h-0 vector-list-container"
1724
- bind:this={vectorListContainer}
1725
- use:watchVectorImageErrors
1726
- onscroll={(e: Event) => {
1727
- e.stopPropagation();
1728
- handleVectorListScroll(e);
1729
- updateScrollState();
1730
- }}
1731
- id={`vector-list-${controllerId}`}
1732
- role="listbox"
1733
- aria-label={$t('editor.vector.list')}
1734
- >
1735
- <div class="space-y-0">
1736
- <!-- Recently used section - only show when not searching -->
1737
- {#if recentVectors.length > 0 && !searchTerm}
1738
- <RecentItemsSection
1739
- recentItems={recentVectors}
1740
- onItemSelect={handleVectorSelect}
1741
- onItemDelete={handleVectorDelete}
1742
- isItemSelected={isVectorSelected}
1743
- renderItem={renderVectorItem}
1744
- isCustomItem={isCustomVector}
1745
- getItemKey={getVectorKey}
1746
- observeItem={observeVector}
1747
- displayMode="grid"
1748
- hideTrashIcon={hideTrashIcon}
1749
- itemType="vector"
1750
- />
1751
- {/if}
1752
-
1753
- <!-- All vectors section -->
1754
- <div class="mt-6 mb-0">
1755
- {#if filteredVectors.length > 0}
1756
- <div id="vector-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">
1757
- <h3 class="subtext text-grey7 px-4 pb-2">
1758
- {searchTerm ? $t('editor.list.searchResults') : $t('editor.list.more')}
1759
- </h3>
1760
- </div>
1761
- {/if}
1762
-
1763
- {#if filteredVectors.length === 0}
1764
- <div class="empty-state-wrapper">
1765
- <EmptyState
1766
- message={searchTerm ? $t('editor.vector.noneFound') : $t('editor.vector.noneAvailable')}
1767
- height="auto"
1768
- />
1769
- </div>
1770
- {:else}
1771
- <ItemGrid
1772
- items={filteredVectors}
1773
- containerRef={(node) => { vectorListContainer = node; }}
1774
- onItemSelect={handleVectorSelect}
1775
- isItemSelected={isVectorSelected}
1776
- renderItem={renderVectorItem}
1777
- getItemKey={getVectorKey}
1778
- observeItem={observeVector}
1779
- loadingMore={loadingMoreVectors}
1780
- hasMoreItems={hasMoreVectors}
1781
- loadNextBatch={() => {
1782
- if (!isLoadingBatch && vectorManagerInstance?.hasMoreVectors(controllerId, currentFilter)) {
1783
- loadNextBatch();
1784
- }
1785
- }}
1786
- layoutClass="grid-cols-3"
1787
- itemType="vector"
1788
- />
1789
- {/if}
1790
- </div>
1791
- </div>
1792
- </div>
1793
- </div>
1794
- </Popover.Content>
1795
- </Popover.Root>
1796
- </div>
1797
- </div>
1798
- </div>
1530
+ <div bind:this={controllerElement} class="vector-ic flex w-full flex-col">
1531
+ <InputControllerRow {label} helpText={description}>
1532
+ <div class="vector-input-ct w-full" onfocusin={onFocus}>
1533
+ <Popover.Root
1534
+ open={$openDropdowns?.has(controllerId)}
1535
+ onOpenChange={(isOpen) => {
1536
+ if (isOpen !== $openDropdowns?.has(controllerId)) {
1537
+ if (isOpen) {
1538
+ // Check if the selected vector image is valid
1539
+ if (value?.name && value.url) {
1540
+ // Create a temporary image to test if it loads
1541
+ const testImg = new Image();
1542
+ testImg.onload = () => {
1543
+ // Remove from error list if it was there
1544
+ if (hasSvgLoadError(value.name)) {
1545
+ svgLoadErrors.delete(value.name);
1546
+ svgLoadErrors = new Map(svgLoadErrors);
1547
+ // console.log(`✅ [VectorInput] Vector now loads successfully: ${value.name}`);
1548
+ }
1549
+ };
1550
+ testImg.onerror = () => {
1551
+ // Mark as error if it fails to load
1552
+ if (!hasSvgLoadError(value.name)) {
1553
+ svgLoadErrors.set(value.name, true);
1554
+ svgLoadErrors = new Map(svgLoadErrors);
1555
+ console.error(
1556
+ `❌ [VectorInput] Current vector failed to load: ${value.name}, URL: ${value.url}`
1557
+ );
1558
+ }
1559
+ };
1560
+ testImg.src = value.url;
1561
+ }
1562
+ } else if (!isOpen && value?.name) {
1563
+ vectorUtils.addRecentVector({
1564
+ name: value.name,
1565
+ category: vectorCategories.normalize(value.category) as VectorItem['category'],
1566
+ url: value.url,
1567
+ isCustom: vectorManagerInstance?.isCustomVector(value.name) || false
1568
+ });
1569
+ }
1570
+
1571
+ toggleDropdown(controllerId);
1572
+ }
1573
+ }}
1574
+ >
1575
+ <Popover.Trigger
1576
+ class="vector-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"
1577
+ onclick={handleButtonClick}
1578
+ onkeydown={handleKeyDown}
1579
+ onmouseenter={() => {
1580
+ if (
1581
+ !$openDropdowns?.has(controllerId) &&
1582
+ filteredVectors.length === 0 &&
1583
+ allVectors.length > 0
1584
+ ) {
1585
+ updateFilteredVectors();
1586
+ }
1587
+ }}
1588
+ aria-expanded={open}
1589
+ aria-haspopup="listbox"
1590
+ aria-controls={`vector-list-${controllerId}`}
1591
+ >
1592
+ <div class="flex min-w-0 flex-1 items-center gap-2 truncate">
1593
+ {#if value?.url}
1594
+ {#if hasSvgLoadError(value.name)}
1595
+ <IconAlertTriangle class="size-4 shrink-0 stroke-[1.333] text-destructive" />
1596
+ <span class="truncate text-start text-body text-foreground">
1597
+ {value?.name || $t('editor.vector.select')}
1598
+ </span>
1599
+ {:else}
1600
+ <img
1601
+ src={value.url}
1602
+ alt={value.name}
1603
+ class="size-5 shrink-0 object-contain"
1604
+ use:handleImageError={value.name}
1605
+ />
1606
+ <span class="truncate text-start text-body text-foreground">
1607
+ {value?.name || $t('editor.vector.select')}
1608
+ </span>
1609
+ {/if}
1610
+ {:else}
1611
+ <span class="truncate text-start text-body text-muted-foreground">
1612
+ {$t('editor.vector.select')}
1613
+ </span>
1614
+ {/if}
1615
+ </div>
1616
+ {#if $openDropdowns?.has(controllerId)}
1617
+ <IconChevronUp class="size-4 shrink-0 stroke-[1.333] text-muted-foreground" />
1618
+ {:else}
1619
+ <IconChevronDown class="size-4 shrink-0 stroke-[1.333] text-muted-foreground" />
1620
+ {/if}
1621
+ </Popover.Trigger>
1622
+
1623
+ <Popover.Content
1624
+ align="end"
1625
+ sideOffset={8}
1626
+ class="vector-input-popover z-50 flex h-[560px] w-picker flex-col overflow-hidden rounded-xl border border-border bg-popover p-0 text-popover-foreground outline-none"
1627
+ >
1628
+ <div class="vector-popover-content flex h-full min-h-0 flex-col">
1629
+ <div class="flex shrink-0 flex-col gap-3 px-4 pt-4 pb-3">
1630
+ <!-- Title and upload icon -->
1631
+ <div class="flex items-center gap-2">
1632
+ <h2 class="min-w-0 flex-1 text-heading-section text-foreground">
1633
+ {$t('editor.vector.title')}
1634
+ </h2>
1635
+ <IconButton
1636
+ variant="ghost"
1637
+ label={$t('editor.file.addFile')}
1638
+ onclick={() => {
1639
+ try {
1640
+ openFileBrowser();
1641
+ } catch (error) {
1642
+ console.error('Error opening file browser:', error);
1643
+ }
1644
+ }}
1645
+ >
1646
+ <IconCloudUpload class="size-4 stroke-[1.333]" />
1647
+ </IconButton>
1648
+ </div>
1649
+ <!-- Search input -->
1650
+ <SearchInput
1651
+ placeholder={$t('editor.vector.search')}
1652
+ bind:value={searchTerm}
1653
+ onInput={(e: Event) => {
1654
+ // Use debounced search for better performance
1655
+ debouncedSearch(e);
1656
+ }}
1657
+ onKeydown={handleSearchKeydown}
1658
+ onPaste={handlePaste}
1659
+ onClear={() => {
1660
+ searchTerm = ''; // Reset search term
1661
+
1662
+ // Restore the previous filter when clearing search
1663
+ currentFilter = lastActiveFilter;
1664
+ if (browser) {
1665
+ writeEditorStorageValue(VECTOR_FILTER_KEY(controllerId), lastActiveFilter);
1666
+ }
1667
+
1668
+ // Reset batch index to start fresh
1669
+ if (vectorManagerInstance) {
1670
+ vectorManagerInstance.resetBatchIndex(controllerId);
1671
+
1672
+ // Get vectors for current category
1673
+ let vectors: VectorData[] = [];
1674
+
1675
+ try {
1676
+ if (currentFilter === 'All') {
1677
+ // Get standard vectors first - add null check
1678
+ const standardVectors =
1679
+ vectorManagerInstance
1680
+ .getCachedVectorList()
1681
+ ?.filter((vector) => !vector.isCustom)
1682
+ ?.slice(0, VectorManager.initialVectorNumber) || [];
1683
+
1684
+ // Get custom vectors - add null check
1685
+ const customVectors =
1686
+ vectorManagerInstance
1687
+ .getCachedVectorList()
1688
+ ?.filter((vector) => vector.isCustom) || [];
1689
+
1690
+ // Combine them with custom vectors at the end
1691
+ vectors = [...standardVectors, ...customVectors];
1692
+ } else if (currentFilter === 'Mine') {
1693
+ vectors = vectorManagerInstance.getPreloadedVectors(
1694
+ currentFilter as VectorItem['category']
1695
+ );
1696
+ } else {
1697
+ // For other categories, filter out custom vectors
1698
+ vectors = vectorManagerInstance
1699
+ .getPreloadedVectors(currentFilter as VectorItem['category'])
1700
+ .filter((vector) => !vector.isCustom);
1701
+ }
1702
+ } catch (error) {
1703
+ console.error('❌ [VectorSearch] Error getting cached vectors:', error);
1704
+ vectors = [];
1705
+ }
1706
+
1707
+ // Update all vectors
1708
+ allVectors = vectors;
1709
+
1710
+ // Update filtered vectors directly to ensure UI updates
1711
+ updateFilteredVectors();
1712
+ }
1713
+
1714
+ // Reset scroll position
1715
+ if (vectorListContainer) {
1716
+ vectorListContainer.scrollTop = 0;
1717
+ }
1718
+
1719
+ // Ensure the observer is set up after the DOM updates
1720
+ setTimeout(() => {
1721
+ setupVectorObserver();
1722
+ // console.log('🔄 [VectorSearch] Observer setup after search clear');
1723
+ }, 50);
1724
+
1725
+ // console.log('🔄 [VectorSearch] Search cleared');
1726
+ }}
1727
+ />
1728
+ </div>
1729
+
1730
+ {#if !searchTerm}
1731
+ <div class="sticky top-0 z-10 bg-popover">
1732
+ <CategoryTabs
1733
+ categories={filterOptions}
1734
+ activeCategory={currentFilter}
1735
+ onCategorySelect={handleFilterChange}
1736
+ getCategoryLabel={(category) => categoryLabel(category, $t)}
1737
+ filterVisible={!searchTerm}
1738
+ />
1739
+ </div>
1740
+ {/if}
1741
+
1742
+ <!-- Scrollable content -->
1743
+ <div
1744
+ class="flex-1 {filteredVectors.length > 0
1745
+ ? 'overflow-y-auto'
1746
+ : 'overflow-hidden'} min-h-0 vector-list-container"
1747
+ bind:this={vectorListContainer}
1748
+ use:watchVectorImageErrors
1749
+ onscroll={(e: Event) => {
1750
+ e.stopPropagation();
1751
+ handleVectorListScroll(e);
1752
+ updateScrollState();
1753
+ }}
1754
+ id={`vector-list-${controllerId}`}
1755
+ role="listbox"
1756
+ aria-label={$t('editor.vector.list')}
1757
+ >
1758
+ <div class="space-y-0">
1759
+ <!-- Recently used section - only show when not searching -->
1760
+ {#if recentVectors.length > 0 && !searchTerm}
1761
+ <RecentItemsSection
1762
+ recentItems={recentVectors}
1763
+ onItemSelect={handleVectorSelect}
1764
+ onItemDelete={handleVectorDelete}
1765
+ isItemSelected={isVectorSelected}
1766
+ renderItem={renderVectorItem}
1767
+ isCustomItem={isCustomVector}
1768
+ getItemKey={getVectorKey}
1769
+ observeItem={observeVector}
1770
+ displayMode="grid"
1771
+ {hideTrashIcon}
1772
+ itemType="vector"
1773
+ />
1774
+ {/if}
1775
+
1776
+ <!-- All vectors section -->
1777
+ <div class="mb-0 mt-4">
1778
+ {#if filteredVectors.length > 0}
1779
+ <div
1780
+ id="vector-header-{controllerId}"
1781
+ class="sticky top-0 z-10 -mt-2 bg-popover px-4 pt-2 {isScrolled
1782
+ ? 'border-b border-border transition-border'
1783
+ : 'border-b border-transparent'}"
1784
+ >
1785
+ <h3 class="pb-2 text-caption-medium text-muted-foreground">
1786
+ {searchTerm ? $t('editor.list.searchResults') : $t('editor.list.more')}
1787
+ </h3>
1788
+ </div>
1789
+ {/if}
1790
+
1791
+ {#if filteredVectors.length === 0}
1792
+ <div class="empty-state-wrapper">
1793
+ <EmptyState
1794
+ message={searchTerm
1795
+ ? $t('editor.vector.noneFound')
1796
+ : $t('editor.vector.noneAvailable')}
1797
+ height="auto"
1798
+ />
1799
+ </div>
1800
+ {:else}
1801
+ <ItemGrid
1802
+ items={filteredVectors}
1803
+ containerRef={(node) => {
1804
+ vectorListContainer = node;
1805
+ }}
1806
+ onItemSelect={handleVectorSelect}
1807
+ isItemSelected={isVectorSelected}
1808
+ renderItem={renderVectorItem}
1809
+ getItemKey={getVectorKey}
1810
+ observeItem={observeVector}
1811
+ loadingMore={loadingMoreVectors}
1812
+ hasMoreItems={hasMoreVectors}
1813
+ loadNextBatch={() => {
1814
+ if (
1815
+ !isLoadingBatch &&
1816
+ vectorManagerInstance?.hasMoreVectors(controllerId, currentFilter)
1817
+ ) {
1818
+ loadNextBatch();
1819
+ }
1820
+ }}
1821
+ layoutClass="grid-cols-6"
1822
+ itemType="vector"
1823
+ />
1824
+ {/if}
1825
+ </div>
1826
+ </div>
1827
+ </div>
1828
+ </div>
1829
+ </Popover.Content>
1830
+ </Popover.Root>
1831
+ </div>
1832
+ </InputControllerRow>
1799
1833
  </div>
1800
1834
 
1801
1835
  <style>
1802
- /* Update button styles */
1803
- :global(button.bg-transparent) {
1804
- background: transparent !important;
1805
- border: none !important;
1806
- }
1807
-
1808
- :global(button.bg-transparent:hover),
1809
- :global(button.bg-transparent:focus) {
1810
- background-color: transparent !important;
1811
- }
1812
-
1813
- /* Add transition only for border appearance */
1814
- :global(.transition-border) {
1815
- transition: border-color 0.2s ease-in-out;
1816
- }
1817
-
1818
- /* Keep scrollbar styles */
1819
- :global(.overflow-y-auto) {
1820
- -webkit-overflow-scrolling: touch;
1821
- scrollbar-width: thin;
1822
- scrollbar-color: hsl(var(--grey3)) transparent;
1823
- }
1824
-
1825
- /* Target specific elements */
1826
- :global(.vector-input-wrapper:hover ~ .vector-input-wrapper .group-hover\\:underline) {
1827
- text-decoration: none;
1828
- }
1829
-
1830
- :global(.vector-input-wrapper:hover ~ .vector-input-wrapper) {
1831
- pointer-events: none;
1832
- }
1833
-
1834
- /* Custom styling for vector items in grid - moved to RecentItemsSection.svelte */
1835
-
1836
- /* Ensure vector list container properly handles scroll events */
1837
- :global(.vector-list-container) {
1838
- -webkit-overflow-scrolling: touch;
1839
- scrollbar-width: thin;
1840
- scrollbar-color: hsl(var(--grey3)) transparent;
1841
- will-change: transform;
1842
- transform: translateZ(0);
1843
- backface-visibility: hidden;
1844
- }
1845
-
1846
- /* Ensure popover content stays open during scrolling */
1847
- :global(.vector-input-popover) {
1848
- z-index: 50;
1849
- will-change: transform;
1850
- transform: translateZ(0);
1851
- backface-visibility: hidden;
1852
- }
1853
-
1854
- /* Optimize vector popover content rendering */
1855
- :global(.vector-popover-content) {
1856
- will-change: transform;
1857
- transform: translateZ(0);
1858
- backface-visibility: hidden;
1859
- }
1860
-
1861
- /* Prevent scrolling when showing empty state */
1862
- .empty-state-wrapper {
1863
- position: absolute;
1864
- top: 0;
1865
- left: 0;
1866
- right: 0;
1867
- bottom: 0;
1868
- display: flex;
1869
- align-items: center;
1870
- justify-content: center;
1871
- overflow: hidden;
1872
- padding-top: 60px; /* Add padding to account for the header */
1873
- padding-bottom: 60px; /* Balance the padding */
1874
- }
1836
+ :global(.transition-border) {
1837
+ transition: border-color 0.2s ease-in-out;
1838
+ }
1839
+
1840
+ :global(.vector-list-container) {
1841
+ -webkit-overflow-scrolling: touch;
1842
+ scrollbar-width: thin;
1843
+ scrollbar-color: var(--border) transparent;
1844
+ will-change: transform;
1845
+ transform: translateZ(0);
1846
+ backface-visibility: hidden;
1847
+ }
1848
+
1849
+ /* Ensure popover content stays open during scrolling */
1850
+ :global(.vector-input-popover) {
1851
+ z-index: 100000000;
1852
+ will-change: transform;
1853
+ transform: translateZ(0);
1854
+ backface-visibility: hidden;
1855
+ }
1856
+
1857
+ /* Optimize vector popover content rendering */
1858
+ :global(.vector-popover-content) {
1859
+ will-change: transform;
1860
+ transform: translateZ(0);
1861
+ backface-visibility: hidden;
1862
+ }
1863
+
1864
+ /* Prevent scrolling when showing empty state */
1865
+ .empty-state-wrapper {
1866
+ position: absolute;
1867
+ top: 0;
1868
+ left: 0;
1869
+ right: 0;
1870
+ bottom: 0;
1871
+ display: flex;
1872
+ align-items: center;
1873
+ justify-content: center;
1874
+ overflow: hidden;
1875
+ padding-top: 60px; /* Add padding to account for the header */
1876
+ padding-bottom: 60px; /* Balance the padding */
1877
+ }
1875
1878
  </style>
1876
-