@avlcodemonkey/nilla-components 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/LICENSE +21 -0
  3. package/README.md +219 -3
  4. package/THIRD_PARTY_NOTICES.md +48 -0
  5. package/css/alert.css +48 -0
  6. package/css/autocomplete.css +38 -0
  7. package/css/dialog.css +61 -0
  8. package/css/file-to-textarea.css +8 -0
  9. package/css/html-editor.css +172 -0
  10. package/css/json.css +44 -0
  11. package/css/list.css +37 -0
  12. package/css/nav-toggle.css +92 -0
  13. package/css/nilla.css +16 -0
  14. package/css/pjax.css +58 -0
  15. package/css/slider-input.css +16 -0
  16. package/css/table.css +99 -0
  17. package/css/tokens.css +44 -0
  18. package/css/unsaved-changes.css +10 -0
  19. package/css/vendor/wysi.css +406 -0
  20. package/docs/llms.txt +319 -0
  21. package/package.json +121 -5
  22. package/src/components/Alert.js +24 -0
  23. package/src/components/Autocomplete.js +127 -0
  24. package/src/components/BaseComponent.js +78 -0
  25. package/src/components/BaseDialog.js +151 -0
  26. package/src/components/ConfirmDialog.js +34 -0
  27. package/src/components/CopyToClipboard.js +66 -0
  28. package/src/components/DateFormatter.js +51 -0
  29. package/src/components/DateTimeInput.js +63 -0
  30. package/src/components/DisplayToggle.js +53 -0
  31. package/src/components/FileToTextarea.js +81 -0
  32. package/src/components/HtmlEditor.js +309 -0
  33. package/src/components/InfoDialog.js +38 -0
  34. package/src/components/JsonFormatter.js +23 -0
  35. package/src/components/List.js +237 -0
  36. package/src/components/ListSortable.js +8 -0
  37. package/src/components/NavToggle.js +119 -0
  38. package/src/components/PJax.js +888 -0
  39. package/src/components/Share.js +41 -0
  40. package/src/components/SliderInput.js +26 -0
  41. package/src/components/Table.js +758 -0
  42. package/src/components/TimeOffsetSelect.js +29 -0
  43. package/src/components/UnsavedChanges.js +187 -0
  44. package/src/constants/Fetch.js +7 -0
  45. package/src/constants/HttpHeaders.js +19 -0
  46. package/src/constants/HttpMethods.js +14 -0
  47. package/src/constants/SortDirection.js +11 -0
  48. package/src/constants/TableElements.js +25 -0
  49. package/src/constants/TableSettings.js +14 -0
  50. package/src/errors/FetchError.js +7 -0
  51. package/src/events/ListReorderEvent.js +19 -0
  52. package/src/events/PJaxErrorEvent.js +38 -0
  53. package/src/events/PJaxNavigatingEvent.js +46 -0
  54. package/src/index.js +26 -0
  55. package/src/locales/en.json +55 -0
  56. package/src/locales/es.js +9 -0
  57. package/src/locales/es.json +55 -0
  58. package/src/models/TableSort.js +20 -0
  59. package/src/utils/ajaxHeaders.js +10 -0
  60. package/src/utils/announce.js +40 -0
  61. package/src/utils/defineElement.js +13 -0
  62. package/src/utils/editor/blockTools.js +256 -0
  63. package/src/utils/editor/elements.js +18 -0
  64. package/src/utils/editor/input.js +350 -0
  65. package/src/utils/editor/selection.js +125 -0
  66. package/src/utils/editor/tableTools.js +497 -0
  67. package/src/utils/escape.js +20 -0
  68. package/src/utils/fetchJsonArray.js +29 -0
  69. package/src/utils/filterArray.js +18 -0
  70. package/src/utils/formActionUrl.js +10 -0
  71. package/src/utils/formData.js +118 -0
  72. package/src/utils/index.js +18 -0
  73. package/src/utils/indexedCompare.js +18 -0
  74. package/src/utils/isSameOrigin.js +12 -0
  75. package/src/utils/locale.js +36 -0
  76. package/src/utils/notifyChange.js +10 -0
  77. package/src/utils/numberSetting.js +14 -0
  78. package/src/utils/pageLanguage.js +13 -0
  79. package/src/utils/parseUtcDate.js +22 -0
  80. package/src/utils/randomId.js +17 -0
  81. package/src/utils/registerTabTrap.js +60 -0
  82. package/src/utils/renderTemplate.js +44 -0
  83. package/src/utils/requestTimeout.js +12 -0
  84. package/src/utils/response.js +28 -0
  85. package/src/utils/sortedCompare.js +67 -0
  86. package/src/utils/storage.js +40 -0
  87. package/src/vendor/autocomplete.js +515 -0
  88. package/src/vendor/formatDate.js +236 -0
  89. package/src/vendor/licenses/autocomplete.LICENSE.md +21 -0
  90. package/src/vendor/licenses/fecha.LICENSE.md +21 -0
  91. package/src/vendor/licenses/pretty-print-json.LICENSE.md +21 -0
  92. package/src/vendor/licenses/wysi.LICENSE.md +21 -0
  93. package/src/vendor/prettyPrintJson.js +108 -0
  94. package/src/vendor/wyzi.js +2024 -0
