@widgetic/editor 4.1.13 → 4.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/components/PreviewChromeControls.svelte +15 -21
  2. package/dist/components/WidgetPreview.svelte +136 -105
  3. package/dist/components/color-select/ColorSelect.svelte +203 -224
  4. package/dist/components/color-select/constants.d.ts +4 -2
  5. package/dist/components/color-select/constants.js +4 -2
  6. package/dist/components/color-select/render.js +10 -9
  7. package/dist/components/editors/CompositionEditorApp.svelte +55 -40
  8. package/dist/components/editors/EditLeaseNotice.svelte +44 -33
  9. package/dist/components/editors/EmbedEditor.svelte +133 -259
  10. package/dist/components/editors/PropsEditor.svelte +426 -1333
  11. package/dist/components/editors/props-editor.css +5 -68
  12. package/dist/components/ic/AngleInputController.svelte +202 -277
  13. package/dist/components/ic/BrowserInputController.svelte +813 -803
  14. package/dist/components/ic/CheckboxInputController.svelte +92 -169
  15. package/dist/components/ic/CheckboxInputController.svelte.d.ts +2 -8
  16. package/dist/components/ic/ColorPickerInputController.svelte +1589 -1587
  17. package/dist/components/ic/ColorPickerInputController.svelte.d.ts +3 -3
  18. package/dist/components/ic/DateFieldInputController.svelte +455 -465
  19. package/dist/components/ic/DatePickerInputController.svelte +355 -368
  20. package/dist/components/ic/DatePickerInputController.svelte.d.ts +1 -1
  21. package/dist/components/ic/DropdownInputController.svelte +130 -200
  22. package/dist/components/ic/FixedPositionInputController.svelte +255 -276
  23. package/dist/components/ic/FixedPositionInputController.svelte.d.ts +5 -1
  24. package/dist/components/ic/FontInputController.svelte +2110 -2231
  25. package/dist/components/ic/FontInputController.svelte.d.ts +11 -11
  26. package/dist/components/ic/InputControllerHeader.svelte +141 -147
  27. package/dist/components/ic/InputControllerRenderer.svelte +5 -1
  28. package/dist/components/ic/InputControllerRenderer.svelte.d.ts +2 -1
  29. package/dist/components/ic/InputControllerRow.svelte +74 -0
  30. package/dist/components/ic/InputControllerRow.svelte.d.ts +14 -0
  31. package/dist/components/ic/KnowledgeDocumentsInputController.svelte +401 -0
  32. package/dist/components/ic/KnowledgeDocumentsInputController.svelte.d.ts +11 -0
  33. package/dist/components/ic/KnowledgeTextForm.svelte +109 -0
  34. package/dist/components/ic/KnowledgeTextForm.svelte.d.ts +15 -0
  35. package/dist/components/ic/NumberControls.svelte +303 -269
  36. package/dist/components/ic/NumberControls.svelte.d.ts +4 -1
  37. package/dist/components/ic/NumberInputController.svelte +361 -301
  38. package/dist/components/ic/NumberInputController.svelte.d.ts +2 -0
  39. package/dist/components/ic/PositionInputController.svelte +253 -176
  40. package/dist/components/ic/PositionInputController.svelte.d.ts +2 -0
  41. package/dist/components/ic/RadioGroupInputController.svelte +71 -137
  42. package/dist/components/ic/RadioGroupInputController.svelte.d.ts +2 -8
  43. package/dist/components/ic/RangeCalendarInputController.svelte +233 -270
  44. package/dist/components/ic/RangeCalendarInputController.svelte.d.ts +2 -2
  45. package/dist/components/ic/RoundedCornersInputController.svelte +412 -435
  46. package/dist/components/ic/RoundedCornersInputController.svelte.d.ts +2 -0
  47. package/dist/components/ic/SliderInputController.svelte +263 -332
  48. package/dist/components/ic/SliderInputController.svelte.d.ts +1 -1
  49. package/dist/components/ic/SliderRangeInputController.svelte +140 -144
  50. package/dist/components/ic/SliderRangeInputController.svelte.d.ts +3 -3
  51. package/dist/components/ic/SwitchInputController.svelte +47 -109
  52. package/dist/components/ic/TagsInputController.svelte +95 -110
  53. package/dist/components/ic/TextAreaInputController.svelte +1794 -1935
  54. package/dist/components/ic/TextAreaPreviewInputController.svelte +436 -438
  55. package/dist/components/ic/TextAreaPreviewInputController.svelte.d.ts +2 -2
  56. package/dist/components/ic/TextInputController.svelte +65 -75
  57. package/dist/components/ic/TextInputController.svelte.d.ts +2 -0
  58. package/dist/components/ic/TimeInputController.svelte +433 -431
  59. package/dist/components/ic/VectorInputController.svelte +1833 -1831
  60. package/dist/components/ic/VectorInputController.svelte.d.ts +10 -10
  61. package/dist/components/ic/index.d.ts +2 -0
  62. package/dist/components/ic/index.js +2 -0
  63. package/dist/components/ic/shared/CategoryTabs.svelte +28 -35
  64. package/dist/components/ic/shared/ItemGrid.svelte +145 -179
  65. package/dist/components/ic/shared/RecentItemsSection.svelte +208 -271
  66. package/dist/components/ic/shared/RecentItemsSection.svelte.d.ts +1 -1
  67. package/dist/components/ui/arrows/OpacitySliderArrows.svelte +23 -38
  68. package/dist/components/ui/arrows/OpacitySliderArrows.svelte.d.ts +1 -4
  69. package/dist/components/ui/calendar-editor-fit/EditorCalendarStyles.svelte +45 -0
  70. package/dist/components/ui/calendar-editor-fit/EditorCalendarStyles.svelte.d.ts +26 -0
  71. package/dist/components/ui/checkerboard-background/CheckerboardBackground.svelte +20 -12
  72. package/dist/components/ui/shadow-picker-host/ShadowPickerHost.svelte +39 -0
  73. package/dist/components/ui/shadow-picker-host/ShadowPickerHost.svelte.d.ts +10 -0
  74. package/dist/composition/compositionApi.d.ts +21 -1
  75. package/dist/composition/compositionApi.js +64 -5
  76. package/dist/composition/knowledgeDocuments.d.ts +90 -0
  77. package/dist/composition/knowledgeDocuments.js +94 -0
  78. package/dist/composition/knowledgeDocumentsPanel.d.ts +152 -0
  79. package/dist/composition/knowledgeDocumentsPanel.js +443 -0
  80. package/dist/i18n/language.d.ts +86 -36
  81. package/dist/i18n/messages.d.ts +97 -34
  82. package/dist/i18n/messages.js +104 -34
  83. package/dist/i18n/translate.d.ts +1 -1
  84. package/dist/index.d.ts +1 -0
  85. package/dist/knowledgeDocumentsContext.d.ts +10 -0
  86. package/dist/knowledgeDocumentsContext.js +31 -0
  87. package/dist/utils.d.ts +7 -0
  88. package/dist/utils.js +26 -2
  89. package/package.json +4 -4
@@ -23,1957 +23,1816 @@
23
23
  -->
24
24
 
25
25
  <script module lang="ts">
26
- import type { InputControllerConfig } from './index';
27
-
28
- /** Declared props contract — the instance script's $props() below is
29
- * annotated from it so the interface cannot drift from what is read. */
30
- export interface TextAreaInputControllerProps {
31
- class?: string;
32
- label: string;
33
- value: string;
34
- onChange: (newValue: string) => void;
35
- config?: InputControllerConfig;
36
- description?: string;
37
- onFocus?: () => void;
38
- onClose?: () => void;
39
- }
26
+ import type { InputControllerConfig } from './index';
27
+
28
+ /** Declared props contract — the instance script's $props() below is
29
+ * annotated from it so the interface cannot drift from what is read. */
30
+ export interface TextAreaInputControllerProps {
31
+ class?: string;
32
+ label: string;
33
+ value: string;
34
+ onChange: (newValue: string) => void;
35
+ config?: InputControllerConfig;
36
+ description?: string;
37
+ onFocus?: () => void;
38
+ onClose?: () => void;
39
+ }
40
40
  </script>
41
41
 
42
42
  <script lang="ts">
43
- // Svelte imports
44
- import { onMount, onDestroy } from 'svelte';
45
- import { writable } from 'svelte/store';
46
- import type { ComponentEvents } from 'svelte';
47
-
48
-
49
- // Import Shadcn UI components
50
- import { Button, ToggleGroup, Popover, Command } from '@widgetic/design-system/components';
51
-
52
- // Import Lucide Icons
53
- import {
54
- IconBrush,
55
- IconBold,
56
- IconItalic,
57
- IconUnderline,
58
- IconLink,
59
- ChevronDown,
60
- X,
61
- IconPilcrow,
62
- IconList,
63
- IconListNumbers,
64
- IconListCheck
65
- } from '@widgetic/design-system/icons';
66
-
67
-
68
- // Import Shad Editor
69
- import { ShadEditor, type TipTapEditor, type TipTapEditorLevel } from '@widgetic/design-system/shad-editor';
70
-
71
- // The words of the editor in the language of the page, and the share of them that belongs to the rich text editor below.
72
- import { useEditorLanguage } from '../../i18n/language';
73
- import type { EditorMessageKey } from '../../i18n/messages';
74
-
75
- // Add local ColorPickerInputController import
76
- import ColorPickerInputController from './ColorPickerInputController.svelte';
77
-
78
- // Looking things up and listening for scrolling in the tree the editor is in (a module has a shadow root)
79
- import { isEventInside, listenForScroll, queryAllInTreeOf, queryInTreeOf } from '../../utils/shadowDom';
80
-
81
- // Add this constant for the decoration type
82
- const TRANSITION_DURATION = 250;
83
-
84
- /**
85
- * Component props
86
- */
87
- let {
88
- class: className = '',
89
- label,
90
- value = $bindable(''),
91
- onChange,
92
- config = {},
93
- description = undefined,
94
- onFocus = () => {},
95
- onClose = undefined
96
- }: TextAreaInputControllerProps = $props();
97
-
98
- // Use config values with fallbacks
99
- const textColor = $derived(config.textColor || '#1a1a1a');
100
-
101
- const { t, shadEditor: shadEditorLanguage } = useEditorLanguage();
102
-
103
- /**
104
- * State Variables
105
- */
106
- let isInitialMount = $state(false); // Tracks initial component mounting to prevent unnecessary updates
107
- let editorInstance: TipTapEditor | null = null; // Reference to TipTap editor instance
108
- let textStyleDropdownOpen = $state(false); // Controls visibility of text style dropdown
109
- let listStyleDropdownOpen = $state(false);
110
- /**
111
- * Format Tracking
112
- * Maintains active format states for toolbar UI:
113
- * - Prevents invalid format combinations
114
- * - Updates reactively with selection changes
115
- * - Syncs with editor commands
116
- */
117
- // Add type definition for formats
118
- type FormatType = 'bold' | 'italic' | 'underline' | 'link';
119
- type ActiveFormats = Record<FormatType, boolean>;
120
- type FormatMapping = Record<FormatType, { value: string; icon: any; messageKey: EditorMessageKey }>;
121
-
122
- let activeFormats = $state<ActiveFormats>({
123
- bold: false,
124
- italic: false,
125
- underline: false,
126
- link: false
127
- });
128
-
129
- const formatMapping: FormatMapping = {
130
- bold: { value: 'b', icon: IconBold, messageKey: 'editor.textArea.toggleBold' },
131
- italic: { value: 'i', icon: IconItalic, messageKey: 'editor.textArea.toggleItalic' },
132
- underline: { value: 'u', icon: IconUnderline, messageKey: 'editor.textArea.toggleUnderline' },
133
- link: { value: 'link', icon: IconLink, messageKey: 'editor.textArea.toggleLink' }
134
- };
135
-
136
- let currentTextStyle = $state('text'); // Track current text style
137
-
138
- let showColorPicker = $state(false);
139
- let currentColor = $derived(textColor);
140
- let selectedTextRange: { from: number, to: number } | null = $state(null);
141
-
142
- // Each option is shown by its message (`messageKey`), in the language of the page.
143
- const textOptions: { value: string; messageKey: EditorMessageKey; icon?: any }[] = [
144
- { value: 'text', messageKey: 'editor.textArea.paragraph', icon: IconPilcrow },
145
- { value: 'h1', messageKey: 'editor.textArea.heading1' },
146
- { value: 'h2', messageKey: 'editor.textArea.heading2' },
147
- { value: 'h3', messageKey: 'editor.textArea.heading3' }
148
- ];
149
-
150
- /** The message of the style the toolbar button shows: the plain text's when the style is none of the options. */
151
- let currentTextStyleMessageKey = $derived<EditorMessageKey>(
152
- textOptions.find((option) => option.value === currentTextStyle)?.messageKey ?? 'editor.textArea.text'
153
- );
154
-
155
- const listOptions: { value: string; messageKey: EditorMessageKey; icon?: any }[] = [
156
- { value: 'bulletList', messageKey: 'editor.textArea.bulletList', icon: IconList },
157
- { value: 'orderedList', messageKey: 'editor.textArea.numberedList', icon: IconListNumbers },
158
- { value: 'checkList', messageKey: 'editor.textArea.checkList', icon: IconListCheck }
159
- ];
160
-
161
- const content = writable(value);
162
-
163
- // Create a store for managing dropdowns
164
- const openDropdowns = writable<Set<string>>(new Set());
165
-
166
- function toggleDropdown(id: string) {
167
- openDropdowns.update(set => {
168
- if (set.has(id)) {
169
- set.delete(id);
170
- } else {
171
- set.add(id);
172
- }
173
- return set;
174
- });
175
- }
176
-
177
- // Add these variables to track focus state
178
- let editorHasFocus = $state(false);
179
- let toolbarRef: HTMLDivElement;
180
-
181
-
182
-
183
- // Static styles — avoid $derived so teardown does not leave inert derived reads.
184
- const editorStyle = `
43
+ // Svelte imports
44
+ import { onMount, onDestroy } from 'svelte';
45
+ import { writable } from 'svelte/store';
46
+ import type { ComponentEvents } from 'svelte';
47
+
48
+ // Import Shadcn UI components
49
+ import {
50
+ Button,
51
+ ToggleGroup,
52
+ Popover,
53
+ Command,
54
+ IconButton
55
+ } from '@widgetic/design-system/components';
56
+ import {
57
+ IconArrowsDiagonalMinimize,
58
+ IconBold,
59
+ IconBrush,
60
+ IconCheck,
61
+ IconChevronDown,
62
+ IconChevronUp,
63
+ IconH1,
64
+ IconH2,
65
+ IconH3,
66
+ IconItalic,
67
+ IconLink,
68
+ IconList,
69
+ IconListCheck,
70
+ IconListNumbers,
71
+ IconPilcrow,
72
+ IconUnderline
73
+ } from '@widgetic/design-system/icons';
74
+
75
+ // Import Shad Editor
76
+ import {
77
+ ShadEditor,
78
+ type TipTapEditor,
79
+ type TipTapEditorLevel
80
+ } from '@widgetic/design-system/shad-editor';
81
+
82
+ // The words of the editor in the language of the page, and the share of them that belongs to the rich text editor below.
83
+ import { useEditorLanguage } from '../../i18n/language';
84
+ import type { EditorMessageKey } from '../../i18n/messages';
85
+
86
+ // Add local ColorPickerInputController import
87
+ import ColorPickerInputController from './ColorPickerInputController.svelte';
88
+
89
+ // Looking things up and listening for scrolling in the tree the editor is in (a module has a shadow root)
90
+ import {
91
+ isEventInside,
92
+ listenForScroll,
93
+ queryAllInTreeOf,
94
+ queryInTreeOf
95
+ } from '../../utils/shadowDom';
96
+
97
+ // Add this constant for the decoration type
98
+ const TRANSITION_DURATION = 250;
99
+
100
+ /**
101
+ * Component props
102
+ */
103
+ let {
104
+ class: className = '',
105
+ label,
106
+ value = $bindable(''),
107
+ onChange,
108
+ config = {},
109
+ description = undefined,
110
+ onFocus = () => {},
111
+ onClose = undefined
112
+ }: TextAreaInputControllerProps = $props();
113
+
114
+ // Use config values with fallbacks
115
+ const textColor = $derived(config.textColor || '#1a1a1a');
116
+
117
+ const { t, shadEditor: shadEditorLanguage } = useEditorLanguage();
118
+
119
+ /**
120
+ * State Variables
121
+ */
122
+ let isInitialMount = $state(false); // Tracks initial component mounting to prevent unnecessary updates
123
+ let editorInstance: TipTapEditor | null = null; // Reference to TipTap editor instance
124
+ let textStyleDropdownOpen = $state(false); // Controls visibility of text style dropdown
125
+ let listStyleDropdownOpen = $state(false);
126
+ /**
127
+ * Format Tracking
128
+ * Maintains active format states for toolbar UI:
129
+ * - Prevents invalid format combinations
130
+ * - Updates reactively with selection changes
131
+ * - Syncs with editor commands
132
+ */
133
+ // Add type definition for formats
134
+ type FormatType = 'bold' | 'italic' | 'underline' | 'link';
135
+ type ActiveFormats = Record<FormatType, boolean>;
136
+ type FormatMapping = Record<
137
+ FormatType,
138
+ { value: string; icon: any; messageKey: EditorMessageKey }
139
+ >;
140
+
141
+ let activeFormats = $state<ActiveFormats>({
142
+ bold: false,
143
+ italic: false,
144
+ underline: false,
145
+ link: false
146
+ });
147
+
148
+ const formatMapping: FormatMapping = {
149
+ bold: { value: 'b', icon: IconBold, messageKey: 'editor.textArea.toggleBold' },
150
+ italic: { value: 'i', icon: IconItalic, messageKey: 'editor.textArea.toggleItalic' },
151
+ underline: { value: 'u', icon: IconUnderline, messageKey: 'editor.textArea.toggleUnderline' },
152
+ link: { value: 'link', icon: IconLink, messageKey: 'editor.textArea.toggleLink' }
153
+ };
154
+
155
+ let currentTextStyle = $state('text'); // Track current text style
156
+
157
+ let showColorPicker = $state(false);
158
+ let currentColor = $derived(textColor);
159
+ let selectedTextRange: { from: number; to: number } | null = $state(null);
160
+
161
+ // Each option is shown by its message (`messageKey`), in the language of the page.
162
+ const textOptions: { value: string; messageKey: EditorMessageKey; icon?: any }[] = [
163
+ { value: 'text', messageKey: 'editor.textArea.paragraph', icon: IconPilcrow },
164
+ { value: 'h1', messageKey: 'editor.textArea.heading1', icon: IconH1 },
165
+ { value: 'h2', messageKey: 'editor.textArea.heading2', icon: IconH2 },
166
+ { value: 'h3', messageKey: 'editor.textArea.heading3', icon: IconH3 }
167
+ ];
168
+
169
+ const toolbarIconClass = 'size-4 shrink-0 stroke-[1.333]';
170
+
171
+ /** The message of the style the toolbar button shows: the plain text's when the style is none of the options. */
172
+ let currentTextStyleMessageKey = $derived<EditorMessageKey>(
173
+ textOptions.find((option) => option.value === currentTextStyle)?.messageKey ??
174
+ 'editor.textArea.text'
175
+ );
176
+
177
+ const listOptions: { value: string; messageKey: EditorMessageKey; icon?: any }[] = [
178
+ { value: 'bulletList', messageKey: 'editor.textArea.bulletList', icon: IconList },
179
+ { value: 'orderedList', messageKey: 'editor.textArea.numberedList', icon: IconListNumbers },
180
+ { value: 'checkList', messageKey: 'editor.textArea.checkList', icon: IconListCheck }
181
+ ];
182
+
183
+ const content = writable(value);
184
+
185
+ // Create a store for managing dropdowns
186
+ const openDropdowns = writable<Set<string>>(new Set());
187
+
188
+ function toggleDropdown(id: string) {
189
+ openDropdowns.update((set) => {
190
+ if (set.has(id)) {
191
+ set.delete(id);
192
+ } else {
193
+ set.add(id);
194
+ }
195
+ return set;
196
+ });
197
+ }
198
+
199
+ // Add these variables to track focus state
200
+ let editorHasFocus = $state(false);
201
+ let toolbarRef: HTMLDivElement;
202
+
203
+ // Static styles — avoid $derived so teardown does not leave inert derived reads.
204
+ const editorStyle = `
185
205
  --editor-min-height: auto;
