@widgetic/editor 4.1.14 → 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 (76) hide show
  1. package/dist/components/PreviewChromeControls.svelte +15 -21
  2. package/dist/components/WidgetPreview.svelte +136 -105
  3. package/dist/components/color-select/ColorSelect.svelte +203 -224
  4. package/dist/components/color-select/constants.d.ts +4 -2
  5. package/dist/components/color-select/constants.js +4 -2
  6. package/dist/components/color-select/render.js +10 -9
  7. package/dist/components/editors/CompositionEditorApp.svelte +47 -40
  8. package/dist/components/editors/EditLeaseNotice.svelte +44 -33
  9. package/dist/components/editors/EmbedEditor.svelte +133 -259
  10. package/dist/components/editors/PropsEditor.svelte +418 -1338
  11. package/dist/components/editors/props-editor.css +5 -68
  12. package/dist/components/ic/AngleInputController.svelte +202 -277
  13. package/dist/components/ic/BrowserInputController.svelte +813 -803
  14. package/dist/components/ic/CheckboxInputController.svelte +92 -169
  15. package/dist/components/ic/CheckboxInputController.svelte.d.ts +2 -8
  16. package/dist/components/ic/ColorPickerInputController.svelte +1589 -1587
  17. package/dist/components/ic/ColorPickerInputController.svelte.d.ts +3 -3
  18. package/dist/components/ic/DateFieldInputController.svelte +455 -465
  19. package/dist/components/ic/DatePickerInputController.svelte +355 -368
  20. package/dist/components/ic/DatePickerInputController.svelte.d.ts +1 -1
  21. package/dist/components/ic/DropdownInputController.svelte +130 -200
  22. package/dist/components/ic/FixedPositionInputController.svelte +255 -276
  23. package/dist/components/ic/FixedPositionInputController.svelte.d.ts +5 -1
  24. package/dist/components/ic/FontInputController.svelte +2110 -2231
  25. package/dist/components/ic/FontInputController.svelte.d.ts +11 -11
  26. package/dist/components/ic/InputControllerHeader.svelte +141 -147
  27. package/dist/components/ic/InputControllerRow.svelte +74 -0
  28. package/dist/components/ic/InputControllerRow.svelte.d.ts +14 -0
  29. package/dist/components/ic/KnowledgeDocumentsInputController.svelte +84 -47
  30. package/dist/components/ic/KnowledgeTextForm.svelte +35 -33
  31. package/dist/components/ic/NumberControls.svelte +303 -269
  32. package/dist/components/ic/NumberControls.svelte.d.ts +4 -1
  33. package/dist/components/ic/NumberInputController.svelte +361 -301
  34. package/dist/components/ic/NumberInputController.svelte.d.ts +2 -0
  35. package/dist/components/ic/PositionInputController.svelte +253 -176
  36. package/dist/components/ic/PositionInputController.svelte.d.ts +2 -0
  37. package/dist/components/ic/RadioGroupInputController.svelte +71 -137
  38. package/dist/components/ic/RadioGroupInputController.svelte.d.ts +2 -8
  39. package/dist/components/ic/RangeCalendarInputController.svelte +233 -270
  40. package/dist/components/ic/RangeCalendarInputController.svelte.d.ts +2 -2
  41. package/dist/components/ic/RoundedCornersInputController.svelte +412 -435
  42. package/dist/components/ic/RoundedCornersInputController.svelte.d.ts +2 -0
  43. package/dist/components/ic/SliderInputController.svelte +263 -332
  44. package/dist/components/ic/SliderInputController.svelte.d.ts +1 -1
  45. package/dist/components/ic/SliderRangeInputController.svelte +140 -144
  46. package/dist/components/ic/SliderRangeInputController.svelte.d.ts +3 -3
  47. package/dist/components/ic/SwitchInputController.svelte +47 -109
  48. package/dist/components/ic/TagsInputController.svelte +95 -110
  49. package/dist/components/ic/TextAreaInputController.svelte +1794 -1935
  50. package/dist/components/ic/TextAreaPreviewInputController.svelte +436 -438
  51. package/dist/components/ic/TextAreaPreviewInputController.svelte.d.ts +2 -2
  52. package/dist/components/ic/TextInputController.svelte +65 -75
  53. package/dist/components/ic/TextInputController.svelte.d.ts +2 -0
  54. package/dist/components/ic/TimeInputController.svelte +433 -431
  55. package/dist/components/ic/VectorInputController.svelte +1833 -1831
  56. package/dist/components/ic/VectorInputController.svelte.d.ts +10 -10
  57. package/dist/components/ic/index.d.ts +1 -0
  58. package/dist/components/ic/index.js +1 -0
  59. package/dist/components/ic/shared/CategoryTabs.svelte +28 -35
  60. package/dist/components/ic/shared/ItemGrid.svelte +145 -179
  61. package/dist/components/ic/shared/RecentItemsSection.svelte +208 -271
  62. package/dist/components/ic/shared/RecentItemsSection.svelte.d.ts +1 -1
  63. package/dist/components/ui/arrows/OpacitySliderArrows.svelte +23 -38
  64. package/dist/components/ui/arrows/OpacitySliderArrows.svelte.d.ts +1 -4
  65. package/dist/components/ui/calendar-editor-fit/EditorCalendarStyles.svelte +45 -0
  66. package/dist/components/ui/calendar-editor-fit/EditorCalendarStyles.svelte.d.ts +26 -0
  67. package/dist/components/ui/checkerboard-background/CheckerboardBackground.svelte +20 -12
  68. package/dist/components/ui/shadow-picker-host/ShadowPickerHost.svelte +39 -0
  69. package/dist/components/ui/shadow-picker-host/ShadowPickerHost.svelte.d.ts +10 -0
  70. package/dist/i18n/language.d.ts +43 -36
  71. package/dist/i18n/messages.d.ts +41 -34
  72. package/dist/i18n/messages.js +47 -34
  73. package/dist/i18n/translate.d.ts +1 -1
  74. package/dist/utils.d.ts +7 -0
  75. package/dist/utils.js +26 -2
  76. package/package.json +4 -4
@@ -19,1315 +19,1343 @@
19
19
  -->
20
20
 
21
21
  <script module lang="ts">
22
- import type { InputControllerConfig } from './index';
23
-
24
- /** Declared props contract — export lets below are annotated from it so the
25
- * interface cannot drift from what the component actually reads. */
26
- export interface ColorPickerInputControllerProps {
27
- label?: string;
28
- value?: string;
29
- onChange: (newValue: string) => void;
30
- controllerId?: string;
31
- id?: string;
32
- config?: InputControllerConfig;
33
- helpText?: string;
34
- saveRecentColors?: boolean;
35
- showOpacityControls?: boolean;
36
- autofocus?: boolean;
37
- portalTarget?: string | HTMLElement;
38
- pickerSize?: number;
39
- sliderWidth?: number;
40
- opacity?: number;
41
- showRing?: boolean;
42
- onFocus?: () => void;
43
- onOpacityChange?: (opacity: number) => void;
44
- }
22
+ import type { InputControllerConfig } from './index';
23
+
24
+ /** Declared props contract — export lets below are annotated from it so the
25
+ * interface cannot drift from what the component actually reads. */
26
+ export interface ColorPickerInputControllerProps {
27
+ label?: string;
28
+ value?: string;
29
+ onChange: (newValue: string) => void;
30
+ controllerId?: string;
31
+ id?: string;
32
+ config?: InputControllerConfig;
33
+ helpText?: string;
34
+ saveRecentColors?: boolean;
35
+ showOpacityControls?: boolean;
36
+ autofocus?: boolean;
37
+ portalTarget?: string | HTMLElement;
38
+ pickerSize?: number;
39
+ sliderWidth?: number;
40
+ opacity?: number;
41
+ showRing?: boolean;
42
+ onFocus?: () => void;
43
+ onOpacityChange?: (opacity: number) => void;
44
+ }
45
45
  </script>
46
46
 
47
47
  <script lang="ts">
