@sparkvault/sdk-js 16.4.1 → 16.5.1

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.
package/dist/index.cjs CHANGED
@@ -6941,6 +6941,50 @@ class OriginNotAllowedView {
6941
6941
  }
6942
6942
  }
6943
6943
 
6944
+ /**
6945
+ * How long a live region waits before it takes new words: long enough that
6946
+ * assistive technology has seen the change that prompted them, and hears the
6947
+ * region's own change as a change.
6948
+ */
6949
+ const ANNOUNCE_DELAY_MS = 100;
6950
+ /**
6951
+ * A polite status region for words said as a view changes. It is placed
6952
+ * empty and kept, and every announcement waits a moment, so the words never
6953
+ * land in the same change as the region or the view that holds them: a
6954
+ * region created with its words already in it is often never announced.
6955
+ */
6956
+ function createLiveRegion(className) {
6957
+ const element = document.createElement('div');
6958
+ element.className = className;
6959
+ element.setAttribute('role', 'status');
6960
+ element.setAttribute('aria-live', 'polite');
6961
+ element.setAttribute('aria-atomic', 'true');
6962
+ let timer = null;
6963
+ const cancel = () => {
6964
+ if (timer !== null)
6965
+ clearTimeout(timer);
6966
+ timer = null;
6967
+ };
6968
+ return {
6969
+ element,
6970
+ announce(words) {
6971
+ cancel();
6972
+ if (!words) {
6973
+ element.textContent = '';
6974
+ return;
6975
+ }
6976
+ timer = setTimeout(() => {
6977
+ timer = null;
6978
+ element.textContent = words;
6979
+ }, ANNOUNCE_DELAY_MS);
6980
+ },
6981
+ destroy() {
6982
+ cancel();
6983
+ element.remove();
6984
+ },
6985
+ };
6986
+ }
6987
+
6944
6988
  /**
6945
6989
  * Identity View Renderer
6946
6990
  *
@@ -6969,12 +7013,6 @@ function blockedSignInMessage(companyName) {
6969
7013
  : 'Sign-in is temporarily unavailable. Please contact the site owner for assistance.';
6970
7014
  }
6971
7015
  const BLOCKED_ERROR_CODES = new Set(IDENTITY_BLOCKED_ERROR_CODES);
6972
- /**
6973
- * How long the live region waits after a view is in place before it takes
6974
- * the view's words: long enough that assistive technology has seen the
6975
- * view's change and hears the region's as a change of its own.
6976
- */
6977
- const STATUS_ANNOUNCE_DELAY_MS = 100;
6978
7016
  const SPARKLINK_CSP_BLOCKED_ERROR = {
6979
7017
  message: [
6980
7018
  'Connection blocked by security policy.',
@@ -7021,11 +7059,8 @@ class IdentityRenderer {
7021
7059
  this.untouchedStep = null;
7022
7060
  // The page's one live region: placed beside the flow content when the
7023
7061
  // container opens, empty, and kept across views, so the words a view
7024
- // announces (View.announcement) land in a region already in the page, which
7025
- // assistive technology hears change. A region created with its words already
7026
- // in it is often never announced.
7062
+ // announces (View.announcement) land in a region already in the page.
7027
7063
  this.statusRegion = null;
7028
- this.statusTimer = null;
7029
7064
  this.container = container;
7030
7065
  this.api = api;
7031
7066
  this.options = options;
@@ -7282,11 +7317,7 @@ class IdentityRenderer {
7282
7317
  window.removeEventListener('pageshow', this.pageRestoreHandler);
7283
7318
  this.pageRestoreHandler = null;
7284
7319
  }
7285
- if (this.statusTimer !== null) {
7286
- clearTimeout(this.statusTimer);
7287
- this.statusTimer = null;
7288
- }
7289
- this.statusRegion?.remove();
7320
+ this.statusRegion?.destroy();
7290
7321
  this.statusRegion = null;
7291
7322
  this.cleanupSparkLink();
7292
7323
  this.destroyCurrentView();
@@ -7531,7 +7562,7 @@ class IdentityRenderer {
7531
7562
  this.container.setMinimalChrome(minimalChromeViews.includes(this.viewState.view));
7532
7563
  const view = this.createViewForState(this.viewState);
7533
7564
  this.currentView = view;
7534
- this.announce(view.announcement ?? '');
7565
+ this.statusRegion?.announce(view.announcement ?? '');
7535
7566
  const rendered = view.render();
7536
7567
  // Each step enters with a calm fade + rise (see .sv-step-enter). The brand
7537
7568
  // lockup and footer live outside `body`, so only the flow content moves.
@@ -7567,37 +7598,11 @@ class IdentityRenderer {
7567
7598
  /** Place the empty live region beside the flow content, once per container. */
7568
7599
  placeStatusRegion() {
7569
7600
  const body = this.container.getBody();
7570
- if (!body || this.statusRegion?.isConnected)
7571
- return;
7572
- const region = document.createElement('div');
7573
- region.className = 'sv-sr-only';
7574
- region.setAttribute('role', 'status');
7575
- region.setAttribute('aria-live', 'polite');
7576
- region.setAttribute('aria-atomic', 'true');
7577
- body.insertAdjacentElement('beforebegin', region);
7578
- this.statusRegion = region;
7579
- }
7580
- /**
7581
- * Put `words` in the live region, a moment after the view that says them
7582
- * is in place, so they never land in the same change as the region or the
7583
- * view that holds them; empty words clear it at once.
7584
- */
7585
- announce(words) {
7586
- if (this.statusTimer !== null) {
7587
- clearTimeout(this.statusTimer);
7588
- this.statusTimer = null;
7589
- }
7590
- const region = this.statusRegion;
7591
- if (!region)
7592
- return;
7593
- if (!words) {
7594
- region.textContent = '';
7601
+ if (!body || this.statusRegion?.element.isConnected)
7595
7602
  return;
7596
- }
7597
- this.statusTimer = setTimeout(() => {
7598
- this.statusTimer = null;
7599
- region.textContent = words;
7600
- }, STATUS_ANNOUNCE_DELAY_MS);
7603
+ this.statusRegion?.destroy();
7604
+ this.statusRegion = createLiveRegion('sv-sr-only');
7605
+ body.insertAdjacentElement('beforebegin', this.statusRegion.element);
7601
7606
  }
7602
7607
  destroyCurrentView() {
7603
7608
  if (this.currentView?.destroy) {
@@ -14335,15 +14340,16 @@ Array.from({ length: 1 << BRAND_BITS.size }, (_, mask) =>
14335
14340
  * API prefix, team mail aliases, the attachment ceremony's steps, the
14336
14341
  * question a customer's new request asks before it is discarded, session,
14337
14342
  * sign-in code (its length, lifetime, sender, resend wait, countdown and
14338
- * the code step's words),
14339
- * merge and pending-attachment timings, hold presets, tag and size limits,
14340
- * the operator display and desk mode choices, the operator queue's views and
14341
- * orders, the reply review list's views and states, the response-time
14342
- * histogram's bucket edges and the sections of a desk's settings an address
14343
- * names live here for the same reason. So do the one rule a tag is stored by
14344
- * (ticketTag), which Core applies where it stores a tag and the console
14345
- * applies where one is typed, and the one rule a typed or pasted sign-in
14346
- * code is read by (helpDeskPinDigits), which every sign-in form applies. So
14343
+ * the code step's words), merge and pending-attachment timings, hold
14344
+ * presets, tag and size limits, the operator display and desk mode choices,
14345
+ * the operator queue's views and orders, the reply review list's views and
14346
+ * states, the response-time histogram's bucket edges, the sections of a
14347
+ * desk's settings an address names, and the messages the widget's native
14348
+ * sign-in posts between the website and its first-party page live here for
14349
+ * the same reason. So do the one rule a tag is stored by (ticketTag), which
14350
+ * Core applies where it stores a tag and the console applies where one is
14351
+ * typed, and the one rule a typed or pasted sign-in code is read by
14352
+ * (helpDeskPinDigits), which every sign-in form applies. So
14347
14353
  * does the one way a client names a message it sends (newMessageId), which
14348
14354
  * the portal, the SDK and the console's composer each send their messages
14349
14355
  * under, and the one rule that a message sent again is the same message
@@ -14368,6 +14374,22 @@ const HELP_DESK_CLOSE_REASONS = Object.freeze(['resolved', 'duplicate', 'spam'])
14368
14374
  /** The close reasons an operator's status change names: a duplicate closes by merging it into the request it repeats. */
14369
14375
  Object.freeze(HELP_DESK_CLOSE_REASONS.filter((reason) => reason !== 'duplicate'));
14370
14376
 
14377
+ /**
14378
+ * The messages the widget's native sign-in exchanges between the website's
14379
+ * window (the JS SDK's openWidgetIdentity) and the first-party page it opens
14380
+ * on auth.sv (Core's widget-identity-page.js), each posted to the other's
14381
+ * exact origin: the page asks its opener for the challenge's state (`ready`),
14382
+ * the opener answers its own popup alone (`state`), and the page reports the
14383
+ * sign-in's code or its cancellation (`result`). Every message names its
14384
+ * challenge, and the state is never in the page's URL or its server-rendered
14385
+ * context, so only the window that started a challenge can complete it.
14386
+ */
14387
+ const HELP_DESK_WIDGET_IDENTITY_MESSAGES = Object.freeze({
14388
+ ready: 'sparkvault:help-desk:identity-ready',
14389
+ state: 'sparkvault:help-desk:identity-state',
14390
+ result: 'sparkvault:help-desk:identity'
14391
+ });
14392
+
14371
14393
  /**
14372
14394
  * Mail local parts no team may take as its alias: the role mailboxes RFC 2142
14373
14395
  * names, the addresses mail systems and their operators keep for themselves,
@@ -17587,7 +17609,17 @@ function openWidgetIdentity(options, prepare, ready, redeem, deskId) {
17587
17609
  if (!challenge || event.source !== popup || event.origin !== firstPartyOrigin)
17588
17610
  return;
17589
17611
  const data = event.data;
17590
- if (!data || data.type !== 'sparkvault:help-desk:identity' || data.challenge_id !== challenge.challenge_id || data.state !== challenge.state)
17612
+ if (!data || data.challenge_id !== challenge.challenge_id)
17613
+ return;
17614
+ // The first-party page this window opened asks for the challenge's
17615
+ // state, without which Core takes none of its steps: only this popup,
17616
+ // at the first-party origin, is ever answered, so a sign-in link opened
17617
+ // in any other window or browser completes nothing.
17618
+ if (data.type === HELP_DESK_WIDGET_IDENTITY_MESSAGES.ready) {
17619
+ popup.postMessage({ type: HELP_DESK_WIDGET_IDENTITY_MESSAGES.state, challenge_id: challenge.challenge_id, state: challenge.state }, event.origin);
17620
+ return;
17621
+ }
17622
+ if (data.type !== HELP_DESK_WIDGET_IDENTITY_MESSAGES.result || data.state !== challenge.state)
17591
17623
  return;
17592
17624
  if (data.cancelled === true) {
17593
17625
  cancel();
@@ -18239,16 +18271,16 @@ function injectHelpDeskFormStyles() {
18239
18271
  .svhd-modal .svhd-container{max-width:none;border:0;border-radius:0;padding-top:8px}
18240
18272
  .svhd-container{box-sizing:border-box;max-width:36rem;border:1px solid ${DS.slate200};border-radius:12px;background:${DS.white};color:${DS.slate900};font:400 15px/1.5 system-ui,sans-serif;padding:24px}
18241
18273
  .svhd-container *{box-sizing:border-box}
18242
- .svhd-container h2{font-size:22px;line-height:1.25;margin:0 0 20px}
18274
+ .svhd-container h2{font-size:22px;line-height:1.25;margin:0}
18275
+ .svhd-step-head h2:focus{outline:none}
18243
18276
  .svhd-form{display:grid;gap:16px}
18244
18277
  .svhd-field{display:grid;gap:6px}
18245
18278
  .svhd-label{font-weight:600}
18246
18279
  .svhd-input{width:100%;border:1px solid ${DS.slate300};border-radius:6px;padding:10px 12px;color:${DS.slate900};background:${DS.white};font:inherit;font-size:16px}
18247
18280
  .svhd-input:focus-visible,.svhd-button:focus-visible,.svhd-link:focus-visible{outline:3px solid ${DS.action};outline-offset:2px}
18248
18281
  .svhd-input:disabled{background:${DS.slate50}}
18249
- .svhd-description{min-height:140px;resize:vertical}
18250
18282
  .svhd-auth{display:grid;gap:16px;border:0;padding:0;margin:0}
18251
- .svhd-form[hidden],.svhd-auth[hidden],.svhd-field[hidden],.svhd-field-error[hidden],.svhd-status[hidden],.svhd-link[hidden],.svhd-actions[hidden],.svhd-confirm[hidden]{display:none}
18283
+ .svhd-form[hidden],.svhd-step[hidden],.svhd-auth[hidden],.svhd-field[hidden],.svhd-field-error[hidden],.svhd-status[hidden],.svhd-link[hidden],.svhd-actions[hidden],.svhd-confirm[hidden],.svhd-widget-account[hidden],.svhd-text-button[hidden],.svhd-composer-drop[hidden],.svhd-attachment-chips[hidden]{display:none}
18252
18284
  .svhd-actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
18253
18285
  .svhd-button{border:0;border-radius:6px;padding:10px 16px;min-height:44px;font:600 15px/1.5 system-ui,sans-serif;background:${DS.action};color:${DS.white};cursor:pointer}
18254
18286
  .svhd-button:hover{background:${DS.actionHover}}
@@ -18266,14 +18298,53 @@ function injectHelpDeskFormStyles() {
18266
18298
  .svhd-done-title:focus{outline:none}
18267
18299
  .svhd-confirmation-message{white-space:pre-wrap;overflow-wrap:anywhere}
18268
18300
  .svhd-link{display:inline-flex;align-items:center;justify-self:start;min-height:44px;color:${DS.action};text-decoration:underline}
18269
- .svhd-attachments[hidden],.svhd-attachments [hidden]{display:none}
18270
- .svhd-file-hint{font-size:13px;color:${DS.slate600};margin:0}
18271
- .svhd-file-list{display:grid;gap:12px;list-style:none;padding:0;margin:0}
18272
- .svhd-file{display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:4px 10px;align-items:center;border:1px solid ${DS.slate200};border-radius:6px;padding:10px}
18273
- .svhd-file-name{font-weight:600;overflow-wrap:anywhere;grid-column:1/-1}
18274
- .svhd-file [role=status]{grid-column:1/-1;font-size:13px}
18275
- .svhd-file progress{width:100%;min-width:0;accent-color:${DS.action}}
18276
- .svhd-file .svhd-button{font-size:13px;padding:0 12px;min-height:44px}
18301
+ .svhd-hint{font-size:13px;color:${DS.slate600};margin:0}
18302
+ .svhd-step{display:grid;gap:16px;min-width:0}
18303
+ .svhd-step-head{display:grid;gap:4px;margin-bottom:4px}
18304
+ .svhd-step-label{margin:0;font-size:13px;font-weight:600;line-height:1.4;color:${DS.slate600}}
18305
+ .svhd-text-button{display:inline-flex;align-items:center;min-height:44px;padding:0 4px;border:0;border-radius:6px;background:transparent;color:${DS.action};font:inherit;font-size:14px;font-weight:600;text-decoration:underline;text-underline-offset:2px;cursor:pointer}
18306
+ .svhd-text-button:hover{color:${DS.actionHover}}
18307
+ .svhd-text-button:focus-visible{outline:3px solid ${DS.action};outline-offset:2px}
18308
+ .svhd-text-button:disabled{color:${DS.slate500};cursor:default}
18309
+ .svhd-widget-account{display:flex;align-items:center;flex-wrap:wrap;gap:0 16px;min-width:0}
18310
+ .svhd-posting-as{margin:0;color:${DS.slate600};font-size:14px;line-height:1.5;overflow-wrap:anywhere}
18311
+ .svhd-note{display:flex;align-items:flex-start;gap:10px;margin:0;padding:12px 14px;border:1px solid ${DS.slate200};border-radius:8px;background:${DS.slate50};color:${DS.slate900};font-size:14px;line-height:1.5}
18312
+ .svhd-step .svhd-note svg{display:block;width:18px;height:18px;flex:none;margin-top:2px;color:${DS.action}}
18313
+ .svhd-recap{display:flex;align-items:center;gap:12px;padding:6px 6px 6px 14px;border:1px solid ${DS.slate200};border-radius:8px}
18314
+ .svhd-recap-request{flex:1;min-width:0}
18315
+ .svhd-recap-label{display:block;color:${DS.slate600};font-size:12px;font-weight:600;line-height:1.4}
18316
+ .svhd-recap-text{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;margin:0;color:${DS.slate900};font-size:14px;line-height:1.5;overflow-wrap:anywhere}
18317
+ .svhd-recap .svhd-text-button{flex:none}
18318
+ /* The frame is the field: its ring shows wherever focus is inside it, and the text inside draws none of its own. */
18319
+ .svhd-composer{position:relative;display:flex;flex-direction:column;min-width:0;border:1px solid ${DS.slate300};border-radius:6px;background:${DS.white}}
18320
+ .svhd-composer:has(.svhd-composer-input:focus-visible){outline:3px solid ${DS.action};outline-offset:2px}
18321
+ @supports not selector(:has(*)){.svhd-composer:focus-within{outline:3px solid ${DS.action};outline-offset:2px}}
18322
+ .svhd-composer-dragging{border-style:dashed;border-color:${DS.action}}
18323
+ .svhd-composer-input{display:block;width:100%;min-height:140px;resize:vertical;border:0;border-radius:6px 6px 0 0;padding:10px 12px;background:transparent;color:${DS.slate900};font:inherit;font-size:16px}
18324
+ .svhd-composer-input:focus,.svhd-composer-input:focus-visible{outline:none}
18325
+ .svhd-composer-input:disabled{background:${DS.slate50}}
18326
+ .svhd-composer-drop{position:absolute;inset:0;z-index:1;display:flex;align-items:center;justify-content:center;margin:0;padding:12px;border-radius:5px;background:${DS.actionBg};color:${DS.action};font-weight:600;text-align:center;pointer-events:none}
18327
+ .svhd-composer-toolbar{display:flex;align-items:center;flex-wrap:wrap;gap:0 12px;padding:0 8px 0 4px;border-top:1px solid ${DS.slate200}}
18328
+ .svhd-composer-attach{display:inline-flex;align-items:center;gap:6px;min-height:44px;padding:0 8px;border:0;border-radius:6px;background:transparent;color:${DS.slate600};font:600 14px/1.4 system-ui,sans-serif;cursor:pointer}
18329
+ .svhd-composer-attach:hover{background:${DS.slate100};color:${DS.slate900}}
18330
+ .svhd-composer-attach:disabled{opacity:.6;cursor:default}
18331
+ .svhd-composer .svhd-composer-attach svg{display:block;width:18px;height:18px}
18332
+ .svhd-composer-hint{flex:1 1 160px;min-width:0;margin:0;padding:6px 0;font-size:12px;line-height:1.4;color:${DS.slate600}}
18333
+ .svhd-composer-notice{margin:0;font-size:14px}
18334
+ .svhd-attachment-chips{display:flex;flex-wrap:wrap;gap:8px;list-style:none;margin:0;padding:8px;border-top:1px solid ${DS.slate200}}
18335
+ .svhd-attachment-chips:empty{display:none}
18336
+ .svhd-attachment-chip{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;flex:0 1 280px;min-width:0;max-width:100%;padding:0 0 8px 10px;border:1px solid ${DS.slate200};border-radius:6px;background:${DS.slate50};font-size:13px;line-height:1.4}
18337
+ .svhd-attachment-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:600;color:${DS.slate900}}
18338
+ .svhd-attachment-status{grid-column:1;padding-right:8px;color:${DS.slate600};font-size:12px;overflow-wrap:anywhere}
18339
+ .svhd-attachment-status.svhd-error{color:${DS.error}}
18340
+ .svhd-attachment-progress{grid-column:1/-1;width:calc(100% - 10px);height:6px;margin-top:6px;accent-color:${DS.action}}
18341
+ .svhd-attachment-chip .svhd-attachment-remove{display:grid;place-items:center;width:44px;height:44px;min-height:44px;padding:0;border:0;border-radius:6px;background:transparent;color:${DS.slate600};cursor:pointer}
18342
+ .svhd-attachment-remove:hover{background:${DS.slate200};color:${DS.slate900}}
18343
+ .svhd-attachment-chip .svhd-attachment-remove svg{display:block;width:16px;height:16px}
18344
+ .svhd-attachment-chip .svhd-attachment-retry{grid-column:2;min-height:44px;padding:0 10px;border:0;border-radius:6px;background:transparent;color:${DS.action};font:600 13px/1.4 system-ui,sans-serif;text-decoration:underline;cursor:pointer}
18345
+ .svhd-composer button:focus-visible{outline:3px solid ${DS.action};outline-offset:-3px}
18346
+ .svhd-attachment-remove:disabled,.svhd-attachment-retry:disabled{opacity:.6;cursor:default}
18347
+ .svhd-live{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
18277
18348
  .svhd-footer{margin-top:20px;font-size:12px;color:${DS.slate500}}
18278
18349
  `;
18279
18350
  document.head.appendChild(style);
@@ -18477,23 +18548,6 @@ function lastExtension(name) {
18477
18548
  return shownExtension(closeUpSpaces(name));
18478
18549
  }
18479
18550
 
18480
- /**
18481
- * The longest prefix of `text` within `maxLength` UTF-16 units that splits no
18482
- * character.
18483
- *
18484
- * @param {string} text
18485
- * @param {number} maxLength
18486
- * @returns {string}
18487
- */
18488
- function truncateToLength(text, maxLength) {
18489
- let truncated = '';
18490
- for (const character of text) {
18491
- if (truncated.length + character.length > maxLength) break;
18492
- truncated += character;
18493
- }
18494
- return truncated;
18495
- }
18496
-
18497
18551
  /**
18498
18552
  * What a help-desk attachment may be named and what its first bytes may not
18499
18553
  * be: the one list of the files a ticket accepts, beside the one list of
@@ -18792,6 +18846,15 @@ const ACCEPTED_ATTACHMENTS_COPY = acceptedKindsCopy(ACCEPTED_ATTACHMENT_KINDS);
18792
18846
  const CUSTOMER_ATTACHMENTS_HINT =
18793
18847
  `Add screenshots, documents or recordings. Up to ${MAX_ATTACHMENTS_PER_MESSAGE} files, ${formatBytes(CUSTOMER_ATTACHMENT_MAX_BYTES)} each.`;
18794
18848
 
18849
+ /**
18850
+ * What a customer reads at a desk that takes no files from its customers
18851
+ * (the desk lookup's `customer_can_attach_files` is false, the upload refusal
18852
+ * CUSTOMER_UPLOAD_REFUSALS.UPLOADS_OFF): the portal's refusal and its note on
18853
+ * the files an email left out, and the SDK's support form refusing a file
18854
+ * dropped, pasted or uploaded there.
18855
+ */
18856
+ const NO_CUSTOMER_FILES_COPY = "This help desk doesn't take files from customers.";
18857
+
18795
18858
  /**
18796
18859
  * A file input's `accept`: every extension a ticket accepts
18797
18860
  * (ACCEPTED_ATTACHMENT_EXTENSIONS), each with its dot, so the system's file
@@ -18839,7 +18902,56 @@ function refusalCopy(refusal, maxBytes) {
18839
18902
  return REFUSAL_COPY[refusal] ?? "This file can't be attached.";
18840
18903
  }
18841
18904
 
18842
- function createProgress() { return document.createElement('progress'); }
18905
+ /**
18906
+ * The help desk's bare outline glyphs, shared by the support wizard and the
18907
+ * ticket form: stroked in `currentColor`, so the stylesheet that sizes them
18908
+ * also colors them, and hidden from assistive technology, since the control
18909
+ * that holds one names it.
18910
+ */
18911
+ const PATHS = {
18912
+ back: 'm14.5 6-6 6 6 6',
18913
+ close: 'm6 6 12 12M18 6 6 18',
18914
+ external: 'M14 4h6v6m0-6L10 14M11 5H5a1 1 0 0 0-1 1v13a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1v-6',
18915
+ check: 'm5 12 4 4L19 6',
18916
+ article: 'M14 3H6a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8Zm0 0v5h5M8 12h8M8 16h6',
18917
+ chevron: 'm9 6 6 6-6 6',
18918
+ thumbUp: 'M7 10v11H3V10Zm0 1 5-8c2 0 3 1 2 4l-1 3h6a2 2 0 0 1 2 2l-2 7a2 2 0 0 1-2 2H7',
18919
+ thumbDown: 'M7 14V3H3v11Zm0-1 5 8c2 0 3-1 2-4l-1-3h6a2 2 0 0 0 2-2l-2-7a2 2 0 0 0-2-2H7',
18920
+ paperclip: 'm21 11-8.6 8.6a5.5 5.5 0 0 1-7.8-7.8l8.6-8.6a3.7 3.7 0 0 1 5.2 5.2l-8.6 8.6a1.8 1.8 0 0 1-2.6-2.6L15 6.6',
18921
+ info: 'M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Zm0-10v5m0-8h.01',
18922
+ };
18923
+ function helpDeskIcon(name) {
18924
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
18925
+ svg.setAttribute('viewBox', '0 0 24 24');
18926
+ svg.setAttribute('aria-hidden', 'true');
18927
+ svg.setAttribute('focusable', 'false');
18928
+ svg.setAttribute('fill', 'none');
18929
+ svg.setAttribute('stroke', 'currentColor');
18930
+ svg.setAttribute('stroke-width', '1.7');
18931
+ svg.setAttribute('stroke-linecap', 'round');
18932
+ svg.setAttribute('stroke-linejoin', 'round');
18933
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
18934
+ path.setAttribute('d', PATHS[name]);
18935
+ svg.append(path);
18936
+ return svg;
18937
+ }
18938
+
18939
+ /** A refusal of files read under the composer, hidden until there is one. */
18940
+ function createNotice() {
18941
+ const notice = document.createElement('p');
18942
+ notice.className = 'svhd-composer-notice svhd-error';
18943
+ notice.hidden = true;
18944
+ return notice;
18945
+ }
18946
+ /** Show a notice's refusal, or hide it with null. It is an alert only while it shows, as a field's error is. */
18947
+ function setNotice(notice, text) {
18948
+ notice.textContent = text ?? '';
18949
+ notice.hidden = text === null;
18950
+ if (text === null)
18951
+ notice.removeAttribute('role');
18952
+ else
18953
+ notice.setAttribute('role', 'alert');
18954
+ }
18843
18955
  /** A failed mint's quota/size refusal remains a visible file error, never a silently omitted file. */
18844
18956
  function problem(error) {
18845
18957
  if (error instanceof SparkVaultError) {
@@ -18851,7 +18963,7 @@ function problem(error) {
18851
18963
  }
18852
18964
  if (error.statusCode === 402) {
18853
18965
  const reason = error.details?.reason;
18854
- return { copy: reason === CUSTOMER_UPLOAD_REFUSALS.UPLOADS_OFF ? 'This help desk does not accept files.'
18966
+ return { copy: reason === CUSTOMER_UPLOAD_REFUSALS.UPLOADS_OFF ? NO_CUSTOMER_FILES_COPY
18855
18967
  : reason === CUSTOMER_UPLOAD_REFUSALS.ALLOWANCE_REACHED ? 'You have reached this help desk’s upload allowance.'
18856
18968
  : 'This help desk cannot store more files right now.', retryable: false };
18857
18969
  }
@@ -18861,48 +18973,58 @@ function problem(error) {
18861
18973
  }
18862
18974
  return { copy: 'This file could not be uploaded. Try again or remove it.', retryable: true };
18863
18975
  }
18864
- /** The picker owns each file's transfer; it publishes only IDs whose Forge receipt has confirmed storage. */
18865
- function createFormAttachments(client, prefix, context) {
18866
- const element = document.createElement('div');
18867
- element.className = 'svhd-field svhd-attachments';
18868
- const label = document.createElement('label');
18869
- label.className = 'svhd-label';
18870
- label.textContent = 'Attachments';
18871
- label.htmlFor = `${prefix}-attachments`;
18976
+ /**
18977
+ * The picker owns each file's transfer; it publishes only IDs whose Forge
18978
+ * receipt has confirmed storage. `onEntriesChange` hears each file the
18979
+ * customer adds or removes.
18980
+ */
18981
+ function createFormAttachments(client, prefix, context, onEntriesChange) {
18872
18982
  const input = document.createElement('input');
18873
18983
  input.type = 'file';
18874
18984
  input.name = 'attachments';
18875
- input.id = label.htmlFor;
18876
18985
  input.multiple = true;
18877
18986
  input.accept = ATTACHMENT_INPUT_ACCEPT;
18878
- input.className = 'svhd-input';
18987
+ input.hidden = true;
18988
+ input.tabIndex = -1;
18879
18989
  const hint = document.createElement('p');
18880
18990
  hint.id = `${prefix}-attachment-hint`;
18881
- hint.className = 'svhd-file-hint';
18991
+ hint.className = 'svhd-composer-hint';
18882
18992
  hint.textContent = CUSTOMER_ATTACHMENTS_HINT;
18883
- input.setAttribute('aria-describedby', hint.id);
18884
- const notice = document.createElement('p');
18885
- notice.className = 'svhd-error svhd-file-hint';
18886
- notice.setAttribute('role', 'alert');
18887
- notice.hidden = true;
18993
+ const attach = document.createElement('button');
18994
+ attach.type = 'button';
18995
+ attach.className = 'svhd-composer-attach';
18996
+ attach.setAttribute('aria-label', 'Attach files');
18997
+ attach.setAttribute('aria-describedby', hint.id);
18998
+ const attachText = document.createElement('span');
18999
+ attachText.textContent = 'Attach';
19000
+ attach.append(helpDeskIcon('paperclip'), attachText);
19001
+ const toolbar = document.createElement('div');
19002
+ toolbar.className = 'svhd-composer-toolbar';
19003
+ toolbar.append(attach, hint, input);
19004
+ const notice = createNotice();
18888
19005
  const list = document.createElement('ul');
18889
- list.className = 'svhd-file-list';
18890
- list.setAttribute('aria-label', 'Selected attachments');
18891
- element.append(label, input, hint, notice, list);
19006
+ list.className = 'svhd-attachment-chips';
19007
+ list.setAttribute('aria-label', 'Attached files');
18892
19008
  let entries = [];
18893
19009
  let revision = 0;
18894
19010
  let locked = false;
18895
19011
  let pickingDisabled = false;
18896
19012
  let destroyed = false;
18897
19013
  const current = (entry, ownRevision) => !destroyed && revision === ownRevision && entries.includes(entry) && !entry.controller?.signal.aborted;
19014
+ function syncPicking() {
19015
+ attach.disabled = locked || pickingDisabled;
19016
+ input.disabled = locked || pickingDisabled;
19017
+ }
18898
19018
  function controls(entry) {
18899
19019
  entry.remove.disabled = locked;
18900
19020
  entry.retry.disabled = locked || !!entry.operation;
18901
19021
  }
18902
19022
  function update(entry, state, text) {
18903
19023
  entry.state = state;
19024
+ entry.row.dataset.state = state;
18904
19025
  entry.status.textContent = text;
18905
19026
  entry.status.classList.toggle('svhd-error', state === 'failed');
19027
+ entry.progress.hidden = state !== 'uploading';
18906
19028
  entry.retry.hidden = !(entry.retryable && (state === 'failed' || state === 'received'));
18907
19029
  entry.retry.textContent = state === 'received' ? 'Check upload' : 'Retry';
18908
19030
  entry.retry.setAttribute('aria-label', `${state === 'received' ? 'Check upload' : 'Retry'} ${entry.file.name}`);
@@ -18942,7 +19064,7 @@ function createFormAttachments(client, prefix, context) {
18942
19064
  if (!stillCurrent())
18943
19065
  return;
18944
19066
  if (!owner) {
18945
- update(entry, 'queued', 'Sign in to upload this file.');
19067
+ update(entry, 'queued', 'Uploads when you send your request.');
18946
19068
  return;
18947
19069
  }
18948
19070
  const options = {
@@ -19025,54 +19147,70 @@ function createFormAttachments(client, prefix, context) {
19025
19147
  function remove(entry) {
19026
19148
  if (locked)
19027
19149
  return;
19150
+ // A keyboard removal keeps focus among the files, else on Attach.
19151
+ const refocus = document.activeElement === entry.remove;
19152
+ const index = entries.indexOf(entry);
19028
19153
  entry.controller?.abort();
19029
19154
  entries = entries.filter(candidate => candidate !== entry);
19030
19155
  entry.row.remove();
19031
- notice.hidden = true;
19156
+ setNotice(notice, null);
19032
19157
  void cancel(entry);
19158
+ onEntriesChange();
19159
+ if (refocus)
19160
+ (entries[Math.min(index, entries.length - 1)]?.remove ?? attach).focus();
19033
19161
  }
19034
19162
  function add(files) {
19035
19163
  if (locked || pickingDisabled || destroyed)
19036
19164
  return;
19037
19165
  const incoming = Array.from(files);
19166
+ if (incoming.length === 0)
19167
+ return;
19038
19168
  const room = Math.max(0, MAX_ATTACHMENTS_PER_MESSAGE - entries.length);
19039
- notice.hidden = incoming.length <= room;
19040
- notice.textContent = `You can attach up to ${MAX_ATTACHMENTS_PER_MESSAGE} files. Remove a file before adding another.`;
19169
+ setNotice(notice, incoming.length > room ? `You can attach up to ${MAX_ATTACHMENTS_PER_MESSAGE} files. Remove a file before adding another.` : null);
19041
19170
  for (const file of incoming.slice(0, room)) {
19042
19171
  const row = document.createElement('li');
19043
- row.className = 'svhd-file';
19172
+ row.className = 'svhd-attachment-chip';
19044
19173
  const filename = document.createElement('span');
19045
- filename.className = 'svhd-file-name';
19174
+ filename.className = 'svhd-attachment-name';
19046
19175
  filename.textContent = file.name;
19176
+ filename.title = file.name;
19047
19177
  const status = document.createElement('span');
19178
+ status.className = 'svhd-attachment-status';
19048
19179
  status.setAttribute('role', 'status');
19049
19180
  status.setAttribute('aria-live', 'polite');
19050
- const progress = createProgress();
19181
+ const progress = document.createElement('progress');
19182
+ progress.className = 'svhd-attachment-progress';
19051
19183
  progress.max = 100;
19052
19184
  progress.value = 0;
19185
+ progress.hidden = true;
19053
19186
  progress.setAttribute('aria-label', `Upload progress for ${file.name}`);
19054
19187
  const removeButton = document.createElement('button');
19055
19188
  removeButton.type = 'button';
19056
- removeButton.className = 'svhd-button svhd-secondary';
19057
- removeButton.textContent = 'Remove';
19189
+ removeButton.className = 'svhd-attachment-remove';
19058
19190
  removeButton.setAttribute('aria-label', `Remove ${file.name}`);
19191
+ removeButton.append(helpDeskIcon('close'));
19059
19192
  const retry = document.createElement('button');
19060
19193
  retry.type = 'button';
19061
- retry.className = 'svhd-button svhd-secondary';
19194
+ retry.className = 'svhd-attachment-retry';
19062
19195
  retry.hidden = true;
19063
19196
  const entry = { file, row, status, progress, remove: removeButton, retry, state: 'queued', retryable: false };
19064
19197
  removeButton.onclick = () => remove(entry);
19065
19198
  retry.onclick = () => { if (!locked && entry.retryable)
19066
19199
  void run(entry); };
19067
- row.append(filename, status, progress, removeButton, retry);
19200
+ row.append(filename, removeButton, status, retry, progress);
19068
19201
  list.append(row);
19069
19202
  entries.push(entry);
19070
19203
  void run(entry);
19071
19204
  }
19205
+ if (room > 0)
19206
+ onEntriesChange();
19072
19207
  }
19073
19208
  const onChange = () => { if (input.files)
19074
19209
  add(input.files); input.value = ''; };
19210
+ const onAttach = () => { if (!attach.disabled)
19211
+ input.click(); };
19075
19212
  input.addEventListener('change', onChange);
19213
+ attach.addEventListener('click', onAttach);
19076
19214
  function clear(preserveComplete = false) {
19077
19215
  revision += 1;
19078
19216
  const previous = entries;
@@ -19084,17 +19222,20 @@ function createFormAttachments(client, prefix, context) {
19084
19222
  }
19085
19223
  list.replaceChildren();
19086
19224
  input.value = '';
19087
- notice.hidden = true;
19225
+ setNotice(notice, null);
19088
19226
  }
19089
19227
  return {
19090
- element,
19228
+ toolbar,
19229
+ list,
19230
+ notice,
19231
+ get accepting() { return !locked && !pickingDisabled && !destroyed; },
19091
19232
  get attachmentIds() { return entries.filter(entry => entry.state === 'complete' && entry.attachmentId).map(entry => entry.attachmentId); },
19092
19233
  get unresolved() { return entries.some(entry => entry.state !== 'complete'); },
19093
19234
  get hasEntries() { return entries.length > 0; },
19094
- get busy() { return entries.some(entry => !!entry.operation); },
19235
+ add,
19095
19236
  async start() { await Promise.all(entries.map(entry => entry.operation ?? (entry.state === 'queued' ? run(entry) : Promise.resolve()))); },
19096
- lock(value) { locked = value; input.disabled = value || pickingDisabled; entries.forEach(controls); },
19097
- disablePicking(value) { pickingDisabled = value; input.disabled = value || locked; },
19237
+ lock(value) { locked = value; syncPicking(); entries.forEach(controls); },
19238
+ disablePicking(value) { pickingDisabled = value; syncPicking(); },
19098
19239
  renewSession(previousToken, nextToken) {
19099
19240
  for (const entry of entries) {
19100
19241
  if (entry.context?.expectedSessionToken === previousToken)
@@ -19102,11 +19243,175 @@ function createFormAttachments(client, prefix, context) {
19102
19243
  }
19103
19244
  },
19104
19245
  clear,
19105
- destroy(preserveComplete = false) { destroyed = true; clear(preserveComplete); input.removeEventListener('change', onChange); },
19246
+ destroy(preserveComplete = false) {
19247
+ destroyed = true;
19248
+ clear(preserveComplete);
19249
+ input.removeEventListener('change', onChange);
19250
+ attach.removeEventListener('click', onAttach);
19251
+ },
19252
+ };
19253
+ }
19254
+
19255
+ const FOLDER_COPY = 'Folders can’t be attached. Add the files inside them instead.';
19256
+ function carriesFiles(event) {
19257
+ return Array.from(event.dataTransfer?.types ?? []).includes('Files');
19258
+ }
19259
+ /**
19260
+ * The details field as a composer. A file pasted into the summary or the
19261
+ * details, or dropped anywhere on the request step, joins the form's one
19262
+ * attachment pipeline (`attachments.add`), under the same limits and
19263
+ * refusals as a picked one; the drop target shows only over the composer. A
19264
+ * paste or drag of text alone stays the browser's. A file brought over the
19265
+ * form is never the browser's to open in place of the unsent request: on the
19266
+ * reply-to step, or while the form takes no files, it is refused outright,
19267
+ * and a desk that takes no files says so when the file is dropped.
19268
+ */
19269
+ function createComposer(options) {
19270
+ const { form, summary, textarea, attachments, deskRefusesFiles, onRequestStep } = options;
19271
+ const frame = document.createElement('div');
19272
+ frame.className = 'svhd-composer';
19273
+ textarea.classList.add('svhd-composer-input');
19274
+ const drop = document.createElement('p');
19275
+ drop.className = 'svhd-composer-drop';
19276
+ drop.textContent = 'Drop the files to attach them.';
19277
+ drop.hidden = true;
19278
+ frame.append(textarea, drop);
19279
+ if (attachments)
19280
+ frame.append(attachments.toolbar, attachments.list);
19281
+ const notice = attachments?.notice ?? createNotice();
19282
+ const fields = [summary, textarea];
19283
+ let pastedImages = 0;
19284
+ function fileAction() {
19285
+ if (!onRequestStep())
19286
+ return 'none';
19287
+ if (attachments)
19288
+ return attachments.accepting ? 'attach' : 'none';
19289
+ return deskRefusesFiles ? 'refuse' : 'none';
19290
+ }
19291
+ function dragging(value) {
19292
+ frame.classList.toggle('svhd-composer-dragging', value);
19293
+ drop.hidden = !value;
19294
+ }
19295
+ function refuseFiles() {
19296
+ if (!notice.hidden && notice.textContent === NO_CUSTOMER_FILES_COPY)
19297
+ return;
19298
+ setNotice(notice, NO_CUSTOMER_FILES_COPY);
19299
+ }
19300
+ // A dropped folder arrives as a file that cannot be read, so it is left out,
19301
+ // and said so beside any refusal the files with it met.
19302
+ function attachDropped(transfer) {
19303
+ const files = [];
19304
+ let folders = 0;
19305
+ for (const item of Array.from(transfer.items)) {
19306
+ if (item.kind !== 'file')
19307
+ continue;
19308
+ if (item.webkitGetAsEntry()?.isDirectory) {
19309
+ folders += 1;
19310
+ continue;
19311
+ }
19312
+ const file = item.getAsFile();
19313
+ if (file)
19314
+ files.push(file);
19315
+ }
19316
+ if (files.length > 0)
19317
+ attachments?.add(files);
19318
+ if (folders > 0)
19319
+ setNotice(notice, files.length > 0 && !notice.hidden ? `${FOLDER_COPY} ${notice.textContent}` : FOLDER_COPY);
19320
+ }
19321
+ // A picture pasted from the clipboard is named "image.png" every time;
19322
+ // numbering the pastes tells their chips, and their Remove buttons, apart.
19323
+ function pastedName(file) {
19324
+ const extension = /^image\.(\w+)$/.exec(file.name)?.[1];
19325
+ if (extension === undefined)
19326
+ return file;
19327
+ pastedImages += 1;
19328
+ return new File([file], `Pasted image ${pastedImages}.${extension}`, { type: file.type, lastModified: file.lastModified });
19329
+ }
19330
+ // Cancelling dragenter and dragover keeps the browser from opening the file
19331
+ // in place of the page. A drop effect of none cancels the drop itself, so a
19332
+ // file the desk refuses keeps one to be refused in words when it lands.
19333
+ const onDragOver = (event) => {
19334
+ if (!carriesFiles(event))
19335
+ return;
19336
+ event.preventDefault();
19337
+ const action = fileAction();
19338
+ if (event.dataTransfer)
19339
+ event.dataTransfer.dropEffect = action === 'none' ? 'none' : 'copy';
19340
+ dragging(action === 'attach' && event.target instanceof Node && frame.contains(event.target));
19341
+ };
19342
+ const onDragLeave = (event) => {
19343
+ if (!(event.relatedTarget instanceof Node) || !frame.contains(event.relatedTarget))
19344
+ dragging(false);
19345
+ };
19346
+ const onDrop = (event) => {
19347
+ if (!carriesFiles(event))
19348
+ return;
19349
+ event.preventDefault();
19350
+ dragging(false);
19351
+ const action = fileAction();
19352
+ if (action === 'attach' && event.dataTransfer)
19353
+ attachDropped(event.dataTransfer);
19354
+ else if (action === 'refuse')
19355
+ refuseFiles();
19356
+ };
19357
+ // A paste that carries files is those files, and the text beside them is
19358
+ // only their names (a file copied in the system's file manager), so none of
19359
+ // it lands in the field. Office apps are the exception: copied cells or
19360
+ // paragraphs come as text and formatted text, with a picture of them as a
19361
+ // file, and that paste is the text.
19362
+ const onPaste = (event) => {
19363
+ const clipboard = event.clipboardData;
19364
+ if (!clipboard || clipboard.files.length === 0)
19365
+ return;
19366
+ if (Array.from(clipboard.types).includes('text/html') && clipboard.getData('text/plain'))
19367
+ return;
19368
+ const action = fileAction();
19369
+ if (action === 'none')
19370
+ return;
19371
+ event.preventDefault();
19372
+ if (action === 'attach')
19373
+ attachments?.add(Array.from(clipboard.files, pastedName));
19374
+ else
19375
+ refuseFiles();
19376
+ };
19377
+ const onInput = () => { if (!attachments)
19378
+ setNotice(notice, null); };
19379
+ form.addEventListener('dragenter', onDragOver);
19380
+ form.addEventListener('dragover', onDragOver);
19381
+ form.addEventListener('dragleave', onDragLeave);
19382
+ form.addEventListener('drop', onDrop);
19383
+ for (const field of fields) {
19384
+ field.addEventListener('paste', onPaste);
19385
+ field.addEventListener('input', onInput);
19386
+ }
19387
+ return {
19388
+ frame,
19389
+ notice,
19390
+ clearNotice: () => setNotice(notice, null),
19391
+ destroy() {
19392
+ form.removeEventListener('dragenter', onDragOver);
19393
+ form.removeEventListener('dragover', onDragOver);
19394
+ form.removeEventListener('dragleave', onDragLeave);
19395
+ form.removeEventListener('drop', onDrop);
19396
+ for (const field of fields) {
19397
+ field.removeEventListener('paste', onPaste);
19398
+ field.removeEventListener('input', onInput);
19399
+ }
19400
+ },
19106
19401
  };
19107
19402
  }
19108
19403
 
19109
19404
  const TTL_MS = 30 * 60 * 1000;
19405
+ /** JSON writes one character of a field as up to six: a control character or lone surrogate becomes an escape like \u0001. */
19406
+ const MAX_ESCAPED_CHAR = 6;
19407
+ /** Room in a row for its keys, ids, timestamps, attachment list and article id. */
19408
+ const ROW_FRAME_CHARS = 8192;
19409
+ /** The longest row a writer can store with these fields, so a reader refuses only rows no writer made. */
19410
+ const maxRowChars = (bodies, subjects) => MAX_ESCAPED_CHAR * (bodies * MAX_BODY_BYTES + subjects * MAX_SUBJECT_LEN) + ROW_FRAME_CHARS;
19411
+ /** The question, the request's subject and description, and the question the request was filled from. */
19412
+ const MAX_ISSUE_ROW_CHARS = maxRowChars(3, 1);
19413
+ /** The request and the uncertain send, each with a subject and description. */
19414
+ const MAX_DRAFT_ROW_CHARS = maxRowChars(2, 2);
19110
19415
  const storageKey = (deskId, requesterId) => isHelpDeskId(deskId) && isResourceIdOf('requester', requesterId) ? `sv-hd-draft:${deskId}:${requesterId}:new` : null;
19111
19416
  const validBody = (value) => typeof value === 'string' && value.length <= MAX_BODY_BYTES && new TextEncoder().encode(value).length <= MAX_BODY_BYTES;
19112
19417
  const validSubject = (value) => typeof value === 'string' && value.length <= MAX_SUBJECT_LEN;
@@ -19127,14 +19432,19 @@ function readSupportDraft(deskId) {
19127
19432
  const raw = sessionStorage.getItem(`sv-hd-issue:${deskId}`);
19128
19433
  if (!raw)
19129
19434
  return null;
19130
- if (raw.length > MAX_BODY_BYTES * 4)
19435
+ if (raw.length > MAX_ISSUE_ROW_CHARS)
19131
19436
  throw new Error('Invalid issue');
19132
19437
  const row = JSON.parse(raw);
19133
19438
  if (row?.desk_id !== deskId || !validBody(row.issue) || !Number.isFinite(row.expires_at) ||
19134
19439
  row.expires_at <= Date.now() || row.expires_at > Date.now() + TTL_MS ||
19135
19440
  (row.composition !== undefined && (!validSubject(row.composition?.subject) || !validBody(row.composition?.body))))
19136
19441
  throw new Error('Invalid issue');
19137
- return { issue: row.issue, ...(row.composition && { composition: { subject: row.composition.subject, body: row.composition.body } }) };
19442
+ if (row.composition === undefined)
19443
+ return { issue: row.issue };
19444
+ // The question a request was filled from only steers refilling it: one that
19445
+ // is not a question, or belongs to no request, is left out, never the row.
19446
+ return { issue: row.issue, composition: { subject: row.composition.subject, body: row.composition.body },
19447
+ ...(validBody(row.composed_from) && { composedFrom: row.composed_from }) };
19138
19448
  }
19139
19449
  catch {
19140
19450
  clearSupportIssue(deskId);
@@ -19142,25 +19452,34 @@ function readSupportDraft(deskId) {
19142
19452
  }
19143
19453
  }
19144
19454
  function readSupportIssue(deskId) { return readSupportDraft(deskId)?.issue ?? null; }
19145
- function readAnonymousFormDraft(deskId) { return readSupportDraft(deskId)?.composition ?? null; }
19146
- function writeSupportDraft(deskId, issue, composition) {
19455
+ function readAnonymousFormDraft(deskId) {
19456
+ const draft = readSupportDraft(deskId);
19457
+ return draft?.composition ? { ...draft.composition, composedFrom: draft.composedFrom ?? '' } : null;
19458
+ }
19459
+ function writeSupportDraft(deskId, draft) {
19147
19460
  try {
19148
- sessionStorage.setItem(`sv-hd-issue:${deskId}`, JSON.stringify({ desk_id: deskId, issue,
19149
- ...(composition && { composition }), expires_at: Date.now() + TTL_MS }));
19461
+ sessionStorage.setItem(`sv-hd-issue:${deskId}`, JSON.stringify({ desk_id: deskId, issue: draft.issue,
19462
+ ...(draft.composition && { composition: draft.composition }), ...(draft.composedFrom !== undefined && { composed_from: draft.composedFrom }),
19463
+ expires_at: Date.now() + TTL_MS }));
19150
19464
  }
19151
19465
  catch { /* The live wizard still keeps its composition in memory. */ }
19152
19466
  }
19153
19467
  function saveSupportIssue(deskId, issue) {
19154
19468
  if (!isHelpDeskId(deskId) || !validBody(issue))
19155
19469
  return;
19156
- const composition = readAnonymousFormDraft(deskId) ?? undefined;
19157
- if (!issue && !composition) {
19470
+ const draft = readSupportDraft(deskId);
19471
+ if (!issue && !draft?.composition) {
19158
19472
  clearSupportIssue(deskId);
19159
19473
  return;
19160
19474
  }
19161
- writeSupportDraft(deskId, issue, composition);
19475
+ writeSupportDraft(deskId, { ...draft, issue });
19162
19476
  }
19163
- function saveAnonymousFormDraft(deskId, composition) {
19477
+ /**
19478
+ * Save a signed-out customer's request beside the tab's question, with the
19479
+ * question it was filled from when the support wizard filled it. A question
19480
+ * too long to keep is left out, so the request reads as the customer's own.
19481
+ */
19482
+ function saveAnonymousFormDraft(deskId, composition, composedFrom) {
19164
19483
  if (!isHelpDeskId(deskId) || !validSubject(composition.subject) || !validBody(composition.body))
19165
19484
  return;
19166
19485
  const issue = readSupportIssue(deskId) ?? '';
@@ -19168,7 +19487,7 @@ function saveAnonymousFormDraft(deskId, composition) {
19168
19487
  clearSupportIssue(deskId);
19169
19488
  return;
19170
19489
  }
19171
- writeSupportDraft(deskId, issue, { subject: composition.subject, body: composition.body });
19490
+ writeSupportDraft(deskId, { issue, composition: { subject: composition.subject, body: composition.body }, ...(validBody(composedFrom) && { composedFrom }) });
19172
19491
  }
19173
19492
  function removeFormDraft(deskId, requesterId) {
19174
19493
  const key = storageKey(deskId, requesterId);
@@ -19186,7 +19505,7 @@ function readFormDraft(deskId, requesterId) {
19186
19505
  const raw = sessionStorage.getItem(key);
19187
19506
  if (!raw)
19188
19507
  return null;
19189
- if (raw.length > MAX_BODY_BYTES * 4)
19508
+ if (raw.length > MAX_DRAFT_ROW_CHARS)
19190
19509
  throw new Error('Invalid draft');
19191
19510
  const row = JSON.parse(raw);
19192
19511
  const sent = row?.uncertain;
@@ -19235,9 +19554,47 @@ function unknownSubmissionOutcome(error) {
19235
19554
  const status = error instanceof SparkVaultError ? error.statusCode : undefined;
19236
19555
  return status === undefined || status < 400 || status === 408 || status >= 500;
19237
19556
  }
19238
- function createDescriptionInput() {
19239
- return document.createElement('textarea');
19557
+ /**
19558
+ * A ticket's body: the details the customer wrote, or, when they wrote none,
19559
+ * the summary, since every ticket carries a message. The one place the two
19560
+ * fields become the body that is checked against the limit and sent.
19561
+ */
19562
+ function ticketBody(summary, details) {
19563
+ return details.trim() ? details : summary;
19564
+ }
19565
+ /** The details field that gives a send's body back through `ticketBody`: empty when the body is its summary. */
19566
+ function detailsOf(submission) {
19567
+ return submission.body === submission.subject ? '' : submission.body;
19568
+ }
19569
+ /** A signed-in customer as the form names them: "Alex M." for Alex Morgan, a one-word name as it is, else their email. */
19570
+ function postingName(customer) {
19571
+ const words = (customer.display_name ?? '').trim().split(/\s+/).filter(Boolean);
19572
+ if (words.length === 0)
19573
+ return customer.email;
19574
+ if (words.length === 1)
19575
+ return words[0];
19576
+ return `${words[0]} ${Array.from(words[words.length - 1])[0]}.`;
19577
+ }
19578
+ function focusAtEnd(field, focusOptions) {
19579
+ field.focus(focusOptions);
19580
+ // An email field has no caret to place.
19581
+ if (field.type !== 'email')
19582
+ field.setSelectionRange(field.value.length, field.value.length);
19240
19583
  }
19584
+ /** A button that reads as a link: an action beside text, never the step's own. */
19585
+ function textButton(text, action) {
19586
+ const button = document.createElement('button');
19587
+ button.type = 'button';
19588
+ button.className = 'svhd-text-button';
19589
+ button.textContent = text;
19590
+ button.addEventListener('click', action);
19591
+ return button;
19592
+ }
19593
+ const SIGN_IN_CANCELLED_COPY = 'Sign-in was cancelled. Your request is still here and hasn’t been sent.';
19594
+ const RECOVER_STATUS_COPY = 'Sign in again to recover your saved request.';
19595
+ const RECOVER_WEBSITE_COPY = 'Sign in to your website account again to recover your saved request.';
19596
+ const WEBSITE_SIGNED_OUT_COPY = 'You’re not signed in to the website. Sign in there, then choose Use website account again.';
19597
+ const RECOVER_NOTE_COPY = 'Sign in with the same email as before to recover your saved request.';
19241
19598
  /** Host callback failures do not change a ticket's accepted or failed result. */
19242
19599
  function notify$1(callback, value) {
19243
19600
  try {
@@ -19265,6 +19622,22 @@ function edited(input, prefill) {
19265
19622
  const text = input.value.trim();
19266
19623
  return text !== '' && text !== prefill.trim();
19267
19624
  }
19625
+ /**
19626
+ * The longest issue that fills the summary when contact starts. An issue this
19627
+ * short, on one line, already names the request; a longer one is the
19628
+ * customer's description, and cutting a summary from it would put words in
19629
+ * their mouth.
19630
+ */
19631
+ const SUMMARY_PREFILL_MAX = 100;
19632
+ /** Whether trimmed text is one line of at most `max` characters. */
19633
+ function oneLine(text, max) {
19634
+ return text.length <= max && !/[\r\n]/.test(text);
19635
+ }
19636
+ /** What contact starts from: a short one-line issue as the summary; any other as the details, every character as written. */
19637
+ function composeIssue(issue) {
19638
+ const text = issue.trim();
19639
+ return oneLine(text, SUMMARY_PREFILL_MAX) ? { subject: text, body: '' } : { subject: '', body: issue };
19640
+ }
19268
19641
  function companySignInUrl(value) {
19269
19642
  try {
19270
19643
  const url = new URL(value ?? '');
@@ -19284,24 +19657,54 @@ function companySignInUrl(value) {
19284
19657
  * line carries the flow (a code sent, a send in progress or uncertain, a
19285
19658
  * changed sign-in, a server error). Closing with unsent work asks first.
19286
19659
  * A confirmed send replaces the form with its confirmation.
19660
+ *
19661
+ * The request is a summary and optional details, in a composer that also
19662
+ * takes files. A signed-out widget customer writes it as step 1 of 2; step 2
19663
+ * asks who the reply goes to and proves it in the native sign-in window.
19287
19664
  */
19288
19665
  function mountHelpDeskForm(client, options) {
19289
19666
  const target = resolveTarget(options.target);
19290
19667
  injectHelpDeskFormStyles();
19668
+ const widget = options.widgetIdentity;
19291
19669
  const shell = new InlineShell(target, {
19292
19670
  containerClassName: 'svhd-container',
19293
19671
  bodyClassName: 'svhd-body',
19294
- footer: createSecuredByFooter('svhd'),
19672
+ // The page that lays the support wizard out carries the attribution itself.
19673
+ footer: options.hostShowsAttribution ? null : createSecuredByFooter('svhd'),
19295
19674
  });
19296
19675
  const prefix = `svhd-${++formSequence}`;
19297
- const heading = document.createElement('h2');
19298
- heading.id = `${prefix}-heading`;
19299
- heading.textContent = 'Contact support';
19300
19676
  const form = document.createElement('form');
19301
19677
  form.className = 'svhd-form';
19302
19678
  form.noValidate = true;
19679
+ shell.body.append(form);
19680
+ /** A step's heading, which takes focus when the step is entered, under its "Step N of 2" label when it has one. */
19681
+ function stepHead(id, title, label) {
19682
+ const head = document.createElement('div');
19683
+ head.className = 'svhd-step-head';
19684
+ const stepLabel = label === null ? null : document.createElement('p');
19685
+ if (stepLabel) {
19686
+ stepLabel.className = 'svhd-step-label';
19687
+ stepLabel.textContent = label;
19688
+ head.append(stepLabel);
19689
+ }
19690
+ const stepHeading = document.createElement('h2');
19691
+ stepHeading.id = id;
19692
+ stepHeading.tabIndex = -1;
19693
+ stepHeading.textContent = title;
19694
+ head.append(stepHeading);
19695
+ return { head, heading: stepHeading, label: stepLabel };
19696
+ }
19697
+ function stepContainer(step) {
19698
+ const container = document.createElement('div');
19699
+ container.className = 'svhd-step';
19700
+ container.dataset.contactStep = step;
19701
+ return container;
19702
+ }
19703
+ const request = stepHead(`${prefix}-heading`, widget ? `Contact ${client.desk.organization_name || 'support'}` : 'Contact support', widget ? 'Step 1 of 2' : null);
19704
+ const heading = request.heading;
19303
19705
  form.setAttribute('aria-labelledby', heading.id);
19304
- shell.body.append(heading, form);
19706
+ const details = stepContainer('details');
19707
+ details.append(request.head);
19305
19708
  // A field's error is an alert only while it shows, so it is announced
19306
19709
  // even when focus already sits on the field it names.
19307
19710
  function setFieldError(entry, text) {
@@ -19333,10 +19736,11 @@ function mountHelpDeskForm(client, options) {
19333
19736
  label.className = 'svhd-label';
19334
19737
  label.htmlFor = `${prefix}-${name}`;
19335
19738
  label.textContent = labelText;
19336
- const input = textarea ? createDescriptionInput() : document.createElement('input');
19739
+ const input = textarea ? document.createElement('textarea') : document.createElement('input');
19337
19740
  input.id = label.htmlFor;
19338
19741
  input.name = name;
19339
- input.className = textarea ? 'svhd-input svhd-description' : 'svhd-input';
19742
+ if (!textarea)
19743
+ input.className = 'svhd-input';
19340
19744
  const error = document.createElement('p');
19341
19745
  error.id = `${input.id}-error`;
19342
19746
  error.className = 'svhd-field-error';
@@ -19346,19 +19750,23 @@ function mountHelpDeskForm(client, options) {
19346
19750
  input.addEventListener('input', () => clearFieldError(created));
19347
19751
  return created;
19348
19752
  }
19349
- const subject = field('Subject', 'subject');
19350
- const description = field('Description', 'description', true);
19753
+ const subject = field('Summary', 'subject');
19754
+ const description = field('Additional details', 'description', true);
19351
19755
  const email = field('Email address', 'email');
19352
19756
  const code = field('Email code', 'code');
19353
19757
  const name = field('Your name', 'display_name');
19354
19758
  const firstName = field('First name', 'given_name');
19355
19759
  const lastName = field('Last name (optional)', 'family_name');
19356
19760
  const fields = [subject, description, email, code, name, firstName, lastName];
19357
- // What the host, or the support controller, filled the form with: text the customer did not write.
19358
- const prefill = { subject: options.subject ?? '', body: options.body ?? '' };
19761
+ // The support wizard's issue the form was last filled from, which either
19762
+ // field may hold; undefined for a form filled from the host's subject and body.
19763
+ let filledFrom = options.issue;
19764
+ /** What a field was filled with: text the customer did not write. */
19765
+ const filledWith = (key) => filledFrom ?? options[key] ?? '';
19766
+ const filled = filledFrom === undefined ? { subject: filledWith('subject'), body: filledWith('body') } : composeIssue(filledFrom);
19359
19767
  subject.input.maxLength = MAX_SUBJECT_LEN;
19360
- subject.input.value = prefill.subject;
19361
- description.input.value = prefill.body;
19768
+ subject.input.value = filled.subject;
19769
+ description.input.value = filled.body;
19362
19770
  email.input.type = 'email';
19363
19771
  email.input.autocomplete = 'email';
19364
19772
  code.input.inputMode = 'numeric';
@@ -19370,7 +19778,7 @@ function mountHelpDeskForm(client, options) {
19370
19778
  lastName.input.maxLength = 100;
19371
19779
  const codeHint = document.createElement('p');
19372
19780
  codeHint.id = `${code.input.id}-hint`;
19373
- codeHint.className = 'svhd-file-hint';
19781
+ codeHint.className = 'svhd-hint';
19374
19782
  codeHint.textContent = `It works for ${HELP_DESK_PIN_TTL_MINUTES} minutes. Not in your inbox? Look in spam for mail from ${client.desk.contact_email ?? helpDeskCodeSender(client.desk.sending_host)}.`;
19375
19783
  code.input.setAttribute('aria-describedby', codeHint.id);
19376
19784
  const resend = document.createElement('button');
@@ -19387,23 +19795,93 @@ function mountHelpDeskForm(client, options) {
19387
19795
  code.wrapper.append(codeHint, codeLinks);
19388
19796
  code.wrapper.hidden = true;
19389
19797
  name.wrapper.hidden = true;
19798
+ subject.input.required = true;
19799
+ // Enter in the summary moves on to the details it leads into, never sends a request half written.
19800
+ subject.input.addEventListener('keydown', (event) => {
19801
+ if (event.key !== 'Enter' || event.isComposing || event.keyCode === 229)
19802
+ return;
19803
+ event.preventDefault();
19804
+ focusAtEnd(description.input);
19805
+ });
19806
+ const attachments = client.desk.customer_can_attach_files && options.attachments !== false
19807
+ ? createFormAttachments(client, prefix, async () => {
19808
+ const ownGeneration = generation;
19809
+ const token = await tokenFor(ownGeneration);
19810
+ if (!token || !alive(ownGeneration))
19811
+ return null;
19812
+ const id = await ensureDraft(ownGeneration, token);
19813
+ if (!alive(ownGeneration))
19814
+ return null;
19815
+ return { draftId: id, expectedSessionToken: token };
19816
+ }, () => {
19817
+ if (attachments?.hasEntries)
19818
+ restoredFiles = false;
19819
+ persistDraft();
19820
+ syncLeaveGuard();
19821
+ })
19822
+ : undefined;
19823
+ const composer = createComposer({
19824
+ form, summary: subject.input, textarea: description.input, attachments,
19825
+ deskRefusesFiles: !client.desk.customer_can_attach_files, onRequestStep: () => step === 'details',
19826
+ });
19827
+ description.wrapper.classList.add('svhd-composer-field');
19828
+ description.wrapper.insertBefore(composer.frame, description.error);
19829
+ description.wrapper.insertBefore(composer.notice, description.error);
19830
+ details.append(subject.wrapper, description.wrapper);
19390
19831
  const auth = document.createElement('fieldset');
19391
19832
  auth.className = 'svhd-auth';
19392
19833
  auth.hidden = true;
19393
- auth.append(email.wrapper, code.wrapper, name.wrapper);
19834
+ auth.append(code.wrapper, name.wrapper);
19394
19835
  const widgetAccount = document.createElement('div');
19395
19836
  widgetAccount.className = 'svhd-widget-account';
19396
- let widgetCustomer = options.widgetIdentity?.customer ?? null;
19397
- if (options.widgetIdentity) {
19398
- const names = document.createElement('div');
19399
- names.className = 'svhd-widget-names';
19400
- names.append(firstName.wrapper, lastName.wrapper);
19401
- auth.prepend(names);
19837
+ let widgetCustomer = widget?.customer ?? null;
19838
+ // A desk that signs in with SparkVault Identity asks only the email: its sign-in window asks a missing name.
19839
+ const asksName = client.desk.auth_mode !== 'identity';
19840
+ const reply = widget ? stepHead(`${prefix}-reply-heading`, asksName ? 'Who should we reply to?' : 'Sign in to send your request', 'Step 2 of 2') : null;
19841
+ const identity = widget ? stepContainer('identity') : null;
19842
+ const recap = document.createElement('div');
19843
+ recap.className = 'svhd-recap';
19844
+ const recapText = document.createElement('p');
19845
+ recapText.className = 'svhd-recap-text';
19846
+ const editRequest = textButton('Edit', () => { if (!pending && !destroyed)
19847
+ enterStep('details'); });
19848
+ editRequest.setAttribute('aria-label', 'Edit your request');
19849
+ const noteText = document.createTextNode('');
19850
+ const unsentNote = asksName
19851
+ ? 'Your request hasn’t been sent yet. Tell us who to reply to, then we’ll send it.'
19852
+ : 'Your request hasn’t been sent yet. Sign in so we know who to reply to, then we’ll send it.';
19853
+ const live = createLiveRegion('svhd-live');
19854
+ if (identity && reply) {
19402
19855
  form.classList.add('svhd-widget-form');
19403
- heading.textContent = `Contact ${client.desk.organization_name || 'support'}`;
19404
- description.wrapper.querySelector('label').textContent = 'Message';
19405
- description.wrapper.classList.add('svhd-widget-message');
19406
- }
19856
+ details.append(widgetAccount);
19857
+ identity.hidden = true;
19858
+ const note = document.createElement('p');
19859
+ note.className = 'svhd-note';
19860
+ note.dataset.unsentNote = '';
19861
+ note.append(helpDeskIcon('info'), noteText);
19862
+ const recapRequest = document.createElement('div');
19863
+ recapRequest.className = 'svhd-recap-request';
19864
+ const recapLabel = document.createElement('span');
19865
+ recapLabel.className = 'svhd-recap-label';
19866
+ recapLabel.textContent = 'Your request';
19867
+ recapRequest.append(recapLabel, recapText);
19868
+ recap.append(recapRequest, editRequest);
19869
+ const helper = document.createElement('p');
19870
+ helper.id = `${email.input.id}-help`;
19871
+ helper.className = 'svhd-hint';
19872
+ helper.textContent = asksName ? 'We’ll email you a code to confirm it’s you.' : 'You’ll confirm it’s you in a secure SparkVault window.';
19873
+ email.input.setAttribute('aria-describedby', helper.id);
19874
+ identity.append(reply.head, note, recap);
19875
+ if (asksName) {
19876
+ const names = document.createElement('div');
19877
+ names.className = 'svhd-widget-names';
19878
+ names.append(firstName.wrapper, lastName.wrapper);
19879
+ identity.append(names);
19880
+ }
19881
+ identity.append(email.wrapper, helper);
19882
+ }
19883
+ else
19884
+ auth.prepend(email.wrapper);
19407
19885
  const status = document.createElement('p');
19408
19886
  status.className = 'svhd-status';
19409
19887
  status.setAttribute('role', 'status');
@@ -19423,13 +19901,15 @@ function mountHelpDeskForm(client, options) {
19423
19901
  const send = document.createElement('button');
19424
19902
  send.className = 'svhd-button';
19425
19903
  send.type = 'submit';
19426
- send.textContent = options.widgetIdentity ? widgetCustomer ? 'Send message' : 'Continue' : 'Send request';
19427
19904
  const cancel = document.createElement('button');
19428
19905
  cancel.className = 'svhd-button svhd-secondary';
19429
19906
  cancel.type = 'button';
19430
19907
  cancel.textContent = 'Cancel';
19431
19908
  cancel.hidden = !options.onCancel;
19432
- actions.append(send, cancel);
19909
+ const startNew = textButton('Start a new request', () => { if (!pending && !destroyed && recovery !== null)
19910
+ leaveRecovery(); });
19911
+ startNew.hidden = true;
19912
+ actions.append(send, startNew, cancel);
19433
19913
  const confirm = document.createElement('div');
19434
19914
  confirm.className = 'svhd-confirm';
19435
19915
  confirm.setAttribute('role', 'group');
@@ -19455,8 +19935,10 @@ function mountHelpDeskForm(client, options) {
19455
19935
  discard.textContent = DISCARD_REQUEST_COPY.discard;
19456
19936
  confirmActions.append(keepEditing, discard);
19457
19937
  confirm.append(confirmTitle, confirmNote, confirmActions);
19458
- form.append(subject.wrapper, description.wrapper, auth, widgetAccount, status, hosted, actions, confirm);
19938
+ form.append(details, ...(identity ? [identity] : []), auth, status, hosted, actions, confirm, live.element);
19459
19939
  let state = 'editing';
19940
+ let step = 'details';
19941
+ let guardingLeave = false;
19460
19942
  let destroyed = false;
19461
19943
  let pending = false;
19462
19944
  let completed = false;
@@ -19476,43 +19958,56 @@ function mountHelpDeskForm(client, options) {
19476
19958
  let uncertainSubmission = null;
19477
19959
  let sessionToken = null;
19478
19960
  let sessionKnown = false;
19479
- let attachments;
19480
19961
  let submittedCode = null;
19481
19962
  let resendAt = 0;
19482
19963
  let resendTimer = null;
19483
19964
  let confirmReturn = null;
19484
19965
  let done = null;
19485
- let draftRequester = null;
19966
+ // The verified customer whose saved request the form holds.
19967
+ let draftOwner = null;
19486
19968
  let restoredDraft = false;
19487
19969
  let restoredAnonymous = false;
19488
19970
  let restoredFiles = false;
19489
- let savedDraftNeedsSignIn = false;
19971
+ // How the customer whose saved request the form hides signed in, while it
19972
+ // waits for them to sign in again: that is the only way back to it.
19973
+ let recovery = null;
19974
+ // The website gave no account back when asked for the hidden request's customer.
19975
+ let websiteSignedOut = false;
19490
19976
  function persistDraft() {
19491
19977
  if (!options.persist || completed || destroyed)
19492
19978
  return;
19493
- if (!draftRequester) {
19494
- if (!savedDraftNeedsSignIn)
19495
- saveAnonymousFormDraft(client.desk.desk_id, { subject: subject.input.value, body: description.input.value });
19979
+ if (!draftOwner) {
19980
+ // The hidden request is a previous customer's; nothing is saved over it.
19981
+ if (recovery === null)
19982
+ saveAnonymousFormDraft(client.desk.desk_id, { subject: subject.input.value, body: description.input.value }, filledFrom);
19496
19983
  return;
19497
19984
  }
19498
- saveFormDraft(client.desk.desk_id, draftRequester, {
19985
+ saveFormDraft(client.desk.desk_id, draftOwner.requester_id, {
19499
19986
  subject: subject.input.value, body: description.input.value, ticketId: draftId,
19500
19987
  uncertain: uncertainSubmission, hadFiles: restoredFiles || attachments?.hasEntries === true,
19501
19988
  });
19502
19989
  }
19503
19990
  function forgetDraft() {
19504
- if (draftRequester)
19505
- removeFormDraft(client.desk.desk_id, draftRequester);
19506
- else if (options.persist)
19991
+ if (!options.persist)
19992
+ return;
19993
+ if (draftOwner)
19994
+ removeFormDraft(client.desk.desk_id, draftOwner.requester_id);
19995
+ else
19507
19996
  clearSupportIssue(client.desk.desk_id);
19508
19997
  }
19509
- /** Only /me or the verified sign-in answer can select a saved requester's draft. */
19998
+ /**
19999
+ * The request is now this verified customer's, saved in this tab or not.
20000
+ * Only /me or the verified sign-in answer can select a saved requester's draft.
20001
+ */
19510
20002
  function restoreDraft(customer) {
19511
- if (!options.persist || draftRequester === customer.requester_id)
20003
+ if (draftOwner?.requester_id === customer.requester_id)
20004
+ return false;
20005
+ draftOwner = customer;
20006
+ recovery = null;
20007
+ renderActions();
20008
+ if (!options.persist)
19512
20009
  return false;
19513
- savedDraftNeedsSignIn = false;
19514
- draftRequester = customer.requester_id;
19515
- const saved = readFormDraft(client.desk.desk_id, draftRequester);
20010
+ const saved = readFormDraft(client.desk.desk_id, customer.requester_id);
19516
20011
  clearSupportIssue(client.desk.desk_id);
19517
20012
  if (!saved) {
19518
20013
  persistDraft();
@@ -19521,12 +20016,10 @@ function mountHelpDeskForm(client, options) {
19521
20016
  restoredDraft = true;
19522
20017
  restoredFiles = saved.hadFiles && !saved.uncertain;
19523
20018
  subject.input.value = saved.uncertain?.subject ?? saved.subject;
19524
- description.input.value = saved.uncertain?.body ?? saved.body;
20019
+ description.input.value = saved.uncertain ? detailsOf(saved.uncertain) : saved.body;
19525
20020
  draftId = saved.ticketId;
19526
20021
  uncertainSubmission = saved.uncertain;
19527
- subject.input.readOnly = uncertainSubmission !== null;
19528
- description.input.readOnly = uncertainSubmission !== null;
19529
- send.textContent = uncertainSubmission ? 'Check submission' : options.widgetIdentity ? widgetCustomer ? 'Send message' : 'Continue' : 'Send request';
20022
+ send.textContent = idleLabel();
19530
20023
  setState(uncertainSubmission ? 'uncertain' : 'editing');
19531
20024
  message(uncertainSubmission
19532
20025
  ? 'Your original request is preserved. Check submission before starting another request.'
@@ -19538,55 +20031,136 @@ function mountHelpDeskForm(client, options) {
19538
20031
  // An account switch must not turn an uncertain send into a fresh request.
19539
20032
  return pending || uncertainSubmission !== null || completed ? null : { subject: subject.input.value, body: description.input.value };
19540
20033
  }
20034
+ /** What the send button reads while nothing is in flight. */
20035
+ function idleLabel() {
20036
+ if (uncertainSubmission)
20037
+ return 'Check submission';
20038
+ if (challenge)
20039
+ return 'Verify and send request';
20040
+ if (recovery === 'external_sso' && widget)
20041
+ return 'Use website account';
20042
+ if (recovery !== null && step === 'details')
20043
+ return 'Sign in to recover request';
20044
+ return widget && !widgetCustomer ? 'Continue' : 'Send request';
20045
+ }
20046
+ /**
20047
+ * The signed-in widget customer writes and sends in one step, posting as
20048
+ * the account named under it; a signed-out one writes the request as step
20049
+ * 1 of 2. Either way the form shows the request.
20050
+ */
19541
20051
  function renderWidgetIdentity() {
19542
- if (!options.widgetIdentity)
20052
+ if (!widget)
19543
20053
  return;
19544
- widgetAccount.replaceChildren();
19545
- send.textContent = widgetCustomer ? 'Send message' : 'Continue';
19546
- auth.hidden = widgetCustomer !== null;
19547
- email.wrapper.hidden = false;
20054
+ if (request.label)
20055
+ request.label.hidden = widgetCustomer !== null;
20056
+ auth.hidden = true;
19548
20057
  code.wrapper.hidden = true;
19549
20058
  name.wrapper.hidden = true;
20059
+ widgetAccount.replaceChildren();
20060
+ const free = () => !pending && !destroyed && uncertainSubmission === null && !completed;
19550
20061
  if (widgetCustomer) {
19551
- const identity = document.createElement('p');
19552
- identity.className = 'svhd-widget-identity';
19553
- const customerName = document.createElement('strong');
19554
- customerName.textContent = widgetCustomer.display_name || widgetCustomer.email;
19555
- const customerEmail = document.createElement('span');
19556
- customerEmail.textContent = widgetCustomer.email;
19557
- identity.append(customerName, customerEmail);
19558
- const change = document.createElement('button');
19559
- change.type = 'button';
19560
- change.className = 'svhd-widget-account-link';
19561
- change.textContent = 'Not you?';
19562
- change.addEventListener('click', () => {
19563
- if (pending || destroyed || uncertainSubmission !== null || completed)
19564
- return;
19565
- options.widgetIdentity?.switchAccount(safeComposition());
19566
- });
19567
- widgetAccount.append(identity, change);
20062
+ const postingAs = document.createElement('p');
20063
+ postingAs.className = 'svhd-posting-as';
20064
+ const shown = postingName(widgetCustomer);
20065
+ // Not you? opens the sign-in window in this click: nothing may await before it.
20066
+ postingAs.append(`Posting as ${shown}${shown.endsWith('.') ? '' : '.'} `, textButton('Not you?', () => {
20067
+ if (free())
20068
+ widget.switchAccount(safeComposition());
20069
+ }));
20070
+ widgetAccount.append(postingAs);
19568
20071
  }
19569
- else {
19570
- const note = document.createElement('p');
19571
- note.className = 'svhd-file-hint';
19572
- note.textContent = 'We’ll confirm your email before sending your request.';
19573
- widgetAccount.append(note);
19574
- }
19575
- if (options.widgetIdentity.useWebsiteAccount) {
19576
- const website = document.createElement('button');
19577
- website.type = 'button';
19578
- website.className = 'svhd-widget-account-link';
19579
- website.textContent = 'Use website account';
19580
- website.addEventListener('click', () => {
19581
- if (!pending && !destroyed && uncertainSubmission === null && !completed)
19582
- options.widgetIdentity?.useWebsiteAccount?.(safeComposition());
19583
- });
19584
- widgetAccount.append(website);
20072
+ if (widget.useWebsiteAccount && widget.offerWebsiteAccount) {
20073
+ widgetAccount.append(textButton('Use website account', () => {
20074
+ if (free())
20075
+ widget.useWebsiteAccount?.(safeComposition());
20076
+ }));
19585
20077
  }
20078
+ setStep('details');
20079
+ }
20080
+ /**
20081
+ * The actions and notes for where the request is. While the form hides a
20082
+ * previous customer's saved request (`recovery`), nothing shows of it, nor
20083
+ * says it was not sent, since it may be a send whose answer was lost: the
20084
+ * request step's status line says how to get it back and the reply-to
20085
+ * step's note alone speaks there, Start a new request leaves it, and the
20086
+ * account row is away. A website-account customer's request comes back only
20087
+ * through that account, so Use website account is its one way on when the
20088
+ * website bridges one, and there is none when it does not.
20089
+ */
20090
+ function renderActions() {
20091
+ send.textContent = idleLabel();
20092
+ send.hidden = recovery === 'external_sso' && widget !== undefined && !widget.useWebsiteAccount;
20093
+ startNew.hidden = recovery === null;
20094
+ widgetAccount.hidden = recovery !== null || widgetAccount.childElementCount === 0;
20095
+ recap.hidden = recovery !== null;
20096
+ noteText.data = recovery === 'identity' || recovery === 'email_pin' ? RECOVER_NOTE_COPY : unsentNote;
20097
+ if (recovery !== null)
20098
+ message(step === 'identity' ? '' : recoveryStatus());
20099
+ }
20100
+ /** What the request step's status line asks for while a saved request is hidden. */
20101
+ function recoveryStatus() {
20102
+ if (recovery !== 'external_sso')
20103
+ return RECOVER_STATUS_COPY;
20104
+ return websiteSignedOut ? WEBSITE_SIGNED_OUT_COPY : RECOVER_WEBSITE_COPY;
20105
+ }
20106
+ /** Start a new request in place of the hidden one, which stays saved for its customer. */
20107
+ function leaveRecovery() {
20108
+ recovery = null;
20109
+ disable(false);
20110
+ message('');
20111
+ // A question asked while the saved request was hidden fills the new one.
20112
+ widget?.followIssue();
20113
+ if (step === 'identity')
20114
+ enterStep('details');
20115
+ else {
20116
+ renderActions();
20117
+ options.onScreenChange?.();
20118
+ controller.focusEntry();
20119
+ }
20120
+ }
20121
+ /** Show one step, the request or who the reply goes to, without moving focus. */
20122
+ function setStep(next) {
20123
+ const changed = next !== step;
20124
+ step = next;
20125
+ details.hidden = next !== 'details';
20126
+ if (identity)
20127
+ identity.hidden = next !== 'identity';
20128
+ if (next === 'identity')
20129
+ recapText.textContent = subject.input.value.trim();
20130
+ renderActions();
20131
+ syncLeaveGuard();
20132
+ if (changed)
20133
+ options.onScreenChange?.();
20134
+ }
20135
+ /** The customer moves between the steps: the new step's heading takes focus and its place is announced. */
20136
+ function enterStep(next) {
20137
+ setStep(next);
20138
+ live.announce(next === 'identity' ? 'Step 2 of 2' : 'Step 1 of 2');
20139
+ (next === 'identity' && reply ? reply.heading : heading).focus();
20140
+ }
20141
+ // An inline wizard, on any host page that gives a `target`, asks before that
20142
+ // page unloads while the request holds unsent work: leaving would lose it.
20143
+ // The floating panel never holds the page.
20144
+ // Chrome and Edge below 119, inside the SDK's browser floor, ask only when
20145
+ // returnValue is set; preventDefault is the standard signal.
20146
+ const onBeforeUnload = (event) => {
20147
+ event.preventDefault();
20148
+ event.returnValue = '';
20149
+ };
20150
+ function syncLeaveGuard() {
20151
+ const needed = options.pageLayout === true && !destroyed && holdsUnsentWork();
20152
+ if (needed === guardingLeave)
20153
+ return;
20154
+ guardingLeave = needed;
20155
+ if (needed)
20156
+ window.addEventListener('beforeunload', onBeforeUnload);
20157
+ else
20158
+ window.removeEventListener('beforeunload', onBeforeUnload);
19586
20159
  }
19587
20160
  function setState(next) {
19588
20161
  state = next;
19589
20162
  persistDraft();
20163
+ syncLeaveGuard();
19590
20164
  notify$1(options.onStateChange, next);
19591
20165
  }
19592
20166
  function message(text, isError = false) {
@@ -19613,13 +20187,22 @@ function mountHelpDeskForm(client, options) {
19613
20187
  resendTimer = setInterval(renderResend, 1000);
19614
20188
  renderResend();
19615
20189
  }
20190
+ /**
20191
+ * Disable every control while `disabled`. The request stays read-only, and
20192
+ * takes no files, while a send is unanswered, its exact text kept for the
20193
+ * check, and while it hides a saved request, which signing in brings back
20194
+ * in place of anything written.
20195
+ */
19616
20196
  function disable(disabled) {
19617
- for (const input of [subject.input, description.input, email.input, code.input, name.input, firstName.input, lastName.input, send, cancel, changeEmail])
20197
+ for (const input of [subject.input, description.input, email.input, code.input, name.input, firstName.input, lastName.input, send, cancel, changeEmail, editRequest, startNew])
19618
20198
  input.disabled = disabled;
20199
+ const held = uncertainSubmission !== null || recovery !== null;
20200
+ subject.input.readOnly = held;
20201
+ description.input.readOnly = held;
19619
20202
  for (const button of widgetAccount.querySelectorAll('button'))
19620
20203
  button.disabled = disabled || uncertainSubmission !== null || completed;
19621
20204
  renderResend();
19622
- attachments?.disablePicking(disabled);
20205
+ attachments?.disablePicking(disabled || recovery !== null);
19623
20206
  attachments?.lock(completed || uncertainSubmission !== null);
19624
20207
  }
19625
20208
  function clearCode() {
@@ -19648,8 +20231,10 @@ function mountHelpDeskForm(client, options) {
19648
20231
  ? 'We may already have received this request. Closing now loses the way to check it.'
19649
20232
  : DISCARD_REQUEST_COPY.note;
19650
20233
  }
19651
- /** The field of the step in view: the code, name or email the sign-in asks for, else the subject. */
20234
+ /** The field of the step in view: who the reply goes to, the code, name or email the sign-in asks for, else the summary. */
19652
20235
  function stepField() {
20236
+ if (step === 'identity')
20237
+ return (asksName ? firstName : email).input;
19653
20238
  const asked = auth.hidden ? undefined : [code, name, email].find((entry) => !entry.wrapper.hidden);
19654
20239
  return (asked ?? subject).input;
19655
20240
  }
@@ -19690,25 +20275,27 @@ function mountHelpDeskForm(client, options) {
19690
20275
  }
19691
20276
  /**
19692
20277
  * Whether closing now would lose something: a send under way or
19693
- * unanswered, a code step, or text and files of the customer's own. The
19694
- * silent company sign-in the form runs as it opens (`authenticating`) is
19695
- * no work of the customer's.
20278
+ * unanswered, a code step, a request moved on to who the reply goes to, or
20279
+ * text and files of the customer's own. The silent company sign-in the
20280
+ * form runs as it opens (`authenticating`) is no work of the customer's.
19696
20281
  */
19697
20282
  function holdsUnsentWork() {
19698
20283
  if (completed)
19699
20284
  return false;
19700
- return (pending && state !== 'authenticating') || uncertainSubmission !== null || challenge !== null
19701
- || edited(subject.input, prefill.subject) || edited(description.input, prefill.body)
20285
+ return (pending && state !== 'authenticating') || uncertainSubmission !== null || challenge !== null || step === 'identity'
20286
+ || edited(subject.input, filledWith('subject')) || edited(description.input, filledWith('body'))
19702
20287
  || attachments?.hasEntries === true;
19703
20288
  }
19704
- /** The field a composition the ticket write would refuse is refused under, with what it reads there; null for one it takes. */
20289
+ /**
20290
+ * The field a request the ticket write would refuse is refused under, with
20291
+ * what it reads there; null for one it takes. The body is `ticketBody`'s,
20292
+ * so a request of a summary alone always has one.
20293
+ */
19705
20294
  function refusal(subjectText, body) {
19706
20295
  if (!subjectText)
19707
- return [subject, 'Add a subject.'];
20296
+ return [subject, 'Add a summary.'];
19708
20297
  if (subjectText.length > MAX_SUBJECT_LEN)
19709
- return [subject, `Keep the subject to ${MAX_SUBJECT_LEN} characters.`];
19710
- if (!body.trim())
19711
- return [description, 'Describe what you need help with.'];
20298
+ return [subject, `Keep the summary to ${MAX_SUBJECT_LEN} characters.`];
19712
20299
  // The limit counts UTF-8 bytes, so a message of fewer characters can be over it;
19713
20300
  // a message of more UTF-16 units than that is over it without being encoded.
19714
20301
  if (body.length > MAX_BODY_BYTES || new TextEncoder().encode(body).length > MAX_BODY_BYTES)
@@ -19777,7 +20364,8 @@ function mountHelpDeskForm(client, options) {
19777
20364
  attachments?.clear(completed || uncertainSubmission !== null);
19778
20365
  attachments?.lock(false);
19779
20366
  if (attachments)
19780
- attachments.element.hidden = false;
20367
+ attachments.list.hidden = false;
20368
+ composer.clearNotice();
19781
20369
  subject.input.value = '';
19782
20370
  description.input.value = '';
19783
20371
  email.input.value = '';
@@ -19798,13 +20386,13 @@ function mountHelpDeskForm(client, options) {
19798
20386
  draftId = null;
19799
20387
  draftPromise = null;
19800
20388
  uncertainSubmission = null;
19801
- savedDraftNeedsSignIn = false;
20389
+ recovery = null;
20390
+ websiteSignedOut = false;
19802
20391
  restoredAnonymous = false;
19803
- subject.input.readOnly = false;
19804
- description.input.readOnly = false;
19805
20392
  completed = false;
19806
- send.textContent = 'Send request';
19807
20393
  message('');
20394
+ renderActions();
20395
+ syncLeaveGuard();
19808
20396
  }
19809
20397
  function sessionChanged(change) {
19810
20398
  if (destroyed)
@@ -19837,18 +20425,26 @@ function mountHelpDeskForm(client, options) {
19837
20425
  // during a pending proof must not leave the previous composer visible.
19838
20426
  subject.input.value = '';
19839
20427
  description.input.value = '';
20428
+ recapText.textContent = '';
19840
20429
  name.input.value = '';
19841
20430
  email.input.value = '';
19842
20431
  clearCode();
19843
20432
  if (attachments)
19844
- attachments.element.hidden = true;
20433
+ attachments.list.hidden = true;
19845
20434
  return;
19846
20435
  }
19847
20436
  // Preserve the old request before hiding it. The next verified requester
19848
20437
  // selects only their own storage key, including after a 401 and sign-in.
19849
20438
  persistDraft();
19850
- const canRecover = options.persist && draftRequester !== null && readFormDraft(client.desk.desk_id, draftRequester) !== null;
19851
- draftRequester = null;
20439
+ // A signed-in customer's request leaves view, saved or not, and with it the
20440
+ // question it was filled from: nothing the form holds may write it back.
20441
+ const hidesCustomer = draftOwner !== null;
20442
+ if (hidesCustomer && filledFrom !== undefined)
20443
+ filledFrom = '';
20444
+ // A saved request stays hidden for its customer, through any further change.
20445
+ const hidden = draftOwner === null ? recovery
20446
+ : options.persist && readFormDraft(client.desk.desk_id, draftOwner.requester_id) !== null ? draftOwner.assurance : null;
20447
+ draftOwner = null;
19852
20448
  restoredDraft = false;
19853
20449
  restoredFiles = false;
19854
20450
  generation += 1;
@@ -19857,15 +20453,19 @@ function mountHelpDeskForm(client, options) {
19857
20453
  if (options.widgetIdentity)
19858
20454
  widgetCustomer = null;
19859
20455
  clearComposer();
19860
- savedDraftNeedsSignIn = Boolean(canRecover);
20456
+ recovery = hidden;
19861
20457
  disable(false);
19862
20458
  setState('editing');
19863
- if (savedDraftNeedsSignIn) {
19864
- send.textContent = 'Sign in to recover request';
19865
- message('Sign in again to recover your saved request. Its text stays private until your account is confirmed.');
19866
- }
19867
- else
20459
+ // The question that led here was the previous customer's too.
20460
+ if (hidesCustomer)
20461
+ widget?.forgetIssue();
20462
+ if (recovery === null)
19868
20463
  message('Your sign-in changed. Start a new request for the current account.');
20464
+ else
20465
+ renderActions();
20466
+ // The request and its actions changed under the pointer: a press already
20467
+ // under way must not act on what replaced them.
20468
+ options.onScreenChange?.();
19869
20469
  }
19870
20470
  const unsubscribe = client.subscribeSession(sessionChanged);
19871
20471
  const alive = (ownGeneration) => !destroyed && generation === ownGeneration;
@@ -19906,19 +20506,6 @@ function mountHelpDeskForm(client, options) {
19906
20506
  }
19907
20507
  return draftPromise;
19908
20508
  }
19909
- if (client.desk.customer_can_attach_files && options.attachments !== false) {
19910
- attachments = createFormAttachments(client, prefix, async () => {
19911
- const ownGeneration = generation;
19912
- const token = await tokenFor(ownGeneration);
19913
- if (!token || !alive(ownGeneration))
19914
- return null;
19915
- const id = await ensureDraft(ownGeneration, token);
19916
- if (!alive(ownGeneration))
19917
- return null;
19918
- return { draftId: id, expectedSessionToken: token };
19919
- });
19920
- form.insertBefore(attachments.element, auth);
19921
- }
19922
20509
  function showEmail() {
19923
20510
  auth.hidden = false;
19924
20511
  email.wrapper.hidden = false;
@@ -19951,31 +20538,46 @@ function mountHelpDeskForm(client, options) {
19951
20538
  // Sending (Enter in a field, a code's last digit) answers the discard
19952
20539
  // question: the customer kept going.
19953
20540
  closeConfirm(false);
20541
+ if (recovery === 'external_sso' && widget) {
20542
+ // Only the website account reaches a website-account customer's saved
20543
+ // request: a code or the secure window would sign in someone else.
20544
+ widget.useWebsiteAccount?.(null, true);
20545
+ return;
20546
+ }
19954
20547
  for (const entry of fields)
19955
20548
  clearFieldError(entry);
19956
20549
  const recoveringSubmission = uncertainSubmission !== null;
19957
20550
  const subjectText = uncertainSubmission?.subject ?? subject.input.value.trim();
19958
- const body = uncertainSubmission?.body ?? description.input.value;
20551
+ const detailsText = uncertainSubmission ? detailsOf(uncertainSubmission) : description.input.value;
20552
+ const body = uncertainSubmission?.body ?? ticketBody(subjectText, detailsText);
19959
20553
  if (uncertainSubmission) {
19960
20554
  // Retrying recovers this exact request. A lost response must never make
19961
20555
  // newly typed text appear to have been accepted as the earlier ticket.
19962
20556
  subject.input.value = subjectText;
19963
- description.input.value = body;
20557
+ description.input.value = detailsText;
19964
20558
  }
19965
20559
  const refused = refusal(subjectText, body);
19966
- const recoveringAfterSignIn = savedDraftNeedsSignIn;
20560
+ const recoveringAfterSignIn = recovery !== null;
19967
20561
  if (refused && !recoveringAfterSignIn) {
19968
20562
  const [entry, text] = refused;
20563
+ if (step !== 'details')
20564
+ setStep('details');
19969
20565
  setFieldError(entry, text);
19970
20566
  entry.input.focus();
19971
20567
  return;
19972
20568
  }
19973
20569
  let widgetSignIn;
19974
- if (options.widgetIdentity && !widgetCustomer) {
19975
- const givenName = firstName.input.value.trim();
19976
- const familyName = lastName.input.value.trim();
20570
+ if (widget && !widgetCustomer) {
20571
+ // The request is written; who the reply goes to is the next step, and
20572
+ // nothing reaches the network before it.
20573
+ if (step === 'details') {
20574
+ enterStep('identity');
20575
+ return;
20576
+ }
20577
+ const givenName = asksName ? firstName.input.value.trim() : '';
20578
+ const familyName = asksName ? lastName.input.value.trim() : '';
19977
20579
  const emailAddress = email.input.value.trim();
19978
- const invalid = !givenName ? firstName : !email.input.validity.valid || !emailAddress ? email : null;
20580
+ const invalid = asksName && !givenName ? firstName : !email.input.validity.valid || !emailAddress ? email : null;
19979
20581
  if (invalid) {
19980
20582
  setFieldError(invalid, invalid === email ? 'Enter your email address.' : 'Enter your first name.');
19981
20583
  invalid.input.focus();
@@ -19984,7 +20586,7 @@ function mountHelpDeskForm(client, options) {
19984
20586
  // Invoke in the original submit gesture, before any awaited token read:
19985
20587
  // the Identity adapter can open its native window without a popup block.
19986
20588
  try {
19987
- widgetSignIn = options.widgetIdentity.signIn({ email: emailAddress, givenName, familyName });
20589
+ widgetSignIn = widget.signIn(asksName ? { email: emailAddress, givenName, familyName } : { email: emailAddress });
19988
20590
  }
19989
20591
  catch (failure) {
19990
20592
  const error = failure instanceof Error ? failure : new Error('Sign-in could not be opened.');
@@ -20001,12 +20603,13 @@ function mountHelpDeskForm(client, options) {
20001
20603
  pending = true;
20002
20604
  disable(true);
20003
20605
  message('');
20606
+ syncLeaveGuard();
20004
20607
  try {
20005
20608
  if (widgetSignIn) {
20006
20609
  authenticating = true;
20007
20610
  authNotification = false;
20008
20611
  setState('authenticating');
20009
- message('Confirm your email in the sign-in window.');
20612
+ message('Finish signing in in the secure window.');
20010
20613
  }
20011
20614
  let token = await tokenFor(ownGeneration);
20012
20615
  if (!alive(ownGeneration))
@@ -20032,10 +20635,10 @@ function mountHelpDeskForm(client, options) {
20032
20635
  sessionKnown = true;
20033
20636
  authenticating = false;
20034
20637
  if (attachments)
20035
- attachments.element.hidden = false;
20638
+ attachments.list.hidden = false;
20036
20639
  subject.input.value = subjectText;
20037
- description.input.value = body;
20038
- if (options.widgetIdentity && session) {
20640
+ description.input.value = detailsText;
20641
+ if (widget && session) {
20039
20642
  widgetCustomer = session.customer;
20040
20643
  renderWidgetIdentity();
20041
20644
  message('');
@@ -20051,7 +20654,8 @@ function mountHelpDeskForm(client, options) {
20051
20654
  if (!alive(ownGeneration))
20052
20655
  return;
20053
20656
  if (!token) {
20054
- if (client.desk.auth_mode !== 'email_pin' && !(client.desk.auth_mode === 'external_sso' && client.desk.external_identity?.guest_email === true)) {
20657
+ // A website-account customer's saved request never comes back through an emailed code.
20658
+ if (recovery === 'external_sso' || (client.desk.auth_mode !== 'email_pin' && !(client.desk.auth_mode === 'external_sso' && client.desk.external_identity?.guest_email === true))) {
20055
20659
  showHosted();
20056
20660
  return;
20057
20661
  }
@@ -20095,10 +20699,10 @@ function mountHelpDeskForm(client, options) {
20095
20699
  sessionKnown = true;
20096
20700
  authenticating = false;
20097
20701
  if (attachments)
20098
- attachments.element.hidden = false;
20702
+ attachments.list.hidden = false;
20099
20703
  dropChallenge();
20100
20704
  subject.input.value = subjectText;
20101
- description.input.value = body;
20705
+ description.input.value = detailsText;
20102
20706
  notify$1(options.onSession, verified);
20103
20707
  }
20104
20708
  if (!token || !alive(ownGeneration))
@@ -20126,7 +20730,7 @@ function mountHelpDeskForm(client, options) {
20126
20730
  email.wrapper.hidden = true;
20127
20731
  code.wrapper.hidden = true;
20128
20732
  name.wrapper.hidden = false;
20129
- send.textContent = 'Send request';
20733
+ send.textContent = idleLabel();
20130
20734
  setState('editing');
20131
20735
  setFieldError(name, 'Add your name before sending your request.');
20132
20736
  focusAfter = name.input;
@@ -20148,7 +20752,7 @@ function mountHelpDeskForm(client, options) {
20148
20752
  setState('submitting');
20149
20753
  if (!alive(ownGeneration))
20150
20754
  return;
20151
- send.textContent = options.widgetIdentity ? 'Sending message' : 'Sending request';
20755
+ send.textContent = 'Sending request';
20152
20756
  if (!uncertainSubmission) {
20153
20757
  const id = await ensureDraft(ownGeneration, token);
20154
20758
  if (!alive(ownGeneration) || !(await tokenFor(ownGeneration)))
@@ -20191,14 +20795,10 @@ function mountHelpDeskForm(client, options) {
20191
20795
  const draftExpired = ticketAttempted && error instanceof SparkVaultError
20192
20796
  && (error.serviceCode === 'DRAFT_EXPIRED' || error.code === 'DRAFT_EXPIRED');
20193
20797
  if (uncertainSubmission && !draftExpired && (!ticketAttempted || recoveringSubmission || unknownSubmissionOutcome(error))) {
20194
- subject.input.readOnly = true;
20195
- description.input.readOnly = true;
20196
20798
  message('We could not confirm whether your request was sent. Check submission to recover it. Your original text is kept unchanged.', true);
20197
20799
  }
20198
20800
  else {
20199
20801
  uncertainSubmission = null;
20200
- subject.input.readOnly = false;
20201
- description.input.readOnly = false;
20202
20802
  if (draftExpired) {
20203
20803
  draftId = null;
20204
20804
  draftPromise = null;
@@ -20209,6 +20809,13 @@ function mountHelpDeskForm(client, options) {
20209
20809
  setFieldError(code, HELP_DESK_CODE_STEP_COPY.codeRefused);
20210
20810
  focusAfter = code.input;
20211
20811
  }
20812
+ else if (widgetSignIn && error instanceof SparkVaultError && error.code === 'user_cancelled') {
20813
+ // The request stays on who the reply goes to, ready to sign in again;
20814
+ // a hidden saved request is not here to speak of, so its note alone stays.
20815
+ if (recovery === null)
20816
+ message(SIGN_IN_CANCELLED_COPY);
20817
+ focusAfter = send;
20818
+ }
20212
20819
  else {
20213
20820
  message(draftExpired ? 'Your saved draft expired. Your text is kept. Choose your files again before sending.' : error.message, true);
20214
20821
  }
@@ -20216,7 +20823,7 @@ function mountHelpDeskForm(client, options) {
20216
20823
  setState(uncertainSubmission ? 'uncertain' : challenge ? 'verifying' : 'editing');
20217
20824
  if (!alive(ownGeneration))
20218
20825
  return;
20219
- send.textContent = uncertainSubmission ? 'Check submission' : challenge ? 'Verify and send request' : options.widgetIdentity ? widgetCustomer ? 'Send message' : 'Continue' : 'Send request';
20826
+ send.textContent = idleLabel();
20220
20827
  notify$1(options.onError, error);
20221
20828
  }
20222
20829
  finally {
@@ -20224,6 +20831,7 @@ function mountHelpDeskForm(client, options) {
20224
20831
  authenticating = false;
20225
20832
  pending = false;
20226
20833
  disable(completed);
20834
+ syncLeaveGuard();
20227
20835
  focusSettled();
20228
20836
  }
20229
20837
  }
@@ -20296,6 +20904,8 @@ function mountHelpDeskForm(client, options) {
20296
20904
  generation += 1;
20297
20905
  stopResendCountdown();
20298
20906
  attachments?.destroy(completed || uncertainSubmission !== null);
20907
+ composer.destroy();
20908
+ live.destroy();
20299
20909
  unsubscribe();
20300
20910
  form.removeEventListener('submit', onSubmit);
20301
20911
  shell.destroy();
@@ -20320,24 +20930,50 @@ function mountHelpDeskForm(client, options) {
20320
20930
  subject.input.value = composition.subject;
20321
20931
  description.input.value = composition.body;
20322
20932
  persistDraft();
20933
+ syncLeaveGuard();
20323
20934
  },
20324
- refill(composition) {
20325
- if (destroyed || restoredDraft || safeComposition() === null)
20935
+ refill(issue) {
20936
+ if (destroyed || restoredDraft || recovery !== null || safeComposition() === null)
20326
20937
  return false;
20938
+ const own = { subject: edited(subject.input, filledWith('subject')), body: edited(description.input, filledWith('body')) };
20939
+ const text = issue.trim();
20940
+ const placed = !own.subject && !own.body ? composeIssue(issue) : { subject: oneLine(text, MAX_SUBJECT_LEN) ? text : '', body: issue };
20327
20941
  for (const [entry, key] of [[subject, 'subject'], [description, 'body']]) {
20328
- if (!edited(entry.input, prefill[key])) {
20329
- entry.input.value = composition[key];
20330
- clearFieldError(entry);
20331
- }
20332
- prefill[key] = composition[key];
20942
+ if (own[key])
20943
+ continue;
20944
+ entry.input.value = placed[key];
20945
+ clearFieldError(entry);
20333
20946
  }
20947
+ filledFrom = issue;
20948
+ if (step === 'identity')
20949
+ recapText.textContent = subject.input.value.trim();
20334
20950
  persistDraft();
20951
+ syncLeaveGuard();
20335
20952
  return true;
20336
20953
  },
20337
20954
  resumeAfterAccess() {
20338
20955
  if (!destroyed && !pending && !completed && uncertainSubmission === null)
20339
20956
  message('');
20340
20957
  },
20958
+ returnToRequest() {
20959
+ if (destroyed || step !== 'identity')
20960
+ return false;
20961
+ // While the sign-in window is open the request stays where it is.
20962
+ if (!pending)
20963
+ enterStep('details');
20964
+ return true;
20965
+ },
20966
+ focusEntry(focusOptions) {
20967
+ if (destroyed || form.hidden)
20968
+ return false;
20969
+ const asked = stepField();
20970
+ const entry = asked === subject.input && subject.input.value.trim() ? description.input : asked;
20971
+ if (entry.disabled || entry.readOnly)
20972
+ (step === 'identity' && reply ? reply.heading : heading).focus(focusOptions);
20973
+ else
20974
+ focusAtEnd(entry, focusOptions);
20975
+ return true;
20976
+ },
20341
20977
  requestDismiss() {
20342
20978
  if (destroyed)
20343
20979
  return;
@@ -20371,18 +21007,28 @@ function mountHelpDeskForm(client, options) {
20371
21007
  keepEditing.addEventListener('click', () => closeConfirm(true));
20372
21008
  discard.addEventListener('click', dismiss);
20373
21009
  form.addEventListener('submit', onSubmit);
20374
- form.addEventListener('input', persistDraft);
20375
- form.addEventListener('change', () => {
20376
- if (attachments?.hasEntries)
20377
- restoredFiles = false;
21010
+ form.addEventListener('input', () => {
20378
21011
  persistDraft();
21012
+ syncLeaveGuard();
20379
21013
  });
21014
+ send.textContent = idleLabel();
20380
21015
  renderWidgetIdentity();
21016
+ // A signed-out widget customer starts on step 1 of 2 with focus in the request.
21017
+ if (widget && !widgetCustomer)
21018
+ live.announce('Step 1 of 2');
20381
21019
  if (options.widgetIdentity?.customer) {
20382
21020
  restoreDraft(options.widgetIdentity.customer);
20383
21021
  disable(false);
20384
21022
  }
20385
- else if (options.persist) {
21023
+ else if (widget?.recovering) {
21024
+ recovery = 'external_sso';
21025
+ websiteSignedOut = widget.recovering.websiteSignedOut;
21026
+ disable(false);
21027
+ renderActions();
21028
+ }
21029
+ else if (options.persist && filledFrom === undefined) {
21030
+ // The support wizard hands a composition it carries to restoreComposition;
21031
+ // a form of the host's own restores the one saved before a reload.
20386
21032
  const saved = readAnonymousFormDraft(client.desk.desk_id);
20387
21033
  if (saved) {
20388
21034
  subject.input.value = saved.subject;
@@ -20390,6 +21036,7 @@ function mountHelpDeskForm(client, options) {
20390
21036
  restoredAnonymous = true;
20391
21037
  }
20392
21038
  }
21039
+ syncLeaveGuard();
20393
21040
  notify$1(options.onStateChange, state);
20394
21041
  // Native company identity starts as the form opens, never from a Connect,
20395
21042
  // Allow, verification or submit gesture. Guest email is explicit desk policy.
@@ -22617,58 +23264,6 @@ function createSupportLauncher(options, open) {
22617
23264
  };
22618
23265
  }
22619
23266
 
22620
- /** A title written with a period: in "Dear Mr. Smith," that period ends no sentence. */
22621
- const HONORIFIC = String.raw `(?:Mr|Mrs|Ms|Mx|Dr|Prof)\.`;
22622
- /**
22623
- * Where a sentence ends: after a period, exclamation or question mark that
22624
- * whitespace follows. An honorific's period is matched first, whole, and left
22625
- * as it is.
22626
- */
22627
- const SENTENCE_END = new RegExp(String.raw `\b${HONORIFIC}(?=\s)|([.!?])(?=\s)`, 'g');
22628
- /** The word a greeting opens with, whole: "Hi", "Hello", "Good morning", "Morning". */
22629
- const SALUTATION = /^(?:hi|hello|hey|hiya|howdy|greetings|dear|good\s+day|(?:good\s+)?(?:morning|afternoon|evening))(?!\p{L})/iu;
22630
- /** The few words greetings use for whom they address. */
22631
- const ADDRESS_WORDS = 'again|there|team|all|everyone|everybody|folks|guys|support|customer|service|sir|madam|or|and';
22632
- /**
22633
- * What may follow the salutation in a greeting: up to four words of address,
22634
- * each an honorific, a name or one of the few words greetings use, in lower
22635
- * case or capitals ("Mr. Smith", "Privacy Bee team", "there", "AGAIN", "Sir
22636
- * or Madam"), then anything but letters and digits: punctuation, symbols and
22637
- * emoji. The words of an issue ("Hi, I can't sign in", "Hey refund please",
22638
- * "HELLO I CANT LOGIN") are none of these, so a sentence holding them is the
22639
- * issue. A name is a capital and lowercase letters, again for each capital of
22640
- * one like PayPal or McKenzie, so a word in capitals is shouted, not a name.
22641
- * Case-sensitive, so that case tells a name: a case-insensitive \p{Lu} matches
22642
- * every letter. A name's apostrophes and hyphens only join letters, so a word
22643
- * of address ends in a letter or an honorific's period, and the closing run
22644
- * never competes with it for more than that one period; that keeps the read
22645
- * linear.
22646
- */
22647
- const ADDRESS = new RegExp(String.raw `^(?:[\s,/&]+(?:${HONORIFIC}|${ADDRESS_WORDS}|${ADDRESS_WORDS.toUpperCase()}|\p{Lu}\p{Ll}*(?:\p{Lu}\p{Ll}+)*(?:['\u2019-]\p{L}+)*)){0,4}[^\p{L}\p{N}]*$`, 'u');
22648
- const TO_WHOM = /^to\s+whom\s+it\s+may\s+concern[^\p{L}\p{N}]*$/iu;
22649
- const LETTER = /\p{L}/u;
22650
- /** A line or sentence that only greets: "Hi there,", "Good morning team!", "Dear Sir or Madam,", "To whom it may concern:". */
22651
- function isGreeting(sentence) {
22652
- const salutation = SALUTATION.exec(sentence);
22653
- return salutation ? ADDRESS.test(sentence.slice(salutation[0].length)) : TO_WHOM.test(sentence);
22654
- }
22655
- /**
22656
- * The subject a support issue prefills: its first line or sentence that holds
22657
- * a word and says more than a greeting (its first one when none does),
22658
- * shortened at a word boundary with an ellipsis to fit MAX_SUBJECT_LEN. The
22659
- * message carries the whole issue, so the subject only needs to name it.
22660
- */
22661
- function issueSubject(issue) {
22662
- const sentences = issue.replace(SENTENCE_END, (match, end) => end ? `${end}\n` : match)
22663
- .split('\n').map((sentence) => sentence.trim()).filter(Boolean);
22664
- const subject = sentences.find((sentence) => LETTER.test(sentence) && !isGreeting(sentence)) ?? sentences[0] ?? '';
22665
- if (subject.length <= MAX_SUBJECT_LEN)
22666
- return subject;
22667
- const kept = truncateToLength(subject, MAX_SUBJECT_LEN - 1);
22668
- const atWord = /\s/u.test(subject.charAt(kept.length)) ? kept : kept.replace(/\s+\S*$/u, '');
22669
- return `${atWord.trimEnd()}…`;
22670
- }
22671
-
22672
23267
  /** The support journey's only skin. Customer content stays in the product register. */
22673
23268
  function injectHelpDeskSupportStyles() {
22674
23269
  if (document.getElementById('sparkvault-help-desk-support-styles'))
@@ -22794,11 +23389,10 @@ function injectHelpDeskSupportStyles() {
22794
23389
  .svhs-unlock-form{margin:0}
22795
23390
  .svhs-contact-target>.svhd-container{display:flex;flex:1;flex-direction:column;min-height:100%;max-width:none;padding:24px;border:0;border-radius:0;box-shadow:none;background:transparent}
22796
23391
  .svhs-contact-target .svhd-body{display:flex;flex:1;flex-direction:column;min-height:0}
22797
- .svhs-contact-target .svhd-container h2{margin-bottom:12px;font-size:22px;line-height:1.25;letter-spacing:-.6px;overflow-wrap:anywhere}
23392
+ .svhs-contact-target .svhd-container h2{font-size:22px;line-height:1.25;letter-spacing:-.6px;overflow-wrap:anywhere}
22798
23393
  .svhs-contact-target .svhd-form{gap:16px}
22799
23394
  .svhs-contact-target .svhd-label{font-size:13px;line-height:1.5}
22800
23395
  .svhs-contact-target .svhd-input{font-size:16px;line-height:1.5}
22801
- .svhs-contact-target .svhd-description{min-height:138px}
22802
23396
  .svhs-contact-target .svhd-actions{gap:10px}
22803
23397
  .svhs-contact-target .svhd-button:not(.svhd-secondary){background:var(--hd-accent,${DS.action});color:var(--hd-on-accent,${DS.white})}
22804
23398
  .svhs-contact-target .svhd-button:not(.svhd-secondary):hover{background:var(--hd-accent-hover,${DS.actionHover})}
@@ -22806,18 +23400,19 @@ function injectHelpDeskSupportStyles() {
22806
23400
  .svhs-contact-target .svhd-actions>.svhd-button:first-child{flex:1}
22807
23401
  .svhs-contact-target .svhd-status{font-size:14px}
22808
23402
  .svhs-contact-target .svhd-auth{gap:14px}
22809
- .svhs-contact-target .svhd-widget-account{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;min-width:0}
22810
- .svhs-contact-target .svhd-widget-identity{display:flex;flex:1;min-width:0;flex-direction:column;gap:2px;margin:0;line-height:1.4;overflow-wrap:anywhere}
22811
- .svhs-contact-target .svhd-widget-identity strong{color:${DS.slate900};font-size:14px;font-weight:600}
22812
- .svhs-contact-target .svhd-widget-identity span{color:${DS.slate500};font-size:13px}
22813
- .svhs-contact-target .svhd-widget-account-link{display:inline-flex;align-items:center;justify-content:center;min-height:44px;max-width:100%;padding:8px 0;border:0;border-radius:6px;background:transparent;color:var(--hd-accent-ink,${DS.action});font-size:13px;line-height:1.4}
22814
- .svhs-contact-target .svhd-widget-account-link:hover{text-decoration:underline}
22815
- .svhs-contact-target .svhd-widget-account-link:focus-visible{outline:2px solid var(--hd-focus,var(--hd-accent-ink,${DS.action}));outline-offset:3px}
22816
- .svhs-contact-target .svhd-widget-account-link:disabled{cursor:progress;color:${DS.slate500}}
23403
+ .svhs-contact-target .svhd-text-button{color:var(--hd-accent-ink,${DS.action})}
23404
+ .svhs-contact-target .svhd-text-button:disabled{color:${DS.slate500}}
23405
+ .svhs-contact-target .svhd-composer:has(.svhd-composer-input:focus-visible){outline:2px solid var(--hd-focus,var(--hd-accent-ink,${DS.action}));outline-offset:3px}
23406
+ @supports not selector(:has(*)){.svhs-contact-target .svhd-composer:focus-within{outline:2px solid var(--hd-focus,var(--hd-accent-ink,${DS.action}));outline-offset:3px}}
23407
+ .svhs-panel .svhd-composer-input:focus-visible{outline:none}
23408
+ .svhs-panel .svhd-composer button:focus-visible{outline-offset:-2px}
22817
23409
  .svhs-contact-target .svhd-widget-names{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:12px}
22818
23410
  .svhs-contact-target .svhd-widget-form{display:flex;flex:1;flex-direction:column;gap:16px}
22819
- .svhs-contact-target .svhd-widget-message{display:flex;flex:1;flex-direction:column;gap:6px;min-height:164px}
22820
- .svhs-contact-target .svhd-widget-message .svhd-description{flex:1;resize:vertical}
23411
+ /* The request fills the panel: the details step, and in it the composer and its text, take the height the fields leave. */
23412
+ .svhs-contact-target .svhd-widget-form>[data-contact-step=details]{display:flex;flex:1;flex-direction:column;gap:16px}
23413
+ .svhs-contact-target .svhd-widget-form .svhd-composer-field{display:flex;flex:1;flex-direction:column;gap:6px;min-height:164px}
23414
+ .svhs-contact-target .svhd-widget-form .svhd-composer{flex:1}
23415
+ .svhs-contact-target .svhd-widget-form .svhd-composer-input{flex:1;min-height:120px}
22821
23416
  .svhs-contact-target .svhd-widget-form>.svhd-actions{position:sticky;bottom:0;z-index:1;margin:auto -24px 0;padding:16px 24px 0;border-top:1px solid ${DS.slate100};background:${DS.white}}
22822
23417
  .svhs-contact-target .svhd-widget-form>.svhd-actions>.svhd-secondary{display:none}
22823
23418
  .svhs-contact-target .svhd-widget-form .svhd-actions>.svhd-button{font-size:14px}
@@ -22830,7 +23425,6 @@ function injectHelpDeskSupportStyles() {
22830
23425
  .svhs-ticket-link{display:inline-flex;align-items:center;min-height:44px;margin:0 0 10px;color:var(--hd-accent-ink,${DS.action});font-size:14px;font-weight:600;text-decoration:underline}
22831
23426
  .svhs-receipt-note{white-space:pre-wrap;overflow-wrap:anywhere}
22832
23427
  .svhs-receipt-actions{display:flex;flex-direction:column;align-items:center;gap:4px}
22833
- .svhs-live{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
22834
23428
  .svhs-toast{box-sizing:border-box;position:fixed;right:24px;bottom:calc(96px + var(--svhs-toast-offset,0px) + env(safe-area-inset-bottom));z-index:2147482901;display:flex;align-items:center;gap:10px;max-width:calc(100vw - 36px);padding:14px 18px;border:1px solid transparent;border-radius:8px;background:${DS.slate900};color:${DS.white};box-shadow:${DS.shadowPopover};font:400 14px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',sans-serif;overflow-wrap:anywhere}
22835
23429
  .svhs-toast svg{width:18px;height:18px;flex:none;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
22836
23430
  .svhs-overlay{position:fixed;inset:0;z-index:2147482900;display:flex;background:${DS.white};padding:0;overflow:hidden}
@@ -22865,7 +23459,6 @@ function injectHelpDeskSupportStyles() {
22865
23459
  .svhs-feedback-actions{margin-top:30px}
22866
23460
  .svhs-feedback-actions .svhs-primary,.svhs-feedback-actions .svhs-secondary{min-height:48px}
22867
23461
  .svhs-contact-scroll{padding:0}
22868
- .svhs-contact-target .svhd-description{min-height:160px}
22869
23462
  .svhs-contact-target>.svhd-container{padding:24px}
22870
23463
  .svhs-contact-target .svhd-widget-form>.svhd-actions{padding-bottom:env(safe-area-inset-bottom)}
22871
23464
  .svhs-receipt-scroll{padding-top:58px}
@@ -23231,24 +23824,6 @@ function button(className, text, action) {
23231
23824
  node.addEventListener('click', action);
23232
23825
  return node;
23233
23826
  }
23234
- function icon(name) {
23235
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
23236
- svg.setAttribute('viewBox', '0 0 24 24');
23237
- svg.setAttribute('aria-hidden', 'true');
23238
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
23239
- path.setAttribute('d', {
23240
- back: 'm14.5 6-6 6 6 6',
23241
- close: 'm6 6 12 12M18 6 6 18',
23242
- external: 'M14 4h6v6m0-6L10 14M11 5H5a1 1 0 0 0-1 1v13a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1v-6',
23243
- check: 'm5 12 4 4L19 6',
23244
- article: 'M14 3H6a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8Zm0 0v5h5M8 12h8M8 16h6',
23245
- chevron: 'm9 6 6 6-6 6',
23246
- thumbUp: 'M7 10v11H3V10Zm0 1 5-8c2 0 3 1 2 4l-1 3h6a2 2 0 0 1 2 2l-2 7a2 2 0 0 1-2 2H7',
23247
- thumbDown: 'M7 14V3H3v11Zm0-1 5 8c2 0 3-1 2-4l-1-3h6a2 2 0 0 0 2-2l-2-7a2 2 0 0 0-2-2H7',
23248
- }[name]);
23249
- svg.append(path);
23250
- return svg;
23251
- }
23252
23827
  function httpUrl(value, base = window.location.href) {
23253
23828
  if (!value)
23254
23829
  return null;
@@ -23307,7 +23882,6 @@ class SupportView {
23307
23882
  this.receiptCopy = element('p', 'svhs-copy');
23308
23883
  this.receiptTicket = element('a', 'svhs-ticket-link');
23309
23884
  this.receiptMessage = element('p', 'svhs-copy svhs-receipt-note');
23310
- this.live = element('div', 'svhs-live');
23311
23885
  this.identityNotice = element('div', 'svhs-identity-notice');
23312
23886
  this.onMediaChange = () => this.syncPresentation();
23313
23887
  this.onViewportChange = () => this.syncViewport();
@@ -23320,6 +23894,24 @@ class SupportView {
23320
23894
  this.ticketGateSignature = '';
23321
23895
  this.toastCleanups = new Set();
23322
23896
  this.destroyed = false;
23897
+ // A multi-click that began before the screen changed (the panel opening, a
23898
+ // new stage or article, a new contact form, its step, or its request and
23899
+ // actions changing in place), wherever its first press
23900
+ // was, lands its later presses on a screen the customer has not seen yet:
23901
+ // they neither take focus there nor reach what is under them. A press in the
23902
+ // panel that starts anew, or a key press, acts as usual.
23903
+ this.screenChanges = 0;
23904
+ this.pressedAt = 0;
23905
+ this.onPress = (event) => {
23906
+ if (event.detail <= 1) {
23907
+ this.pressedAt = this.screenChanges;
23908
+ return;
23909
+ }
23910
+ if (this.screenChanges === this.pressedAt)
23911
+ return;
23912
+ event.preventDefault();
23913
+ event.stopPropagation();
23914
+ };
23323
23915
  injectHelpDeskSupportStyles();
23324
23916
  this.phoneHistory = !target && actions.onBrowserBack && actions.onBrowserForward ? new SupportPhoneHistory({
23325
23917
  onBack: () => this.actions.onBrowserBack?.(),
@@ -23332,20 +23924,20 @@ class SupportView {
23332
23924
  this.panel.hidden = true;
23333
23925
  this.panel.setAttribute('aria-labelledby', `${this.prefix}-name`);
23334
23926
  this.deskName.id = `${this.prefix}-name`;
23335
- this.live.setAttribute('role', 'status');
23336
- this.live.setAttribute('aria-live', 'polite');
23927
+ this.panel.addEventListener('mousedown', this.onPress, true);
23928
+ this.panel.addEventListener('click', this.onPress, true);
23337
23929
  const toolbar = element('header', 'svhs-toolbar');
23338
23930
  this.toolbar = toolbar;
23339
23931
  this.back = button('svhs-back', 'Back', () => this.actions.onBack());
23340
- this.back.prepend(icon('back'));
23932
+ this.back.prepend(helpDeskIcon('back'));
23341
23933
  this.close = button('svhs-icon-button', '', () => this.actions.onClose());
23342
23934
  this.close.setAttribute('aria-label', 'Close support');
23343
- this.close.append(icon('close'));
23935
+ this.close.append(helpDeskIcon('close'));
23344
23936
  this.external.setAttribute('aria-label', 'Open article in a new tab');
23345
23937
  this.external.title = 'Open article in a new tab';
23346
23938
  this.external.target = '_blank';
23347
23939
  this.external.rel = 'noopener noreferrer';
23348
- this.external.append(icon('external'));
23940
+ this.external.append(helpDeskIcon('external'));
23349
23941
  const toolbarActions = element('div', 'svhs-toolbar-actions');
23350
23942
  toolbarActions.append(this.external);
23351
23943
  if (!target)
@@ -23419,9 +24011,9 @@ class SupportView {
23419
24011
  const readerActions = element('div', 'svhs-reader-actions');
23420
24012
  const yes = button('svhs-primary', 'Yes', () => { if (this.state?.article && !this.state.busy && !this.state.error)
23421
24013
  this.actions.onAnswered(); });
23422
- yes.prepend(icon('thumbUp'));
24014
+ yes.prepend(helpDeskIcon('thumbUp'));
23423
24015
  const no = button('svhs-text-button', 'No, create a ticket', () => this.actions.onContact('article_not_answered'));
23424
- no.prepend(icon('thumbDown'));
24016
+ no.prepend(helpDeskIcon('thumbDown'));
23425
24017
  readerActions.append(yes, no);
23426
24018
  this.articleFooter.append(element('span', 'svhs-article-question', 'Did this resolve your question?'), readerActions);
23427
24019
  this.screens.get('article').append(this.articleFooter);
@@ -23463,7 +24055,7 @@ class SupportView {
23463
24055
  contact.append(this.contactTarget);
23464
24056
  const receipt = this.screen('receipt', 'Message sent');
23465
24057
  receipt.classList.add('svhs-receipt-scroll');
23466
- const receiptMark = icon('check');
24058
+ const receiptMark = helpDeskIcon('check');
23467
24059
  receiptMark.classList.add('svhs-receipt-mark');
23468
24060
  receipt.prepend(receiptMark);
23469
24061
  this.receiptTicket.target = '_blank';
@@ -23474,7 +24066,6 @@ class SupportView {
23474
24066
  if (!target)
23475
24067
  receiptFooter.append(button('svhs-secondary svhs-full', 'Done', () => this.actions.onClose()));
23476
24068
  receiptFooter.append(this.restart);
23477
- this.panel.append(this.live);
23478
24069
  this.media = typeof window.matchMedia === 'function' ? window.matchMedia('(max-width:640px)') : null;
23479
24070
  if (!target) {
23480
24071
  this.media?.addEventListener('change', this.onMediaChange);
@@ -23563,24 +24154,34 @@ class SupportView {
23563
24154
  if (!next.visible)
23564
24155
  return;
23565
24156
  if (!previous?.visible || previous.stage !== next.stage || previous.article?.id !== next.article?.id) {
24157
+ // A new screen, however it opened: from a press in the panel, the
24158
+ // launcher or a host link.
24159
+ this.screenChanges += 1;
23566
24160
  this.restoreScroll(next);
23567
24161
  this.focusCurrent();
23568
24162
  }
23569
24163
  }
24164
+ /** A new contact form, or one whose controls changed in place: a change of screen, as a new stage is. */
24165
+ contactScreenChanged() {
24166
+ this.screenChanges += 1;
24167
+ }
23570
24168
  /** Programmatic close invalidates Forward restoration even after neutral Back. */
23571
24169
  deactivateHistory() {
23572
24170
  this.phoneHistory?.deactivate();
23573
24171
  }
23574
- /** Focus the shared form after its controller has mounted it. */
24172
+ /** Focus the shared form where the customer goes on, else its heading, after its controller has mounted it. */
23575
24173
  focusContact() {
23576
24174
  if (this.destroyed || !this.state?.visible || this.state.stage !== 'contact')
23577
24175
  return;
23578
24176
  const heading = this.contactTarget.querySelector('h1,h2,h3');
23579
24177
  this.contactTitle.hidden = Boolean(heading);
23580
24178
  this.contactTitle.parentElement.hidden = this.contactTitle.hidden && this.contactStatus.hidden && this.contactError.hidden && this.sourceArticle.hidden;
24179
+ const focusOptions = { preventScroll: !this.target };
24180
+ if (!this.contactTarget.hidden && this.actions.onFocusContact?.(focusOptions))
24181
+ return;
23581
24182
  const target = heading ?? this.contactTarget;
23582
24183
  target.tabIndex = -1;
23583
- target.focus({ preventScroll: !this.target });
24184
+ target.focus(focusOptions);
23584
24185
  }
23585
24186
  /** Hydrate only the current reader's matching authorized publication assets. */
23586
24187
  setArticleAsset(path, blobUrl) {
@@ -23631,7 +24232,7 @@ class SupportView {
23631
24232
  const toast = element('div', 'svhs-toast');
23632
24233
  toast.setAttribute('role', 'status');
23633
24234
  toast.setAttribute('aria-atomic', 'true');
23634
- toast.append(icon('check'), document.createTextNode(message));
24235
+ toast.append(helpDeskIcon('check'), document.createTextNode(message));
23635
24236
  document.body.append(toast);
23636
24237
  const arrange = () => {
23637
24238
  let offset = 0;
@@ -23682,6 +24283,8 @@ class SupportView {
23682
24283
  return;
23683
24284
  this.destroyed = true;
23684
24285
  this.phoneHistory?.destroy();
24286
+ this.panel.removeEventListener('mousedown', this.onPress, true);
24287
+ this.panel.removeEventListener('click', this.onPress, true);
23685
24288
  document.removeEventListener('keydown', this.onKeydown);
23686
24289
  this.media?.removeEventListener('change', this.onMediaChange);
23687
24290
  window.visualViewport?.removeEventListener('resize', this.onViewportChange);
@@ -23752,9 +24355,9 @@ class SupportView {
23752
24355
  copy.append(element('span', 'svhs-result-excerpt', result.summary));
23753
24356
  if (result.category)
23754
24357
  copy.append(element('span', 'svhs-result-category', result.category));
23755
- const documentIcon = icon('article');
24358
+ const documentIcon = helpDeskIcon('article');
23756
24359
  documentIcon.classList.add('svhs-result-icon');
23757
- const chevron = icon('chevron');
24360
+ const chevron = helpDeskIcon('chevron');
23758
24361
  chevron.classList.add('svhs-result-chevron');
23759
24362
  open.append(documentIcon, copy, chevron);
23760
24363
  item.append(open);
@@ -24126,8 +24729,6 @@ class SupportView {
24126
24729
  }
24127
24730
  }
24128
24731
 
24129
- /** What contact starts from: the issue's subject and, as the message, every character of the issue. */
24130
- function composeIssue(issue) { return { subject: issueSubject(issue), body: issue }; }
24131
24732
  function notify(callback, value) {
24132
24733
  try {
24133
24734
  void Promise.resolve(callback?.(value)).catch(() => undefined);
@@ -24153,10 +24754,14 @@ function createHelpDeskSupport(config, options) {
24153
24754
  // only while it is the current sequence, so whatever supersedes it frees it.
24154
24755
  let contactOpening = null;
24155
24756
  let pendingComposition = null;
24156
- // The issue, trimmed, that the held composition (the mounted form, or the one
24157
- // a re-authorized form will take) was last filled from: '' for one filled from
24158
- // none. A re-authorized form is filled from it too, so the text it carries is
24159
- // the customer's own, or not, as it was in the form it came from.
24757
+ // A website-account customer's saved request the next form keeps hidden,
24758
+ // asked for through the website account, which may give no account back.
24759
+ let pendingRecovery = null;
24760
+ // The issue, as written, that the held composition (the mounted form, the one
24761
+ // a re-authorized form will take, or the one saved before a reload) was last
24762
+ // filled from: '' for one filled from none. A form taking that composition is
24763
+ // filled from it too, so the text it carries is the customer's own, or not,
24764
+ // as it was in the form it came from.
24160
24765
  let composedFrom = '';
24161
24766
  let nativeIdentity = null;
24162
24767
  let switchedAccount = false;
@@ -24190,6 +24795,9 @@ function createHelpDeskSupport(config, options) {
24190
24795
  onBack: () => {
24191
24796
  if (destroyed || state.navigationLocked || state.identityPending)
24192
24797
  return;
24798
+ // On who the reply goes to, Back returns to the request it is for.
24799
+ if (state.stage === 'contact' && !state.ticketAccessRequired && contact?.returnToRequest())
24800
+ return;
24193
24801
  // A held form shows at once while contact still checks access behind it,
24194
24802
  // so a contact opening in flight is cancelled even when nothing is busy.
24195
24803
  if (state.busy || contactOpening === sequence)
@@ -24236,6 +24844,7 @@ function createHelpDeskSupport(config, options) {
24236
24844
  onUnlock: (password) => { void unlock(password); },
24237
24845
  onUnlockTicketAccess: (password) => { void unlockTicketAccess(password); },
24238
24846
  onCancelIdentity: () => nativeIdentity?.abort(),
24847
+ onFocusContact: (focusOptions) => contact?.focusEntry(focusOptions) ?? false,
24239
24848
  onBrowserBack: minimize,
24240
24849
  onBrowserForward: () => update({ visible: true }),
24241
24850
  }, options.target === undefined ? undefined : resolveTarget(options.target));
@@ -24315,7 +24924,7 @@ function createHelpDeskSupport(config, options) {
24315
24924
  const saved = readFormDraft(active.desk.desk_id, customer.requester_id);
24316
24925
  const composition = readAnonymousFormDraft(active.desk.desk_id);
24317
24926
  if ((saved || composition) && !state.issue) {
24318
- update({ issue: saved?.body ?? readSupportIssue(active.desk.desk_id) ?? '' });
24927
+ update({ issue: saved ? ticketBody(saved.subject, saved.body) : readSupportIssue(active.desk.desk_id) ?? '' });
24319
24928
  await showContact('direct');
24320
24929
  }
24321
24930
  else if (!state.issue)
@@ -24394,6 +25003,7 @@ function createHelpDeskSupport(config, options) {
24394
25003
  results = [];
24395
25004
  requestedArticle = null;
24396
25005
  pendingComposition = null;
25006
+ pendingRecovery = null;
24397
25007
  feedbackSequence += 1;
24398
25008
  sourceArticleId = undefined;
24399
25009
  if (options.persist && client)
@@ -24554,18 +25164,28 @@ function createHelpDeskSupport(config, options) {
24554
25164
  notify(options.onError, error);
24555
25165
  }
24556
25166
  }
24557
- function mountContact(composition, customer) {
25167
+ /** Mount the contact form filled from `composedFrom`, then put a composition carried from an earlier form in it. */
25168
+ function mountContact(carried, customer) {
24558
25169
  if (!client || destroyed)
24559
25170
  return;
24560
25171
  contactCustomer = customer;
25172
+ // A customer the website gave back sees their own saved request; none keeps it hidden.
25173
+ const recovering = customer ? null : pendingRecovery;
25174
+ pendingRecovery = null;
24561
25175
  let activeAttempt = null;
25176
+ // A ticket carries the attempt the form opened under only while it is still
25177
+ // the journey's: recovery drops it with the previous customer's question.
25178
+ const formAttempt = attempt;
25179
+ const bridged = Boolean(options.getSessionToken || options.getIdentityAssertion || options.identityEndpoint);
24562
25180
  contact = mountHelpDeskForm(client, {
24563
25181
  target: view.contactTarget,
24564
- // Filled with the issue its composition came from, so text the customer
25182
+ // Filled from the issue its composition came from, so text the customer
24565
25183
  // wrote in an earlier form and carried here stays their own.
24566
- ...composeIssue(composedFrom),
25184
+ issue: composedFrom,
24567
25185
  attachments: options.attachments,
24568
25186
  persist: options.persist,
25187
+ pageLayout: options.target !== undefined,
25188
+ hostShowsAttribution: options.hostShowsAttribution === true,
24569
25189
  onSession: (session) => {
24570
25190
  anonymous = false;
24571
25191
  if (options.persist)
@@ -24576,9 +25196,14 @@ function createHelpDeskSupport(config, options) {
24576
25196
  customer,
24577
25197
  signIn: (input) => signIn(input).then((session) => { contactCustomer = session.customer; return session; }),
24578
25198
  switchAccount: (safe) => { void switchAccount(safe); },
24579
- ...(switchedAccount && (options.getSessionToken || options.getIdentityAssertion || options.identityEndpoint) ? { useWebsiteAccount: (safe) => { void useWebsiteAccount(safe); } } : {}),
25199
+ ...(bridged && { useWebsiteAccount: (safe, recover) => { void useWebsiteAccount(safe, recover); } }),
25200
+ offerWebsiteAccount: switchedAccount,
25201
+ forgetIssue,
25202
+ followIssue,
25203
+ ...(recovering && { recovering }),
24580
25204
  },
24581
- assistanceContext: () => activeAttempt?.ticketContext(),
25205
+ onScreenChange: () => view.contactScreenChanged(),
25206
+ assistanceContext: () => (attempt === formAttempt ? activeAttempt?.ticketContext() : undefined),
24582
25207
  sourceArticleId: () => sourceArticleId,
24583
25208
  onError: (error) => {
24584
25209
  notify(options.onError, error);
@@ -24597,11 +25222,14 @@ function createHelpDeskSupport(config, options) {
24597
25222
  onSuccess: (ticket) => receipt(ticket),
24598
25223
  onStateChange: (next) => update({ navigationLocked: ['authenticating', 'submitting', 'uncertain'].includes(next) }),
24599
25224
  });
24600
- contact.restoreComposition(composition);
24601
- // A composition carried across re-authorization was filled from the issue as it read then.
25225
+ // A form in place of another can put a different control under the pointer.
25226
+ view.contactScreenChanged();
25227
+ if (carried)
25228
+ contact.restoreComposition(carried);
25229
+ // A carried composition was filled from the issue as it read then.
24602
25230
  followIssue();
24603
25231
  const activeForm = contact;
24604
- void attempt?.then((active) => {
25232
+ void formAttempt?.then((active) => {
24605
25233
  // Keep the mutable callback small: an analytics response arriving late
24606
25234
  // must not delay contact, authentication or ticket submission.
24607
25235
  if (contact === activeForm && active)
@@ -24617,10 +25245,30 @@ function createHelpDeskSupport(config, options) {
24617
25245
  */
24618
25246
  function followIssue() {
24619
25247
  const issue = state.issue.trim();
24620
- if (!contact || !issue || issue === composedFrom)
25248
+ if (!contact || !issue || issue === composedFrom.trim())
24621
25249
  return;
24622
- if (contact.refill(composeIssue(state.issue)))
24623
- composedFrom = issue;
25250
+ if (contact.refill(state.issue))
25251
+ composedFrom = state.issue;
25252
+ }
25253
+ /**
25254
+ * Forget the question of a customer whose request just left the contact
25255
+ * form: it, and the answers and article it led to, are theirs, in view and
25256
+ * in this tab's storage. The visitor is unknown again until one signs in,
25257
+ * so the tab keeps their next question as any signed-out visitor's.
25258
+ */
25259
+ function forgetIssue() {
25260
+ cancelArticleAssets?.();
25261
+ cancelArticleAssets = null;
25262
+ kbConfig = null;
25263
+ results = [];
25264
+ requestedArticle = null;
25265
+ attempt = null;
25266
+ sourceArticleId = undefined;
25267
+ composedFrom = '';
25268
+ anonymous = true;
25269
+ if (options.persist && client)
25270
+ clearSupportIssue(client.desk.desk_id);
25271
+ update({ issue: '', results: [], article: undefined, articleUrl: undefined, kbState: undefined, sourceArticle: undefined });
24624
25272
  }
24625
25273
  async function showContact(reason) {
24626
25274
  if (destroyed || contactOpening === sequence)
@@ -24667,12 +25315,16 @@ function createHelpDeskSupport(config, options) {
24667
25315
  return;
24668
25316
  update({ busy: false, ticketAccessRequired: false, ticketAccessMode: undefined });
24669
25317
  anonymous = !customer;
24670
- const composition = pendingComposition ?? (options.persist ? readAnonymousFormDraft(active.desk.desk_id) : null) ?? composeIssue(state.issue);
25318
+ // A composition saved before a reload goes on from the issue it was filled
25319
+ // from; with none carried, the form fills itself from the issue as written.
25320
+ const saved = pendingComposition === null && options.persist ? readAnonymousFormDraft(active.desk.desk_id) : null;
25321
+ if (saved)
25322
+ composedFrom = saved.composedFrom;
25323
+ else if (pendingComposition === null)
25324
+ composedFrom = state.issue;
24671
25325
  if (customer && options.persist)
24672
25326
  clearSupportIssue(active.desk.desk_id);
24673
- if (!pendingComposition)
24674
- composedFrom = state.issue.trim();
24675
- mountContact(composition, customer);
25327
+ mountContact(pendingComposition ?? saved, customer);
24676
25328
  pendingComposition = null;
24677
25329
  }
24678
25330
  catch (value) {
@@ -24736,6 +25388,7 @@ function createHelpDeskSupport(config, options) {
24736
25388
  cancelArticleAssets?.();
24737
25389
  cancelArticleAssets = null;
24738
25390
  pendingComposition = composition ?? { subject: '', body: '' };
25391
+ pendingRecovery = null;
24739
25392
  kb?.clearAccess();
24740
25393
  kbConfig = null;
24741
25394
  results = [];
@@ -24775,7 +25428,7 @@ function createHelpDeskSupport(config, options) {
24775
25428
  await showContact('direct');
24776
25429
  }
24777
25430
  }
24778
- async function useWebsiteAccount(composition) {
25431
+ async function useWebsiteAccount(composition, recovering = false) {
24779
25432
  if (!client || destroyed || state.navigationLocked)
24780
25433
  return;
24781
25434
  const ownSequence = ++sequence;
@@ -24784,6 +25437,7 @@ function createHelpDeskSupport(config, options) {
24784
25437
  cancelArticleAssets?.();
24785
25438
  cancelArticleAssets = null;
24786
25439
  pendingComposition = composition ?? { subject: '', body: '' };
25440
+ pendingRecovery = recovering ? { websiteSignedOut: true } : null;
24787
25441
  kb?.clearAccess();
24788
25442
  kbConfig = null;
24789
25443
  results = [];
@@ -24804,6 +25458,9 @@ function createHelpDeskSupport(config, options) {
24804
25458
  return;
24805
25459
  const error = failure(value);
24806
25460
  update({ busy: false, error: error.message });
25461
+ // The website was not reached, so it is not known to have no account.
25462
+ if (pendingRecovery)
25463
+ pendingRecovery = { websiteSignedOut: false };
24807
25464
  if (client.hasTicketAccess) {
24808
25465
  mountContact(composition ?? { subject: '', body: '' }, null);
24809
25466
  pendingComposition = null;
@@ -29618,7 +30275,7 @@ class SparkVault {
29618
30275
  }
29619
30276
  /** Get the SDK version */
29620
30277
  static get version() {
29621
- return '16.4.1';
30278
+ return '16.5.1';
29622
30279
  }
29623
30280
  }
29624
30281
  if (typeof window !== 'undefined') {