186
206
  --editor-max-height: none;
187
207
  --transition-duration: 0ms;
188
208
  --transition-timing: ease-out;
189
209
  `;
190
210
 
191
- // Add this with other state declarations
192
- let editorClass = 'border-none overflow-auto editor-height';
193
-
194
- // Add state to track if any dropdown is open
195
- let isDropdownOpen = $state(false);
196
-
197
- /**
198
- * Editor Mount Handler
199
- *
200
- * Initializes the editor instance and sets up event listeners:
201
- * 1. Sets initial content if provided
202
- * 2. Configures editor options (autofocus, editability)
203
- * 3. Sets up selection tracking for format updates
204
- * 4. Manages focus/blur behavior and height transitions
205
- * 5. Handles initial mount state
206
- *
207
- * Edge Cases:
208
- * - Prevents height changes when dropdowns are open
209
- * - Manages focus state during toolbar interactions
210
- * - Handles selection preservation during format changes
211
- */
212
- // Add these new state variables after the other state declarations
213
- let lastKnownContent = $state('');
214
- let wasVisible = $state(true);
215
- let isDestroyed = false;
216
-
217
- function handleEditorMount(e: any) {
218
- editorInstance = e.detail.editor;
219
-
220
- if (!editorInstance) {
221
- console.error('Failed to initialize editor instance');
222
- return;
223
- }
224
-
225
- // Restore content if we were previously hidden
226
- if (!wasVisible && lastKnownContent) {
227
- try {
228
- const coloredContent = `<span style="color: ${textColor}">${lastKnownContent}</span>`;
229
- editorInstance.commands.setContent(coloredContent);
230
- } catch (error) {
231
- console.error('Error restoring content after visibility change:', error);
232
- }
233
- } else if (value) {
234
- try {
235
- const coloredContent = `<span style="color: ${textColor}">${value}</span>`;
236
- editorInstance.commands.setContent(coloredContent);
237
-
238
- // Set caret to start after setting content
239
- editorInstance.commands.setTextSelection(0);
240
- } catch (error) {
241
- console.error('Error setting initial content and color:', error);
242
- }
243
- }
244
-
245
- // Disable auto-focus behavior
246
- editorInstance.setOptions({
247
- autofocus: false,
248
- editable: true
249
- });
250
-
251
- // Add selection change listener
252
- editorInstance.on('selectionUpdate', () => {
253
- handleSelectionChange();
254
- updateActiveFormats();
255
- });
256
-
257
- // Track focus state and handle height changes
258
- editorInstance.on('focus', () => {
259
- onFocus();
260
- editorHasFocus = true;
261
-
262
- // When focusing, ensure caret is at start if this is initial mount
263
- if (isInitialMount && editorInstance) {
264
- editorInstance.commands.setTextSelection(0);
265
- }
266
- });
267
-
268
- // Update the blur handler inside handleEditorMount
269
- editorInstance.on('blur', ({ event }) => {
270
- const relatedTarget = (event as FocusEvent).relatedTarget as Node | null;
271
- handleEditorBlur(relatedTarget);
272
- });
273
-
274
- // Set initial mount flag
275
- isInitialMount = true;
276
- setTimeout(() => {
277
- isInitialMount = false;
278
- // Check overflow only once after initial mount
279
- setTimeout(() => {
280
- checkContentOverflow();
281
- }, 300); // Give it a bit more time to ensure content is fully rendered
282
- }, 100);
283
-
284
- updateActiveFormats();
285
-
286
- // Helper function to check if content overflows viewport - only called once on mount
287
- function checkContentOverflow() {
288
- if (!editorInstance) return;
289
- try {
290
- const editorDom = editorInstance.view.dom;
291
- const contentArea = editorDom.closest('.editor-content-area') as HTMLElement;
292
-
293
- if (!contentArea) {
294
- console.error('Could not find .editor-content-area parent element');
295
- return;
296
- }
297
-
298
- const proseMirror = contentArea.querySelector('.ProseMirror') as HTMLElement;
299
- if (!proseMirror) {
300
- console.error('Could not find .ProseMirror element inside content area');
301
- return;
302
- }
303
-
304
- // Get the actual content height (including padding)
305
- const contentHeight = proseMirror.scrollHeight;
306
- // Get the available container height
307
- const containerHeight = contentArea.clientHeight;
308
- const isOverflowing = contentHeight > containerHeight;
309
-
310
- // console.log('Initial overflow check:', {
311
- // contentHeight,
312
- // containerHeight,
313
- // difference: contentHeight - containerHeight,
314
- // isOverflowing
315
- // });
316
-
317
- if (isOverflowing) {
318
- proseMirror.style.backgroundColor = 'rgba(255, 0, 0, 0.1)';
319
- }
320
- } catch (error) {
321
- console.error('Error checking content overflow:', error);
322
- }
323
- }
324
-
325
- // Helper function to force caret and scroll to beginning
326
- function forceCaretToStart() {
327
- if (!editorInstance) return;
328
- try {
329
- // Only force caret to start if this is the initial mount
330
- if (isInitialMount) {
331
- // Force the caret (text selection) to the beginning
332
- editorInstance.chain().setTextSelection({ from: 0, to: 0 }).run();
333
- }
334
- } catch (error) {
335
- console.error('Error forcing caret to beginning:', error);
336
- }
337
- }
338
-
339
- // Only call forceCaretToStart once during initial mount
340
- if (isInitialMount) {
341
- setTimeout(forceCaretToStart, 300);
342
- }
343
- }
344
-
345
- function handleEditorUpdate(e: any) {
346
- if (!editorInstance) return;
347
-
348
- // bind:content on ShadEditor already assigned `value` before this event,
349
- // so comparing to `value` skipped onChange and the compact preview never updated.
350
- const newContent = e.detail?.html ?? editorInstance.getHTML?.() ?? '';
351
- lastKnownContent = newContent;
352
- content.set(newContent);
353
- onChange?.(newContent);
354
- updateActiveFormats();
355
- currentTextStyle = getCurrentTextStyle();
356
- }
357
-
358
- /**
359
- * Format Management System
360
- *
361
- * Handles text formatting operations and state:
362
- * - Updates toolbar UI based on current selection
363
- * - Manages format toggles (bold, italic, etc.)
364
- * - Handles text style changes (headings, lists)
365
- * - Preserves selection during format operations
366
- *
367
- * Selection Handling:
368
- * - Tracks active formats only when text is selected
369
- * - Resets formats when no selection exists
370
- * - Maintains format state during dropdown operations
371
- */
372
- function updateActiveFormats() {
373
- if (!editorInstance) return;
374
-
375
- // Update activeFormats based on editor state
376
- const newFormats = {
377
- bold: editorInstance.isActive('bold'),
378
- italic: editorInstance.isActive('italic'),
379
- underline: editorInstance.isActive('underline'),
380
- link: editorInstance.isActive('link')
381
- };
382
-
383
- // Only update if there's a change to prevent unnecessary rerenders
384
- if (JSON.stringify(newFormats) !== JSON.stringify($state.snapshot(activeFormats))) {
385
- activeFormats = newFormats;
386
- syncToggleValues();
387
- // console.log('Active formats updated:', $state.snapshot(activeFormats));
388
- }
389
- }
390
-
391
- function applyFormat(format: FormatType, isAdding: boolean = true) {
392
- if (!editorInstance) return;
393
-
394
- try {
395
- // Always focus first and start a chain
396
- const chain = editorInstance.chain().focus() as any;
397
-
398
- switch (format) {
399
- case 'bold':
400
- chain.toggleBold().run();
401
- break;
402
- case 'italic':
403
- chain.toggleItalic().run();
404
- break;
405
- case 'underline':
406
- chain.toggleUnderline().run();
407
- break;
408
- case 'link':
409
- if (isAdding) {
410
- const href = window.prompt($t('editor.textArea.enterUrl'));
411
- if (href) {
412
- chain.setLink({ href }).run();
413
- }
414
- } else {
415
- chain.unsetLink().run();
416
- }
417
- break;
418
- }
419
-
420
- // Update formats after applying changes
421
- setTimeout(() => {
422
- updateActiveFormats();
423
- }, 0);
424
- } catch (error) {
425
- console.error('Error applying format:', format, error);
426
- }
427
- }
428
-
429
- function handleToggleChange(newValues: string[] | undefined): void {
430
- if (!editorInstance) {
431
- console.warn('No editor instance available');
432
- return;
433
- }
434
-
435
- if (!newValues) {
436
- console.warn('No new values provided');
437
- return;
438
- }
439
-
440
- // Use $state.snapshot() for logging
441
- const currentValues = $state.snapshot(toggleValues);
442
- // console.log('Toggle change:', { newValues, currentValues });
443
-
444
- // Find which format was toggled by comparing the arrays
445
- const added = newValues.filter(v => !currentValues.includes(v));
446
- const removed = currentValues.filter(v => !newValues.includes(v));
447
-
448
- // Handle the change
449
- if (added.length > 0) {
450
- // Find the format type for the added value
451
- const format = Object.entries(formatMapping).find(([_, m]) => m.value === added[0])?.[0] as FormatType;
452
- if (format) {
453
- // console.log('Applying format:', format);
454
- applyFormat(format, true);
455
- }
456
- } else if (removed.length > 0) {
457
- // Find the format type for the removed value
458
- const format = Object.entries(formatMapping).find(([_, m]) => m.value === removed[0])?.[0] as FormatType;
459
- if (format) {
460
- // console.log('Removing format:', format);
461
- applyFormat(format, false);
462
- }
463
- }
464
- }
465
-
466
- // Compute toggle values without $derived — TipTap callbacks can run after unmount
467
- // and reading an inert derived triggers Svelte's derived_inert warning.
468
- function getToggleValues(): string[] {
469
- if (isDestroyed) return [];
470
- return Object.entries(activeFormats)
471
- .filter(([_, isActive]) => isActive)
472
- .map(([format]) => formatMapping[format as FormatType].value);
473
- }
474
-
475
- let toggleValues = $state<string[]>([]);
476
- function syncToggleValues() {
477
- if (isDestroyed) return;
478
- toggleValues = getToggleValues();
479
- }
480
-
481
- // Restore handleTextStyleChange for other style changes
482
- function handleTextStyleChange(value: string) {
483
- if (!editorInstance) return;
484
-
485
- try {
486
- const { from, to } = editorInstance.state.selection;
487
- const selectedText = editorInstance.state.doc.textBetween(from, to);
488
-
489
- // console.log('Changing style for text "%s" to:', (selectedText || 'No text selected'), value);
490
-
491
- // Store the current scroll position and selection
492
- const editorDom = editorInstance.view.dom;
493
- const contentArea = editorDom.closest('.editor-content-area') as HTMLElement;
494
- const scrollTop = contentArea ? contentArea.scrollTop : editorDom.scrollTop;
495
- const selection = { from, to };
496
-
497
- const chain = editorInstance.chain().focus() as any;
498
-
499
- switch (value) {
500
- case 'text':
501
- chain.setNode('paragraph').run();
502
- currentTextStyle = value;
503
- break;
504
- case 'h1':
505
- case 'h2':
506
- case 'h3':
507
- const level = parseInt(value.charAt(1)) as TipTapEditorLevel;
508
- chain.toggleHeading({ level }).run();
509
- currentTextStyle = editorInstance.isActive('heading', { level }) ? value : 'text';
510
- break;
511
- case 'bulletList':
512
- chain.toggleBulletList().run();
513
- currentTextStyle = value;
514
- break;
515
- case 'orderedList':
516
- chain.toggleOrderedList().run();
517
- currentTextStyle = value;
518
- break;
519
- case 'checkList':
520
- chain.toggleTaskList().run();
521
- currentTextStyle = value;
522
- break;
523
- case 'blockquote':
524
- chain.toggleBlockquote().run();
525
- currentTextStyle = value;
526
- break;
527
- case 'code':
528
- chain.toggleCode().run();
529
- currentTextStyle = value;
530
- break;
531
- case 'strike':
532
- chain.toggleStrike().run();
533
- currentTextStyle = value;
534
- break;
535
- }
536
-
537
- // Restore the scroll position and selection after the style change
538
- requestAnimationFrame(() => {
539
- if (contentArea) {
540
- contentArea.scrollTop = scrollTop;
541
- } else if (editorDom) {
542
- editorDom.scrollTop = scrollTop;
543
- }
544
- // Restore selection
545
- editorInstance?.chain()
546
- .setTextSelection(selection)
547
- .run();
548
- });
549
-
550
- updateActiveFormats();
551
- // Choosing from either menu (text style or list style) closes it: the list style menu used to stay open.
552
- textStyleDropdownOpen = false;
553
- listStyleDropdownOpen = false;
554
- } catch (error) {
555
- console.error('Error changing text style:', error);
556
- }
557
- }
558
-
559
- function getCurrentTextStyle() {
560
- if (!editorInstance) return 'text';
561
-
562
- // Check for headings first
563
- if (editorInstance.isActive('heading', { level: 1 })) return 'h1';
564
- if (editorInstance.isActive('heading', { level: 2 })) return 'h2';
565
- if (editorInstance.isActive('heading', { level: 3 })) return 'h3';
566
-
567
- // Check for lists and other block-level formats
568
- if (editorInstance.isActive('bulletList')) return 'bulletList';
569
- if (editorInstance.isActive('orderedList')) return 'orderedList';
570
- if (editorInstance.isActive('checkList')) return 'checkList';
571
- if (editorInstance.isActive('blockquote')) return 'blockquote';
572
- if (editorInstance.isActive('code')) return 'code';
573
- if (editorInstance.isActive('strike')) return 'strike';
574
-
575
- // If no block-level format is active, return the current text style
576
- const marks = editorInstance.state.selection.$head.marks();
577
- if (marks.length > 0) {
578
- // Keep the current text style if there are inline marks
579
- return currentTextStyle;
580
- }
581
-
582
- return 'text';
583
- }
584
- // Function to store text selection
585
- function storeSelection() {
586
- if (!editorInstance) return null;
587
- const { from, to } = editorInstance.state.selection;
588
- if (from === to) return null;
589
- return { from, to };
590
- }
591
-
592
- // Function to restore text selection
593
- function restoreSelection() {
594
- if (!editorInstance || !selectedTextRange) return;
595
- editorInstance.chain()
596
- .setTextSelection({ from: selectedTextRange.from, to: selectedTextRange.to })
597
- .run();
598
- }
599
-
600
- // Helper function to convert RGB to Hex
601
- function rgbToHex(r: number, g: number, b: number): string {
602
- const toHex = (n: number) => {
603
- const hex = Math.round(n).toString(16);
604
- return hex.length === 1 ? '0' + hex : hex;
605
- };
606
- return '#' + toHex(r) + toHex(g) + toHex(b);
607
- }
608
-
609
- // Update handleColorChange to use current selection if available
610
- function handleColorChange(color: string) {
611
- if (!editorInstance) return;
612
-
613
- try {
614
- // Get current selection
615
- const { from, to } = editorInstance.state.selection;
616
- const hasSelection = from !== to;
617
-
618
- if (hasSelection) {
619
- // Apply color to selection using the correct command
620
- editorInstance.chain()
621
- .setTextSelection({ from, to })
622
- .setMark('textStyle', { color })
623
- .run();
624
-
625
- // Remove any highlight marks and restore selection visibility
626
- editorInstance.chain()
627
- .unsetMark('highlight')
628
- .run();
629
-
630
- // Remove hide-selection class
631
- editorInstance.view.dom.classList.remove('hide-selection');
632
-
633
- // Ensure editor has focus
634
- editorInstance.commands.focus();
635
- }
636
- } catch (error) {
637
- console.error('Error applying color:', error);
638
- }
639
- }
640
-
641
- // $effect(() => {
642
- // if (value !== $content && editorInstance) {
643
- // console.log('External value changed:', value);
644
- // content.set(value);
645
- // editorInstance.commands.setContent(value);
646
- // }
647
- // });
648
-
649
- // Add colorPickerOpen state
650
- let colorPickerOpen = $state(false);
651
-
652
- // Add function to handle color picker open/close
653
- function handleColorPickerToggle() {
654
- colorPickerOpen = !colorPickerOpen;
655
- if (colorPickerOpen && selectedTextRange) {
656
- restoreSelection();
657
- }
658
- }
659
-
660
- // Update getSelectedTextColor to ensure hex format with 100% opacity
661
- function getSelectedTextColor(): string {
662
- if (!editorInstance) return currentColor;
663
-
664
- const { from, to } = editorInstance.state.selection;
665
- if (from === to) return currentColor;
666
-
667
- // Get the color mark from the selection
668
- const marks = editorInstance.state.doc.nodeAt(from)?.marks;
669
- const colorMark = marks?.find(mark => mark.type.name === 'textStyle' && mark.attrs.color);
670
-
671
- let color = colorMark?.attrs.color || currentColor;
672
-
673
- // Convert RGB to Hex if needed
674
- if (color.startsWith('rgb')) {
675
- const matches = color.match(/\d+/g);
676
- if (matches && matches.length >= 3) {
677
- color = rgbToHex(
678
- parseInt(matches[0]),
679
- parseInt(matches[1]),
680
- parseInt(matches[2])
681
- );
682
- }
683
- }
684
-
685
- // Ensure color is in hex format and has 100% opacity
686
- if (color.length === 9) { // If it's a hex with alpha
687
- color = color.substring(0, 7); // Remove alpha channel
688
- }
689
-
690
- return color;
691
- }
692
-
693
- // Update handleSelectionChange to properly handle color conversion
694
- function handleSelectionChange() {
695
- if (!editorInstance) return;
696
-
697
- const { from, to } = editorInstance.state.selection;
698
- const hasSelection = from !== to;
699
-
700
- if (hasSelection) {
701
- selectedRange = { from, to };
702
-
703
- // Get the selected text and check for color mark
704
- const marks = editorInstance.state.doc.nodeAt(from)?.marks || [];
705
- const colorMark = marks.find(mark =>
706
- mark.type.name === 'textStyle' && mark.attrs.color
707
- );
708
-
709
- // Update currentColor if a color mark is found
710
- if (colorMark?.attrs.color) {
711
- let color = colorMark.attrs.color;
712
-
713
- // Convert RGB to Hex if needed
714
- if (color.startsWith('rgb')) {
715
- const matches = color.match(/\d+/g);
716
- if (matches && matches.length >= 3) {
717
- color = rgbToHex(
718
- parseInt(matches[0]),
719
- parseInt(matches[1]),
720
- parseInt(matches[2])
721
- );
722
- }
723
- }
724
-
725
- // Remove alpha channel if present
726
- if (color.length === 9) {
727
- color = color.substring(0, 7);
728
- }
729
-
730
- currentColor = color;
731
- }
732
-
733
- // console.log('Selection updated:', {
734
- // text: editorInstance.state.doc.textBetween(from, to),
735
- // range: { from, to },
736
- // style: currentTextStyle,
737
- // format: [
738
- // ...(editorInstance.isActive('bold') ? ['b'] : []),
739
- // ...(editorInstance.isActive('italic') ? ['i'] : []),
740
- // ...(editorInstance.isActive('underline') ? ['u'] : []),
741
- // ...(editorInstance.isActive('link') ? ['link'] : [])
742
- // ],
743
- // color: currentColor
744
- // });
745
- } else {
746
- selectedRange = null;
747
- currentColor = textColor; // Reset to default color when deselecting
748
- }
749
- }
750
-
751
- // Add this state to track animation
752
- let isColorPickerAnimating = $state(false);
753
-
754
- // Update handleColorButtonClick to ensure hex format
755
- function handleColorButtonClick() {
756
- if (!editorInstance) return;
757
-
758
- const { from, to } = editorInstance.state.selection;
759
- if (from !== to) {
760
- selectedRange = { from, to };
761
- isSelectionActive = true;
762
-
763
- // Get and convert color to hex format
764
- let selectedColor = getSelectedTextColor();
765
- // Ensure we convert any rgb colors to hex
766
- if (selectedColor.startsWith('rgb')) {
767
- const matches = selectedColor.match(/\d+/g);
768
- if (matches && matches.length >= 3) {
769
- selectedColor = rgbToHex(
770
- parseInt(matches[0]),
771
- parseInt(matches[1]),
772
- parseInt(matches[2])
773
- );
774
- }
775
- }
776
- // Remove any alpha channel
777
- if (selectedColor.length === 9) {
778
- selectedColor = selectedColor.substring(0, 7);
779
- }
780
-
781
- currentColor = selectedColor;
782
-
783
- // Set focus to editor
784
- editorHasFocus = true;
785
- // editorInstance.commands.focus();
786
-
787
- } else {
788
- selectedRange = null;
789
- isSelectionActive = false;
790
- }
791
-
792
- showColorPicker = true;
793
- isColorPickerAnimating = true;
794
-
795
- // console.log('Color picker toolbar opened with selection:', {
796
- // range: selectedRange,
797
- // color: currentColor,
798
- // hasFocus: editorHasFocus,
799
- // isActive
800
- // });
801
- }
802
-
803
- // Update the event handler function to handle CustomEvent
804
- function handleColorPickerInteraction(event: CustomEvent<any>) {
805
- // Get the original MouseEvent from the detail if available
806
- const mouseEvent = event.detail?.originalEvent as MouseEvent;
807
- if (mouseEvent) {
808
- // Prevent the default behavior that might clear the selection
809
- mouseEvent.preventDefault();
810
- mouseEvent.stopPropagation();
811
- }
812
-
813
- // Reapply the selection if it exists
814
- if (selectedRange && editorInstance) {
815
- editorInstance.chain()
816
- .focus()
817
- .setTextSelection(selectedRange)
818
- .run();
819
- }
820
- }
821
-
822
- // Update handleColorPickerClose function
823
- function handleColorPickerClose() {
824
- showColorPicker = false;
825
- isColorPickerAnimating = false;
826
- isSelectionActive = false;
827
-
828
- if (editorInstance) {
829
- // Create a chain to handle all operations
830
- const chain = editorInstance.chain();
831
-
832
- // Remove highlight if it exists
833
- chain.unsetMark('highlight');
834
-
835
- // Store current selection before cleanup
836
- const currentSelection = editorInstance.state.selection;
837
- const hasSelection = currentSelection.from !== currentSelection.to;
838
-
839
- // Run the chain
840
- chain.run();
841
-
842
- // Remove hide-selection class
843
- editorInstance.view.dom.classList.remove('hide-selection');
844
-
845
- // Always focus the editor first
846
- editorInstance.view.focus();
847
-
848
- // Then reapply selection if it existed
849
- if (hasSelection) {
850
- editorInstance.commands.setTextSelection({
851
- from: currentSelection.from,
852
- to: currentSelection.to
853
- });
854
- }
855
- }
856
- }
857
-
858
- // Add effect to handle clicks outside Color Select
859
- $effect(() => {
860
- if (isDestroyed) return;
861
- const handleClickOutside = (event: MouseEvent) => {
862
- if (isDestroyed) return;
863
- // Looked for in the tree this editor is in (inside a module, `document` has none of the editor's elements and may
864
- // have a popover of the customer's page), and checked with the event's path (the target the document sees is the
865
- // module's host)
866
- const colorSelectModals = queryAllInTreeOf(toolbarRef, '[data-radix-popper-content-wrapper]');
867
- const isClickingColorSelect = colorSelectModals.some((colorSelectModal) => isEventInside(event, colorSelectModal));
868
-
869
- // Don't do anything if clicking within the color select modal
870
- if (isClickingColorSelect) {
871
- // Prevent any focus changes
872
- event.preventDefault();
873
- event.stopPropagation();
874
- return;
875
- }
876
- };
877
-
878
- if (isColorSelectOpen) {
879
- document.addEventListener('mousedown', handleClickOutside);
880
- return () => document.removeEventListener('mousedown', handleClickOutside);
881
- }
882
- });
883
-
884
- /**
885
- * Color Management System
886
- *
887
- * Handles text color operations:
888
- * - Stores and restores text selection during color picker use
889
- * - Manages color picker visibility state
890
- * - Applies colors to selected text
891
- * - Retrieves current text color for selected range
892
- *
893
- * Selection Preservation:
894
- * - Stores selection before opening color picker
895
- * - Restores selection after color picker closes
896
- * - Handles edge cases when no text is selected
897
- */
898
-
899
- // Add this with the other function declarations in the script section
900
- function handleToolbarInteraction(event: MouseEvent) {
901
- const target = event.target as HTMLElement;
902
-
903
- // If clicking toolbar elements or color picker, maintain expanded state
904
- if (target.matches('input, button, [role="button"], [tabindex="0"]') ||
905
- target.closest('.color-picker-container')) {
906
- // Keep toolbar enabled since we're interacting with it
907
- editorHasFocus = true;
908
- return;
909
- }
910
-
911
- event.preventDefault();
912
- event.stopPropagation();
913
-
914
- // When clicking toolbar itself, maintain focus and enabled state
915
- if (editorInstance) {
916
- editorInstance.commands.focus();
917
- editorHasFocus = true;
918
- }
919
- }
920
-
921
- // Add this function to handle keyboard interactions
922
- function handleToolbarKeyDown(event: KeyboardEvent) {
923
- // Don't handle keyboard events for inputs and interactive elements
924
- const target = event.target as HTMLElement;
925
- if (target.matches('input, button, [role="button"], [tabindex="0"]')) {
926
- return;
927
- }
928
-
929
- // Handle keyboard interactions for toolbar
930
- if (event.key === 'Enter' || event.key === ' ') {
931
- event.preventDefault();
932
- handleToolbarInteraction(event as unknown as MouseEvent);
933
- }
934
- }
935
-
936
- // Update the effect that maintains selection during color picker interactions
937
- $effect(() => {
938
- if (isDestroyed) return;
939
- if (showColorPicker && selectedTextRange && editorInstance) {
940
- const { from, to } = selectedTextRange;
941
- editorInstance.chain()
942
- .setTextSelection({ from, to })
943
- .run();
944
- }
945
- });
946
-
947
- // Add these near the top of the script section with other state declarations
948
- let isColorSelectOpen = $state(false);
949
-
950
- // Add handleKeyDown function
951
- function handleKeyDown(event: KeyboardEvent) {
952
- if (event.key === 'Escape') {
953
- if (showColorPicker) {
954
- event.preventDefault();
955
- handleColorPickerClose();
956
- }
957
- }
958
- }
959
-
960
- // Update handleEditorBlur to maintain toolbar state
961
- function handleEditorBlur(relatedTarget: Node | null) {
962
- if (!editorInstance) return;
963
-
964
- // Looked for in the tree the editor is in: `document` does not see inside a module's shadow root, and may have a
965
- // dialog of the customer's page
966
- const colorSelectModal = queryInTreeOf(toolbarRef, '[data-radix-popper-content-wrapper]');
967
- const popoverContent = queryInTreeOf(toolbarRef, '[role="dialog"]');
968
- const commandMenu = queryInTreeOf(toolbarRef, '[cmdk-root]');
969
-
970
- const isClickingInside = toolbarRef?.contains(relatedTarget) ||
971
- editorInstance.view.dom.contains(relatedTarget as Node) ||
972
- colorSelectModal?.contains(relatedTarget as Node) ||
973
- popoverContent?.contains(relatedTarget as Node) ||
974
- commandMenu?.contains(relatedTarget as Node);
975
-
976
- if (!isClickingInside) {
977
- editorHasFocus = false;
978
- }
979
- }
980
-
981
- // Add this logging helper
982
- function logTransitionState(source: string) {
983
- // console.log(`Transition State [${source}]:`, {
984
- // isTransitioning,
985
- // editorHeight,
986
- // isActive,
987
- // editorHasFocus,
988
- // isIdle: editorHeight === IDLE_HEIGHT
989
- // });
990
- }
991
-
992
- // Add this function to handle popover state changes
993
- function handlePopoverOpenChange(isOpen: boolean) {
994
- textStyleDropdownOpen = isOpen;
995
-
996
- // Ensure editor maintains focus when popover opens/closes
997
- if (editorInstance) {
998
- editorHasFocus = true;
999
- editorInstance.commands.focus();
1000
- }
1001
- }
1002
-
1003
- // Add this function to handle command item selection
1004
- function handleCommandSelect(value: string) {
1005
- if (!editorInstance) return;
1006
-
1007
- // Change the text style to the selected value
1008
- handleTextStyleChange(value);
1009
-
1010
- // Restore editor focus after command selection
1011
- setTimeout(() => {
1012
- if (!editorInstance) return;
1013
- editorHasFocus = true;
1014
- editorInstance.commands.focus();
1015
- }, 0);
1016
- }
1017
-
1018
- // Add these variables to track button position
1019
- let triggerButtonRect = $state<DOMRect | null>(null);
1020
- let triggerButton: any;
1021
- let triggerButtonElement: HTMLButtonElement;
1022
-
1023
- // Add function to update position using the button element directly
1024
- function updateTriggerPosition(buttonElement: HTMLButtonElement) {
1025
- triggerButtonRect = buttonElement.getBoundingClientRect();
1026
- }
1027
-
1028
- // Add these state variables near the top with other state declarations
1029
- let selectedRange: { from: number, to: number } | null = $state(null);
1030
- let isSelectionActive = $state(false);
1031
-
1032
- // Add this near the top of the script section with other constants
1033
- const STYLE_DROPDOWN_ID = 'text-style-dropdown';
1034
-
1035
- // Add these functions near the top with other event handlers
1036
- function closeTextStyleDropdown() {
1037
- if (textStyleDropdownOpen) {
1038
- textStyleDropdownOpen = false;
1039
- // Restore focus to editor
1040
- if (!editorInstance) return;
1041
-
1042
- setTimeout(() => {
1043
- if (!editorInstance) return;
1044
- editorHasFocus = true;
1045
- editorInstance.commands.focus();
1046
- }, 0);
1047
- }
1048
- }
1049
-
1050
- function handleScroll() {
1051
- closeTextStyleDropdown();
1052
- }
1053
-
1054
- // Add to lifecycle management
1055
- // (listens to the page and, inside a module, to the module's own panels too: a scroll never leaves a shadow root)
1056
- let stopListeningForScroll: () => void = () => {};
1057
-
1058
- onMount(() => {
1059
- stopListeningForScroll = listenForScroll(toolbarRef, handleScroll);
1060
- });
1061
-
1062
- onDestroy(() => {
1063
- stopListeningForScroll();
1064
- });
1065
-
1066
- // Add cleanup function
1067
- onDestroy(() => {
1068
- isDestroyed = true;
1069
- if (editorInstance) {
1070
- // Store the current content before unmounting
1071
- lastKnownContent = editorInstance.getHTML();
1072
- wasVisible = false;
1073
-
1074
- // Clean up editor instance
1075
- editorInstance.destroy();
1076
- editorInstance = null;
1077
- }
1078
- });
1079
-
1080
- // Update mousedown handler to remove height changes
1081
- function handleMouseDown(e: MouseEvent) {
1082
- if (editorInstance) {
1083
- const target = e.target as HTMLElement;
1084
- const isInteractive = target.matches('button, input, [role="button"], [tabindex="0"]') ||
1085
- target.closest('button, input, [role="button"], [tabindex="0"]');
1086
-
1087
- if (!isInteractive) {
1088
- e.preventDefault();
1089
- e.stopPropagation();
1090
-
1091
- // Just focus the editor
1092
- editorHasFocus = true;
1093
- editorInstance.commands.focus();
1094
- }
1095
- }
1096
- }
1097
-
1098
- // Update hit zone handler to remove transitions
1099
- function handleHitZone(e: MouseEvent) {
1100
- e.preventDefault();
1101
- e.stopPropagation();
1102
- if (editorInstance) {
1103
- editorInstance.commands.focus();
1104
- editorHasFocus = true;
1105
- }
1106
- }
211
+ // Add this with other state declarations
212
+ let editorClass = 'border-none overflow-auto editor-height';
213
+
214
+ // Add state to track if any dropdown is open
215
+ let isDropdownOpen = $state(false);
216
+
217
+ /**
218
+ * Editor Mount Handler
219
+ *
220
+ * Initializes the editor instance and sets up event listeners:
221
+ * 1. Sets initial content if provided
222
+ * 2. Configures editor options (autofocus, editability)
223
+ * 3. Sets up selection tracking for format updates
224
+ * 4. Manages focus/blur behavior and height transitions
225
+ * 5. Handles initial mount state
226
+ *
227
+ * Edge Cases:
228
+ * - Prevents height changes when dropdowns are open
229
+ * - Manages focus state during toolbar interactions
230
+ * - Handles selection preservation during format changes
231
+ */
232
+ // Add these new state variables after the other state declarations
233
+ let lastKnownContent = $state('');
234
+ let wasVisible = $state(true);
235
+ let isDestroyed = false;
236
+
237
+ function handleEditorMount(e: any) {
238
+ editorInstance = e.detail.editor;
239
+
240
+ if (!editorInstance) {
241
+ console.error('Failed to initialize editor instance');
242
+ return;
243
+ }
244
+
245
+ // Restore content if we were previously hidden
246
+ if (!wasVisible && lastKnownContent) {
247
+ try {
248
+ const coloredContent = `<span style="color: ${textColor}">${lastKnownContent}</span>`;
249
+ editorInstance.commands.setContent(coloredContent);
250
+ } catch (error) {
251
+ console.error('Error restoring content after visibility change:', error);
252
+ }
253
+ } else if (value) {
254
+ try {
255
+ const coloredContent = `<span style="color: ${textColor}">${value}</span>`;
256
+ editorInstance.commands.setContent(coloredContent);
257
+
258
+ // Set caret to start after setting content
259
+ editorInstance.commands.setTextSelection(0);
260
+ } catch (error) {
261
+ console.error('Error setting initial content and color:', error);
262
+ }
263
+ }
264
+
265
+ // Disable auto-focus behavior
266
+ editorInstance.setOptions({
267
+ autofocus: false,
268
+ editable: true
269
+ });
270
+
271
+ // Add selection change listener
272
+ editorInstance.on('selectionUpdate', () => {
273
+ handleSelectionChange();
274
+ updateActiveFormats();
275
+ });
276
+
277
+ // Track focus state and handle height changes
278
+ editorInstance.on('focus', () => {
279
+ onFocus();
280
+ editorHasFocus = true;
281
+
282
+ // When focusing, ensure caret is at start if this is initial mount
283
+ if (isInitialMount && editorInstance) {
284
+ editorInstance.commands.setTextSelection(0);
285
+ }
286
+ });
287
+
288
+ // Update the blur handler inside handleEditorMount
289
+ editorInstance.on('blur', ({ event }) => {
290
+ const relatedTarget = (event as FocusEvent).relatedTarget as Node | null;
291
+ handleEditorBlur(relatedTarget);
292
+ });
293
+
294
+ // Set initial mount flag
295
+ isInitialMount = true;
296
+ setTimeout(() => {
297
+ isInitialMount = false;
298
+ // Check overflow only once after initial mount
299
+ setTimeout(() => {
300
+ checkContentOverflow();
301
+ }, 300); // Give it a bit more time to ensure content is fully rendered
302
+ }, 100);
303
+
304
+ updateActiveFormats();
305
+
306
+ // Helper function to check if content overflows viewport - only called once on mount
307
+ function checkContentOverflow() {
308
+ if (!editorInstance) return;
309
+ try {
310
+ const editorDom = editorInstance.view.dom;
311
+ const contentArea = editorDom.closest('.editor-content-area') as HTMLElement;
312
+
313
+ if (!contentArea) {
314
+ console.error('Could not find .editor-content-area parent element');
315
+ return;
316
+ }
317
+
318
+ const proseMirror = contentArea.querySelector('.ProseMirror') as HTMLElement;
319
+ if (!proseMirror) {
320
+ console.error('Could not find .ProseMirror element inside content area');
321
+ return;
322
+ }
323
+
324
+ // Get the actual content height (including padding)
325
+ const contentHeight = proseMirror.scrollHeight;
326
+ // Get the available container height
327
+ const containerHeight = contentArea.clientHeight;
328
+ const isOverflowing = contentHeight > containerHeight;
329
+
330
+ // console.log('Initial overflow check:', {
331
+ // contentHeight,
332
+ // containerHeight,
333
+ // difference: contentHeight - containerHeight,
334
+ // isOverflowing
335
+ // });
336
+ } catch (error) {
337
+ console.error('Error checking content overflow:', error);
338
+ }
339
+ }
340
+
341
+ // Helper function to force caret and scroll to beginning
342
+ function forceCaretToStart() {
343
+ if (!editorInstance) return;
344
+ try {
345
+ // Only force caret to start if this is the initial mount
346
+ if (isInitialMount) {
347
+ // Force the caret (text selection) to the beginning
348
+ editorInstance.chain().setTextSelection({ from: 0, to: 0 }).run();
349
+ }
350
+ } catch (error) {
351
+ console.error('Error forcing caret to beginning:', error);
352
+ }
353
+ }
354
+
355
+ // Only call forceCaretToStart once during initial mount
356
+ if (isInitialMount) {
357
+ setTimeout(forceCaretToStart, 300);
358
+ }
359
+ }
360
+
361
+ function handleEditorUpdate(e: any) {
362
+ if (!editorInstance) return;
363
+
364
+ // bind:content on ShadEditor already assigned `value` before this event,
365
+ // so comparing to `value` skipped onChange and the compact preview never updated.
366
+ const newContent = e.detail?.html ?? editorInstance.getHTML?.() ?? '';
367
+ lastKnownContent = newContent;
368
+ content.set(newContent);
369
+ onChange?.(newContent);
370
+ updateActiveFormats();
371
+ currentTextStyle = getCurrentTextStyle();
372
+ }
373
+
374
+ /**
375
+ * Format Management System
376
+ *
377
+ * Handles text formatting operations and state:
378
+ * - Updates toolbar UI based on current selection
379
+ * - Manages format toggles (bold, italic, etc.)
380
+ * - Handles text style changes (headings, lists)
381
+ * - Preserves selection during format operations
382
+ *
383
+ * Selection Handling:
384
+ * - Tracks active formats only when text is selected
385
+ * - Resets formats when no selection exists
386
+ * - Maintains format state during dropdown operations
387
+ */
388
+ function updateActiveFormats() {
389
+ if (!editorInstance) return;
390
+
391
+ // Update activeFormats based on editor state
392
+ const newFormats = {
393
+ bold: editorInstance.isActive('bold'),
394
+ italic: editorInstance.isActive('italic'),
395
+ underline: editorInstance.isActive('underline'),
396
+ link: editorInstance.isActive('link')
397
+ };
398
+
399
+ // Only update if there's a change to prevent unnecessary rerenders
400
+ if (JSON.stringify(newFormats) !== JSON.stringify($state.snapshot(activeFormats))) {
401
+ activeFormats = newFormats;
402
+ syncToggleValues();
403
+ // console.log('Active formats updated:', $state.snapshot(activeFormats));
404
+ }
405
+ }
406
+
407
+ function applyFormat(format: FormatType, isAdding: boolean = true) {
408
+ if (!editorInstance) return;
409
+
410
+ try {
411
+ // Always focus first and start a chain
412
+ const chain = editorInstance.chain().focus() as any;
413
+
414
+ switch (format) {
415
+ case 'bold':
416
+ chain.toggleBold().run();
417
+ break;
418
+ case 'italic':
419
+ chain.toggleItalic().run();
420
+ break;
421
+ case 'underline':
422
+ chain.toggleUnderline().run();
423
+ break;
424
+ case 'link':
425
+ if (isAdding) {
426
+ const href = window.prompt($t('editor.textArea.enterUrl'));
427
+ if (href) {
428
+ chain.setLink({ href }).run();
429
+ }
430
+ } else {
431
+ chain.unsetLink().run();
432
+ }
433
+ break;
434
+ }
435
+
436
+ // Update formats after applying changes
437
+ setTimeout(() => {
438
+ updateActiveFormats();
439
+ }, 0);
440
+ } catch (error) {
441
+ console.error('Error applying format:', format, error);
442
+ }
443
+ }
444
+
445
+ function handleToggleChange(newValues: string[] | undefined): void {
446
+ if (!editorInstance) {
447
+ console.warn('No editor instance available');
448
+ return;
449
+ }
450
+
451
+ if (!newValues) {
452
+ console.warn('No new values provided');
453
+ return;
454
+ }
455
+
456
+ // Use $state.snapshot() for logging
457
+ const currentValues = $state.snapshot(toggleValues);
458
+ // console.log('Toggle change:', { newValues, currentValues });
459
+
460
+ // Find which format was toggled by comparing the arrays
461
+ const added = newValues.filter((v) => !currentValues.includes(v));
462
+ const removed = currentValues.filter((v) => !newValues.includes(v));
463
+
464
+ // Handle the change
465
+ if (added.length > 0) {
466
+ // Find the format type for the added value
467
+ const format = Object.entries(formatMapping).find(
468
+ ([_, m]) => m.value === added[0]
469
+ )?.[0] as FormatType;
470
+ if (format) {
471
+ // console.log('Applying format:', format);
472
+ applyFormat(format, true);
473
+ }
474
+ } else if (removed.length > 0) {
475
+ // Find the format type for the removed value
476
+ const format = Object.entries(formatMapping).find(
477
+ ([_, m]) => m.value === removed[0]
478
+ )?.[0] as FormatType;
479
+ if (format) {
480
+ // console.log('Removing format:', format);
481
+ applyFormat(format, false);
482
+ }
483
+ }
484
+ }
485
+
486
+ // Compute toggle values without $derived — TipTap callbacks can run after unmount
487
+ // and reading an inert derived triggers Svelte's derived_inert warning.
488
+ function getToggleValues(): string[] {
489
+ if (isDestroyed) return [];
490
+ return Object.entries(activeFormats)
491
+ .filter(([_, isActive]) => isActive)
492
+ .map(([format]) => formatMapping[format as FormatType].value);
493
+ }
494
+
495
+ let toggleValues = $state<string[]>([]);
496
+ function syncToggleValues() {
497
+ if (isDestroyed) return;
498
+ toggleValues = getToggleValues();
499
+ }
500
+
501
+ // Restore handleTextStyleChange for other style changes
502
+ function handleTextStyleChange(value: string) {
503
+ if (!editorInstance) return;
504
+
505
+ try {
506
+ const { from, to } = editorInstance.state.selection;
507
+ const selectedText = editorInstance.state.doc.textBetween(from, to);
508
+
509
+ // console.log('Changing style for text "%s" to:', (selectedText || 'No text selected'), value);
510
+
511
+ // Store the current scroll position and selection
512
+ const editorDom = editorInstance.view.dom;
513
+ const contentArea = editorDom.closest('.editor-content-area') as HTMLElement;
514
+ const scrollTop = contentArea ? contentArea.scrollTop : editorDom.scrollTop;
515
+ const selection = { from, to };
516
+
517
+ const chain = editorInstance.chain().focus() as any;
518
+
519
+ switch (value) {
520
+ case 'text':
521
+ chain.setNode('paragraph').run();
522
+ currentTextStyle = value;
523
+ break;
524
+ case 'h1':
525
+ case 'h2':
526
+ case 'h3':
527
+ const level = parseInt(value.charAt(1)) as TipTapEditorLevel;
528
+ chain.toggleHeading({ level }).run();
529
+ currentTextStyle = editorInstance.isActive('heading', { level }) ? value : 'text';
530
+ break;
531
+ case 'bulletList':
532
+ chain.toggleBulletList().run();
533
+ currentTextStyle = value;
534
+ break;
535
+ case 'orderedList':
536
+ chain.toggleOrderedList().run();
537
+ currentTextStyle = value;
538
+ break;
539
+ case 'checkList':
540
+ chain.toggleTaskList().run();
541
+ currentTextStyle = value;
542
+ break;
543
+ case 'blockquote':
544
+ chain.toggleBlockquote().run();
545
+ currentTextStyle = value;
546
+ break;
547
+ case 'code':
548
+ chain.toggleCode().run();
549
+ currentTextStyle = value;
550
+ break;
551
+ case 'strike':
552
+ chain.toggleStrike().run();
553
+ currentTextStyle = value;
554
+ break;
555
+ }
556
+
557
+ // Restore the scroll position and selection after the style change
558
+ requestAnimationFrame(() => {
559
+ if (contentArea) {
560
+ contentArea.scrollTop = scrollTop;
561
+ } else if (editorDom) {
562
+ editorDom.scrollTop = scrollTop;
563
+ }
564
+ // Restore selection
565
+ editorInstance?.chain().setTextSelection(selection).run();
566
+ });
567
+
568
+ updateActiveFormats();
569
+ // Choosing from either menu (text style or list style) closes it: the list style menu used to stay open.
570
+ textStyleDropdownOpen = false;
571
+ listStyleDropdownOpen = false;
572
+ } catch (error) {
573
+ console.error('Error changing text style:', error);
574
+ }
575
+ }
576
+
577
+ function getCurrentTextStyle() {
578
+ if (!editorInstance) return 'text';
579
+
580
+ // Check for headings first
581
+ if (editorInstance.isActive('heading', { level: 1 })) return 'h1';
582
+ if (editorInstance.isActive('heading', { level: 2 })) return 'h2';
583
+ if (editorInstance.isActive('heading', { level: 3 })) return 'h3';
584
+
585
+ // Check for lists and other block-level formats
586
+ if (editorInstance.isActive('bulletList')) return 'bulletList';
587
+ if (editorInstance.isActive('orderedList')) return 'orderedList';
588
+ if (editorInstance.isActive('checkList')) return 'checkList';
589
+ if (editorInstance.isActive('blockquote')) return 'blockquote';
590
+ if (editorInstance.isActive('code')) return 'code';
591
+ if (editorInstance.isActive('strike')) return 'strike';
592
+
593
+ // If no block-level format is active, return the current text style
594
+ const marks = editorInstance.state.selection.$head.marks();
595
+ if (marks.length > 0) {
596
+ // Keep the current text style if there are inline marks
597
+ return currentTextStyle;
598
+ }
599
+
600
+ return 'text';
601
+ }
602
+ // Function to store text selection
603
+ function storeSelection() {
604
+ if (!editorInstance) return null;
605
+ const { from, to } = editorInstance.state.selection;
606
+ if (from === to) return null;
607
+ return { from, to };
608
+ }
609
+
610
+ // Function to restore text selection
611
+ function restoreSelection() {
612
+ if (!editorInstance || !selectedTextRange) return;
613
+ editorInstance
614
+ .chain()
615
+ .setTextSelection({ from: selectedTextRange.from, to: selectedTextRange.to })
616
+ .run();
617
+ }
618
+
619
+ // Helper function to convert RGB to Hex
620
+ function rgbToHex(r: number, g: number, b: number): string {
621
+ const toHex = (n: number) => {
622
+ const hex = Math.round(n).toString(16);
623
+ return hex.length === 1 ? '0' + hex : hex;
624
+ };
625
+ return '#' + toHex(r) + toHex(g) + toHex(b);
626
+ }
627
+
628
+ // Update handleColorChange to use current selection if available
629
+ function handleColorChange(color: string) {
630
+ if (!editorInstance) return;
631
+
632
+ try {
633
+ // Get current selection
634
+ const { from, to } = editorInstance.state.selection;
635
+ const hasSelection = from !== to;
636
+
637
+ if (hasSelection) {
638
+ // Apply color to selection using the correct command
639
+ editorInstance.chain().setTextSelection({ from, to }).setMark('textStyle', { color }).run();
640
+
641
+ // Remove any highlight marks and restore selection visibility
642
+ editorInstance.chain().unsetMark('highlight').run();
643
+
644
+ // Remove hide-selection class
645
+ editorInstance.view.dom.classList.remove('hide-selection');
646
+
647
+ // Ensure editor has focus
648
+ editorInstance.commands.focus();
649
+ }
650
+ } catch (error) {
651
+ console.error('Error applying color:', error);
652
+ }
653
+ }
654
+
655
+ // $effect(() => {
656
+ // if (value !== $content && editorInstance) {
657
+ // console.log('External value changed:', value);
658
+ // content.set(value);
659
+ // editorInstance.commands.setContent(value);
660
+ // }
661
+ // });
662
+
663
+ // Add colorPickerOpen state
664
+ let colorPickerOpen = $state(false);
665
+
666
+ // Add function to handle color picker open/close
667
+ function handleColorPickerToggle() {
668
+ colorPickerOpen = !colorPickerOpen;
669
+ if (colorPickerOpen && selectedTextRange) {
670
+ restoreSelection();
671
+ }
672
+ }
673
+
674
+ // Update getSelectedTextColor to ensure hex format with 100% opacity
675
+ function getSelectedTextColor(): string {
676
+ if (!editorInstance) return currentColor;
677
+
678
+ const { from, to } = editorInstance.state.selection;
679
+ if (from === to) return currentColor;
680
+
681
+ // Get the color mark from the selection
682
+ const marks = editorInstance.state.doc.nodeAt(from)?.marks;
683
+ const colorMark = marks?.find((mark) => mark.type.name === 'textStyle' && mark.attrs.color);
684
+
685
+ let color = colorMark?.attrs.color || currentColor;
686
+
687
+ // Convert RGB to Hex if needed
688
+ if (color.startsWith('rgb')) {
689
+ const matches = color.match(/\d+/g);
690
+ if (matches && matches.length >= 3) {
691
+ color = rgbToHex(parseInt(matches[0]), parseInt(matches[1]), parseInt(matches[2]));
692
+ }
693
+ }
694
+
695
+ // Ensure color is in hex format and has 100% opacity
696
+ if (color.length === 9) {
697
+ // If it's a hex with alpha
698
+ color = color.substring(0, 7); // Remove alpha channel
699
+ }
700
+
701
+ return color;
702
+ }
703
+
704
+ // Update handleSelectionChange to properly handle color conversion
705
+ function handleSelectionChange() {
706
+ if (!editorInstance) return;
707
+
708
+ const { from, to } = editorInstance.state.selection;
709
+ const hasSelection = from !== to;
710
+
711
+ if (hasSelection) {
712
+ selectedRange = { from, to };
713
+
714
+ // Get the selected text and check for color mark
715
+ const marks = editorInstance.state.doc.nodeAt(from)?.marks || [];
716
+ const colorMark = marks.find((mark) => mark.type.name === 'textStyle' && mark.attrs.color);
717
+
718
+ // Update currentColor if a color mark is found
719
+ if (colorMark?.attrs.color) {
720
+ let color = colorMark.attrs.color;
721
+
722
+ // Convert RGB to Hex if needed
723
+ if (color.startsWith('rgb')) {
724
+ const matches = color.match(/\d+/g);
725
+ if (matches && matches.length >= 3) {
726
+ color = rgbToHex(parseInt(matches[0]), parseInt(matches[1]), parseInt(matches[2]));
727
+ }
728
+ }
729
+
730
+ // Remove alpha channel if present
731
+ if (color.length === 9) {
732
+ color = color.substring(0, 7);
733
+ }
734
+
735
+ currentColor = color;
736
+ }
737
+
738
+ // console.log('Selection updated:', {
739
+ // text: editorInstance.state.doc.textBetween(from, to),
740
+ // range: { from, to },
741
+ // style: currentTextStyle,
742
+ // format: [
743
+ // ...(editorInstance.isActive('bold') ? ['b'] : []),
744
+ // ...(editorInstance.isActive('italic') ? ['i'] : []),
745
+ // ...(editorInstance.isActive('underline') ? ['u'] : []),
746
+ // ...(editorInstance.isActive('link') ? ['link'] : [])
747
+ // ],
748
+ // color: currentColor
749
+ // });
750
+ } else {
751
+ selectedRange = null;
752
+ currentColor = textColor; // Reset to default color when deselecting
753
+ }
754
+ }
755
+
756
+ // Add this state to track animation
757
+ let isColorPickerAnimating = $state(false);
758
+
759
+ // Update handleColorButtonClick to ensure hex format
760
+ function handleColorButtonClick() {
761
+ if (!editorInstance) return;
762
+
763
+ const { from, to } = editorInstance.state.selection;
764
+ if (from !== to) {
765
+ selectedRange = { from, to };
766
+ isSelectionActive = true;
767
+
768
+ // Get and convert color to hex format
769
+ let selectedColor = getSelectedTextColor();
770
+ // Ensure we convert any rgb colors to hex
771
+ if (selectedColor.startsWith('rgb')) {
772
+ const matches = selectedColor.match(/\d+/g);
773
+ if (matches && matches.length >= 3) {
774
+ selectedColor = rgbToHex(
775
+ parseInt(matches[0]),
776
+ parseInt(matches[1]),
777
+ parseInt(matches[2])
778
+ );
779
+ }
780
+ }
781
+ // Remove any alpha channel
782
+ if (selectedColor.length === 9) {
783
+ selectedColor = selectedColor.substring(0, 7);
784
+ }
785
+
786
+ currentColor = selectedColor;
787
+
788
+ // Set focus to editor
789
+ editorHasFocus = true;
790
+ // editorInstance.commands.focus();
791
+ } else {
792
+ selectedRange = null;
793
+ isSelectionActive = false;
794
+ }
795
+
796
+ showColorPicker = true;
797
+ isColorPickerAnimating = true;
798
+
799
+ // console.log('Color picker toolbar opened with selection:', {
800
+ // range: selectedRange,
801
+ // color: currentColor,
802
+ // hasFocus: editorHasFocus,
803
+ // isActive
804
+ // });
805
+ }
806
+
807
+ // Update the event handler function to handle CustomEvent
808
+ function handleColorPickerInteraction(event: CustomEvent<any>) {
809
+ // Get the original MouseEvent from the detail if available
810
+ const mouseEvent = event.detail?.originalEvent as MouseEvent;
811
+ if (mouseEvent) {
812
+ // Prevent the default behavior that might clear the selection
813
+ mouseEvent.preventDefault();
814
+ mouseEvent.stopPropagation();
815
+ }
816
+
817
+ // Reapply the selection if it exists
818
+ if (selectedRange && editorInstance) {
819
+ editorInstance.chain().focus().setTextSelection(selectedRange).run();
820
+ }
821
+ }
822
+
823
+ // Update handleColorPickerClose function
824
+ function handleColorPickerClose() {
825
+ showColorPicker = false;
826
+ isColorPickerAnimating = false;
827
+ isSelectionActive = false;
828
+
829
+ if (editorInstance) {
830
+ // Create a chain to handle all operations
831
+ const chain = editorInstance.chain();
832
+
833
+ // Remove highlight if it exists
834
+ chain.unsetMark('highlight');
835
+
836
+ // Store current selection before cleanup
837
+ const currentSelection = editorInstance.state.selection;
838
+ const hasSelection = currentSelection.from !== currentSelection.to;
839
+
840
+ // Run the chain
841
+ chain.run();
842
+
843
+ // Remove hide-selection class
844
+ editorInstance.view.dom.classList.remove('hide-selection');
845
+
846
+ // Always focus the editor first
847
+ editorInstance.view.focus();
848
+
849
+ // Then reapply selection if it existed
850
+ if (hasSelection) {
851
+ editorInstance.commands.setTextSelection({
852
+ from: currentSelection.from,
853
+ to: currentSelection.to
854
+ });
855
+ }
856
+ }
857
+ }
858
+
859
+ // Add effect to handle clicks outside Color Select
860
+ $effect(() => {
861
+ if (isDestroyed) return;
862
+ const handleClickOutside = (event: MouseEvent) => {
863
+ if (isDestroyed) return;
864
+ // Looked for in the tree this editor is in (inside a module, `document` has none of the editor's elements and may
865
+ // have a popover of the customer's page), and checked with the event's path (the target the document sees is the
866
+ // module's host)
867
+ const colorSelectModals = queryAllInTreeOf(toolbarRef, '[data-radix-popper-content-wrapper]');
868
+ const isClickingColorSelect = colorSelectModals.some((colorSelectModal) =>
869
+ isEventInside(event, colorSelectModal)
870
+ );
871
+
872
+ // Don't do anything if clicking within the color select modal
873
+ if (isClickingColorSelect) {
874
+ // Prevent any focus changes
875
+ event.preventDefault();
876
+ event.stopPropagation();
877
+ return;
878
+ }
879
+ };
880
+
881
+ if (isColorSelectOpen) {
882
+ document.addEventListener('mousedown', handleClickOutside);
883
+ return () => document.removeEventListener('mousedown', handleClickOutside);
884
+ }
885
+ });
886
+
887
+ /**
888
+ * Color Management System
889
+ *
890
+ * Handles text color operations:
891
+ * - Stores and restores text selection during color picker use
892
+ * - Manages color picker visibility state
893
+ * - Applies colors to selected text
894
+ * - Retrieves current text color for selected range
895
+ *
896
+ * Selection Preservation:
897
+ * - Stores selection before opening color picker
898
+ * - Restores selection after color picker closes
899
+ * - Handles edge cases when no text is selected
900
+ */
901
+
902
+ // Add this with the other function declarations in the script section
903
+ function handleToolbarInteraction(event: MouseEvent) {
904
+ const target = event.target as HTMLElement;
905
+
906
+ // If clicking toolbar elements or color picker, maintain expanded state
907
+ if (
908
+ target.matches('input, button, [role="button"], [tabindex="0"]') ||
909
+ target.closest('.color-picker-container')
910
+ ) {
911
+ // Keep toolbar enabled since we're interacting with it
912
+ editorHasFocus = true;
913
+ return;
914
+ }
915
+
916
+ event.preventDefault();
917
+ event.stopPropagation();
918
+
919
+ // When clicking toolbar itself, maintain focus and enabled state
920
+ if (editorInstance) {
921
+ editorInstance.commands.focus();
922
+ editorHasFocus = true;
923
+ }
924
+ }
925
+
926
+ // Add this function to handle keyboard interactions
927
+ function handleToolbarKeyDown(event: KeyboardEvent) {
928
+ // Don't handle keyboard events for inputs and interactive elements
929
+ const target = event.target as HTMLElement;
930
+ if (target.matches('input, button, [role="button"], [tabindex="0"]')) {
931
+ return;
932
+ }
933
+
934
+ // Handle keyboard interactions for toolbar
935
+ if (event.key === 'Enter' || event.key === ' ') {
936
+ event.preventDefault();
937
+ handleToolbarInteraction(event as unknown as MouseEvent);
938
+ }
939
+ }
940
+
941
+ // Update the effect that maintains selection during color picker interactions
942
+ $effect(() => {
943
+ if (isDestroyed) return;
944
+ if (showColorPicker && selectedTextRange && editorInstance) {
945
+ const { from, to } = selectedTextRange;
946
+ editorInstance.chain().setTextSelection({ from, to }).run();
947
+ }
948
+ });
949
+
950
+ // Add these near the top of the script section with other state declarations
951
+ let isColorSelectOpen = $state(false);
952
+
953
+ // Add handleKeyDown function
954
+ function handleKeyDown(event: KeyboardEvent) {
955
+ if (event.key === 'Escape') {
956
+ if (showColorPicker) {
957
+ event.preventDefault();
958
+ handleColorPickerClose();
959
+ }
960
+ }
961
+ }
962
+
963
+ // Update handleEditorBlur to maintain toolbar state
964
+ function handleEditorBlur(relatedTarget: Node | null) {
965
+ if (!editorInstance) return;
966
+
967
+ // Looked for in the tree the editor is in: `document` does not see inside a module's shadow root, and may have a
968
+ // dialog of the customer's page
969
+ const colorSelectModal = queryInTreeOf(toolbarRef, '[data-radix-popper-content-wrapper]');
970
+ const popoverContent = queryInTreeOf(toolbarRef, '[role="dialog"]');
971
+ const commandMenu = queryInTreeOf(toolbarRef, '[cmdk-root]');
972
+
973
+ const isClickingInside =
974
+ toolbarRef?.contains(relatedTarget) ||
975
+ editorInstance.view.dom.contains(relatedTarget as Node) ||
976
+ colorSelectModal?.contains(relatedTarget as Node) ||
977
+ popoverContent?.contains(relatedTarget as Node) ||
978
+ commandMenu?.contains(relatedTarget as Node);
979
+
980
+ if (!isClickingInside) {
981
+ editorHasFocus = false;
982
+ }
983
+ }
984
+
985
+ // Add this logging helper
986
+ function logTransitionState(source: string) {
987
+ // console.log(`Transition State [${source}]:`, {
988
+ // isTransitioning,
989
+ // editorHeight,
990
+ // isActive,
991
+ // editorHasFocus,
992
+ // isIdle: editorHeight === IDLE_HEIGHT
993
+ // });
994
+ }
995
+
996
+ // Add this function to handle popover state changes
997
+ function handlePopoverOpenChange(isOpen: boolean) {
998
+ textStyleDropdownOpen = isOpen;
999
+
1000
+ // Ensure editor maintains focus when popover opens/closes
1001
+ if (editorInstance) {
1002
+ editorHasFocus = true;
1003
+ editorInstance.commands.focus();
1004
+ }
1005
+ }
1006
+
1007
+ // Add this function to handle command item selection
1008
+ function handleCommandSelect(value: string) {
1009
+ if (!editorInstance) return;
1010
+
1011
+ // Change the text style to the selected value
1012
+ handleTextStyleChange(value);
1013
+
1014
+ // Restore editor focus after command selection
1015
+ setTimeout(() => {
1016
+ if (!editorInstance) return;
1017
+ editorHasFocus = true;
1018
+ editorInstance.commands.focus();
1019
+ }, 0);
1020
+ }
1021
+
1022
+ // Add these variables to track button position
1023
+ let triggerButtonRect = $state<DOMRect | null>(null);
1024
+ let triggerButton: any;
1025
+ let triggerButtonElement: HTMLButtonElement;
1026
+
1027
+ // Add function to update position using the button element directly
1028
+ function updateTriggerPosition(buttonElement: HTMLButtonElement) {
1029
+ triggerButtonRect = buttonElement.getBoundingClientRect();
1030
+ }
1031
+
1032
+ // Add these state variables near the top with other state declarations
1033
+ let selectedRange: { from: number; to: number } | null = $state(null);
1034
+ let isSelectionActive = $state(false);
1035
+
1036
+ // Add this near the top of the script section with other constants
1037
+ const STYLE_DROPDOWN_ID = 'text-style-dropdown';
1038
+
1039
+ // Add these functions near the top with other event handlers
1040
+ function closeTextStyleDropdown() {
1041
+ if (textStyleDropdownOpen) {
1042
+ textStyleDropdownOpen = false;
1043
+ // Restore focus to editor
1044
+ if (!editorInstance) return;
1045
+
1046
+ setTimeout(() => {
1047
+ if (!editorInstance) return;
1048
+ editorHasFocus = true;
1049
+ editorInstance.commands.focus();
1050
+ }, 0);
1051
+ }
1052
+ }
1053
+
1054
+ function handleScroll() {
1055
+ closeTextStyleDropdown();
1056
+ }
1057
+
1058
+ // Add to lifecycle management
1059
+ // (listens to the page and, inside a module, to the module's own panels too: a scroll never leaves a shadow root)
1060
+ let stopListeningForScroll: () => void = () => {};
1061
+
1062
+ onMount(() => {
1063
+ stopListeningForScroll = listenForScroll(toolbarRef, handleScroll);
1064
+ });
1065
+
1066
+ onDestroy(() => {
1067
+ stopListeningForScroll();
1068
+ });
1069
+
1070
+ // Add cleanup function
1071
+ onDestroy(() => {
1072
+ isDestroyed = true;
1073
+ if (editorInstance) {
1074
+ // Store the current content before unmounting
1075
+ lastKnownContent = editorInstance.getHTML();
1076
+ wasVisible = false;
1077
+
1078
+ // Clean up editor instance
1079
+ editorInstance.destroy();
1080
+ editorInstance = null;
1081
+ }
1082
+ });
1083
+
1084
+ // Update mousedown handler to remove height changes
1085
+ function handleMouseDown(e: MouseEvent) {
1086
+ if (editorInstance) {
1087
+ const target = e.target as HTMLElement;
1088
+ const isInteractive =
1089
+ target.matches('button, input, [role="button"], [tabindex="0"]') ||
1090
+ target.closest('button, input, [role="button"], [tabindex="0"]');
1091
+
1092
+ if (!isInteractive) {
1093
+ e.preventDefault();
1094
+ e.stopPropagation();
1095
+
1096
+ // Just focus the editor
1097
+ editorHasFocus = true;
1098
+ editorInstance.commands.focus();
1099
+ }
1100
+ }
1101
+ }
1102
+
1103
+ // Update hit zone handler to remove transitions
1104
+ function handleHitZone(e: MouseEvent) {
1105
+ e.preventDefault();
1106
+ e.stopPropagation();
1107
+ if (editorInstance) {
1108
+ editorInstance.commands.focus();
1109
+ editorHasFocus = true;
1110
+ }
1111
+ }
1107
1112
  </script>
1108
1113
 
1109
1114
  <!-- svelte-ignore a11y_no_static_element_interactions -->
1110
1115
  <!-- svelte-ignore event_directive_deprecated -->
1111
- <div
1112
- class="text-area-input-controller {className ? className + ' ' : ''}flex flex-col"
1113
- on:keydown={handleKeyDown}
1114
- tabindex="-1"
1116
+ <div
1117
+ class="text-area-input-controller {className ? className + ' ' : ''}flex flex-col"
1118
+ on:keydown={handleKeyDown}
1119
+ tabindex="-1"
1115
1120
  >
1116
- <!-- Label section -->
1117
- <div class="label-container flex items-center justify-between">
1118
- <!-- svelte-ignore a11y_label_has_associated_control -->
1119
- <label class="subtext text-grey5 cursor-default select-none truncate">{label}</label>
1120
- </div>
1121
-
1122
- <!-- Main editor container -->
1123
- <div
1124
- class="main-editor-container group relative w-full h-full rounded-small widgetic-colors bg-grey1 flex flex-col overflow-hidden"
1125
- style={editorStyle}
1126
- on:mousedown={handleMouseDown}
1127
- >
1128
- <!-- Toolbar at the top -->
1129
- <div
1130
- bind:this={toolbarRef}
1131
- class="toolbar-container sticky top-0 start-0 end-0 h-[56px] bg-grey1 z-10 border-b border-grey2 overflow-visible select-none"
1132
- on:mousedown={handleToolbarInteraction}
1133
- on:click={handleToolbarInteraction}
1134
- on:keydown={handleToolbarKeyDown}
1135
- role="toolbar"
1136
- aria-label={$t('editor.textArea.toolbar')}
1137
- tabindex="-1"
1138
- >
1139
- <div class="toolbar-items-row relative flex items-center h-full w-full">
1140
- <!-- Format cluster centered; close stays on the right -->
1141
- <div class={`toolbar-items-container absolute inset-y-0 start-0 end-10 flex items-center justify-center gap-2 transition-transform duration-200 ease-out ${
1142
- isColorPickerAnimating ? 'translate-y-[-200%]' :
1143
- showColorPicker ? 'translate-y-[-200%]' :
1144
- 'translate-y-0'
1145
- }`}>
1146
- <Button
1147
- variant="outline"
1148
- size="icon"
1149
- class="color-picker-preview-button toolbar-button !h-8 !w-8 !min-w-8 !p-0 shrink-0"
1150
- onclick={(e) => {
1151
- e.stopPropagation();
1152
- e.preventDefault();
1153
- const button = e.currentTarget as HTMLButtonElement;
1154
- button.blur();
1155
- handleColorButtonClick();
1156
- }}
1157
- >
1158
- <div class="toolbar-button-content flex h-full w-full items-center justify-center">
1159
- <IconBrush
1160
- class="!text-grey5 hover:!text-grey7"
1161
- style="width: 20px !important; height: 20px !important; min-width: 20px !important; min-height: 20px !important; max-width: 20px !important; max-height: 20px !important; {selectedRange ? `color: ${currentColor} !important;` : ''}"
1162
- />
1163
- </div>
1164
- </Button>
1165
-
1166
- <!-- Text Formatting Toggle Group -->
1167
- <ToggleGroup.Root
1168
- type="multiple"
1169
- size="sm"
1170
- variant="outline"
1171
- class="text-formatting-toggle-group inline-flex h-8 gap-2"
1172
- value={toggleValues}
1173
- onValueChange={(value) => {
1174
- if (!editorInstance) return;
1175
- if (value === undefined) return;
1176
- handleToggleChange(value);
1177
- }}
1178
- >
1179
- {#each Object.entries(formatMapping) as [format, { value, icon: Icon, messageKey }] (format)}
1180
- <ToggleGroup.Item
1181
- {value}
1182
- aria-label={$t(messageKey)}
1183
- data-state={activeFormats[format as FormatType] ? 'on' : 'off'}
1184
- class="toolbar-button shrink-0 !h-8 !w-8 !min-w-8 !p-0 {activeFormats[format as FormatType] ? 'bg-muted' : ''}"
1185
- >
1186
- <div class="toolbar-button-content flex h-full w-full items-center justify-center">
1187
- <Icon
1188
- class="text-current"
1189
- style="width: 20px !important; height: 20px !important; min-width: 20px !important; min-height: 20px !important; max-width: 20px !important; max-height: 20px !important;"
1190
- />
1191
- </div>
1192
- </ToggleGroup.Item>
1193
- {/each}
1194
- </ToggleGroup.Root>
1195
-
1196
- <!-- Text Style Dropdown -->
1197
- <div class="toolbar-text-style-ct inline-flex items-center shrink-0">
1198
- <Popover.Root
1199
- bind:open={textStyleDropdownOpen}
1200
- onOpenChange={(e: any) => {
1201
- handlePopoverOpenChange(e);
1202
- textStyleDropdownOpen = e;
1203
- }}
1204
- >
1205
- <Popover.Trigger>
1206
- <Button
1207
- bind:this={triggerButton}
1208
- id="text-style-trigger"
1209
- variant="outline"
1210
- size="icon"
1211
- class="toolbar-button toolbar-dropdown-trigger !h-8 !w-11 !min-w-11 !max-w-11 !p-0 justify-center"
1212
- onclick={(e) => {
1213
- e.stopPropagation();
1214
- e.preventDefault();
1215
-
1216
- const buttonElement = e.currentTarget as HTMLButtonElement;
1217
- updateTriggerPosition(buttonElement);
1218
- buttonElement.blur();
1219
-
1220
- textStyleDropdownOpen = !textStyleDropdownOpen;
1221
- }}
1222
- >
1223
- <div class="toolbar-button-content flex h-full w-full items-center justify-center gap-0.5 px-1">
1224
- {#if currentTextStyle === 'text'}
1225
- <IconPilcrow class="h-3.5 w-3.5 shrink-0" />
1226
- {:else}
1227
- <span class="text-xs">{$t(currentTextStyleMessageKey)}</span>
1228
- {/if}
1229
- <ChevronDown class="h-3 w-3 shrink-0" />
1230
- </div>
1231
- </Button>
1232
- </Popover.Trigger>
1233
-
1234
- <Popover.Content
1235
- class="w-[200px] p-0"
1236
- >
1237
- <Command.Root>
1238
- <Command.List aria-label={$t('editor.textArea.textStyles')}>
1239
- {#each textOptions as option}
1240
- <Command.Item
1241
- value={option.value}
1242
- onclick={(e: any) => {
1243
- e.stopPropagation();
1244
- e.preventDefault();
1245
- handleCommandSelect(option.value);
1246
- }}
1247
- class="flex items-center justify-between px-2 py-1.5 text-sm hover:bg-muted cursor-pointer"
1248
- >
1249
- {#if option.icon}
1250
- <div class="flex items-center gap-2">
1251
- {#if option.icon}
1252
- <option.icon class="h-4 w-4" />
1253
- {/if}
1254
- <span>{$t(option.messageKey)}</span>
1255
- </div>
1256
- {:else}
1257
- <span>{$t(option.messageKey)}</span>
1258
- {/if}
1259
- {#if option.value === currentTextStyle}
1260
- <div class="h-4 w-4">✓</div>
1261
- {/if}
1262
- </Command.Item>
1263
- {/each}
1264
- </Command.List>
1265
- </Command.Root>
1266
- </Popover.Content>
1267
- </Popover.Root>
1268
- </div>
1269
-
1270
- <!-- List Style Dropdown -->
1271
- <div class="toolbar-list-style-ct inline-flex items-center shrink-0">
1272
- <Popover.Root
1273
- bind:open={listStyleDropdownOpen}
1274
- onOpenChange={(e: any) => {
1275
- handlePopoverOpenChange(e);
1276
- listStyleDropdownOpen = e;
1277
- }}
1278
- >
1279
- <Popover.Trigger>
1280
- <Button
1281
- variant="outline"
1282
- size="icon"
1283
- id="list-style-trigger"
1284
- class="toolbar-button toolbar-dropdown-trigger !h-8 !w-11 !min-w-11 !max-w-11 !p-0 justify-center"
1285
- onclick={(e) => {
1286
- e.stopPropagation();
1287
- e.preventDefault();
1288
- const buttonElement = e.currentTarget as HTMLButtonElement;
1289
- buttonElement.blur();
1290
- listStyleDropdownOpen = !listStyleDropdownOpen;
1291
- }}
1292
- >
1293
- <div class="toolbar-button-content flex h-full w-full items-center justify-center gap-0.5 px-1">
1294
- {#if currentTextStyle && currentTextStyle.includes('List')}
1295
- {@const activeListOption = listOptions.find(opt => opt.value === currentTextStyle)}
1296
- {#if activeListOption?.icon}
1297
- <activeListOption.icon class="h-3.5 w-3.5 shrink-0" />
1298
- {/if}
1299
- {:else}
1300
- <IconList class="h-3.5 w-3.5 shrink-0" />
1301
- {/if}
1302
- <ChevronDown class="h-3 w-3 shrink-0" />
1303
- </div>
1304
- </Button>
1305
- </Popover.Trigger>
1306
-
1307
- <Popover.Content
1308
- class="style-dropdown-container w-[300px] p-0"
1309
- >
1310
- <Command.Root>
1311
- <Command.List aria-label={$t('editor.textArea.listStyles')}>
1312
- {#each listOptions as option}
1313
- <Command.Item
1314
- value={option.value}
1315
- onclick={(e: any) => {
1316
- e.stopPropagation();
1317
- e.preventDefault();
1318
- handleCommandSelect(option.value);
1319
- }}
1320
- class="flex items-center justify-between px-2 py-1.5 text-sm hover:bg-muted cursor-pointer"
1321
- >
1322
- <div class="flex items-center gap-2">
1323
- {#if option.icon}
1324
- <option.icon class="h-4 w-4" />
1325
- {/if}
1326
- <span>{$t(option.messageKey)}</span>
1327
- </div>
1328
- {#if option.value === currentTextStyle}
1329
- <div class="h-4 w-4">✓</div>
1330
- {/if}
1331
- </Command.Item>
1332
- {/each}
1333
- </Command.List>
1334
- </Command.Root>
1335
- </Popover.Content>
1336
- </Popover.Root>
1337
- </div>
1338
- </div>
1339
-
1340
- {#if onClose && !showColorPicker && !isColorPickerAnimating}
1341
- <Button
1342
- variant="ghost"
1343
- class="toolbar-close-button ms-auto shrink-0 p-0 hover:bg-transparent h-8 w-8 me-2 z-10"
1344
- onclick={(e) => {
1345
- e.stopPropagation();
1346
- e.preventDefault();
1347
- onClose();
1348
- }}
1349
- >
1350
- <X class="h-6 w-6 text-grey5 hover:text-grey7" />
1351
- </Button>
1352
- {/if}
1353
-
1354
- {#if showColorPicker || isColorPickerAnimating}
1355
- <div class={`color-picker-parent flex items-center gap-2 absolute inset-0 z-20 bg-grey1 px-3 transition-transform duration-200 ease-out ${
1356
- isColorPickerAnimating ? 'translate-y-0' :
1357
- showColorPicker ? 'translate-y-0' :
1358
- 'translate-y-[200%]'
1359
- }`}>
1360
- <Button
1361
- variant="outline"
1362
- size="icon"
1363
- class="color-picker-close-button toolbar-button !h-8 !w-8 !p-0 shrink-0"
1364
- onclick={(e) => {
1365
- e.stopPropagation();
1366
- e.preventDefault();
1367
- const button = e.currentTarget as HTMLButtonElement;
1368
- button.blur();
1369
- handleColorPickerClose();
1370
- }}
1371
- >
1372
- <div class="toolbar-button-content flex h-full w-full items-center justify-center">
1373
- <X class="h-4 w-4" />
1374
- </div>
1375
- </Button>
1376
-
1377
- <div class="color-picker-toolbar-slot relative w-[185px] shrink-0 overflow-visible">
1378
- <ColorPickerInputController
1379
- bind:value={currentColor}
1380
- onChange={(color) => {
1381
- currentColor = color;
1382
- handleColorChange(color);
1383
- }}
1384
- controllerId="text-color-picker"
1385
- saveRecentColors={true}
1386
- showOpacityControls={false}
1387
- showRing={false}
1388
- portalTarget="text-area-portal"
1389
- on:mousedown={handleColorPickerInteraction}
1390
- on:mousemove={handleColorPickerInteraction}
1391
- on:focus={() => {
1392
- if (editorInstance && selectedRange) {
1393
- editorInstance.chain()
1394
- .setTextSelection(selectedRange)
1395
- .setMark('highlight', { color: 'var(--text-background-color)' })
1396
- .run();
1397
- editorInstance.view.dom.classList.add('hide-selection');
1398
- }
1399
- }}
1400
- on:blur={() => {
1401
- if (editorInstance) {
1402
- editorInstance.chain().unsetMark('highlight').run();
1403
- }
1404
- }}
1405
- />
1406
- </div>
1407
- </div>
1408
- {/if}
1409
- </div>
1410
- </div>
1411
-
1412
- <!-- Scrollable content area -->
1413
- <div class="editor-content-area min-h-0 flex-1 overflow-y-auto overflow-x-hidden">
1414
- <ShadEditor
1415
- bind:content={value}
1416
- showToolbar={false}
1417
- locale={$shadEditorLanguage.locale ?? undefined}
1418
- messages={$shadEditorLanguage.messages ?? undefined}
1419
- class="shad-editor subtext {editorClass} {showColorPicker || textStyleDropdownOpen ? 'color-picking-active' : ''} {editorHasFocus ? 'editor-focused' : ''} {isSelectionActive ? 'selection-active' : ''}"
1420
- on:mount={handleEditorMount}
1421
- on:update={handleEditorUpdate}
1422
- />
1423
- </div>
1424
- </div>
1425
-
1426
- {#if description}
1427
- <p class="text-sm text-muted-foreground mt-2">{description}</p>
1428
- {/if}
1121
+ <!-- Label section -->
1122
+ <div class="label-container flex items-center justify-between">
1123
+ <!-- svelte-ignore a11y_label_has_associated_control -->
1124
+ <label class="text-caption text-muted-foreground cursor-default select-none truncate"
1125
+ >{label}</label
1126
+ >
1127
+ </div>
1128
+
1129
+ <!-- Main editor container -->
1130
+ <div
1131
+ class="main-editor-container group relative flex h-full w-full flex-col gap-2 overflow-hidden rounded-lg bg-accent pt-2.5 px-4 pb-4"
1132
+ style={editorStyle}
1133
+ on:mousedown={handleMouseDown}
1134
+ >
1135
+ <!-- Toolbar at the top -->
1136
+ <div
1137
+ bind:this={toolbarRef}
1138
+ class="toolbar-container sticky top-0 z-10 h-9 shrink-0 select-none overflow-visible border-b border-border bg-transparent"
1139
+ on:mousedown={handleToolbarInteraction}
1140
+ on:click={handleToolbarInteraction}
1141
+ on:keydown={handleToolbarKeyDown}
1142
+ role="toolbar"
1143
+ aria-label={$t('editor.textArea.toolbar')}
1144
+ tabindex="-1"
1145
+ >
1146
+ <div
1147
+ class="toolbar-items-row relative flex h-full w-full max-w-[370px] items-center justify-between gap-2"
1148
+ >
1149
+ <!-- Format cluster centered; close stays on the right -->
1150
+ <div
1151
+ class={`toolbar-items-container flex min-w-0 flex-1 items-center gap-2 transition-transform duration-base ease-out ${
1152
+ showColorPicker || isColorPickerAnimating ? 'me-8' : ''
1153
+ } ${
1154
+ isColorPickerAnimating
1155
+ ? 'translate-y-[-200%]'
1156
+ : showColorPicker
1157
+ ? 'translate-y-[-200%]'
1158
+ : 'translate-y-0'
1159
+ }`}
1160
+ >
1161
+ <!-- Update the color picker button to show selected color -->
1162
+ <Button
1163
+ variant="ghost"
1164
+ size="icon"
1165
+ class="color-picker-preview-button size-9 shrink-0 rounded-lg border-0 bg-background p-2 hover:bg-accent data-[state=on]:bg-brand-subtle"
1166
+ onclick={(e) => {
1167
+ e.stopPropagation();
1168
+ e.preventDefault();
1169
+ const button = e.currentTarget as HTMLButtonElement;
1170
+ button.blur();
1171
+ handleColorButtonClick();
1172
+ }}
1173
+ >
1174
+ <div class="toolbar-button-content flex h-full w-full items-center justify-center">
1175
+ <!-- Color the brush icon based on selected color -->
1176
+ <IconBrush
1177
+ class="{toolbarIconClass} text-muted-foreground"
1178
+ style={selectedRange ? `color: ${currentColor}` : ''}
1179
+ />
1180
+ </div>
1181
+ </Button>
1182
+
1183
+ <!-- Text Formatting Toggle Group -->
1184
+ <ToggleGroup.Root
1185
+ type="multiple"
1186
+ class="text-formatting-toggle-group inline-flex h-9 gap-2 bg-transparent"
1187
+ value={toggleValues}
1188
+ onValueChange={(value) => {
1189
+ if (!editorInstance) return;
1190
+ if (value === undefined) return;
1191
+ handleToggleChange(value);
1192
+ }}
1193
+ >
1194
+ {#each Object.entries(formatMapping) as [format, { value, icon: Icon, messageKey }] (format)}
1195
+ <ToggleGroup.Item
1196
+ {value}
1197
+ aria-label={$t(messageKey)}
1198
+ data-state={activeFormats[format as FormatType] ? 'on' : 'off'}
1199
+ class="size-9 shrink-0 rounded-lg border-0 bg-background p-2 hover:bg-accent data-[state=on]:bg-brand-subtle data-[state=on]:text-foreground"
1200
+ >
1201
+ <div class="toolbar-button-content flex h-full w-full items-center justify-center">
1202
+ <Icon class="{toolbarIconClass} text-current" />
1203
+ </div>
1204
+ </ToggleGroup.Item>
1205
+ {/each}
1206
+ </ToggleGroup.Root>
1207
+
1208
+ <!-- Text Style Dropdown -->
1209
+ <div class="toolbar-text-style-ct inline-flex items-center shrink-0">
1210
+ <Popover.Root
1211
+ bind:open={textStyleDropdownOpen}
1212
+ onOpenChange={(e: any) => {
1213
+ handlePopoverOpenChange(e);
1214
+ textStyleDropdownOpen = e;
1215
+ }}
1216
+ >
1217
+ <Popover.Trigger>
1218
+ <Button
1219
+ bind:this={triggerButton}
1220
+ id="text-style-trigger"
1221
+ variant="ghost"
1222
+ data-state={textStyleDropdownOpen ? 'open' : 'closed'}
1223
+ class="toolbar-dropdown-trigger h-9 w-[51px] min-w-[51px] max-w-[51px] shrink-0 justify-center gap-1 rounded-lg border-0 bg-background p-0 hover:bg-accent data-[state=open]:ring-2 data-[state=open]:ring-ring data-[state=open]:ring-offset-2 data-[state=open]:ring-offset-background"
1224
+ onclick={(e) => {
1225
+ e.stopPropagation();
1226
+ e.preventDefault();
1227
+
1228
+ const buttonElement = e.currentTarget as HTMLButtonElement;
1229
+ updateTriggerPosition(buttonElement);
1230
+ buttonElement.blur();
1231
+
1232
+ textStyleDropdownOpen = !textStyleDropdownOpen;
1233
+ }}
1234
+ >
1235
+ <div
1236
+ class="toolbar-button-content flex h-full w-full items-center justify-center gap-1 px-1"
1237
+ >
1238
+ {#if currentTextStyle === 'text'}
1239
+ <IconPilcrow class={toolbarIconClass} />
1240
+ {:else}
1241
+ {@const activeHeading = textOptions.find((o) => o.value === currentTextStyle)}
1242
+ {#if activeHeading?.icon}
1243
+ <activeHeading.icon class={toolbarIconClass} />
1244
+ {:else}
1245
+ <span class="text-label-small">{$t(currentTextStyleMessageKey)}</span>
1246
+ {/if}
1247
+ {/if}
1248
+ {#if textStyleDropdownOpen}
1249
+ <IconChevronUp class={toolbarIconClass} />
1250
+ {:else}
1251
+ <IconChevronDown class={toolbarIconClass} />
1252
+ {/if}
1253
+ </div>
1254
+ </Button>
1255
+ </Popover.Trigger>
1256
+
1257
+ <Popover.Content
1258
+ class="w-[200px] rounded-xl border border-border bg-popover p-1 shadow-none"
1259
+ align="end"
1260
+ sideOffset={8}
1261
+ >
1262
+ <Command.Root>
1263
+ <Command.List
1264
+ aria-label={$t('editor.textArea.textStyles')}
1265
+ class="flex flex-col gap-0.5"
1266
+ >
1267
+ {#each textOptions as option}
1268
+ <Command.Item
1269
+ value={option.value}
1270
+ onclick={(e: any) => {
1271
+ e.stopPropagation();
1272
+ e.preventDefault();
1273
+ handleCommandSelect(option.value);
1274
+ }}
1275
+ class="flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-body hover:bg-accent data-[selected=true]:bg-accent {option.value ===
1276
+ currentTextStyle
1277
+ ? 'bg-brand-subtle'
1278
+ : ''}"
1279
+ >
1280
+ <span
1281
+ class="flex size-4 shrink-0 items-center justify-center"
1282
+ aria-hidden="true"
1283
+ >
1284
+ {#if option.value === currentTextStyle}
1285
+ <IconCheck class={toolbarIconClass} />
1286
+ {/if}
1287
+ </span>
1288
+ {#if option.icon}
1289
+ <option.icon class="{toolbarIconClass} text-muted-foreground" />
1290
+ {/if}
1291
+ <span class="min-w-0 flex-1 truncate text-start"
1292
+ >{$t(option.messageKey)}</span
1293
+ >
1294
+ </Command.Item>
1295
+ {/each}
1296
+ </Command.List>
1297
+ </Command.Root>
1298
+ </Popover.Content>
1299
+ </Popover.Root>
1300
+ </div>
1301
+
1302
+ <!-- List Style Dropdown -->
1303
+ <div class="toolbar-list-style-ct inline-flex items-center shrink-0">
1304
+ <Popover.Root
1305
+ bind:open={listStyleDropdownOpen}
1306
+ onOpenChange={(e: any) => {
1307
+ handlePopoverOpenChange(e);
1308
+ listStyleDropdownOpen = e;
1309
+ }}
1310
+ >
1311
+ <Popover.Trigger>
1312
+ <Button
1313
+ variant="ghost"
1314
+ id="list-style-trigger"
1315
+ data-state={listStyleDropdownOpen ? 'open' : 'closed'}
1316
+ class="toolbar-dropdown-trigger h-9 w-[51px] min-w-[51px] max-w-[51px] shrink-0 justify-center gap-1 rounded-lg border-0 bg-background p-0 hover:bg-accent data-[state=open]:ring-2 data-[state=open]:ring-ring data-[state=open]:ring-offset-2 data-[state=open]:ring-offset-background"
1317
+ onclick={(e) => {
1318
+ e.stopPropagation();
1319
+ e.preventDefault();
1320
+ const buttonElement = e.currentTarget as HTMLButtonElement;
1321
+ buttonElement.blur();
1322
+ listStyleDropdownOpen = !listStyleDropdownOpen;
1323
+ }}
1324
+ >
1325
+ <div
1326
+ class="toolbar-button-content flex h-full w-full items-center justify-center gap-1 px-1"
1327
+ >
1328
+ {#if currentTextStyle && currentTextStyle.includes('List')}
1329
+ {@const activeListOption = listOptions.find(
1330
+ (opt) => opt.value === currentTextStyle
1331
+ )}
1332
+ {#if activeListOption?.icon}
1333
+ <activeListOption.icon class={toolbarIconClass} />
1334
+ {/if}
1335
+ {:else}
1336
+ <IconList class={toolbarIconClass} />
1337
+ {/if}
1338
+ {#if listStyleDropdownOpen}
1339
+ <IconChevronUp class={toolbarIconClass} />
1340
+ {:else}
1341
+ <IconChevronDown class={toolbarIconClass} />
1342
+ {/if}
1343
+ </div>
1344
+ </Button>
1345
+ </Popover.Trigger>
1346
+
1347
+ <Popover.Content
1348
+ class="style-dropdown-container w-[200px] rounded-xl border border-border bg-popover p-1 shadow-none"
1349
+ align="end"
1350
+ sideOffset={8}
1351
+ >
1352
+ <Command.Root>
1353
+ <Command.List
1354
+ aria-label={$t('editor.textArea.listStyles')}
1355
+ class="flex flex-col gap-0.5"
1356
+ >
1357
+ {#each listOptions as option}
1358
+ <Command.Item
1359
+ value={option.value}
1360
+ onclick={(e: any) => {
1361
+ e.stopPropagation();
1362
+ e.preventDefault();
1363
+ handleCommandSelect(option.value);
1364
+ }}
1365
+ class="flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-body hover:bg-accent data-[selected=true]:bg-accent {option.value ===
1366
+ currentTextStyle
1367
+ ? 'bg-brand-subtle'
1368
+ : ''}"
1369
+ >
1370
+ <span
1371
+ class="flex size-4 shrink-0 items-center justify-center"
1372
+ aria-hidden="true"
1373
+ >
1374
+ {#if option.value === currentTextStyle}
1375
+ <IconCheck class={toolbarIconClass} />
1376
+ {/if}
1377
+ </span>
1378
+ {#if option.icon}
1379
+ <option.icon class="{toolbarIconClass} text-muted-foreground" />
1380
+ {/if}
1381
+ <span class="min-w-0 flex-1 truncate text-start"
1382
+ >{$t(option.messageKey)}</span
1383
+ >
1384
+ </Command.Item>
1385
+ {/each}
1386
+ </Command.List>
1387
+ </Command.Root>
1388
+ </Popover.Content>
1389
+ </Popover.Root>
1390
+ </div>
1391
+ </div>
1392
+
1393
+ {#if onClose && !showColorPicker && !isColorPickerAnimating}
1394
+ <IconButton
1395
+ variant="ghost"
1396
+ size="default"
1397
+ class="toolbar-close-button z-10 ms-auto shrink-0"
1398
+ label={$t('editor.textArea.closePanel')}
1399
+ onclick={(e) => {
1400
+ e.stopPropagation();
1401
+ e.preventDefault();
1402
+ onClose();
1403
+ }}
1404
+ >
1405
+ <IconArrowsDiagonalMinimize class={toolbarIconClass} />
1406
+ </IconButton>
1407
+ {/if}
1408
+
1409
+ {#if showColorPicker || isColorPickerAnimating}
1410
+ <div
1411
+ class={`color-picker-parent absolute inset-0 z-20 flex items-center gap-2 bg-accent px-1 transition-transform duration-base ease-out ${
1412
+ isColorPickerAnimating
1413
+ ? 'translate-y-0'
1414
+ : showColorPicker
1415
+ ? 'translate-y-0'
1416
+ : 'translate-y-[200%]'
1417
+ }`}
1418
+ >
1419
+ <IconButton
1420
+ variant="ghost"
1421
+ size="default"
1422
+ class="color-picker-close-button toolbar-button shrink-0"
1423
+ label={$t('editor.textArea.closeColorMode')}
1424
+ onclick={(e) => {
1425
+ e.stopPropagation();
1426
+ e.preventDefault();
1427
+ const button = e.currentTarget as HTMLButtonElement;
1428
+ button.blur();
1429
+ handleColorPickerClose();
1430
+ }}
1431
+ >
1432
+ <IconChevronUp class={toolbarIconClass} />
1433
+ </IconButton>
1434
+
1435
+ <div
1436
+ class="color-picker-toolbar-slot relative w-[286px] max-w-[286px] shrink-0 overflow-visible"
1437
+ >
1438
+ <ColorPickerInputController
1439
+ bind:value={currentColor}
1440
+ onChange={(color) => {
1441
+ currentColor = color;
1442
+ handleColorChange(color);
1443
+ }}
1444
+ controllerId="text-color-picker"
1445
+ saveRecentColors={true}
1446
+ showOpacityControls={false}
1447
+ showRing={false}
1448
+ portalTarget="text-area-portal"
1449
+ on:mousedown={handleColorPickerInteraction}
1450
+ on:mousemove={handleColorPickerInteraction}
1451
+ on:focus={() => {
1452
+ if (editorInstance && selectedRange) {
1453
+ editorInstance
1454
+ .chain()
1455
+ .setTextSelection(selectedRange)
1456
+ .setMark('highlight', { color: 'var(--text-background-color)' })
1457
+ .run();
1458
+ editorInstance.view.dom.classList.add('hide-selection');
1459
+ }
1460
+ }}
1461
+ on:blur={() => {
1462
+ if (editorInstance) {
1463
+ editorInstance.chain().unsetMark('highlight').run();
1464
+ }
1465
+ }}
1466
+ />
1467
+ </div>
1468
+ </div>
1469
+ {/if}
1470
+ </div>
1471
+ </div>
1472
+
1473
+ <!-- Scrollable content area -->
1474
+ <div class="editor-content-area min-h-0 flex-1 overflow-y-auto overflow-x-hidden">
1475
+ <ShadEditor
1476
+ bind:content={value}
1477
+ showToolbar={false}
1478
+ locale={$shadEditorLanguage.locale ?? undefined}
1479
+ messages={$shadEditorLanguage.messages ?? undefined}
1480
+ class="shad-editor text-body text-foreground {editorClass} {showColorPicker ||
1481
+ textStyleDropdownOpen
1482
+ ? 'color-picking-active'
1483
+ : ''} {editorHasFocus ? 'editor-focused' : ''} {isSelectionActive
1484
+ ? 'selection-active'
1485
+ : ''}"
1486
+ on:mount={handleEditorMount}
1487
+ on:update={handleEditorUpdate}
1488
+ />
1489
+ </div>
1490
+ </div>
1491
+
1492
+ {#if description}
1493
+ <p class="text-caption text-muted-foreground mt-2">{description}</p>
1494
+ {/if}
1429
1495
  </div>
1430
1496
 
1431
1497
  <style>
1432
-
1433
- /* Update editor styles */
1434
- :global(.text-area-input-controller .ProseMirror) {
1435
- outline: none !important;
1436
- width: 100%;
1437
- min-height: 100%;
1438
- height: auto;
1439
- padding: var(--editor-padding-top, 0.35rem) var(--editor-padding-right, 0.35rem)
1440
- var(--editor-padding-bottom, 0.35rem) var(--editor-padding-left, 0.35rem);
1441
- background: transparent !important;
1442
- border: none !important;
1443
- border-radius: inherit;
1444
- overflow: visible;
1445
- margin-top: 0;
1446
- scrollbar-width: thin;
1447
- scrollbar-color: transparent transparent;
1448
- }
1449
-
1450
- :global(.ProseMirror p) {
1451
- margin: 0;
1452
- }
1453
-
1454
- /* Remove height management styles */
1455
- :global(.editor-height) {
1456
- border: none;
1457
- overflow: auto;
1458
- }
1459
-
1460
- /* Keep scrollbar styles */
1461
- :global(.ProseMirror::-webkit-scrollbar) {
1462
- width: 6px;
1463
- margin-inline-end: 2px;
1464
- }
1465
-
1466
- :global(.ProseMirror::-webkit-scrollbar-track) {
1467
- background-color: transparent;
1468
- margin-inline-end: 2px;
1469
- }
1470
-
1471
- :global(.ProseMirror::-webkit-scrollbar-thumb) {
1472
- background-color: hsl(var(--border)) !important;
1473
- border-radius: 3px;
1474
- margin-inline-end: 2px;
1475
- }
1476
-
1477
- :global(.ProseMirror::-webkit-scrollbar-thumb:hover) {
1478
- background-color: hsl(var(--muted-foreground) / 0.6) !important;
1479
- }
1480
-
1481
- /* Keep typography styles */
1482
- :global(.ProseMirror p),
1483
- :global(.ProseMirror h1),
1484
- :global(.ProseMirror h2),
1485
- :global(.ProseMirror h3),
1486
- :global(.ProseMirror li p),
1487
- :global(.ProseMirror [data-type="taskItem"] p) {
1488
- margin: 0;
1489
- line-height: 1.4;
1490
- }
1491
-
1492
- /* Heading specific styles */
1493
- :global(.ProseMirror h1) { font-size: 2em; font-weight: 700; }
1494
- :global(.ProseMirror h2) { font-size: 1.5em; font-weight: 700; }
1495
- :global(.ProseMirror h3) { font-size: 1.17em; font-weight: 700; }
1496
-
1497
- /* List styles - Consolidated */
1498
- :global(.ProseMirror ul),
1499
- :global(.ProseMirror ol),
1500
- :global(.ProseMirror [data-type="taskList"]) {
1501
- padding-inline-start: 1.5rem;
1502
- margin: 0;
1503
- line-height: 1.4;
1504
- }
1505
-
1506
- :global(.ProseMirror li),
1507
- :global(.ProseMirror [data-type="taskItem"]) {
1508
- position: relative;
1509
- padding-inline-start: 0.5rem;
1510
- margin: 0;
1511
- }
1512
-
1513
- /* Task list specific styles */
1514
- :global(.ProseMirror [data-type="taskList"]) {
1515
- list-style: none;
1516
- padding-inline-start: 0rem !important;
1517
- }
1518
-
1519
- :global(.ProseMirror [data-type="taskItem"]) {
1520
- display: flex;
1521
- align-items: flex-start;
1522
- padding-inline-start: 0 !important;
1523
- margin-inline-start: 0 !important;
1524
- gap: 0.5rem;
1525
- }
1526
-
1527
- :global(.ProseMirror [data-type="taskItem"] label) {
1528
- display: flex;
1529
- align-items: center;
1530
- margin: 0;
1531
- padding: 0;
1532
- }
1533
-
1534
- :global(.ProseMirror [data-type="taskItem"] input[type="checkbox"]) {
1535
- margin: 0;
1536
- margin-top: 0.4em;
1537
- }
1538
-
1539
- /* Focus states - Consolidated */
1540
- :global(.ProseMirror),
1541
- :global(.ProseMirror:hover),
1542
- :global(.ProseMirror:focus),
1543
- :global(.ProseMirror:focus-visible),
1544
- :global(.ProseMirror:focus-within),
1545
- :global(.ProseMirror *),
1546
- :global(.ProseMirror * *),
1547
- :global(.ProseMirror-focused) {
1548
- border-color: transparent !important;
1549
- outline: none !important;
1550
- box-shadow: none !important;
1551
- }
1552
-
1553
- /* Container focus styles */
1554
- :global(.group:focus-within) {
1555
- outline: none !important;
1556
- }
1557
-
1558
- /* Toolbar styles - Consolidated */
1559
- :global(.toolbar-container button:focus),
1560
- :global(.toolbar-container button:focus-visible),
1561
- :global(.toolbar-container a:focus),
1562
- :global(.toolbar-container a:focus-visible) {
1563
- outline: none;
1564
- box-shadow: none;
1565
- }
1566
-
1567
- :global(.toolbar-button) {
1568
- position: relative !important;
1569
- border: 1px solid hsl(var(--border)) !important;
1570
- transition: border-color 0.2s ease-in-out, background-color 0.2s ease-in-out !important;
1571
- }
1572
-
1573
- :global(.toolbar-button:hover) {
1574
- border-color: hsl(var(--grey3)) !important;
1575
- background-color: hsl(var(--grey1)) !important;
1576
- }
1577
-
1578
- :global(.toolbar-button svg) {
1579
- transition: color 0.2s ease-in-out !important;
1580
- }
1581
-
1582
- :global(.toolbar-button:hover svg) {
1583
- color: hsl(var(--grey7)) !important;
1584
- }
1585
-
1586
- :global(.toolbar-button-content) {
1587
- position: relative !important;
1588
- z-index: 2 !important;
1589
- }
1590
-
1591
- :global(.toolbar-text-style-ct),
1592
- :global(.toolbar-list-style-ct) {
1593
- width: 44px;
1594
- min-width: 44px;
1595
- max-width: 44px;
1596
- flex-shrink: 0;
1597
- }
1598
-
1599
- :global(.text-formatting-toggle-group button),
1600
- :global(.color-picker-preview-button) {
1601
- width: 2rem !important;
1602
- min-width: 2rem !important;
1603
- max-width: 2rem !important;
1604
- height: 2rem !important;
1605
- padding: 0 !important;
1606
- }
1607
-
1608
- :global(.toolbar-text-style-ct button),
1609
- :global(.toolbar-list-style-ct button),
1610
- :global(.toolbar-dropdown-trigger) {
1611
- width: 44px !important;
1612
- min-width: 44px !important;
1613
- max-width: 44px !important;
1614
- height: 2rem !important;
1615
- padding: 0 !important;
1616
- }
1617
-
1618
- :global(.text-area-input-controller .editor-content-area) {
1619
- scrollbar-width: thin;
1620
- scrollbar-color: hsl(var(--grey3) / 0.5) transparent;
1621
- }
1622
-
1623
- :global(.text-area-input-controller .editor-content-area::-webkit-scrollbar) {
1624
- width: 6px;
1625
- }
1626
-
1627
- :global(.text-area-input-controller .editor-content-area::-webkit-scrollbar-thumb) {
1628
- background: hsl(var(--grey3) / 0.45);
1629
- border-radius: 999px;
1630
- }
1631
-
1632
- /* Input styles */
1633
- :global(input.h-8),
1634
- :global(.input-container) {
1635
- height: 2rem !important;
1636
- min-height: 2rem !important;
1637
- line-height: 2rem !important;
1638
- padding-top: 0 !important;
1639
- padding-bottom: 0 !important;
1640
- font-size: 0.875rem !important;
1641
- }
1642
-
1643
- /* Color picker styles */
1644
- :global(.color-picker-container) {
1645
- display: flex !important;
1646
- align-items: center !important;
1647
- gap: 8px !important;
1648
- }
1649
-
1650
- :global(.color-picker-container input[type="text"]) {
1651
- width: 162px !important;
1652
- min-width: 162px !important;
1653
- }
1654
-
1655
- :global(.color-picker-container:focus-within) {
1656
- z-index: 10;
1657
- }
1658
-
1659
- :global(.color-picker-container input[type="text"]),
1660
- :global(.color-picker-container input[type="text"]:focus),
1661
- :global(.color-picker-container input[type="text"]:focus-visible),
1662
- :global(.color-picker-container input[type="text"]:focus-within),
1663
- :global(.color-picker-container input[type="text"]:hover) {
1664
- outline: none !important;
1665
- border: 1px solid hsl(var(--border)) !important;
1666
- box-shadow: none !important;
1667
- --tw-ring-offset-width: 0 !important;
1668
- --tw-ring-offset-color: transparent !important;
1669
- --tw-ring-color: transparent !important;
1670
- --tw-ring-offset-shadow: none !important;
1671
- --tw-ring-shadow: none !important;
1672
- }
1673
-
1674
- /* Add these styles to ensure proper positioning */
1675
- :global(.fixed) {
1676
- position: fixed;
1677
- }
1678
-
1679
- :global(.z-50) {
1680
- z-index: 50;
1681
- }
1682
-
1683
- /* Update existing styles to handle portaled content */
1684
- :global([cmdk-root]) {
1685
- position: relative;
1686
- background: white;
1687
- border-radius: 0.375rem;
1688
- overflow: hidden;
1689
- }
1690
-
1691
- :global([cmdk-list]) {
1692
- max-height: 300px;
1693
- overflow-y: auto;
1694
- }
1695
-
1696
- :global([cmdk-item]) {
1697
- cursor: pointer;
1698
- padding: 0.5rem 1rem;
1699
- }
1700
-
1701
- :global([cmdk-item]:hover) {
1702
- background-color: hsl(var(--muted));
1703
- }
1704
-
1705
- /* Add these styles to handle the portaled color suggestions */
1706
- :global(.color-suggestions-portal) {
1707
- position: fixed;
1708
- z-index: 100;
1709
- background: white;
1710
- border-radius: 0.375rem;
1711
- box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
1712
- border: 1px solid hsl(var(--border));
1713
- }
1714
-
1715
- /* Selection Styles */
1716
- :global(.ProseMirror mark[data-color="#adcff5"]) {
1717
- background-color: #b4d5fe !important;
1718
- color: inherit !important;
1719
- border-radius: 2px !important;
1720
- padding: 2px 0 !important;
1721
- margin: -2px 0 !important;
1722
- }
1723
-
1724
- /* Selection Styles */
1725
- :global(.ProseMirror) {
1726
- --selection-color: #b4d5fe;
1727
- --text-background-color: #b4d5fe;
1728
- }
1729
-
1730
- /* Default selection style */
1731
- :global(.ProseMirror ::selection) {
1732
- background-color: var(--selection-color) !important;
1733
- color: inherit !important;
1734
- }
1735
-
1736
- /* Selection style during color picker */
1737
- :global(.ProseMirror.color-picking-active ::selection) {
1738
- background-color: var(--selection-color) !important;
1739
- color: inherit !important;
1740
- }
1741
-
1742
- /* Hide selection when text background is active */
1743
- :global(.ProseMirror.hide-selection ::selection) {
1744
- background-color: transparent !important;
1745
- }
1746
-
1747
- /* Text background highlight */
1748
- :global(.ProseMirror mark[data-highlight]) {
1749
- background-color: var(--text-background-color) !important;
1750
- color: inherit !important;
1751
- }
1752
-
1753
- :global(.text-area) {
1754
- height: 100% !important;
1755
- width: 100% !important;
1756
- border-radius: var(--radius-small) !important;
1757
- overflow: hidden !important;
1758
- background-color: hsl(var(--grey1)) !important;
1759
- border: 1px solid hsl(var(--grey2));
1760
- transition: border-color 0.2s ease !important;
1761
- }
1762
-
1763
- :global(.text-area .ProseMirror) {
1764
- margin-top: 0 !important;
1765
- padding: 8px 16px 24px 16px !important;
1766
- background-color: transparent !important;
1767
- cursor: text !important;
1768
- border: none !important;
1769
- }
1770
-
1771
- /* Add portal border radius */
1772
- :global(.portal-contents) {
1773
- border-radius: var(--radius-small) !important;
1774
- overflow: hidden !important;
1775
- }
1776
-
1777
- :global(.text-area .toolbar-container) {
1778
- padding: 10px 0 !important;
1779
- display: flex !important;
1780
- gap: 0 !important;
1781
- border-bottom: 1px solid hsl(var(--grey2)) !important;
1782
- background-color: hsl(var(--grey1)) !important;
1783
- }
1784
-
1785
- :global(.text-area .toolbar-container button) {
1786
- width: 32px !important;
1787
- height: 32px !important;
1788
- min-width: 32px !important;
1789
- max-width: 32px !important;
1790
- padding: 0 !important;
1791
- background-color: white !important;
1792
- border: 1px solid hsl(var(--grey2)) !important;
1793
- border-radius: var(--radius) !important;
1794
- display: flex !important;
1795
- align-items: center !important;
1796
- justify-content: center !important;
1797
- transition: all 0.2s !important;
1798
- }
1799
-
1800
- :global(.text-area .toolbar-container button.toolbar-dropdown-trigger),
1801
- :global(.text-area .toolbar-container #text-style-trigger),
1802
- :global(.text-area .toolbar-container #list-style-trigger) {
1803
- width: 44px !important;
1804
- min-width: 44px !important;
1805
- max-width: 44px !important;
1806
- padding: 0 !important;
1807
- }
1808
-
1809
- :global(.text-area .toolbar-container .toolbar-items-container) {
1810
- display: flex !important;
1811
- align-items: center !important;
1812
- justify-content: center !important;
1813
- gap: 8px !important;
1814
- height: 100% !important;
1815
- position: absolute !important;
1816
- inset-block: 0 !important;
1817
- inset-inline: 0 2.5rem !important;
1818
- }
1819
-
1820
- :global(.text-area #text-style-trigger) {
1821
- margin-inline-end: 0 !important;
1822
- }
1823
-
1824
- /* Color the brush icon based on selected color */
1825
- :global(.text-area .color-picker-preview-button svg) {
1826
- color: var(--selected-color, currentColor) !important;
1827
- }
1828
-
1829
- :global(.text-area .color-picker-preview-button:hover svg) {
1830
- color: var(--selected-color, hsl(var(--grey7))) !important;
1831
- }
1832
- /* Button spacing */
1833
- :global(.text-area .color-picker-preview-button) {
1834
- margin-inline-start: 0 !important;
1835
- margin-inline-end: 0 !important;
1836
- }
1837
-
1838
- :global(.text-area .text-formatting-toggle-group) {
1839
- margin-inline-end: 0 !important;
1840
- display: flex !important;
1841
- gap: 8px !important;
1842
- }
1843
-
1844
- :global(.text-area .text-formatting-toggle-group button) {
1845
- margin: 0 !important;
1846
- }
1847
-
1848
- :global(.text-area .text-formatting-toggle-group button:not(:last-child)) {
1849
- margin-inline-end: 0 !important;
1850
- }
1851
-
1852
- :global(.text-area #text-style-trigger),
1853
- :global(.text-area #list-style-trigger) {
1854
- width: 44px !important;
1855
- min-width: 44px !important;
1856
- max-width: 44px !important;
1857
- }
1858
-
1859
- :global(.text-area .toolbar-container button:hover) {
1860
- border-color: hsl(var(--grey2)) !important;
1861
- }
1862
-
1863
- :global(.text-area .toolbar-container button:active) {
1864
- transform: scale(0.95) !important;
1865
- }
1866
-
1867
- :global(.text-area .toolbar-container button svg) {
1868
- width: 20px !important;
1869
- height: 20px !important;
1870
- color: hsl(var(--grey5)) !important;
1871
- transition: color 0.2s !important;
1872
- }
1873
-
1874
- :global(.text-area .toolbar-container button:hover svg) {
1875
- color: hsl(var(--grey7)) !important;
1876
- }
1877
-
1878
- :global(.text-area .toolbar-container button[data-state="on"]) {
1879
- background-color: hsl(var(--sage-green)) !important;
1880
- border-color: hsl(var(--sage-green)) !important;
1881
- color: white !important;
1882
- }
1883
-
1884
- :global(.text-area .toolbar-container button[data-state="on"] svg),
1885
- :global(.text-area .toolbar-container button[data-state="on"] svg *) {
1886
- color: white !important;
1887
- stroke: white !important;
1888
- }
1889
-
1890
- :global(.text-area .toolbar-text-style-ct),
1891
- :global(.text-area .toolbar-list-style-ct) {
1892
- margin-inline-start: 0 !important;
1893
- }
1894
-
1895
- /* Update the color picker button to show selected color */
1896
- :global(.text-area .color-picker-preview-button) {
1897
- position: relative !important;
1898
- }
1899
-
1900
- :global(.text-area .color-picker-preview-button::after) {
1901
- display: none !important;
1902
- }
1903
-
1904
- /* Update icon color based on selection */
1905
- :global(.text-area .color-picker-preview-button .toolbar-button-content svg) {
1906
- transition: color 0.2s ease !important;
1907
- }
1908
-
1909
- :global(.text-area .color-picker-preview-button:hover .toolbar-button-content svg) {
1910
- color: currentColor !important;
1911
- }
1912
-
1913
- /* Remove hit zone since we want clicks everywhere */
1914
- .input-hit-zone {
1915
- display: none;
1916
- }
1917
-
1918
- /* Make the main container clickable */
1919
- .main-editor-container {
1920
- cursor: text;
1921
- }
1922
-
1923
- :global(.text-area .toolbar-button.h-8:not(.toolbar-dropdown-trigger):not(#text-style-trigger):not(#list-style-trigger)) {
1924
- width: 32px !important;
1925
- }
1926
-
1927
- :global(.text-area .toolbar-text-style-ct),
1928
- :global(.text-area .toolbar-list-style-ct) {
1929
- display: inline-flex !important;
1930
- width: 44px !important;
1931
- min-width: 44px !important;
1932
- max-width: 44px !important;
1933
- margin-inline-start: 0 !important;
1934
- padding-inline-start: 0 !important;
1935
- }
1936
-
1937
- /* Update color picker container styles */
1938
- :global(.color-picker-parent) {
1939
- position: absolute;
1940
- inset: 0;
1941
- padding: 0 12px;
1942
- display: flex;
1943
- align-items: center;
1944
- justify-content: flex-start;
1945
- gap: 8px;
1946
- }
1947
-
1948
- /* ColorPicker uses absolute right-0 for the Design column; in the toolbar that
1498
+ /* Update editor styles */
1499
+ :global(.text-area-input-controller .ProseMirror) {
1500
+ outline: none !important;
1501
+ width: 100%;
1502
+ min-height: 100%;
1503
+ height: auto;
1504
+ padding: var(--editor-padding-top, 0.35rem) var(--editor-padding-right, 0.35rem)
1505
+ var(--editor-padding-bottom, 0.35rem) var(--editor-padding-left, 0.35rem);
1506
+ background: transparent !important;
1507
+ border: none !important;
1508
+ border-radius: inherit;
1509
+ overflow: visible;
1510
+ margin-top: 0;
1511
+ scrollbar-width: thin;
1512
+ scrollbar-color: transparent transparent;
1513
+ }
1514
+
1515
+ :global(.ProseMirror p) {
1516
+ margin: 0;
1517
+ }
1518
+
1519
+ :global(.ProseMirror p + p) {
1520
+ margin-top: 0.75rem;
1521
+ }
1522
+
1523
+ /* Remove height management styles */
1524
+ :global(.editor-height) {
1525
+ border: none;
1526
+ overflow: auto;
1527
+ }
1528
+
1529
+ /* Keep scrollbar styles */
1530
+ :global(.ProseMirror::-webkit-scrollbar) {
1531
+ width: 6px;
1532
+ margin-inline-end: 2px;
1533
+ }
1534
+
1535
+ :global(.ProseMirror::-webkit-scrollbar-track) {
1536
+ background-color: transparent;
1537
+ margin-inline-end: 2px;
1538
+ }
1539
+
1540
+ :global(.ProseMirror::-webkit-scrollbar-thumb) {
1541
+ background-color: var(--input);
1542
+ border-radius: 2px;
1543
+ margin-inline-end: 2px;
1544
+ }
1545
+
1546
+ :global(.ProseMirror::-webkit-scrollbar-thumb:hover) {
1547
+ background-color: var(--muted-foreground);
1548
+ opacity: 0.6;
1549
+ }
1550
+
1551
+ /* Keep typography styles */
1552
+ :global(.ProseMirror p),
1553
+ :global(.ProseMirror h1),
1554
+ :global(.ProseMirror h2),
1555
+ :global(.ProseMirror h3),
1556
+ :global(.ProseMirror li p),
1557
+ :global(.ProseMirror [data-type='taskItem'] p) {
1558
+ margin: 0;
1559
+ line-height: 1.4;
1560
+ }
1561
+
1562
+ /* Heading specific styles */
1563
+ :global(.ProseMirror h1) {
1564
+ font-size: 2em;
1565
+ font-weight: 700;
1566
+ }
1567
+ :global(.ProseMirror h2) {
1568
+ font-size: 1.5em;
1569
+ font-weight: 700;
1570
+ }
1571
+ :global(.ProseMirror h3) {
1572
+ font-size: 1.17em;
1573
+ font-weight: 700;
1574
+ }
1575
+
1576
+ /* List styles - Consolidated */
1577
+ :global(.ProseMirror ul),
1578
+ :global(.ProseMirror ol),
1579
+ :global(.ProseMirror [data-type='taskList']) {
1580
+ padding-inline-start: 1.5rem;
1581
+ margin: 0;
1582
+ line-height: 1.4;
1583
+ }
1584
+
1585
+ :global(.ProseMirror li),
1586
+ :global(.ProseMirror [data-type='taskItem']) {
1587
+ position: relative;
1588
+ padding-inline-start: 0.5rem;
1589
+ margin: 0;
1590
+ }
1591
+
1592
+ /* Task list specific styles */
1593
+ :global(.ProseMirror [data-type='taskList']) {
1594
+ list-style: none;
1595
+ padding-inline-start: 0rem !important;
1596
+ }
1597
+
1598
+ :global(.ProseMirror [data-type='taskItem']) {
1599
+ display: flex;
1600
+ align-items: flex-start;
1601
+ padding-inline-start: 0 !important;
1602
+ margin-inline-start: 0 !important;
1603
+ gap: 0.5rem;
1604
+ }
1605
+
1606
+ :global(.ProseMirror [data-type='taskItem'] label) {
1607
+ display: flex;
1608
+ align-items: center;
1609
+ margin: 0;
1610
+ padding: 0;
1611
+ }
1612
+
1613
+ :global(.ProseMirror [data-type='taskItem'] input[type='checkbox']) {
1614
+ margin: 0;
1615
+ margin-top: 0.4em;
1616
+ }
1617
+
1618
+ /* Focus states - Consolidated */
1619
+ :global(.ProseMirror),
1620
+ :global(.ProseMirror:hover),
1621
+ :global(.ProseMirror:focus),
1622
+ :global(.ProseMirror:focus-visible),
1623
+ :global(.ProseMirror:focus-within),
1624
+ :global(.ProseMirror *),
1625
+ :global(.ProseMirror * *),
1626
+ :global(.ProseMirror-focused) {
1627
+ border-color: transparent !important;
1628
+ outline: none !important;
1629
+ box-shadow: none !important;
1630
+ }
1631
+
1632
+ /* Container focus styles */
1633
+ :global(.group:focus-within) {
1634
+ outline: none !important;
1635
+ }
1636
+
1637
+ /* Toolbar styles - Consolidated */
1638
+ :global(.toolbar-button-content) {
1639
+ position: relative;
1640
+ z-index: 2;
1641
+ }
1642
+
1643
+ /* Update icon color based on selection */
1644
+ :global(.color-picker-preview-button .toolbar-button-content svg) {
1645
+ transition: color 120ms ease-out;
1646
+ }
1647
+
1648
+ :global(.text-area-input-controller .editor-content-area) {
1649
+ scrollbar-width: thin;
1650
+ scrollbar-color: var(--input) transparent;
1651
+ }
1652
+
1653
+ :global(.text-area-input-controller .editor-content-area::-webkit-scrollbar) {
1654
+ width: 4px;
1655
+ }
1656
+
1657
+ :global(.text-area-input-controller .editor-content-area::-webkit-scrollbar-thumb) {
1658
+ background: var(--input);
1659
+ border-radius: 2px;
1660
+ }
1661
+
1662
+ /* Input styles */
1663
+ :global(input.h-8),
1664
+ :global(.input-container) {
1665
+ height: 2rem !important;
1666
+ min-height: 2rem !important;
1667
+ line-height: 2rem !important;
1668
+ padding-top: 0 !important;
1669
+ padding-bottom: 0 !important;
1670
+ font-size: 0.875rem !important;
1671
+ }
1672
+
1673
+ /* Color picker styles */
1674
+ :global(.color-picker-container) {
1675
+ display: flex !important;
1676
+ align-items: center !important;
1677
+ gap: 8px !important;
1678
+ }
1679
+
1680
+ :global(.color-picker-container input[type='text']) {
1681
+ width: 162px !important;
1682
+ min-width: 162px !important;
1683
+ }
1684
+
1685
+ :global(.color-picker-container:focus-within) {
1686
+ z-index: 10;
1687
+ }
1688
+
1689
+ :global(.color-picker-container input[type='text']),
1690
+ :global(.color-picker-container input[type='text']:focus),
1691
+ :global(.color-picker-container input[type='text']:focus-visible),
1692
+ :global(.color-picker-container input[type='text']:focus-within),
1693
+ :global(.color-picker-container input[type='text']:hover) {
1694
+ outline: none !important;
1695
+ border: 1px solid var(--border) !important;
1696
+ box-shadow: none !important;
1697
+ --tw-ring-offset-width: 0 !important;
1698
+ --tw-ring-offset-color: transparent !important;
1699
+ --tw-ring-color: transparent !important;
1700
+ --tw-ring-offset-shadow: none !important;
1701
+ --tw-ring-shadow: none !important;
1702
+ }
1703
+
1704
+ /* Add these styles to ensure proper positioning */
1705
+ :global(.fixed) {
1706
+ position: fixed;
1707
+ }
1708
+
1709
+ :global(.z-50) {
1710
+ z-index: 50;
1711
+ }
1712
+
1713
+ /* Update existing styles to handle portaled content */
1714
+ :global(.text-area-input-controller [cmdk-root]) {
1715
+ position: relative;
1716
+ overflow: hidden;
1717
+ background: transparent;
1718
+ }
1719
+
1720
+ :global(.text-area-input-controller [cmdk-list]) {
1721
+ max-height: 300px;
1722
+ overflow-y: auto;
1723
+ }
1724
+
1725
+ /* Add these styles to handle the portaled color suggestions */
1726
+ :global(.color-suggestions-portal) {
1727
+ position: fixed;
1728
+ z-index: 100;
1729
+ background: var(--popover);
1730
+ border-radius: var(--radius-xl);
1731
+ border: 1px solid var(--border);
1732
+ }
1733
+
1734
+ /* Selection Styles */
1735
+ :global(.ProseMirror mark[data-color='#adcff5']) {
1736
+ background-color: #b4d5fe !important;
1737
+ color: inherit !important;
1738
+ border-radius: 2px !important;
1739
+ padding: 2px 0 !important;
1740
+ margin: -2px 0 !important;
1741
+ }
1742
+
1743
+ /* Selection Styles */
1744
+ :global(.ProseMirror) {
1745
+ --selection-color: #b4d5fe;
1746
+ --text-background-color: #b4d5fe;
1747
+ }
1748
+
1749
+ /* Default selection style */
1750
+ :global(.ProseMirror ::selection) {
1751
+ background-color: var(--selection-color) !important;
1752
+ color: inherit !important;
1753
+ }
1754
+
1755
+ /* Selection style during color picker */
1756
+ :global(.ProseMirror.color-picking-active ::selection) {
1757
+ background-color: var(--selection-color) !important;
1758
+ color: inherit !important;
1759
+ }
1760
+
1761
+ /* Hide selection when text background is active */
1762
+ :global(.ProseMirror.hide-selection ::selection) {
1763
+ background-color: transparent !important;
1764
+ }
1765
+
1766
+ /* Text background highlight */
1767
+ :global(.ProseMirror mark[data-highlight]) {
1768
+ background-color: var(--text-background-color) !important;
1769
+ color: inherit !important;
1770
+ }
1771
+
1772
+ :global(.text-area) {
1773
+ height: 100% !important;
1774
+ width: 100% !important;
1775
+ overflow: hidden !important;
1776
+ border: none !important;
1777
+ background: transparent !important;
1778
+ }
1779
+
1780
+ :global(.text-area .ProseMirror) {
1781
+ margin-top: 0 !important;
1782
+ padding: 0 !important;
1783
+ background-color: transparent !important;
1784
+ cursor: text !important;
1785
+ border: none !important;
1786
+ }
1787
+
1788
+ /* Remove hit zone since we want clicks everywhere */
1789
+ .input-hit-zone {
1790
+ display: none;
1791
+ }
1792
+
1793
+ /* Make the main container clickable */
1794
+ .main-editor-container {
1795
+ cursor: text;
1796
+ }
1797
+
1798
+ /* Update color picker container styles */
1799
+ :global(.color-picker-parent) {
1800
+ position: absolute;
1801
+ inset: 0;
1802
+ padding: 0 12px;
1803
+ display: flex;
1804
+ align-items: center;
1805
+ justify-content: flex-start;
1806
+ gap: 8px;
1807
+ }
1808
+
1809
+ /* ColorPicker uses absolute right-0 for the Design column; in the toolbar that
1949
1810
  pins the 185px input to the far right and the popover flush to the edge. */
1950
- :global(.color-picker-toolbar-slot .input-controller-ct) {
1951
- position: relative !important;
1952
- right: auto !important;
1953
- left: auto !important;
1954
- }
1955
-
1956
- :global(.color-picker-toolbar-slot .input-controller-header-ct) {
1957
- display: none !important;
1958
- }
1959
-
1960
- :global(.color-picker-toolbar-slot .color-picker-input-controller-ct > .flex) {
1961
- display: block !important;
1962
- }
1963
-
1964
- :global(.color-picker-parent input[type="text"]) {
1965
- width: 162px !important;
1966
- min-width: 162px !important;
1967
- height: 36px !important;
1968
- min-height: 36px !important;
1969
- }
1970
-
1971
- :global(.color-picker-close-button) {
1972
- width: 36px !important;
1973
- height: 36px !important;
1974
- min-width: 36px !important;
1975
- min-height: 36px !important;
1976
- }
1811
+ :global(.color-picker-toolbar-slot .input-controller-ct) {
1812
+ position: relative !important;
1813
+ right: auto !important;
1814
+ left: auto !important;
1815
+ }
1816
+
1817
+ :global(.color-picker-toolbar-slot .input-controller-header-ct) {
1818
+ display: none !important;
1819
+ }
1820
+
1821
+ :global(.color-picker-toolbar-slot .color-picker-input-controller-ct > .flex) {
1822
+ display: block !important;
1823
+ }
1824
+
1825
+ :global(.color-picker-parent input[type='text']) {
1826
+ width: 162px !important;
1827
+ min-width: 162px !important;
1828
+ height: 36px !important;
1829
+ min-height: 36px !important;
1830
+ }
1831
+
1832
+ :global(.color-picker-close-button) {
1833
+ width: 36px !important;
1834
+ height: 36px !important;
1835
+ min-width: 36px !important;
1836
+ min-height: 36px !important;
1837
+ }
1977
1838
  </style>
1978
-
1979
-