48
- // Svelte imports
49
- import { onMount, onDestroy, tick } from 'svelte';
50
- import { createEventDispatcher } from 'svelte';
51
- const dispatch = createEventDispatcher();
52
-
53
-
54
- // Shadcn UI Components
55
- import { Input } from '@widgetic/design-system/components';
56
- import { InputControllerHeader } from './index';
57
-
58
- // Icons from Widgetic Design System
59
- import { CheckerBoardBackground, OpacitySliderArrows } from '@widgetic/design-system/icons';
60
-
61
- // Third party imports
62
- import { Portal } from '@widgetic/design-system/components';
63
- // Remove ColorSelect import from dependencies, use local forked version only
64
- // import ColorSelect from 'svelte-color-select';
65
- import ColorSelect from '../color-select/ColorSelect.svelte';
66
-
67
- // Utils imports
68
- import { ColorTransparencyHandler, type RGB } from '../../utils/colorTransparency';
69
- import { colorNames } from '../../utils/colorNames';
70
- import { getColorSuggestions, getNextSuggestion, type AutocompleteResult } from '../../utils/colorAutocomplete';
71
- import { recentColorsUtil } from '../../utils/recentColors';
72
- import { listenForScroll, lockPointerStyle } from '../../utils/shadowDom';
73
- import { useEditorLanguage } from '../../i18n/language';
74
- import { useTextDirection } from '@widgetic/design-system/components/textDirection';
75
-
76
- // The words of the editor in the language of the page.
77
- const { t } = useEditorLanguage();
78
-
79
- // The way the screen is read: the pop-up opens from the end of the field, which is its left edge on a right to left screen.
80
- const textDirection = useTextDirection();
81
-
82
-
83
-
84
- /**
85
- * State Management
86
- * Core state variables controlling component behavior and UI
87
- * Handles keyboard modifiers, visibility states, and color history
88
- */
89
- let isShiftPressed = false;
90
- let isSpacePressed = false;
91
- let showNoRecentMessage = false;
92
- let recentColors = recentColorsUtil.getRecentColors();
93
-
94
- /**
95
- * Component Props
96
- * External properties that configure the color picker's behavior
97
- */
98
- export let label: ColorPickerInputControllerProps['label'] = ''; // Display label
99
- export let value: ColorPickerInputControllerProps['value'] = '#000000'; // Current color value
100
- export let onChange: ColorPickerInputControllerProps['onChange']; // Value change callback
101
- export let controllerId: ColorPickerInputControllerProps['controllerId'] = '';
102
- export let id: ColorPickerInputControllerProps['id'] = '';
103
- // Passed through the dynamic-component props object but never read here —
104
- // export const keeps the init-set contract without the unused-reactive warning.
105
- export const openDropdowns: any = undefined;
106
- export const toggleDropdown: (id: string) => void = () => {};
107
- export let config: ColorPickerInputControllerProps['config'] = {}; // Additional configuration
108
- export let helpText: ColorPickerInputControllerProps['helpText'] = undefined; // Help text for the input
109
-
110
- // Use config values with fallbacks
111
- export let saveRecentColors: ColorPickerInputControllerProps['saveRecentColors'] = true;
112
- export let showOpacityControls: ColorPickerInputControllerProps['showOpacityControls'] = true;
113
- export let autofocus: ColorPickerInputControllerProps['autofocus'] = false;
114
- export let portalTarget: ColorPickerInputControllerProps['portalTarget'] = 'editor-portal';
115
-
116
- // Sizing props for easy adjustment (can be overridden by parent)
117
- export let pickerSize: ColorPickerInputControllerProps['pickerSize'] = 200; // width/height of color area
118
- export let sliderWidth: ColorPickerInputControllerProps['sliderWidth'] = 24; // width of hue bar and opacity input
119
- $: swatchGap = 4;
120
- $: swatchCount = 5;
121
- $: swatchAreaWidth = pickerSize + sliderWidth + 14;
122
- $: swatchSize = Math.floor((swatchAreaWidth - (swatchCount - 1) * swatchGap) / swatchCount);
123
-
124
- // Exported opacity with default handling
125
- export let opacity: ColorPickerInputControllerProps['opacity'] = config.defaultTransparency !== undefined ? config.defaultTransparency / 100 : 1;
126
-
127
- // Tracks the last known opacity to maintain consistency
128
- let lastKnownOpacity = opacity;
129
-
130
- // Reactive statement to keep lastKnownOpacity in sync with opacity changes
131
- $: lastKnownOpacity = opacity;
132
-
133
- // Initialize the transparency handler with the current opacity
134
- const transparencyHandler = new ColorTransparencyHandler(lastKnownOpacity);
135
-
136
- /**
137
- * Color State
138
- * Maintains synchronized state between different color representations
139
- * Uses isInternalUpdate flag to prevent recursive updates during state changes
140
- */
141
- let rgb = { r: 0, g: 0, b: 0, a: lastKnownOpacity };
142
- let opacityValue = lastKnownOpacity;
143
- let opacityPercentage = Math.round(lastKnownOpacity * 100);
144
-
145
- // Unique instance ID for this color picker (use controllerId, id, or generate one)
146
- const instanceId = controllerId || id || `cpicker-${Math.random().toString(36).slice(2, 8)}`;
147
-
148
- // Local open state — not derived from store
149
- let open = false;
150
-
151
- // Listen for "close all color pickers except me" events from other instances
152
- function onCloseOtherPickers(e: CustomEvent<string>) {
153
- if (e.detail !== instanceId && open) {
154
- open = false;
155
- saveToRecentColors(value, lastKnownOpacity);
156
- if (isColorSelectOpen) {
157
- dispatch('colorselectmodalclose');
158
- isColorSelectOpen = false;
159
- }
160
- }
161
- }
162
-
163
- let opacitySliderRef: HTMLDivElement;
164
- let isDragging = false;
165
- let isHueDragging = false;
166
-
167
- let hexInput: string = value;
168
- let previewColor: string = value;
169
- let persistentOpacity: number = 1;
170
-
171
- let isInternalUpdate = false;
172
-
173
- // Tracks the position of the opacity indicator for visual feedback
174
- $: indicatorLeft = `calc(${lastKnownOpacity * 100}% - ${parseInt(opacityLineWidth) / 2}px)`;
175
-
176
- // Opacity bar dimensions for slider calculations
177
- const opacityBarWidth = "257px";
178
- const opacityBarHeight = "33px";
179
-
180
- // Opacity line aesthetics and dimensions
181
- const opacityLineStrokeColor = "rgb(0, 0, 0)";
182
- const opacityLineStrokeOpacity = 0.1;
183
- const opacityLineWidth = "2px";
184
- const opacityLineColor = "rgba(255, 255, 255, 0)";
185
-
186
- // Add to props section
187
- export let showRing: ColorPickerInputControllerProps['showRing'] = true;
188
-
189
- /**
190
- * Generates RGBA border string based on color and opacity
191
- * @param color - Base color in RGB format
192
- * @param opacity - Opacity value to apply
193
- * @returns CSS border string with RGBA color
194
- */
195
- const getRGBABorder = (color: string, opacity: number) => {
196
- return `1px solid ${color.replace('rgb', 'rgba').replace(')', `, ${opacity})`)}`;
197
- };
198
-
199
- /**
200
- * Converts hex color to RGBA while preserving opacity
201
- * Handles both 3 and 6 character hex codes
202
- * Returns normalized RGB values (0-1 range)
203
- * @param hex - Hexadecimal color string
204
- * @returns RGB object with normalized values
205
- */
206
- function hexToRgba(hex: string): RGB {
207
- // Remove hash and handle both 3 and 6 character hex
208
- const digits = hex.replace('#', '');
209
- let r, g, b;
210
-
211
- if (digits.length === 3) {
212
- // For 3-character hex, duplicate each character
213
- r = parseInt(digits[0] + digits[0], 16) / 255;
214
- g = parseInt(digits[1] + digits[1], 16) / 255;
215
- b = parseInt(digits[2] + digits[2], 16) / 255;
216
- } else {
217
- // For 6-character hex
218
- r = parseInt(digits.slice(0, 2), 16) / 255;
219
- g = parseInt(digits.slice(2, 4), 16) / 255;
220
- b = parseInt(digits.slice(4, 6), 16) / 255;
221
- }
222
-
223
- return {
224
- r,
225
- g,
226
- b,
227
- a: lastKnownOpacity
228
- };
229
- }
230
-
231
- /**
232
- * Converts RGB values to hex format
233
- * Delegates to transparency handler for consistent color conversion
234
- * Preserves alpha channel information
235
- * @param r - Red component (0-1)
236
- * @param g - Green component (0-1)
237
- * @param b - Blue component (0-1)
238
- * @param a - Alpha component (0-1)
239
- * @returns Hexadecimal color string
240
- */
241
- function rgbaToHex(r: number, g: number, b: number, a: number): string {
242
- return transparencyHandler.rgbaToHex(r, g, b, a);
243
- }
244
-
245
- // Reactive statement to synchronize value changes with internal state
246
- $: {
247
- if (value !== hexInput) {
248
- const newRgb = hexToRgba(value);
249
- rgb = newRgb; // The handler will preserve the opacity
250
- hexInput = value;
251
- previewColor = value;
252
- }
253
- }
254
-
255
- /**
256
- * Updates color state and triggers change events
257
- * - Validates hex format
258
- * - Updates preview color
259
- * - Triggers onChange callback only for valid hex values
260
- * - Maintains 6-digit hex format
261
- * @param newColor - New hex color value
262
- */
263
- function updateColor(newColor: string) {
264
- previewColor = newColor;
265
- if (/^#[0-9A-Fa-f]{6,8}$/.test(newColor)) {
266
- value = newColor;
267
- onChange(newColor);
268
- }
269
- }
270
-
271
- /**
272
- * Handles color changes from the color picker
273
- * - Updates hex value while preserving opacity
274
- * - Prevents recursive updates with isInternalUpdate flag
275
- * - Maintains consistent state across all color representations
276
- * - Triggers onChange with clean hex value
277
- */
278
- function handleColorChange(eventOrDetail?: CustomEvent | Record<string, any>) {
279
- try {
280
- isInternalUpdate = true;
281
- const detail = eventOrDetail instanceof CustomEvent ? eventOrDetail.detail : eventOrDetail;
282
- if (detail && detail.rgb) {
283
- rgb = detail.rgb;
284
- if (typeof detail.a === 'number') {
285
- lastKnownOpacity = detail.a;
286
- }
287
- }
288
- // Only use the 6-character hex without alpha
289
- const hexValue = `#${Math.round(rgb.r * 255).toString(16).padStart(2, '0')}${Math.round(rgb.g * 255).toString(16).padStart(2, '0')}${Math.round(rgb.b * 255).toString(16).padStart(2, '0')}`;
290
- value = hexValue;
291
- hexInput = hexValue;
292
- previewColor = getRgbaColor();
293
- onChange(hexValue);
294
- } finally {
295
- isInternalUpdate = false;
296
- }
297
- }
298
-
299
- /**
300
- * Normalizes hex color input
301
- * - Handles color names conversion
302
- * - Validates hex characters
303
- * - Supports both 3 and 6 character formats
304
- * - Returns standardized hex format
305
- * @param input - User input string
306
- * @returns Normalized hex color string
307
- */
308
- function normalizeHexInput(input: string): string {
309
- // Remove hash if present and convert to lowercase
310
- let color = input.toLowerCase().replace('#', '');
311
-
312
- // Check if it's a color name
313
- if (colorNames[color]) {
314
- return colorNames[color];
315
- }
316
-
317
- // Only validate the characters, don't expand
318
- if (!/^[0-9a-f]*$/i.test(color)) {
319
- return value; // Return current value if invalid characters
320
- }
321
-
322
- // Return the current input with # prefix
323
- return '#' + color;
324
- }
325
-
326
- /**
327
- * Validates if a string is a valid hex color
328
- * @param hex - Hexadecimal color string
329
- * @returns Boolean indicating validity
330
- */
331
- function isValidHex(hex: string): boolean {
332
- const digits = hex.replace('#', '');
333
- return (digits.length === 3 || digits.length === 6) && /^[0-9a-f]+$/i.test(digits);
334
- }
335
-
336
- let currentSuggestion: AutocompleteResult | null = null;
337
- let suggestionVisible = false;
338
-
339
- /**
340
- * Handles input events for hex input field
341
- * - Processes valid hex inputs
342
- * - Manages color name suggestions
343
- * @param event - Input event from the text field
344
- */
345
- function handleHexInput(event: Event) {
346
- const input = event.target as HTMLInputElement;
347
- let newValue = input.value.toLowerCase();
348
-
349
- // validate the new value
350
- if (newValue.startsWith('#') || /^[0-9a-f]+$/i.test(newValue)) {
351
- // if the value starts with #, keep it, otherwise add it
352
- const processedValue = newValue.startsWith('#') ? newValue : `#${newValue}`;
353
-
354
- // console.log('handleHexInput processedValue:', processedValue);
355
-
356
- // if new value is a hex color(starts with # and has 3 or 6 characters): call the onChange callback
357
- const hexRegex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
358
- if (hexRegex.test(processedValue)) {
359
- // console.log('Valid hex color detected:', processedValue);
360
- try {
361
- // set the internal update flag to true
362
- isInternalUpdate = true;
363
-
364
- // update the component's value
365
- value = processedValue;
366
-
367
- // update the rgb value
368
- const newRgb = hexToRgba(processedValue);
369
- rgb = { ...newRgb, a: lastKnownOpacity };
370
-
371
- // update the preview color
372
- previewColor = getRgbaColor();
373
-
374
- // call the onChange callback
375
- onChange(processedValue);
376
- } finally {
377
- isInternalUpdate = false;
378
- }
379
- return;
380
- }
381
- }
382
-
383
- // console.log('handleHexInput newValue:', !/[^a-z\s]/.test(newValue));
384
-
385
- // if newValue is empty or contains invalid characters, clear the suggestions
386
- if (!newValue || /[^a-z\s]/.test(newValue)) {
387
- // console.log('Clearing suggestions due to invalid input');
388
- suggestionVisible = false;
389
- currentSuggestion = null;
390
- return;
391
- }
392
-
393
- // if newValue is a valid color name, get the suggestions and show them
394
- const suggestions = getColorSuggestions(newValue, colorNames);
395
- // console.log('Color suggestions:', { input: newValue, suggestions });
396
- if (suggestions) {
397
- currentSuggestion = suggestions;
398
- suggestionVisible = true;
399
- } else {
400
- suggestionVisible = false;
401
- currentSuggestion = null;
402
- }
403
- }
404
-
405
- /**
406
- * Handles the selection of a color from suggestions
407
- * @param colorName - Selected color name
408
- * @param isShiftPressed - Indicates if the shift key was held during selection
409
- */
410
- function handleColorSelection(colorName: string, isShiftPressed: boolean) {
411
- // console.log('Handling color selection:', {
412
- // colorName,
413
- // isShiftPressed,
414
- // currentOpacity: lastKnownOpacity
415
- // });
416
-
417
- const colorValue = colorNames[colorName];
418
- value = colorValue;
419
- const newRgb = hexToRgba(colorValue);
420
-
421
- // If Shift is pressed, set opacity to 100%
422
- if (isShiftPressed) {
423
- // console.log('Shift pressed: Setting opacity to 100%');
424
- lastKnownOpacity = 1;
425
- rgb = { ...newRgb, a: 1 };
426
- opacityPercentage = 100;
427
- } else {
428
- // Keep current opacity
429
- rgb = { ...newRgb, a: lastKnownOpacity };
430
- }
431
-
432
- previewColor = getRgbaColor();
433
- onChange(colorValue);
434
- suggestionVisible = false;
435
- currentSuggestion = null;
436
-
437
- // Save to recent colors
438
- saveToRecentColors(colorValue, rgb.a);
439
- }
440
-
441
- /**
442
- * Handles keydown events for keyboard navigation and interactions
443
- * @param event - Keyboard event
444
- */
445
- function handleKeyDown(event: KeyboardEvent) {
446
- const input = event.target as HTMLInputElement;
447
- const currentInputValue = input.value;
448
-
449
- // Only prevent default for special keys when popup is open
450
- if (open && (event.key === 'Shift' || event.key === ' ')) {
451
- event.preventDefault();
452
- return;
453
- }
454
-
455
- // console.log('Key pressed:', {
456
- // key: event.key,
457
- // actualInputValue: currentInputValue,
458
- // boundHexInput: hexInput,
459
- // isEmpty: !currentInputValue.trim(),
460
- // currentValue: value
461
- // });
462
-
463
- if (event.key === 'Escape') {
464
- event.preventDefault();
465
- closeAutosuggestions();
466
- if (!currentInputValue.trim()) {
467
- restoreCurrentColor();
468
- }
469
- return;
470
- }
471
-
472
- if (event.key === 'Enter') {
473
- if (!currentInputValue.trim() || currentInputValue === '#') {
474
- restoreCurrentColor();
475
- return;
476
- }
477
- }
478
-
479
- // if the suggestions are visible, handle the key events to navigate the suggestions
480
- if (suggestionVisible && currentSuggestion) {
481
- if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
482
- event.preventDefault();
483
-
484
- const direction = event.key === 'ArrowDown' ? 'down' : 'up';
485
-
486
- const result = getNextSuggestion(currentSuggestion, direction);
487
- if (result) {
488
- currentSuggestion = result;
489
- }
490
- } else if (event.key === 'Enter') {
491
- event.preventDefault();
492
- handleColorSelection(currentSuggestion.suggestion, event.shiftKey);
493
- }
494
- }
495
- }
496
-
497
- /**
498
- * Handles popover open/close state changes
499
- * - Saves current color when closing
500
- * - Closes autosuggestions if opening
501
- * - Calculates fixed position when opening
502
- */
503
- function handleToggle(isOpen: boolean) {
504
- // console.warn('[ColorPicker] handleToggle called:', { isOpen, currentOpen: open, instanceId, portalTarget });
505
- if (isOpen === open) return;
506
-
507
- if (!isOpen) {
508
- saveToRecentColors(value, lastKnownOpacity);
509
- if (isColorSelectOpen) {
510
- dispatch('colorselectmodalclose');
511
- isColorSelectOpen = false;
512
- }
513
- } else {
514
- // Close all other color pickers before opening this one
515
- window.dispatchEvent(new CustomEvent('widgetic:close-color-pickers', { detail: instanceId }));
516
- closeAutosuggestions();
517
- dispatch('colorselectmodalopen');
518
- isColorSelectOpen = true;
519
- updatePopoverPosition();
520
- // Re-position after portal is mounted and layout stabilizes
521
- tick().then(() => {
522
- requestAnimationFrame(updatePopoverPosition);
523
- });
524
- }
525
-
526
- open = isOpen;
527
- }
528
-
529
- /**
530
- * Closes the color picker dropdown and autosuggestions
531
- */
532
- function closeDropdown() {
533
- if (open) {
534
- handleToggle(false);
535
- }
48
+ // Svelte imports
49
+ import { onMount, onDestroy, tick } from 'svelte';
50
+ import { createEventDispatcher } from 'svelte';
51
+ const dispatch = createEventDispatcher();
52
+
53
+ // Shadcn UI Components
54
+ import { Input } from '@widgetic/design-system/components';
55
+ import InputControllerRow from './InputControllerRow.svelte';
56
+
57
+ // Icons from Widgetic Design System
58
+ import CheckerBoardBackground from '../ui/checkerboard-background/CheckerboardBackground.svelte';
59
+
60
+ // Third party imports
61
+ import { Portal } from '@widgetic/design-system/components';
62
+ // Remove ColorSelect import from dependencies, use local forked version only
63
+ // import ColorSelect from 'svelte-color-select';
64
+ import ColorSelect from '../color-select/ColorSelect.svelte';
65
+
66
+ // Utils imports
67
+ import { ColorTransparencyHandler, type RGB } from '../../utils/colorTransparency';
68
+ import { colorNames } from '../../utils/colorNames';
69
+ import {
70
+ getColorSuggestions,
71
+ getNextSuggestion,
72
+ type AutocompleteResult
73
+ } from '../../utils/colorAutocomplete';
74
+ import { recentColorsUtil } from '../../utils/recentColors';
75
+ import { listenForScroll, lockPointerStyle } from '../../utils/shadowDom';
76
+ import { useEditorLanguage } from '../../i18n/language';
77
+ import { useTextDirection } from '@widgetic/design-system/components/textDirection';
78
+
79
+ // The words of the editor in the language of the page.
80
+ const { t } = useEditorLanguage();
81
+
82
+ // The way the screen is read: the pop-up opens from the end of the field, which is its left edge on a right to left screen.
83
+ const textDirection = useTextDirection();
84
+
85
+ /**
86
+ * State Management
87
+ * Core state variables controlling component behavior and UI
88
+ * Handles keyboard modifiers, visibility states, and color history
89
+ */
90
+ let isShiftPressed = false;
91
+ let isSpacePressed = false;
92
+ let showNoRecentMessage = false;
93
+ let recentColors = recentColorsUtil.getRecentColors();
94
+
95
+ /**
96
+ * Component Props
97
+ * External properties that configure the color picker's behavior
98
+ */
99
+ export let label: ColorPickerInputControllerProps['label'] = ''; // Display label
100
+ export let value: ColorPickerInputControllerProps['value'] = '#000000'; // Current color value
101
+ export let onChange: ColorPickerInputControllerProps['onChange']; // Value change callback
102
+ export let controllerId: ColorPickerInputControllerProps['controllerId'] = '';
103
+ export let id: ColorPickerInputControllerProps['id'] = '';
104
+ // Passed through the dynamic-component props object but never read here —
105
+ // export const keeps the init-set contract without the unused-reactive warning.
106
+ export const openDropdowns: any = undefined;
107
+ export const toggleDropdown: (id: string) => void = () => {};
108
+ export let config: ColorPickerInputControllerProps['config'] = {}; // Additional configuration
109
+ export let helpText: ColorPickerInputControllerProps['helpText'] = undefined; // Help text for the input
110
+
111
+ // Use config values with fallbacks
112
+ export let saveRecentColors: ColorPickerInputControllerProps['saveRecentColors'] = true;
113
+ export let showOpacityControls: ColorPickerInputControllerProps['showOpacityControls'] = true;
114
+ export let autofocus: ColorPickerInputControllerProps['autofocus'] = false;
115
+ export let portalTarget: ColorPickerInputControllerProps['portalTarget'] = 'editor-portal';
116
+
117
+ // Sizing props for easy adjustment (can be overridden by parent)
118
+ export let pickerSize: ColorPickerInputControllerProps['pickerSize'] = 200; // width/height of color area
119
+ export let sliderWidth: ColorPickerInputControllerProps['sliderWidth'] = 24; // width of hue bar and opacity input
120
+ $: swatchGap = 8;
121
+ $: swatchCount = 5;
122
+ /** Figma Color Picker recent swatches: 40×40, five across in the 232px content column. */
123
+ $: swatchSize = 40;
124
+ const opacityBarContentWidth = 184;
125
+
126
+ // Exported opacity with default handling
127
+ export let opacity: ColorPickerInputControllerProps['opacity'] =
128
+ config.defaultTransparency !== undefined ? config.defaultTransparency / 100 : 1;
129
+
130
+ // Tracks the last known opacity to maintain consistency
131
+ let lastKnownOpacity = opacity;
132
+
133
+ // Reactive statement to keep lastKnownOpacity in sync with opacity changes
134
+ $: lastKnownOpacity = opacity;
135
+
136
+ // Initialize the transparency handler with the current opacity
137
+ const transparencyHandler = new ColorTransparencyHandler(lastKnownOpacity);
138
+
139
+ /**
140
+ * Color State
141
+ * Maintains synchronized state between different color representations
142
+ * Uses isInternalUpdate flag to prevent recursive updates during state changes
143
+ */
144
+ let rgb = { r: 0, g: 0, b: 0, a: lastKnownOpacity };
145
+ let opacityValue = lastKnownOpacity;
146
+ let opacityPercentage = Math.round(lastKnownOpacity * 100);
147
+
148
+ // Unique instance ID for this color picker (use controllerId, id, or generate one)
149
+ const instanceId = controllerId || id || `cpicker-${Math.random().toString(36).slice(2, 8)}`;
150
+
151
+ // Local open state — not derived from store
152
+ let open = false;
153
+
154
+ // Listen for "close all color pickers except me" events from other instances
155
+ function onCloseOtherPickers(e: CustomEvent<string>) {
156
+ if (e.detail !== instanceId && open) {
157
+ open = false;
158
+ saveToRecentColors(value, lastKnownOpacity);
159
+ if (isColorSelectOpen) {
160
+ dispatch('colorselectmodalclose');
161
+ isColorSelectOpen = false;
162
+ }
163
+ }
164
+ }
536
165
 
537
- closeAutosuggestions();
538
- }
166
+ let opacitySliderRef: HTMLDivElement;
167
+ let isDragging = false;
168
+ let isHueDragging = false;
169
+
170
+ let hexInput: string = value;
171
+ let previewColor: string = value;
172
+ let persistentOpacity: number = 1;
173
+
174
+ let isInternalUpdate = false;
175
+
176
+ // Tracks the position of the opacity indicator for visual feedback
177
+ $: indicatorLeft = `calc(${lastKnownOpacity * 100}% - 4px)`;
178
+
179
+ // Opacity bar dimensions for slider calculations
180
+ const opacityBarWidth = '257px';
181
+ const opacityBarHeight = '33px';
182
+
183
+ // Opacity line aesthetics and dimensions
184
+ const opacityLineStrokeColor = 'rgb(0, 0, 0)';
185
+ const opacityLineStrokeOpacity = 0.1;
186
+ const opacityLineWidth = '2px';
187
+ const opacityLineColor = 'rgba(255, 255, 255, 0)';
188
+
189
+ // Add to props section
190
+ export let showRing: ColorPickerInputControllerProps['showRing'] = true;
191
+
192
+ /**
193
+ * Generates RGBA border string based on color and opacity
194
+ * @param color - Base color in RGB format
195
+ * @param opacity - Opacity value to apply
196
+ * @returns CSS border string with RGBA color
197
+ */
198
+ const getRGBABorder = (color: string, opacity: number) => {
199
+ return `1px solid ${color.replace('rgb', 'rgba').replace(')', `, ${opacity})`)}`;
200
+ };
201
+
202
+ /**
203
+ * Converts hex color to RGBA while preserving opacity
204
+ * Handles both 3 and 6 character hex codes
205
+ * Returns normalized RGB values (0-1 range)
206
+ * @param hex - Hexadecimal color string
207
+ * @returns RGB object with normalized values
208
+ */
209
+ function hexToRgba(hex: string): RGB {
210
+ // Remove hash and handle both 3 and 6 character hex
211
+ const digits = hex.replace('#', '');
212
+ let r, g, b;
213
+
214
+ if (digits.length === 3) {
215
+ // For 3-character hex, duplicate each character
216
+ r = parseInt(digits[0] + digits[0], 16) / 255;
217
+ g = parseInt(digits[1] + digits[1], 16) / 255;
218
+ b = parseInt(digits[2] + digits[2], 16) / 255;
219
+ } else {
220
+ // For 6-character hex
221
+ r = parseInt(digits.slice(0, 2), 16) / 255;
222
+ g = parseInt(digits.slice(2, 4), 16) / 255;
223
+ b = parseInt(digits.slice(4, 6), 16) / 255;
224
+ }
225
+
226
+ return {
227
+ r,
228
+ g,
229
+ b,
230
+ a: lastKnownOpacity
231
+ };
232
+ }
539
233
 
