@sparkvault/sdk-js 16.4.1 → 16.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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)
7601
+ if (!body || this.statusRegion?.element.isConnected)
7592
7602
  return;
7593
- if (!words) {
7594
- region.textContent = '';
7595
- 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) {
@@ -18239,16 +18244,16 @@ function injectHelpDeskFormStyles() {
18239
18244
  .svhd-modal .svhd-container{max-width:none;border:0;border-radius:0;padding-top:8px}
18240
18245
  .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
18246
  .svhd-container *{box-sizing:border-box}
18242
- .svhd-container h2{font-size:22px;line-height:1.25;margin:0 0 20px}
18247
+ .svhd-container h2{font-size:22px;line-height:1.25;margin:0}
18248
+ .svhd-step-head h2:focus{outline:none}
18243
18249
  .svhd-form{display:grid;gap:16px}
18244
18250
  .svhd-field{display:grid;gap:6px}
18245
18251
  .svhd-label{font-weight:600}
18246
18252
  .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
18253
  .svhd-input:focus-visible,.svhd-button:focus-visible,.svhd-link:focus-visible{outline:3px solid ${DS.action};outline-offset:2px}
18248
18254
  .svhd-input:disabled{background:${DS.slate50}}
18249
- .svhd-description{min-height:140px;resize:vertical}
18250
18255
  .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}
18256
+ .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
18257
  .svhd-actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
18253
18258
  .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
18259
  .svhd-button:hover{background:${DS.actionHover}}
@@ -18266,14 +18271,53 @@ function injectHelpDeskFormStyles() {
18266
18271
  .svhd-done-title:focus{outline:none}
18267
18272
  .svhd-confirmation-message{white-space:pre-wrap;overflow-wrap:anywhere}
18268
18273
  .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}
18274
+ .svhd-hint{font-size:13px;color:${DS.slate600};margin:0}
18275
+ .svhd-step{display:grid;gap:16px;min-width:0}
18276
+ .svhd-step-head{display:grid;gap:4px;margin-bottom:4px}
18277
+ .svhd-step-label{margin:0;font-size:13px;font-weight:600;line-height:1.4;color:${DS.slate600}}
18278
+ .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}
18279
+ .svhd-text-button:hover{color:${DS.actionHover}}
18280
+ .svhd-text-button:focus-visible{outline:3px solid ${DS.action};outline-offset:2px}
18281
+ .svhd-text-button:disabled{color:${DS.slate500};cursor:default}
18282
+ .svhd-widget-account{display:flex;align-items:center;flex-wrap:wrap;gap:0 16px;min-width:0}
18283
+ .svhd-posting-as{margin:0;color:${DS.slate600};font-size:14px;line-height:1.5;overflow-wrap:anywhere}
18284
+ .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}
18285
+ .svhd-step .svhd-note svg{display:block;width:18px;height:18px;flex:none;margin-top:2px;color:${DS.action}}
18286
+ .svhd-recap{display:flex;align-items:center;gap:12px;padding:6px 6px 6px 14px;border:1px solid ${DS.slate200};border-radius:8px}
18287
+ .svhd-recap-request{flex:1;min-width:0}
18288
+ .svhd-recap-label{display:block;color:${DS.slate600};font-size:12px;font-weight:600;line-height:1.4}
18289
+ .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}
18290
+ .svhd-recap .svhd-text-button{flex:none}
18291
+ /* The frame is the field: its ring shows wherever focus is inside it, and the text inside draws none of its own. */
18292
+ .svhd-composer{position:relative;display:flex;flex-direction:column;min-width:0;border:1px solid ${DS.slate300};border-radius:6px;background:${DS.white}}
18293
+ .svhd-composer:has(.svhd-composer-input:focus-visible){outline:3px solid ${DS.action};outline-offset:2px}
18294
+ @supports not selector(:has(*)){.svhd-composer:focus-within{outline:3px solid ${DS.action};outline-offset:2px}}
18295
+ .svhd-composer-dragging{border-style:dashed;border-color:${DS.action}}
18296
+ .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}
18297
+ .svhd-composer-input:focus,.svhd-composer-input:focus-visible{outline:none}
18298
+ .svhd-composer-input:disabled{background:${DS.slate50}}
18299
+ .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}
18300
+ .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}}
18301
+ .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}
18302
+ .svhd-composer-attach:hover{background:${DS.slate100};color:${DS.slate900}}
18303
+ .svhd-composer-attach:disabled{opacity:.6;cursor:default}
18304
+ .svhd-composer .svhd-composer-attach svg{display:block;width:18px;height:18px}
18305
+ .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}}
18306
+ .svhd-composer-notice{margin:0;font-size:14px}
18307
+ .svhd-attachment-chips{display:flex;flex-wrap:wrap;gap:8px;list-style:none;margin:0;padding:8px;border-top:1px solid ${DS.slate200}}
18308
+ .svhd-attachment-chips:empty{display:none}
18309
+ .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}
18310
+ .svhd-attachment-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:600;color:${DS.slate900}}
18311
+ .svhd-attachment-status{grid-column:1;padding-right:8px;color:${DS.slate600};font-size:12px;overflow-wrap:anywhere}
18312
+ .svhd-attachment-status.svhd-error{color:${DS.error}}
18313
+ .svhd-attachment-progress{grid-column:1/-1;width:calc(100% - 10px);height:6px;margin-top:6px;accent-color:${DS.action}}
18314
+ .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}
18315
+ .svhd-attachment-remove:hover{background:${DS.slate200};color:${DS.slate900}}
18316
+ .svhd-attachment-chip .svhd-attachment-remove svg{display:block;width:16px;height:16px}
18317
+ .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}
18318
+ .svhd-composer button:focus-visible{outline:3px solid ${DS.action};outline-offset:-3px}
18319
+ .svhd-attachment-remove:disabled,.svhd-attachment-retry:disabled{opacity:.6;cursor:default}
18320
+ .svhd-live{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
18277
18321
  .svhd-footer{margin-top:20px;font-size:12px;color:${DS.slate500}}
18278
18322
  `;
18279
18323
  document.head.appendChild(style);
@@ -18477,23 +18521,6 @@ function lastExtension(name) {
18477
18521
  return shownExtension(closeUpSpaces(name));
18478
18522
  }
18479
18523
 
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
18524
  /**
18498
18525
  * What a help-desk attachment may be named and what its first bytes may not
18499
18526
  * be: the one list of the files a ticket accepts, beside the one list of
@@ -18792,6 +18819,15 @@ const ACCEPTED_ATTACHMENTS_COPY = acceptedKindsCopy(ACCEPTED_ATTACHMENT_KINDS);
18792
18819
  const CUSTOMER_ATTACHMENTS_HINT =
18793
18820
  `Add screenshots, documents or recordings. Up to ${MAX_ATTACHMENTS_PER_MESSAGE} files, ${formatBytes(CUSTOMER_ATTACHMENT_MAX_BYTES)} each.`;
18794
18821
 
18822
+ /**
18823
+ * What a customer reads at a desk that takes no files from its customers
18824
+ * (the desk lookup's `customer_can_attach_files` is false, the upload refusal
18825
+ * CUSTOMER_UPLOAD_REFUSALS.UPLOADS_OFF): the portal's refusal and its note on
18826
+ * the files an email left out, and the SDK's support form refusing a file
18827
+ * dropped, pasted or uploaded there.
18828
+ */
18829
+ const NO_CUSTOMER_FILES_COPY = "This help desk doesn't take files from customers.";
18830
+
18795
18831
  /**
18796
18832
  * A file input's `accept`: every extension a ticket accepts
18797
18833
  * (ACCEPTED_ATTACHMENT_EXTENSIONS), each with its dot, so the system's file
@@ -18839,7 +18875,56 @@ function refusalCopy(refusal, maxBytes) {
18839
18875
  return REFUSAL_COPY[refusal] ?? "This file can't be attached.";
18840
18876
  }
18841
18877
 
18842
- function createProgress() { return document.createElement('progress'); }
18878
+ /**
18879
+ * The help desk's bare outline glyphs, shared by the support wizard and the
18880
+ * ticket form: stroked in `currentColor`, so the stylesheet that sizes them
18881
+ * also colors them, and hidden from assistive technology, since the control
18882
+ * that holds one names it.
18883
+ */
18884
+ const PATHS = {
18885
+ back: 'm14.5 6-6 6 6 6',
18886
+ close: 'm6 6 12 12M18 6 6 18',
18887
+ 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',
18888
+ check: 'm5 12 4 4L19 6',
18889
+ article: 'M14 3H6a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8Zm0 0v5h5M8 12h8M8 16h6',
18890
+ chevron: 'm9 6 6 6-6 6',
18891
+ 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',
18892
+ 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',
18893
+ 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',
18894
+ info: 'M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Zm0-10v5m0-8h.01',
18895
+ };
18896
+ function helpDeskIcon(name) {
18897
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
18898
+ svg.setAttribute('viewBox', '0 0 24 24');
18899
+ svg.setAttribute('aria-hidden', 'true');
18900
+ svg.setAttribute('focusable', 'false');
18901
+ svg.setAttribute('fill', 'none');
18902
+ svg.setAttribute('stroke', 'currentColor');
18903
+ svg.setAttribute('stroke-width', '1.7');
18904
+ svg.setAttribute('stroke-linecap', 'round');
18905
+ svg.setAttribute('stroke-linejoin', 'round');
18906
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
18907
+ path.setAttribute('d', PATHS[name]);
18908
+ svg.append(path);
18909
+ return svg;
18910
+ }
18911
+
18912
+ /** A refusal of files read under the composer, hidden until there is one. */
18913
+ function createNotice() {
18914
+ const notice = document.createElement('p');
18915
+ notice.className = 'svhd-composer-notice svhd-error';
18916
+ notice.hidden = true;
18917
+ return notice;
18918
+ }
18919
+ /** Show a notice's refusal, or hide it with null. It is an alert only while it shows, as a field's error is. */
18920
+ function setNotice(notice, text) {
18921
+ notice.textContent = text ?? '';
18922
+ notice.hidden = text === null;
18923
+ if (text === null)
18924
+ notice.removeAttribute('role');
18925
+ else
18926
+ notice.setAttribute('role', 'alert');
18927
+ }
18843
18928
  /** A failed mint's quota/size refusal remains a visible file error, never a silently omitted file. */
18844
18929
  function problem(error) {
18845
18930
  if (error instanceof SparkVaultError) {
@@ -18851,7 +18936,7 @@ function problem(error) {
18851
18936
  }
18852
18937
  if (error.statusCode === 402) {
18853
18938
  const reason = error.details?.reason;
18854
- return { copy: reason === CUSTOMER_UPLOAD_REFUSALS.UPLOADS_OFF ? 'This help desk does not accept files.'
18939
+ return { copy: reason === CUSTOMER_UPLOAD_REFUSALS.UPLOADS_OFF ? NO_CUSTOMER_FILES_COPY
18855
18940
  : reason === CUSTOMER_UPLOAD_REFUSALS.ALLOWANCE_REACHED ? 'You have reached this help desk’s upload allowance.'
18856
18941
  : 'This help desk cannot store more files right now.', retryable: false };
18857
18942
  }
@@ -18861,48 +18946,58 @@ function problem(error) {
18861
18946
  }
18862
18947
  return { copy: 'This file could not be uploaded. Try again or remove it.', retryable: true };
18863
18948
  }
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`;
18949
+ /**
18950
+ * The picker owns each file's transfer; it publishes only IDs whose Forge
18951
+ * receipt has confirmed storage. `onEntriesChange` hears each file the
18952
+ * customer adds or removes.
18953
+ */
18954
+ function createFormAttachments(client, prefix, context, onEntriesChange) {
18872
18955
  const input = document.createElement('input');
18873
18956
  input.type = 'file';
18874
18957
  input.name = 'attachments';
18875
- input.id = label.htmlFor;
18876
18958
  input.multiple = true;
18877
18959
  input.accept = ATTACHMENT_INPUT_ACCEPT;
18878
- input.className = 'svhd-input';
18960
+ input.hidden = true;
18961
+ input.tabIndex = -1;
18879
18962
  const hint = document.createElement('p');
18880
18963
  hint.id = `${prefix}-attachment-hint`;
18881
- hint.className = 'svhd-file-hint';
18964
+ hint.className = 'svhd-composer-hint';
18882
18965
  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;
18966
+ const attach = document.createElement('button');
18967
+ attach.type = 'button';
18968
+ attach.className = 'svhd-composer-attach';
18969
+ attach.setAttribute('aria-label', 'Attach files');
18970
+ attach.setAttribute('aria-describedby', hint.id);
18971
+ const attachText = document.createElement('span');
18972
+ attachText.textContent = 'Attach';
18973
+ attach.append(helpDeskIcon('paperclip'), attachText);
18974
+ const toolbar = document.createElement('div');
18975
+ toolbar.className = 'svhd-composer-toolbar';
18976
+ toolbar.append(attach, hint, input);
18977
+ const notice = createNotice();
18888
18978
  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);
18979
+ list.className = 'svhd-attachment-chips';
18980
+ list.setAttribute('aria-label', 'Attached files');
18892
18981
  let entries = [];
18893
18982
  let revision = 0;
18894
18983
  let locked = false;
18895
18984
  let pickingDisabled = false;
18896
18985
  let destroyed = false;
18897
18986
  const current = (entry, ownRevision) => !destroyed && revision === ownRevision && entries.includes(entry) && !entry.controller?.signal.aborted;
18987
+ function syncPicking() {
18988
+ attach.disabled = locked || pickingDisabled;
18989
+ input.disabled = locked || pickingDisabled;
18990
+ }
18898
18991
  function controls(entry) {
18899
18992
  entry.remove.disabled = locked;
18900
18993
  entry.retry.disabled = locked || !!entry.operation;
18901
18994
  }
18902
18995
  function update(entry, state, text) {
18903
18996
  entry.state = state;
18997
+ entry.row.dataset.state = state;
18904
18998
  entry.status.textContent = text;
18905
18999
  entry.status.classList.toggle('svhd-error', state === 'failed');
19000
+ entry.progress.hidden = state !== 'uploading';
18906
19001
  entry.retry.hidden = !(entry.retryable && (state === 'failed' || state === 'received'));
18907
19002
  entry.retry.textContent = state === 'received' ? 'Check upload' : 'Retry';
18908
19003
  entry.retry.setAttribute('aria-label', `${state === 'received' ? 'Check upload' : 'Retry'} ${entry.file.name}`);
@@ -18942,7 +19037,7 @@ function createFormAttachments(client, prefix, context) {
18942
19037
  if (!stillCurrent())
18943
19038
  return;
18944
19039
  if (!owner) {
18945
- update(entry, 'queued', 'Sign in to upload this file.');
19040
+ update(entry, 'queued', 'Uploads when you send your request.');
18946
19041
  return;
18947
19042
  }
18948
19043
  const options = {
@@ -19025,54 +19120,70 @@ function createFormAttachments(client, prefix, context) {
19025
19120
  function remove(entry) {
19026
19121
  if (locked)
19027
19122
  return;
19123
+ // A keyboard removal keeps focus among the files, else on Attach.
19124
+ const refocus = document.activeElement === entry.remove;
19125
+ const index = entries.indexOf(entry);
19028
19126
  entry.controller?.abort();
19029
19127
  entries = entries.filter(candidate => candidate !== entry);
19030
19128
  entry.row.remove();
19031
- notice.hidden = true;
19129
+ setNotice(notice, null);
19032
19130
  void cancel(entry);
19131
+ onEntriesChange();
19132
+ if (refocus)
19133
+ (entries[Math.min(index, entries.length - 1)]?.remove ?? attach).focus();
19033
19134
  }
19034
19135
  function add(files) {
19035
19136
  if (locked || pickingDisabled || destroyed)
19036
19137
  return;
19037
19138
  const incoming = Array.from(files);
19139
+ if (incoming.length === 0)
19140
+ return;
19038
19141
  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.`;
19142
+ setNotice(notice, incoming.length > room ? `You can attach up to ${MAX_ATTACHMENTS_PER_MESSAGE} files. Remove a file before adding another.` : null);
19041
19143
  for (const file of incoming.slice(0, room)) {
19042
19144
  const row = document.createElement('li');
19043
- row.className = 'svhd-file';
19145
+ row.className = 'svhd-attachment-chip';
19044
19146
  const filename = document.createElement('span');
19045
- filename.className = 'svhd-file-name';
19147
+ filename.className = 'svhd-attachment-name';
19046
19148
  filename.textContent = file.name;
19149
+ filename.title = file.name;
19047
19150
  const status = document.createElement('span');
19151
+ status.className = 'svhd-attachment-status';
19048
19152
  status.setAttribute('role', 'status');
19049
19153
  status.setAttribute('aria-live', 'polite');
19050
- const progress = createProgress();
19154
+ const progress = document.createElement('progress');
19155
+ progress.className = 'svhd-attachment-progress';
19051
19156
  progress.max = 100;
19052
19157
  progress.value = 0;
19158
+ progress.hidden = true;
19053
19159
  progress.setAttribute('aria-label', `Upload progress for ${file.name}`);
19054
19160
  const removeButton = document.createElement('button');
19055
19161
  removeButton.type = 'button';
19056
- removeButton.className = 'svhd-button svhd-secondary';
19057
- removeButton.textContent = 'Remove';
19162
+ removeButton.className = 'svhd-attachment-remove';
19058
19163
  removeButton.setAttribute('aria-label', `Remove ${file.name}`);
19164
+ removeButton.append(helpDeskIcon('close'));
19059
19165
  const retry = document.createElement('button');
19060
19166
  retry.type = 'button';
19061
- retry.className = 'svhd-button svhd-secondary';
19167
+ retry.className = 'svhd-attachment-retry';
19062
19168
  retry.hidden = true;
19063
19169
  const entry = { file, row, status, progress, remove: removeButton, retry, state: 'queued', retryable: false };
19064
19170
  removeButton.onclick = () => remove(entry);
19065
19171
  retry.onclick = () => { if (!locked && entry.retryable)
19066
19172
  void run(entry); };
19067
- row.append(filename, status, progress, removeButton, retry);
19173
+ row.append(filename, removeButton, status, retry, progress);
19068
19174
  list.append(row);
19069
19175
  entries.push(entry);
19070
19176
  void run(entry);
19071
19177
  }
19178
+ if (room > 0)
19179
+ onEntriesChange();
19072
19180
  }
19073
19181
  const onChange = () => { if (input.files)
19074
19182
  add(input.files); input.value = ''; };
19183
+ const onAttach = () => { if (!attach.disabled)
19184
+ input.click(); };
19075
19185
  input.addEventListener('change', onChange);
19186
+ attach.addEventListener('click', onAttach);
19076
19187
  function clear(preserveComplete = false) {
19077
19188
  revision += 1;
19078
19189
  const previous = entries;
@@ -19084,17 +19195,20 @@ function createFormAttachments(client, prefix, context) {
19084
19195
  }
19085
19196
  list.replaceChildren();
19086
19197
  input.value = '';
19087
- notice.hidden = true;
19198
+ setNotice(notice, null);
19088
19199
  }
19089
19200
  return {
19090
- element,
19201
+ toolbar,
19202
+ list,
19203
+ notice,
19204
+ get accepting() { return !locked && !pickingDisabled && !destroyed; },
19091
19205
  get attachmentIds() { return entries.filter(entry => entry.state === 'complete' && entry.attachmentId).map(entry => entry.attachmentId); },
19092
19206
  get unresolved() { return entries.some(entry => entry.state !== 'complete'); },
19093
19207
  get hasEntries() { return entries.length > 0; },
19094
- get busy() { return entries.some(entry => !!entry.operation); },
19208
+ add,
19095
19209
  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; },
19210
+ lock(value) { locked = value; syncPicking(); entries.forEach(controls); },
19211
+ disablePicking(value) { pickingDisabled = value; syncPicking(); },
19098
19212
  renewSession(previousToken, nextToken) {
19099
19213
  for (const entry of entries) {
19100
19214
  if (entry.context?.expectedSessionToken === previousToken)
@@ -19102,11 +19216,175 @@ function createFormAttachments(client, prefix, context) {
19102
19216
  }
19103
19217
  },
19104
19218
  clear,
19105
- destroy(preserveComplete = false) { destroyed = true; clear(preserveComplete); input.removeEventListener('change', onChange); },
19219
+ destroy(preserveComplete = false) {
19220
+ destroyed = true;
19221
+ clear(preserveComplete);
19222
+ input.removeEventListener('change', onChange);
19223
+ attach.removeEventListener('click', onAttach);
19224
+ },
19225
+ };
19226
+ }
19227
+
19228
+ const FOLDER_COPY = 'Folders can’t be attached. Add the files inside them instead.';
19229
+ function carriesFiles(event) {
19230
+ return Array.from(event.dataTransfer?.types ?? []).includes('Files');
19231
+ }
19232
+ /**
19233
+ * The details field as a composer. A file pasted into the summary or the
19234
+ * details, or dropped anywhere on the request step, joins the form's one
19235
+ * attachment pipeline (`attachments.add`), under the same limits and
19236
+ * refusals as a picked one; the drop target shows only over the composer. A
19237
+ * paste or drag of text alone stays the browser's. A file brought over the
19238
+ * form is never the browser's to open in place of the unsent request: on the
19239
+ * reply-to step, or while the form takes no files, it is refused outright,
19240
+ * and a desk that takes no files says so when the file is dropped.
19241
+ */
19242
+ function createComposer(options) {
19243
+ const { form, summary, textarea, attachments, deskRefusesFiles, onRequestStep } = options;
19244
+ const frame = document.createElement('div');
19245
+ frame.className = 'svhd-composer';
19246
+ textarea.classList.add('svhd-composer-input');
19247
+ const drop = document.createElement('p');
19248
+ drop.className = 'svhd-composer-drop';
19249
+ drop.textContent = 'Drop the files to attach them.';
19250
+ drop.hidden = true;
19251
+ frame.append(textarea, drop);
19252
+ if (attachments)
19253
+ frame.append(attachments.toolbar, attachments.list);
19254
+ const notice = attachments?.notice ?? createNotice();
19255
+ const fields = [summary, textarea];
19256
+ let pastedImages = 0;
19257
+ function fileAction() {
19258
+ if (!onRequestStep())
19259
+ return 'none';
19260
+ if (attachments)
19261
+ return attachments.accepting ? 'attach' : 'none';
19262
+ return deskRefusesFiles ? 'refuse' : 'none';
19263
+ }
19264
+ function dragging(value) {
19265
+ frame.classList.toggle('svhd-composer-dragging', value);
19266
+ drop.hidden = !value;
19267
+ }
19268
+ function refuseFiles() {
19269
+ if (!notice.hidden && notice.textContent === NO_CUSTOMER_FILES_COPY)
19270
+ return;
19271
+ setNotice(notice, NO_CUSTOMER_FILES_COPY);
19272
+ }
19273
+ // A dropped folder arrives as a file that cannot be read, so it is left out,
19274
+ // and said so beside any refusal the files with it met.
19275
+ function attachDropped(transfer) {
19276
+ const files = [];
19277
+ let folders = 0;
19278
+ for (const item of Array.from(transfer.items)) {
19279
+ if (item.kind !== 'file')
19280
+ continue;
19281
+ if (item.webkitGetAsEntry()?.isDirectory) {
19282
+ folders += 1;
19283
+ continue;
19284
+ }
19285
+ const file = item.getAsFile();
19286
+ if (file)
19287
+ files.push(file);
19288
+ }
19289
+ if (files.length > 0)
19290
+ attachments?.add(files);
19291
+ if (folders > 0)
19292
+ setNotice(notice, files.length > 0 && !notice.hidden ? `${FOLDER_COPY} ${notice.textContent}` : FOLDER_COPY);
19293
+ }
19294
+ // A picture pasted from the clipboard is named "image.png" every time;
19295
+ // numbering the pastes tells their chips, and their Remove buttons, apart.
19296
+ function pastedName(file) {
19297
+ const extension = /^image\.(\w+)$/.exec(file.name)?.[1];
19298
+ if (extension === undefined)
19299
+ return file;
19300
+ pastedImages += 1;
19301
+ return new File([file], `Pasted image ${pastedImages}.${extension}`, { type: file.type, lastModified: file.lastModified });
19302
+ }
19303
+ // Cancelling dragenter and dragover keeps the browser from opening the file
19304
+ // in place of the page. A drop effect of none cancels the drop itself, so a
19305
+ // file the desk refuses keeps one to be refused in words when it lands.
19306
+ const onDragOver = (event) => {
19307
+ if (!carriesFiles(event))
19308
+ return;
19309
+ event.preventDefault();
19310
+ const action = fileAction();
19311
+ if (event.dataTransfer)
19312
+ event.dataTransfer.dropEffect = action === 'none' ? 'none' : 'copy';
19313
+ dragging(action === 'attach' && event.target instanceof Node && frame.contains(event.target));
19314
+ };
19315
+ const onDragLeave = (event) => {
19316
+ if (!(event.relatedTarget instanceof Node) || !frame.contains(event.relatedTarget))
19317
+ dragging(false);
19318
+ };
19319
+ const onDrop = (event) => {
19320
+ if (!carriesFiles(event))
19321
+ return;
19322
+ event.preventDefault();
19323
+ dragging(false);
19324
+ const action = fileAction();
19325
+ if (action === 'attach' && event.dataTransfer)
19326
+ attachDropped(event.dataTransfer);
19327
+ else if (action === 'refuse')
19328
+ refuseFiles();
19329
+ };
19330
+ // A paste that carries files is those files, and the text beside them is
19331
+ // only their names (a file copied in the system's file manager), so none of
19332
+ // it lands in the field. Office apps are the exception: copied cells or
19333
+ // paragraphs come as text and formatted text, with a picture of them as a
19334
+ // file, and that paste is the text.
19335
+ const onPaste = (event) => {
19336
+ const clipboard = event.clipboardData;
19337
+ if (!clipboard || clipboard.files.length === 0)
19338
+ return;
19339
+ if (Array.from(clipboard.types).includes('text/html') && clipboard.getData('text/plain'))
19340
+ return;
19341
+ const action = fileAction();
19342
+ if (action === 'none')
19343
+ return;
19344
+ event.preventDefault();
19345
+ if (action === 'attach')
19346
+ attachments?.add(Array.from(clipboard.files, pastedName));
19347
+ else
19348
+ refuseFiles();
19349
+ };
19350
+ const onInput = () => { if (!attachments)
19351
+ setNotice(notice, null); };
19352
+ form.addEventListener('dragenter', onDragOver);
19353
+ form.addEventListener('dragover', onDragOver);
19354
+ form.addEventListener('dragleave', onDragLeave);
19355
+ form.addEventListener('drop', onDrop);
19356
+ for (const field of fields) {
19357
+ field.addEventListener('paste', onPaste);
19358
+ field.addEventListener('input', onInput);
19359
+ }
19360
+ return {
19361
+ frame,
19362
+ notice,
19363
+ clearNotice: () => setNotice(notice, null),
19364
+ destroy() {
19365
+ form.removeEventListener('dragenter', onDragOver);
19366
+ form.removeEventListener('dragover', onDragOver);
19367
+ form.removeEventListener('dragleave', onDragLeave);
19368
+ form.removeEventListener('drop', onDrop);
19369
+ for (const field of fields) {
19370
+ field.removeEventListener('paste', onPaste);
19371
+ field.removeEventListener('input', onInput);
19372
+ }
19373
+ },
19106
19374
  };
19107
19375
  }
19108
19376
 
19109
19377
  const TTL_MS = 30 * 60 * 1000;
19378
+ /** JSON writes one character of a field as up to six: a control character or lone surrogate becomes an escape like \u0001. */
19379
+ const MAX_ESCAPED_CHAR = 6;
19380
+ /** Room in a row for its keys, ids, timestamps, attachment list and article id. */
19381
+ const ROW_FRAME_CHARS = 8192;
19382
+ /** The longest row a writer can store with these fields, so a reader refuses only rows no writer made. */
19383
+ const maxRowChars = (bodies, subjects) => MAX_ESCAPED_CHAR * (bodies * MAX_BODY_BYTES + subjects * MAX_SUBJECT_LEN) + ROW_FRAME_CHARS;
19384
+ /** The question, the request's subject and description, and the question the request was filled from. */
19385
+ const MAX_ISSUE_ROW_CHARS = maxRowChars(3, 1);
19386
+ /** The request and the uncertain send, each with a subject and description. */
19387
+ const MAX_DRAFT_ROW_CHARS = maxRowChars(2, 2);
19110
19388
  const storageKey = (deskId, requesterId) => isHelpDeskId(deskId) && isResourceIdOf('requester', requesterId) ? `sv-hd-draft:${deskId}:${requesterId}:new` : null;
19111
19389
  const validBody = (value) => typeof value === 'string' && value.length <= MAX_BODY_BYTES && new TextEncoder().encode(value).length <= MAX_BODY_BYTES;
19112
19390
  const validSubject = (value) => typeof value === 'string' && value.length <= MAX_SUBJECT_LEN;
@@ -19127,14 +19405,19 @@ function readSupportDraft(deskId) {
19127
19405
  const raw = sessionStorage.getItem(`sv-hd-issue:${deskId}`);
19128
19406
  if (!raw)
19129
19407
  return null;
19130
- if (raw.length > MAX_BODY_BYTES * 4)
19408
+ if (raw.length > MAX_ISSUE_ROW_CHARS)
19131
19409
  throw new Error('Invalid issue');
19132
19410
  const row = JSON.parse(raw);
19133
19411
  if (row?.desk_id !== deskId || !validBody(row.issue) || !Number.isFinite(row.expires_at) ||
19134
19412
  row.expires_at <= Date.now() || row.expires_at > Date.now() + TTL_MS ||
19135
19413
  (row.composition !== undefined && (!validSubject(row.composition?.subject) || !validBody(row.composition?.body))))
19136
19414
  throw new Error('Invalid issue');
19137
- return { issue: row.issue, ...(row.composition && { composition: { subject: row.composition.subject, body: row.composition.body } }) };
19415
+ if (row.composition === undefined)
19416
+ return { issue: row.issue };
19417
+ // The question a request was filled from only steers refilling it: one that
19418
+ // is not a question, or belongs to no request, is left out, never the row.
19419
+ return { issue: row.issue, composition: { subject: row.composition.subject, body: row.composition.body },
19420
+ ...(validBody(row.composed_from) && { composedFrom: row.composed_from }) };
19138
19421
  }
19139
19422
  catch {
19140
19423
  clearSupportIssue(deskId);
@@ -19142,25 +19425,34 @@ function readSupportDraft(deskId) {
19142
19425
  }
19143
19426
  }
19144
19427
  function readSupportIssue(deskId) { return readSupportDraft(deskId)?.issue ?? null; }
19145
- function readAnonymousFormDraft(deskId) { return readSupportDraft(deskId)?.composition ?? null; }
19146
- function writeSupportDraft(deskId, issue, composition) {
19428
+ function readAnonymousFormDraft(deskId) {
19429
+ const draft = readSupportDraft(deskId);
19430
+ return draft?.composition ? { ...draft.composition, composedFrom: draft.composedFrom ?? '' } : null;
19431
+ }
19432
+ function writeSupportDraft(deskId, draft) {
19147
19433
  try {
19148
- sessionStorage.setItem(`sv-hd-issue:${deskId}`, JSON.stringify({ desk_id: deskId, issue,
19149
- ...(composition && { composition }), expires_at: Date.now() + TTL_MS }));
19434
+ sessionStorage.setItem(`sv-hd-issue:${deskId}`, JSON.stringify({ desk_id: deskId, issue: draft.issue,
19435
+ ...(draft.composition && { composition: draft.composition }), ...(draft.composedFrom !== undefined && { composed_from: draft.composedFrom }),
19436
+ expires_at: Date.now() + TTL_MS }));
19150
19437
  }
19151
19438
  catch { /* The live wizard still keeps its composition in memory. */ }
19152
19439
  }
19153
19440
  function saveSupportIssue(deskId, issue) {
19154
19441
  if (!isHelpDeskId(deskId) || !validBody(issue))
19155
19442
  return;
19156
- const composition = readAnonymousFormDraft(deskId) ?? undefined;
19157
- if (!issue && !composition) {
19443
+ const draft = readSupportDraft(deskId);
19444
+ if (!issue && !draft?.composition) {
19158
19445
  clearSupportIssue(deskId);
19159
19446
  return;
19160
19447
  }
19161
- writeSupportDraft(deskId, issue, composition);
19448
+ writeSupportDraft(deskId, { ...draft, issue });
19162
19449
  }
19163
- function saveAnonymousFormDraft(deskId, composition) {
19450
+ /**
19451
+ * Save a signed-out customer's request beside the tab's question, with the
19452
+ * question it was filled from when the support wizard filled it. A question
19453
+ * too long to keep is left out, so the request reads as the customer's own.
19454
+ */
19455
+ function saveAnonymousFormDraft(deskId, composition, composedFrom) {
19164
19456
  if (!isHelpDeskId(deskId) || !validSubject(composition.subject) || !validBody(composition.body))
19165
19457
  return;
19166
19458
  const issue = readSupportIssue(deskId) ?? '';
@@ -19168,7 +19460,7 @@ function saveAnonymousFormDraft(deskId, composition) {
19168
19460
  clearSupportIssue(deskId);
19169
19461
  return;
19170
19462
  }
19171
- writeSupportDraft(deskId, issue, { subject: composition.subject, body: composition.body });
19463
+ writeSupportDraft(deskId, { issue, composition: { subject: composition.subject, body: composition.body }, ...(validBody(composedFrom) && { composedFrom }) });
19172
19464
  }
19173
19465
  function removeFormDraft(deskId, requesterId) {
19174
19466
  const key = storageKey(deskId, requesterId);
@@ -19186,7 +19478,7 @@ function readFormDraft(deskId, requesterId) {
19186
19478
  const raw = sessionStorage.getItem(key);
19187
19479
  if (!raw)
19188
19480
  return null;
19189
- if (raw.length > MAX_BODY_BYTES * 4)
19481
+ if (raw.length > MAX_DRAFT_ROW_CHARS)
19190
19482
  throw new Error('Invalid draft');
19191
19483
  const row = JSON.parse(raw);
19192
19484
  const sent = row?.uncertain;
@@ -19235,9 +19527,47 @@ function unknownSubmissionOutcome(error) {
19235
19527
  const status = error instanceof SparkVaultError ? error.statusCode : undefined;
19236
19528
  return status === undefined || status < 400 || status === 408 || status >= 500;
19237
19529
  }
19238
- function createDescriptionInput() {
19239
- return document.createElement('textarea');
19530
+ /**
19531
+ * A ticket's body: the details the customer wrote, or, when they wrote none,
19532
+ * the summary, since every ticket carries a message. The one place the two
19533
+ * fields become the body that is checked against the limit and sent.
19534
+ */
19535
+ function ticketBody(summary, details) {
19536
+ return details.trim() ? details : summary;
19537
+ }
19538
+ /** The details field that gives a send's body back through `ticketBody`: empty when the body is its summary. */
19539
+ function detailsOf(submission) {
19540
+ return submission.body === submission.subject ? '' : submission.body;
19541
+ }
19542
+ /** A signed-in customer as the form names them: "Alex M." for Alex Morgan, a one-word name as it is, else their email. */
19543
+ function postingName(customer) {
19544
+ const words = (customer.display_name ?? '').trim().split(/\s+/).filter(Boolean);
19545
+ if (words.length === 0)
19546
+ return customer.email;
19547
+ if (words.length === 1)
19548
+ return words[0];
19549
+ return `${words[0]} ${Array.from(words[words.length - 1])[0]}.`;
19550
+ }
19551
+ function focusAtEnd(field, focusOptions) {
19552
+ field.focus(focusOptions);
19553
+ // An email field has no caret to place.
19554
+ if (field.type !== 'email')
19555
+ field.setSelectionRange(field.value.length, field.value.length);
19240
19556
  }
19557
+ /** A button that reads as a link: an action beside text, never the step's own. */
19558
+ function textButton(text, action) {
19559
+ const button = document.createElement('button');
19560
+ button.type = 'button';
19561
+ button.className = 'svhd-text-button';
19562
+ button.textContent = text;
19563
+ button.addEventListener('click', action);
19564
+ return button;
19565
+ }
19566
+ const SIGN_IN_CANCELLED_COPY = 'Sign-in was cancelled. Your request is still here and hasn’t been sent.';
19567
+ const RECOVER_STATUS_COPY = 'Sign in again to recover your saved request.';
19568
+ const RECOVER_WEBSITE_COPY = 'Sign in to your website account again to recover your saved request.';
19569
+ const WEBSITE_SIGNED_OUT_COPY = 'You’re not signed in to the website. Sign in there, then choose Use website account again.';
19570
+ const RECOVER_NOTE_COPY = 'Sign in with the same email as before to recover your saved request.';
19241
19571
  /** Host callback failures do not change a ticket's accepted or failed result. */
19242
19572
  function notify$1(callback, value) {
19243
19573
  try {
@@ -19265,6 +19595,22 @@ function edited(input, prefill) {
19265
19595
  const text = input.value.trim();
19266
19596
  return text !== '' && text !== prefill.trim();
19267
19597
  }
19598
+ /**
19599
+ * The longest issue that fills the summary when contact starts. An issue this
19600
+ * short, on one line, already names the request; a longer one is the
19601
+ * customer's description, and cutting a summary from it would put words in
19602
+ * their mouth.
19603
+ */
19604
+ const SUMMARY_PREFILL_MAX = 100;
19605
+ /** Whether trimmed text is one line of at most `max` characters. */
19606
+ function oneLine(text, max) {
19607
+ return text.length <= max && !/[\r\n]/.test(text);
19608
+ }
19609
+ /** What contact starts from: a short one-line issue as the summary; any other as the details, every character as written. */
19610
+ function composeIssue(issue) {
19611
+ const text = issue.trim();
19612
+ return oneLine(text, SUMMARY_PREFILL_MAX) ? { subject: text, body: '' } : { subject: '', body: issue };
19613
+ }
19268
19614
  function companySignInUrl(value) {
19269
19615
  try {
19270
19616
  const url = new URL(value ?? '');
@@ -19284,24 +19630,54 @@ function companySignInUrl(value) {
19284
19630
  * line carries the flow (a code sent, a send in progress or uncertain, a
19285
19631
  * changed sign-in, a server error). Closing with unsent work asks first.
19286
19632
  * A confirmed send replaces the form with its confirmation.
19633
+ *
19634
+ * The request is a summary and optional details, in a composer that also
19635
+ * takes files. A signed-out widget customer writes it as step 1 of 2; step 2
19636
+ * asks who the reply goes to and proves it in the native sign-in window.
19287
19637
  */
19288
19638
  function mountHelpDeskForm(client, options) {
19289
19639
  const target = resolveTarget(options.target);
19290
19640
  injectHelpDeskFormStyles();
19641
+ const widget = options.widgetIdentity;
19291
19642
  const shell = new InlineShell(target, {
19292
19643
  containerClassName: 'svhd-container',
19293
19644
  bodyClassName: 'svhd-body',
19294
- footer: createSecuredByFooter('svhd'),
19645
+ // The page that lays the support wizard out carries the attribution itself.
19646
+ footer: options.hostShowsAttribution ? null : createSecuredByFooter('svhd'),
19295
19647
  });
19296
19648
  const prefix = `svhd-${++formSequence}`;
19297
- const heading = document.createElement('h2');
19298
- heading.id = `${prefix}-heading`;
19299
- heading.textContent = 'Contact support';
19300
19649
  const form = document.createElement('form');
19301
19650
  form.className = 'svhd-form';
19302
19651
  form.noValidate = true;
19652
+ shell.body.append(form);
19653
+ /** A step's heading, which takes focus when the step is entered, under its "Step N of 2" label when it has one. */
19654
+ function stepHead(id, title, label) {
19655
+ const head = document.createElement('div');
19656
+ head.className = 'svhd-step-head';
19657
+ const stepLabel = label === null ? null : document.createElement('p');
19658
+ if (stepLabel) {
19659
+ stepLabel.className = 'svhd-step-label';
19660
+ stepLabel.textContent = label;
19661
+ head.append(stepLabel);
19662
+ }
19663
+ const stepHeading = document.createElement('h2');
19664
+ stepHeading.id = id;
19665
+ stepHeading.tabIndex = -1;
19666
+ stepHeading.textContent = title;
19667
+ head.append(stepHeading);
19668
+ return { head, heading: stepHeading, label: stepLabel };
19669
+ }
19670
+ function stepContainer(step) {
19671
+ const container = document.createElement('div');
19672
+ container.className = 'svhd-step';
19673
+ container.dataset.contactStep = step;
19674
+ return container;
19675
+ }
19676
+ const request = stepHead(`${prefix}-heading`, widget ? `Contact ${client.desk.organization_name || 'support'}` : 'Contact support', widget ? 'Step 1 of 2' : null);
19677
+ const heading = request.heading;
19303
19678
  form.setAttribute('aria-labelledby', heading.id);
19304
- shell.body.append(heading, form);
19679
+ const details = stepContainer('details');
19680
+ details.append(request.head);
19305
19681
  // A field's error is an alert only while it shows, so it is announced
19306
19682
  // even when focus already sits on the field it names.
19307
19683
  function setFieldError(entry, text) {
@@ -19333,10 +19709,11 @@ function mountHelpDeskForm(client, options) {
19333
19709
  label.className = 'svhd-label';
19334
19710
  label.htmlFor = `${prefix}-${name}`;
19335
19711
  label.textContent = labelText;
19336
- const input = textarea ? createDescriptionInput() : document.createElement('input');
19712
+ const input = textarea ? document.createElement('textarea') : document.createElement('input');
19337
19713
  input.id = label.htmlFor;
19338
19714
  input.name = name;
19339
- input.className = textarea ? 'svhd-input svhd-description' : 'svhd-input';
19715
+ if (!textarea)
19716
+ input.className = 'svhd-input';
19340
19717
  const error = document.createElement('p');
19341
19718
  error.id = `${input.id}-error`;
19342
19719
  error.className = 'svhd-field-error';
@@ -19346,19 +19723,23 @@ function mountHelpDeskForm(client, options) {
19346
19723
  input.addEventListener('input', () => clearFieldError(created));
19347
19724
  return created;
19348
19725
  }
19349
- const subject = field('Subject', 'subject');
19350
- const description = field('Description', 'description', true);
19726
+ const subject = field('Summary', 'subject');
19727
+ const description = field('Additional details', 'description', true);
19351
19728
  const email = field('Email address', 'email');
19352
19729
  const code = field('Email code', 'code');
19353
19730
  const name = field('Your name', 'display_name');
19354
19731
  const firstName = field('First name', 'given_name');
19355
19732
  const lastName = field('Last name (optional)', 'family_name');
19356
19733
  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 ?? '' };
19734
+ // The support wizard's issue the form was last filled from, which either
19735
+ // field may hold; undefined for a form filled from the host's subject and body.
19736
+ let filledFrom = options.issue;
19737
+ /** What a field was filled with: text the customer did not write. */
19738
+ const filledWith = (key) => filledFrom ?? options[key] ?? '';
19739
+ const filled = filledFrom === undefined ? { subject: filledWith('subject'), body: filledWith('body') } : composeIssue(filledFrom);
19359
19740
  subject.input.maxLength = MAX_SUBJECT_LEN;
19360
- subject.input.value = prefill.subject;
19361
- description.input.value = prefill.body;
19741
+ subject.input.value = filled.subject;
19742
+ description.input.value = filled.body;
19362
19743
  email.input.type = 'email';
19363
19744
  email.input.autocomplete = 'email';
19364
19745
  code.input.inputMode = 'numeric';
@@ -19370,7 +19751,7 @@ function mountHelpDeskForm(client, options) {
19370
19751
  lastName.input.maxLength = 100;
19371
19752
  const codeHint = document.createElement('p');
19372
19753
  codeHint.id = `${code.input.id}-hint`;
19373
- codeHint.className = 'svhd-file-hint';
19754
+ codeHint.className = 'svhd-hint';
19374
19755
  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
19756
  code.input.setAttribute('aria-describedby', codeHint.id);
19376
19757
  const resend = document.createElement('button');
@@ -19387,23 +19768,93 @@ function mountHelpDeskForm(client, options) {
19387
19768
  code.wrapper.append(codeHint, codeLinks);
19388
19769
  code.wrapper.hidden = true;
19389
19770
  name.wrapper.hidden = true;
19771
+ subject.input.required = true;
19772
+ // Enter in the summary moves on to the details it leads into, never sends a request half written.
19773
+ subject.input.addEventListener('keydown', (event) => {
19774
+ if (event.key !== 'Enter' || event.isComposing || event.keyCode === 229)
19775
+ return;
19776
+ event.preventDefault();
19777
+ focusAtEnd(description.input);
19778
+ });
19779
+ const attachments = client.desk.customer_can_attach_files && options.attachments !== false
19780
+ ? createFormAttachments(client, prefix, async () => {
19781
+ const ownGeneration = generation;
19782
+ const token = await tokenFor(ownGeneration);
19783
+ if (!token || !alive(ownGeneration))
19784
+ return null;
19785
+ const id = await ensureDraft(ownGeneration, token);
19786
+ if (!alive(ownGeneration))
19787
+ return null;
19788
+ return { draftId: id, expectedSessionToken: token };
19789
+ }, () => {
19790
+ if (attachments?.hasEntries)
19791
+ restoredFiles = false;
19792
+ persistDraft();
19793
+ syncLeaveGuard();
19794
+ })
19795
+ : undefined;
19796
+ const composer = createComposer({
19797
+ form, summary: subject.input, textarea: description.input, attachments,
19798
+ deskRefusesFiles: !client.desk.customer_can_attach_files, onRequestStep: () => step === 'details',
19799
+ });
19800
+ description.wrapper.classList.add('svhd-composer-field');
19801
+ description.wrapper.insertBefore(composer.frame, description.error);
19802
+ description.wrapper.insertBefore(composer.notice, description.error);
19803
+ details.append(subject.wrapper, description.wrapper);
19390
19804
  const auth = document.createElement('fieldset');
19391
19805
  auth.className = 'svhd-auth';
19392
19806
  auth.hidden = true;
19393
- auth.append(email.wrapper, code.wrapper, name.wrapper);
19807
+ auth.append(code.wrapper, name.wrapper);
19394
19808
  const widgetAccount = document.createElement('div');
19395
19809
  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);
19810
+ let widgetCustomer = widget?.customer ?? null;
19811
+ // A desk that signs in with SparkVault Identity asks only the email: its sign-in window asks a missing name.
19812
+ const asksName = client.desk.auth_mode !== 'identity';
19813
+ const reply = widget ? stepHead(`${prefix}-reply-heading`, asksName ? 'Who should we reply to?' : 'Sign in to send your request', 'Step 2 of 2') : null;
19814
+ const identity = widget ? stepContainer('identity') : null;
19815
+ const recap = document.createElement('div');
19816
+ recap.className = 'svhd-recap';
19817
+ const recapText = document.createElement('p');
19818
+ recapText.className = 'svhd-recap-text';
19819
+ const editRequest = textButton('Edit', () => { if (!pending && !destroyed)
19820
+ enterStep('details'); });
19821
+ editRequest.setAttribute('aria-label', 'Edit your request');
19822
+ const noteText = document.createTextNode('');
19823
+ const unsentNote = asksName
19824
+ ? 'Your request hasn’t been sent yet. Tell us who to reply to, then we’ll send it.'
19825
+ : 'Your request hasn’t been sent yet. Sign in so we know who to reply to, then we’ll send it.';
19826
+ const live = createLiveRegion('svhd-live');
19827
+ if (identity && reply) {
19402
19828
  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
- }
19829
+ details.append(widgetAccount);
19830
+ identity.hidden = true;
19831
+ const note = document.createElement('p');
19832
+ note.className = 'svhd-note';
19833
+ note.dataset.unsentNote = '';
19834
+ note.append(helpDeskIcon('info'), noteText);
19835
+ const recapRequest = document.createElement('div');
19836
+ recapRequest.className = 'svhd-recap-request';
19837
+ const recapLabel = document.createElement('span');
19838
+ recapLabel.className = 'svhd-recap-label';
19839
+ recapLabel.textContent = 'Your request';
19840
+ recapRequest.append(recapLabel, recapText);
19841
+ recap.append(recapRequest, editRequest);
19842
+ const helper = document.createElement('p');
19843
+ helper.id = `${email.input.id}-help`;
19844
+ helper.className = 'svhd-hint';
19845
+ 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.';
19846
+ email.input.setAttribute('aria-describedby', helper.id);
19847
+ identity.append(reply.head, note, recap);
19848
+ if (asksName) {
19849
+ const names = document.createElement('div');
19850
+ names.className = 'svhd-widget-names';
19851
+ names.append(firstName.wrapper, lastName.wrapper);
19852
+ identity.append(names);
19853
+ }
19854
+ identity.append(email.wrapper, helper);
19855
+ }
19856
+ else
19857
+ auth.prepend(email.wrapper);
19407
19858
  const status = document.createElement('p');
19408
19859
  status.className = 'svhd-status';
19409
19860
  status.setAttribute('role', 'status');
@@ -19423,13 +19874,15 @@ function mountHelpDeskForm(client, options) {
19423
19874
  const send = document.createElement('button');
19424
19875
  send.className = 'svhd-button';
19425
19876
  send.type = 'submit';
19426
- send.textContent = options.widgetIdentity ? widgetCustomer ? 'Send message' : 'Continue' : 'Send request';
19427
19877
  const cancel = document.createElement('button');
19428
19878
  cancel.className = 'svhd-button svhd-secondary';
19429
19879
  cancel.type = 'button';
19430
19880
  cancel.textContent = 'Cancel';
19431
19881
  cancel.hidden = !options.onCancel;
19432
- actions.append(send, cancel);
19882
+ const startNew = textButton('Start a new request', () => { if (!pending && !destroyed && recovery !== null)
19883
+ leaveRecovery(); });
19884
+ startNew.hidden = true;
19885
+ actions.append(send, startNew, cancel);
19433
19886
  const confirm = document.createElement('div');
19434
19887
  confirm.className = 'svhd-confirm';
19435
19888
  confirm.setAttribute('role', 'group');
@@ -19455,8 +19908,10 @@ function mountHelpDeskForm(client, options) {
19455
19908
  discard.textContent = DISCARD_REQUEST_COPY.discard;
19456
19909
  confirmActions.append(keepEditing, discard);
19457
19910
  confirm.append(confirmTitle, confirmNote, confirmActions);
19458
- form.append(subject.wrapper, description.wrapper, auth, widgetAccount, status, hosted, actions, confirm);
19911
+ form.append(details, ...(identity ? [identity] : []), auth, status, hosted, actions, confirm, live.element);
19459
19912
  let state = 'editing';
19913
+ let step = 'details';
19914
+ let guardingLeave = false;
19460
19915
  let destroyed = false;
19461
19916
  let pending = false;
19462
19917
  let completed = false;
@@ -19476,43 +19931,56 @@ function mountHelpDeskForm(client, options) {
19476
19931
  let uncertainSubmission = null;
19477
19932
  let sessionToken = null;
19478
19933
  let sessionKnown = false;
19479
- let attachments;
19480
19934
  let submittedCode = null;
19481
19935
  let resendAt = 0;
19482
19936
  let resendTimer = null;
19483
19937
  let confirmReturn = null;
19484
19938
  let done = null;
19485
- let draftRequester = null;
19939
+ // The verified customer whose saved request the form holds.
19940
+ let draftOwner = null;
19486
19941
  let restoredDraft = false;
19487
19942
  let restoredAnonymous = false;
19488
19943
  let restoredFiles = false;
19489
- let savedDraftNeedsSignIn = false;
19944
+ // How the customer whose saved request the form hides signed in, while it
19945
+ // waits for them to sign in again: that is the only way back to it.
19946
+ let recovery = null;
19947
+ // The website gave no account back when asked for the hidden request's customer.
19948
+ let websiteSignedOut = false;
19490
19949
  function persistDraft() {
19491
19950
  if (!options.persist || completed || destroyed)
19492
19951
  return;
19493
- if (!draftRequester) {
19494
- if (!savedDraftNeedsSignIn)
19495
- saveAnonymousFormDraft(client.desk.desk_id, { subject: subject.input.value, body: description.input.value });
19952
+ if (!draftOwner) {
19953
+ // The hidden request is a previous customer's; nothing is saved over it.
19954
+ if (recovery === null)
19955
+ saveAnonymousFormDraft(client.desk.desk_id, { subject: subject.input.value, body: description.input.value }, filledFrom);
19496
19956
  return;
19497
19957
  }
19498
- saveFormDraft(client.desk.desk_id, draftRequester, {
19958
+ saveFormDraft(client.desk.desk_id, draftOwner.requester_id, {
19499
19959
  subject: subject.input.value, body: description.input.value, ticketId: draftId,
19500
19960
  uncertain: uncertainSubmission, hadFiles: restoredFiles || attachments?.hasEntries === true,
19501
19961
  });
19502
19962
  }
19503
19963
  function forgetDraft() {
19504
- if (draftRequester)
19505
- removeFormDraft(client.desk.desk_id, draftRequester);
19506
- else if (options.persist)
19964
+ if (!options.persist)
19965
+ return;
19966
+ if (draftOwner)
19967
+ removeFormDraft(client.desk.desk_id, draftOwner.requester_id);
19968
+ else
19507
19969
  clearSupportIssue(client.desk.desk_id);
19508
19970
  }
19509
- /** Only /me or the verified sign-in answer can select a saved requester's draft. */
19971
+ /**
19972
+ * The request is now this verified customer's, saved in this tab or not.
19973
+ * Only /me or the verified sign-in answer can select a saved requester's draft.
19974
+ */
19510
19975
  function restoreDraft(customer) {
19511
- if (!options.persist || draftRequester === customer.requester_id)
19976
+ if (draftOwner?.requester_id === customer.requester_id)
19512
19977
  return false;
19513
- savedDraftNeedsSignIn = false;
19514
- draftRequester = customer.requester_id;
19515
- const saved = readFormDraft(client.desk.desk_id, draftRequester);
19978
+ draftOwner = customer;
19979
+ recovery = null;
19980
+ renderActions();
19981
+ if (!options.persist)
19982
+ return false;
19983
+ const saved = readFormDraft(client.desk.desk_id, customer.requester_id);
19516
19984
  clearSupportIssue(client.desk.desk_id);
19517
19985
  if (!saved) {
19518
19986
  persistDraft();
@@ -19521,12 +19989,10 @@ function mountHelpDeskForm(client, options) {
19521
19989
  restoredDraft = true;
19522
19990
  restoredFiles = saved.hadFiles && !saved.uncertain;
19523
19991
  subject.input.value = saved.uncertain?.subject ?? saved.subject;
19524
- description.input.value = saved.uncertain?.body ?? saved.body;
19992
+ description.input.value = saved.uncertain ? detailsOf(saved.uncertain) : saved.body;
19525
19993
  draftId = saved.ticketId;
19526
19994
  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';
19995
+ send.textContent = idleLabel();
19530
19996
  setState(uncertainSubmission ? 'uncertain' : 'editing');
19531
19997
  message(uncertainSubmission
19532
19998
  ? 'Your original request is preserved. Check submission before starting another request.'
@@ -19538,55 +20004,136 @@ function mountHelpDeskForm(client, options) {
19538
20004
  // An account switch must not turn an uncertain send into a fresh request.
19539
20005
  return pending || uncertainSubmission !== null || completed ? null : { subject: subject.input.value, body: description.input.value };
19540
20006
  }
20007
+ /** What the send button reads while nothing is in flight. */
20008
+ function idleLabel() {
20009
+ if (uncertainSubmission)
20010
+ return 'Check submission';
20011
+ if (challenge)
20012
+ return 'Verify and send request';
20013
+ if (recovery === 'external_sso' && widget)
20014
+ return 'Use website account';
20015
+ if (recovery !== null && step === 'details')
20016
+ return 'Sign in to recover request';
20017
+ return widget && !widgetCustomer ? 'Continue' : 'Send request';
20018
+ }
20019
+ /**
20020
+ * The signed-in widget customer writes and sends in one step, posting as
20021
+ * the account named under it; a signed-out one writes the request as step
20022
+ * 1 of 2. Either way the form shows the request.
20023
+ */
19541
20024
  function renderWidgetIdentity() {
19542
- if (!options.widgetIdentity)
20025
+ if (!widget)
19543
20026
  return;
19544
- widgetAccount.replaceChildren();
19545
- send.textContent = widgetCustomer ? 'Send message' : 'Continue';
19546
- auth.hidden = widgetCustomer !== null;
19547
- email.wrapper.hidden = false;
20027
+ if (request.label)
20028
+ request.label.hidden = widgetCustomer !== null;
20029
+ auth.hidden = true;
19548
20030
  code.wrapper.hidden = true;
19549
20031
  name.wrapper.hidden = true;
20032
+ widgetAccount.replaceChildren();
20033
+ const free = () => !pending && !destroyed && uncertainSubmission === null && !completed;
19550
20034
  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);
20035
+ const postingAs = document.createElement('p');
20036
+ postingAs.className = 'svhd-posting-as';
20037
+ const shown = postingName(widgetCustomer);
20038
+ // Not you? opens the sign-in window in this click: nothing may await before it.
20039
+ postingAs.append(`Posting as ${shown}${shown.endsWith('.') ? '' : '.'} `, textButton('Not you?', () => {
20040
+ if (free())
20041
+ widget.switchAccount(safeComposition());
20042
+ }));
20043
+ widgetAccount.append(postingAs);
19568
20044
  }
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);
20045
+ if (widget.useWebsiteAccount && widget.offerWebsiteAccount) {
20046
+ widgetAccount.append(textButton('Use website account', () => {
20047
+ if (free())
20048
+ widget.useWebsiteAccount?.(safeComposition());
20049
+ }));
19585
20050
  }
20051
+ setStep('details');
20052
+ }
20053
+ /**
20054
+ * The actions and notes for where the request is. While the form hides a
20055
+ * previous customer's saved request (`recovery`), nothing shows of it, nor
20056
+ * says it was not sent, since it may be a send whose answer was lost: the
20057
+ * request step's status line says how to get it back and the reply-to
20058
+ * step's note alone speaks there, Start a new request leaves it, and the
20059
+ * account row is away. A website-account customer's request comes back only
20060
+ * through that account, so Use website account is its one way on when the
20061
+ * website bridges one, and there is none when it does not.
20062
+ */
20063
+ function renderActions() {
20064
+ send.textContent = idleLabel();
20065
+ send.hidden = recovery === 'external_sso' && widget !== undefined && !widget.useWebsiteAccount;
20066
+ startNew.hidden = recovery === null;
20067
+ widgetAccount.hidden = recovery !== null || widgetAccount.childElementCount === 0;
20068
+ recap.hidden = recovery !== null;
20069
+ noteText.data = recovery === 'identity' || recovery === 'email_pin' ? RECOVER_NOTE_COPY : unsentNote;
20070
+ if (recovery !== null)
20071
+ message(step === 'identity' ? '' : recoveryStatus());
20072
+ }
20073
+ /** What the request step's status line asks for while a saved request is hidden. */
20074
+ function recoveryStatus() {
20075
+ if (recovery !== 'external_sso')
20076
+ return RECOVER_STATUS_COPY;
20077
+ return websiteSignedOut ? WEBSITE_SIGNED_OUT_COPY : RECOVER_WEBSITE_COPY;
20078
+ }
20079
+ /** Start a new request in place of the hidden one, which stays saved for its customer. */
20080
+ function leaveRecovery() {
20081
+ recovery = null;
20082
+ disable(false);
20083
+ message('');
20084
+ // A question asked while the saved request was hidden fills the new one.
20085
+ widget?.followIssue();
20086
+ if (step === 'identity')
20087
+ enterStep('details');
20088
+ else {
20089
+ renderActions();
20090
+ options.onScreenChange?.();
20091
+ controller.focusEntry();
20092
+ }
20093
+ }
20094
+ /** Show one step, the request or who the reply goes to, without moving focus. */
20095
+ function setStep(next) {
20096
+ const changed = next !== step;
20097
+ step = next;
20098
+ details.hidden = next !== 'details';
20099
+ if (identity)
20100
+ identity.hidden = next !== 'identity';
20101
+ if (next === 'identity')
20102
+ recapText.textContent = subject.input.value.trim();
20103
+ renderActions();
20104
+ syncLeaveGuard();
20105
+ if (changed)
20106
+ options.onScreenChange?.();
20107
+ }
20108
+ /** The customer moves between the steps: the new step's heading takes focus and its place is announced. */
20109
+ function enterStep(next) {
20110
+ setStep(next);
20111
+ live.announce(next === 'identity' ? 'Step 2 of 2' : 'Step 1 of 2');
20112
+ (next === 'identity' && reply ? reply.heading : heading).focus();
20113
+ }
20114
+ // An inline wizard, on any host page that gives a `target`, asks before that
20115
+ // page unloads while the request holds unsent work: leaving would lose it.
20116
+ // The floating panel never holds the page.
20117
+ // Chrome and Edge below 119, inside the SDK's browser floor, ask only when
20118
+ // returnValue is set; preventDefault is the standard signal.
20119
+ const onBeforeUnload = (event) => {
20120
+ event.preventDefault();
20121
+ event.returnValue = '';
20122
+ };
20123
+ function syncLeaveGuard() {
20124
+ const needed = options.pageLayout === true && !destroyed && holdsUnsentWork();
20125
+ if (needed === guardingLeave)
20126
+ return;
20127
+ guardingLeave = needed;
20128
+ if (needed)
20129
+ window.addEventListener('beforeunload', onBeforeUnload);
20130
+ else
20131
+ window.removeEventListener('beforeunload', onBeforeUnload);
19586
20132
  }
19587
20133
  function setState(next) {
19588
20134
  state = next;
19589
20135
  persistDraft();
20136
+ syncLeaveGuard();
19590
20137
  notify$1(options.onStateChange, next);
19591
20138
  }
19592
20139
  function message(text, isError = false) {
@@ -19613,13 +20160,22 @@ function mountHelpDeskForm(client, options) {
19613
20160
  resendTimer = setInterval(renderResend, 1000);
19614
20161
  renderResend();
19615
20162
  }
20163
+ /**
20164
+ * Disable every control while `disabled`. The request stays read-only, and
20165
+ * takes no files, while a send is unanswered, its exact text kept for the
20166
+ * check, and while it hides a saved request, which signing in brings back
20167
+ * in place of anything written.
20168
+ */
19616
20169
  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])
20170
+ for (const input of [subject.input, description.input, email.input, code.input, name.input, firstName.input, lastName.input, send, cancel, changeEmail, editRequest, startNew])
19618
20171
  input.disabled = disabled;
20172
+ const held = uncertainSubmission !== null || recovery !== null;
20173
+ subject.input.readOnly = held;
20174
+ description.input.readOnly = held;
19619
20175
  for (const button of widgetAccount.querySelectorAll('button'))
19620
20176
  button.disabled = disabled || uncertainSubmission !== null || completed;
19621
20177
  renderResend();
19622
- attachments?.disablePicking(disabled);
20178
+ attachments?.disablePicking(disabled || recovery !== null);
19623
20179
  attachments?.lock(completed || uncertainSubmission !== null);
19624
20180
  }
19625
20181
  function clearCode() {
@@ -19648,8 +20204,10 @@ function mountHelpDeskForm(client, options) {
19648
20204
  ? 'We may already have received this request. Closing now loses the way to check it.'
19649
20205
  : DISCARD_REQUEST_COPY.note;
19650
20206
  }
19651
- /** The field of the step in view: the code, name or email the sign-in asks for, else the subject. */
20207
+ /** 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
20208
  function stepField() {
20209
+ if (step === 'identity')
20210
+ return (asksName ? firstName : email).input;
19653
20211
  const asked = auth.hidden ? undefined : [code, name, email].find((entry) => !entry.wrapper.hidden);
19654
20212
  return (asked ?? subject).input;
19655
20213
  }
@@ -19690,25 +20248,27 @@ function mountHelpDeskForm(client, options) {
19690
20248
  }
19691
20249
  /**
19692
20250
  * 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.
20251
+ * unanswered, a code step, a request moved on to who the reply goes to, or
20252
+ * text and files of the customer's own. The silent company sign-in the
20253
+ * form runs as it opens (`authenticating`) is no work of the customer's.
19696
20254
  */
19697
20255
  function holdsUnsentWork() {
19698
20256
  if (completed)
19699
20257
  return false;
19700
- return (pending && state !== 'authenticating') || uncertainSubmission !== null || challenge !== null
19701
- || edited(subject.input, prefill.subject) || edited(description.input, prefill.body)
20258
+ return (pending && state !== 'authenticating') || uncertainSubmission !== null || challenge !== null || step === 'identity'
20259
+ || edited(subject.input, filledWith('subject')) || edited(description.input, filledWith('body'))
19702
20260
  || attachments?.hasEntries === true;
19703
20261
  }
19704
- /** The field a composition the ticket write would refuse is refused under, with what it reads there; null for one it takes. */
20262
+ /**
20263
+ * The field a request the ticket write would refuse is refused under, with
20264
+ * what it reads there; null for one it takes. The body is `ticketBody`'s,
20265
+ * so a request of a summary alone always has one.
20266
+ */
19705
20267
  function refusal(subjectText, body) {
19706
20268
  if (!subjectText)
19707
- return [subject, 'Add a subject.'];
20269
+ return [subject, 'Add a summary.'];
19708
20270
  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.'];
20271
+ return [subject, `Keep the summary to ${MAX_SUBJECT_LEN} characters.`];
19712
20272
  // The limit counts UTF-8 bytes, so a message of fewer characters can be over it;
19713
20273
  // a message of more UTF-16 units than that is over it without being encoded.
19714
20274
  if (body.length > MAX_BODY_BYTES || new TextEncoder().encode(body).length > MAX_BODY_BYTES)
@@ -19777,7 +20337,8 @@ function mountHelpDeskForm(client, options) {
19777
20337
  attachments?.clear(completed || uncertainSubmission !== null);
19778
20338
  attachments?.lock(false);
19779
20339
  if (attachments)
19780
- attachments.element.hidden = false;
20340
+ attachments.list.hidden = false;
20341
+ composer.clearNotice();
19781
20342
  subject.input.value = '';
19782
20343
  description.input.value = '';
19783
20344
  email.input.value = '';
@@ -19798,13 +20359,13 @@ function mountHelpDeskForm(client, options) {
19798
20359
  draftId = null;
19799
20360
  draftPromise = null;
19800
20361
  uncertainSubmission = null;
19801
- savedDraftNeedsSignIn = false;
20362
+ recovery = null;
20363
+ websiteSignedOut = false;
19802
20364
  restoredAnonymous = false;
19803
- subject.input.readOnly = false;
19804
- description.input.readOnly = false;
19805
20365
  completed = false;
19806
- send.textContent = 'Send request';
19807
20366
  message('');
20367
+ renderActions();
20368
+ syncLeaveGuard();
19808
20369
  }
19809
20370
  function sessionChanged(change) {
19810
20371
  if (destroyed)
@@ -19837,18 +20398,26 @@ function mountHelpDeskForm(client, options) {
19837
20398
  // during a pending proof must not leave the previous composer visible.
19838
20399
  subject.input.value = '';
19839
20400
  description.input.value = '';
20401
+ recapText.textContent = '';
19840
20402
  name.input.value = '';
19841
20403
  email.input.value = '';
19842
20404
  clearCode();
19843
20405
  if (attachments)
19844
- attachments.element.hidden = true;
20406
+ attachments.list.hidden = true;
19845
20407
  return;
19846
20408
  }
19847
20409
  // Preserve the old request before hiding it. The next verified requester
19848
20410
  // selects only their own storage key, including after a 401 and sign-in.
19849
20411
  persistDraft();
19850
- const canRecover = options.persist && draftRequester !== null && readFormDraft(client.desk.desk_id, draftRequester) !== null;
19851
- draftRequester = null;
20412
+ // A signed-in customer's request leaves view, saved or not, and with it the
20413
+ // question it was filled from: nothing the form holds may write it back.
20414
+ const hidesCustomer = draftOwner !== null;
20415
+ if (hidesCustomer && filledFrom !== undefined)
20416
+ filledFrom = '';
20417
+ // A saved request stays hidden for its customer, through any further change.
20418
+ const hidden = draftOwner === null ? recovery
20419
+ : options.persist && readFormDraft(client.desk.desk_id, draftOwner.requester_id) !== null ? draftOwner.assurance : null;
20420
+ draftOwner = null;
19852
20421
  restoredDraft = false;
19853
20422
  restoredFiles = false;
19854
20423
  generation += 1;
@@ -19857,15 +20426,19 @@ function mountHelpDeskForm(client, options) {
19857
20426
  if (options.widgetIdentity)
19858
20427
  widgetCustomer = null;
19859
20428
  clearComposer();
19860
- savedDraftNeedsSignIn = Boolean(canRecover);
20429
+ recovery = hidden;
19861
20430
  disable(false);
19862
20431
  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
20432
+ // The question that led here was the previous customer's too.
20433
+ if (hidesCustomer)
20434
+ widget?.forgetIssue();
20435
+ if (recovery === null)
19868
20436
  message('Your sign-in changed. Start a new request for the current account.');
20437
+ else
20438
+ renderActions();
20439
+ // The request and its actions changed under the pointer: a press already
20440
+ // under way must not act on what replaced them.
20441
+ options.onScreenChange?.();
19869
20442
  }
19870
20443
  const unsubscribe = client.subscribeSession(sessionChanged);
19871
20444
  const alive = (ownGeneration) => !destroyed && generation === ownGeneration;
@@ -19906,19 +20479,6 @@ function mountHelpDeskForm(client, options) {
19906
20479
  }
19907
20480
  return draftPromise;
19908
20481
  }
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
20482
  function showEmail() {
19923
20483
  auth.hidden = false;
19924
20484
  email.wrapper.hidden = false;
@@ -19951,31 +20511,46 @@ function mountHelpDeskForm(client, options) {
19951
20511
  // Sending (Enter in a field, a code's last digit) answers the discard
19952
20512
  // question: the customer kept going.
19953
20513
  closeConfirm(false);
20514
+ if (recovery === 'external_sso' && widget) {
20515
+ // Only the website account reaches a website-account customer's saved
20516
+ // request: a code or the secure window would sign in someone else.
20517
+ widget.useWebsiteAccount?.(null, true);
20518
+ return;
20519
+ }
19954
20520
  for (const entry of fields)
19955
20521
  clearFieldError(entry);
19956
20522
  const recoveringSubmission = uncertainSubmission !== null;
19957
20523
  const subjectText = uncertainSubmission?.subject ?? subject.input.value.trim();
19958
- const body = uncertainSubmission?.body ?? description.input.value;
20524
+ const detailsText = uncertainSubmission ? detailsOf(uncertainSubmission) : description.input.value;
20525
+ const body = uncertainSubmission?.body ?? ticketBody(subjectText, detailsText);
19959
20526
  if (uncertainSubmission) {
19960
20527
  // Retrying recovers this exact request. A lost response must never make
19961
20528
  // newly typed text appear to have been accepted as the earlier ticket.
19962
20529
  subject.input.value = subjectText;
19963
- description.input.value = body;
20530
+ description.input.value = detailsText;
19964
20531
  }
19965
20532
  const refused = refusal(subjectText, body);
19966
- const recoveringAfterSignIn = savedDraftNeedsSignIn;
20533
+ const recoveringAfterSignIn = recovery !== null;
19967
20534
  if (refused && !recoveringAfterSignIn) {
19968
20535
  const [entry, text] = refused;
20536
+ if (step !== 'details')
20537
+ setStep('details');
19969
20538
  setFieldError(entry, text);
19970
20539
  entry.input.focus();
19971
20540
  return;
19972
20541
  }
19973
20542
  let widgetSignIn;
19974
- if (options.widgetIdentity && !widgetCustomer) {
19975
- const givenName = firstName.input.value.trim();
19976
- const familyName = lastName.input.value.trim();
20543
+ if (widget && !widgetCustomer) {
20544
+ // The request is written; who the reply goes to is the next step, and
20545
+ // nothing reaches the network before it.
20546
+ if (step === 'details') {
20547
+ enterStep('identity');
20548
+ return;
20549
+ }
20550
+ const givenName = asksName ? firstName.input.value.trim() : '';
20551
+ const familyName = asksName ? lastName.input.value.trim() : '';
19977
20552
  const emailAddress = email.input.value.trim();
19978
- const invalid = !givenName ? firstName : !email.input.validity.valid || !emailAddress ? email : null;
20553
+ const invalid = asksName && !givenName ? firstName : !email.input.validity.valid || !emailAddress ? email : null;
19979
20554
  if (invalid) {
19980
20555
  setFieldError(invalid, invalid === email ? 'Enter your email address.' : 'Enter your first name.');
19981
20556
  invalid.input.focus();
@@ -19984,7 +20559,7 @@ function mountHelpDeskForm(client, options) {
19984
20559
  // Invoke in the original submit gesture, before any awaited token read:
19985
20560
  // the Identity adapter can open its native window without a popup block.
19986
20561
  try {
19987
- widgetSignIn = options.widgetIdentity.signIn({ email: emailAddress, givenName, familyName });
20562
+ widgetSignIn = widget.signIn(asksName ? { email: emailAddress, givenName, familyName } : { email: emailAddress });
19988
20563
  }
19989
20564
  catch (failure) {
19990
20565
  const error = failure instanceof Error ? failure : new Error('Sign-in could not be opened.');
@@ -20001,12 +20576,13 @@ function mountHelpDeskForm(client, options) {
20001
20576
  pending = true;
20002
20577
  disable(true);
20003
20578
  message('');
20579
+ syncLeaveGuard();
20004
20580
  try {
20005
20581
  if (widgetSignIn) {
20006
20582
  authenticating = true;
20007
20583
  authNotification = false;
20008
20584
  setState('authenticating');
20009
- message('Confirm your email in the sign-in window.');
20585
+ message('Finish signing in in the secure window.');
20010
20586
  }
20011
20587
  let token = await tokenFor(ownGeneration);
20012
20588
  if (!alive(ownGeneration))
@@ -20032,10 +20608,10 @@ function mountHelpDeskForm(client, options) {
20032
20608
  sessionKnown = true;
20033
20609
  authenticating = false;
20034
20610
  if (attachments)
20035
- attachments.element.hidden = false;
20611
+ attachments.list.hidden = false;
20036
20612
  subject.input.value = subjectText;
20037
- description.input.value = body;
20038
- if (options.widgetIdentity && session) {
20613
+ description.input.value = detailsText;
20614
+ if (widget && session) {
20039
20615
  widgetCustomer = session.customer;
20040
20616
  renderWidgetIdentity();
20041
20617
  message('');
@@ -20051,7 +20627,8 @@ function mountHelpDeskForm(client, options) {
20051
20627
  if (!alive(ownGeneration))
20052
20628
  return;
20053
20629
  if (!token) {
20054
- if (client.desk.auth_mode !== 'email_pin' && !(client.desk.auth_mode === 'external_sso' && client.desk.external_identity?.guest_email === true)) {
20630
+ // A website-account customer's saved request never comes back through an emailed code.
20631
+ if (recovery === 'external_sso' || (client.desk.auth_mode !== 'email_pin' && !(client.desk.auth_mode === 'external_sso' && client.desk.external_identity?.guest_email === true))) {
20055
20632
  showHosted();
20056
20633
  return;
20057
20634
  }
@@ -20095,10 +20672,10 @@ function mountHelpDeskForm(client, options) {
20095
20672
  sessionKnown = true;
20096
20673
  authenticating = false;
20097
20674
  if (attachments)
20098
- attachments.element.hidden = false;
20675
+ attachments.list.hidden = false;
20099
20676
  dropChallenge();
20100
20677
  subject.input.value = subjectText;
20101
- description.input.value = body;
20678
+ description.input.value = detailsText;
20102
20679
  notify$1(options.onSession, verified);
20103
20680
  }
20104
20681
  if (!token || !alive(ownGeneration))
@@ -20126,7 +20703,7 @@ function mountHelpDeskForm(client, options) {
20126
20703
  email.wrapper.hidden = true;
20127
20704
  code.wrapper.hidden = true;
20128
20705
  name.wrapper.hidden = false;
20129
- send.textContent = 'Send request';
20706
+ send.textContent = idleLabel();
20130
20707
  setState('editing');
20131
20708
  setFieldError(name, 'Add your name before sending your request.');
20132
20709
  focusAfter = name.input;
@@ -20148,7 +20725,7 @@ function mountHelpDeskForm(client, options) {
20148
20725
  setState('submitting');
20149
20726
  if (!alive(ownGeneration))
20150
20727
  return;
20151
- send.textContent = options.widgetIdentity ? 'Sending message' : 'Sending request';
20728
+ send.textContent = 'Sending request';
20152
20729
  if (!uncertainSubmission) {
20153
20730
  const id = await ensureDraft(ownGeneration, token);
20154
20731
  if (!alive(ownGeneration) || !(await tokenFor(ownGeneration)))
@@ -20191,14 +20768,10 @@ function mountHelpDeskForm(client, options) {
20191
20768
  const draftExpired = ticketAttempted && error instanceof SparkVaultError
20192
20769
  && (error.serviceCode === 'DRAFT_EXPIRED' || error.code === 'DRAFT_EXPIRED');
20193
20770
  if (uncertainSubmission && !draftExpired && (!ticketAttempted || recoveringSubmission || unknownSubmissionOutcome(error))) {
20194
- subject.input.readOnly = true;
20195
- description.input.readOnly = true;
20196
20771
  message('We could not confirm whether your request was sent. Check submission to recover it. Your original text is kept unchanged.', true);
20197
20772
  }
20198
20773
  else {
20199
20774
  uncertainSubmission = null;
20200
- subject.input.readOnly = false;
20201
- description.input.readOnly = false;
20202
20775
  if (draftExpired) {
20203
20776
  draftId = null;
20204
20777
  draftPromise = null;
@@ -20209,6 +20782,13 @@ function mountHelpDeskForm(client, options) {
20209
20782
  setFieldError(code, HELP_DESK_CODE_STEP_COPY.codeRefused);
20210
20783
  focusAfter = code.input;
20211
20784
  }
20785
+ else if (widgetSignIn && error instanceof SparkVaultError && error.code === 'user_cancelled') {
20786
+ // The request stays on who the reply goes to, ready to sign in again;
20787
+ // a hidden saved request is not here to speak of, so its note alone stays.
20788
+ if (recovery === null)
20789
+ message(SIGN_IN_CANCELLED_COPY);
20790
+ focusAfter = send;
20791
+ }
20212
20792
  else {
20213
20793
  message(draftExpired ? 'Your saved draft expired. Your text is kept. Choose your files again before sending.' : error.message, true);
20214
20794
  }
@@ -20216,7 +20796,7 @@ function mountHelpDeskForm(client, options) {
20216
20796
  setState(uncertainSubmission ? 'uncertain' : challenge ? 'verifying' : 'editing');
20217
20797
  if (!alive(ownGeneration))
20218
20798
  return;
20219
- send.textContent = uncertainSubmission ? 'Check submission' : challenge ? 'Verify and send request' : options.widgetIdentity ? widgetCustomer ? 'Send message' : 'Continue' : 'Send request';
20799
+ send.textContent = idleLabel();
20220
20800
  notify$1(options.onError, error);
20221
20801
  }
20222
20802
  finally {
@@ -20224,6 +20804,7 @@ function mountHelpDeskForm(client, options) {
20224
20804
  authenticating = false;
20225
20805
  pending = false;
20226
20806
  disable(completed);
20807
+ syncLeaveGuard();
20227
20808
  focusSettled();
20228
20809
  }
20229
20810
  }
@@ -20296,6 +20877,8 @@ function mountHelpDeskForm(client, options) {
20296
20877
  generation += 1;
20297
20878
  stopResendCountdown();
20298
20879
  attachments?.destroy(completed || uncertainSubmission !== null);
20880
+ composer.destroy();
20881
+ live.destroy();
20299
20882
  unsubscribe();
20300
20883
  form.removeEventListener('submit', onSubmit);
20301
20884
  shell.destroy();
@@ -20320,24 +20903,50 @@ function mountHelpDeskForm(client, options) {
20320
20903
  subject.input.value = composition.subject;
20321
20904
  description.input.value = composition.body;
20322
20905
  persistDraft();
20906
+ syncLeaveGuard();
20323
20907
  },
20324
- refill(composition) {
20325
- if (destroyed || restoredDraft || safeComposition() === null)
20908
+ refill(issue) {
20909
+ if (destroyed || restoredDraft || recovery !== null || safeComposition() === null)
20326
20910
  return false;
20911
+ const own = { subject: edited(subject.input, filledWith('subject')), body: edited(description.input, filledWith('body')) };
20912
+ const text = issue.trim();
20913
+ const placed = !own.subject && !own.body ? composeIssue(issue) : { subject: oneLine(text, MAX_SUBJECT_LEN) ? text : '', body: issue };
20327
20914
  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];
20915
+ if (own[key])
20916
+ continue;
20917
+ entry.input.value = placed[key];
20918
+ clearFieldError(entry);
20333
20919
  }
20920
+ filledFrom = issue;
20921
+ if (step === 'identity')
20922
+ recapText.textContent = subject.input.value.trim();
20334
20923
  persistDraft();
20924
+ syncLeaveGuard();
20335
20925
  return true;
20336
20926
  },
20337
20927
  resumeAfterAccess() {
20338
20928
  if (!destroyed && !pending && !completed && uncertainSubmission === null)
20339
20929
  message('');
20340
20930
  },
20931
+ returnToRequest() {
20932
+ if (destroyed || step !== 'identity')
20933
+ return false;
20934
+ // While the sign-in window is open the request stays where it is.
20935
+ if (!pending)
20936
+ enterStep('details');
20937
+ return true;
20938
+ },
20939
+ focusEntry(focusOptions) {
20940
+ if (destroyed || form.hidden)
20941
+ return false;
20942
+ const asked = stepField();
20943
+ const entry = asked === subject.input && subject.input.value.trim() ? description.input : asked;
20944
+ if (entry.disabled || entry.readOnly)
20945
+ (step === 'identity' && reply ? reply.heading : heading).focus(focusOptions);
20946
+ else
20947
+ focusAtEnd(entry, focusOptions);
20948
+ return true;
20949
+ },
20341
20950
  requestDismiss() {
20342
20951
  if (destroyed)
20343
20952
  return;
@@ -20371,18 +20980,28 @@ function mountHelpDeskForm(client, options) {
20371
20980
  keepEditing.addEventListener('click', () => closeConfirm(true));
20372
20981
  discard.addEventListener('click', dismiss);
20373
20982
  form.addEventListener('submit', onSubmit);
20374
- form.addEventListener('input', persistDraft);
20375
- form.addEventListener('change', () => {
20376
- if (attachments?.hasEntries)
20377
- restoredFiles = false;
20983
+ form.addEventListener('input', () => {
20378
20984
  persistDraft();
20985
+ syncLeaveGuard();
20379
20986
  });
20987
+ send.textContent = idleLabel();
20380
20988
  renderWidgetIdentity();
20989
+ // A signed-out widget customer starts on step 1 of 2 with focus in the request.
20990
+ if (widget && !widgetCustomer)
20991
+ live.announce('Step 1 of 2');
20381
20992
  if (options.widgetIdentity?.customer) {
20382
20993
  restoreDraft(options.widgetIdentity.customer);
20383
20994
  disable(false);
20384
20995
  }
20385
- else if (options.persist) {
20996
+ else if (widget?.recovering) {
20997
+ recovery = 'external_sso';
20998
+ websiteSignedOut = widget.recovering.websiteSignedOut;
20999
+ disable(false);
21000
+ renderActions();
21001
+ }
21002
+ else if (options.persist && filledFrom === undefined) {
21003
+ // The support wizard hands a composition it carries to restoreComposition;
21004
+ // a form of the host's own restores the one saved before a reload.
20386
21005
  const saved = readAnonymousFormDraft(client.desk.desk_id);
20387
21006
  if (saved) {
20388
21007
  subject.input.value = saved.subject;
@@ -20390,6 +21009,7 @@ function mountHelpDeskForm(client, options) {
20390
21009
  restoredAnonymous = true;
20391
21010
  }
20392
21011
  }
21012
+ syncLeaveGuard();
20393
21013
  notify$1(options.onStateChange, state);
20394
21014
  // Native company identity starts as the form opens, never from a Connect,
20395
21015
  // Allow, verification or submit gesture. Guest email is explicit desk policy.
@@ -22617,58 +23237,6 @@ function createSupportLauncher(options, open) {
22617
23237
  };
22618
23238
  }
22619
23239
 
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
23240
  /** The support journey's only skin. Customer content stays in the product register. */
22673
23241
  function injectHelpDeskSupportStyles() {
22674
23242
  if (document.getElementById('sparkvault-help-desk-support-styles'))
@@ -22794,11 +23362,10 @@ function injectHelpDeskSupportStyles() {
22794
23362
  .svhs-unlock-form{margin:0}
22795
23363
  .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
23364
  .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}
23365
+ .svhs-contact-target .svhd-container h2{font-size:22px;line-height:1.25;letter-spacing:-.6px;overflow-wrap:anywhere}
22798
23366
  .svhs-contact-target .svhd-form{gap:16px}
22799
23367
  .svhs-contact-target .svhd-label{font-size:13px;line-height:1.5}
22800
23368
  .svhs-contact-target .svhd-input{font-size:16px;line-height:1.5}
22801
- .svhs-contact-target .svhd-description{min-height:138px}
22802
23369
  .svhs-contact-target .svhd-actions{gap:10px}
22803
23370
  .svhs-contact-target .svhd-button:not(.svhd-secondary){background:var(--hd-accent,${DS.action});color:var(--hd-on-accent,${DS.white})}
22804
23371
  .svhs-contact-target .svhd-button:not(.svhd-secondary):hover{background:var(--hd-accent-hover,${DS.actionHover})}
@@ -22806,18 +23373,19 @@ function injectHelpDeskSupportStyles() {
22806
23373
  .svhs-contact-target .svhd-actions>.svhd-button:first-child{flex:1}
22807
23374
  .svhs-contact-target .svhd-status{font-size:14px}
22808
23375
  .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}}
23376
+ .svhs-contact-target .svhd-text-button{color:var(--hd-accent-ink,${DS.action})}
23377
+ .svhs-contact-target .svhd-text-button:disabled{color:${DS.slate500}}
23378
+ .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}
23379
+ @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}}
23380
+ .svhs-panel .svhd-composer-input:focus-visible{outline:none}
23381
+ .svhs-panel .svhd-composer button:focus-visible{outline-offset:-2px}
22817
23382
  .svhs-contact-target .svhd-widget-names{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:12px}
22818
23383
  .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}
23384
+ /* The request fills the panel: the details step, and in it the composer and its text, take the height the fields leave. */
23385
+ .svhs-contact-target .svhd-widget-form>[data-contact-step=details]{display:flex;flex:1;flex-direction:column;gap:16px}
23386
+ .svhs-contact-target .svhd-widget-form .svhd-composer-field{display:flex;flex:1;flex-direction:column;gap:6px;min-height:164px}
23387
+ .svhs-contact-target .svhd-widget-form .svhd-composer{flex:1}
23388
+ .svhs-contact-target .svhd-widget-form .svhd-composer-input{flex:1;min-height:120px}
22821
23389
  .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
23390
  .svhs-contact-target .svhd-widget-form>.svhd-actions>.svhd-secondary{display:none}
22823
23391
  .svhs-contact-target .svhd-widget-form .svhd-actions>.svhd-button{font-size:14px}
@@ -22830,7 +23398,6 @@ function injectHelpDeskSupportStyles() {
22830
23398
  .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
23399
  .svhs-receipt-note{white-space:pre-wrap;overflow-wrap:anywhere}
22832
23400
  .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
23401
  .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
23402
  .svhs-toast svg{width:18px;height:18px;flex:none;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
22836
23403
  .svhs-overlay{position:fixed;inset:0;z-index:2147482900;display:flex;background:${DS.white};padding:0;overflow:hidden}
@@ -22865,7 +23432,6 @@ function injectHelpDeskSupportStyles() {
22865
23432
  .svhs-feedback-actions{margin-top:30px}
22866
23433
  .svhs-feedback-actions .svhs-primary,.svhs-feedback-actions .svhs-secondary{min-height:48px}
22867
23434
  .svhs-contact-scroll{padding:0}
22868
- .svhs-contact-target .svhd-description{min-height:160px}
22869
23435
  .svhs-contact-target>.svhd-container{padding:24px}
22870
23436
  .svhs-contact-target .svhd-widget-form>.svhd-actions{padding-bottom:env(safe-area-inset-bottom)}
22871
23437
  .svhs-receipt-scroll{padding-top:58px}
@@ -23231,24 +23797,6 @@ function button(className, text, action) {
23231
23797
  node.addEventListener('click', action);
23232
23798
  return node;
23233
23799
  }
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
23800
  function httpUrl(value, base = window.location.href) {
23253
23801
  if (!value)
23254
23802
  return null;
@@ -23307,7 +23855,6 @@ class SupportView {
23307
23855
  this.receiptCopy = element('p', 'svhs-copy');
23308
23856
  this.receiptTicket = element('a', 'svhs-ticket-link');
23309
23857
  this.receiptMessage = element('p', 'svhs-copy svhs-receipt-note');
23310
- this.live = element('div', 'svhs-live');
23311
23858
  this.identityNotice = element('div', 'svhs-identity-notice');
23312
23859
  this.onMediaChange = () => this.syncPresentation();
23313
23860
  this.onViewportChange = () => this.syncViewport();
@@ -23320,6 +23867,24 @@ class SupportView {
23320
23867
  this.ticketGateSignature = '';
23321
23868
  this.toastCleanups = new Set();
23322
23869
  this.destroyed = false;
23870
+ // A multi-click that began before the screen changed (the panel opening, a
23871
+ // new stage or article, a new contact form, its step, or its request and
23872
+ // actions changing in place), wherever its first press
23873
+ // was, lands its later presses on a screen the customer has not seen yet:
23874
+ // they neither take focus there nor reach what is under them. A press in the
23875
+ // panel that starts anew, or a key press, acts as usual.
23876
+ this.screenChanges = 0;
23877
+ this.pressedAt = 0;
23878
+ this.onPress = (event) => {
23879
+ if (event.detail <= 1) {
23880
+ this.pressedAt = this.screenChanges;
23881
+ return;
23882
+ }
23883
+ if (this.screenChanges === this.pressedAt)
23884
+ return;
23885
+ event.preventDefault();
23886
+ event.stopPropagation();
23887
+ };
23323
23888
  injectHelpDeskSupportStyles();
23324
23889
  this.phoneHistory = !target && actions.onBrowserBack && actions.onBrowserForward ? new SupportPhoneHistory({
23325
23890
  onBack: () => this.actions.onBrowserBack?.(),
@@ -23332,20 +23897,20 @@ class SupportView {
23332
23897
  this.panel.hidden = true;
23333
23898
  this.panel.setAttribute('aria-labelledby', `${this.prefix}-name`);
23334
23899
  this.deskName.id = `${this.prefix}-name`;
23335
- this.live.setAttribute('role', 'status');
23336
- this.live.setAttribute('aria-live', 'polite');
23900
+ this.panel.addEventListener('mousedown', this.onPress, true);
23901
+ this.panel.addEventListener('click', this.onPress, true);
23337
23902
  const toolbar = element('header', 'svhs-toolbar');
23338
23903
  this.toolbar = toolbar;
23339
23904
  this.back = button('svhs-back', 'Back', () => this.actions.onBack());
23340
- this.back.prepend(icon('back'));
23905
+ this.back.prepend(helpDeskIcon('back'));
23341
23906
  this.close = button('svhs-icon-button', '', () => this.actions.onClose());
23342
23907
  this.close.setAttribute('aria-label', 'Close support');
23343
- this.close.append(icon('close'));
23908
+ this.close.append(helpDeskIcon('close'));
23344
23909
  this.external.setAttribute('aria-label', 'Open article in a new tab');
23345
23910
  this.external.title = 'Open article in a new tab';
23346
23911
  this.external.target = '_blank';
23347
23912
  this.external.rel = 'noopener noreferrer';
23348
- this.external.append(icon('external'));
23913
+ this.external.append(helpDeskIcon('external'));
23349
23914
  const toolbarActions = element('div', 'svhs-toolbar-actions');
23350
23915
  toolbarActions.append(this.external);
23351
23916
  if (!target)
@@ -23419,9 +23984,9 @@ class SupportView {
23419
23984
  const readerActions = element('div', 'svhs-reader-actions');
23420
23985
  const yes = button('svhs-primary', 'Yes', () => { if (this.state?.article && !this.state.busy && !this.state.error)
23421
23986
  this.actions.onAnswered(); });
23422
- yes.prepend(icon('thumbUp'));
23987
+ yes.prepend(helpDeskIcon('thumbUp'));
23423
23988
  const no = button('svhs-text-button', 'No, create a ticket', () => this.actions.onContact('article_not_answered'));
23424
- no.prepend(icon('thumbDown'));
23989
+ no.prepend(helpDeskIcon('thumbDown'));
23425
23990
  readerActions.append(yes, no);
23426
23991
  this.articleFooter.append(element('span', 'svhs-article-question', 'Did this resolve your question?'), readerActions);
23427
23992
  this.screens.get('article').append(this.articleFooter);
@@ -23463,7 +24028,7 @@ class SupportView {
23463
24028
  contact.append(this.contactTarget);
23464
24029
  const receipt = this.screen('receipt', 'Message sent');
23465
24030
  receipt.classList.add('svhs-receipt-scroll');
23466
- const receiptMark = icon('check');
24031
+ const receiptMark = helpDeskIcon('check');
23467
24032
  receiptMark.classList.add('svhs-receipt-mark');
23468
24033
  receipt.prepend(receiptMark);
23469
24034
  this.receiptTicket.target = '_blank';
@@ -23474,7 +24039,6 @@ class SupportView {
23474
24039
  if (!target)
23475
24040
  receiptFooter.append(button('svhs-secondary svhs-full', 'Done', () => this.actions.onClose()));
23476
24041
  receiptFooter.append(this.restart);
23477
- this.panel.append(this.live);
23478
24042
  this.media = typeof window.matchMedia === 'function' ? window.matchMedia('(max-width:640px)') : null;
23479
24043
  if (!target) {
23480
24044
  this.media?.addEventListener('change', this.onMediaChange);
@@ -23563,24 +24127,34 @@ class SupportView {
23563
24127
  if (!next.visible)
23564
24128
  return;
23565
24129
  if (!previous?.visible || previous.stage !== next.stage || previous.article?.id !== next.article?.id) {
24130
+ // A new screen, however it opened: from a press in the panel, the
24131
+ // launcher or a host link.
24132
+ this.screenChanges += 1;
23566
24133
  this.restoreScroll(next);
23567
24134
  this.focusCurrent();
23568
24135
  }
23569
24136
  }
24137
+ /** A new contact form, or one whose controls changed in place: a change of screen, as a new stage is. */
24138
+ contactScreenChanged() {
24139
+ this.screenChanges += 1;
24140
+ }
23570
24141
  /** Programmatic close invalidates Forward restoration even after neutral Back. */
23571
24142
  deactivateHistory() {
23572
24143
  this.phoneHistory?.deactivate();
23573
24144
  }
23574
- /** Focus the shared form after its controller has mounted it. */
24145
+ /** Focus the shared form where the customer goes on, else its heading, after its controller has mounted it. */
23575
24146
  focusContact() {
23576
24147
  if (this.destroyed || !this.state?.visible || this.state.stage !== 'contact')
23577
24148
  return;
23578
24149
  const heading = this.contactTarget.querySelector('h1,h2,h3');
23579
24150
  this.contactTitle.hidden = Boolean(heading);
23580
24151
  this.contactTitle.parentElement.hidden = this.contactTitle.hidden && this.contactStatus.hidden && this.contactError.hidden && this.sourceArticle.hidden;
24152
+ const focusOptions = { preventScroll: !this.target };
24153
+ if (!this.contactTarget.hidden && this.actions.onFocusContact?.(focusOptions))
24154
+ return;
23581
24155
  const target = heading ?? this.contactTarget;
23582
24156
  target.tabIndex = -1;
23583
- target.focus({ preventScroll: !this.target });
24157
+ target.focus(focusOptions);
23584
24158
  }
23585
24159
  /** Hydrate only the current reader's matching authorized publication assets. */
23586
24160
  setArticleAsset(path, blobUrl) {
@@ -23631,7 +24205,7 @@ class SupportView {
23631
24205
  const toast = element('div', 'svhs-toast');
23632
24206
  toast.setAttribute('role', 'status');
23633
24207
  toast.setAttribute('aria-atomic', 'true');
23634
- toast.append(icon('check'), document.createTextNode(message));
24208
+ toast.append(helpDeskIcon('check'), document.createTextNode(message));
23635
24209
  document.body.append(toast);
23636
24210
  const arrange = () => {
23637
24211
  let offset = 0;
@@ -23682,6 +24256,8 @@ class SupportView {
23682
24256
  return;
23683
24257
  this.destroyed = true;
23684
24258
  this.phoneHistory?.destroy();
24259
+ this.panel.removeEventListener('mousedown', this.onPress, true);
24260
+ this.panel.removeEventListener('click', this.onPress, true);
23685
24261
  document.removeEventListener('keydown', this.onKeydown);
23686
24262
  this.media?.removeEventListener('change', this.onMediaChange);
23687
24263
  window.visualViewport?.removeEventListener('resize', this.onViewportChange);
@@ -23752,9 +24328,9 @@ class SupportView {
23752
24328
  copy.append(element('span', 'svhs-result-excerpt', result.summary));
23753
24329
  if (result.category)
23754
24330
  copy.append(element('span', 'svhs-result-category', result.category));
23755
- const documentIcon = icon('article');
24331
+ const documentIcon = helpDeskIcon('article');
23756
24332
  documentIcon.classList.add('svhs-result-icon');
23757
- const chevron = icon('chevron');
24333
+ const chevron = helpDeskIcon('chevron');
23758
24334
  chevron.classList.add('svhs-result-chevron');
23759
24335
  open.append(documentIcon, copy, chevron);
23760
24336
  item.append(open);
@@ -24126,8 +24702,6 @@ class SupportView {
24126
24702
  }
24127
24703
  }
24128
24704
 
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
24705
  function notify(callback, value) {
24132
24706
  try {
24133
24707
  void Promise.resolve(callback?.(value)).catch(() => undefined);
@@ -24153,10 +24727,14 @@ function createHelpDeskSupport(config, options) {
24153
24727
  // only while it is the current sequence, so whatever supersedes it frees it.
24154
24728
  let contactOpening = null;
24155
24729
  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.
24730
+ // A website-account customer's saved request the next form keeps hidden,
24731
+ // asked for through the website account, which may give no account back.
24732
+ let pendingRecovery = null;
24733
+ // The issue, as written, that the held composition (the mounted form, the one
24734
+ // a re-authorized form will take, or the one saved before a reload) was last
24735
+ // filled from: '' for one filled from none. A form taking that composition is
24736
+ // filled from it too, so the text it carries is the customer's own, or not,
24737
+ // as it was in the form it came from.
24160
24738
  let composedFrom = '';
24161
24739
  let nativeIdentity = null;
24162
24740
  let switchedAccount = false;
@@ -24190,6 +24768,9 @@ function createHelpDeskSupport(config, options) {
24190
24768
  onBack: () => {
24191
24769
  if (destroyed || state.navigationLocked || state.identityPending)
24192
24770
  return;
24771
+ // On who the reply goes to, Back returns to the request it is for.
24772
+ if (state.stage === 'contact' && !state.ticketAccessRequired && contact?.returnToRequest())
24773
+ return;
24193
24774
  // A held form shows at once while contact still checks access behind it,
24194
24775
  // so a contact opening in flight is cancelled even when nothing is busy.
24195
24776
  if (state.busy || contactOpening === sequence)
@@ -24236,6 +24817,7 @@ function createHelpDeskSupport(config, options) {
24236
24817
  onUnlock: (password) => { void unlock(password); },
24237
24818
  onUnlockTicketAccess: (password) => { void unlockTicketAccess(password); },
24238
24819
  onCancelIdentity: () => nativeIdentity?.abort(),
24820
+ onFocusContact: (focusOptions) => contact?.focusEntry(focusOptions) ?? false,
24239
24821
  onBrowserBack: minimize,
24240
24822
  onBrowserForward: () => update({ visible: true }),
24241
24823
  }, options.target === undefined ? undefined : resolveTarget(options.target));
@@ -24315,7 +24897,7 @@ function createHelpDeskSupport(config, options) {
24315
24897
  const saved = readFormDraft(active.desk.desk_id, customer.requester_id);
24316
24898
  const composition = readAnonymousFormDraft(active.desk.desk_id);
24317
24899
  if ((saved || composition) && !state.issue) {
24318
- update({ issue: saved?.body ?? readSupportIssue(active.desk.desk_id) ?? '' });
24900
+ update({ issue: saved ? ticketBody(saved.subject, saved.body) : readSupportIssue(active.desk.desk_id) ?? '' });
24319
24901
  await showContact('direct');
24320
24902
  }
24321
24903
  else if (!state.issue)
@@ -24394,6 +24976,7 @@ function createHelpDeskSupport(config, options) {
24394
24976
  results = [];
24395
24977
  requestedArticle = null;
24396
24978
  pendingComposition = null;
24979
+ pendingRecovery = null;
24397
24980
  feedbackSequence += 1;
24398
24981
  sourceArticleId = undefined;
24399
24982
  if (options.persist && client)
@@ -24554,18 +25137,28 @@ function createHelpDeskSupport(config, options) {
24554
25137
  notify(options.onError, error);
24555
25138
  }
24556
25139
  }
24557
- function mountContact(composition, customer) {
25140
+ /** Mount the contact form filled from `composedFrom`, then put a composition carried from an earlier form in it. */
25141
+ function mountContact(carried, customer) {
24558
25142
  if (!client || destroyed)
24559
25143
  return;
24560
25144
  contactCustomer = customer;
25145
+ // A customer the website gave back sees their own saved request; none keeps it hidden.
25146
+ const recovering = customer ? null : pendingRecovery;
25147
+ pendingRecovery = null;
24561
25148
  let activeAttempt = null;
25149
+ // A ticket carries the attempt the form opened under only while it is still
25150
+ // the journey's: recovery drops it with the previous customer's question.
25151
+ const formAttempt = attempt;
25152
+ const bridged = Boolean(options.getSessionToken || options.getIdentityAssertion || options.identityEndpoint);
24562
25153
  contact = mountHelpDeskForm(client, {
24563
25154
  target: view.contactTarget,
24564
- // Filled with the issue its composition came from, so text the customer
25155
+ // Filled from the issue its composition came from, so text the customer
24565
25156
  // wrote in an earlier form and carried here stays their own.
24566
- ...composeIssue(composedFrom),
25157
+ issue: composedFrom,
24567
25158
  attachments: options.attachments,
24568
25159
  persist: options.persist,
25160
+ pageLayout: options.target !== undefined,
25161
+ hostShowsAttribution: options.hostShowsAttribution === true,
24569
25162
  onSession: (session) => {
24570
25163
  anonymous = false;
24571
25164
  if (options.persist)
@@ -24576,9 +25169,14 @@ function createHelpDeskSupport(config, options) {
24576
25169
  customer,
24577
25170
  signIn: (input) => signIn(input).then((session) => { contactCustomer = session.customer; return session; }),
24578
25171
  switchAccount: (safe) => { void switchAccount(safe); },
24579
- ...(switchedAccount && (options.getSessionToken || options.getIdentityAssertion || options.identityEndpoint) ? { useWebsiteAccount: (safe) => { void useWebsiteAccount(safe); } } : {}),
25172
+ ...(bridged && { useWebsiteAccount: (safe, recover) => { void useWebsiteAccount(safe, recover); } }),
25173
+ offerWebsiteAccount: switchedAccount,
25174
+ forgetIssue,
25175
+ followIssue,
25176
+ ...(recovering && { recovering }),
24580
25177
  },
24581
- assistanceContext: () => activeAttempt?.ticketContext(),
25178
+ onScreenChange: () => view.contactScreenChanged(),
25179
+ assistanceContext: () => (attempt === formAttempt ? activeAttempt?.ticketContext() : undefined),
24582
25180
  sourceArticleId: () => sourceArticleId,
24583
25181
  onError: (error) => {
24584
25182
  notify(options.onError, error);
@@ -24597,11 +25195,14 @@ function createHelpDeskSupport(config, options) {
24597
25195
  onSuccess: (ticket) => receipt(ticket),
24598
25196
  onStateChange: (next) => update({ navigationLocked: ['authenticating', 'submitting', 'uncertain'].includes(next) }),
24599
25197
  });
24600
- contact.restoreComposition(composition);
24601
- // A composition carried across re-authorization was filled from the issue as it read then.
25198
+ // A form in place of another can put a different control under the pointer.
25199
+ view.contactScreenChanged();
25200
+ if (carried)
25201
+ contact.restoreComposition(carried);
25202
+ // A carried composition was filled from the issue as it read then.
24602
25203
  followIssue();
24603
25204
  const activeForm = contact;
24604
- void attempt?.then((active) => {
25205
+ void formAttempt?.then((active) => {
24605
25206
  // Keep the mutable callback small: an analytics response arriving late
24606
25207
  // must not delay contact, authentication or ticket submission.
24607
25208
  if (contact === activeForm && active)
@@ -24617,10 +25218,30 @@ function createHelpDeskSupport(config, options) {
24617
25218
  */
24618
25219
  function followIssue() {
24619
25220
  const issue = state.issue.trim();
24620
- if (!contact || !issue || issue === composedFrom)
25221
+ if (!contact || !issue || issue === composedFrom.trim())
24621
25222
  return;
24622
- if (contact.refill(composeIssue(state.issue)))
24623
- composedFrom = issue;
25223
+ if (contact.refill(state.issue))
25224
+ composedFrom = state.issue;
25225
+ }
25226
+ /**
25227
+ * Forget the question of a customer whose request just left the contact
25228
+ * form: it, and the answers and article it led to, are theirs, in view and
25229
+ * in this tab's storage. The visitor is unknown again until one signs in,
25230
+ * so the tab keeps their next question as any signed-out visitor's.
25231
+ */
25232
+ function forgetIssue() {
25233
+ cancelArticleAssets?.();
25234
+ cancelArticleAssets = null;
25235
+ kbConfig = null;
25236
+ results = [];
25237
+ requestedArticle = null;
25238
+ attempt = null;
25239
+ sourceArticleId = undefined;
25240
+ composedFrom = '';
25241
+ anonymous = true;
25242
+ if (options.persist && client)
25243
+ clearSupportIssue(client.desk.desk_id);
25244
+ update({ issue: '', results: [], article: undefined, articleUrl: undefined, kbState: undefined, sourceArticle: undefined });
24624
25245
  }
24625
25246
  async function showContact(reason) {
24626
25247
  if (destroyed || contactOpening === sequence)
@@ -24667,12 +25288,16 @@ function createHelpDeskSupport(config, options) {
24667
25288
  return;
24668
25289
  update({ busy: false, ticketAccessRequired: false, ticketAccessMode: undefined });
24669
25290
  anonymous = !customer;
24670
- const composition = pendingComposition ?? (options.persist ? readAnonymousFormDraft(active.desk.desk_id) : null) ?? composeIssue(state.issue);
25291
+ // A composition saved before a reload goes on from the issue it was filled
25292
+ // from; with none carried, the form fills itself from the issue as written.
25293
+ const saved = pendingComposition === null && options.persist ? readAnonymousFormDraft(active.desk.desk_id) : null;
25294
+ if (saved)
25295
+ composedFrom = saved.composedFrom;
25296
+ else if (pendingComposition === null)
25297
+ composedFrom = state.issue;
24671
25298
  if (customer && options.persist)
24672
25299
  clearSupportIssue(active.desk.desk_id);
24673
- if (!pendingComposition)
24674
- composedFrom = state.issue.trim();
24675
- mountContact(composition, customer);
25300
+ mountContact(pendingComposition ?? saved, customer);
24676
25301
  pendingComposition = null;
24677
25302
  }
24678
25303
  catch (value) {
@@ -24736,6 +25361,7 @@ function createHelpDeskSupport(config, options) {
24736
25361
  cancelArticleAssets?.();
24737
25362
  cancelArticleAssets = null;
24738
25363
  pendingComposition = composition ?? { subject: '', body: '' };
25364
+ pendingRecovery = null;
24739
25365
  kb?.clearAccess();
24740
25366
  kbConfig = null;
24741
25367
  results = [];
@@ -24775,7 +25401,7 @@ function createHelpDeskSupport(config, options) {
24775
25401
  await showContact('direct');
24776
25402
  }
24777
25403
  }
24778
- async function useWebsiteAccount(composition) {
25404
+ async function useWebsiteAccount(composition, recovering = false) {
24779
25405
  if (!client || destroyed || state.navigationLocked)
24780
25406
  return;
24781
25407
  const ownSequence = ++sequence;
@@ -24784,6 +25410,7 @@ function createHelpDeskSupport(config, options) {
24784
25410
  cancelArticleAssets?.();
24785
25411
  cancelArticleAssets = null;
24786
25412
  pendingComposition = composition ?? { subject: '', body: '' };
25413
+ pendingRecovery = recovering ? { websiteSignedOut: true } : null;
24787
25414
  kb?.clearAccess();
24788
25415
  kbConfig = null;
24789
25416
  results = [];
@@ -24804,6 +25431,9 @@ function createHelpDeskSupport(config, options) {
24804
25431
  return;
24805
25432
  const error = failure(value);
24806
25433
  update({ busy: false, error: error.message });
25434
+ // The website was not reached, so it is not known to have no account.
25435
+ if (pendingRecovery)
25436
+ pendingRecovery = { websiteSignedOut: false };
24807
25437
  if (client.hasTicketAccess) {
24808
25438
  mountContact(composition ?? { subject: '', body: '' }, null);
24809
25439
  pendingComposition = null;
@@ -29618,7 +30248,7 @@ class SparkVault {
29618
30248
  }
29619
30249
  /** Get the SDK version */
29620
30250
  static get version() {
29621
- return '16.4.1';
30251
+ return '16.5.0';
29622
30252
  }
29623
30253
  }
29624
30254
  if (typeof window !== 'undefined') {