@widgetic/editor 4.1.22 → 4.1.24

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 (31) hide show
  1. package/README.md +43 -0
  2. package/dist/components/editors/CompositionEditorApp.svelte +228 -206
  3. package/dist/components/editors/EmbedAssistantPanel.svelte +270 -48
  4. package/dist/components/ic/AngleInputController.svelte +18 -3
  5. package/dist/components/ic/ColorPickerInputController.svelte +81 -49
  6. package/dist/components/ic/DatePickerInputController.svelte +134 -74
  7. package/dist/components/ic/DatePickerInputController.svelte.d.ts +2 -2
  8. package/dist/components/ic/NumberInputController.svelte +16 -2
  9. package/dist/components/ic/shared/EditorFileBrowserOverlay.svelte +26 -18
  10. package/dist/composition/compositionApi.d.ts +25 -0
  11. package/dist/composition/compositionApi.js +34 -4
  12. package/dist/composition/compositionEditorController.d.ts +63 -3
  13. package/dist/composition/compositionEditorController.js +207 -10
  14. package/dist/composition/staleGuard.d.ts +111 -0
  15. package/dist/composition/staleGuard.js +279 -0
  16. package/dist/embedAssistant/embedAssistantSuggest.d.ts +20 -0
  17. package/dist/embedAssistant/embedAssistantSuggest.js +29 -0
  18. package/dist/embedAssistant/embedAssistantTurns.d.ts +73 -0
  19. package/dist/embedAssistant/embedAssistantTurns.js +56 -0
  20. package/dist/embedAssistant/types.d.ts +15 -0
  21. package/dist/i18n/language.d.ts +19 -3
  22. package/dist/i18n/messages.d.ts +9 -0
  23. package/dist/i18n/messages.js +11 -0
  24. package/dist/i18n/translate.d.ts +1 -1
  25. package/package.json +8 -3
  26. package/dist/components/ic/NumberControls.svelte +0 -505
  27. package/dist/components/ic/NumberControls.svelte.d.ts +0 -37
  28. package/dist/components/ic/numberControlsSteps.d.ts +0 -17
  29. package/dist/components/ic/numberControlsSteps.js +0 -23
  30. package/dist/components/ic/numberControlsValueArea.d.ts +0 -29
  31. package/dist/components/ic/numberControlsValueArea.js +0 -51
@@ -6,8 +6,25 @@
6
6
  <script lang="ts">
7
7
  import { createEventDispatcher, onDestroy, onMount } from 'svelte';
8
8
  import { Button } from '@widgetic/design-system/components';
9
+ // The grey words after what the person has typed, which Tab takes: the engine is the design system's, one box's part is below
10
+ import {
11
+ completionHintMemory,
12
+ createGatewayCompletion,
13
+ inlineCompletion,
14
+ type GatewayCompletion,
15
+ type GhostView,
16
+ } from '@widgetic/design-system/inline-completion';
17
+ // The assistant's face: the chat's turn (the avatar with its content beside it) and its rules for the avatar's look, with the
18
+ // brand's mascot as the drawing. The chat itself is not used: this panel keeps its own transcript, question and composer.
19
+ import { AgentTurn, liveAgentLook, settledAgentLook } from '@widgetic/chat';
20
+ import type { AgentAvatarRenderProps, AgentLook } from '@widgetic/chat';
21
+ import { Mascot, warmUpMascot } from '@widgetic/brand/mascot';
9
22
  import { useEditorLanguage } from '../../i18n/language.js';
10
23
  import type { EmbedAssistantWireConfig } from '../../embedAssistant/types.js';
24
+ import {
25
+ EMBED_ASSISTANT_SUGGEST_SURFACE,
26
+ embedSuggestContext,
27
+ } from '../../embedAssistant/embedAssistantSuggest.js';
11
28
  import {
12
29
  buildAssistantHistory,
13
30
  emptyEmbedAssistantUiState,
@@ -18,6 +35,12 @@
18
35
  EMBED_ASSISTANT_STREAM_MESSAGES,
19
36
  parseEmbedAssistantSseStream,
20
37
  } from '../../embedAssistant/embedAssistantStream.js';
38
+ import {
39
+ embedAssistantMoment,
40
+ embedMomentKeepsAvatarSmall,
41
+ groupEmbedAssistantTurns,
42
+ type EmbedAssistantMoment,
43
+ } from '../../embedAssistant/embedAssistantTurns.js';
21
44
 
22
45
  const SESSION_OPEN_KEY = 'embed_assistant_panel_open';
23
46
  const SESSION_WIDTH_KEY = 'embed_assistant_panel_width';