234
+ /**
235
+ * Converts RGB values to hex format
236
+ * Delegates to transparency handler for consistent color conversion
237
+ * Preserves alpha channel information
238
+ * @param r - Red component (0-1)
239
+ * @param g - Green component (0-1)
240
+ * @param b - Blue component (0-1)
241
+ * @param a - Alpha component (0-1)
242
+ * @returns Hexadecimal color string
243
+ */
244
+ function rgbaToHex(r: number, g: number, b: number, a: number): string {
245
+ return transparencyHandler.rgbaToHex(r, g, b, a);
246
+ }
247
+
248
+ // Reactive statement to synchronize value changes with internal state
249
+ $: {
250
+ if (value !== hexInput) {
251
+ const newRgb = hexToRgba(value);
252
+ rgb = newRgb; // The handler will preserve the opacity
253
+ hexInput = value;
254
+ previewColor = value;
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Updates color state and triggers change events
260
+ * - Validates hex format
261
+ * - Updates preview color
262
+ * - Triggers onChange callback only for valid hex values
263
+ * - Maintains 6-digit hex format
264
+ * @param newColor - New hex color value
265
+ */
266
+ function updateColor(newColor: string) {
267
+ previewColor = newColor;
268
+ if (/^#[0-9A-Fa-f]{6,8}$/.test(newColor)) {
269
+ value = newColor;
270
+ onChange(newColor);
271
+ }
272
+ }
273
+
274
+ /**
275
+ * Handles color changes from the color picker
276
+ * - Updates hex value while preserving opacity
277
+ * - Prevents recursive updates with isInternalUpdate flag
278
+ * - Maintains consistent state across all color representations
279
+ * - Triggers onChange with clean hex value
280
+ */
281
+ function handleColorChange(eventOrDetail?: CustomEvent | Record<string, any>) {
282
+ try {
283
+ isInternalUpdate = true;
284
+ const detail = eventOrDetail instanceof CustomEvent ? eventOrDetail.detail : eventOrDetail;
285
+ if (detail && detail.rgb) {
286
+ rgb = detail.rgb;
287
+ if (typeof detail.a === 'number') {
288
+ lastKnownOpacity = detail.a;
289
+ }
290
+ }
291
+ // Only use the 6-character hex without alpha
292
+ const hexValue = `#${Math.round(rgb.r * 255)
293
+ .toString(16)
294
+ .padStart(2, '0')}${Math.round(rgb.g * 255)
295
+ .toString(16)
296
+ .padStart(2, '0')}${Math.round(rgb.b * 255)
297
+ .toString(16)
298
+ .padStart(2, '0')}`;
299
+ value = hexValue;
300
+ hexInput = hexValue;
301
+ previewColor = getRgbaColor();
302
+ onChange(hexValue);
303
+ } finally {
304
+ isInternalUpdate = false;
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Normalizes hex color input
310
+ * - Handles color names conversion
311
+ * - Validates hex characters
312
+ * - Supports both 3 and 6 character formats
313
+ * - Returns standardized hex format
314
+ * @param input - User input string
315
+ * @returns Normalized hex color string
316
+ */
317
+ function normalizeHexInput(input: string): string {
318
+ // Remove hash if present and convert to lowercase
319
+ let color = input.toLowerCase().replace('#', '');
320
+
321
+ // Check if it's a color name
322
+ if (colorNames[color]) {
323
+ return colorNames[color];
324
+ }
325
+
326
+ // Only validate the characters, don't expand
327
+ if (!/^[0-9a-f]*$/i.test(color)) {
328
+ return value; // Return current value if invalid characters
329
+ }
330
+
331
+ // Return the current input with # prefix
332
+ return '#' + color;
333
+ }
334
+
335
+ /**
336
+ * Validates if a string is a valid hex color
337
+ * @param hex - Hexadecimal color string
338
+ * @returns Boolean indicating validity
339
+ */
340
+ function isValidHex(hex: string): boolean {
341
+ const digits = hex.replace('#', '');
342
+ return (digits.length === 3 || digits.length === 6) && /^[0-9a-f]+$/i.test(digits);
343
+ }
344
+
345
+ let currentSuggestion: AutocompleteResult | null = null;
346
+ let suggestionVisible = false;
347
+
348
+ /**
349
+ * Handles input events for hex input field
350
+ * - Processes valid hex inputs
351
+ * - Manages color name suggestions
352
+ * @param event - Input event from the text field
353
+ */
354
+ function handleHexInput(event: Event) {
355
+ const input = event.target as HTMLInputElement;
356
+ let newValue = input.value.toLowerCase();
357
+
358
+ // validate the new value
359
+ if (newValue.startsWith('#') || /^[0-9a-f]+$/i.test(newValue)) {
360
+ // if the value starts with #, keep it, otherwise add it
361
+ const processedValue = newValue.startsWith('#') ? newValue : `#${newValue}`;
362
+
363
+ // console.log('handleHexInput processedValue:', processedValue);
364
+
365
+ // if new value is a hex color(starts with # and has 3 or 6 characters): call the onChange callback
366
+ const hexRegex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
367
+ if (hexRegex.test(processedValue)) {
368
+ // console.log('Valid hex color detected:', processedValue);
369
+ try {
370
+ // set the internal update flag to true
371
+ isInternalUpdate = true;
372
+
373
+ // update the component's value
374
+ value = processedValue;
375
+
376
+ // update the rgb value
377
+ const newRgb = hexToRgba(processedValue);
378
+ rgb = { ...newRgb, a: lastKnownOpacity };
379
+
380
+ // update the preview color
381
+ previewColor = getRgbaColor();
382
+
383
+ // call the onChange callback
384
+ onChange(processedValue);
385
+ } finally {
386
+ isInternalUpdate = false;
387
+ }
388
+ return;
389
+ }
390
+ }
391
+
392
+ // console.log('handleHexInput newValue:', !/[^a-z\s]/.test(newValue));
393
+
394
+ // if newValue is empty or contains invalid characters, clear the suggestions
395
+ if (!newValue || /[^a-z\s]/.test(newValue)) {
396
+ // console.log('Clearing suggestions due to invalid input');
397
+ suggestionVisible = false;
398
+ currentSuggestion = null;
399
+ return;
400
+ }
401
+
402
+ // if newValue is a valid color name, get the suggestions and show them
403
+ const suggestions = getColorSuggestions(newValue, colorNames);
404
+ // console.log('Color suggestions:', { input: newValue, suggestions });
405
+ if (suggestions) {
406
+ currentSuggestion = suggestions;
407
+ suggestionVisible = true;
408
+ } else {
409
+ suggestionVisible = false;
410
+ currentSuggestion = null;
411
+ }
412
+ }
413
+
414
+ /**
415
+ * Handles the selection of a color from suggestions
416
+ * @param colorName - Selected color name
417
+ * @param isShiftPressed - Indicates if the shift key was held during selection
418
+ */
419
+ function handleColorSelection(colorName: string, isShiftPressed: boolean) {
420
+ // console.log('Handling color selection:', {
421
+ // colorName,
422
+ // isShiftPressed,
423
+ // currentOpacity: lastKnownOpacity
424
+ // });
425
+
426
+ const colorValue = colorNames[colorName];
427
+ value = colorValue;
428
+ const newRgb = hexToRgba(colorValue);
429
+
430
+ // If Shift is pressed, set opacity to 100%
431
+ if (isShiftPressed) {
432
+ // console.log('Shift pressed: Setting opacity to 100%');
433
+ lastKnownOpacity = 1;
434
+ rgb = { ...newRgb, a: 1 };
435
+ opacityPercentage = 100;
436
+ } else {
437
+ // Keep current opacity
438
+ rgb = { ...newRgb, a: lastKnownOpacity };
439
+ }
440
+
441
+ previewColor = getRgbaColor();
442
+ onChange(colorValue);
443
+ suggestionVisible = false;
444
+ currentSuggestion = null;
445
+
446
+ // Save to recent colors
447
+ saveToRecentColors(colorValue, rgb.a);
448
+ }
449
+
450
+ /**
451
+ * Handles keydown events for keyboard navigation and interactions
452
+ * @param event - Keyboard event
453
+ */
454
+ function handleKeyDown(event: KeyboardEvent) {
455
+ const input = event.target as HTMLInputElement;
456
+ const currentInputValue = input.value;
457
+
458
+ // Only prevent default for special keys when popup is open
459
+ if (open && (event.key === 'Shift' || event.key === ' ')) {
460
+ event.preventDefault();
461
+ return;
462
+ }
463
+
464
+ // console.log('Key pressed:', {
465
+ // key: event.key,
466
+ // actualInputValue: currentInputValue,
467
+ // boundHexInput: hexInput,
468
+ // isEmpty: !currentInputValue.trim(),
469
+ // currentValue: value
470
+ // });
471
+
472
+ if (event.key === 'Escape') {
473
+ event.preventDefault();
474
+ closeAutosuggestions();
475
+ if (!currentInputValue.trim()) {
476
+ restoreCurrentColor();
477
+ }
478
+ return;
479
+ }
480
+
481
+ if (event.key === 'Enter') {
482
+ if (!currentInputValue.trim() || currentInputValue === '#') {
483
+ restoreCurrentColor();
484
+ return;
485
+ }
486
+ }
487
+
488
+ // if the suggestions are visible, handle the key events to navigate the suggestions
489
+ if (suggestionVisible && currentSuggestion) {
490
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
491
+ event.preventDefault();
492
+
493
+ const direction = event.key === 'ArrowDown' ? 'down' : 'up';
494
+
495
+ const result = getNextSuggestion(currentSuggestion, direction);
496
+ if (result) {
497
+ currentSuggestion = result;
498
+ }
499
+ } else if (event.key === 'Enter') {
500
+ event.preventDefault();
501
+ handleColorSelection(currentSuggestion.suggestion, event.shiftKey);
502
+ }
503
+ }
504
+ }
505
+
506
+ /**
507
+ * Handles popover open/close state changes
508
+ * - Saves current color when closing
509
+ * - Closes autosuggestions if opening
510
+ * - Calculates fixed position when opening
511
+ */
512
+ function handleToggle(isOpen: boolean) {
513
+ // console.warn('[ColorPicker] handleToggle called:', { isOpen, currentOpen: open, instanceId, portalTarget });
514
+ if (isOpen === open) return;
515
+
516
+ if (!isOpen) {
517
+ saveToRecentColors(value, lastKnownOpacity);
518
+ if (isColorSelectOpen) {
519
+ dispatch('colorselectmodalclose');
520
+ isColorSelectOpen = false;
521
+ }
522
+ } else {
523
+ // Close all other color pickers before opening this one
524
+ window.dispatchEvent(new CustomEvent('widgetic:close-color-pickers', { detail: instanceId }));
525
+ closeAutosuggestions();
526
+ dispatch('colorselectmodalopen');
527
+ isColorSelectOpen = true;
528
+ updatePopoverPosition();
529
+ // Re-position after portal is mounted and layout stabilizes
530
+ tick().then(() => {
531
+ requestAnimationFrame(updatePopoverPosition);
532
+ });
533
+ }
534
+
535
+ open = isOpen;
536
+ }
537
+
538
+ /**
539
+ * Closes the color picker dropdown and autosuggestions
540
+ */
541
+ function closeDropdown() {
542
+ if (open) {
543
+ handleToggle(false);
544
+ }
545
+
546
+ closeAutosuggestions();
547
+ }
540
548
 
541
549
  function closeAutosuggestions() {
542
- // Close autosuggestions if they're open
543
- if (suggestionVisible) {
544
- suggestionVisible = false;
545
- currentSuggestion = null;
546
- // Set the input to the current hex value
547
- hexInput = value.slice(0, 7); // Only take the 6-character hex
548
- }
550
+ // Close autosuggestions if they're open
551
+ if (suggestionVisible) {
552
+ suggestionVisible = false;
553
+ currentSuggestion = null;
554
+ // Set the input to the current hex value
555
+ hexInput = value.slice(0, 7); // Only take the 6-character hex
556
+ }
549
557
  }
550
558
 
551
- /**
552
- * Handles scroll events to save color and close dropdown if necessary
553
- * @param event - Scroll event
554
- */
555
- function handleScroll(event: Event) {
556
- // Don't close if scrolling happens within allowed elements. The page itself scrolling has the document as its
557
- // target (it has no closest()), so only an element can be one of the allowed ones.
558
- const scrollTarget = event.target;
559
- if (scrollTarget instanceof Element && scrollTarget.closest('[data-allow-scroll="true"]')) {
560
- return;
561
- }
562
-
563
- // Close both suggestions and color picker
564
- if (suggestionVisible || open) {
565
- suggestionVisible = false;
566
- currentSuggestion = null;
567
- closeDropdown();
568
- }
569
- }
570
-
571
- // Puts the pointer back after an opacity drag, however the drag ends (the picker can be removed in the middle of one).
572
- let releaseOpacityPointerStyle: (() => void) | null = null;
573
-
574
- /**
575
- * Manages opacity slider interactions
576
- * - Handles mouse drag events
577
- * - Updates opacity state
578
- * - Maintains color consistency
579
- * - Prevents event bubbling
580
- * @param event - Mouse event
581
- */
582
- function handleOpacityMouseDown(event: MouseEvent) {
583
- isDragging = true;
584
- // The cursor is shown on the host of the shadow root the picker is in, and on <body> only on a normal page: the
585
- // <body> of a customer's page is not the editor's to change.
586
- releaseOpacityPointerStyle?.();
587
- releaseOpacityPointerStyle = lockPointerStyle(event.currentTarget ?? event.target, 'grabbing', {
588
- blockTextSelection: false
589
- });
590
- updateOpacity(event);
591
-
592
- const handleMouseMove = (e: MouseEvent) => {
593
- if (isDragging) {
594
- updateOpacity(e);
595
- }
596
- };
597
-
598
- const handleMouseUp = () => {
599
- isDragging = false;
600
- releaseOpacityPointerStyle?.();
601
- releaseOpacityPointerStyle = null;
602
- window.removeEventListener('mousemove', handleMouseMove);
603
- window.removeEventListener('mouseup', handleMouseUp);
604
- };
605
-
606
- window.addEventListener('mousemove', handleMouseMove);
607
- window.addEventListener('mouseup', handleMouseUp);
608
- }
609
-
610
- // Reactive statement to handle external value changes
611
- $: {
612
- if (value !== hexInput && !isInternalUpdate) {
613
- const newRgb = hexToRgba(value);
614
- rgb = { ...newRgb, a: lastKnownOpacity }; // Preserve opacity
615
- hexInput = value;
616
- previewColor = value;
617
- }
618
- }
619
-
620
- // Reactive statement to update the style of the opacity indicator
621
- $: verticalLineStyle = `
559
+ /**
560
+ * Handles scroll events to save color and close dropdown if necessary
561
+ * @param event - Scroll event
562
+ */
563
+ function handleScroll(event: Event) {
564
+ // Don't close if scrolling happens within allowed elements. The page itself scrolling has the document as its
565
+ // target (it has no closest()), so only an element can be one of the allowed ones.
566
+ const scrollTarget = event.target;
567
+ if (scrollTarget instanceof Element && scrollTarget.closest('[data-allow-scroll="true"]')) {
568
+ return;
569
+ }
570
+
571
+ // Close both suggestions and color picker
572
+ if (suggestionVisible || open) {
573
+ suggestionVisible = false;
574
+ currentSuggestion = null;
575
+ closeDropdown();
576
+ }
577
+ }
578
+
579
+ // Puts the pointer back after an opacity drag, however the drag ends (the picker can be removed in the middle of one).
580
+ let releaseOpacityPointerStyle: (() => void) | null = null;
581
+
582
+ /**
583
+ * Manages opacity slider interactions
584
+ * - Handles mouse drag events
585
+ * - Updates opacity state
586
+ * - Maintains color consistency
587
+ * - Prevents event bubbling
588
+ * @param event - Mouse event
589
+ */
590
+ function handleOpacityMouseDown(event: MouseEvent) {
591
+ isDragging = true;
592
+ // The cursor is shown on the host of the shadow root the picker is in, and on <body> only on a normal page: the
593
+ // <body> of a customer's page is not the editor's to change.
594
+ releaseOpacityPointerStyle?.();
595
+ releaseOpacityPointerStyle = lockPointerStyle(event.currentTarget ?? event.target, 'grabbing', {
596
+ blockTextSelection: false
597
+ });
598
+ updateOpacity(event);
599
+
600
+ const handleMouseMove = (e: MouseEvent) => {
601
+ if (isDragging) {
602
+ updateOpacity(e);
603
+ }
604
+ };
605
+
606
+ const handleMouseUp = () => {
607
+ isDragging = false;
608
+ releaseOpacityPointerStyle?.();
609
+ releaseOpacityPointerStyle = null;
610
+ window.removeEventListener('mousemove', handleMouseMove);
611
+ window.removeEventListener('mouseup', handleMouseUp);
612
+ };
613
+
614
+ window.addEventListener('mousemove', handleMouseMove);
615
+ window.addEventListener('mouseup', handleMouseUp);
616
+ }
617
+
618
+ // Reactive statement to handle external value changes
619
+ $: {
620
+ if (value !== hexInput && !isInternalUpdate) {
621
+ const newRgb = hexToRgba(value);
622
+ rgb = { ...newRgb, a: lastKnownOpacity }; // Preserve opacity
623
+ hexInput = value;
624
+ previewColor = value;
625
+ }
626
+ }
627
+
628
+ // Reactive statement to update the style of the opacity indicator
629
+ $: verticalLineStyle = `
622
630
  left: ${indicatorLeft};
623
631
  width: ${opacityLineWidth};
624
632
  background-color: ${opacityLineColor};
625
633
  `;
626
634
 
627
- /**
628
- * Applies opacity to a given RGB color
629
- * @param color - RGB color object
630
- * @param opacity - Opacity value to apply
631
- * @returns RGB color object with updated opacity
632
- */
633
- function applyOpacityToColor(color: RGB, opacity: number): RGB {
634
- return {
635
- r: color.r,
636
- g: color.g,
637
- b: color.b,
638
- a: opacity
639
- };
640
- }
641
-
642
- // Reactive statement to apply opacity changes
643
- $: {
644
- if (value !== hexInput && !isInternalUpdate) {
645
- const newRgb = hexToRgba(value);
646
- rgb = applyOpacityToColor(newRgb, lastKnownOpacity);
647
- hexInput = value;
648
- previewColor = rgbaToHex(rgb.r, rgb.g, rgb.b, lastKnownOpacity);
649
- }
650
- }
651
-
652
- /**
653
- * Updates opacity based on slider position
654
- * - Calculates normalized opacity value
655
- * - Updates all color representations
656
- * - Triggers change callbacks
657
- * - Handles edge cases
658
- * @param event - Mouse event from slider interaction
659
- */
660
- function updateOpacity(event: MouseEvent) {
661
- if (!opacitySliderRef) return;
662
-
663
- const rect = opacitySliderRef.getBoundingClientRect();
664
- const x = event.clientX - rect.left;
665
- const width = rect.width;
666
-
667
- let newOpacity = Math.max(0, Math.min(x, width)) / width;
668
- newOpacity = Math.round(newOpacity * 100) / 100;
669
-
670
- try {
671
- isInternalUpdate = true;
672
- opacity = newOpacity; // This will trigger the reactive statement
673
- rgb = { ...rgb, a: newOpacity };
674
- lastKnownOpacity = newOpacity;
675
- const hexValue = `#${Math.round(rgb.r * 255).toString(16).padStart(2, '0')}${Math.round(rgb.g * 255).toString(16).padStart(2, '0')}${Math.round(rgb.b * 255).toString(16).padStart(2, '0')}`;
676
- value = hexValue;
677
- hexInput = hexValue;
678
- previewColor = getRgbaColor();
679
- onChange(hexValue);
680
- onOpacityChange(newOpacity); // Call the opacity change handler
681
- } finally {
682
- isInternalUpdate = false;
683
- }
684
- }
685
-
686
- /**
687
- * Updates opacity from numeric input
688
- * - Validates input range (0-100)
689
- * - Converts percentage to decimal
690
- * - Updates all color states
691
- * - Maintains color consistency
692
- * - Prevents invalid states
693
- * @param event - Input event from the numeric opacity field
694
- */
695
- function updateOpacityFromInput(event: Event) {
696
- const input = event.target as HTMLInputElement;
697
- input.value = input.value.replace(/[^\d]/g, '').slice(0, 3);
698
-
699
- let num = parseInt(input.value);
700
- if (isNaN(num) || input.value === '') num = 0;
701
- if (num > 100) num = 100;
702
-
703
- input.value = num.toString();
704
- opacityPercentage = num;
705
-
706
- try {
707
- isInternalUpdate = true;
708
- lastKnownOpacity = num / 100;
709
- rgb = { ...rgb, a: num / 100 };
710
- // Only use the 6-character hex without alpha
711
- const hexValue = `#${Math.round(rgb.r * 255).toString(16).padStart(2, '0')}${Math.round(rgb.g * 255).toString(16).padStart(2, '0')}${Math.round(rgb.b * 255).toString(16).padStart(2, '0')}`;
712
- value = hexValue;
713
- hexInput = hexValue;
714
- previewColor = getRgbaColor();
715
- onChange(hexValue);
716
- } finally {
717
- isInternalUpdate = false;
718
- }
719
- }
720
-
721
- // Reactive statement to calculate opacity percentage
722
- $: opacityPercentage = Math.round(lastKnownOpacity * 100);
723
-
724
- let lastKnownHue = 0;
725
- let colorSelectRef: ColorSelect; // Reference to ColorSelect component
726
-
727
- /**
728
- * Converts HSV to RGB values
729
- * @param h - Hue value
730
- * @param s - Saturation value
731
- * @param v - Value (brightness) value
732
- * @returns RGB color object with normalized values
733
- */
734
- function hsvToRgb(h: number, s: number, v: number) {
735
- const f = (n: number, k = (n + h/60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0);
736
- return {
737
- r: Math.round(f(5) * 255) / 255,
738
- g: Math.round(f(3) * 255) / 255,
739
- b: Math.round(f(1) * 255) / 255,
740
- a: lastKnownOpacity
741
- };
742
- }
743
-
744
- /**
745
- * Logs color-related events for debugging purposes
746
- * @param event - Custom event from color picker interactions
747
- */
748
- function onColorEvent(event: CustomEvent) {
749
- // Safe logging that won't throw errors
750
- // console.log('Color event received:', {
751
- // type: event.type,
752
- // rgb: event.detail?.rgb || rgb,
753
- // mode: event.detail?.mode,
754
- // rawEvent: {
755
- // detail: event.detail,
756
- // target: event.target ? 'exists' : 'null',
757
- // currentTarget: event.currentTarget ? 'exists' : 'null'
758
- // }
759
- // });
760
- }
761
-
762
- /**
763
- * Handles direct hue changes from the color picker
764
- * @param event - Custom event containing hue information
765
- */
766
- function handleHueChange(event: CustomEvent) {
767
- // console.log('Hue change event:', event.detail);
768
- try {
769
- isInternalUpdate = true;
770
- lastKnownHue = event.detail.h;
771
-
772
- // Convert HSV to RGB using current saturation and value
773
- const newRgb = hsvToRgb(
774
- lastKnownHue,
775
- 1, // Full saturation for testing
776
- 1 // Full value for testing
777
- );
778
-
779
- rgb = newRgb;
780
- handleColorChange();
781
-
782
- // console.log('After hue change:', {
783
- // hue: lastKnownHue,
784
- // rgb: newRgb,
785
- // hexValue: rgbaToHex(newRgb.r, newRgb.g, newRgb.b, lastKnownOpacity)
786
- // });
787
- } finally {
788
- isInternalUpdate = false;
789
- }
790
- }
791
-
792
- let dragState = {
793
- isHueDragging: false,
794
- isOpacityDragging: false,
795
- isColorDragging: false
796
- };
797
-
798
- /**
799
- * Manages drag state across different interactions
800
- * Prevents race conditions and maintains consistent state
801
- * Handles cleanup on component destruction
802
- * @param event - Mouse event from global interactions
803
- */
804
- function handleGlobalMouseUp(event: MouseEvent) {
805
- if (!open) return;
806
-
807
- // console.log('Global mouseup triggered', dragState);
808
- if (dragState.isHueDragging || dragState.isOpacityDragging || dragState.isColorDragging) {
809
- dragState = {
810
- isHueDragging: false,
811
- isOpacityDragging: false,
812
- isColorDragging: false
813
- };
814
- handleColorChange();
815
- // console.log('Dragging stopped');
816
- }
817
- }
818
-
819
- /**
820
- * Handles global mouse move events during dragging
821
- * @param event - Mouse move event
822
- */
823
- function handleGlobalMouseMove(event: MouseEvent) {
824
- if (dragState.isHueDragging || dragState.isOpacityDragging || dragState.isColorDragging) {
825
- // console.log('Moving while dragging:', {
826
- // type: dragState.isHueDragging ? 'hue' :
827
- // dragState.isOpacityDragging ? 'opacity' : 'color',
828
- // event: event
829
- // });
830
- handleColorChange();
831
- }
832
- }
833
-
834
- /**
835
- * Determines the type of drag based on mouse interaction
836
- * @param event - Mouse down event initiating drag
837
- */
838
- function handleDragStart(event: MouseEvent) {
839
- const target = event.target as HTMLElement;
840
- const rect = target.getBoundingClientRect();
841
- const parentRect = target.parentElement?.getBoundingClientRect();
842
-
843
- // Log all relevant information for debugging
844
- // console.log('Mousedown details:', {
845
- // element: target,
846
- // rect: rect,
847
- // parentRect: parentRect,
848
- // style: target.getAttribute('style'),
849
- // parentStyle: target.parentElement?.getAttribute('style')
850
- // });
851
-
852
- // Check if it's a canvas element
853
- if (target.tagName.toLowerCase() === 'canvas') {
854
- // Get the computed style to check positioning
855
- const computedStyle = window.getComputedStyle(target);
856
- const top = parseInt(computedStyle.top);
857
-
858
- if (rect.width === 31 && rect.height === 256) {
859
- if (top < 50) { // Hue slider is typically at the top
860
- dragState.isHueDragging = true;
861
- // console.log('Hue drag started (top slider)');
862
- } else { // Opacity slider is typically at the bottom
863
- dragState.isOpacityDragging = true;
864
- // console.log('Opacity drag started (bottom slider)');
865
- }
866
- } else {
867
- dragState.isColorDragging = true;
868
- // console.log('Color drag started (main area)');
869
- }
870
- }
871
-
872
- // console.log('Current drag state:', dragState);
873
- }
874
-
875
- /**
876
- * Initializes component state
877
- * - Normalizes initial color value
878
- * - Sets up event listeners
879
- * - Configures opacity handling
880
- * - Initializes recent colors
881
- */
882
- function initializeColor() {
883
- const normalizedHex = normalizeHexInput(value);
884
- if (normalizedHex.startsWith('#')) {
885
- const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(normalizedHex);
886
- if (result) {
887
- const r = parseInt(result[1], 16) / 255;
888
- const g = parseInt(result[2], 16) / 255;
889
- const b = parseInt(result[3], 16) / 255;
890
-
891
- rgb = {
892
- // r: r === 0 ? 0.000001 : r, // Prevent zero opacity issues
893
- r: r,
894
- g: g,
895
- b: b,
896
- a: lastKnownOpacity
897
- };
898
-
899
- // Set initial display values
900
- hexInput = normalizedHex;
901
- previewColor = getRgbaColor();
902
-
903
- // console.log('Color initialized:', {
904
- // hex: normalizedHex,
905
- // rgb,
906
- // opacity: lastKnownOpacity,
907
- // percentage: opacityPercentage
908
- // });
909
- }
910
- }
911
- }
912
-
913
- /**
914
- * Generates an RGBA color string for CSS
915
- * @returns RGBA color string based on current RGB and opacity
916
- */
917
- function getRgbaColor() {
918
- const r = Math.round(rgb.r * 255);
919
- const g = Math.round(rgb.g * 255);
920
- const b = Math.round(rgb.b * 255);
921
- return `rgba(${r}, ${g}, ${b}, ${lastKnownOpacity})`;
922
- }
923
-
924
- // Make previewColor reactive so it updates instantly whenever rgb or opacity change
925
- $: previewColor = getRgbaColor();
926
-
927
- /**
928
- * Handles keydown events within the popover for modifier keys
929
- * @param event - Keyboard event
930
- */
931
- function handlePopupKeyDown(event: KeyboardEvent) {
932
- // Only handle keys if the popup is open
933
- if (!open) return;
934
-
935
- if (event.key === 'Shift' || event.key === ' ') {
936
- event.preventDefault(); // Prevent space from scrolling
937
-
938
- if (event.key === 'Shift') {
939
- isShiftPressed = true;
940
- } else if (event.key === ' ') {
941
- isSpacePressed = true;
942
- }
943
-
944
- if (recentColors.length === 0) {
945
- showNoRecentMessage = true;
946
- setTimeout(() => {
947
- showNoRecentMessage = false;
948
- }, 2000);
949
- }
950
- }
951
- }
952
-
953
- /**
954
- * Handles keyup events within the popover to reset modifier keys
955
- * @param event - Keyboard event
956
- */
957
- function handlePopupKeyUp(event: KeyboardEvent) {
958
- // Only handle keys if the popup is open
959
- if (!open) return;
960
-
961
- if (event.key === 'Shift' || event.key === ' ') {
962
- if (event.key === 'Shift') {
963
- isShiftPressed = false;
964
- } else if (event.key === ' ') {
965
- isSpacePressed = false;
966
- }
967
- }
968
- }
969
-
970
- // Stops listening for scrolling (the page and, inside a module, the module's own panels: a scroll never leaves a
971
- // shadow root, so a listener on the window alone does not hear about those)
972
- let stopListeningForScroll: () => void = () => {};
973
-
974
- // Sets up event listeners when the component mounts
975
- onMount(() => {
976
- initializeColor();
977
- window.addEventListener('mouseup', handleGlobalMouseUp);
978
- window.addEventListener('mousemove', handleGlobalMouseMove);
979
- window.addEventListener('keydown', handlePopupKeyDown);
980
- window.addEventListener('keyup', handlePopupKeyUp);
981
- stopListeningForScroll = listenForScroll(inputRef, handleScroll);
982
- window.addEventListener('widgetic:close-color-pickers', onCloseOtherPickers as EventListener);
983
- });
984
-
985
- // Cleans up event listeners when the component is destroyed
986
- onDestroy(() => {
987
- releaseOpacityPointerStyle?.();
988
- releaseOpacityPointerStyle = null;
989
- window.removeEventListener('mouseup', handleGlobalMouseUp);
990
- window.removeEventListener('mousemove', handleGlobalMouseMove);
991
- window.removeEventListener('keydown', handlePopupKeyDown);
992
- window.removeEventListener('keyup', handlePopupKeyUp);
993
- stopListeningForScroll();
994
- window.removeEventListener('widgetic:close-color-pickers', onCloseOtherPickers as EventListener);
995
- });
996
-
997
- // Then handle opacity updates
998
- $: {
999
- if (value) {
1000
- if (value.startsWith('rgba')) {
1001
- const matches = value.match(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)/);
1002
- if (matches) {
1003
- const [_, r, g, b, a] = matches;
1004
- rgb = {
1005
- r: parseInt(r) / 255,
1006
- g: parseInt(g) / 255,
1007
- b: parseInt(b) / 255,
1008
- a: parseFloat(a)
1009
- };
1010
- opacityValue = parseFloat(a);
1011
- opacityPercentage = Math.round(opacityValue * 100);
1012
- }
1013
- }
1014
- else if (value.startsWith('#') && value.length === 9) {
1015
- const alpha = parseInt(value.slice(7), 16);
1016
- opacityValue = alpha / 255;
1017
- opacityPercentage = Math.round(opacityValue * 100);
1018
- rgb.a = opacityValue;
1019
- }
1020
- }
1021
- }
1022
-
1023
- /**
1024
- * Saves a color to the recent colors list
1025
- * - Prevents duplicates by checking the most recent entry
1026
- * - Maintains storage limits through utility functions
1027
- * @param color - Hexadecimal color string
1028
- * @param alpha - Opacity value of the color
1029
- */
1030
- function saveToRecentColors(color: string, alpha: number) {
1031
- if (!saveRecentColors) {
1032
- // console.log('Recent colors saving is disabled');
1033
- return;
1034
- }
1035
-
1036
- // Check if this exact color+alpha combination is already the most recent
1037
- const currentRecents = recentColorsUtil.getRecentColors();
1038
- // console.log('Current recent colors:', currentRecents);
1039
-
1040
- const mostRecent = currentRecents[0];
1041
-
1042
- if (mostRecent &&
1043
- mostRecent.color.toLowerCase() === color.toLowerCase() &&
1044
- mostRecent.alpha === alpha) {
1045
- // console.log('Color already most recent, skipping save:', { color, alpha });
1046
- return;
1047
- }
1048
-
1049
- // console.log('Saving new color to recent colors:', { color, alpha });
1050
- recentColors = recentColorsUtil.addRecentColor(color, alpha);
1051
- // console.log('Updated recent colors list:', recentColors);
1052
- }
1053
-
1054
- /**
1055
- * Handles the selection of a color name from suggestions
1056
- * @param colorName - Selected color name
1057
- */
1058
- function handleColorNameSelection(colorName: string) {
1059
- const colorValue = colorNames[colorName];
1060
- value = colorValue;
1061
- const newRgb = hexToRgba(colorValue);
1062
- rgb = { ...newRgb, a: lastKnownOpacity };
1063
- previewColor = getRgbaColor();
1064
- onChange(colorValue);
1065
- suggestionVisible = false;
1066
- currentSuggestion = null;
1067
-
1068
- // Save the selected color name
1069
- saveToRecentColors(colorValue, lastKnownOpacity);
1070
- }
1071
-
1072
- /**
1073
- * Handles click events on color suggestions
1074
- * @param match - The matched color name clicked by the user
1075
- */
1076
- function handleSuggestionClick(match: string) {
1077
- // console.log('Color name selected:', match);
1078
- hexInput = match;
1079
- const colorValue = colorNames[match];
1080
- // console.log('Converting color name to hex:', { name: match, hex: colorValue });
1081
-
1082
- value = colorValue;
1083
- const newRgb = hexToRgba(colorValue);
1084
- rgb = { ...newRgb, a: lastKnownOpacity };
1085
- previewColor = getRgbaColor();
1086
- onChange(colorValue);
1087
- suggestionVisible = false;
1088
- currentSuggestion = null;
1089
-
1090
- // Save the hex value of the selected color name
1091
- saveToRecentColors(colorValue, lastKnownOpacity);
1092
- }
1093
-
1094
- /**
1095
- * Handles blur events on the hex input field to restore color if input is empty
1096
- * @param event - Focus event from the input field
1097
- */
1098
- function handleInputBlur(event: FocusEvent) {
1099
- // Get the related target (element receiving focus)
1100
- const relatedTarget = event.relatedTarget as HTMLElement;
1101
-
1102
- // Don't close if focus is moving to a suggestion item
1103
- if (relatedTarget?.closest('.color-suggestions')) {
1104
- return;
1105
- }
1106
-
1107
- const input = event.target as HTMLInputElement;
1108
- const currentInputValue = input.value;
1109
-
1110
- // Close suggestions
1111
- closeAutosuggestions();
1112
-
1113
- // Check actual input value
1114
- if (!currentInputValue.trim()) {
1115
- restoreCurrentColor();
1116
- }
1117
- }
1118
-
1119
- let inputRef: HTMLDivElement;
1120
-
1121
- /**
1122
- * Restores the current color value when input is invalid or empty
1123
- * - Resets the hex input to the last valid color value
1124
- * - Forces the input field to update and regain focus
1125
- */
1126
- function restoreCurrentColor() {
1127
- // console.log('Restoring current color:', {
1128
- // currentValue: value,
1129
- // hexToRestore: value.slice(0, 7),
1130
- // currentHexInput: hexInput
1131
- // });
1132
-
1133
- if (value && value.startsWith('#')) {
1134
- const colorToRestore = value.slice(0, 7);
1135
-
1136
- // Force immediate update
1137
- hexInput = colorToRestore;
1138
- value = colorToRestore;
1139
-
1140
- // Force input focus and update
1141
- setTimeout(() => {
1142
- const inputElement = inputRef?.querySelector('input') as HTMLInputElement;
1143
- if (inputElement) {
1144
- inputElement.value = colorToRestore;
1145
- inputElement.focus();
1146
- inputElement.blur();
1147
- }
1148
- }, 0);
1149
- }
1150
- }
1151
-
1152
- // Exported onFocus handler with default no-op
1153
- export let onFocus: ColorPickerInputControllerProps['onFocus'] = () => {};
1154
-
1155
- // Sets autofocus on mount if enabled
1156
- onMount(() => {
1157
- if (autofocus && inputRef) {
1158
- inputRef.focus();
1159
- // console.log('ColorPickerInputController focused');
1160
- }
1161
- });
1162
-
1163
- /**
1164
- * Focus method to programmatically focus the input field
1165
- */
1166
- export function focus() {
1167
- if (inputRef) {
1168
- inputRef.focus();
1169
- // console.log('ColorPickerInputController focus method called');
1170
- }
1171
- }
1172
-
1173
- // Popover visibility is now handled by {#if open} conditional rendering
1174
-
1175
- // Exported opacity change handler with default no-op
1176
- export let onOpacityChange: ColorPickerInputControllerProps['onOpacityChange'] = () => {};
1177
-
1178
- // Add these variables to track input position
1179
- let inputComponent: any;
1180
- let inputRect: DOMRect | null = null;
1181
-
1182
- // Track trigger position for fixed-position popover
1183
- let triggerRef: HTMLDivElement;
1184
- let popoverStyle = '';
1185
-
1186
- function updatePopoverPosition() {
1187
- if (!triggerRef) return;
1188
- const rect = triggerRef.getBoundingClientRect();
1189
- // Guard: if trigger hasn't been laid out yet, defer
1190
- if (rect.width === 0 && rect.height === 0) {
1191
- requestAnimationFrame(updatePopoverPosition);
1192
- return;
1193
- }
1194
- const popoverHeight = 420;
1195
- const spaceBelow = window.innerHeight - rect.bottom;
1196
- const spaceAbove = rect.top;
1197
- const openAbove = spaceBelow < popoverHeight + 8 && spaceAbove > popoverHeight + 8;
1198
- const top = openAbove
1199
- ? Math.round(rect.top - popoverHeight - 4)
1200
- : Math.round(rect.bottom + 4);
1201
- // Align the popup's end edge with the end edge of the full input container: the right edge on a left to right screen,
1202
- // the left edge on a right to left one (the popup itself is a drawing, drawn left to right, and opens toward the inside)
1203
- const inputContainer = triggerRef.closest('.color-input-main-container') as HTMLElement | null;
1204
- const containerRect = inputContainer ? inputContainer.getBoundingClientRect() : rect;
1205
- if ($textDirection === 'rtl') {
1206
- popoverStyle = `top: ${top}px; left: ${Math.round(containerRect.left)}px;`; // rtl-ok: the end edge of a right to left field is its left edge
1207
- } else {
1208
- const right = Math.round(window.innerWidth - containerRect.right);
1209
- popoverStyle = `top: ${top}px; right: ${right}px;`; // rtl-ok: the end edge of a left to right field is its right edge
1210
- }
1211
- }
1212
-
1213
- // Position is calculated in handleToggle after tick()
1214
-
1215
- // Update the position function to get the actual input element
1216
- function updateInputPosition() {
1217
- // Get the actual input element from the component
1218
- // console.log('updateInputPosition', inputRef);
1219
- const inputElement = inputRef?.querySelector('input');
1220
- if (inputElement) {
1221
- inputRect = inputElement.getBoundingClientRect();
1222
- // console.log('inputRect', inputRect);
1223
- }
1224
- }
1225
-
1226
- // Update the suggestions position when they become visible
1227
- $: if (suggestionVisible) {
1228
- updateInputPosition();
1229
- }
1230
-
1231
- // Close suggestions when picker is closed
1232
- $: if (!open) {
1233
- suggestionVisible = false;
1234
- currentSuggestion = null;
1235
- if (isColorSelectOpen) {
1236
- dispatch('colorselectmodalclose');
1237
- isColorSelectOpen = false;
1238
- }
1239
- }
1240
-
1241
- // Add this near the top with other state declarations
1242
- let isColorSelectOpen = false;
1243
-
1244
- // Add these computed styles for layout
1245
- $: opacityBarWidthPx = `${pickerSize}px`;
1246
- $: recentColorsMaxWidth = `${pickerSize + sliderWidth}px`;
635
+ /**
636
+ * Applies opacity to a given RGB color
637
+ * @param color - RGB color object
638
+ * @param opacity - Opacity value to apply
639
+ * @returns RGB color object with updated opacity
640
+ */
641
+ function applyOpacityToColor(color: RGB, opacity: number): RGB {
642
+ return {
643
+ r: color.r,
644
+ g: color.g,
645
+ b: color.b,
646
+ a: opacity
647
+ };
648
+ }
649
+
650
+ // Reactive statement to apply opacity changes
651
+ $: {
652
+ if (value !== hexInput && !isInternalUpdate) {
653
+ const newRgb = hexToRgba(value);
654
+ rgb = applyOpacityToColor(newRgb, lastKnownOpacity);
655
+ hexInput = value;
656
+ previewColor = rgbaToHex(rgb.r, rgb.g, rgb.b, lastKnownOpacity);
657
+ }
658
+ }
659
+
660
+ /**
661
+ * Updates opacity based on slider position
662
+ * - Calculates normalized opacity value
663
+ * - Updates all color representations
664
+ * - Triggers change callbacks
665
+ * - Handles edge cases
666
+ * @param event - Mouse event from slider interaction
667
+ */
668
+ function updateOpacity(event: MouseEvent) {
669
+ if (!opacitySliderRef) return;
670
+
671
+ const rect = opacitySliderRef.getBoundingClientRect();
672
+ const x = event.clientX - rect.left;
673
+ const width = rect.width;
674
+
675
+ let newOpacity = Math.max(0, Math.min(x, width)) / width;
676
+ newOpacity = Math.round(newOpacity * 100) / 100;
677
+
678
+ try {
679
+ isInternalUpdate = true;
680
+ opacity = newOpacity; // This will trigger the reactive statement
681
+ rgb = { ...rgb, a: newOpacity };
682
+ lastKnownOpacity = newOpacity;
683
+ const hexValue = `#${Math.round(rgb.r * 255)
684
+ .toString(16)
685
+ .padStart(2, '0')}${Math.round(rgb.g * 255)
686
+ .toString(16)
687
+ .padStart(2, '0')}${Math.round(rgb.b * 255)
688
+ .toString(16)
689
+ .padStart(2, '0')}`;
690
+ value = hexValue;
691
+ hexInput = hexValue;
692
+ previewColor = getRgbaColor();
693
+ onChange(hexValue);
694
+ onOpacityChange(newOpacity); // Call the opacity change handler
695
+ } finally {
696
+ isInternalUpdate = false;
697
+ }
698
+ }
699
+
700
+ /**
701
+ * Updates opacity from numeric input
702
+ * - Validates input range (0-100)
703
+ * - Converts percentage to decimal
704
+ * - Updates all color states
705
+ * - Maintains color consistency
706
+ * - Prevents invalid states
707
+ * @param event - Input event from the numeric opacity field
708
+ */
709
+ function updateOpacityFromInput(event: Event) {
710
+ const input = event.target as HTMLInputElement;
711
+ input.value = input.value.replace(/[^\d]/g, '').slice(0, 3);
712
+
713
+ let num = parseInt(input.value);
714
+ if (isNaN(num) || input.value === '') num = 0;
715
+ if (num > 100) num = 100;
716
+
717
+ input.value = num.toString();
718
+ opacityPercentage = num;
719
+
720
+ try {
721
+ isInternalUpdate = true;
722
+ lastKnownOpacity = num / 100;
723
+ rgb = { ...rgb, a: num / 100 };
724
+ // Only use the 6-character hex without alpha
725
+ const hexValue = `#${Math.round(rgb.r * 255)
726
+ .toString(16)
727
+ .padStart(2, '0')}${Math.round(rgb.g * 255)
728
+ .toString(16)
729
+ .padStart(2, '0')}${Math.round(rgb.b * 255)
730
+ .toString(16)
731
+ .padStart(2, '0')}`;
732
+ value = hexValue;
733
+ hexInput = hexValue;
734
+ previewColor = getRgbaColor();
735
+ onChange(hexValue);
736
+ } finally {
737
+ isInternalUpdate = false;
738
+ }
739
+ }
740
+
741
+ // Reactive statement to calculate opacity percentage
742
+ $: opacityPercentage = Math.round(lastKnownOpacity * 100);
743
+
744
+ let lastKnownHue = 0;
745
+ let colorSelectRef: ColorSelect; // Reference to ColorSelect component
746
+
747
+ /**
748
+ * Converts HSV to RGB values
749
+ * @param h - Hue value
750
+ * @param s - Saturation value
751
+ * @param v - Value (brightness) value
752
+ * @returns RGB color object with normalized values
753
+ */
754
+ function hsvToRgb(h: number, s: number, v: number) {
755
+ const f = (n: number, k = (n + h / 60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0);
756
+ return {
757
+ r: Math.round(f(5) * 255) / 255,
758
+ g: Math.round(f(3) * 255) / 255,
759
+ b: Math.round(f(1) * 255) / 255,
760
+ a: lastKnownOpacity
761
+ };
762
+ }
763
+
764
+ /**
765
+ * Logs color-related events for debugging purposes
766
+ * @param event - Custom event from color picker interactions
767
+ */
768
+ function onColorEvent(event: CustomEvent) {
769
+ // Safe logging that won't throw errors
770
+ // console.log('Color event received:', {
771
+ // type: event.type,
772
+ // rgb: event.detail?.rgb || rgb,
773
+ // mode: event.detail?.mode,
774
+ // rawEvent: {
775
+ // detail: event.detail,
776
+ // target: event.target ? 'exists' : 'null',
777
+ // currentTarget: event.currentTarget ? 'exists' : 'null'
778
+ // }
779
+ // });
780
+ }
781
+
782
+ /**
783
+ * Handles direct hue changes from the color picker
784
+ * @param event - Custom event containing hue information
785
+ */
786
+ function handleHueChange(event: CustomEvent) {
787
+ // console.log('Hue change event:', event.detail);
788
+ try {
789
+ isInternalUpdate = true;
790
+ lastKnownHue = event.detail.h;
791
+
792
+ // Convert HSV to RGB using current saturation and value
793
+ const newRgb = hsvToRgb(
794
+ lastKnownHue,
795
+ 1, // Full saturation for testing
796
+ 1 // Full value for testing
797
+ );
798
+
799
+ rgb = newRgb;
800
+ handleColorChange();
801
+
802
+ // console.log('After hue change:', {
803
+ // hue: lastKnownHue,
804
+ // rgb: newRgb,
805
+ // hexValue: rgbaToHex(newRgb.r, newRgb.g, newRgb.b, lastKnownOpacity)
806
+ // });
807
+ } finally {
808
+ isInternalUpdate = false;
809
+ }
810
+ }
811
+
812
+ let dragState = {
813
+ isHueDragging: false,
814
+ isOpacityDragging: false,
815
+ isColorDragging: false
816
+ };
817
+
818
+ /**
819
+ * Manages drag state across different interactions
820
+ * Prevents race conditions and maintains consistent state
821
+ * Handles cleanup on component destruction
822
+ * @param event - Mouse event from global interactions
823
+ */
824
+ function handleGlobalMouseUp(event: MouseEvent) {
825
+ if (!open) return;
826
+
827
+ // console.log('Global mouseup triggered', dragState);
828
+ if (dragState.isHueDragging || dragState.isOpacityDragging || dragState.isColorDragging) {
829
+ dragState = {
830
+ isHueDragging: false,
831
+ isOpacityDragging: false,
832
+ isColorDragging: false
833
+ };
834
+ handleColorChange();
835
+ // console.log('Dragging stopped');
836
+ }
837
+ }
838
+
839
+ /**
840
+ * Handles global mouse move events during dragging
841
+ * @param event - Mouse move event
842
+ */
843
+ function handleGlobalMouseMove(event: MouseEvent) {
844
+ if (dragState.isHueDragging || dragState.isOpacityDragging || dragState.isColorDragging) {
845
+ // console.log('Moving while dragging:', {
846
+ // type: dragState.isHueDragging ? 'hue' :
847
+ // dragState.isOpacityDragging ? 'opacity' : 'color',
848
+ // event: event
849
+ // });
850
+ handleColorChange();
851
+ }
852
+ }
853
+
854
+ /**
855
+ * Determines the type of drag based on mouse interaction
856
+ * @param event - Mouse down event initiating drag
857
+ */
858
+ function handleDragStart(event: MouseEvent) {
859
+ const target = event.target as HTMLElement;
860
+ const rect = target.getBoundingClientRect();
861
+ const parentRect = target.parentElement?.getBoundingClientRect();
862
+
863
+ // Log all relevant information for debugging
864
+ // console.log('Mousedown details:', {
865
+ // element: target,
866
+ // rect: rect,
867
+ // parentRect: parentRect,
868
+ // style: target.getAttribute('style'),
869
+ // parentStyle: target.parentElement?.getAttribute('style')
870
+ // });
871
+
872
+ // Check if it's a canvas element
873
+ if (target.tagName.toLowerCase() === 'canvas') {
874
+ // Get the computed style to check positioning
875
+ const computedStyle = window.getComputedStyle(target);
876
+ const top = parseInt(computedStyle.top);
877
+
878
+ if (rect.width === 31 && rect.height === 256) {
879
+ if (top < 50) {
880
+ // Hue slider is typically at the top
881
+ dragState.isHueDragging = true;
882
+ // console.log('Hue drag started (top slider)');
883
+ } else {
884
+ // Opacity slider is typically at the bottom
885
+ dragState.isOpacityDragging = true;
886
+ // console.log('Opacity drag started (bottom slider)');
887
+ }
888
+ } else {
889
+ dragState.isColorDragging = true;
890
+ // console.log('Color drag started (main area)');
891
+ }
892
+ }
893
+
894
+ // console.log('Current drag state:', dragState);
895
+ }
896
+
897
+ /**
898
+ * Initializes component state
899
+ * - Normalizes initial color value
900
+ * - Sets up event listeners
901
+ * - Configures opacity handling
902
+ * - Initializes recent colors
903
+ */
904
+ function initializeColor() {
905
+ const normalizedHex = normalizeHexInput(value);
906
+ if (normalizedHex.startsWith('#')) {
907
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(normalizedHex);
908
+ if (result) {
909
+ const r = parseInt(result[1], 16) / 255;
910
+ const g = parseInt(result[2], 16) / 255;
911
+ const b = parseInt(result[3], 16) / 255;
912
+
913
+ rgb = {
914
+ // r: r === 0 ? 0.000001 : r, // Prevent zero opacity issues
915
+ r: r,
916
+ g: g,
917
+ b: b,
918
+ a: lastKnownOpacity
919
+ };
920
+
921
+ // Set initial display values
922
+ hexInput = normalizedHex;
923
+ previewColor = getRgbaColor();
924
+
925
+ // console.log('Color initialized:', {
926
+ // hex: normalizedHex,
927
+ // rgb,
928
+ // opacity: lastKnownOpacity,
929
+ // percentage: opacityPercentage
930
+ // });
931
+ }
932
+ }
933
+ }
934
+
935
+ /**
936
+ * Generates an RGBA color string for CSS
937
+ * @returns RGBA color string based on current RGB and opacity
938
+ */
939
+ function getRgbaColor() {
940
+ const r = Math.round(rgb.r * 255);
941
+ const g = Math.round(rgb.g * 255);
942
+ const b = Math.round(rgb.b * 255);
943
+ return `rgba(${r}, ${g}, ${b}, ${lastKnownOpacity})`;
944
+ }
945
+
946
+ // Make previewColor reactive so it updates instantly whenever rgb or opacity change
947
+ $: previewColor = getRgbaColor();
948
+
949
+ /**
950
+ * Handles keydown events within the popover for modifier keys
951
+ * @param event - Keyboard event
952
+ */
953
+ function handlePopupKeyDown(event: KeyboardEvent) {
954
+ // Only handle keys if the popup is open
955
+ if (!open) return;
956
+
957
+ if (event.key === 'Shift' || event.key === ' ') {
958
+ event.preventDefault(); // Prevent space from scrolling
959
+
960
+ if (event.key === 'Shift') {
961
+ isShiftPressed = true;
962
+ } else if (event.key === ' ') {
963
+ isSpacePressed = true;
964
+ }
965
+
966
+ if (recentColors.length === 0) {
967
+ showNoRecentMessage = true;
968
+ setTimeout(() => {
969
+ showNoRecentMessage = false;
970
+ }, 2000);
971
+ }
972
+ }
973
+ }
974
+
975
+ /**
976
+ * Handles keyup events within the popover to reset modifier keys
977
+ * @param event - Keyboard event
978
+ */
979
+ function handlePopupKeyUp(event: KeyboardEvent) {
980
+ // Only handle keys if the popup is open
981
+ if (!open) return;
982
+
983
+ if (event.key === 'Shift' || event.key === ' ') {
984
+ if (event.key === 'Shift') {
985
+ isShiftPressed = false;
986
+ } else if (event.key === ' ') {
987
+ isSpacePressed = false;
988
+ }
989
+ }
990
+ }
991
+
992
+ // Stops listening for scrolling (the page and, inside a module, the module's own panels: a scroll never leaves a
993
+ // shadow root, so a listener on the window alone does not hear about those)
994
+ let stopListeningForScroll: () => void = () => {};
995
+
996
+ // Sets up event listeners when the component mounts
997
+ onMount(() => {
998
+ initializeColor();
999
+ window.addEventListener('mouseup', handleGlobalMouseUp);
1000
+ window.addEventListener('mousemove', handleGlobalMouseMove);
1001
+ window.addEventListener('keydown', handlePopupKeyDown);
1002
+ window.addEventListener('keyup', handlePopupKeyUp);
1003
+ stopListeningForScroll = listenForScroll(inputRef, handleScroll);
1004
+ window.addEventListener('widgetic:close-color-pickers', onCloseOtherPickers as EventListener);
1005
+ });
1006
+
1007
+ // Cleans up event listeners when the component is destroyed
1008
+ onDestroy(() => {
1009
+ releaseOpacityPointerStyle?.();
1010
+ releaseOpacityPointerStyle = null;
1011
+ window.removeEventListener('mouseup', handleGlobalMouseUp);
1012
+ window.removeEventListener('mousemove', handleGlobalMouseMove);
1013
+ window.removeEventListener('keydown', handlePopupKeyDown);
1014
+ window.removeEventListener('keyup', handlePopupKeyUp);
1015
+ stopListeningForScroll();
1016
+ window.removeEventListener(
1017
+ 'widgetic:close-color-pickers',
1018
+ onCloseOtherPickers as EventListener
1019
+ );
1020
+ });
1021
+
1022
+ // Then handle opacity updates
1023
+ $: {
1024
+ if (value) {
1025
+ if (value.startsWith('rgba')) {
1026
+ const matches = value.match(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)/);
1027
+ if (matches) {
1028
+ const [_, r, g, b, a] = matches;
1029
+ rgb = {
1030
+ r: parseInt(r) / 255,
1031
+ g: parseInt(g) / 255,
1032
+ b: parseInt(b) / 255,
1033
+ a: parseFloat(a)
1034
+ };
1035
+ opacityValue = parseFloat(a);
1036
+ opacityPercentage = Math.round(opacityValue * 100);
1037
+ }
1038
+ } else if (value.startsWith('#') && value.length === 9) {
1039
+ const alpha = parseInt(value.slice(7), 16);
1040
+ opacityValue = alpha / 255;
1041
+ opacityPercentage = Math.round(opacityValue * 100);
1042
+ rgb.a = opacityValue;
1043
+ }
1044
+ }
1045
+ }
1046
+
1047
+ /**
1048
+ * Saves a color to the recent colors list
1049
+ * - Prevents duplicates by checking the most recent entry
1050
+ * - Maintains storage limits through utility functions
1051
+ * @param color - Hexadecimal color string
1052
+ * @param alpha - Opacity value of the color
1053
+ */
1054
+ function saveToRecentColors(color: string, alpha: number) {
1055
+ if (!saveRecentColors) {
1056
+ // console.log('Recent colors saving is disabled');
1057
+ return;
1058
+ }
1059
+
1060
+ // Check if this exact color+alpha combination is already the most recent
1061
+ const currentRecents = recentColorsUtil.getRecentColors();
1062
+ // console.log('Current recent colors:', currentRecents);
1063
+
1064
+ const mostRecent = currentRecents[0];
1065
+
1066
+ if (
1067
+ mostRecent &&
1068
+ mostRecent.color.toLowerCase() === color.toLowerCase() &&
1069
+ mostRecent.alpha === alpha
1070
+ ) {
1071
+ // console.log('Color already most recent, skipping save:', { color, alpha });
1072
+ return;
1073
+ }
1074
+
1075
+ // console.log('Saving new color to recent colors:', { color, alpha });
1076
+ recentColors = recentColorsUtil.addRecentColor(color, alpha);
1077
+ // console.log('Updated recent colors list:', recentColors);
1078
+ }
1079
+
1080
+ /**
1081
+ * Handles the selection of a color name from suggestions
1082
+ * @param colorName - Selected color name
1083
+ */
1084
+ function handleColorNameSelection(colorName: string) {
1085
+ const colorValue = colorNames[colorName];
1086
+ value = colorValue;
1087
+ const newRgb = hexToRgba(colorValue);
1088
+ rgb = { ...newRgb, a: lastKnownOpacity };
1089
+ previewColor = getRgbaColor();
1090
+ onChange(colorValue);
1091
+ suggestionVisible = false;
1092
+ currentSuggestion = null;
1093
+
1094
+ // Save the selected color name
1095
+ saveToRecentColors(colorValue, lastKnownOpacity);
1096
+ }
1097
+
1098
+ /**
1099
+ * Handles click events on color suggestions
1100
+ * @param match - The matched color name clicked by the user
1101
+ */
1102
+ function handleSuggestionClick(match: string) {
1103
+ // console.log('Color name selected:', match);
1104
+ hexInput = match;
1105
+ const colorValue = colorNames[match];
1106
+ // console.log('Converting color name to hex:', { name: match, hex: colorValue });
1107
+
1108
+ value = colorValue;
1109
+ const newRgb = hexToRgba(colorValue);
1110
+ rgb = { ...newRgb, a: lastKnownOpacity };
1111
+ previewColor = getRgbaColor();
1112
+ onChange(colorValue);
1113
+ suggestionVisible = false;
1114
+ currentSuggestion = null;
1115
+
1116
+ // Save the hex value of the selected color name
1117
+ saveToRecentColors(colorValue, lastKnownOpacity);
1118
+ }
1119
+
1120
+ /**
1121
+ * Handles blur events on the hex input field to restore color if input is empty
1122
+ * @param event - Focus event from the input field
1123
+ */
1124
+ function handleInputBlur(event: FocusEvent) {
1125
+ // Get the related target (element receiving focus)
1126
+ const relatedTarget = event.relatedTarget as HTMLElement;
1127
+
1128
+ // Don't close if focus is moving to a suggestion item
1129
+ if (relatedTarget?.closest('.color-suggestions')) {
1130
+ return;
1131
+ }
1132
+
1133
+ const input = event.target as HTMLInputElement;
1134
+ const currentInputValue = input.value;
1135
+
1136
+ // Close suggestions
1137
+ closeAutosuggestions();
1138
+
1139
+ // Check actual input value
1140
+ if (!currentInputValue.trim()) {
1141
+ restoreCurrentColor();
1142
+ }
1143
+ }
1144
+
1145
+ let inputRef: HTMLDivElement;
1146
+
1147
+ /**
1148
+ * Restores the current color value when input is invalid or empty
1149
+ * - Resets the hex input to the last valid color value
1150
+ * - Forces the input field to update and regain focus
1151
+ */
1152
+ function restoreCurrentColor() {
1153
+ // console.log('Restoring current color:', {
1154
+ // currentValue: value,
1155
+ // hexToRestore: value.slice(0, 7),
1156
+ // currentHexInput: hexInput
1157
+ // });
1158
+
1159
+ if (value && value.startsWith('#')) {
1160
+ const colorToRestore = value.slice(0, 7);
1161
+
1162
+ // Force immediate update
1163
+ hexInput = colorToRestore;
1164
+ value = colorToRestore;
1165
+
1166
+ // Force input focus and update
1167
+ setTimeout(() => {
1168
+ const inputElement = inputRef?.querySelector('input') as HTMLInputElement;
1169
+ if (inputElement) {
1170
+ inputElement.value = colorToRestore;
1171
+ inputElement.focus();
1172
+ inputElement.blur();
1173
+ }
1174
+ }, 0);
1175
+ }
1176
+ }
1177
+
1178
+ // Exported onFocus handler with default no-op
1179
+ export let onFocus: ColorPickerInputControllerProps['onFocus'] = () => {};
1180
+
1181
+ // Sets autofocus on mount if enabled
1182
+ onMount(() => {
1183
+ if (autofocus && inputRef) {
1184
+ inputRef.focus();
1185
+ // console.log('ColorPickerInputController focused');
1186
+ }
1187
+ });
1188
+
1189
+ /**
1190
+ * Focus method to programmatically focus the input field
1191
+ */
1192
+ export function focus() {
1193
+ if (inputRef) {
1194
+ inputRef.focus();
1195
+ // console.log('ColorPickerInputController focus method called');
1196
+ }
1197
+ }
1198
+
1199
+ // Popover visibility is now handled by {#if open} conditional rendering
1200
+
1201
+ // Exported opacity change handler with default no-op
1202
+ export let onOpacityChange: ColorPickerInputControllerProps['onOpacityChange'] = () => {};
1203
+
1204
+ // Add these variables to track input position
1205
+ let inputComponent: any;
1206
+ let inputRect: DOMRect | null = null;
1207
+
1208
+ // Track trigger position for fixed-position popover
1209
+ let triggerRef: HTMLDivElement;
1210
+ let popoverStyle = '';
1211
+
1212
+ function updatePopoverPosition() {
1213
+ if (!triggerRef) return;
1214
+ const rect = triggerRef.getBoundingClientRect();
1215
+ // Guard: if trigger hasn't been laid out yet, defer
1216
+ if (rect.width === 0 && rect.height === 0) {
1217
+ requestAnimationFrame(updatePopoverPosition);
1218
+ return;
1219
+ }
1220
+ const popoverHeight = 420;
1221
+ const spaceBelow = window.innerHeight - rect.bottom;
1222
+ const spaceAbove = rect.top;
1223
+ const openAbove = spaceBelow < popoverHeight + 8 && spaceAbove > popoverHeight + 8;
1224
+ const top = openAbove ? Math.round(rect.top - popoverHeight - 8) : Math.round(rect.bottom + 8);
1225
+ // Align the popup's end edge with the end edge of the full input container: the right edge on a left to right screen,
1226
+ // the left edge on a right to left one (the popup itself is a drawing, drawn left to right, and opens toward the inside)
1227
+ const inputContainer = triggerRef.closest('.color-input-main-container') as HTMLElement | null;
1228
+ const containerRect = inputContainer ? inputContainer.getBoundingClientRect() : rect;
1229
+ if ($textDirection === 'rtl') {
1230
+ popoverStyle = `top: ${top}px; left: ${Math.round(containerRect.left)}px;`; // rtl-ok: the end edge of a right to left field is its left edge
1231
+ } else {
1232
+ const right = Math.round(window.innerWidth - containerRect.right);
1233
+ popoverStyle = `top: ${top}px; right: ${right}px;`; // rtl-ok: the end edge of a left to right field is its right edge
1234
+ }
1235
+ }
1236
+
1237
+ // Position is calculated in handleToggle after tick()
1238
+
1239
+ // Update the position function to get the actual input element
1240
+ function updateInputPosition() {
1241
+ // Get the actual input element from the component
1242
+ // console.log('updateInputPosition', inputRef);
1243
+ const inputElement = inputRef?.querySelector('input');
1244
+ if (inputElement) {
1245
+ inputRect = inputElement.getBoundingClientRect();
1246
+ // console.log('inputRect', inputRect);
1247
+ }
1248
+ }
1249
+
1250
+ // Update the suggestions position when they become visible
1251
+ $: if (suggestionVisible) {
1252
+ updateInputPosition();
1253
+ }
1254
+
1255
+ // Close suggestions when picker is closed
1256
+ $: if (!open) {
1257
+ suggestionVisible = false;
1258
+ currentSuggestion = null;
1259
+ if (isColorSelectOpen) {
1260
+ dispatch('colorselectmodalclose');
1261
+ isColorSelectOpen = false;
1262
+ }
1263
+ }
1264
+
1265
+ // Add this near the top with other state declarations
1266
+ let isColorSelectOpen = false;
1267
+
1268
+ // Add these computed styles for layout
1269
+ $: opacityBarWidthPx = `${pickerSize}px`;
1270
+ $: recentColorsMaxWidth = `${pickerSize + sliderWidth}px`;
1247
1271
  </script>
1248
1272
 
1249
1273
  <!-- Color Picker Input Controller Container -->
1250
- <div class="color-picker-input-controller-ct flex flex-col gap-2 widgetic-colors">
1251
- <div class="flex items-center w-full relative">
1252
-
1253
- <!-- Input Controller Header -->
1254
- <div class="input-controller-header-ct flex-1 min-w-0">
1255
- <InputControllerHeader {label} helpText={helpText} />
1256
- </div>
1257
-
1258
- <!-- Input Controller Container -->
1259
- <div class="input-controller-ct absolute end-0">
1260
- <div class="color-input-main-container rounded-large flex items-center transition-colors duration-200"
1261
- style="height: 48px; width: 185px; background: hsl(var(--grey1)); {showRing ? 'border: 1px solid hsl(var(--grey2));' : ''}">
1262
- <div class="flex items-center w-full justify-between" style="padding-inline-end: 12px;">
1263
-
1264
- <!-- Hex Input Container -->
1265
- <div class="hex-input-container flex-1" bind:this={inputRef}>
1266
- <!-- A colour code (#FF00AA) is read left to right on every screen: in a right to left line its "#" would end up at the wrong end -->
1267
- <Input
1268
- bind:this={inputComponent}
1269
- type="text"
1270
- dir="ltr"
1271
- class="h-9 border-0 bg-transparent subtext text-grey7 placeholder:text-grey3 focus-visible:ring-0 focus-visible:ring-offset-0 ps-4"
1272
- value={hexInput}
1273
- onfocus={(e) => {
1274
- dispatch('focus', e);
1275
- onFocus();
1276
- }}
1277
- onblur={(e) => {
1278
- dispatch('blur', e);
1279
- const input = e.target as HTMLInputElement;
1280
- if (!input.value.trim()) {
1281
- restoreCurrentColor();
1282
- } else {
1283
- handleInputBlur(e);
1284
- }
1285
- }}
1286
- oninput={(e) => {
1287
- const input = e.target as HTMLInputElement;
1288
- if (!input.value) {
1289
- hexInput = '';
1290
- }
1291
- handleHexInput(e);
1292
- updateInputPosition();
1293
- }}
1294
- onkeydown={(e) => {
1295
- const input = e.target as HTMLInputElement;
1296
- if ((e.key === 'Enter' || e.key === 'Escape') && !input.value.trim()) {
1297
- e.preventDefault();
1298
- restoreCurrentColor();
1299
- } else {
1300
- handleKeyDown(e);
1301
- }
1302
- }}
1303
- />
1304
- </div>
1305
-
1306
- <!-- Color Preview Button -->
1307
- <div class="color-preview-button-container relative flex items-center" style="height: 48px;">
1308
- <div class="color-picker-button-content-ct relative">
1309
- <!-- Color Picker Trigger (manual, no bits-ui Popover) -->
1310
- <!-- svelte-ignore a11y_click_events_have_key_events -->
1311
- <!-- svelte-ignore a11y_no_static_element_interactions -->
1312
- <div bind:this={triggerRef}
1313
- class="color-preview-button flex items-center justify-center rounded-small cursor-pointer relative overflow-hidden {showRing ? 'ring-1 ring-grey2' : ''}"
1314
- style="width: 24px; height: 24px; min-width: 24px;"
1315
- role="button"
1316
- tabindex="0"
1317
- onclick={(e) => { e.stopPropagation(); handleToggle(!open); }}
1318
- >
1319
- <CheckerBoardBackground class="absolute inset-0 w-full h-full pointer-events-none rounded-[inherit]" />
1320
- <div class="absolute inset-0 w-full h-full rounded-[inherit] pointer-events-none" style="background-color: {previewColor};"></div>
1321
- </div>
1322
-
1323
- <!-- Color Suggestions Portal -->
1324
- {#if suggestionVisible && currentSuggestion}
1325
- <Portal target={portalTarget} class="color-suggestions-portal">
1326
- {#if currentSuggestion.allMatches.length > 0 && inputRect}
1327
- <!-- svelte-ignore a11y_no_static_element_interactions -->
1328
- <div
1329
- class="color-suggestions fixed bg-white border rounded-md shadow-lg overflow-y-auto"
1330
- style="
1274
+ <!-- Figma IC Color 172:116, Color Picker 211:3877 -->
1275
+ <div class="color-picker-input-controller-ct">
1276
+ <!-- Input Controller Header -->
1277
+ <InputControllerRow {label} {helpText}>
1278
+ <!-- Input Controller Container -->
1279
+ <div
1280
+ class="color-input-main-container flex h-9 w-full items-center gap-2 rounded-lg bg-accent pe-2 ps-3 transition-colors duration-fast hover:bg-accent-hover focus-within:outline-hidden focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background"
1281
+ >
1282
+ <!-- Hex Input Container -->
1283
+ <div class="hex-input-container min-w-0 flex-1" bind:this={inputRef}>
1284
+ <!-- A colour code (#FF00AA) is read left to right on every screen: in a right to left line its "#" would end up at the wrong end -->
1285
+ <Input
1286
+ bind:this={inputComponent}
1287
+ type="text"
1288
+ dir="ltr"
1289
+ class="h-full border-0 bg-transparent p-0 text-body text-foreground placeholder:text-muted-foreground focus-visible:ring-0 focus-visible:ring-offset-0"
1290
+ value={hexInput}
1291
+ onfocus={(e) => {
1292
+ dispatch('focus', e);
1293
+ onFocus();
1294
+ }}
1295
+ onblur={(e) => {
1296
+ dispatch('blur', e);
1297
+ const input = e.target as HTMLInputElement;
1298
+ if (!input.value.trim()) {
1299
+ restoreCurrentColor();
1300
+ } else {
1301
+ handleInputBlur(e);
1302
+ }
1303
+ }}
1304
+ oninput={(e) => {
1305
+ const input = e.target as HTMLInputElement;
1306
+ if (!input.value) {
1307
+ hexInput = '';
1308
+ }
1309
+ handleHexInput(e);
1310
+ updateInputPosition();
1311
+ }}
1312
+ onkeydown={(e) => {
1313
+ const input = e.target as HTMLInputElement;
1314
+ if ((e.key === 'Enter' || e.key === 'Escape') && !input.value.trim()) {
1315
+ e.preventDefault();
1316
+ restoreCurrentColor();
1317
+ } else {
1318
+ handleKeyDown(e);
1319
+ }
1320
+ }}
1321
+ />
1322
+ </div>
1323
+
1324
+ <!-- Color Preview Button -->
1325
+ <div class="color-preview-button-container relative flex shrink-0 items-center">
1326
+ <div class="color-picker-button-content-ct relative">
1327
+ <!-- Color Picker Trigger (manual, no bits-ui Popover) -->
1328
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
1329
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
1330
+ <div
1331
+ bind:this={triggerRef}
1332
+ class="color-preview-button relative flex size-5 shrink-0 cursor-pointer items-center justify-center overflow-hidden rounded-sm border border-border {showRing
1333
+ ? ''
1334
+ : 'border-transparent'}"
1335
+ role="button"
1336
+ tabindex="0"
1337
+ onclick={(e) => {
1338
+ e.stopPropagation();
1339
+ handleToggle(!open);
1340
+ }}
1341
+ >
1342
+ <CheckerBoardBackground
1343
+ className="absolute inset-0 w-full h-full pointer-events-none rounded-[inherit]"
1344
+ />
1345
+ <div
1346
+ class="absolute inset-0 w-full h-full rounded-[inherit] pointer-events-none"
1347
+ style="background-color: {previewColor};"
1348
+ ></div>
1349
+ </div>
1350
+
1351
+ <!-- Color Suggestions Portal -->
1352
+ {#if suggestionVisible && currentSuggestion}
1353
+ <Portal target={portalTarget} class="color-suggestions-portal">
1354
+ {#if currentSuggestion.allMatches.length > 0 && inputRect}
1355
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
1356
+ <div
1357
+ class="color-suggestions fixed overflow-y-auto rounded-xl border border-border bg-popover text-popover-foreground shadow-none"
1358
+ style="
1331
1359
  pointer-events: auto !important;
1332
1360
  z-index: 99999;
1333
1361
  max-height: 12rem;
@@ -1335,197 +1363,213 @@
1335
1363
  left: {inputRect.left}px; /* rtl-ok: the list is as wide as the field it opens from, so its left edge is the field's */
1336
1364
  width: {inputRect.width}px;
1337
1365
  "
1338
- data-allow-scroll="true"
1339
- onscroll={(e) => e.stopPropagation()}
1340
- onmousedown={(event) => {
1341
- event.preventDefault();
1342
- event.stopPropagation();
1343
- const target = event.target as HTMLElement;
1344
- if (target.closest('.color-suggestion-item')) {
1345
- event.preventDefault();
1346
- }
1347
- }}
1348
- onfocusout={(event) => {
1349
- const relatedTarget = event.relatedTarget as HTMLElement;
1350
- // Only close if focus is moving outside the suggestions
1351
- if (!relatedTarget?.closest('.color-suggestions')) {
1352
- closeAutosuggestions();
1353
- }
1354
- }}
1355
- >
1356
- {#each currentSuggestion.allMatches as match, i}
1357
- <div
1358
- class="color-suggestion-item px-2 py-1 cursor-pointer hover:bg-gray-100"
1359
- style="position: relative; z-index: 99999; pointer-events: auto !important;"
1360
- class:bg-gray-100={i === currentSuggestion?.currentIndex}
1361
- onmousedown={(event) => {
1362
- event.preventDefault();
1363
- event.stopPropagation();
1364
- handleColorSelection(match, event.shiftKey);
1365
- }}
1366
- >
1367
- {match}
1368
- </div>
1369
- {/each}
1370
- </div>
1371
- {/if}
1372
- </Portal>
1373
- {/if}
1374
-
1375
- <!-- Color Picker — portaled to a unique body-level div -->
1376
- {#if open}
1377
- <Portal target="color-picker-portal" class="color-picker-portal-ct" style="position: fixed; inset: 0; z-index: 99999; pointer-events: none;">
1378
-
1379
- <!-- svelte-ignore a11y_no_static_element_interactions -->
1380
- <div class="color-picker-backdrop" style="z-index: 1;" onmousedown={() => handleToggle(false)}></div>
1381
-
1382
- <!-- svelte-ignore a11y_no_static_element_interactions -->
1383
- <!-- svelte-ignore a11y_click_events_have_key_events -->
1384
- <div class="color-picker-popover-content w-auto pt-2 pb-2 ps-2 pe-0 widgetic-colors widgetic-radius modal-shadow"
1385
- dir="ltr"
1386
- style="{popoverStyle} border: 1px solid hsl(var(--grey2)); z-index: 2;"
1387
- onmousedown={(e) => e.stopPropagation()}
1388
- onclick={(e) => e.stopPropagation()}
1389
- >
1390
- <!-- Color Picker Popover Content Wrapper -->
1391
- <div class="color-picker-popover-content-wrapper flex flex-col">
1392
-
1393
- <!-- Recent Colors Container -->
1394
- {#if saveRecentColors && (isShiftPressed || isSpacePressed)}
1395
- <div class="recent-colors-container" style="width: {pickerSize + sliderWidth + 14}px; margin-inline-start: 10px; padding-top: 11px; padding-bottom: 8px;">
1396
- {#if recentColors.length > 0}
1397
- <div class="recent-colors-grid" style="display: grid; grid-template-columns: repeat(5, 1fr); width: 100%; gap: {swatchGap}px;">
1398
- {#each recentColors.slice(0, 5) as {color, alpha}, i}
1399
- <button
1400
- class="widgetic-colors rounded-medium relative overflow-hidden animate-recent-color"
1401
- style="width: {swatchSize}px; height: {swatchSize}px; border: 1px solid hsl(var(--forest-green)); animation-delay: {i * 0.05}s"
1402
- onclick={() => {
1403
- try {
1404
- isInternalUpdate = true;
1405
- lastKnownOpacity = showOpacityControls ? alpha : 1;
1406
- const newRgb = hexToRgba(color);
1407
- rgb = { ...newRgb, a: showOpacityControls ? alpha : 1 };
1408
- opacityPercentage = Math.round((showOpacityControls ? alpha : 1) * 100);
1409
- value = color;
1410
- hexInput = color;
1411
- previewColor = getRgbaColor();
1412
- onChange(color);
1413
- } finally {
1414
- isInternalUpdate = false;
1415
- }
1416
- }}
1417
- >
1418
- <CheckerBoardBackground />
1419
- <!-- svelte-ignore element_invalid_self_closing_tag -->
1420
- <div
1421
- class="absolute inset-0"
1422
- style="background-color: {color}; opacity: {showOpacityControls ? alpha : 1};"
1423
- />
1424
- </button>
1425
- {/each}
1426
- </div>
1427
- {:else}
1428
- <div class="text-sm text-gray-500 text-center py-2">
1429
- {$t('editor.color.noRecent')}
1430
- </div>
1431
- {/if}
1432
- </div>
1433
- {/if}
1434
-
1435
- <!-- Color Picker Container (block layout, padded) -->
1436
- <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
1437
- <div
1438
- class="color-picker-wrapper relative flex flex-col"
1439
- role="application"
1440
- aria-label={$t('editor.color.picker')}
1441
- onmousedown={handleDragStart}
1442
- style="padding: 0;"
1443
- >
1444
- <!-- Picker row: 8px left/top padding, 8px right padding for hue bar -->
1445
- <div style="display: flex; flex-direction: row; align-items: flex-start;">
1446
- <ColorSelect
1447
- bind:this={colorSelectRef}
1448
- bind:rgb
1449
- bind:a={lastKnownOpacity}
1450
- onchange={handleColorChange}
1451
- alpha={true}
1452
- {pickerSize}
1453
- {sliderWidth}
1454
- />
1455
- <!-- 8px right padding for hue bar is handled by ColorSelect's sliderWidth prop -->
1456
- </div>
1457
-
1458
- <!-- Opacity bar and number input: horizontal flex row under picker/hue bar -->
1459
- <div style="display: flex; flex-direction: row; align-items: center; margin-top: 4px;">
1460
- <!-- Opacity bar under color picker -->
1461
- <!-- svelte-ignore a11y_no_static_element_interactions -->
1462
- <div
1463
- bind:this={opacitySliderRef}
1464
- class="relative cursor-pointer opacity-slider"
1465
- style="width: {pickerSize}px; height: {sliderWidth}px; margin-inline-start: 10px;"
1466
- onmousedown={handleOpacityMouseDown}
1467
- >
1468
- <div class="absolute inset-0 overflow-hidden">
1469
- <CheckerBoardBackground />
1470
- <div
1471
- class="absolute inset-0"
1472
- style="background: linear-gradient(to right,
1473
- rgba({Math.round(rgb.r * 255)}, {Math.round(rgb.g * 255)}, {Math.round(rgb.b * 255)}, 0) 0%,
1474
- rgba({Math.round(rgb.r * 255)}, {Math.round(rgb.g * 255)}, {Math.round(rgb.b * 255)}, 1) 100%
1366
+ data-allow-scroll="true"
1367
+ onscroll={(e) => e.stopPropagation()}
1368
+ onmousedown={(event) => {
1369
+ event.preventDefault();
1370
+ event.stopPropagation();
1371
+ const target = event.target as HTMLElement;
1372
+ if (target.closest('.color-suggestion-item')) {
1373
+ event.preventDefault();
1374
+ }
1375
+ }}
1376
+ onfocusout={(event) => {
1377
+ const relatedTarget = event.relatedTarget as HTMLElement;
1378
+ // Only close if focus is moving outside the suggestions
1379
+ if (!relatedTarget?.closest('.color-suggestions')) {
1380
+ closeAutosuggestions();
1381
+ }
1382
+ }}
1383
+ >
1384
+ {#each currentSuggestion.allMatches as match, i}
1385
+ <div
1386
+ class="color-suggestion-item flex cursor-pointer items-center gap-2 px-2 py-1.5 text-body transition-colors duration-fast hover:bg-accent {i ===
1387
+ currentSuggestion?.currentIndex
1388
+ ? 'bg-brand-subtle'
1389
+ : ''}"
1390
+ style="position: relative; z-index: 99999; pointer-events: auto !important;"
1391
+ onmousedown={(event) => {
1392
+ event.preventDefault();
1393
+ event.stopPropagation();
1394
+ handleColorSelection(match, event.shiftKey);
1395
+ }}
1396
+ >
1397
+ {match}
1398
+ </div>
1399
+ {/each}
1400
+ </div>
1401
+ {/if}
1402
+ </Portal>
1403
+ {/if}
1404
+
1405
+ <!-- Color Picker — portaled to a unique body-level div -->
1406
+ {#if open}
1407
+ <Portal
1408
+ target="color-picker-portal"
1409
+ class="color-picker-portal-ct"
1410
+ style="position: fixed; inset: 0; z-index: 99999; pointer-events: none;"
1411
+ >
1412
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
1413
+ <div
1414
+ class="color-picker-backdrop"
1415
+ style="z-index: 1;"
1416
+ onmousedown={() => handleToggle(false)}
1417
+ ></div>
1418
+
1419
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
1420
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
1421
+ <div
1422
+ class="color-picker-popover-content w-64 rounded-xl border border-border bg-popover p-3 text-popover-foreground shadow-none"
1423
+ dir="ltr"
1424
+ style="{popoverStyle} z-index: 2;"
1425
+ onmousedown={(e) => e.stopPropagation()}
1426
+ onclick={(e) => e.stopPropagation()}
1427
+ >
1428
+ <!-- Color Picker Popover Content Wrapper -->
1429
+ <div class="color-picker-popover-content-wrapper flex flex-col gap-3">
1430
+ {#if saveRecentColors && (isShiftPressed || isSpacePressed)}
1431
+ <!-- Recent Colors Container -->
1432
+ <div class="recent-colors-container w-full">
1433
+ {#if recentColors.length > 0}
1434
+ <div class="recent-colors-grid grid w-full grid-cols-5 gap-2">
1435
+ {#each recentColors.slice(0, 5) as { color, alpha }, i}
1436
+ <button
1437
+ type="button"
1438
+ class="animate-recent-color relative size-10 overflow-hidden rounded-lg border border-border"
1439
+ style="animation-delay: {i * 0.05}s"
1440
+ onclick={() => {
1441
+ try {
1442
+ isInternalUpdate = true;
1443
+ lastKnownOpacity = showOpacityControls ? alpha : 1;
1444
+ const newRgb = hexToRgba(color);
1445
+ rgb = { ...newRgb, a: showOpacityControls ? alpha : 1 };
1446
+ opacityPercentage = Math.round(
1447
+ (showOpacityControls ? alpha : 1) * 100
1448
+ );
1449
+ value = color;
1450
+ hexInput = color;
1451
+ previewColor = getRgbaColor();
1452
+ onChange(color);
1453
+ } finally {
1454
+ isInternalUpdate = false;
1455
+ }
1456
+ }}
1457
+ >
1458
+ <CheckerBoardBackground />
1459
+ <!-- svelte-ignore element_invalid_self_closing_tag -->
1460
+ <div
1461
+ class="absolute inset-0"
1462
+ style="background-color: {color}; opacity: {showOpacityControls
1463
+ ? alpha
1464
+ : 1};"
1465
+ />
1466
+ </button>
1467
+ {/each}
1468
+ </div>
1469
+ {:else}
1470
+ <p class="py-1 text-center text-body text-muted-foreground">
1471
+ {$t('editor.color.noRecent')}
1472
+ </p>
1473
+ {/if}
1474
+ </div>
1475
+ {/if}
1476
+
1477
+ <!-- Color Picker Container (block layout, padded) -->
1478
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
1479
+ <div
1480
+ class="color-picker-wrapper relative flex flex-col"
1481
+ role="application"
1482
+ aria-label={$t('editor.color.picker')}
1483
+ onmousedown={handleDragStart}
1484
+ style="padding: 0;"
1485
+ >
1486
+ <!-- Picker row: 8px left/top padding, 8px right padding for hue bar -->
1487
+ <div style="display: flex; flex-direction: row; align-items: flex-start;">
1488
+ <ColorSelect
1489
+ bind:this={colorSelectRef}
1490
+ bind:rgb
1491
+ bind:a={lastKnownOpacity}
1492
+ onchange={handleColorChange}
1493
+ alpha={true}
1494
+ {pickerSize}
1495
+ {sliderWidth}
1496
+ />
1497
+ <!-- 8px right padding for hue bar is handled by ColorSelect's sliderWidth prop -->
1498
+ </div>
1499
+
1500
+ <!-- Opacity bar and number input: horizontal flex row under picker/hue bar -->
1501
+ <!-- Opacity bar under color picker -->
1502
+ <div class="flex flex-row items-center gap-2">
1503
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
1504
+ <div
1505
+ bind:this={opacitySliderRef}
1506
+ class="opacity-slider relative h-6 cursor-pointer overflow-visible rounded-lg"
1507
+ style="width: {opacityBarContentWidth}px;"
1508
+ onmousedown={handleOpacityMouseDown}
1509
+ >
1510
+ <div class="absolute inset-0 overflow-hidden rounded-[inherit]">
1511
+ <CheckerBoardBackground className="rounded-[inherit]" />
1512
+ <div
1513
+ class="absolute inset-0"
1514
+ style="background: linear-gradient(to right,
1515
+ rgba({Math.round(rgb.r * 255)}, {Math.round(
1516
+ rgb.g * 255
1517
+ )}, {Math.round(rgb.b * 255)}, 0) 0%,
1518
+ rgba({Math.round(rgb.r * 255)}, {Math.round(
1519
+ rgb.g * 255
1520
+ )}, {Math.round(rgb.b * 255)}, 1) 100%
1475
1521
  );"
1476
- ></div>
1477
- </div>
1478
- <div
1479
- class="opacity-scrub absolute top-0 bottom-0 w-0.5 bg-white cursor-pointer z-20"
1480
- style={verticalLineStyle}
1481
- >
1482
- <OpacitySliderArrows class="opacity-slider-arrows" />
1483
- </div>
1484
- </div>
1485
- <!-- Opacity number input — square, matching swatch size -->
1486
- <div class="opacity-number-ct flex items-center justify-center" style="width: {swatchSize + 6}px; min-width: {swatchSize + 6}px; height: {swatchSize}px; margin-inline-start: 8px;">
1487
- <Input
1488
- type="number"
1489
- min="0"
1490
- max="100"
1491
- class="w-full h-full text-center [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none ring-0 focus:ring-0 shadow-none widgetic-colors subtext"
1492
- style="border: 1px solid hsl(var(--forest-green)); color: hsl(var(--grey7)); padding-inline-start: 8px; padding-inline-end: 0;"
1493
- value={opacityPercentage}
1494
- oninput={(e) => {
1495
- e.stopPropagation();
1496
- updateOpacityFromInput(e);
1497
- }}
1498
- onkeydown={(e) => {
1499
- if (e.key === 'Shift') isShiftPressed = true;
1500
- e.stopPropagation();
1501
- }}
1502
- onkeyup={(e) => {
1503
- if (e.key === 'Shift') isShiftPressed = false;
1504
- e.stopPropagation();
1505
- }}
1506
- onclick={(e) => {
1507
- e.stopPropagation();
1508
- }}
1509
- />
1510
- </div>
1511
- </div>
1512
- </div> <!-- end of color-picker -->
1513
-
1514
- </div> <!-- end of color-picker-popover-content-wrapper -->
1515
- </div>
1516
- </Portal>
1517
- {/if}
1518
- </div>
1519
- </div> <!-- end of color-preview-button-container -->
1520
-
1521
- </div>
1522
- </div>
1523
- </div>
1524
- </div>
1522
+ ></div>
1523
+ </div>
1524
+ <div
1525
+ class="opacity-scrub pointer-events-none absolute top-1/2 z-20 -translate-y-1/2 cursor-pointer rounded-full border-2 border-background bg-background shadow-floating box-border"
1526
+ style="{verticalLineStyle}; width: 8px; height: 32px;"
1527
+ ></div>
1528
+ </div>
1529
+ <!-- Opacity number input — square, matching swatch size -->
1530
+ <div
1531
+ class="opacity-number-ct flex h-8 w-10 shrink-0 items-center justify-center rounded-lg bg-accent"
1532
+ >
1533
+ <Input
1534
+ type="number"
1535
+ min="0"
1536
+ max="100"
1537
+ class="h-full w-full border-0 bg-transparent p-0 text-center text-body text-foreground shadow-none [appearance:textfield] focus-visible:ring-0 focus-visible:ring-offset-0 [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
1538
+ value={opacityPercentage}
1539
+ oninput={(e) => {
1540
+ e.stopPropagation();
1541
+ updateOpacityFromInput(e);
1542
+ }}
1543
+ onkeydown={(e) => {
1544
+ if (e.key === 'Shift') isShiftPressed = true;
1545
+ e.stopPropagation();
1546
+ }}
1547
+ onkeyup={(e) => {
1548
+ if (e.key === 'Shift') isShiftPressed = false;
1549
+ e.stopPropagation();
1550
+ }}
1551
+ onclick={(e) => {
1552
+ e.stopPropagation();
1553
+ }}
1554
+ />
1555
+ </div>
1556
+ </div>
1557
+ </div>
1558
+ <!-- end of color-picker -->
1559
+ </div>
1560
+ <!-- end of color-picker-popover-content-wrapper -->
1561
+ </div>
1562
+ </Portal>
1563
+ {/if}
1564
+ </div>
1565
+ <!-- end of color-preview-button-container -->
1566
+ </div>
1567
+ </div>
1568
+ </InputControllerRow>
1525
1569
  </div>
1526
1570
 
1527
1571
  <style>
1528
- /**
1572
+ /**
1529
1573
  * Component Styling
1530
1574
  * - Manages z-index stacking
1531
1575
  * - Handles drag interactions
@@ -1533,112 +1577,70 @@
1533
1577
  * - Ensures proper event handling
1534
1578
  */
1535
1579
 
1536
- .color-input-main-container:hover {
1537
- border-color: hsl(var(--forest-green)) !important;
1538
- }
1539
-
1540
- /* Add cursor styles for dragging */
1541
- :global(.color-picker-wrapper canvas),
1542
- .opacity-slider {
1543
- cursor: grab !important;
1544
- user-select: none !important;
1545
- }
1546
-
1547
- :global(.color-picker-wrapper canvas:active),
1548
- .opacity-slider:active {
1549
- cursor: grabbing !important;
1550
- user-select: none !important;
1551
- }
1552
-
1553
- /* Prevent cursor from changing during drag */
1554
- :global(.color-picker-wrapper *),
1555
- .opacity-slider * {
1556
- cursor: inherit !important;
1557
- }
1558
-
1559
- /* Add a class when dragging starts */
1560
- .opacity-slider:active * {
1561
- cursor: grabbing !important;
1562
- }
1563
-
1564
- /* Backdrop covers the entire viewport to catch outside clicks */
1565
- .color-picker-backdrop {
1566
- position: fixed;
1567
- inset: 0;
1568
- z-index: 99998;
1569
- pointer-events: auto;
1570
- }
1571
-
1572
- /* Popover content — fixed position relative to viewport */
1573
- .color-picker-popover-content {
1574
- position: fixed;
1575
- z-index: 99999;
1576
- margin: 0;
1577
- padding: 8px;
1578
- background: hsl(var(--grey1));
1579
- border: 1px solid hsl(var(--forest-green));
1580
- border-radius: var(--radius-small);
1581
- box-shadow: 0px 0px 15px 3px rgba(0, 0, 0, 0.1);
1582
- pointer-events: auto;
1583
- }
1584
-
1585
- /* Update input styles */
1586
- :global(input.bg-transparent) {
1587
- background: transparent !important;
1588
- border: none !important;
1589
- }
1590
-
1591
- :global(input.bg-transparent:focus),
1592
- :global(input.bg-transparent:focus-visible) {
1593
- outline: none !important;
1594
- box-shadow: none !important;
1595
- }
1596
-
1597
- /* Update button styles */
1598
- :global(button.rounded-md) {
1599
- border-radius: var(--radius) !important;
1600
- }
1601
-
1602
- /* Ensure opacity slider border is visible */
1603
- :global(.opacity-slider) {
1604
- border: 1px solid hsl(var(--forest-green)) !important;
1605
- }
1606
-
1607
- /* Updated animation for individual recent colors */
1608
- @keyframes zoomIn {
1609
- from {
1610
- transform: scale(0.6);
1611
- opacity: 0;
1612
- }
1613
- to {
1614
- transform: scale(1);
1615
- opacity: 1;
1616
- }
1617
- }
1618
-
1619
- :global(.animate-recent-color) {
1620
- animation: zoomIn 0.2s cubic-bezier(0.34, 1.56, 0.64, 1) backwards;
1621
- transform-origin: center center;
1622
- }
1623
-
1624
- /* Add these styles */
1625
- .color-preview-button {
1626
- outline: none !important;
1627
- box-shadow: none !important;
1628
- }
1629
-
1630
- .color-preview-button:focus {
1631
- outline: none !important;
1632
- box-shadow: none !important;
1633
- }
1634
-
1635
- .color-preview-button::after {
1636
- content: '';
1637
- position: absolute;
1638
- inset: 0;
1639
- border-radius: inherit;
1640
- border: 1px solid hsl(var(--grey3));
1641
- pointer-events: none;
1642
- }
1643
- </style>
1580
+ /* Add cursor styles for dragging */
1581
+ :global(.color-picker-wrapper canvas),
1582
+ .opacity-slider {
1583
+ cursor: grab !important;
1584
+ user-select: none !important;
1585
+ }
1586
+
1587
+ :global(.color-picker-wrapper canvas:active),
1588
+ .opacity-slider:active {
1589
+ cursor: grabbing !important;
1590
+ user-select: none !important;
1591
+ }
1592
+
1593
+ /* Prevent cursor from changing during drag */
1594
+ :global(.color-picker-wrapper *),
1595
+ .opacity-slider * {
1596
+ cursor: inherit !important;
1597
+ }
1598
+
1599
+ /* Add a class when dragging starts */
1600
+ .opacity-slider:active * {
1601
+ cursor: grabbing !important;
1602
+ }
1603
+
1604
+ /* Backdrop covers the entire viewport to catch outside clicks */
1605
+ .color-picker-backdrop {
1606
+ position: fixed;
1607
+ inset: 0;
1608
+ z-index: 99998;
1609
+ pointer-events: auto;
1610
+ }
1611
+
1612
+ /* Popover content — fixed position relative to viewport */
1613
+ .color-picker-popover-content {
1614
+ position: fixed;
1615
+ margin: 0;
1616
+ pointer-events: auto;
1617
+ }
1644
1618
 
1619
+ /* Updated animation for individual recent colors */
1620
+ @keyframes zoomIn {
1621
+ from {
1622
+ transform: scale(0.6);
1623
+ opacity: 0;
1624
+ }
1625
+ to {
1626
+ transform: scale(1);
1627
+ opacity: 1;
1628
+ }
1629
+ }
1630
+
1631
+ :global(.animate-recent-color) {
1632
+ animation: zoomIn 0.2s var(--ease-out, cubic-bezier(0.23, 1, 0.32, 1)) backwards;
1633
+ transform-origin: center center;
1634
+ }
1635
+
1636
+ /* Add these styles */
1637
+ .color-preview-button {
1638
+ outline: none !important;
1639
+ box-shadow: none !important;
1640
+ }
1641
+
1642
+ .color-preview-button:focus {
1643
+ outline: none !important;
1644
+ box-shadow: none !important;
1645
+ }
1646
+ </style>