@avlcodemonkey/nilla-components 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,10 @@
1
+ /**
2
+ * Gets the address a form submits to. Pass the `action` or `formaction` attribute rather than the form's `action`
3
+ * property, which a field named "action" hides.
4
+ * @param {string|null|undefined} action Attribute value.
5
+ * @returns {URL|null} Absolute URL, which is the current page without an action, or null if the value isn't a URL.
6
+ */
7
+ export default function formActionUrl(action) {
8
+ const value = action || window.location.href;
9
+ return URL.canParse(value, document.baseURI) ? new URL(value, document.baseURI) : null;
10
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Convert form object to an object that can be JSON serialized.
3
+ * @param {HTMLFormElement} formElement Form element to convert
4
+ * @returns {object} New object with form data.
5
+ */
6
+ function formToObject(formElement) {
7
+ const result = {};
8
+
9
+ if (!formElement) {
10
+ return result;
11
+ }
12
+
13
+ new FormData(formElement)?.forEach((value, key) => {
14
+ if (!Object.hasOwn(result, key)) {
15
+ result[key] = value;
16
+ return;
17
+ }
18
+
19
+ if (!Array.isArray(result[key])) {
20
+ result[key] = [result[key]];
21
+ }
22
+ result[key].push(value);
23
+ });
24
+
25
+ return result;
26
+ }
27
+
28
+ /**
29
+ * Checks whether a form field is a checkbox or radio button.
30
+ * @param {Element} field Form field.
31
+ * @returns {boolean} True for checkboxes and radio buttons.
32
+ */
33
+ function isCheckable(field) {
34
+ return field.tagName === 'INPUT' && ['checkbox', 'radio'].includes(/** @type {HTMLInputElement} */ (field).type);
35
+ }
36
+
37
+ /**
38
+ * Sets the fields that share one name to the saved values.
39
+ * @param {Element[]} fields Fields with the name, in form order.
40
+ * @param {string[]} values Saved values for the name.
41
+ */
42
+ function setFields(fields, values) {
43
+ // checkboxes with a hidden companion, as ASP.NET and Rails render them, are restored through the checkbox alone
44
+ const hasCheckable = fields.some(isCheckable);
45
+ let next = 0;
46
+ for (const field of /** @type {(HTMLInputElement|HTMLSelectElement|HTMLTextAreaElement)[]} */ (fields)) {
47
+ if (field.disabled || (hasCheckable && field.type === 'hidden')) {
48
+ continue;
49
+ }
50
+ if (isCheckable(field)) {
51
+ /** @type {HTMLInputElement} */ (field).checked = values.includes(field.value);
52
+ } else if (field instanceof window.HTMLSelectElement && field.multiple) {
53
+ Array.from(field.options).forEach((option) => {
54
+ option.selected = values.includes(option.value);
55
+ });
56
+ } else {
57
+ field.value = values[next] ?? '';
58
+ next += 1;
59
+ }
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Use object properties to populate a form, such as one read earlier with `formToObject`.
65
+ * Checkboxes and radio buttons whose name isn't in the data are cleared, since unchecked fields aren't saved.
66
+ * @param {object} data Data to populate into form.
67
+ * @param {HTMLFormElement} formElement Form element to populate
68
+ */
69
+ function objectToForm(data, formElement) {
70
+ if (!(data && formElement)) {
71
+ return;
72
+ }
73
+
74
+ const fieldsByName = new Map();
75
+ for (const field of Array.from(formElement.elements)) {
76
+ const { name } = /** @type {HTMLInputElement} */ (field);
77
+ if (name) {
78
+ fieldsByName.set(name, [...(fieldsByName.get(name) ?? []), field]);
79
+ }
80
+ }
81
+
82
+ for (const [name, fields] of fieldsByName) {
83
+ if (Object.hasOwn(data, name)) {
84
+ const value = data[name];
85
+ const values = (Array.isArray(value) ? value : [value]).map(x => `${x ?? ''}`);
86
+ // set each name on its own so one field that can't be restored doesn't stop the rest
87
+ try {
88
+ setFields(fields, values);
89
+ } catch {
90
+ /* empty */
91
+ }
92
+ } else {
93
+ fields.filter(x => isCheckable(x) && !x.disabled).forEach((x) => {
94
+ x.checked = false;
95
+ });
96
+ }
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Builds the URL a GET form submits to: the form's fields replace the action's query string, as the browser does.
102
+ * File fields are left out, since a URL can't carry them.
103
+ * @param {string|URL} action Form action URL.
104
+ * @param {FormData} formData Form fields.
105
+ * @returns {URL} URL with the fields as its query string.
106
+ */
107
+ function formDataToUrl(action, formData) {
108
+ const url = new URL(action, window.location.href);
109
+ url.search = '';
110
+ for (const [key, value] of formData) {
111
+ if (typeof value === 'string') {
112
+ url.searchParams.append(key, value);
113
+ }
114
+ }
115
+ return url;
116
+ }
117
+
118
+ export { formDataToUrl, formToObject, objectToForm };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Helper functions used by the components, exported for apps that want the same behavior.
3
+ */
4
+ export { default as ajaxHeaders } from './ajaxHeaders.js';
5
+ export { default as defineElement } from './defineElement.js';
6
+ export { default as escape } from './escape.js';
7
+ export { default as filterArray } from './filterArray.js';
8
+ export { formDataToUrl, formToObject, objectToForm } from './formData.js';
9
+ export { default as indexedCompare } from './indexedCompare.js';
10
+ export { default as isSameOrigin } from './isSameOrigin.js';
11
+ export { getText, setLocale } from './locale.js';
12
+ export { default as registerTabTrap } from './registerTabTrap.js';
13
+ export { default as renderTemplate } from './renderTemplate.js';
14
+ export { getContentType, getResponseBody, isJson } from './response.js';
15
+ export { default as sortedCompare } from './sortedCompare.js';
16
+ export { default as autocomplete } from '../vendor/autocomplete.js';
17
+ export { formatDate } from '../vendor/formatDate.js';
18
+ export { prettyPrintJson } from '../vendor/prettyPrintJson.js';
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @typedef IndexedRow
3
+ * @type {object}
4
+ * @property {number} _index Unique identifier for the row.
5
+ */
6
+
7
+ /**
8
+ * Sorts rows by their original index.
9
+ * @param {IndexedRow} a First row.
10
+ * @param {IndexedRow} b Row to compare first row to.
11
+ * @returns {number} Negative if a is less than b, positive if a is greater than b, and zero if they are equal
12
+ */
13
+ export default function indexedCompare(a, b) {
14
+ if (a._index > b._index) {
15
+ return 1;
16
+ }
17
+ return a._index < b._index ? -1 : 0;
18
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Checks whether a URL points at the page's own origin. Components only fetch from their own site, so a
3
+ * `data-src-url` pointing elsewhere can't send requests, with the ajax headers, to a third party.
4
+ * @param {string|URL} url Absolute or relative URL.
5
+ * @returns {boolean} True when the URL has the same origin as the page.
6
+ */
7
+ export default function isSameOrigin(url) {
8
+ if (!URL.canParse(url, window.location.href)) {
9
+ return false;
10
+ }
11
+ return new URL(url, window.location.href).origin === window.location.origin;
12
+ }
@@ -0,0 +1,36 @@
1
+ import en from '../locales/en.json' with { type: 'json' };
2
+ import pageLanguage from './pageLanguage.js';
3
+
4
+ /**
5
+ * Text by language and then by key. English is always there, for text another language doesn't have.
6
+ * @type {Map<string, Record<string, string>>}
7
+ */
8
+ const locales = new Map([['en', en]]);
9
+
10
+ /**
11
+ * Adds a language, or changes some of one's text. Call it before the components are used, since text is read when it's shown.
12
+ * @param {string} lang Language tag, such as `fr` or `es-MX`.
13
+ * @param {Record<string, string>} texts Text by key, as in `locales/en.json`.
14
+ */
15
+ export function setLocale(lang, texts) {
16
+ const key = lang.toLowerCase();
17
+ locales.set(key, { ...locales.get(key), ...texts });
18
+ }
19
+
20
+ /**
21
+ * Gets text in the language of an element. A region's text, such as `es-MX`, comes before its language's, then English.
22
+ * @param {string} key Key of the text.
23
+ * @param {Element} [element] Element the text is for.
24
+ * @returns {string} Text, or the key if there's none.
25
+ */
26
+ export function getText(key, element) {
27
+ let lang = pageLanguage(element)?.toLowerCase() ?? '';
28
+ while (lang) {
29
+ const text = locales.get(lang)?.[key];
30
+ if (text) {
31
+ return text;
32
+ }
33
+ lang = lang.slice(0, Math.max(lang.lastIndexOf('-'), 0));
34
+ }
35
+ return locales.get('en')[key] ?? key;
36
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Fires the `input` and `change` events that typing would, after a component changes a form's content from code, so
3
+ * form listeners such as unsaved-changes warnings notice.
4
+ * @param {Element} element Field whose value changed, or the element whose fields were added, removed, or reordered.
5
+ */
6
+ export default function notifyChange(element) {
7
+ for (const type of ['input', 'change']) {
8
+ element.dispatchEvent(new Event(type, { bubbles: true }));
9
+ }
10
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Reads a number from a component's attribute, so an app can override a default.
3
+ * @param {string|undefined} value Attribute value.
4
+ * @param {number} fallback Default, used when the value is missing, empty, not a number, or too small.
5
+ * @param {object} [options] What counts as usable.
6
+ * @param {boolean} [options.allowZero] Whether zero is usable. Negative numbers never are.
7
+ * @param {boolean} [options.integer] Whether only whole numbers are usable.
8
+ * @returns {number} The value, or the fallback.
9
+ */
10
+ export default function numberSetting(value, fallback, { allowZero = false, integer = false } = {}) {
11
+ const number = value?.trim() ? Number(value) : Number.NaN;
12
+ const bigEnough = number > 0 || (allowZero && number === 0);
13
+ return Number.isFinite(number) && bigEnough && (!integer || Number.isInteger(number)) ? number : fallback;
14
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Gets the language of an element, from the nearest `lang` attribute, or of the page.
3
+ * @param {Element} [element] Element, or nothing for the page.
4
+ * @returns {string|undefined} Language tag, or undefined if there isn't a usable one.
5
+ */
6
+ export default function pageLanguage(element) {
7
+ const lang = element?.closest('[lang]')?.getAttribute('lang') || (typeof document !== 'undefined' && document.documentElement.lang);
8
+ try {
9
+ return lang ? Intl.getCanonicalLocales(lang)[0] : undefined;
10
+ } catch {
11
+ return undefined;
12
+ }
13
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Matches a date string that ends with a time zone: `Z`, `GMT`, `UTC`, an offset like `+05:30` or `-0500`, or a zone name
3
+ * in brackets, as `Date.toString` writes it.
4
+ * @type {RegExp}
5
+ */
6
+ const TimeZonePattern = /(?:z|gmt|utc|[+-]\d{2}:?\d{2}|\))$/i;
7
+
8
+ /**
9
+ * Matches a date without a time, which is already read as UTC.
10
+ * @type {RegExp}
11
+ */
12
+ export const DateOnlyPattern = /^\d{4}-\d{2}-\d{2}$/;
13
+
14
+ /**
15
+ * Parses a date from the server. One without a time zone is UTC, where `new Date` would read it as local time.
16
+ * @param {string} value Date string.
17
+ * @returns {Date} Parsed date, which is invalid if the string isn't a date.
18
+ */
19
+ export default function parseUtcDate(value) {
20
+ const text = value.trim();
21
+ return new Date(TimeZonePattern.test(text) || DateOnlyPattern.test(text) ? text : `${text}Z`);
22
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Makes a random ID in UUID format. `crypto.randomUUID` is only available on HTTPS pages and localhost, so other pages
3
+ * build the same kind of ID from `crypto.getRandomValues`, which works everywhere.
4
+ * @returns {string} Version 4 UUID.
5
+ */
6
+ export default function randomId() {
7
+ if (crypto.randomUUID) {
8
+ return crypto.randomUUID();
9
+ }
10
+
11
+ const bytes = [...crypto.getRandomValues(new Uint8Array(16))];
12
+ // the format fixes the version (4) and variant bits
13
+ bytes[6] = (bytes[6] % 16) + 0x40;
14
+ bytes[8] = (bytes[8] % 64) + 0x80;
15
+ const hex = bytes.map(x => x.toString(16).padStart(2, '0')).join('');
16
+ return hex.replace(/^(.{8})(.{4})(.{4})(.{4})/, '$1-$2-$3-$4-');
17
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Elements that can receive focus from the keyboard.
3
+ * @type {string}
4
+ */
5
+ const TabbableSelector = 'a[href], button, input:not([type="hidden"]), select, textarea, [tabindex]:not([tabindex="-1"])';
6
+
7
+ /**
8
+ * Registers a focus trap for the given dialog. Returns a cleanup function that removes all registered listeners.
9
+ * @param {HTMLDialogElement} dialog Dialog element to trap focus within.
10
+ * @returns {() => void} Cleanup function.
11
+ */
12
+ export default function registerTabTrap(dialog) {
13
+ const tabbableElements = /** @type {HTMLElement[]} */ (Array.from(dialog.querySelectorAll(TabbableSelector))
14
+ .filter((tabbableElement) => {
15
+ if (tabbableElement.matches(':disabled')) {
16
+ return false;
17
+ }
18
+
19
+ const computedStyle = window.getComputedStyle(tabbableElement);
20
+ return !(computedStyle.display === 'none' || computedStyle.visibility === 'hidden');
21
+ }));
22
+
23
+ if (tabbableElements.length === 0) {
24
+ return () => {
25
+ };
26
+ }
27
+
28
+ const firstTabbableElement = tabbableElements.at(0);
29
+ const lastTabbableElement = tabbableElements.at(-1);
30
+
31
+ const focusInHandler = (event) => {
32
+ if (!dialog.contains(event.target)) {
33
+ event.preventDefault();
34
+ firstTabbableElement.focus();
35
+ }
36
+ };
37
+ document.addEventListener('focusin', focusInHandler);
38
+
39
+ const firstKeydownHandler = (event) => {
40
+ if (event.key === 'Tab' && event.shiftKey) {
41
+ event.preventDefault();
42
+ lastTabbableElement.focus();
43
+ }
44
+ };
45
+ firstTabbableElement.addEventListener('keydown', firstKeydownHandler);
46
+
47
+ const lastKeydownHandler = (event) => {
48
+ if (event.key === 'Tab' && !event.shiftKey) {
49
+ event.preventDefault();
50
+ firstTabbableElement.focus();
51
+ }
52
+ };
53
+ lastTabbableElement.addEventListener('keydown', lastKeydownHandler);
54
+
55
+ return () => {
56
+ document.removeEventListener('focusin', focusInHandler);
57
+ firstTabbableElement.removeEventListener('keydown', firstKeydownHandler);
58
+ lastTabbableElement.removeEventListener('keydown', lastKeydownHandler);
59
+ };
60
+ }
@@ -0,0 +1,44 @@
1
+ import escape from './escape.js';
2
+
3
+ /**
4
+ * Matches a `{{key}}` placeholder. Keys can hold any characters but braces; `#` and `/` start the if-block syntax instead.
5
+ * @type {RegExp}
6
+ */
7
+ const placeholderRegex = /{{(?![#/])([^{}]+)}}/g;
8
+
9
+ // regex for handling ifs
10
+ const ifRegex = /{{#if\s*(!)?(\w+)}}([\s\S]+?){{\/if}}/g;
11
+
12
+ /**
13
+ * Converts a template string with replacement values into usable HTML.
14
+ * @param {string} template A template string containing replacement values and conditional blocks.
15
+ * @param {object} data An object whose keys match the replacement strings in your template.
16
+ * @param {boolean} shouldEscape If true escape HTML characters in the replacement values.
17
+ * @returns {string} Updated template string with replacements made.
18
+ * @description Supports simple replacements using `{{key}}` syntax, and conditional blocks using `{{#if condition}}...{{/if}}` syntax.
19
+ * No nested properties or conditionals. Placeholders without a matching key render as nothing. Every
20
+ * placeholder is filled in one pass, so a value that looks like `{{other}}` stays as that text.
21
+ */
22
+ export default function renderTemplate(template, data, shouldEscape = true) {
23
+ let result = template ?? '';
24
+
25
+ // if the template is empty, return an empty string
26
+ if (result === '') {
27
+ return '';
28
+ }
29
+ // if the data is not an object, return the template as is
30
+ if (typeof data !== 'object' || data === null) {
31
+ return result;
32
+ }
33
+
34
+ // keep or drop each block. a function's result is inserted as is, where "$&" in a string would insert the block again
35
+ result = result.replace(ifRegex, (_block, not, key, content) => (Boolean(data[key]) !== Boolean(not) ? content : ''));
36
+
37
+ // loop through each property of the data
38
+ // one pass, so values are never read again as template
39
+ return result.replace(placeholderRegex, (placeholder, key) => {
40
+ const raw = Object.hasOwn(data, key) ? data[key] : undefined;
41
+ const value = raw === undefined || raw === null ? '' : `${raw}`;
42
+ return shouldEscape ? escape(value) : value;
43
+ });
44
+ }
@@ -0,0 +1,12 @@
1
+ import DefaultTimeout from '../constants/Fetch.js';
2
+ import numberSetting from './numberSetting.js';
3
+
4
+ /**
5
+ * Gets a request timeout from an attribute given in seconds.
6
+ * @param {string|undefined} seconds Attribute value, such as `data-timeout`.
7
+ * @param {number} [fallback] Timeout in milliseconds when the attribute isn't a positive number.
8
+ * @returns {number} Timeout in milliseconds.
9
+ */
10
+ export default function requestTimeout(seconds, fallback = DefaultTimeout) {
11
+ return numberSetting(seconds, fallback / 1000) * 1000;
12
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Get content type from reponse.
3
+ * @param {Response} response Response object to get type from.
4
+ * @returns {string} Content type.
5
+ */
6
+ function getContentType(response) {
7
+ return response?.headers.get('content-type')?.toLowerCase() ?? '';
8
+ }
9
+
10
+ /**
11
+ * Check if response is json.
12
+ * @param {Response} response Response object to check.
13
+ * @returns {boolean} True if response is json.
14
+ */
15
+ function isJson(response) {
16
+ return getContentType(response).includes('application/json');
17
+ }
18
+
19
+ /**
20
+ * Get the body from the response.
21
+ * @param {Response} response Response object to get body from.
22
+ * @returns {Promise<string>} Response content.
23
+ */
24
+ async function getResponseBody(response) {
25
+ return isJson(response) ? response.json() : response.text();
26
+ }
27
+
28
+ export { getContentType, isJson, getResponseBody };
@@ -0,0 +1,67 @@
1
+ import SortDirection from '../constants/SortDirection.js';
2
+ import TableSort from '../models/TableSort.js';
3
+ import pageLanguage from './pageLanguage.js';
4
+
5
+ /**
6
+ * Collator for the page's language, cached until the language changes.
7
+ * @type {{ lang: string|undefined, collator: Intl.Collator }|undefined}
8
+ */
9
+ let cachedCollator;
10
+
11
+ /**
12
+ * Gets a collator that compares text the way readers of the page's language expect: ignoring case, with accents in
13
+ * their natural place, and digit runs compared as numbers, so "9" comes before "10".
14
+ * @returns {Intl.Collator} Collator for the page's `<html lang>`, or the browser's language without one.
15
+ */
16
+ function getCollator() {
17
+ const lang = pageLanguage();
18
+ if (!cachedCollator || cachedCollator.lang !== lang) {
19
+ cachedCollator = { lang, collator: new Intl.Collator(lang, { numeric: true, sensitivity: 'base' }) };
20
+ }
21
+ return cachedCollator.collator;
22
+ }
23
+
24
+ /**
25
+ * Compares two values of one property, ascending.
26
+ * @param {unknown} a First value.
27
+ * @param {unknown} b Second value.
28
+ * @returns {number} -1, 0, or 1.
29
+ */
30
+ function compareValues(a, b) {
31
+ // numbers and booleans keep their own order; everything else compares as text
32
+ if ((typeof a === 'number' && typeof b === 'number') || (typeof a === 'boolean' && typeof b === 'boolean')) {
33
+ return a < b ? -1 : Number(a > b);
34
+ }
35
+ return Math.sign(getCollator().compare(`${a}`, `${b}`));
36
+ }
37
+
38
+ /**
39
+ * Sorts rows based on Sort property.
40
+ * @param {Array<TableSort>} sorts Array of TableSort objects.
41
+ * @param {object} a First element for comparison.
42
+ * @param {object} b Second element for comparison.
43
+ * @returns {number} Negative if a is less than b, positive if a is greater than b, and zero if they are equal
44
+ */
45
+ export default function sortedCompare(sorts, a, b) {
46
+ for (const sort of sorts) {
47
+ const aa = a[sort.property];
48
+ const bb = b[sort.property];
49
+ const aMissing = aa === null || aa === undefined;
50
+ const bMissing = bb === null || bb === undefined;
51
+
52
+ // missing values sort last in both directions. two missing values are equal, so the next sort decides
53
+ if (aMissing || bMissing) {
54
+ if (aMissing && bMissing) {
55
+ continue;
56
+ }
57
+ return aMissing ? 1 : -1;
58
+ }
59
+
60
+ const result = compareValues(aa, bb);
61
+ if (result !== 0) {
62
+ return sort.direction === SortDirection.Asc ? result : -result;
63
+ }
64
+ }
65
+
66
+ return 0;
67
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Browser storage that never throws. Storage can be blocked, in which case even reading `window.localStorage` fails, or
3
+ * full. Saved settings are a convenience, so components carry on without them.
4
+ */
5
+
6
+ /**
7
+ * @typedef {'localStorage'|'sessionStorage'} StorageType
8
+ */
9
+
10
+ /**
11
+ * Reads a saved value.
12
+ * @param {StorageType} type Which storage to use.
13
+ * @param {string} key Key the value was saved under.
14
+ * @returns {string|null} Saved value, or null if there isn't one or storage can't be used.
15
+ */
16
+ export function readStorage(type, key) {
17
+ try {
18
+ return window[type].getItem(key);
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ /**
25
+ * Saves a value, or removes it.
26
+ * @param {StorageType} type Which storage to use.
27
+ * @param {string} key Key to save the value under.
28
+ * @param {string|null} value Value to save, or null to remove it.
29
+ */
30
+ export function writeStorage(type, key, value) {
31
+ try {
32
+ if (value === null) {
33
+ window[type].removeItem(key);
34
+ } else {
35
+ window[type].setItem(key, value);
36
+ }
37
+ } catch {
38
+ // the setting just isn't remembered
39
+ }
40
+ }