@@ -32,7 +55,7 @@
32
55
  copyEmbedCode: void;
33
56
  }>();
34
57
 
35
- const { t } = useEditorLanguage();
58
+ const { t, locale } = useEditorLanguage();
36
59
 
37
60
  let collapsed = true;
38
61
  let draft = '';
@@ -43,12 +66,87 @@
43
66
  let isResizing = false;
44
67
  let streamAbort: AbortController | null = null;
45
68
 
69
+ // "Desired Suggestions": the grey words after what the person has typed (Tab takes them, typing on or Esc sends them away). The
70
+ // host gives a suggest route or it does not: without one the box has no suggestions and the panel is what it always was.
71
+ let completion: GatewayCompletion | null = null;
72
+ // A suggestion is on the screen now: the hint beside the box says what Tab does with it
73
+ let suggestionShows = false;
74
+ // The line of the hint stays once it has been needed, so the panel does not move each time a suggestion comes and goes
75
+ let isHintLineKept = false;
76
+ // The routes are read as plain text, so a host that hands in a new config object with the same routes does not start the box over
77
+ $: suggestUrl = assistant.suggestUrl || undefined;
78
+ $: outcomeUrl = assistant.outcomeUrl || undefined;
79
+ $: completion = buildCompletion(suggestUrl, outcomeUrl);
80
+
46
81
  const welcomeChips = [
47
82
  { labelKey: 'editor.embedAssistant.chipOverlayExitIntent', messageKey: 'editor.embedAssistant.chipOverlayExitIntent' },
48
83
  { labelKey: 'editor.embedAssistant.chipCenteredFiveTimes', messageKey: 'editor.embedAssistant.chipCenteredFiveTimes' },
49
84
  { labelKey: 'editor.embedAssistant.chipHideOnMobile', messageKey: 'editor.embedAssistant.chipHideOnMobile' },
50
85
  ] as const;
51
86
 