@@ -0,0 +1,888 @@
1
+ import HttpHeaders from '../constants/HttpHeaders.js';
2
+ import HttpMethods from '../constants/HttpMethods.js';
3
+ import FetchError from '../errors/FetchError.js';
4
+ import PJaxErrorEvent from '../events/PJaxErrorEvent.js';
5
+ import PJaxNavigatingEvent from '../events/PJaxNavigatingEvent.js';
6
+ import ajaxHeaders from '../utils/ajaxHeaders.js';
7
+ import formActionUrl from '../utils/formActionUrl.js';
8
+ import { formDataToUrl } from '../utils/formData.js';
9
+ import isSameOrigin from '../utils/isSameOrigin.js';
10
+ import { getContentType, isJson } from '../utils/response.js';
11
+ import BaseComponent from './BaseComponent.js';
12
+ import NillaInfo from './InfoDialog.js';
13
+ import defineElement from '../utils/defineElement.js';
14
+ import requestTimeout from '../utils/requestTimeout.js';
15
+
16
+ /**
17
+ * Enum for identifiers to query DOM elements.
18
+ * @readonly
19
+ * @enum {string}
20
+ */
21
+ const Elements = Object.freeze({
22
+ Target: 'target',
23
+ LoadingIndicator: 'loading-indicator',
24
+ InfoDialog: 'info-dialog',
25
+ });
26
+
27
+ /**
28
+ * Matches the start of a whole HTML document, after any white space and comments.
29
+ * @type {RegExp}
30
+ */
31
+ const FullDocumentRegex = /^(?:\s|<!--(?:(?!-->)[\s\S])*-->)*<(?:!doctype|html)\b/i;
32
+
33
+ /**
34
+ * How to scroll after new content loads.
35
+ * @readonly
36
+ * @enum {string}
37
+ */
38
+ const ScrollModes = Object.freeze({
39
+ /** Scroll to the top of the page. The default, for a PJax element that wraps the whole page. */
40
+ Top: 'top',
41
+ /**
42
+ * Scroll to the target, only if its top is above the viewport, or under a sticky header the target's
43
+ * `scroll-margin-top` allows for. For a PJax element that wraps part of a page.
44
+ */
45
+ Target: 'target',
46
+ /** Leave the scroll position alone. */
47
+ None: 'none',
48
+ });
49
+
50
+ /**
51
+ * History entry PJax created.
52
+ * @typedef {{ urlForHistory: string, key: string }} HistoryEntry
53
+ */
54
+
55
+ /**
56
+ * Web component for pushState + ajax support.
57
+ * Set `data-scroll` to `top` (default), `target`, or `none` to choose how the page scrolls after new content loads.
58
+ * Back and forward restore the scroll position the page had when it was left.
59
+ */
60
+ class PJax extends BaseComponent {
61
+ /**
62
+ * Version number to include with requests.
63
+ * @type {string}
64
+ */
65
+ #version = '';
66
+
67
+ /**
68
+ * List of file types to ignore when intercepting links.
69
+ * @type {string[]}
70
+ */
71
+ #ignoreFileTypes = ['pdf', 'doc', 'docx', 'zip', 'rar', '7z', 'gif', 'jpeg', 'jpg', 'png'];
72
+
73
+ /**
74
+ * Request timeout in milliseconds, from `data-timeout`.
75
+ * @type {number}
76
+ */
77
+ #timeout;
78
+
79
+ /**
80
+ * Name of attribute that indicates an element should be ignored.
81
+ * @type {string}
82
+ */
83
+ #excludeAttribute = 'data-pjax-no-follow';
84
+
85
+ /**
86
+ * Bound popState event listener.
87
+ * @type {(event: PopStateEvent) => Promise<void>|undefined}
88
+ */
89
+ #popStateListener;
90
+
91
+ /**
92
+ * Bound click event listener.
93
+ * @type {(event: MouseEvent) => Promise<void>|undefined}
94
+ */
95
+ #clickListener;
96
+
97
+ /**
98
+ * Bound submit event listener.
99
+ * @type {(event: SubmitEvent) => Promise<void>|undefined}
100
+ */
101
+ #submitListener;
102
+
103
+ /**
104
+ * Path of the current page to use when creating history.
105
+ * @type {string}
106
+ */
107
+ #currentUrlForHistory;
108
+
109
+ /**
110
+ * Url origin.
111
+ * @type {string}
112
+ */
113
+ #origin;
114
+
115
+ /**
116
+ * How to scroll after new content loads.
117
+ * @type {string}
118
+ */
119
+ #scrollMode = ScrollModes.Top;
120
+
121
+ /**
122
+ * Key of the history entry that's showing, used to remember its scroll position.
123
+ * @type {string}
124
+ */
125
+ #currentKey = '';
126
+
127
+ /**
128
+ * Scroll positions of the history entries visited, by key.
129
+ * @type {Map<string, { x: number, y: number }>}
130
+ */
131
+ #scrollPositions = new Map();
132
+
133
+ /**
134
+ * Scroll restoration setting to put back when the component is removed.
135
+ * @type {'auto'|'manual'|undefined}
136
+ */
137
+ #previousScrollRestoration;
138
+
139
+ /**
140
+ * Aborts the latest request.
141
+ * @type {AbortController|undefined}
142
+ */
143
+ #request;
144
+
145
+ /**
146
+ * Address that back or forward changed to, until its content loads.
147
+ * @type {string|undefined}
148
+ */
149
+ #unloadedUrl;
150
+
151
+ /**
152
+ * Number of history keys created, to keep keys unique.
153
+ * @type {number}
154
+ */
155
+ static #keyCount = 0;
156
+
157
+ /**
158
+ * Initialize pjax and record the current page in history.
159
+ */
160
+ constructor() {
161
+ super('pjax');
162
+
163
+ this.#timeout = requestTimeout(this.dataset.timeout);
164
+ if (this.dataset.version) {
165
+ this.#version = this.dataset.version;
166
+ }
167
+ if (Object.values(ScrollModes).includes(this.dataset.scroll)) {
168
+ this.#scrollMode = this.dataset.scroll;
169
+ }
170
+
171
+ this.#popStateListener = event => this.#onPopState(event);
172
+ this.#clickListener = event => this.#onClickListener(event);
173
+ this.#submitListener = event => this.#onSubmitListener(event);
174
+
175
+ // create a state object for the current page, with a key to remember its scroll position by
176
+ this.#currentKey = PJax.#newKey();
177
+ window.history.replaceState({ url: window.location.href, title: document.title, key: this.#currentKey }, '');
178
+
179
+ const currentUrl = new URL(window.location.href);
180
+ this.#currentUrlForHistory = this.#getUrlForHistory(currentUrl);
181
+ this.#origin = currentUrl.origin;
182
+ }
183
+
184
+ /**
185
+ * Start listening each time the component is added to the page, so moving it keeps it working.
186
+ */
187
+ connectedCallback() {
188
+ window.addEventListener('popstate', this.#popStateListener);
189
+ this.addEventListener('click', this.#clickListener);
190
+ this.addEventListener('submit', this.#submitListener);
191
+
192
+ // PJax replaces the content itself, so the browser can't restore scroll positions for these entries
193
+ if ('scrollRestoration' in window.history && this.#previousScrollRestoration === undefined) {
194
+ this.#previousScrollRestoration = window.history.scrollRestoration;
195
+ window.history.scrollRestoration = 'manual';
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Clean up when removing component. Listeners are kept, so they can be added again if the component returns.
201
+ */
202
+ disconnectedCallback() {
203
+ window.removeEventListener('popstate', this.#popStateListener);
204
+ this.removeEventListener('click', this.#clickListener);
205
+ this.removeEventListener('submit', this.#submitListener);
206
+ if (this.#previousScrollRestoration) {
207
+ window.history.scrollRestoration = this.#previousScrollRestoration;
208
+ this.#previousScrollRestoration = undefined;
209
+ }
210
+
211
+ super.disconnectedCallback();
212
+ }
213
+
214
+ /**
215
+ * Listens for back/forward navigation events and updates page accordingly.
216
+ * @param {PopStateEvent} event PopState event
217
+ */
218
+ async #onPopState(event) {
219
+ // entries added by the page itself aren't PJax's to load, but those from following a hash link, which have no state, are
220
+ if (event.state ? !event.state.url : !window.location.href.includes('#')) {
221
+ return;
222
+ }
223
+
224
+ // the browser has already changed the address
225
+ const url = new URL(window.location.href);
226
+ if (this.#isShowing(url)) {
227
+ this.#showEntry(url, event.state?.key);
228
+ return;
229
+ }
230
+
231
+ // history only holds GET requests, since the body of other methods isn't kept
232
+ const previousUrlForHistory = this.#currentUrlForHistory;
233
+ const previousKey = this.#currentKey;
234
+ this.#saveScrollPosition();
235
+ await this.#navigate(url, async () => {
236
+ // the user may have moved on before a listener let this proceed
237
+ if (window.location.href === url.href) {
238
+ // if the request fails, the page that's still showing stays the current entry
239
+ await this.#loadEntry(url, event.state?.key);
240
+ }
241
+ }, () => {
242
+ // browser already changed the url, so put back the url of the page that's still showing
243
+ window.history.pushState({ url: previousUrlForHistory, title: document.title, key: previousKey }, '', previousUrlForHistory);
244
+ });
245
+ }
246
+
247
+ /**
248
+ * Loads the history entry the browser is on.
249
+ * @param {URL} url URL of the entry.
250
+ * @param {string|undefined} key Key of the entry, if it has one.
251
+ */
252
+ async #loadEntry(url, key) {
253
+ this.#unloadedUrl = url.href;
254
+ const entry = { urlForHistory: this.#getUrlForHistory(url), key: key ?? PJax.#newKey() };
255
+ await this.#send(url, HttpMethods.GET, { entry });
256
+ }
257
+
258
+ /**
259
+ * Checks whether a URL is for the page that's showing, whatever its hash.
260
+ * @param {URL} url URL to check.
261
+ * @returns {boolean} True if the URL's content is showing.
262
+ */
263
+ #isShowing(url) {
264
+ const current = new URL(this.#currentUrlForHistory, this.#origin);
265
+ return url.pathname === current.pathname && url.search === current.search;
266
+ }
267
+
268
+ /**
269
+ * Goes to a history entry for the page that's showing, without loading it again.
270
+ * @param {URL} url URL of the entry.
271
+ * @param {string|undefined} key Key of the entry, if it has one.
272
+ */
273
+ #showEntry(url, key) {
274
+ // stop loading another entry, as the browser does
275
+ this.#request?.abort();
276
+ this.#currentUrlForHistory = this.#getUrlForHistory(url);
277
+
278
+ if (key) {
279
+ this.#saveScrollPosition();
280
+ this.#currentKey = key;
281
+ } else {
282
+ // the browser added the entry for a hash link, so it needs a key to remember its own position by
283
+ this.#currentKey = PJax.#newKey();
284
+ window.history.replaceState({ url: this.#currentUrlForHistory, title: document.title, key: this.#currentKey }, '');
285
+ }
286
+
287
+ const position = key ? this.#scrollPositions.get(key) : undefined;
288
+ if (position) {
289
+ window.scrollTo(position.x, position.y);
290
+ } else {
291
+ PJax.#findAnchor(url)?.scrollIntoView();
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Navigates unless a listener cancels it, giving the page a chance to stop it.
297
+ * @param {URL} url Url that will be loaded.
298
+ * @param {() => Promise<void>} navigate Performs the navigation.
299
+ * @param {() => void} [onCancel] Runs if a listener cancels the navigation and then decides to stay.
300
+ */
301
+ async #navigate(url, navigate, onCancel = () => {
302
+ }) {
303
+ const event = new PJaxNavigatingEvent(url, navigate, onCancel);
304
+ if (document.dispatchEvent(event)) {
305
+ await navigate();
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Link click listener.
311
+ * @param {Event} event Click event
312
+ */
313
+ async #onClickListener(event) {
314
+ // the page, or a component such as share, has already handled it
315
+ if (event.defaultPrevented) {
316
+ return;
317
+ }
318
+
319
+ let target = /** @type {HTMLAnchorElement} */ (event.target);
320
+ if (target.nodeName !== 'A') {
321
+ target = target.closest('a');
322
+ }
323
+
324
+ // Ignore clicks unless its a link
325
+ if (target?.nodeName !== 'A') {
326
+ return;
327
+ }
328
+
329
+ // Ignore non-primary or modified clicks so browser handles new tabs/windows
330
+ if (
331
+ event.button !== 0
332
+ || event.metaKey
333
+ || event.ctrlKey
334
+ || event.shiftKey
335
+ || event.altKey
336
+ ) {
337
+ return;
338
+ }
339
+
340
+ // Ignore links being edited, so clicking one places the cursor
341
+ if (target.closest('[contenteditable]:not([contenteditable="false"])')) {
342
+ return;
343
+ }
344
+
345
+ // Ignore links intended for new context or download
346
+ if ((target.target && target.target !== '_self') || target.hasAttribute('download')) {
347
+ return;
348
+ }
349
+
350
+ // Ignore clicks if link has the exclude class
351
+ if (this.#excludeAttribute && target.hasAttribute(this.#excludeAttribute)) {
352
+ return;
353
+ }
354
+
355
+ if (!URL.canParse(target.href)) {
356
+ return;
357
+ }
358
+
359
+ // Ignore external links
360
+ const url = new URL(target.href);
361
+ if (url.origin !== this.#origin) {
362
+ return;
363
+ }
364
+
365
+ // back or forward changed the address, but the content it's for didn't load
366
+ const unloaded = window.location.href === this.#unloadedUrl;
367
+
368
+ // Ignore anchors on the same page
369
+ if (!unloaded && url.pathname === window.location.pathname && url.search === window.location.search && url.href.includes('#')) {
370
+ // PJax restores the position on the way back, since it turns off the browser's own restoration
371
+ this.#saveScrollPosition();
372
+ return;
373
+ }
374
+
375
+ // Skip link if file type is within ignored types array
376
+ if (this.#ignoreFileTypes.includes(url.pathname.split('.').pop().toLowerCase())) {
377
+ return;
378
+ }
379
+
380
+ // Don't fire normal event
381
+ event.preventDefault();
382
+
383
+ // Take no action if we are already on requested page
384
+ if (window.location.href === target.href) {
385
+ if (unloaded) {
386
+ await this.#navigate(url, () => this.#loadEntry(url, window.history.state?.key));
387
+ }
388
+ return;
389
+ }
390
+
391
+ // links only ever GET: state changes belong in forms, which carry antiforgery tokens and aren't replayed by back
392
+ await this.#navigate(url, () => this.#send(url, HttpMethods.GET));
393
+ }
394
+
395
+ /**
396
+ * Form submit listener.
397
+ * @param {Event} event Submit event.
398
+ */
399
+ async #onSubmitListener(event) {
400
+ // the page has already handled it
401
+ if (event.defaultPrevented) {
402
+ return;
403
+ }
404
+
405
+ let target = /** @type {HTMLFormElement} */ (event.target);
406
+ if (target.nodeName !== 'FORM') {
407
+ target = target.closest('form');
408
+ }
409
+
410
+ // Ignore submit unless its a form
411
+ if (target?.nodeName !== 'FORM') {
412
+ return;
413
+ }
414
+
415
+ // Ignore submit if the form has the exclude attribute
416
+ if (this.#excludeAttribute && target.hasAttribute(this.#excludeAttribute)) {
417
+ return;
418
+ }
419
+
420
+ // the button that submitted can override the form, as it does without PJax
421
+ const { submitter } = /** @type {SubmitEvent} */ (event);
422
+ // read attributes, since a field named "action" or "method" hides the form's property of that name
423
+ const attribute = name => submitter?.getAttribute(`form${name}`) ?? target.getAttribute(name);
424
+
425
+ const browsingContext = attribute('target');
426
+ if ((browsingContext && browsingContext !== '_self') || attribute('method')?.toLowerCase() === 'dialog') {
427
+ return;
428
+ }
429
+
430
+ // Ignore submit if the origin doesn't match
431
+ const url = formActionUrl(attribute('action'));
432
+ if (url?.origin !== this.#origin) {
433
+ return;
434
+ }
435
+
436
+ // Don't fire normal event
437
+ event.preventDefault();
438
+
439
+ const methods = [submitter?.getAttribute('formmethod'), target.dataset.pjaxMethod, target.getAttribute('method')];
440
+ const method = methods.map(x => x?.toUpperCase()).find(x => x && x in HttpMethods) ?? HttpMethods.GET;
441
+
442
+ const formData = new FormData(target, submitter);
443
+ const timeout = requestTimeout(target.dataset.pjaxTimeout, this.#timeout);
444
+ if (method === HttpMethods.GET) {
445
+ // GET can't have a body, so the fields go in the query string; GET forms load a new page like a link,
446
+ // so listeners such as unsaved changes can stop them
447
+ const getUrl = formDataToUrl(url, formData);
448
+ await this.#navigate(getUrl, () => this.#send(getUrl, HttpMethods.GET, { timeout, form: target }));
449
+ return;
450
+ }
451
+
452
+ await this.#send(url, method, { body: formData, timeout, form: target });
453
+ }
454
+
455
+ /**
456
+ * Sends a request to the server, shows the loading indicator while it runs, and handles the result. Like a browser
457
+ * navigation, it stops the one before.
458
+ * @param {URL} url Url to request.
459
+ * @param {string} method Http method to use for request.
460
+ * @param {object} [options] Options for the request.
461
+ * @param {HistoryEntry} [options.entry] History entry that back or forward is loading. It becomes the current entry only
462
+ * once its content loads. Without one, a new entry is added.
463
+ * @param {FormData} [options.body] Form data to send, if any.
464
+ * @param {number} [options.timeout] Request timeout in milliseconds.
465
+ * @param {HTMLFormElement} [options.form] Form being sent, if any.
466
+ */
467
+ async #send(url, method, { entry, body, timeout = this.#timeout, form } = {}) {
468
+ // the form is the reason, so the stopped request can tell whether the same form replaced it
469
+ this.#request?.abort(form);
470
+ const request = new AbortController();
471
+ this.#request = request;
472
+ this.#showLoadingIndicator();
473
+
474
+ try {
475
+ const response = await fetch(url, {
476
+ method,
477
+ // the same address can also be a whole page, so neither use nor fill the browser's cache
478
+ cache: 'no-store',
479
+ signal: AbortSignal.any([request.signal, AbortSignal.timeout(timeout)]),
480
+ headers: this.#buildRequestHeaders(),
481
+ body,
482
+ });
483
+ // an app's own wrapper around fetch may not stop when told to
484
+ request.signal.throwIfAborted();
485
+
486
+ // a redirect is followed by fetch, so show what it led to, unless that needs a full load, such as a sign-in page
487
+ if (response.redirected && !(await PJax.#isFragment(response))) {
488
+ window.location.assign(response.url);
489
+ return;
490
+ }
491
+
492
+ if (!response.ok) {
493
+ throw new FetchError(`HTTP ${response.status}: ${response.statusText}`);
494
+ }
495
+
496
+ const pageUrl = response.redirected ? new URL(response.url) : url;
497
+ await this.#processResponse(pageUrl, response, method, entry);
498
+ } catch (error) {
499
+ if (!request.signal.aborted) {
500
+ this.#handleError(error, url, form);
501
+ } else if (request.signal.reason !== form) {
502
+ form?.dispatchEvent(new PJaxErrorEvent(url, { aborted: true }));
503
+ }
504
+ } finally {
505
+ // a newer request is still loading
506
+ if (this.#request === request) {
507
+ this.#hideLoadingIndicator();
508
+ }
509
+ }
510
+ }
511
+
512
+ /**
513
+ * Checks whether a response can be shown inside the target: HTML from this site that isn't a whole document, and that
514
+ * the server hasn't asked to be loaded afresh.
515
+ * @param {Response} response Fetch response.
516
+ * @returns {Promise<boolean>} True for a successful HTML fragment.
517
+ */
518
+ static async #isFragment(response) {
519
+ const usable = response.ok && !response.headers.has(HttpHeaders.PJaxRefresh) && isSameOrigin(response.url);
520
+ if (!(usable && getContentType(response).includes('text/html'))) {
521
+ return false;
522
+ }
523
+ // read a copy, so the body can still be read to show it
524
+ return !FullDocumentRegex.test(await response.clone().text());
525
+ }
526
+
527
+ /**
528
+ * Creates headers to use with requests to server.
529
+ * @returns {object} Headers for fetch request
530
+ */
531
+ #buildRequestHeaders() {
532
+ return ajaxHeaders({ [HttpHeaders.PJax]: true, [HttpHeaders.PJaxVersion]: this.#version });
533
+ }
534
+
535
+ /**
536
+ * Process a response from the server.
537
+ * @param {URL} requestUrl Requested url, or the one the request was redirected to.
538
+ * @param {Response} response Fetch response.
539
+ * @param {string} method Http method the request used.
540
+ * @param {HistoryEntry} [entry] History entry that was loaded, if it was back or forward.
541
+ */
542
+ async #processResponse(requestUrl, response, method, entry) {
543
+ if (response.headers.has(HttpHeaders.PJaxRefresh)) {
544
+ PJax.#loadAfresh(requestUrl, method);
545
+ return;
546
+ }
547
+
548
+ // the server has nothing to show, so stay on the page, as the browser does
549
+ if (response.status === 204) {
550
+ return;
551
+ }
552
+
553
+ // only HTML belongs in the page. the browser can show or download other content, but only by asking again with a GET
554
+ if (!getContentType(response).includes('text/html')) {
555
+ if (method !== HttpMethods.GET || isJson(response)) {
556
+ throw new FetchError(`Response from '${requestUrl}' isn't HTML.`);
557
+ }
558
+ PJax.#loadAfresh(requestUrl, method);
559
+ return;
560
+ }
561
+
562
+ const body = await response.text();
563
+
564
+ this.#unloadedUrl = undefined;
565
+ if (entry) {
566
+ this.#currentUrlForHistory = entry.urlForHistory;
567
+ this.#currentKey = entry.key;
568
+ }
569
+ this.#updateHistory(requestUrl, !entry, response);
570
+ const targetElement = await this.#updateTarget(body);
571
+ this.#updateTitle(response);
572
+ this.#updateDescription(response);
573
+ this.#updateCanonical(response);
574
+ this.#updateOgType(response);
575
+
576
+ // new pages follow the scroll mode, and back or forward returns to where the reader was
577
+ const savedPosition = entry ? this.#scrollPositions.get(this.#currentKey) : undefined;
578
+ const anchor = PJax.#findAnchor(requestUrl);
579
+ if (savedPosition) {
580
+ window.scrollTo(savedPosition.x, savedPosition.y);
581
+ } else {
582
+ this.#scrollAfterLoad(targetElement, anchor);
583
+ }
584
+
585
+ this.#focusNewContent(targetElement, !!savedPosition || !!anchor || this.#scrollMode === ScrollModes.None);
586
+ }
587
+
588
+ /**
589
+ * Does a full page load, as the server asked. Only a GET's address can be visited. After another method, such as a
590
+ * form post the server has already handled, the page that's showing is reloaded.
591
+ * @param {URL} requestUrl Requested url.
592
+ * @param {string} method Http method the request used.
593
+ */
594
+ static #loadAfresh(requestUrl, method) {
595
+ // visiting the address that's showing only scrolls when it has a hash
596
+ if (method !== HttpMethods.GET || requestUrl.href === window.location.href) {
597
+ window.location.reload();
598
+ return;
599
+ }
600
+ window.location.assign(requestUrl);
601
+ }
602
+
603
+ /**
604
+ * Finds the element a URL's hash points to, as the browser does for a full page load.
605
+ * @param {URL} url URL with or without a hash.
606
+ * @returns {HTMLElement|null} Element, or null if there isn't one.
607
+ */
608
+ static #findAnchor(url) {
609
+ const id = url.hash.slice(1);
610
+ try {
611
+ return document.getElementById(id) ?? document.getElementById(decodeURIComponent(id));
612
+ } catch {
613
+ // not a valid encoding
614
+ return null;
615
+ }
616
+ }
617
+
618
+ /**
619
+ * Scrolls the page after new content loads, as `data-scroll` says.
620
+ * @param {HTMLElement|undefined} targetElement Element the content was loaded into.
621
+ * @param {HTMLElement|null} anchor Element the address's hash points to, which is scrolled to instead.
622
+ */
623
+ #scrollAfterLoad(targetElement, anchor) {
624
+ if (this.#scrollMode === ScrollModes.None) {
625
+ return;
626
+ }
627
+ if (anchor) {
628
+ anchor.scrollIntoView();
629
+ return;
630
+ }
631
+ if (this.#scrollMode === ScrollModes.Target) {
632
+ // scroll-margin-top leaves room for a sticky header, both here and in scrollIntoView
633
+ const margin = targetElement ? Number.parseFloat(window.getComputedStyle(targetElement).scrollMarginTop) || 0 : 0;
634
+ if (targetElement && targetElement.getBoundingClientRect().top < margin) {
635
+ targetElement.scrollIntoView({ block: 'start' });
636
+ }
637
+ return;
638
+ }
639
+ window.scrollTo(0, 0);
640
+ }
641
+
642
+ /**
643
+ * Moves focus into the new content, so keyboard and screen reader users start there.
644
+ * Focuses the first `[autofocus]` element, or else the target itself.
645
+ * @param {HTMLElement|undefined} targetElement Element the content was loaded into.
646
+ * @param {boolean} keepScroll Focus without scrolling the focused element into view.
647
+ */
648
+ #focusNewContent(targetElement, keepScroll) {
649
+ if (!targetElement) {
650
+ return;
651
+ }
652
+
653
+ const autofocus = /** @type {HTMLElement|null} */ (targetElement.querySelector('[autofocus]'));
654
+ if (autofocus) {
655
+ autofocus.focus({ preventScroll: keepScroll });
656
+ return;
657
+ }
658
+
659
+ if (!targetElement.hasAttribute('tabindex')) {
660
+ targetElement.setAttribute('tabindex', '-1');
661
+ }
662
+ // scroll mode already placed the page, so focusing shouldn't move it again
663
+ targetElement.focus({ preventScroll: true });
664
+ }
665
+
666
+ /**
667
+ * Remembers the scroll position of the history entry that's showing.
668
+ */
669
+ #saveScrollPosition() {
670
+ if (this.#currentKey) {
671
+ this.#scrollPositions.set(this.#currentKey, { x: window.scrollX, y: window.scrollY });
672
+ }
673
+ }
674
+
675
+ /**
676
+ * Creates a key for a history entry.
677
+ * @returns {string} Unique key.
678
+ */
679
+ static #newKey() {
680
+ PJax.#keyCount += 1;
681
+ return `${Date.now().toString(36)}-${PJax.#keyCount}`;
682
+ }
683
+
684
+ /**
685
+ * Updates browser history for a successful response.
686
+ * @param {URL} requestUrl Requested url, or the one the request was redirected to.
687
+ * @param {boolean} updateHistory Update browser history if true.
688
+ * @param {Response} response Fetch response.
689
+ */
690
+ #updateHistory(requestUrl, updateHistory, response) {
691
+ if (!updateHistory) {
692
+ // going back or forward to an address that now redirects: keep the entry, with the address that's showing
693
+ if (response.redirected) {
694
+ this.#currentUrlForHistory = this.#getUrlForHistory(requestUrl);
695
+ const state = { url: this.#currentUrlForHistory, title: document.title, key: this.#currentKey };
696
+ window.history.replaceState(state, '', this.#currentUrlForHistory);
697
+ }
698
+ return;
699
+ }
700
+
701
+ const newUrl = response.headers.has(HttpHeaders.PJaxPushUrl)
702
+ ? response.headers.get(HttpHeaders.PJaxPushUrl)
703
+ : this.#getUrlForHistory(requestUrl);
704
+
705
+ if (this.#currentUrlForHistory !== newUrl) {
706
+ this.#saveScrollPosition();
707
+ this.#currentUrlForHistory = newUrl;
708
+ this.#currentKey = PJax.#newKey();
709
+ window.history.pushState({ url: this.#currentUrlForHistory, title: document.title, key: this.#currentKey }, '', this.#currentUrlForHistory);
710
+ }
711
+ }
712
+
713
+ /**
714
+ * Updates the page content.
715
+ * @param {string} body HTML content.
716
+ * @returns {Promise<HTMLElement|undefined>} Content target element, once the new content is in place.
717
+ */
718
+ async #updateTarget(body) {
719
+ const targetElement = /** @type {HTMLElement|undefined} */ (this.getElement(Elements.Target));
720
+ if (targetElement) {
721
+ if (document.startViewTransition) {
722
+ // wait for the swap, so scrolling and focus happen with the new content in place
723
+ await document.startViewTransition(() => {
724
+ targetElement.innerHTML = body;
725
+ }).updateCallbackDone;
726
+ } else {
727
+ targetElement.innerHTML = body;
728
+ }
729
+ }
730
+ return targetElement;
731
+ }
732
+
733
+ /**
734
+ * Updates the document title from the response header.
735
+ * @param {Response} response Fetch response.
736
+ */
737
+ #updateTitle(response) {
738
+ if (!response.headers.has(HttpHeaders.PJaxTitle)) {
739
+ return;
740
+ }
741
+
742
+ const title = response.headers.get(HttpHeaders.PJaxTitle);
743
+ if (title) {
744
+ document.title = title;
745
+
746
+ PJax.#setMeta('property', 'og:title', title);
747
+ }
748
+ }
749
+
750
+ /**
751
+ * Updates the description and `og:description` from the response header.
752
+ * @param {Response} response Fetch response.
753
+ */
754
+ #updateDescription(response) {
755
+ const description = response.headers.get(HttpHeaders.PJaxDescription);
756
+ if (description) {
757
+ PJax.#setMeta('name', 'description', description);
758
+ PJax.#setMeta('property', 'og:description', description);
759
+ }
760
+ }
761
+
762
+ /**
763
+ * Updates the canonical link and `og:url` from the response header. Without the header, those the page already has are
764
+ * pointed at the page now showing, so they don't go stale, and none are added.
765
+ * @param {Response} response Fetch response.
766
+ */
767
+ #updateCanonical(response) {
768
+ let linkCanonical = /** @type {HTMLLinkElement|null} */ (document.querySelector('link[rel="canonical"]'));
769
+
770
+ if (!response.headers.has(HttpHeaders.PJaxCanonical)) {
771
+ const metaOgUrl = /** @type {HTMLMetaElement|null} */ (document.querySelector('meta[property="og:url"]'));
772
+ if (linkCanonical) {
773
+ linkCanonical.href = PJax.#currentUrlOn(linkCanonical.getAttribute('href'));
774
+ }
775
+ if (metaOgUrl) {
776
+ metaOgUrl.content = PJax.#currentUrlOn(metaOgUrl.content);
777
+ }
778
+ return;
779
+ }
780
+
781
+ const canonical = response.headers.get(HttpHeaders.PJaxCanonical);
782
+ if (!canonical) {
783
+ return;
784
+ }
785
+
786
+ const canonicalUrl = new URL(canonical, PJax.#originOf(linkCanonical?.getAttribute('href')));
787
+ if (!linkCanonical) {
788
+ linkCanonical = document.createElement('link');
789
+ linkCanonical.rel = 'canonical';
790
+ document.head.appendChild(linkCanonical);
791
+ }
792
+ linkCanonical.href = canonicalUrl.href;
793
+ PJax.#setMeta('property', 'og:url', canonicalUrl.href);
794
+ }
795
+
796
+ /**
797
+ * Updates the Open Graph type from the response header.
798
+ * @param {Response} response Fetch response.
799
+ */
800
+ #updateOgType(response) {
801
+ const ogType = response.headers.get(HttpHeaders.PJaxOgType);
802
+ if (ogType) {
803
+ PJax.#setMeta('property', 'og:type', ogType);
804
+ }
805
+ }
806
+
807
+ /**
808
+ * Sets a meta tag's content, adding the tag if the page doesn't have it.
809
+ * @param {'name'|'property'} attribute Attribute that identifies the tag.
810
+ * @param {string} key Value of that attribute.
811
+ * @param {string} content New content.
812
+ */
813
+ static #setMeta(attribute, key, content) {
814
+ let meta = /** @type {HTMLMetaElement|null} */ (document.querySelector(`meta[${attribute}="${key}"]`));
815
+ if (!meta) {
816
+ meta = document.createElement('meta');
817
+ meta.setAttribute(attribute, key);
818
+ document.head.appendChild(meta);
819
+ }
820
+ meta.content = content;
821
+ }
822
+
823
+ /**
824
+ * Gets a URL's origin, so a site's public origin is kept even when it differs from the one being browsed.
825
+ * @param {string|null|undefined} url URL from an existing tag.
826
+ * @returns {string} Its origin, or the current page's if there's no usable URL.
827
+ */
828
+ static #originOf(url) {
829
+ return url && URL.canParse(url, window.location.href) ? new URL(url, window.location.href).origin : window.location.origin;
830
+ }
831
+
832
+ /**
833
+ * Gets the address of the page now showing, on the same origin as an existing tag's URL.
834
+ * @param {string|null} url URL the tag has now.
835
+ * @returns {string} Absolute URL with the current path and query string.
836
+ */
837
+ static #currentUrlOn(url) {
838
+ const current = new URL(PJax.#originOf(url));
839
+ current.pathname = window.location.pathname;
840
+ current.search = window.location.search;
841
+ return current.href;
842
+ }
843
+
844
+ /**
845
+ * Builds a URL string for history.
846
+ * @param {URL} url URL to build from.
847
+ * @returns {string} The URL without its origin.
848
+ */
849
+ #getUrlForHistory(url) {
850
+ return url.pathname + url.search + url.hash;
851
+ }
852
+
853
+ /**
854
+ * Shows the loading indicator.
855
+ */
856
+ #showLoadingIndicator() {
857
+ const indicator = this.getElement(Elements.LoadingIndicator);
858
+ indicator?.setAttribute('aria-busy', 'true');
859
+ this.getElement(Elements.Target)?.setAttribute('aria-busy', 'true');
860
+ }
861
+
862
+ /**
863
+ * Hides the loading indicator.
864
+ */
865
+ #hideLoadingIndicator() {
866
+ const indicator = this.getElement(Elements.LoadingIndicator);
867
+ indicator?.removeAttribute('aria-busy');
868
+ this.getElement(Elements.Target)?.removeAttribute('aria-busy');
869
+ }
870
+
871
+ /**
872
+ * Handles a failed request, by raising an event and showing the error dialog.
873
+ * @param {Error} error Error from fetch.
874
+ * @param {URL} url Url that was requested.
875
+ * @param {HTMLFormElement} [form] Form that was sent, if any.
876
+ */
877
+ #handleError(error, url, form) {
878
+ console.error(error.message);
879
+ (form ?? this).dispatchEvent(new PJaxErrorEvent(url));
880
+
881
+ const element = /** @type {NillaInfo} */ (this.getElement(Elements.InfoDialog));
882
+ element?.show();
883
+ }
884
+ }
885
+
886
+ defineElement('nilla-pjax', PJax);
887
+
888
+ export default PJax;