@classic-homes/feedback-svelte 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,667 @@
1
+ <script lang="ts">
2
+ import { onDestroy, tick, untrack } from 'svelte';
3
+ import {
4
+ ACCEPT_ATTRIBUTE,
5
+ COMMENT_COUNTER_THRESHOLD,
6
+ FEEDBACK_LIMITS,
7
+ MESSAGES,
8
+ buildPayload,
9
+ capturePage,
10
+ clearPageSelection,
11
+ closeFeedback,
12
+ createClientId,
13
+ createIdPrefix,
14
+ createSelectionWatcher,
15
+ errorMessage,
16
+ getState,
17
+ imageFromClipboardEvent,
18
+ initialCategory,
19
+ needsTurnstile,
20
+ prepareImage,
21
+ renderTurnstile,
22
+ sendFeedback,
23
+ validateForm,
24
+ type FeedbackConfig,
25
+ type FieldErrors,
26
+ type ResolvedFeedbackOptions,
27
+ type SelectionData,
28
+ type TurnstileHandle,
29
+ } from '@classic-homes/feedback-core';
30
+
31
+ interface Props {
32
+ config: FeedbackConfig;
33
+ options: ResolvedFeedbackOptions;
34
+ open: boolean;
35
+ initialSelection: SelectionData | null;
36
+ launchContext: Record<string, unknown> | null;
37
+ fallbackFocus: () => HTMLElement | undefined;
38
+ }
39
+
40
+ type Status = 'idle' | 'submitting' | 'success' | 'queued' | 'error';
41
+
42
+ interface Attachment {
43
+ id: string;
44
+ blob: Blob;
45
+ url: string;
46
+ }
47
+
48
+ let { config, options, open, initialSelection, launchContext, fallbackFocus }: Props = $props();
49
+
50
+ const id = createIdPrefix();
51
+ const ids = {
52
+ title: `${id}-title`,
53
+ desc: `${id}-desc`,
54
+ category: `${id}-category`,
55
+ comment: `${id}-comment`,
56
+ commentError: `${id}-comment-error`,
57
+ counter: `${id}-counter`,
58
+ name: `${id}-name`,
59
+ email: `${id}-email`,
60
+ emailError: `${id}-email-error`,
61
+ attachments: `${id}-attachments`,
62
+ confirm: `${id}-confirm`,
63
+ };
64
+
65
+ // Seeded once per dialog session (the parent keys this component by nonce).
66
+ let category = $state(untrack(() => initialCategory(options.categories, !!initialSelection)));
67
+ let comment = $state('');
68
+ let name = $state(untrack(() => config.user?.name ?? ''));
69
+ let email = $state(untrack(() => config.user?.email ?? ''));
70
+ let selection: SelectionData | null = $state(untrack(() => initialSelection));
71
+ let attachments: Attachment[] = $state([]);
72
+ let status = $state<Status>('idle');
73
+ let error: string | null = $state(null);
74
+ let fieldErrors: FieldErrors = $state({});
75
+ let confirming = $state(false);
76
+ let picking = $state(false);
77
+ let capturing = $state(false);
78
+ let processing = $state(false);
79
+ let attachError: string | null = $state(null);
80
+ let dragActive = $state(false);
81
+ let showTurnstile = $state(false);
82
+
83
+ let dialogEl: HTMLDialogElement | undefined = $state();
84
+ let textareaEl: HTMLTextAreaElement | undefined = $state();
85
+ let emailEl: HTMLInputElement | undefined = $state();
86
+ let fileEl: HTMLInputElement | undefined = $state();
87
+ let keepEditingEl: HTMLButtonElement | undefined = $state();
88
+ let doneEl: HTMLButtonElement | undefined = $state();
89
+ let turnstileEl: HTMLDivElement | undefined = $state();
90
+
91
+ let turnstile: TurnstileHandle | null = null;
92
+ const clientId = createClientId();
93
+ let returnFocus: HTMLElement | null = null;
94
+ let closing = false;
95
+ let pointerOnBackdrop = false;
96
+ let wasOpen = false;
97
+
98
+ const done = $derived(status === 'success' || status === 'queued');
99
+ const dirty = $derived(!done && (comment.trim().length > 0 || attachments.length > 0));
100
+ const submitting = $derived(status === 'submitting');
101
+ const counterVisible = $derived(comment.length >= COMMENT_COUNTER_THRESHOLD);
102
+ const anonymous = $derived(!config.user);
103
+ const canAttachMore = $derived(attachments.length < options.maxAttachments);
104
+ const commentDescribedBy = $derived(
105
+ [fieldErrors.comment ? ids.commentError : '', counterVisible ? ids.counter : '']
106
+ .filter(Boolean)
107
+ .join(' ') || undefined
108
+ );
109
+
110
+ function requestClose() {
111
+ if (status === 'submitting') return;
112
+ if (dirty) confirming = true;
113
+ else closeFeedback();
114
+ }
115
+
116
+ // Drive the native dialog from controller state. It is also closed (not the
117
+ // controller) while picking, because a modal dialog makes the page inert.
118
+ $effect(() => {
119
+ const isOpen = open;
120
+ const isPicking = picking;
121
+ const dialog = dialogEl;
122
+ if (!dialog) return;
123
+ untrack(() => {
124
+ const show = isOpen && !isPicking;
125
+ if (show && !dialog.open) {
126
+ if (!wasOpen) returnFocus = document.activeElement as HTMLElement | null;
127
+ dialog.showModal();
128
+ textareaEl?.focus();
129
+ } else if (!show && dialog.open) {
130
+ closing = true;
131
+ dialog.close();
132
+ }
133
+ if (!isOpen && wasOpen) {
134
+ const target = returnFocus;
135
+ if (target && target.isConnected && target !== document.body) target.focus();
136
+ else fallbackFocus()?.focus();
137
+ }
138
+ wasOpen = isOpen;
139
+ });
140
+ });
141
+
142
+ function onCancel(e: Event) {
143
+ e.preventDefault();
144
+ requestClose();
145
+ }
146
+
147
+ function onClose() {
148
+ if (closing) {
149
+ closing = false;
150
+ return;
151
+ }
152
+ // The browser closed it without us (e.g. a repeated Escape).
153
+ if (!getState().open || picking) return;
154
+ if (dirty) {
155
+ dialogEl?.showModal();
156
+ confirming = true;
157
+ } else {
158
+ closeFeedback();
159
+ }
160
+ }
161
+
162
+ $effect(() => {
163
+ if (confirming) keepEditingEl?.focus();
164
+ });
165
+
166
+ $effect(() => {
167
+ if (done) void tick().then(() => doneEl?.focus());
168
+ });
169
+
170
+ // Turnstile: only for anonymous use of the built-in transport. Decided once.
171
+ let turnstileChecked = false;
172
+ $effect(() => {
173
+ if (!open || turnstileChecked) return;
174
+ turnstileChecked = true;
175
+ let cancelled = false;
176
+ void needsTurnstile(untrack(() => config)).then((needed) => {
177
+ if (!cancelled) showTurnstile = needed;
178
+ });
179
+ return () => {
180
+ cancelled = true;
181
+ };
182
+ });
183
+
184
+ $effect(() => {
185
+ const el = turnstileEl;
186
+ const siteKey = config.turnstileSiteKey;
187
+ if (!showTurnstile || !el || !siteKey || turnstile) return;
188
+ turnstile = renderTurnstile(el, siteKey);
189
+ });
190
+
191
+ onDestroy(() => {
192
+ turnstile?.remove();
193
+ turnstile = null;
194
+ for (const a of attachments) URL.revokeObjectURL(a.url);
195
+ });
196
+
197
+ // Picking mode: the next selection inside the container becomes the quote.
198
+ $effect(() => {
199
+ const container = options.selectionContainer;
200
+ if (!picking || !container) return;
201
+ const watcher = createSelectionWatcher({
202
+ container,
203
+ onSelect: (data) => {
204
+ selection = data;
205
+ picking = false;
206
+ clearPageSelection();
207
+ },
208
+ onClear: () => {},
209
+ });
210
+ const onKey = (e: KeyboardEvent) => {
211
+ if (e.key === 'Escape') picking = false;
212
+ };
213
+ document.addEventListener('keydown', onKey);
214
+ return () => {
215
+ watcher.destroy();
216
+ document.removeEventListener('keydown', onKey);
217
+ };
218
+ });
219
+
220
+ function startPicking() {
221
+ clearPageSelection();
222
+ picking = true;
223
+ }
224
+
225
+ async function addFiles(files: Blob[]) {
226
+ attachError = null;
227
+ const room = options.maxAttachments - attachments.length;
228
+ if (room <= 0 || files.length > room) {
229
+ attachError = MESSAGES.attachmentLimit(options.maxAttachments);
230
+ }
231
+ const accepted = files.slice(0, Math.max(0, room));
232
+ if (!accepted.length) return;
233
+ processing = true;
234
+ for (const file of accepted) {
235
+ try {
236
+ const blob = await prepareImage(file);
237
+ if (attachments.length >= options.maxAttachments) break;
238
+ attachments.push({ id: createClientId(), blob, url: URL.createObjectURL(blob) });
239
+ } catch (err) {
240
+ attachError = errorMessage(err);
241
+ }
242
+ }
243
+ processing = false;
244
+ }
245
+
246
+ function removeAttachment(attachmentId: string) {
247
+ const target = attachments.find((a) => a.id === attachmentId);
248
+ if (target) URL.revokeObjectURL(target.url);
249
+ attachments = attachments.filter((a) => a.id !== attachmentId);
250
+ attachError = null;
251
+ }
252
+
253
+ async function onCapture() {
254
+ capturing = true;
255
+ attachError = null;
256
+ try {
257
+ const blob = await capturePage();
258
+ await addFiles([blob]);
259
+ } catch {
260
+ attachError = MESSAGES.captureFailed;
261
+ } finally {
262
+ capturing = false;
263
+ }
264
+ }
265
+
266
+ function onFileChange(e: Event) {
267
+ const input = e.currentTarget as HTMLInputElement;
268
+ const files = Array.from(input.files ?? []);
269
+ input.value = '';
270
+ void addFiles(files);
271
+ }
272
+
273
+ function onDrop(e: DragEvent) {
274
+ e.preventDefault();
275
+ dragActive = false;
276
+ const files = Array.from(e.dataTransfer?.files ?? []).filter((f) =>
277
+ f.type.startsWith('image/')
278
+ );
279
+ void addFiles(files);
280
+ }
281
+
282
+ function onPaste(e: ClipboardEvent) {
283
+ if (options.maxAttachments === 0 || done) return;
284
+ const file = imageFromClipboardEvent(e);
285
+ if (!file) return;
286
+ e.preventDefault();
287
+ void addFiles([file]);
288
+ }
289
+
290
+ async function onSubmit(e: SubmitEvent) {
291
+ e.preventDefault();
292
+ if (status === 'submitting') return;
293
+ const errors = validateForm({ comment, email });
294
+ fieldErrors = errors;
295
+ if (errors.comment) {
296
+ textareaEl?.focus();
297
+ return;
298
+ }
299
+ if (errors.email) {
300
+ emailEl?.focus();
301
+ return;
302
+ }
303
+ status = 'submitting';
304
+ error = null;
305
+ confirming = false;
306
+ try {
307
+ const payload = buildPayload(
308
+ config,
309
+ { category, comment, name, email, selection: selection ? { ...selection } : null },
310
+ { context: launchContext, clientId }
311
+ );
312
+ const result = await sendFeedback(
313
+ config,
314
+ payload,
315
+ attachments.map((a) => a.blob),
316
+ turnstile
317
+ );
318
+ status = result.queued ? 'queued' : 'success';
319
+ config.onSubmitted?.(result);
320
+ } catch (err) {
321
+ status = 'error';
322
+ error = errorMessage(err);
323
+ }
324
+ }
325
+ </script>
326
+
327
+ <dialog
328
+ bind:this={dialogEl}
329
+ class="chf chf-dialog"
330
+ aria-labelledby={ids.title}
331
+ aria-describedby={done ? undefined : ids.desc}
332
+ oncancel={onCancel}
333
+ onclose={onClose}
334
+ onpointerdown={(e) => {
335
+ pointerOnBackdrop = e.target === e.currentTarget;
336
+ }}
337
+ onclick={(e) => {
338
+ if (e.target === e.currentTarget && pointerOnBackdrop) requestClose();
339
+ pointerOnBackdrop = false;
340
+ }}
341
+ onpaste={onPaste}
342
+ >
343
+ <div class="chf-dialog__panel">
344
+ <div class="chf-dialog__header">
345
+ <h2 id={ids.title} class="chf-dialog__title">
346
+ {selection ? MESSAGES.titleSelection : MESSAGES.titlePage}
347
+ </h2>
348
+ <button
349
+ type="button"
350
+ class="chf-icon-btn chf-dialog__close"
351
+ aria-label={MESSAGES.close}
352
+ onclick={requestClose}
353
+ >
354
+ <span aria-hidden="true">×</span>
355
+ </button>
356
+ </div>
357
+
358
+ {#if done}
359
+ <div class="chf-result chf-result--{status}" role="status" aria-live="polite">
360
+ <span class="chf-result__icon" aria-hidden="true">{status === 'queued' ? '⇡' : '✓'}</span>
361
+ <p class="chf-result__title">
362
+ {status === 'queued' ? MESSAGES.queuedTitle : MESSAGES.successTitle}
363
+ </p>
364
+ <p class="chf-result__body">
365
+ {status === 'queued' ? MESSAGES.queuedBody : MESSAGES.successBody}
366
+ </p>
367
+ <button
368
+ bind:this={doneEl}
369
+ type="button"
370
+ class="chf-btn chf-btn--primary"
371
+ onclick={() => closeFeedback()}
372
+ >
373
+ {MESSAGES.done}
374
+ </button>
375
+ </div>
376
+ {:else}
377
+ <form class="chf-form" novalidate onsubmit={onSubmit}>
378
+ <p id={ids.desc} class="chf-dialog__desc">
379
+ {selection ? MESSAGES.descSelection : MESSAGES.descPage}
380
+ </p>
381
+
382
+ {#if selection}
383
+ <figure class="chf-quote">
384
+ <blockquote class="chf-quote__text">{selection.quote}</blockquote>
385
+ {#if selection.headingText}
386
+ <figcaption class="chf-quote__cite">
387
+ {MESSAGES.quoteUnder} “{selection.headingText}”
388
+ </figcaption>
389
+ {/if}
390
+ <div class="chf-quote__actions">
391
+ {#if options.selectionContainer}
392
+ <button
393
+ type="button"
394
+ class="chf-link-btn"
395
+ aria-label="Change the attached passage"
396
+ onclick={startPicking}
397
+ >
398
+ {MESSAGES.quoteChange}
399
+ </button>
400
+ {/if}
401
+ <button
402
+ type="button"
403
+ class="chf-link-btn"
404
+ aria-label="Remove the attached passage"
405
+ onclick={() => (selection = null)}
406
+ >
407
+ {MESSAGES.quoteRemove}
408
+ </button>
409
+ </div>
410
+ </figure>
411
+ {:else if options.selectionContainer}
412
+ <button type="button" class="chf-attach-btn" onclick={startPicking}>
413
+ <span aria-hidden="true">✎</span>
414
+ {MESSAGES.attachPassage}
415
+ </button>
416
+ {/if}
417
+
418
+ <fieldset class="chf-field">
419
+ <legend id={ids.category} class="chf-label">{MESSAGES.categoryLegend}</legend>
420
+ <div class="chf-chips" role="radiogroup" aria-labelledby={ids.category}>
421
+ {#each options.categories as c (c.value)}
422
+ <label class="chf-chip" data-checked={category === c.value ? 'true' : undefined}>
423
+ <input
424
+ type="radio"
425
+ class="chf-chip__input"
426
+ name="{id}-category-input"
427
+ value={c.value}
428
+ bind:group={category}
429
+ />
430
+ {c.label}
431
+ </label>
432
+ {/each}
433
+ </div>
434
+ </fieldset>
435
+
436
+ <div class="chf-field">
437
+ <label for={ids.comment} class="chf-label">
438
+ {MESSAGES.commentLabel}
439
+ <span class="chf-required" aria-hidden="true">*</span>
440
+ </label>
441
+ <textarea
442
+ bind:this={textareaEl}
443
+ id={ids.comment}
444
+ class="chf-textarea"
445
+ rows="5"
446
+ required
447
+ aria-required="true"
448
+ maxlength={FEEDBACK_LIMITS.commentMax}
449
+ placeholder={MESSAGES.commentPlaceholder}
450
+ aria-invalid={fieldErrors.comment ? 'true' : undefined}
451
+ aria-describedby={commentDescribedBy}
452
+ bind:value={comment}
453
+ oninput={() => {
454
+ if (fieldErrors.comment) fieldErrors = { ...fieldErrors, comment: undefined };
455
+ }}
456
+ ></textarea>
457
+ {#if fieldErrors.comment || counterVisible}
458
+ <div class="chf-field__meta">
459
+ {#if fieldErrors.comment}
460
+ <p id={ids.commentError} class="chf-field-error">{fieldErrors.comment}</p>
461
+ {/if}
462
+ {#if counterVisible}
463
+ <span
464
+ id={ids.counter}
465
+ class="chf-counter"
466
+ data-over={comment.length >= FEEDBACK_LIMITS.commentMax ? 'true' : undefined}
467
+ >
468
+ {comment.length} / {FEEDBACK_LIMITS.commentMax}
469
+ </span>
470
+ {/if}
471
+ </div>
472
+ {/if}
473
+ </div>
474
+
475
+ {#if options.maxAttachments > 0}
476
+ <div class="chf-field chf-attachments" role="group" aria-labelledby={ids.attachments}>
477
+ <span id={ids.attachments} class="chf-label">
478
+ {MESSAGES.attachmentsLabel}
479
+ <span class="chf-hint"
480
+ >({MESSAGES.optional}{options.maxAttachments > 1
481
+ ? `, up to ${options.maxAttachments}`
482
+ : ''})</span
483
+ >
484
+ </span>
485
+ {#if attachments.length > 0}
486
+ <ul class="chf-thumbs">
487
+ {#each attachments as a, i (a.id)}
488
+ <li class="chf-thumb">
489
+ <img class="chf-thumb__img" src={a.url} alt={MESSAGES.attachmentAlt(i + 1)} />
490
+ <button
491
+ type="button"
492
+ class="chf-thumb__remove"
493
+ aria-label={MESSAGES.removeAttachment(i + 1)}
494
+ onclick={() => removeAttachment(a.id)}
495
+ >
496
+ <span aria-hidden="true">×</span>
497
+ </button>
498
+ </li>
499
+ {/each}
500
+ </ul>
501
+ {/if}
502
+ {#if canAttachMore}
503
+ <div
504
+ class="chf-dropzone"
505
+ role="presentation"
506
+ data-active={dragActive ? 'true' : undefined}
507
+ ondragover={(e) => {
508
+ e.preventDefault();
509
+ dragActive = true;
510
+ }}
511
+ ondragleave={() => (dragActive = false)}
512
+ ondrop={onDrop}
513
+ >
514
+ <p class="chf-dropzone__prompt">{MESSAGES.dropPrompt}</p>
515
+ <div class="chf-dropzone__actions">
516
+ <input
517
+ bind:this={fileEl}
518
+ type="file"
519
+ class="chf-visually-hidden"
520
+ tabindex="-1"
521
+ aria-hidden="true"
522
+ accept={ACCEPT_ATTRIBUTE}
523
+ multiple={options.maxAttachments - attachments.length > 1}
524
+ onchange={onFileChange}
525
+ />
526
+ <button
527
+ type="button"
528
+ class="chf-btn chf-btn--secondary chf-btn--sm"
529
+ disabled={processing}
530
+ onclick={() => fileEl?.click()}
531
+ >
532
+ {MESSAGES.chooseImage}
533
+ </button>
534
+ {#if options.allowScreenshotCapture}
535
+ <button
536
+ type="button"
537
+ class="chf-btn chf-btn--secondary chf-btn--sm"
538
+ disabled={capturing || processing}
539
+ aria-busy={capturing || undefined}
540
+ onclick={() => void onCapture()}
541
+ >
542
+ {#if capturing}<span class="chf-spinner" aria-hidden="true"></span>{/if}
543
+ {capturing ? MESSAGES.capturing : MESSAGES.capturePage}
544
+ </button>
545
+ {/if}
546
+ </div>
547
+ </div>
548
+ {/if}
549
+ <p class="chf-hint" aria-live="polite">{processing ? MESSAGES.processing : ''}</p>
550
+ {#if attachError}<p class="chf-field-error">{attachError}</p>{/if}
551
+ </div>
552
+ {/if}
553
+
554
+ <div class="chf-row">
555
+ <div class="chf-field">
556
+ <label for={ids.name} class="chf-label">
557
+ {MESSAGES.name}{#if anonymous}<span class="chf-hint">
558
+ ({MESSAGES.optional})</span
559
+ >{/if}
560
+ </label>
561
+ <input
562
+ id={ids.name}
563
+ class="chf-input"
564
+ type="text"
565
+ autocomplete="name"
566
+ maxlength={FEEDBACK_LIMITS.nameMax}
567
+ bind:value={name}
568
+ />
569
+ </div>
570
+ <div class="chf-field">
571
+ <label for={ids.email} class="chf-label">
572
+ {MESSAGES.email}{#if anonymous}<span class="chf-hint">
573
+ ({MESSAGES.optional})</span
574
+ >{/if}
575
+ </label>
576
+ <input
577
+ bind:this={emailEl}
578
+ id={ids.email}
579
+ class="chf-input"
580
+ type="email"
581
+ autocomplete="email"
582
+ maxlength={FEEDBACK_LIMITS.emailMax}
583
+ aria-invalid={fieldErrors.email ? 'true' : undefined}
584
+ aria-describedby={fieldErrors.email ? ids.emailError : undefined}
585
+ bind:value={email}
586
+ oninput={() => {
587
+ if (fieldErrors.email) fieldErrors = { ...fieldErrors, email: undefined };
588
+ }}
589
+ />
590
+ {#if fieldErrors.email}
591
+ <p id={ids.emailError} class="chf-field-error">{fieldErrors.email}</p>
592
+ {/if}
593
+ </div>
594
+ </div>
595
+
596
+ {#if showTurnstile}
597
+ <div bind:this={turnstileEl} class="chf-turnstile"></div>
598
+ {/if}
599
+
600
+ {#if error}
601
+ <div class="chf-alert" role="alert">{error}</div>
602
+ {/if}
603
+
604
+ {#if confirming}
605
+ <div class="chf-confirm" role="group" aria-labelledby={ids.confirm}>
606
+ <p id={ids.confirm} class="chf-confirm__text">{MESSAGES.discardPrompt}</p>
607
+ <div class="chf-confirm__actions">
608
+ <button
609
+ bind:this={keepEditingEl}
610
+ type="button"
611
+ class="chf-btn chf-btn--secondary chf-btn--sm"
612
+ onclick={() => {
613
+ confirming = false;
614
+ textareaEl?.focus();
615
+ }}
616
+ >
617
+ {MESSAGES.keepEditing}
618
+ </button>
619
+ <button
620
+ type="button"
621
+ class="chf-btn chf-btn--primary chf-btn--sm"
622
+ onclick={() => closeFeedback()}
623
+ >
624
+ {MESSAGES.discard}
625
+ </button>
626
+ </div>
627
+ </div>
628
+ {:else}
629
+ <div class="chf-actions">
630
+ <button
631
+ type="button"
632
+ class="chf-btn chf-btn--ghost"
633
+ disabled={submitting}
634
+ onclick={requestClose}
635
+ >
636
+ {MESSAGES.cancel}
637
+ </button>
638
+ <button
639
+ type="submit"
640
+ class="chf-btn chf-btn--primary"
641
+ disabled={submitting}
642
+ aria-busy={submitting || undefined}
643
+ >
644
+ {#if submitting}<span class="chf-spinner" aria-hidden="true"></span>{/if}
645
+ {submitting ? MESSAGES.submitting : MESSAGES.submit}
646
+ </button>
647
+ </div>
648
+ {/if}
649
+ </form>
650
+ {/if}
651
+ </div>
652
+ </dialog>
653
+
654
+ {#if picking}
655
+ <div class="chf chf-picking-bar" role="status">
656
+ <span aria-hidden="true">✎</span>
657
+ <span>{MESSAGES.pickingPrompt}</span>
658
+ <button
659
+ type="button"
660
+ class="chf-picking-bar__cancel"
661
+ onmousedown={(e) => e.preventDefault()}
662
+ onclick={() => (picking = false)}
663
+ >
664
+ {MESSAGES.pickingCancel}
665
+ </button>
666
+ </div>
667
+ {/if}
@@ -0,0 +1,12 @@
1
+ import { type FeedbackConfig, type ResolvedFeedbackOptions, type SelectionData } from '@classic-homes/feedback-core';
2
+ interface Props {
3
+ config: FeedbackConfig;
4
+ options: ResolvedFeedbackOptions;
5
+ open: boolean;
6
+ initialSelection: SelectionData | null;
7
+ launchContext: Record<string, unknown> | null;
8
+ fallbackFocus: () => HTMLElement | undefined;
9
+ }
10
+ declare const FeedbackDialog: import("svelte").Component<Props, {}, "">;
11
+ type FeedbackDialog = ReturnType<typeof FeedbackDialog>;
12
+ export default FeedbackDialog;
@@ -0,0 +1,116 @@
1
+ <script lang="ts">
2
+ import { onMount } from 'svelte';
3
+ import {
4
+ MESSAGES,
5
+ clearPageSelection,
6
+ createSelectionWatcher,
7
+ getState,
8
+ isCoarsePointer,
9
+ openFeedback,
10
+ resolveOptions,
11
+ selectionButtonPosition,
12
+ type FeedbackConfig,
13
+ type FloatingPosition,
14
+ type SelectionData,
15
+ } from '@classic-homes/feedback-core';
16
+ import FeedbackDialog from './FeedbackDialog.svelte';
17
+ import { feedbackState } from './feedbackState.svelte.js';
18
+ import { portal } from './portal.js';
19
+
20
+ /**
21
+ * Feedback edge tab, selection "Comment" button and dialog. Renders nothing
22
+ * during SSR; everything mounts into document.body on the client.
23
+ */
24
+ let props: FeedbackConfig = $props();
25
+
26
+ const options = $derived(resolveOptions(props));
27
+ let mounted = $state(false);
28
+ let tabEl: HTMLButtonElement | undefined = $state();
29
+ let selectionUi: { data: SelectionData; pos: FloatingPosition } | null = $state(null);
30
+
31
+ onMount(() => {
32
+ mounted = true;
33
+ });
34
+
35
+ $effect(() => {
36
+ const container = options.selectionContainer;
37
+ if (!mounted || !container) return;
38
+ const watcher = createSelectionWatcher({
39
+ container,
40
+ onSelect: (data, rect) => {
41
+ // The dialog owns selection while it is open (including picking mode).
42
+ if (getState().open) return;
43
+ const pos = rect
44
+ ? selectionButtonPosition(rect, { preferBelow: isCoarsePointer() })
45
+ : { top: 8, left: 8 };
46
+ selectionUi = { data, pos };
47
+ },
48
+ onClear: () => {
49
+ selectionUi = null;
50
+ },
51
+ });
52
+ return () => watcher.destroy();
53
+ });
54
+
55
+ $effect(() => {
56
+ if (feedbackState.open) selectionUi = null;
57
+ });
58
+
59
+ function openFromSelection() {
60
+ const current = selectionUi;
61
+ if (!current) return;
62
+ selectionUi = null;
63
+ clearPageSelection();
64
+ openFeedback({ selection: current.data });
65
+ }
66
+ </script>
67
+
68
+ {#if mounted}
69
+ <div class="chf-portal" style="display: contents" use:portal>
70
+ {#if options.trigger === 'tab'}
71
+ <button
72
+ bind:this={tabEl}
73
+ type="button"
74
+ class="chf chf-tab"
75
+ aria-haspopup="dialog"
76
+ aria-label={MESSAGES.tabAria}
77
+ onclick={() => openFeedback()}
78
+ >
79
+ <span class="chf-tab__icon" aria-hidden="true">✎</span>
80
+ <span class="chf-tab__label">{options.tabLabel}</span>
81
+ </button>
82
+ {/if}
83
+
84
+ {#if selectionUi && !feedbackState.open}
85
+ <button
86
+ type="button"
87
+ class="chf chf-select-btn"
88
+ style:top="{selectionUi.pos.top}px"
89
+ style:left="{selectionUi.pos.left}px"
90
+ aria-label={MESSAGES.commentOnSelectionAria}
91
+ onpointerdown={(e) => {
92
+ // Pointer down fires before the browser clears the selection.
93
+ e.preventDefault();
94
+ e.stopPropagation();
95
+ openFromSelection();
96
+ }}
97
+ onmousedown={(e) => e.preventDefault()}
98
+ onclick={openFromSelection}
99
+ >
100
+ <span aria-hidden="true">✎</span>
101
+ <span>{MESSAGES.commentOnSelection}</span>
102
+ </button>
103
+ {/if}
104
+
105
+ {#key feedbackState.nonce}
106
+ <FeedbackDialog
107
+ config={props}
108
+ {options}
109
+ open={feedbackState.open}
110
+ initialSelection={feedbackState.selection}
111
+ launchContext={feedbackState.context}
112
+ fallbackFocus={() => tabEl}
113
+ />
114
+ {/key}
115
+ </div>
116
+ {/if}
@@ -0,0 +1,4 @@
1
+ import { type FeedbackConfig } from '@classic-homes/feedback-core';
2
+ declare const FeedbackWidget: import("svelte").Component<FeedbackConfig, {}, "">;
3
+ type FeedbackWidget = ReturnType<typeof FeedbackWidget>;
4
+ export default FeedbackWidget;
@@ -0,0 +1,6 @@
1
+ import { type FeedbackState } from '@classic-homes/feedback-core';
2
+ /**
3
+ * Reactive view of the feedback controller for Svelte 5 components:
4
+ * `{#if feedbackState.open}` re-renders when the dialog opens or closes.
5
+ */
6
+ export declare const feedbackState: Readonly<FeedbackState>;
@@ -0,0 +1,23 @@
1
+ import { getState, subscribe } from '@classic-homes/feedback-core';
2
+ let current = $state.raw(getState());
3
+ subscribe((next) => {
4
+ current = next;
5
+ });
6
+ /**
7
+ * Reactive view of the feedback controller for Svelte 5 components:
8
+ * `{#if feedbackState.open}` re-renders when the dialog opens or closes.
9
+ */
10
+ export const feedbackState = {
11
+ get open() {
12
+ return current.open;
13
+ },
14
+ get selection() {
15
+ return current.selection;
16
+ },
17
+ get context() {
18
+ return current.context;
19
+ },
20
+ get nonce() {
21
+ return current.nonce;
22
+ },
23
+ };
@@ -0,0 +1,3 @@
1
+ export { default as FeedbackWidget } from './FeedbackWidget.svelte';
2
+ export { feedbackState } from './feedbackState.svelte.js';
3
+ export { openFeedback, closeFeedback, submitFeedback, FeedbackError, isFeedbackError, DEFAULT_CATEGORIES, type FeedbackConfig, type FeedbackPayload, type FeedbackCategoryOption, type FeedbackErrorCode, type FeedbackPageContext, type FeedbackState, type OpenFeedbackOptions, type SelectionData, type SubmitResult, } from '@classic-homes/feedback-core';
@@ -0,0 +1,3 @@
1
+ export { default as FeedbackWidget } from './FeedbackWidget.svelte';
2
+ export { feedbackState } from './feedbackState.svelte.js';
3
+ export { openFeedback, closeFeedback, submitFeedback, FeedbackError, isFeedbackError, DEFAULT_CATEGORIES, } from '@classic-homes/feedback-core';
@@ -0,0 +1,4 @@
1
+ /** Svelte action: move the node to document.body while it is mounted. */
2
+ export declare function portal(node: HTMLElement): {
3
+ destroy(): void;
4
+ };
@@ -0,0 +1,9 @@
1
+ /** Svelte action: move the node to document.body while it is mounted. */
2
+ export function portal(node) {
3
+ document.body.appendChild(node);
4
+ return {
5
+ destroy() {
6
+ node.remove();
7
+ },
8
+ };
9
+ }
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@classic-homes/feedback-svelte",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Svelte 5 feedback widget (edge tab, selection comments, screenshots) for chapi",
5
+ "type": "module",
6
+ "svelte": "./dist/lib/index.js",
7
+ "types": "./dist/lib/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/lib/index.d.ts",
11
+ "svelte": "./dist/lib/index.js",
12
+ "default": "./dist/lib/index.js"
13
+ }
14
+ },
15
+ "sideEffects": false,
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "scripts": {
20
+ "build": "svelte-package -i src",
21
+ "dev": "svelte-package -i src --watch",
22
+ "clean": "node ../../scripts/rm.mjs dist",
23
+ "typecheck": "svelte-check --tsconfig ./tsconfig.json",
24
+ "test": "vitest run"
25
+ },
26
+ "dependencies": {
27
+ "@classic-homes/feedback-core": "*"
28
+ },
29
+ "peerDependencies": {
30
+ "svelte": "^5.0.0"
31
+ },
32
+ "devDependencies": {
33
+ "@sveltejs/package": "^2.3.0",
34
+ "@sveltejs/vite-plugin-svelte": "^7.0.0",
35
+ "@testing-library/jest-dom": "^6.6.0",
36
+ "@testing-library/svelte": "^5.0.0",
37
+ "@testing-library/user-event": "^14.5.0",
38
+ "jsdom": "^25.0.0",
39
+ "svelte": "^5.0.0",
40
+ "svelte-check": "^4.0.0",
41
+ "typescript": "^5.3.0",
42
+ "vitest": "^4.1.10",
43
+ "vitest-axe": "^0.1.0"
44
+ },
45
+ "keywords": [
46
+ "feedback",
47
+ "widget",
48
+ "svelte",
49
+ "classic-theme"
50
+ ],
51
+ "license": "MIT",
52
+ "repository": {
53
+ "type": "git",
54
+ "url": "https://github.com/Classic-Homes/classic-theme.git",
55
+ "directory": "packages/feedback-svelte"
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ }
60
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.