87
+ /** How long the mascot's WebGL context is kept ready for the next one, in milliseconds: two minutes, as the creator keeps it. */
88
+ const MASCOT_KEEP_WARM_MILLISECONDS = 120_000;
89
+ /** A turn that is not the newest: a small still picture, so a long conversation keeps one mascot moving and not one per turn. */
90
+ const stillAvatarLook: AgentLook = { state: 'idle', size: 'small', live: false };
91
+
92
+ // "Desired Run Facts": the settings the LATEST run (a message sent) changed. The stream tells the host about them and does not
93
+ // keep them in the screen's state, so the panel notes it, and forgets it when the person speaks again or starts a new chat.
94
+ let hasRunSetOptions = false;
95
+ // True once the panel is on screen: the moment of the assistant is told in the console from then on, never while rendering
96
+ let isMounted = false;
97
+ let lastReportedMoment = '';
98
+
99
+ // "Desired Mascot": the assistant is drawn as the Scribble Mascot unless the host says false (a partner can turn it off)
100
+ $: isMascotEnabled = assistant.agentMascot !== false;
101
+ // "Desired Assistant Moment": what the assistant is doing right now, as far as its avatar cares. A question waiting is the
102
+ // card that is on screen (the stream clears it when the run is done), a failure is the line that is on screen.
103
+ $: currentAssistantMoment = embedAssistantMoment({
104
+ isStreaming: ui.isStreaming,
105
+ hasReplyStarted: ui.messages[ui.messages.length - 1]?.role === 'assistant',
106
+ hasCardToAnswer: ui.pendingQuestion !== null,
107
+ hasFailed: ui.lastError !== null,
108
+ hasSucceeded: hasRunSetOptions,
109
+ });
110
+ // The newest turn's avatar follows the chat's own rules for the moment (the panel is narrow, so a question waiting keeps the
111
+ // small avatar: see `embedMomentKeepsAvatarSmall`); the turns before it rest
112
+ $: newestAvatarLook = lookOfNewestAvatar(currentAssistantMoment);
113
+ // Something of the assistant's is on screen after the transcript, so the last turn is its own even when the person spoke last
114
+ $: hasLiveContent = ui.isStreaming || ui.pendingQuestion !== null || ui.lastError !== null;
115
+ // "Desired Turns": the transcript as rows, the assistant's messages in a row being one turn with one face
116
+ $: transcriptTurns = groupEmbedAssistantTurns(ui.messages, hasLiveContent);
117
+ $: if (isMounted) reportAssistantMoment(currentAssistantMoment);
118
+
119
+ function lookOfNewestAvatar(moment: EmbedAssistantMoment): AgentLook {
120
+ const chatLook =
121
+ moment.kind === 'live' ? liveAgentLook(moment.phase) : settledAgentLook(moment.outcome, true);
122
+ return embedMomentKeepsAvatarSmall(moment) ? { ...chatLook, size: 'small' } : chatLook;
123
+ }
124
+
125
+ // Said once for each change of what the assistant is doing, never on every redraw
126
+ function reportAssistantMoment(moment: EmbedAssistantMoment): void {
127
+ const momentSignature = [moment.kind, moment.kind === 'live' ? moment.phase : moment.outcome].join(
128
+ '/',
129
+ );
130
+ if (momentSignature === lastReportedMoment) return;
131
+ lastReportedMoment = momentSignature;
132
+ console.debug('[embed-assistant] the assistant is now', momentSignature);
133
+ }
134
+
135
+ // The first mascot of a page waits for Three.js, the WebGL context and the shader (a still picture until then). They are got
136
+ // ready once the panel is open, so the first thing the assistant does starts moving at once. With the mascot off, nothing is fetched.
137
+ function warmUpAssistantMascot(): void {
138
+ if (assistant.agentMascot === false) return;
139
+ try {
140
+ // The brand never throws and never rejects: a page without WebGL gets the poster, as every mascot does
141
+ void warmUpMascot({ keepWarmForMilliseconds: MASCOT_KEEP_WARM_MILLISECONDS });
142
+ } catch (error) {
143
+ console.debug(
144
+ '[embed-assistant] the mascot could not be warmed up; the first one starts as it always did',
145
+ error,
146
+ );
147
+ }
148
+ }
149
+
52
150
  onMount(() => {
53
151
  try {
54
152
  collapsed = sessionStorage.getItem(SESSION_OPEN_KEY) !== 'open';
@@ -62,6 +160,8 @@
62
160
  if (assistant.initialTranscript?.length) {
63
161
  ui = { ...ui, messages: [...assistant.initialTranscript] };
64
162
  }
163
+ if (!collapsed) warmUpAssistantMascot();
164
+ isMounted = true;
65
165
  });
66
166
 
67
167
  function persistOpenState(): void {
@@ -77,11 +177,66 @@
77
177
  assistant.onTranscriptChange?.(ui.messages);
78
178
  }
79
179
 
80
- async function authHeaders(): Promise<Record<string, string>> {
180
+ // The headers of a call to the gateway, as the host gives them: at once, or when it has them (a token refreshed on demand)
181
+ function authHeaders(): Promise<Record<string, string>> | Record<string, string> {
81
182
  const headers = assistant.getAuthHeaders;
82
183
  return typeof headers === 'function' ? headers() : headers;
83
184
  }
84
185
 
186
+ // What the engine says it did, quietly and once per kind of thing (a gateway that is down is one line, not one per keystroke)
187
+ function logCompletion(message: string, detail?: Record<string, unknown>): void {
188
+ console.debug('[embed-assistant] suggestions:', message, detail ?? '');
189
+ }
190
+
191
+ // The box of suggestions for the routes the host gave, or null without a suggest route. What the previous one counted goes out
192
+ // first (the host gave other routes), and it is let go of.
193
+ function buildCompletion(
194
+ suggestRoute: string | undefined,
195
+ outcomeRoute: string | undefined,
196
+ ): GatewayCompletion | null {
197
+ completion?.destroy();
198
+ if (!suggestRoute) return null;
199
+ try {
200
+ return createGatewayCompletion({
201
+ surface: EMBED_ASSISTANT_SUGGEST_SURFACE,
202
+ suggestUrl: suggestRoute,
203
+ outcomeUrl: outcomeRoute,
204
+ headers: authHeaders,
205
+ // The calls carry the person's token and not a cookie, as the stream's do
206
+ credentials: 'omit',
207
+ locale: () => $locale,
208
+ // What the box says about itself: the settings that are set, so a setting that is set is not suggested again
209
+ context: () => embedSuggestContext(currentSettings),
210
+ log: logCompletion,
211
+ });
212
+ } catch (error) {
213
+ console.debug(
214
+ '[embed-assistant] the suggestions could not be set up; the box shows none',
215
+ error,
216
+ );
217
+ return null;
218
+ }
219
+ }
220
+
221
+ // The suggestion on the screen comes and goes: the hint beside the box follows it. The hint is for the first suggestion only: the
222
+ // design system's action notes the first one taken (before it tells the box the grey words are gone), and from then on the box has no
223
+ // hint and no line for one, so the panel is as it is without suggestions.
224
+ function handleSuggestionChange(suggestion: GhostView | null): void {
225
+ suggestionShows = suggestion !== null;
226
+ if (completionHintMemory.learned) {
227
+ isHintLineKept = false;
228
+ return;
229
+ }
230
+ if (suggestionShows) isHintLineKept = true;
231
+ }
232
+
233
+ // What a screen reader hears when a suggestion shows: the words typed with the suggestion in them
234
+ function describeSuggestion(suggestionText: string): string {
235
+ return $t('editor.embedAssistant.suggestionAnnouncement', {
236
+ text: `${draft}${suggestionText}`.trim(),
237
+ });
238
+ }
239
+
85
240
  async function sendMessage(
86
241
  text: string,
87
242
  answer?: { cardId: string; selectedOptionIds: string[] },
@@ -89,6 +244,7 @@
89
244
  if (!text.trim() || ui.isStreaming) return;
90
245
  streamAbort?.abort();
91
246
  streamAbort = new AbortController();
247
+ hasRunSetOptions = false;
92
248
  ui = reduceEmbedAssistantUiState(ui, { type: 'user_message', id: crypto.randomUUID(), text });
93
249
  ui = reduceEmbedAssistantUiState(ui, { type: 'streaming', value: true });
94
250
  notifyTranscript();
@@ -106,6 +262,7 @@
106
262
  });
107
263
  for await (const event of parseEmbedAssistantSseStream(response, streamAbort.signal)) {
108
264
  if (event.type === 'options_set') {
265
+ hasRunSetOptions = true;
109
266
  dispatch('optionsSet', {
110
267
  options: event.payload.options,
111
268
  changedIds: event.payload.changedIds,
@@ -139,10 +296,12 @@
139
296
  function toggleCollapsed(): void {
140
297
  collapsed = !collapsed;
141
298
  persistOpenState();
299
+ if (!collapsed) warmUpAssistantMascot();
142
300
  }
143
301
 
144
302
  function newChat(): void {
145
303
  streamAbort?.abort();
304
+ hasRunSetOptions = false;
146
305
  ui = reduceEmbedAssistantUiState(ui, { type: 'reset' });
147
306
  notifyTranscript();
148
307
  }
@@ -180,11 +339,60 @@
180
339
  onDestroy(() => {
181
340
  streamAbort?.abort();
182
341
  endResize();
342
+ // What the box counted of its suggestions goes out as it goes away
343
+ completion?.destroy();
183
344
  });
184
345
  </script>
185
346
 
186
347
  <svelte:window on:pointermove={onResizeMove} on:pointerup={endResize} />
187
348
 
349
+ {#snippet assistantAvatar(avatar: AgentAvatarRenderProps)}
350
+ <!-- The assistant's face: the brand's mascot, drawn as the chat's avatar asks (its state, its size, a still picture for a turn that is not the newest). -->
351
+ <Mascot
352
+ state={avatar.state}
353
+ size={avatar.size}
354
+ label={avatar.label}
355
+ decorative={!avatar.label}
356
+ frozenAt={avatar.live ? undefined : 0.5}
357
+ settleTo="idle"
358
+ />
359
+ {/snippet}
360
+
361
+ <!-- The question the assistant asked, which the newest turn shows until the person has answered. -->
362
+ {#snippet pendingQuestionCard()}
363
+ {#if ui.pendingQuestion}
364
+ <div class="border-border rounded-xl border bg-accent/30 p-3">
365
+ <p class="text-body text-foreground mb-2">{ui.pendingQuestion.question}</p>
366
+ <div class="flex flex-col gap-2">
367
+ {#each ui.pendingQuestion.options as option (option.id)}
368
+ <label class="flex cursor-pointer items-center gap-2">
369
+ <input
370
+ type={ui.pendingQuestion.allowMultiple ? 'checkbox' : 'radio'}
371
+ name="embed-assistant-question"
372
+ value={option.id}
373
+ checked={selectedOptionIds.includes(option.id)}
374
+ on:change={() => {
375
+ if (ui.pendingQuestion?.allowMultiple) {
376
+ selectedOptionIds = selectedOptionIds.includes(option.id)
377
+ ? selectedOptionIds.filter((id) => id !== option.id)
378
+ : [...selectedOptionIds, option.id];
379
+ } else {
380
+ selectedOptionIds = [option.id];
381
+ }
382
+ }}
383
+ />
384
+ <span class="text-body text-foreground">{option.label}</span>
385
+ </label>
386
+ {/each}
387
+ </div>
388
+ <!-- Secondary: the editor already has its main call to action, a chat card never adds a second one. -->
389
+ <Button class="mt-3" size="sm" variant="secondary" onclick={submitQuestionAnswer}>
390
+ {$t('editor.embedAssistant.continue')}
391
+ </Button>
392
+ </div>
393
+ {/if}
394
+ {/snippet}
395
+
188
396
  {#if collapsed}
189
397
  <button
190
398
  type="button"
@@ -229,64 +437,63 @@
229
437
  {/each}
230
438
  </div>
231
439
  {/if}
232
- {#each ui.messages as message (message.id)}
233
- <div
234
- class="text-body {message.role === 'user'
235
- ? 'text-foreground'
236
- : 'text-muted-foreground'}"
237
- >
238
- {message.text}
239
- </div>
240
- {/each}
241
- {#if ui.isStreaming}
242
- <p class="text-caption text-muted-foreground" aria-live="polite">{$t('editor.embedAssistant.working')}</p>
243
- {/if}
244
- {#if ui.pendingQuestion}
245
- <div class="border-border rounded-xl border bg-accent/30 p-3">
246
- <p class="text-body text-foreground mb-2">{ui.pendingQuestion.question}</p>
247
- <div class="flex flex-col gap-2">
248
- {#each ui.pendingQuestion.options as option (option.id)}
249
- <label class="flex cursor-pointer items-center gap-2">
250
- <input
251
- type={ui.pendingQuestion.allowMultiple ? 'checkbox' : 'radio'}
252
- name="embed-assistant-question"
253
- value={option.id}
254
- checked={selectedOptionIds.includes(option.id)}
255
- on:change={() => {
256
- if (ui.pendingQuestion?.allowMultiple) {
257
- selectedOptionIds = selectedOptionIds.includes(option.id)
258
- ? selectedOptionIds.filter((id) => id !== option.id)
259
- : [...selectedOptionIds, option.id];
260
- } else {
261
- selectedOptionIds = [option.id];
262
- }
263
- }}
264
- />
265
- <span class="text-body text-foreground">{option.label}</span>
266
- </label>
267
- {/each}
440
+ {#each transcriptTurns as turn (turn.key)}
441
+ {#if turn.kind === 'user'}
442
+ <div class="text-body text-foreground">
443
+ {turn.message.text}
268
444
  </div>
269
- <Button class="mt-3" size="sm" onclick={submitQuestionAnswer}>
270
- {$t('editor.embedAssistant.continue')}
271
- </Button>
272
- </div>
273
- {/if}
274
- {#if ui.lastError}
275
- <p class="text-caption text-destructive" role="alert">{ui.lastError}</p>
276
- {/if}
445
+ {:else}
446
+ <!-- The newest turn is the one that moves; the others are still pictures. -->
447
+ <AgentTurn
448
+ look={turn.isNewest ? newestAvatarLook : stillAvatarLook}
449
+ renderAgentAvatar={isMascotEnabled ? assistantAvatar : undefined}
450
+ >
451
+ {#each turn.messages as message, messageIndex (message.id)}
452
+ <p
453
+ class="text-body text-muted-foreground {messageIndex === 0
454
+ ? 'flex min-h-7 items-center'
455
+ : ''}"
456
+ >
457
+ {message.text}
458
+ </p>
459
+ {/each}
460
+ {#if turn.isNewest}
461
+ {#if ui.isStreaming}
462
+ <p class="text-caption text-muted-foreground flex min-h-7 items-center" aria-live="polite">{$t('editor.embedAssistant.working')}</p>
463
+ {/if}
464
+ {@render pendingQuestionCard()}
465
+ {#if ui.lastError}
466
+ <p class="text-caption text-destructive flex min-h-7 items-center" role="alert">{ui.lastError}</p>
467
+ {/if}
468
+ {/if}
469
+ </AgentTurn>
470
+ {/if}
471
+ {/each}
277
472
  </div>
278
473
  <footer class="border-border border-t px-4 py-3">
279
474
  {#if ui.showCopyPrimary}
280
- <Button class="mb-2 w-full" onclick={() => dispatch('copyEmbedCode')}>
475
+ <!-- Secondary, like the buttons of the chat cards: the editor keeps one main call to action. -->
476
+ <Button class="mb-2 w-full" variant="secondary" onclick={() => dispatch('copyEmbedCode')}>
281
477
  {$t('editor.embedAssistant.copyEmbedCode')}
282
478
  </Button>
283
479
  {/if}
284
- <div class="flex gap-2">
480
+ <!-- `relative`: the grey words are drawn on a layer placed against the nearest positioned parent of the box -->
481
+ <div class="relative flex gap-2">
285
482
  <input
286
483
  class="text-body text-foreground bg-accent border-border min-w-0 flex-1 rounded-lg border px-3 py-2"
287
484
  placeholder={$t('editor.embedAssistant.composerPlaceholder')}
288
485
  bind:value={draft}
289
486
  disabled={ui.isStreaming}
487
+ use:inlineCompletion={{
488
+ source: completion?.source ?? null,
489
+ value: draft,
490
+ // The box is shut while the assistant answers, and so are its suggestions
491
+ disabled: ui.isStreaming,
492
+ onEvent: completion?.onEvent,
493
+ onChange: handleSuggestionChange,
494
+ announce: describeSuggestion,
495
+ log: logCompletion,
496
+ }}
290
497
  on:keydown={(event) => {
291
498
  if (event.key === 'Enter' && !event.shiftKey) {
292
499
  event.preventDefault();
@@ -298,6 +505,21 @@
298
505
  {$t('editor.embedAssistant.send')}
299
506
  </Button>
300
507
  </div>
508
+ {#if isHintLineKept}
509
+ <!-- A line of its own once it has been needed, so the panel does not move as suggestions come and go. A screen reader is told by the box itself. -->
510
+ <p
511
+ class="text-caption text-muted-foreground mt-2 flex h-5 items-center gap-1.5"
512
+ data-testid="embed-assistant-suggestion-hint"
513
+ aria-hidden="true"
514
+ >
515
+ {#if suggestionShows}
516
+ <kbd class="border-border bg-accent text-caption rounded-sm border px-1.5 font-sans"
517
+ >{$t('editor.embedAssistant.suggestionTabKey')}</kbd
518
+ >
519
+ <span>{$t('editor.embedAssistant.suggestionTabHint')}</span>
520
+ {/if}
521
+ </p>
522
+ {/if}
301
523
  </footer>
302
524
  </aside>
303
525
  {/if}
@@ -22,10 +22,14 @@
22
22
 
23
23
  <script lang="ts">
24
24
  import { onDestroy } from 'svelte';
25
+ // The number control is the design system's: the one component the editor and the canvas panel draw
26
+ import { NumberControls } from '@widgetic/design-system/components';
25
27
  import InputControllerRow from './InputControllerRow.svelte';
26
- import NumberControls from './NumberControls.svelte';
28
+ import { useEditorLanguage } from '../../i18n/language';
27
29
  import { normalizeAngleDegrees } from '../../utils/angleMath';
28
30
 
31
+ const { t } = useEditorLanguage();
32
+
29
33
  export let label: AngleInputControllerProps['label'];
30
34
  export let value: AngleInputControllerProps['value'] = 0;
31
35
  export let onChange: AngleInputControllerProps['onChange'];
@@ -103,6 +107,15 @@
103
107
  }
104
108
  }
105
109
 
110
+ /**
111
+ * A number typed or stepped in the field: the dial's needle follows it at once (the control used to write it back into
112
+ * `value` through `bind:value`), and the page is told.
113
+ */
114
+ function handleNumberControlsChange(newValue: number) {
115
+ value = newValue;
116
+ onChange(newValue);
117
+ }
118
+
106
119
  function handleMouseDown(event: MouseEvent) {
107
120
  if (!circleContainer) return;
108
121
 
@@ -192,14 +205,16 @@
192
205
  <NumberControls
193
206
  class="min-w-0 flex-1"
194
207
  surfacePaddingClass="pe-1.5"
195
- bind:value
196
- {onChange}
208
+ {value}
209
+ onChange={handleNumberControlsChange}
197
210
  {min}
198
211
  {max}
199
212
  {step}
200
213
  {onFocus}
201
214
  wrapAround={true}
202
215
  suffix="°"
216
+ decreaseLabel={$t('editor.stepper.decrease')}
217
+ increaseLabel={$t('editor.stepper.increase')}
203
218
  />
204
219
  </div>
205
220
  </InputControllerRow>
@@ -616,32 +616,61 @@
616
616
  * - Prevents event bubbling
617
617
  * @param event - Mouse event
618
618
  */
619
- function handleOpacityMouseDown(event: MouseEvent) {
619
+ function sliderRelativeX(event: PointerEvent, slider: HTMLElement): number {
620
+ if (event.target === slider && typeof event.offsetX === 'number') {
621
+ return event.offsetX;
622
+ }
623
+ const rect = slider.getBoundingClientRect();
624
+ const viewportX = event.clientX - rect.left;
625
+ if (viewportX >= -1 && viewportX <= rect.width + 1) return viewportX;
626
+ const rootNode = slider.getRootNode();
627
+ if (rootNode instanceof ShadowRoot && rootNode.host) {
628
+ const hostRect = rootNode.host.getBoundingClientRect();
629
+ return event.clientX - hostRect.left - rect.left;
630
+ }
631
+ return viewportX;
632
+ }
633
+
634
+ function handleOpacityPointerDown(event: PointerEvent) {
635
+ const slider = event.currentTarget as HTMLDivElement | null;
636
+ if (!slider) return;
637
+ event.preventDefault();
638
+ event.stopPropagation();
620
639
  isDragging = true;
621
- // The cursor is shown on the host of the shadow root the picker is in, and on <body> only on a normal page: the
622
- // <body> of a customer's page is not the editor's to change.
640
+ opacitySliderRef = slider;
641
+ try {
642
+ slider.setPointerCapture(event.pointerId);
643
+ } catch (error) {
644
+ console.warn('[ColorPicker] Could not capture the opacity pointer:', error);
645
+ }
623
646
  releaseOpacityPointerStyle?.();
624
- releaseOpacityPointerStyle = lockPointerStyle(event.currentTarget ?? event.target, 'grabbing', {
647
+ releaseOpacityPointerStyle = lockPointerStyle(slider, 'grabbing', {
625
648
  blockTextSelection: false
626
649
  });
627
- updateOpacity(event);
650
+ updateOpacityFromSlider(slider, event);
628
651
 
629
- const handleMouseMove = (e: MouseEvent) => {
630
- if (isDragging) {
631
- updateOpacity(e);
632
- }
652
+ const handlePointerMove = (moveEvent: PointerEvent) => {
653
+ if (isDragging) updateOpacityFromSlider(slider, moveEvent);
633
654
  };
634
-
635
- const handleMouseUp = () => {
655
+ const handlePointerUp = () => {
636
656
  isDragging = false;
637
657
  releaseOpacityPointerStyle?.();
638
658
  releaseOpacityPointerStyle = null;
639
- window.removeEventListener('mousemove', handleMouseMove);
640
- window.removeEventListener('mouseup', handleMouseUp);
659
+ slider.removeEventListener('pointermove', handlePointerMove);
660
+ slider.removeEventListener('pointerup', handlePointerUp);
661
+ slider.removeEventListener('pointercancel', handlePointerUp);
662
+ try {
663
+ if (slider.hasPointerCapture(event.pointerId)) {
664
+ slider.releasePointerCapture(event.pointerId);
665
+ }
666
+ } catch {
667
+ /* capture already released */
668
+ }
641
669
  };
642
670
 
643
- window.addEventListener('mousemove', handleMouseMove);
644
- window.addEventListener('mouseup', handleMouseUp);
671
+ slider.addEventListener('pointermove', handlePointerMove);
672
+ slider.addEventListener('pointerup', handlePointerUp);
673
+ slider.addEventListener('pointercancel', handlePointerUp);
645
674
  }
646
675
 
647
676
  // Reactive statement to handle external value changes
@@ -694,33 +723,21 @@
694
723
  * - Handles edge cases
695
724
  * @param event - Mouse event from slider interaction
696
725
  */
697
- function updateOpacity(event: MouseEvent) {
698
- if (!opacitySliderRef) return;
699
-
700
- const rect = opacitySliderRef.getBoundingClientRect();
701
- const x = event.clientX - rect.left;
702
- const width = rect.width;
726
+ function updateOpacityFromSlider(slider: HTMLElement, event: PointerEvent) {
727
+ const width = slider.clientWidth || slider.getBoundingClientRect().width;
728
+ if (!width) return;
703
729
 
730
+ const x = sliderRelativeX(event, slider);
704
731
  let newOpacity = Math.max(0, Math.min(x, width)) / width;
705
732
  newOpacity = Math.round(newOpacity * 100) / 100;
706
733
 
707
734
  try {
708
735
  isInternalUpdate = true;
709
- opacity = newOpacity; // This will trigger the reactive statement
736
+ opacity = newOpacity;
710
737
  rgb = { ...rgb, a: newOpacity };
711
738
  lastKnownOpacity = newOpacity;
712
- const hexValue = `#${Math.round(rgb.r * 255)
713
- .toString(16)
714
- .padStart(2, '0')}${Math.round(rgb.g * 255)
715
- .toString(16)
716
- .padStart(2, '0')}${Math.round(rgb.b * 255)
717
- .toString(16)
718
- .padStart(2, '0')}`;
719
- value = hexValue;
720
- hexInput = hexValue;
721
739
  previewColor = getRgbaColor();
722
- onChange(hexValue);
723
- onOpacityChange(newOpacity); // Call the opacity change handler
740
+ onOpacityChange(newOpacity);
724
741
  } finally {
725
742
  isInternalUpdate = false;
726
743
  }
@@ -1042,14 +1059,19 @@
1042
1059
 
1043
1060
  function handlePointerDownOutside(event: MouseEvent) {
1044
1061
  if (!open) return;
1045
- const target = event.target;
1046
- if (!(target instanceof Element)) return;
1047
- if (
1048
- target.closest('.color-picker-popover-content') ||
1049
- target.closest('.color-preview-button') ||
1050
- target.closest('.color-input-main-container')
1051
- ) {
1052
- return;
1062
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : [event.target];
1063
+ for (const node of path) {
1064
+ if (!(node instanceof Element)) continue;
1065
+ if (
1066
+ node === popoverContentRef ||
1067
+ node === triggerRef ||
1068
+ node === inputRef ||
1069
+ node.closest?.('.color-picker-popover-content') ||
1070
+ node.closest?.('.color-preview-button') ||
1071
+ node.closest?.('.color-input-main-container')
1072
+ ) {
1073
+ return;
1074
+ }
1053
1075
  }
1054
1076
  handleToggle(false);
1055
1077
  }
@@ -1293,15 +1315,24 @@
1293
1315
  const spaceBelow = window.innerHeight - swatchRect.bottom;
1294
1316
  const spaceAbove = swatchRect.top;
1295
1317
  const openAbove = spaceBelow < popoverHeight + popoverGapPx && spaceAbove > spaceBelow;
1296
- const top = openAbove
1318
+ const viewportTop = openAbove
1297
1319
  ? Math.round(swatchRect.top - popoverHeight - popoverGapPx)
1298
1320
  : Math.round(swatchRect.bottom + popoverGapPx);
1299
1321
  // Anchor horizontally to the swatch: centered when it fits, clamped inside the viewport otherwise.
1300
- let left = Math.round(swatchRect.left + swatchRect.width / 2 - popoverWidthPx / 2);
1322
+ let viewportLeft = Math.round(swatchRect.left + swatchRect.width / 2 - popoverWidthPx / 2);
1301
1323
  const horizontalMargin = 8;
1302
1324
  const maxLeft = window.innerWidth - popoverWidthPx - horizontalMargin;
1303
- left = Math.max(horizontalMargin, Math.min(left, maxLeft));
1304
- popoverStyle = `top: ${top}px; left: ${left}px;`; /* rtl-ok: viewport coords from getBoundingClientRect; popover is dir=ltr */
1325
+ viewportLeft = Math.max(horizontalMargin, Math.min(viewportLeft, maxLeft));
1326
+ // Inside a ShadowRoot with `contain: layout` on `:host`, `position: fixed` is relative to the host box
1327
+ // rather than the viewport, so convert viewport coordinates into host-relative coordinates.
1328
+ const rootNode = (popoverContentRef ?? triggerRef).getRootNode?.();
1329
+ const hostRect =
1330
+ rootNode && typeof ShadowRoot !== 'undefined' && rootNode instanceof ShadowRoot
1331
+ ? rootNode.host.getBoundingClientRect()
1332
+ : { left: 0, top: 0 };
1333
+ const top = Math.round(viewportTop - hostRect.top);
1334
+ const left = Math.round(viewportLeft - hostRect.left);
1335
+ popoverStyle = `top: ${top}px; left: ${left}px;`; /* rtl-ok: viewport coords from getBoundingClientRect adjusted for ShadowRoot host; popover is dir=ltr */
1305
1336
  }
1306
1337
 
1307
1338
  // Position is calculated in handleToggle after tick()
@@ -1594,13 +1625,13 @@
1594
1625
  <div
1595
1626
  bind:this={opacitySliderRef}
1596
1627
  class="opacity-slider relative h-6 cursor-pointer overflow-visible rounded-lg"
1597
- style="width: {opacityBarContentWidth}px;"
1598
- onmousedown={handleOpacityMouseDown}
1628
+ style="width: {opacityBarContentWidth}px; touch-action: none;"
1629
+ onpointerdown={handleOpacityPointerDown}
1599
1630
  >
1600
- <div class="absolute inset-0 overflow-hidden rounded-[inherit]">
1631
+ <div class="pointer-events-none absolute inset-0 overflow-hidden rounded-[inherit]">
1601
1632
  <CheckerBoardBackground className="rounded-[inherit]" />
1602
1633
  <div
1603
- class="absolute inset-0"
1634
+ class="pointer-events-none absolute inset-0"
1604
1635
  style="background: linear-gradient(to right,
1605
1636
  rgba({Math.round(rgb.r * 255)}, {Math.round(
1606
1637
  rgb.g * 255
@@ -1672,6 +1703,7 @@
1672
1703
  .opacity-slider {
1673
1704
  cursor: grab !important;
1674
1705
  user-select: none !important;
1706
+ touch-action: none;
1675
1707
  }
1676
1708
 
1677
1709
  :global(.color-picker-wrapper canvas:active),