@sv443-network/userutils 8.3.3 → 9.0.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/README.md CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  <!-- #region Description -->
4
4
  ## UserUtils
5
- Lightweight library with various utilities for userscripts - register listeners for when CSS selectors exist, intercept events, create persistent & synchronous data stores, modify the DOM more easily and more.
6
-
5
+ Lightweight library with various utilities for userscripts - register listeners for when CSS selectors exist, intercept events, create persistent & synchronous data stores, modify the DOM more easily and much more.
7
6
  Contains builtin TypeScript declarations. Supports ESM and CJS imports via a bundler and global declaration via `@require`
7
+ The library also works in any DOM environment without the [GreaseMonkey API](https://wiki.greasespot.net/Greasemonkey_Manual:API), but some features will be unavailable or limited.
8
8
 
9
9
  You may want to check out my [template for userscripts in TypeScript](https://github.com/Sv443/Userscript.ts) that you can use to get started quickly. It also includes this library by default.
10
10
  If you like using this library, please consider [supporting the development ❤️](https://github.com/sponsors/Sv443)
@@ -23,7 +23,8 @@ View the documentation of previous major releases:
23
23
  </sup>
24
24
  <sub>
25
25
 
26
- <a href="https://github.com/Sv443-Network/UserUtils/blob/v7.3.0/README.md" rel="noopener noreferrer">7.3.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v6.3.0/README.md" rel="noopener noreferrer">6.3.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v5.0.1/README.md" rel="noopener noreferrer">5.0.1</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v4.2.1/README.md" rel="noopener noreferrer">4.2.1</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v3.0.0/README.md" rel="noopener noreferrer">3.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v2.0.1/README.md" rel="noopener noreferrer">2.0.1</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v1.2.0/README.md" rel="noopener noreferrer">1.2.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v0.5.3/README.md" rel="noopener noreferrer">0.5.3</a>
26
+ <!-- <a href="https://github.com/Sv443-Network/UserUtils/blob/vX.0.0/docs.md" rel="noopener noreferrer">X.0.0</a>, -->
27
+ <a href="https://github.com/Sv443-Network/UserUtils/blob/v8.0.0/README.md" rel="noopener noreferrer">8.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v7.0.0/README.md" rel="noopener noreferrer">7.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v6.0.0/README.md" rel="noopener noreferrer">6.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v5.0.0/README.md" rel="noopener noreferrer">5.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v4.0.0/README.md" rel="noopener noreferrer">4.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v3.0.0/README.md" rel="noopener noreferrer">3.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v2.0.0/README.md" rel="noopener noreferrer">2.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v1.0.0/README.md" rel="noopener noreferrer">1.0.0</a>, <a href="https://github.com/Sv443-Network/UserUtils/blob/v0.5.3/README.md" rel="noopener noreferrer">0.5.3</a>
27
28
 
28
29
  </sub>
29
30
  </div>
@@ -32,63 +33,75 @@ View the documentation of previous major releases:
32
33
  <!-- #region Table of Contents -->
33
34
  ## Table of Contents:
34
35
  - [**Installation**](#installation)
35
- - [**Preamble** (info about the documentation)](#preamble)
36
36
  - [**License**](#license)
37
- - [**Features**](#features)
38
- - [**DOM:**](#dom)
39
- - [`SelectorObserver`](#selectorobserver) - class that manages listeners that are called when selectors are found in the DOM
40
- - [`getUnsafeWindow()`](#getunsafewindow) - get the unsafeWindow object or fall back to the regular window object
41
- - [`addParent()`](#addparent) - add a parent element around another element
42
- - [`addGlobalStyle()`](#addglobalstyle) - add a global style to the page
43
- - [`preloadImages()`](#preloadimages) - preload images into the browser cache for faster loading later on
44
- - [`openInNewTab()`](#openinnewtab) - open a link in a new tab
45
- - [`interceptEvent()`](#interceptevent) - conditionally intercepts events registered by `addEventListener()` on any given EventTarget object
46
- - [`interceptWindowEvent()`](#interceptwindowevent) - conditionally intercepts events registered by `addEventListener()` on the window object
47
- - [`isScrollable()`](#isscrollable) - check if an element has a horizontal or vertical scroll bar
48
- - [`observeElementProp()`](#observeelementprop) - observe changes to an element's property that can't be observed with MutationObserver
49
- - [`getSiblingsFrame()`](#getsiblingsframe) - returns a frame of an element's siblings, with a given alignment and size
50
- - [`setInnerHtmlUnsafe()`](#setinnerhtmlunsafe) - set the innerHTML of an element using a [Trusted Types policy](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API) without sanitizing or escaping it
51
- - [**Math:**](#math)
52
- - [`clamp()`](#clamp) - constrain a number between a min and max value
53
- - [`mapRange()`](#maprange) - map a number from one range to the same spot in another range
54
- - [`randRange()`](#randrange) - generate a random number between a min and max boundary
55
- - [**Misc:**](#misc)
56
- - [`DataStore`](#datastore) - class that manages a hybrid sync & async persistent JSON database, including data migration
57
- - [`DataStoreSerializer`](#datastoreserializer) - class for importing & exporting data of multiple DataStore instances, including compression, checksumming and running migrations
58
- - [`Dialog`](#dialog) - class for creating custom modal dialogs with a promise-based API and a generic, default style
59
- - [`NanoEmitter`](#nanoemitter) - tiny event emitter class with a focus on performance and simplicity (based on [nanoevents](https://npmjs.com/package/nanoevents))
60
- - [`autoPlural()`](#autoplural) - automatically pluralize a string
61
- - [`pauseFor()`](#pausefor) - pause the execution of a function for a given amount of time
62
- - [`debounce()`](#debounce) - call a function only once in a series of calls, after or before a given timeout
63
- - [`fetchAdvanced()`](#fetchadvanced) - wrapper around the fetch API with a timeout option
64
- - [`insertValues()`](#insertvalues) - insert values into a string at specified placeholders
65
- - [`compress()`](#compress) - compress a string with Gzip or Deflate
66
- - [`decompress()`](#decompress) - decompress a previously compressed string
67
- - [`computeHash()`](#computehash) - compute the hash / checksum of a string or ArrayBuffer
68
- - [`randomId()`](#randomid) - generate a random ID of a given length and radix
69
- - [**Arrays:**](#arrays)
70
- - [`randomItem()`](#randomitem) - returns a random item from an array
71
- - [`randomItemIndex()`](#randomitemindex) - returns a tuple of a random item and its index from an array
72
- - [`takeRandomItem()`](#takerandomitem) - returns a random item from an array and mutates it to remove the item
73
- - [`randomizeArray()`](#randomizearray) - returns a copy of the array with its items in a random order
74
- - [**Translation:**](#translation)
75
- - [`tr()`](#tr) - simple translation of a string to another language
76
- - [`tr.forLang()`](#trforlang) - specify a language besides the currently set one for the translation
77
- - [`tr.addLanguage()`](#traddlanguage) - add a language and its translations
78
- - [`tr.setLanguage()`](#trsetlanguage) - set the currently active language for translations
79
- - [`tr.getLanguage()`](#trgetlanguage) - returns the currently active language
80
- - [`tr.getTranslations()`](#trgettranslations) - returns the translations for the given language or the currently active one
81
- - [**Colors:**](#colors)
82
- - [`hexToRgb()`](#hextorgb) - convert a hex color string to an RGB or RGBA value tuple
83
- - [`rgbToHex()`](#rgbtohex) - convert RGB or RGBA values to a hex color string
84
- - [`lightenColor()`](#lightencolor) - lighten a CSS color string (hex, rgb or rgba) by a given percentage
85
- - [`darkenColor()`](#darkencolor) - darken a CSS color string (hex, rgb or rgba) by a given percentage
86
- - [**Utility types for TypeScript:**](#utility-types)
87
- - [`Stringifiable`](#stringifiable) - any value that is a string or can be converted to one (implicitly or explicitly)
88
- - [`NonEmptyArray`](#nonemptyarray) - any array that should have at least one item
89
- - [`NonEmptyString`](#nonemptystring) - any string that should have at least one character
90
- - [`LooseUnion`](#looseunion) - a union that gives autocomplete in the IDE but also allows any other value of the same type
91
- - [`Prettify`](#prettify) - expands a complex type into a more readable format while keeping functionality the same
37
+ - [**Preamble** (info about the documentation)](./docs.md#preamble)
38
+ - [**Features**](./docs.md#features)
39
+ - [**DOM:**](./docs.md#dom)
40
+ - [`SelectorObserver`](./docs.md#selectorobserver) - class that manages listeners that are called when selectors are found in the DOM
41
+ - [`getUnsafeWindow()`](./docs.md#getunsafewindow) - get the unsafeWindow object or fall back to the regular window object
42
+ - [`addParent()`](./docs.md#addparent) - add a parent element around another element
43
+ - [`addGlobalStyle()`](./docs.md#addglobalstyle) - add a global style to the page
44
+ - [`preloadImages()`](./docs.md#preloadimages) - preload images into the browser cache for faster loading later on
45
+ - [`openInNewTab()`](./docs.md#openinnewtab) - open a link in a new tab
46
+ - [`interceptEvent()`](./docs.md#interceptevent) - conditionally intercepts events registered by `addEventListener()` on any given EventTarget object
47
+ - [`interceptWindowEvent()`](./docs.md#interceptwindowevent) - conditionally intercepts events registered by `addEventListener()` on the window object
48
+ - [`isScrollable()`](./docs.md#isscrollable) - check if an element has a horizontal or vertical scroll bar
49
+ - [`observeElementProp()`](./docs.md#observeelementprop) - observe changes to an element's property that can't be observed with MutationObserver
50
+ - [`getSiblingsFrame()`](./docs.md#getsiblingsframe) - returns a frame of an element's siblings, with a given alignment and size
51
+ - [`setInnerHtmlUnsafe()`](./docs.md#setinnerhtmlunsafe) - set the innerHTML of an element using a [Trusted Types policy](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API) without sanitizing or escaping it
52
+ - [**Math:**](./docs.md#math)
53
+ - [`clamp()`](./docs.md#clamp) - constrain a number between a min and max value
54
+ - [`mapRange()`](./docs.md#maprange) - map a number from one range to the same spot in another range
55
+ - [`randRange()`](./docs.md#randrange) - generate a random number between a min and max boundary
56
+ - [`digitCount()`](./docs.md#digitcount) - calculate the amount of digits in a number
57
+ - [**Misc:**](./docs.md#misc)
58
+ - [`DataStore`](./docs.md#datastore) - class that manages a hybrid sync & async persistent JSON database, including data migration
59
+ - [`DataStoreSerializer`](./docs.md#datastoreserializer) - class for importing & exporting data of multiple DataStore instances, including compression, checksumming and running migrations
60
+ - [`Dialog`](./docs.md#dialog) - class for creating custom modal dialogs with a promise-based API and a generic, default style
61
+ - [`NanoEmitter`](./docs.md#nanoemitter) - tiny event emitter class with a focus on performance and simplicity (based on [nanoevents](https://npmjs.com/package/nanoevents))
62
+ - [`Debouncer`](./docs.md#debouncer) - class for debouncing function calls with a given timeout
63
+ - [`debounce()`](./docs.md#debounce) - function wrapper for the Debouncer class for easier usage
64
+ - [`autoPlural()`](./docs.md#autoplural) - automatically pluralize a string
65
+ - [`pauseFor()`](./docs.md#pausefor) - pause the execution of a function for a given amount of time
66
+ - [`fetchAdvanced()`](./docs.md#fetchadvanced) - wrapper around the fetch API with a timeout option
67
+ - [`insertValues()`](./docs.md#insertvalues) - insert values into a string at specified placeholders
68
+ - [`compress()`](./docs.md#compress) - compress a string with Gzip or Deflate
69
+ - [`decompress()`](./docs.md#decompress) - decompress a previously compressed string
70
+ - [`computeHash()`](./docs.md#computehash) - compute the hash / checksum of a string or ArrayBuffer
71
+ - [`randomId()`](./docs.md#randomid) - generate a random ID of a given length and radix
72
+ - [`consumeGen()`](./docs.md#consumegen) - consumes a ValueGen and returns the value
73
+ - [`consumeStringGen()`](./docs.md#consumestringgen) - consumes a StringGen and returns the string
74
+ - [**Arrays:**](./docs.md#arrays)
75
+ - [`randomItem()`](./docs.md#randomitem) - returns a random item from an array
76
+ - [`randomItemIndex()`](./docs.md#randomitemindex) - returns a tuple of a random item and its index from an array
77
+ - [`takeRandomItem()`](./docs.md#takerandomitem) - returns a random item from an array and mutates it to remove the item
78
+ - [`randomizeArray()`](./docs.md#randomizearray) - returns a copy of the array with its items in a random order
79
+ - [**Translation:**](./docs.md#translation)
80
+ - [`tr.for()`](./docs.md#trfor) - translates a key for the specified language
81
+ - [`tr.use()`](./docs.md#truse) - creates a translation function for the specified language
82
+ - [`tr.hasKey()`](./docs.md#trhaskey) - checks if a key exists in the given language
83
+ - [`tr.addTranslations()`](./docs.md#traddtranslations) - add a flat or recursive translation object for a language
84
+ - [`tr.getTranslations()`](./docs.md#trgettranslations) - returns the translation object for a language
85
+ - [`tr.deleteTranslations()`](./docs.md#trdeletetranslations) - delete the translation object for a language
86
+ - [`tr.setFallbackLanguage()`](./docs.md#trsetfallbacklanguage) - set the fallback language used when a key is not found in the given language
87
+ - [`tr.getFallbackLanguage()`](./docs.md#trgetfallbacklanguage) - returns the fallback language
88
+ - [`tr.addTransform()`](./docs.md#traddtransform) - adds a transform function to the translation system for custom argument insertion and much more
89
+ - [`tr.deleteTransform()`](./docs.md#trdeletetransform) - removes a transform function
90
+ - [`tr.transforms`](./docs.md#trtransforms) - predefined transform functions for quickly adding custom argument insertion
91
+ - [`TrKeys`](./docs.md#trkeys) - generic type that extracts all keys from a flat or recursive translation object into a union
92
+ - [**Colors:**](./docs.md#colors)
93
+ - [`hexToRgb()`](./docs.md#hextorgb) - convert a hex color string to an RGB or RGBA value tuple
94
+ - [`rgbToHex()`](./docs.md#rgbtohex) - convert RGB or RGBA values to a hex color string
95
+ - [`lightenColor()`](./docs.md#lightencolor) - lighten a CSS color string (hex, rgb or rgba) by a given percentage
96
+ - [`darkenColor()`](./docs.md#darkencolor) - darken a CSS color string (hex, rgb or rgba) by a given percentage
97
+ - [**Utility types for TypeScript:**](./docs.md#utility-types)
98
+ - [`Stringifiable`](./docs.md#stringifiable) - any value that is a string or can be converted to one (implicitly or explicitly)
99
+ - [`NonEmptyArray`](./docs.md#nonemptyarray) - any array that should have at least one item
100
+ - [`NonEmptyString`](./docs.md#nonemptystring) - any string that should have at least one character
101
+ - [`LooseUnion`](./docs.md#looseunion) - a union that gives autocomplete in the IDE but also allows any other value of the same type
102
+ - [`Prettify`](./docs.md#prettify) - expands a complex type into a more readable format while keeping functionality the same
103
+ - [`ValueGen`](./docs.md#valuegen) - a "generator" value that allows for super flexible value typing and declaration
104
+ - [`StringGen`](./docs.md#stringgen) - a "generator" string that allows for super flexible string typing and declaration, including enhanced support for unions
92
105
 
93
106
  <br><br>
94
107
 
@@ -107,10 +120,13 @@ Shameless plug: I made a [template for userscripts in TypeScript](https://github
107
120
  Then import it in your script as usual:
108
121
 
109
122
  ```ts
123
+ // on Node:
110
124
  import { addGlobalStyle } from "@sv443-network/userutils";
111
125
 
112
- // or just import everything (not recommended because of worse treeshaking support):
126
+ // on Deno:
127
+ import { addGlobalStyle } from "jsr:@sv443-network/userutils";
113
128
 
129
+ // you can also import the entire library as an object (not recommended because of worse treeshaking support):
114
130
  import * as UserUtils from "@sv443-network/userutils";
115
131
  ```
116
132
 
@@ -170,2504 +186,17 @@ Shameless plug: I made a [template for userscripts in TypeScript](https://github
170
186
 
171
187
  <br><br>
172
188
 
173
- <!-- #region Preamble -->
174
- ## Preamble:
175
- This library is written in TypeScript and contains builtin TypeScript declarations.
176
-
177
- Each feature has example code that can be expanded by clicking on the text "Example - click to view".
178
- The usages and examples are written in TypeScript and use ESM import syntax, but the library can also be used in plain JavaScript after removing the type annotations (and changing the imports if you are using CommonJS or the global declaration).
179
- If the usage section contains multiple usages of the function, each occurrence represents an overload and you can choose which one you want to use.
180
-
181
- Some features require the `@run-at` or `@grant` directives to be tweaked in the userscript header or have other specific requirements and limitations.
182
- Those will be listed in a section marked by a warning emoji (⚠️) each.
183
-
184
- If you need help with something, please [create a new discussion](https://github.com/Sv443-Network/UserUtils/discussions) or [join my Discord server.](https://dc.sv443.net/)
185
- For submitting bug reports or feature requests, please use the [GitHub issue tracker.](https://github.com/Sv443-Network/UserUtils/issues)
186
-
187
- <br><br>
188
-
189
189
  <!-- #region License -->
190
190
  ## License:
191
191
  This library is licensed under the MIT License.
192
192
  See the [license file](./LICENSE.txt) for details.
193
193
 
194
- <br><br>
195
-
196
- <!-- #region Features -->
197
- ## Features:
198
-
199
- <br>
200
-
201
- <!-- #region DOM -->
202
- ## DOM:
203
-
204
- ### SelectorObserver
205
- Usage:
206
- ```ts
207
- new SelectorObserver(baseElement: Element, options?: SelectorObserverOptions)
208
- new SelectorObserver(baseElementSelector: string, options?: SelectorObserverOptions)
209
- ```
210
-
211
- A class that manages listeners that are called when elements at given selectors are found in the DOM.
212
- It is useful for userscripts that need to wait for elements to be added to the DOM at an indeterminate point in time before they can be interacted with.
213
- By default, it uses the MutationObserver API to observe for any element changes, and as such is highly customizable, but can also be configured to run on a fixed interval.
214
-
215
- The constructor takes a `baseElement`, which is a parent of the elements you want to observe.
216
- If a selector string is passed instead, it will be used to find the element.
217
- If you want to observe the entire document, you can pass `document.body` - ⚠️ you should only use this to initialize other SelectorObserver instances, and never run continuous listeners on this instance, as the performance impact can be massive!
218
-
219
- The `options` parameter is optional and will be passed to the MutationObserver that is used internally.
220
- The MutationObserver options present by default are `{ childList: true, subtree: true }` - you may see the [MutationObserver.observe() documentation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe#options) for more information and a list of options.
221
- For example, if you want to trigger the listeners when certain attributes change, pass `{ attributeFilter: ["class", "data-my-attribute"] }`
222
-
223
- Additionally, there are the following extra options:
224
- - `disableOnNoListeners` - whether to disable the SelectorObserver when there are no listeners left (defaults to false)
225
- - `enableOnAddListener` - whether to enable the SelectorObserver when a new listener is added (defaults to true)
226
- - `defaultDebounce` - if set to a number, this debounce will be applied to every listener that doesn't have a custom debounce set (defaults to 0)
227
- - `defaultDebounceEdge` - can be set to "falling" (default) or "rising", to call the function at (rising) on the very first call and subsequent times after the given debounce time or (falling) the very last call after the debounce time passed with no new calls - [see `debounce()` for more info and a diagram](#debounce)
228
- - `checkInterval` - if set to a number, the checks will be run on interval instead of on mutation events - in that case all MutationObserverInit props will be ignored
229
-
230
- ⚠️ Make sure to call `enable()` to actually start observing. This will need to be done after the DOM has loaded (when using `@run-at document-end` or after `DOMContentLoaded` has fired) **and** as soon as the `baseElement` or `baseElementSelector` is available.
231
-
232
- <br>
233
-
234
- ### Methods:
235
- #### `SelectorObserver.addListener()`
236
- Usage: `SelectorObserver.addListener<TElement = HTMLElement>(selector: string, options: SelectorListenerOptions): void`
237
- Adds a listener (specified in `options.listener`) for the given selector that will be called once the selector exists in the DOM. It will be passed the element(s) that match the selector as the only argument.
238
- The listener will be called immediately if the selector already exists in the DOM.
239
-
240
- > `options.listener` is the only required property of the `options` object.
241
- > It is a function that will be called once the selector exists in the DOM.
242
- > It will be passed the found element or NodeList of elements, depending on if `options.all` is set to true or false.
243
-
244
- > If `options.all` is set to true, querySelectorAll() will be used instead and the listener will be passed a `NodeList` of matching elements.
245
- > This will also include elements that were already found in a previous listener call.
246
- > If set to false (default), querySelector() will be used and only the first matching element will be returned.
247
-
248
- > If `options.continuous` is set to true, this listener will not be deregistered after it was called once (defaults to false).
249
- >
250
- > ⚠️ You should keep usage of this option to a minimum, as it will cause this listener to be called every time the selector is *checked for and found* and this can stack up quite quickly.
251
- > ⚠️ You should try to only use this option on SelectorObserver instances that are scoped really low in the DOM tree to prevent as many selector checks as possible from being triggered.
252
- > ⚠️ I also recommend always setting a debounce time (see constructor or below) if you use this option.
253
-
254
- > If `options.debounce` is set to a number above 0, this listener will be debounced by that amount of milliseconds (defaults to 0).
255
- > E.g. if the debounce time is set to 200 and the selector is found twice within 100ms, only the last call of this listener will be executed.
256
-
257
- > `options.debounceEdge` is set to "falling" by default, which means the debounce timer will start after the last call of this listener.
258
- > If set to "rising", the debounce timer will start after the first call of this listener.
259
-
260
- > When using TypeScript, the generic `TElement` can be used to specify the type of the element(s) that this listener will return.
261
- > It will default to HTMLElement if left undefined.
262
-
263
- <br>
264
-
265
- #### `SelectorObserver.enable()`
266
- Usage: `SelectorObserver.enable(immediatelyCheckSelectors?: boolean): boolean`
267
- Enables the observation of the child elements for the first time or if it was disabled before.
268
- `immediatelyCheckSelectors` is set to true by default, which means all previously registered selectors will be checked. Set to false to only check them on the first detected mutation.
269
- Returns true if the observation was enabled, false if it was already enabled or the passed `baseElementSelector` couldn't be found.
270
-
271
- <br>
272
-
273
- #### `SelectorObserver.disable()`
274
- Usage: `SelectorObserver.disable(): void`
275
- Disables the observation of the child elements.
276
- If selectors are currently being checked, the current selector will be finished before disabling.
277
-
278
- <br>
279
-
280
- #### `SelectorObserver.isEnabled()`
281
- Usage: `SelectorObserver.isEnabled(): boolean`
282
- Returns whether the observation of the child elements is currently enabled.
283
-
284
- <br>
285
-
286
- #### `SelectorObserver.clearListeners()`
287
- Usage: `SelectorObserver.clearListeners(): void`
288
- Removes all listeners for all selectors.
289
-
290
- <br>
291
-
292
- #### `SelectorObserver.removeAllListeners()`
293
- Usage: `SelectorObserver.removeAllListeners(selector: string): boolean`
294
- Removes all listeners for the given selector.
295
-
296
- <br>
297
-
298
- #### `SelectorObserver.removeListener()`
299
- Usage: `SelectorObserver.removeListener(selector: string, options: SelectorListenerOptions): boolean`
300
- Removes a specific listener for the given selector and options.
301
-
302
- <br>
303
-
304
- #### `SelectorObserver.getAllListeners()`
305
- Usage: `SelectorObserver.getAllListeners(): Map<string, SelectorListenerOptions[]>`
306
- Returns a Map of all selectors and their listeners.
307
-
308
- <br>
309
-
310
- #### `SelectorObserver.getListeners()`
311
- Usage: `SelectorObserver.getListeners(selector: string): SelectorListenerOptions[] | undefined`
312
- Returns all listeners for the given selector or undefined if there are none.
313
-
314
- <br>
315
-
316
- <details><summary><b>Examples - click to view</b></summary>
317
-
318
- #### Basic usage:
319
-
320
- ```ts
321
- import { SelectorObserver } from "@sv443-network/userutils";
322
-
323
- // adding a single-shot listener before the element exists:
324
- const fooObserver = new SelectorObserver("body");
325
-
326
- fooObserver.addListener("#my-element", {
327
- listener: (element) => {
328
- console.log("Element found:", element);
329
- },
330
- });
331
-
332
- document.addEventListener("DOMContentLoaded", () => {
333
- // starting observation after the <body> element is available:
334
- fooObserver.enable();
335
-
336
-
337
- // adding custom observer options:
338
-
339
- const barObserver = new SelectorObserver(document.body, {
340
- // only check if the following attributes change:
341
- attributeFilter: ["class", "style", "data-whatever"],
342
- // debounce all listeners by 100ms unless specified otherwise:
343
- defaultDebounce: 100,
344
- // "rising" means listeners are called immediately and use the debounce as a timeout between subsequent calls - see the debounce() function for a better explanation
345
- defaultDebounceEdge: "rising",
346
- // other settings from the MutationObserver API can be set here too - see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe#options
347
- });
348
-
349
- barObserver.addListener("#my-element", {
350
- listener: (element) => {
351
- console.log("Element's attributes changed:", element);
352
- },
353
- });
354
-
355
- barObserver.addListener("#my-other-element", {
356
- // set the debounce higher than provided by the defaultDebounce property:
357
- debounce: 250,
358
- // adjust the debounceEdge back to the default "falling" for this specific listener:
359
- debounceEdge: "falling",
360
- listener: (element) => {
361
- console.log("Other element's attributes changed:", element);
362
- },
363
- });
364
-
365
- barObserver.enable();
366
-
367
-
368
- // using custom listener options:
369
-
370
- const bazObserver = new SelectorObserver(document.body);
371
-
372
- // for TypeScript, specify that input elements are returned by the listener:
373
- const unsubscribe = bazObserver.addListener<HTMLInputElement>("input", {
374
- all: true, // use querySelectorAll() instead of querySelector()
375
- continuous: true, // don't remove the listener after it was called once
376
- debounce: 50, // debounce the listener by 50ms
377
- listener: (elements) => {
378
- // type of `elements` is NodeListOf<HTMLInputElement>
379
- console.log("Input elements found:", elements);
380
- },
381
- });
382
-
383
- bazObserver.enable();
384
-
385
- window.addEventListener("something", () => {
386
- // remove the listener after the event "something" was dispatched:
387
- unsubscribe();
388
- });
389
-
390
-
391
- // use a different element as the base:
392
-
393
- const myElement = document.querySelector("#my-element");
394
- if(myElement) {
395
- const quxObserver = new SelectorObserver(myElement);
396
-
397
- quxObserver.addListener("#my-child-element", {
398
- listener: (element) => {
399
- console.log("Child element found:", element);
400
- },
401
- });
402
-
403
- quxObserver.enable();
404
- }
405
- });
406
- ```
407
-
408
- <br>
409
-
410
- #### Get and remove listeners:
411
-
412
- ```ts
413
- import { SelectorObserver } from "@sv443-network/userutils";
414
-
415
- document.addEventListener("DOMContentLoaded", () => {
416
- const observer = new SelectorObserver(document.body);
417
-
418
- observer.addListener("#my-element-foo", {
419
- continuous: true,
420
- listener: (element) => {
421
- console.log("Element found:", element);
422
- },
423
- });
424
-
425
- observer.addListener("#my-element-bar", {
426
- listener: (element) => {
427
- console.log("Element found again:", element);
428
- },
429
- });
430
-
431
- observer.enable();
432
-
433
-
434
- // get all listeners:
435
-
436
- console.log(observer.getAllListeners());
437
- // Map(2) {
438
- // '#my-element-foo' => [ { listener: [Function: listener] } ],
439
- // '#my-element-bar' => [ { listener: [Function: listener] } ]
440
- // }
441
-
442
-
443
- // get listeners for a specific selector:
444
-
445
- console.log(observer.getListeners("#my-element-foo"));
446
- // [ { listener: [Function: listener], continuous: true } ]
447
-
448
-
449
- // remove all listeners for a specific selector:
450
-
451
- observer.removeAllListeners("#my-element-foo");
452
- console.log(observer.getAllListeners());
453
- // Map(1) {
454
- // '#my-element-bar' => [ { listener: [Function: listener] } ]
455
- // }
456
- });
457
- ```
458
-
459
- <br>
460
-
461
- #### Chaining:
462
-
463
- ```ts
464
- import { SelectorObserver } from "@sv443-network/userutils";
465
- import type { SelectorObserverOptions } from "@sv443-network/userutils";
466
-
467
- // apply a default debounce to all SelectorObserver instances:
468
- const defaultOptions: SelectorObserverOptions = {
469
- defaultDebounce: 100,
470
- };
471
-
472
- document.addEventListener("DOMContentLoaded", () => {
473
- // initialize generic observer that in turn initializes "sub-observers":
474
- const fooObserver = new SelectorObserver(document.body, {
475
- ...defaultOptions,
476
- // define any other specific options here
477
- });
478
-
479
- const myElementSelector = "#my-element";
480
-
481
- // this relatively expensive listener (as it is in the full <body> scope) will only fire once:
482
- fooObserver.addListener(myElementSelector, {
483
- listener: (element) => {
484
- // only enable barObserver once its baseElement exists:
485
- barObserver.enable();
486
- },
487
- });
488
-
489
- // barObserver is created at the same time as fooObserver, but only enabled once #my-element exists
490
- const barObserver = new SelectorObserver(element, {
491
- ...defaultOptions,
492
- // define any other specific options here
493
- });
494
-
495
- // this selector will be checked for immediately after `enable()` is called
496
- // and on each subsequent mutation because `continuous` is set to true.
497
- // however it is much less expensive as it is scoped to a lower element which will receive less DOM updates
498
- barObserver.addListener(".my-child-element", {
499
- all: true,
500
- continuous: true,
501
- listener: (elements) => {
502
- console.log("Child elements found:", elements);
503
- },
504
- });
505
-
506
- // immediately enable fooObserver as the <body> is available as soon as "DOMContentLoaded" fires:
507
- fooObserver.enable();
508
- });
509
- ```
510
- </details>
511
-
512
- <br>
513
-
514
- ### getUnsafeWindow()
515
- Usage:
516
- ```ts
517
- getUnsafeWindow(): Window
518
- ```
519
-
520
- Returns the unsafeWindow object or falls back to the regular window object if the `@grant unsafeWindow` is not given.
521
- Userscripts are sandboxed and do not have access to the regular window object, so this function is useful for websites that reject some events that were dispatched by the userscript, or userscripts that need to interact with other userscripts, and more.
522
-
523
- <details><summary><b>Example - click to view</b></summary>
524
-
525
- ```ts
526
- import { getUnsafeWindow } from "@sv443-network/userutils";
527
-
528
- // trick the site into thinking the mouse was moved:
529
- const mouseEvent = new MouseEvent("mousemove", {
530
- view: getUnsafeWindow(),
531
- screenY: 69,
532
- screenX: 420,
533
- movementX: 10,
534
- movementY: 0,
535
- });
536
-
537
- document.body.dispatchEvent(mouseEvent);
538
- ```
539
- </details>
540
-
541
- <br>
542
-
543
- ### addParent()
544
- Usage:
545
- ```ts
546
- addParent(element: Element, newParent: Element): Element
547
- ```
548
-
549
- Adds a parent element around the passed `element` and returns the new parent.
550
- Previously registered event listeners are kept intact.
551
-
552
- ⚠️ This function needs to be run after the DOM has loaded (when using `@run-at document-end` or after `DOMContentLoaded` has fired).
553
-
554
- <details><summary><b>Example - click to view</b></summary>
555
-
556
- ```ts
557
- import { addParent } from "@sv443-network/userutils";
558
-
559
- // add an <a> around an element
560
- const element = document.querySelector("#element");
561
- const newParent = document.createElement("a");
562
- newParent.href = "https://example.org/";
563
-
564
- addParent(element, newParent);
565
- ```
566
- </details>
567
-
568
- <br>
569
-
570
- ### addGlobalStyle()
571
- Usage:
572
- ```ts
573
- addGlobalStyle(css: string): HTMLStyleElement
574
- ```
575
-
576
- Adds a global style to the page in form of a `<style>` element that's inserted into the `<head>`.
577
- Returns the style element that was just created.
578
- ⚠️ This function needs to be run after the DOM has loaded (when using `@run-at document-end` or after `DOMContentLoaded` has fired).
579
-
580
- <details><summary><b>Example - click to view</b></summary>
581
-
582
- ```ts
583
- import { addGlobalStyle } from "@sv443-network/userutils";
584
-
585
- document.addEventListener("DOMContentLoaded", () => {
586
- addGlobalStyle(`
587
- body {
588
- background-color: red;
589
- }
590
- `);
591
- });
592
- ```
593
- </details>
594
-
595
- <br>
596
-
597
- ### preloadImages()
598
- Usage:
599
- ```ts
600
- preloadImages(urls: string[], rejects?: boolean): Promise<Array<PromiseSettledResult<HTMLImageElement>>>
601
- ```
602
-
603
- Preloads images into browser cache by creating an invisible `<img>` element for each URL passed.
604
- The images will be loaded in parallel and the returned Promise will only resolve once all images have been loaded.
605
- The resulting PromiseSettledResult array will contain the image elements if resolved, or an ErrorEvent if rejected, but only if `rejects` is set to true.
606
-
607
- <details><summary><b>Example - click to view</b></summary>
608
-
609
- ```ts
610
- import { preloadImages } from "@sv443-network/userutils";
611
-
612
- preloadImages([
613
- "https://example.org/image1.png",
614
- "https://example.org/image2.png",
615
- "https://example.org/image3.png",
616
- ], true)
617
- .then((results) => {
618
- console.log("Images preloaded. Results:", results);
619
- })
620
- .catch((results) => {
621
- console.error("Couldn't preload all images. Results:", results);
622
- });
623
- ```
624
- </details>
625
-
626
- <br>
627
-
628
- ### openInNewTab()
629
- Usage:
630
- ```ts
631
- openInNewTab(url: string, background?: boolean): void
632
- ```
633
-
634
- Tries to use `GM.openInTab` to open the given URL in a new tab, or as a fallback if the grant is not given, creates an invisible anchor element and clicks it.
635
- If `background` is set to true, the tab will be opened in the background. Leave `undefined` to use the browser's default behavior.
636
-
637
- ⚠️ Needs the `@grant GM.openInTab` directive, otherwise only the fallback behavior will be used and the warning below is extra important:
638
- ⚠️ For the fallback to work, this function needs to be run in response to a user interaction event, else the browser might reject it.
639
-
640
- <details><summary><b>Example - click to view</b></summary>
641
-
642
- ```ts
643
- import { openInNewTab } from "@sv443-network/userutils";
644
-
645
- document.querySelector("#my-button").addEventListener("click", () => {
646
- // open in background:
647
- openInNewTab("https://example.org/", true);
648
- });
649
- ```
650
- </details>
651
-
652
- <br>
653
-
654
- ### interceptEvent()
655
- Usage:
656
- ```ts
657
- interceptEvent(
658
- eventObject: EventTarget,
659
- eventName: string,
660
- predicate?: (event: Event) => boolean
661
- ): void
662
- ```
663
-
664
- Intercepts all events dispatched on the `eventObject` and prevents the listeners from being called as long as the predicate function returns a truthy value.
665
- If no predicate is specified, all events will be discarded.
666
- Calling this function will set the `Error.stackTraceLimit` to 100 (if it's not already higher) to ensure the stack trace is preserved.
667
-
668
- ⚠️ This function should be called as soon as possible (I recommend using `@run-at document-start`), as it will only intercept events that are *attached* after this function is called.
669
- ⚠️ Due to this function modifying the `addEventListener` prototype, it might break execution of the page's main script if the userscript is running in an isolated context (like it does in FireMonkey). In that case, calling this function will throw an error.
670
-
671
- <details><summary><b>Example - click to view</b></summary>
672
-
673
- ```ts
674
- import { interceptEvent } from "@sv443-network/userutils";
675
-
676
- interceptEvent(document.body, "click", (event) => {
677
- // prevent all click events on <a> elements within the entire <body>
678
- if(event.target instanceof HTMLAnchorElement) {
679
- console.log("Intercepting click event:", event);
680
- return true;
681
- }
682
- return false; // allow all other click events through
683
- });
684
- ```
685
- </details>
686
-
687
- <br>
688
-
689
- ### interceptWindowEvent()
690
- Usage:
691
- ```ts
692
- interceptWindowEvent(
693
- eventName: string,
694
- predicate?: (event: Event) => boolean
695
- ): void
696
- ```
697
-
698
- Intercepts all events dispatched on the `window` object and prevents the listeners from being called as long as the predicate function returns a truthy value.
699
- If no predicate is specified, all events will be discarded.
700
- This is essentially the same as [`interceptEvent()`](#interceptevent), but automatically uses the `unsafeWindow` (or falls back to regular `window`).
701
-
702
- ⚠️ This function should be called as soon as possible (I recommend using `@run-at document-start`), as it will only intercept events that are *attached* after this function is called.
703
- ⚠️ In order to have the best chance at intercepting events, the directive `@grant unsafeWindow` should be set.
704
- ⚠️ Due to this function modifying the `addEventListener` prototype, it might break execution of the page's main script if the userscript is running in an isolated context (like it does in FireMonkey). In that case, calling this function will throw an error.
705
-
706
- <details><summary><b>Example - click to view</b></summary>
707
-
708
- ```ts
709
- import { interceptWindowEvent } from "@sv443-network/userutils";
710
-
711
- // prevent the pesky "Are you sure you want to leave this page?" popup
712
- // as no predicate is specified, all events will be discarded by default
713
- interceptWindowEvent("beforeunload");
714
- ```
715
- </details>
716
-
717
- <br>
718
-
719
- ### isScrollable()
720
- Usage:
721
- ```ts
722
- isScrollable(element: Element): { horizontal: boolean, vertical: boolean }
723
- ```
724
-
725
- Checks if an element has a horizontal or vertical scroll bar.
726
- This uses the computed style of the element, so it will also work if the element is hidden.
727
-
728
- <details><summary><b>Example - click to view</b></summary>
729
-
730
- ```ts
731
- import { isScrollable } from "@sv443-network/userutils";
732
-
733
- const element = document.querySelector("#element");
734
- const { horizontal, vertical } = isScrollable(element);
735
-
736
- console.log("Element has a horizontal scroll bar:", horizontal);
737
- console.log("Element has a vertical scroll bar:", vertical);
738
- ```
739
- </details>
740
-
741
- <br>
742
-
743
- ### observeElementProp()
744
- Usage:
745
- ```ts
746
- observeElementProp(
747
- element: Element,
748
- property: string,
749
- callback: (oldValue: any, newValue: any) => void
750
- ): void
751
- ```
752
-
753
- This function observes changes to the given property of a given element.
754
- While regular HTML attributes can be observed using a MutationObserver, this is not always possible for properties that are assigned on the JS object.
755
- This function shims the setter of the provided property and calls the callback function whenever it is changed through any means.
756
-
757
- When using TypeScript, the types for `element`, `property` and the arguments for `callback` will be automatically inferred.
758
-
759
- <details><summary><b>Example - click to view</b></summary>
760
-
761
- ```ts
762
- import { observeElementProp } from "@sv443-network/userutils";
763
-
764
- const myInput = document.querySelector("input#my-input");
765
-
766
- let value = 0;
767
-
768
- setInterval(() => {
769
- value += 1;
770
- myInput.value = String(value);
771
- }, 1000);
772
-
773
-
774
- const observer = new MutationObserver((mutations) => {
775
- // will never be called:
776
- console.log("MutationObserver mutation:", mutations);
777
- });
778
-
779
- // one would think this should work, but "value" is a JS object *property*, not a DOM *attribute*
780
- observer.observe(myInput, {
781
- attributes: true,
782
- attributeFilter: ["value"],
783
- });
784
-
785
-
786
- observeElementProp(myInput, "value", (oldValue, newValue) => {
787
- // will be called every time the value changes:
788
- console.log("Value changed from", oldValue, "to", newValue);
789
- });
790
- ```
791
- </details>
792
-
793
- <br>
794
-
795
- ### getSiblingsFrame()
796
- Usage:
797
- ```ts
798
- getSiblingsFrame<
799
- TSiblingType extends Element = HTMLElement
800
- >(
801
- refElement: Element,
802
- siblingAmount: number,
803
- refElementAlignment: "center-top" | "center-bottom" | "top" | "bottom" = "center-top",
804
- includeRef = true
805
- ): TSiblingType[]
806
- ```
807
- Returns a "frame" of the closest siblings of the reference element, based on the passed amount of siblings and element alignment.
808
- The returned type is an array of `HTMLElement` by default but can be changed by specifying the `TSiblingType` generic in TypeScript.
809
-
810
- These are the parameters:
811
- - The `refElement` parameter is the reference element to return the relative closest siblings from.
812
- - The `siblingAmount` parameter is the amount of siblings to return in total (including or excluding the `refElement` based on the `includeRef` parameter).
813
- - The `refElementAlignment` parameter can be set to `center-top` (default), `center-bottom`, `top`, or `bottom`, which will determine where the relative location of the provided `refElement` is in the returned array.
814
- `center-top` (default) will try to keep the `refElement` in the center of the returned array, but can shift around by one element. In those cases it will prefer the top spot.
815
- Same goes for `center-bottom` in reverse.
816
- `top` will keep the `refElement` at the top of the returned array, and `bottom` will keep it at the bottom.
817
- - If `includeRef` is set to `true` (default), the provided `refElement` will be included in the returned array at its corresponding position.
818
-
819
- <details><summary><b>Example - click to view</b></summary>
820
-
821
- ```ts
822
- import { getSiblingsFrame } from "@sv443-network/userutils";
823
-
824
- const refElement = document.querySelector("#ref");
825
- // ^ structure of the elements:
826
- // <div id="parent">
827
- // <div>1</div>
828
- // <div>2</div>
829
- // <div id="ref">3</div>
830
- // <div>4</div>
831
- // <div>5</div>
832
- // <div>6</div>
833
- // </div>
834
-
835
- // ref element aligned to the top of the frame's center positions and included in the result:
836
- const siblingsFoo = getSiblingsFrame(refElement, 4, "center-top", true);
837
- // <div>1</div>
838
- // <div>2</div> ◄──┐
839
- // <div id="ref">3</div> │ returned <(ref is here because refElementAlignment = "center-top")
840
- // <div>4</div> │ frame
841
- // <div>5</div> ◄──┘
842
- // <div>6</div>
843
-
844
- // ref element aligned to the bottom of the frame's center positions and included in the result:
845
- const siblingsBar = getSiblingsFrame(refElement, 4, "center-bottom", true);
846
- // <div>1</div> ◄──┐
847
- // <div>2</div> │ returned
848
- // <div id="ref">3</div> │ frame <(ref is here because refElementAlignment = "center-bottom")
849
- // <div>4</div> ◄──┘
850
- // <div>5</div>
851
- // <div>6</div>
852
-
853
- // ref element aligned to the bottom of the frame's center positions, but excluded from the result:
854
- const siblingsBaz = getSiblingsFrame(refElement, 3, "center-bottom", false);
855
- // <div>1</div> ◄──┐
856
- // <div>2</div> ◄──┘ returned...
857
- // <div id="ref">3</div> <(skipped because includeRef = false)
858
- // <div>4</div> ◄─── ...frame
859
- // <div>5</div>
860
- // <div>6</div>
861
-
862
- // ref element aligned to the top of the frame, but excluded from the result:
863
- const siblingsQux = getSiblingsFrame(refElement, 3, "top", false);
864
- // <div>1</div>
865
- // <div>2</div>
866
- // <div id="ref">3</div> <(skipped because includeRef = false)
867
- // <div>4</div> ◄──┐ returned
868
- // <div>5</div> │ frame
869
- // <div>6</div> ◄──┘
870
-
871
- // ref element aligned to the top of the frame, but this time included in the result:
872
- const siblingsQuux = getSiblingsFrame(refElement, 3, "top", true);
873
- // <div>1</div>
874
- // <div>2</div>
875
- // <div id="ref">3</div> ◄──┐ returned <(not skipped because includeRef = true)
876
- // <div>4</div> │ frame
877
- // <div>5</div> ◄──┘
878
- // <div>6</div>
879
- ```
880
-
881
- More useful examples:
882
-
883
- ```ts
884
- const refElement = document.querySelector("#ref");
885
- // ^ structure of the elements:
886
- // <div id="parent">
887
- // <div>1</div>
888
- // <div>2</div>
889
- // <div id="ref">3</div>
890
- // <div>4</div>
891
- // <div>5</div>
892
- // <div>6</div>
893
- // </div>
894
-
895
- // get all elements above and include the reference element:
896
- const allAbove = getSiblingsFrame(refElement, Infinity, "top", true);
897
- // <div>1</div> ◄──┐ returned
898
- // <div>2</div> │ frame
899
- // <div id="ref">3</div> ◄──┘
900
- // <div>4</div>
901
- // <div>5</div>
902
- // <div>6</div>
903
-
904
- // get all elements below and exclude the reference element:
905
- const allBelowExcl = getSiblingsFrame(refElement, Infinity, "bottom", false);
906
- // <div>1</div>
907
- // <div>2</div>
908
- // <div id="ref">3</div>
909
- // <div>4</div> ◄──┐ returned
910
- // <div>5</div> │ frame
911
- // <div>6</div> ◄──┘
912
- ```
913
- </details>
914
-
915
- <br>
916
-
917
- ### setInnerHtmlUnsafe()
918
- Usage:
919
- ```ts
920
- setInnerHtmlUnsafe(element: Element, html: string): Element
921
- ```
922
-
923
- Sets the innerHTML property of the provided element without any sanitation or validation.
924
- Makes use of the [Trusted Types API](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API) to trick the browser into thinking the HTML is safe.
925
- Use this function if the page makes use of the CSP directive `require-trusted-types-for 'script'` and throws a "This document requires 'TrustedHTML' assignment" error on Chromium-based browsers.
926
- If the browser doesn't support Trusted Types, this function will fall back to regular innerHTML assignment.
927
-
928
- ⚠️ This function does not perform any sanitization, it only tricks the browser into thinking the HTML is safe and should thus be used with utmost caution, as it can easily cause XSS vulnerabilities!
929
- A much better way of doing this is by using the [DOMPurify](https://github.com/cure53/DOMPurify#what-about-dompurify-and-trusted-types) library to create your own Trusted Types policy that *actually* sanitizes the HTML and prevents (most) XSS attack vectors.
930
- You can also find more info [here.](https://web.dev/articles/trusted-types#library)
931
-
932
- <details><summary><b>Example - click to view</b></summary>
933
-
934
- ```ts
935
- import { setInnerHtmlUnsafe } from "@sv443-network/userutils";
936
-
937
- const myElement = document.querySelector("#my-element");
938
- setInnerHtmlUnsafe(myElement, "<img src='https://picsum.photos/100/100' />"); // hardcoded value, so no XSS risk
939
-
940
- const myXssElement = document.querySelector("#my-xss-element");
941
- const userModifiableVariable = `<img onerror="alert('XSS!')" src="invalid" />`; // let's pretend this came from user input
942
- setInnerHtmlUnsafe(myXssElement, userModifiableVariable); // <- uses a user-modifiable variable, so big XSS risk!
943
- ```
944
- </details>
945
-
946
- <br><br>
947
-
948
- <!-- #region Math -->
949
- ## Math:
950
-
951
- ### clamp()
952
- Usage:
953
- ```ts
954
- clamp(num: number, min: number, max: number): number
955
- ```
956
-
957
- Clamps a number between a min and max boundary (inclusive).
958
-
959
- <details><summary><b>Example - click to view</b></summary>
960
-
961
- ```ts
962
- import { clamp } from "@sv443-network/userutils";
963
-
964
- clamp(7, 0, 10); // 7
965
- clamp(-1, 0, 10); // 0
966
- clamp(5, -5, 0); // 0
967
- clamp(99999, 0, 10); // 10
968
-
969
- // clamp without a min or max boundary:
970
- clamp(-99999, -Infinity, 0); // -99999
971
- clamp(99999, 0, Infinity); // 99999
972
- ```
973
- </details>
974
-
975
- <br>
976
-
977
- ### mapRange()
978
- Usage:
979
- ```ts
980
- mapRange(value: number, range1min: number, range1max: number, range2min: number, range2max: number): number
981
- mapRange(value: number, range1max: number, range2max: number): number
982
- ```
983
-
984
- Maps a number from one range to the spot it would be in another range.
985
- If only the `max` arguments are passed, the function will set the `min` for both ranges to 0.
986
-
987
- <details><summary><b>Example - click to view</b></summary>
988
-
989
- ```ts
990
- import { mapRange } from "@sv443-network/userutils";
991
-
992
- mapRange(5, 0, 10, 0, 100); // 50
993
- mapRange(5, 0, 10, 0, 50); // 25
994
- mapRange(5, 10, 50); // 25
995
-
996
- // to calculate a percentage from arbitrary values, use 0 and 100 as the second range
997
- // for example, if 4 files of a total of 13 were downloaded:
998
- mapRange(4, 0, 13, 0, 100); // 30.76923076923077
999
- ```
1000
- </details>
1001
-
1002
- <br>
1003
-
1004
- ### randRange()
1005
- Usages:
1006
- ```ts
1007
- randRange(min: number, max: number, enhancedEntropy?: boolean): number
1008
- randRange(max: number, enhancedEntropy?: boolean): number
1009
- ```
1010
-
1011
- Returns a random number between `min` and `max` (inclusive).
1012
- If only one argument is passed, it will be used as the `max` value and `min` will be set to 0.
1013
-
1014
- If `enhancedEntropy` is set to true (false by default), the [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) is used for generating the random numbers.
1015
- Note that this makes the function call take longer, but the generated IDs will have a higher entropy.
1016
-
1017
- <details><summary><b>Example - click to view</b></summary>
1018
-
1019
- ```ts
1020
- import { randRange } from "@sv443-network/userutils";
1021
-
1022
- randRange(0, 10); // 4
1023
- randRange(10, 20); // 17
1024
- randRange(10); // 7
1025
- randRange(0, 10, true); // 4 (the devil is in the details)
1026
-
1027
-
1028
- function benchmark(enhancedEntropy: boolean) {
1029
- const timestamp = Date.now();
1030
- for(let i = 0; i < 100_000; i++)
1031
- randRange(0, 100, enhancedEntropy);
1032
- console.log(`Generated 100k in ${Date.now() - timestamp}ms`)
1033
- }
1034
-
1035
- // using Math.random():
1036
- benchmark(false); // Generated 100k in 90ms
1037
-
1038
- // using crypto.getRandomValues():
1039
- benchmark(true); // Generated 100k in 461ms
1040
-
1041
- // about a 5x slowdown, but the generated numbers are more entropic
1042
- ```
1043
- </details>
1044
-
1045
- <br><br>
1046
-
1047
- <!-- #region Misc -->
1048
- ## Misc:
1049
-
1050
- ### DataStore
1051
- Usage:
1052
- ```ts
1053
- new DataStore(options: DataStoreOptions)
1054
- ```
1055
-
1056
- A class that manages a sync & async JSON database that is persistently saved to and loaded from GM storage, localStorage or sessionStorage.
1057
- Also supports automatic migration of outdated data formats via provided migration functions.
1058
- You may create as many instances as you like as long as they have different IDs.
1059
-
1060
- The class' internal methods are all declared as protected, so you can extend this class and override them if you need to add your own functionality, like changing the location data is stored.
1061
-
1062
- If you have multiple DataStore instances and you want to be able to easily and safely export and import their data, take a look at the [DataStoreSerializer](#datastoreserializer) class.
1063
- It combines the data of multiple DataStore instances into a single object that can be exported and imported as a whole by the end user.
1064
-
1065
- ⚠️ The data is stored as a JSON string, so only JSON-compatible data can be used. Circular structures and complex objects will throw an error on load and save or cause otherwise unexpected behavior.
1066
- ⚠️ The directives `@grant GM.getValue` and `@grant GM.setValue` are required if the storageMethod is left as the default of `"GM"`
1067
-
1068
- The options object has the following properties:
1069
- | Property | Description |
1070
- | :-- | :-- |
1071
- | `id` | A unique internal identification string for this instance. If two DataStores share the same ID, they will overwrite each other's data, so it is recommended that you use a prefix that is unique to your project. |
1072
- | `defaultData` | The default data to use if no data is saved in persistent storage yet. Until the data is loaded from persistent storage, this will be the data returned by `getData()`. For TypeScript, the type of the data passed here is what will be used for all other methods of the instance. |
1073
- | `formatVersion` | An incremental version of the data format. If the format of the data is changed in any way, this number should be incremented, in which case all necessary functions of the migrations dictionary will be run consecutively. Never decrement this number or skip numbers. |
1074
- | `migrations?` | (Optional) A dictionary of functions that can be used to migrate data from older versions of the data to newer ones. The keys of the dictionary should be the format version that the functions can migrate to, from the previous whole integer value. The values should be functions that take the data in the old format and return the data in the new format. The functions will be run in order from the oldest to the newest version. If the current format version is not in the dictionary, no migrations will be run. |
1075
- | `migrateIds?` | (Optional) A string or array of strings that migrate from one or more old IDs to the ID set in the constructor. If no data exist for the old ID(s), nothing will be done, but some time may still pass trying to fetch the non-existent data. The ID migration will be done once per session in the call to [`loadData()`](#datastoreloaddata). |
1076
- | `storageMethod?` | (Optional) The method that is used to store the data. Can be `"GM"` (default), `"localStorage"` or `"sessionStorage"`. If you want to store the data in a different way, you can override the methods of the DataStore class. |
1077
- | `encodeData?` | (Optional, but required when `decodeData` is set) Function that encodes the data before saving - you can use [compress()](#compress) here to save space at the cost of a little bit of performance |
1078
- | `decodeData?` | (Optional, but required when `encodeData` is set) Function that decodes the data when loading - you can use [decompress()](#decompress) here to decode data that was previously compressed with [compress()](#compress) |
1079
-
1080
- <br>
1081
-
1082
- ### Methods:
1083
- #### `DataStore.loadData()`
1084
- Usage: `loadData(): Promise<TData>`
1085
- Asynchronously loads the data from persistent storage and returns it.
1086
- If no data was saved in persistent storage before, the value of `options.defaultData` will be returned and also written to persistent storage before resolving.
1087
- If the `options.migrateIds` property is present and this is the first time calling this function in this session, the data will be migrated from the old ID(s) to the current one.
1088
- Then, if the `formatVersion` of the saved data is lower than the current one and the `options.migrations` property is present, the instance will try to migrate the data to the latest format before resolving, updating the in-memory cache and persistent storage.
1089
-
1090
- <br>
1091
-
1092
- #### `DataStore.getData()`
1093
- Usage: `getData(): TData`
1094
- Synchronously returns the current data that is stored in the internal cache.
1095
- If no data was loaded from persistent storage yet using `loadData()`, the value of `options.defaultData` will be returned.
1096
-
1097
- <br>
1098
-
1099
- #### `DataStore.setData()`
1100
- Usage: `setData(data: TData): Promise<void>`
1101
- Writes the given data synchronously to the internal cache and asynchronously to persistent storage.
1102
-
1103
- <br>
1104
-
1105
- #### `DataStore.saveDefaultData()`
1106
- Usage: `saveDefaultData(): Promise<void>`
1107
- Writes the default data given in `options.defaultData` synchronously to the internal cache and asynchronously to persistent storage.
1108
-
1109
- <br>
1110
-
1111
- #### `DataStore.deleteData()`
1112
- Usage: `deleteData(): Promise<void>`
1113
- Fully deletes the data from persistent storage only.
1114
- The internal cache will be left untouched, so any subsequent calls to `getData()` will return the data that was last loaded.
1115
- If `loadData()` or `setData()` are called after this, the persistent storage will be populated with the value of `options.defaultData` again.
1116
- This is why you should either immediately repopulate the cache and persistent storage or the page should probably be reloaded or closed after this method is called.
1117
- ⚠️ If you want to use this method, the additional directive `@grant GM.deleteValue` is required.
1118
-
1119
- <br>
1120
-
1121
- #### `DataStore.runMigrations()`
1122
- Usage: `runMigrations(oldData: any, oldFmtVer: number, resetOnError?: boolean): Promise<TData>`
1123
- Runs all necessary migration functions to migrate the given `oldData` to the latest format.
1124
- If `resetOnError` is set to `false`, the migration will be aborted if an error is thrown and no data will be committed. If it is set to `true` (default) and an error is encountered, it will be suppressed and the `defaultData` will be saved to persistent storage and returned.
1125
-
1126
- <br>
1127
-
1128
- #### `DataStore.migrateId()`
1129
- Usage: `migrateId(oldIds: string | string[]): Promise<void>`
1130
- Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
1131
- If no data exist for the old ID(s), nothing will be done, but some time may still pass trying to fetch the non-existent data.
1132
- Instead of calling this manually, consider setting the `migrateIds` property in the constructor to automatically migrate the data once per session in the call to `loadData()`, unless you know that you need to migrate the ID(s) manually.
1133
-
1134
- <br>
1135
-
1136
- #### `DataStore.encodingEnabled()`
1137
- Usage: `encodingEnabled(): boolean`
1138
- Returns `true` if both `options.encodeData` and `options.decodeData` are set, else `false`.
1139
- Uses TypeScript's type guard notation for easier use in conditional statements.
1140
-
1141
- <br>
1142
-
1143
- <details><summary><b>Example - click to view</b></summary>
1144
-
1145
- ```ts
1146
- import { DataStore, compress, decompress } from "@sv443-network/userutils";
1147
-
1148
- /** Example: Userscript configuration data */
1149
- interface MyConfig {
1150
- foo: string;
1151
- bar: number;
1152
- baz: string;
1153
- qux: string;
1154
- }
1155
-
1156
- /** Default data returned by getData() calls until setData() is used and also fallback data if something goes wrong */
1157
- const defaultData: MyConfig = {
1158
- foo: "hello",
1159
- bar: 42,
1160
- baz: "xyz",
1161
- qux: "something",
1162
- };
1163
- /** If any properties are added to, removed from, or renamed in the MyConfig type, increment this number */
1164
- const formatVersion = 2;
1165
- /** These are functions that migrate outdated data to the latest format - make sure a function exists for every previously used formatVersion and that no numbers are skipped! */
1166
- const migrations = {
1167
- // migrate from format version 0 to 1
1168
- 1: (oldData: Record<string, unknown>) => {
1169
- return {
1170
- foo: oldData.foo,
1171
- bar: oldData.bar,
1172
- baz: "world",
1173
- };
1174
- },
1175
- // asynchronously migrate from format version 1 to 2
1176
- 2: async (oldData: Record<string, unknown>) => {
1177
- // using arbitrary async operations for the new format:
1178
- const qux = await grabQuxDataAsync();
1179
- return {
1180
- foo: oldData.foo,
1181
- bar: oldData.bar,
1182
- baz: oldData.baz,
1183
- qux,
1184
- };
1185
- },
1186
- };
1187
-
1188
- // You probably want to export this instance (or helper functions) so you can use it anywhere in your script:
1189
- export const manager = new DataStore({
1190
- /** A unique ID for this instance */
1191
- id: "my-userscript-config",
1192
- /** Default, initial and fallback data */
1193
- defaultData,
1194
- /** The current version of the data format - should be a whole number that is only ever incremented */
1195
- formatVersion,
1196
- /** Data format migration functions called when the formatVersion is increased */
1197
- migrations,
1198
- /** If the data was saved under different ID(s) before, providing them here will make sure the data is migrated to the current ID when `loadData()` is called */
1199
- migrateIds: ["my-data", "config"],
1200
- /**
1201
- * Where the data should be stored.
1202
- * For example, you could use `"sessionStorage"` to make the data be automatically deleted after the browser session is finished, or use `"localStorage"` if you don't have access to GM storage for some reason.
1203
- */
1204
- storageMethod: "localStorage",
1205
-
1206
- // Compression example:
1207
- // Adding the following will save space at the cost of a little bit of performance (only for the initial loading and every time new data is saved)
1208
- // Feel free to use your own functions here, as long as they take in the stringified JSON and return another string, either synchronously or asynchronously
1209
- // Either both of these properties or none of them should be set
1210
-
1211
- /** Compresses the data using the "deflate" algorithm and digests it as a string */
1212
- encodeData: (data) => compress(data, "deflate", "string"),
1213
- /** Decompresses the "deflate" encoded data as a string */
1214
- decodeData: (data) => decompress(data, "deflate", "string"),
1215
- });
1216
-
1217
- /** Entrypoint of the userscript */
1218
- async function init() {
1219
- // wait for the data to be loaded from persistent storage
1220
- // if no data was saved in persistent storage before or getData() is called before loadData(), the value of options.defaultData will be returned
1221
- // if the previously saved data needs to be migrated to a newer version, it will happen inside this function call
1222
- const configData = await manager.loadData();
1223
-
1224
- console.log(configData.foo); // "hello"
1225
-
1226
- // update the data
1227
- configData.foo = "world";
1228
- configData.bar = 123;
1229
-
1230
- // save the updated data - synchronously to the cache and asynchronously to persistent storage
1231
- manager.saveData(configData).then(() => {
1232
- console.log("Data saved to persistent storage!");
1233
- });
1234
-
1235
- // the internal cache is updated synchronously, so the updated data can be accessed before the Promise resolves:
1236
- console.log(manager.getData().foo); // "world"
1237
- }
1238
-
1239
- init();
1240
- ```
1241
- </details>
1242
-
1243
- <br>
1244
-
1245
- ### DataStoreSerializer
1246
- Usage:
1247
- ```ts
1248
- new DataStoreSerializer(stores: DataStore[], options?: DataStoreSerializerOptions)
1249
- ```
1250
-
1251
- A class that manages serializing and deserializing (exporting and importing) one to infinite DataStore instances.
1252
- The serialized data is a JSON string that can be saved to a file, copied to the clipboard, or stored in any other way.
1253
- Each DataStore instance's settings like data encoding are respected and saved next to the exported data.
1254
- Also, by default a checksum is calculated and importing data with a mismatching checksum will throw an error.
1255
-
1256
- The class' internal methods are all declared as protected, so you can extend this class and override them if you need to add your own functionality.
1257
-
1258
- ⚠️ Needs to run in a secure context (HTTPS) due to the use of the SubtleCrypto API.
1259
-
1260
- The options object has the following properties:
1261
- | Property | Description |
1262
- | :-- | :-- |
1263
- | `addChecksum?` | (Optional) If set to `true` (default), a SHA-256 checksum will be calculated and saved with the serialized data. If set to `false`, no checksum will be calculated and saved. |
1264
- | `ensureIntegrity?` | (Optional) If set to `true` (default), the checksum will be checked when importing data and an error will be thrown if it doesn't match. If set to `false`, the checksum will not be checked and no error will be thrown. If no checksum property exists on the imported data (for example because it wasn't enabled in a previous data format version), the checksum check will be skipped regardless of this setting. |
1265
-
1266
- <br>
1267
-
1268
- ### Methods:
1269
- #### `DataStoreSerializer.serialize()`
1270
- Usage: `serialize(): Promise<string>`
1271
- Serializes all DataStore instances passed in the constructor and returns the serialized data as a JSON string.
1272
- <details><summary>Click to view the structure of the returned data.</summary>
1273
-
1274
- ```jsonc
1275
- [
1276
- {
1277
- "id": "foo-data", // the ID property given to the DataStore instance
1278
- "data": "eJyrVkrKTFeyUkrOKM1LLy1WqgUAMvAF6g==", // serialized data (may be compressed / encoded or not)
1279
- "formatVersion": 2, // the format version of the data
1280
- "encoded": true, // only set to true if both encodeData and decodeData are set in the DataStore instance
1281
- "checksum": "420deadbeef69", // property will be missing if addChecksum is set to false
1282
- },
1283
- {
1284
- // ...
1285
- }
1286
- ]
1287
- ```
1288
- </details>
1289
-
1290
- <br>
1291
-
1292
- #### `DataStoreSerializer.deserialize()`
1293
- Usage: `deserialize(data: string): Promise<void>`
1294
- Deserializes the given string that was created with `serialize()` and imports the contained data each DataStore instance.
1295
- In the process of importing the data, the migrations will be run, if the `formatVersion` property is lower than the one set on the DataStore instance.
1296
-
1297
- If `ensureIntegrity` is set to `true` and the checksum doesn't match, an error will be thrown.
1298
- If `ensureIntegrity` is set to `false`, the checksum check will be skipped entirely.
1299
- If the `checksum` property is missing on the imported data, the checksum check will also be skipped.
1300
- If `encoded` is set to `true`, the data will be decoded using the `decodeData` function set on the DataStore instance.
1301
-
1302
- <br>
1303
-
1304
- #### `DataStoreSerializer.loadStoresData()`
1305
- Usage: `loadStoresData(): PromiseSettledResult<{ id: string, data: object }>[];`
1306
- Loads the persistent data of the DataStore instances into the in-memory cache of each DataStore instance.
1307
- Also triggers the migration process if the data format has changed.
1308
- See the [`DataStore.loadData()`](#datastoreloaddata) method for more information.
1309
-
1310
- <details><summary>Click to view the structure of the returned data.</summary>
1311
-
1312
- ```jsonc
1313
- [
1314
- {
1315
- "status": "fulfilled",
1316
- "value": {
1317
- "id": "foo-data",
1318
- "data": {
1319
- "foo": "hello",
1320
- "bar": "world"
1321
- }
1322
- }
1323
- },
1324
- {
1325
- "status": "rejected",
1326
- "reason": "Checksum mismatch for DataStore with ID \"bar-data\"!\nExpected: 69beefdead420\nHas: abcdef42"
1327
- }
1328
- ]
1329
- ```
1330
-
1331
- </details>
1332
-
1333
- <br>
1334
-
1335
- #### `DataStoreSerializer.resetStoresData()`
1336
- Usage: `resetStoresData(): PromiseSettledResult[];`
1337
- Resets the persistent data of the DataStore instances to their default values.
1338
- This affects both the in-memory cache and the persistent storage.
1339
- Any call to `serialize()` will then use the value of `options.defaultData` of the respective DataStore instance.
1340
-
1341
- <br>
1342
-
1343
- #### `DataStoreSerializer.deleteStoresData()`
1344
- Usage: `deleteStoresData(): PromiseSettledResult[];`
1345
- Deletes the persistent data of the DataStore instances from the set storage method.
1346
- Leaves the in-memory cache of the DataStore instances untouched.
1347
- Any call to `setData()` on the instances will recreate their own persistent storage data.
1348
-
1349
- <br>
1350
-
1351
- <details><summary><b>Example - click to view</b></summary>
1352
-
1353
- ```ts
1354
- import { DataStore, DataStoreSerializer, compress, decompress } from "@sv443-network/userutils";
1355
-
1356
- /** This store doesn't have migrations to run and also has no encodeData and decodeData functions */
1357
- const fooStore = new DataStore({
1358
- id: "foo-data",
1359
- defaultData: {
1360
- foo: "hello",
1361
- },
1362
- formatVersion: 1,
1363
- });
1364
-
1365
- /** This store has migrations to run and also has encodeData and decodeData functions */
1366
- const barStore = new DataStore({
1367
- id: "bar-data",
1368
- defaultData: {
1369
- foo: "hello",
1370
- },
1371
- formatVersion: 2,
1372
- migrations: {
1373
- 2: (oldData) => ({
1374
- ...oldData,
1375
- bar: "world",
1376
- }),
1377
- },
1378
- encodeData: (data) => compress(data, "deflate", "string"),
1379
- decodeData: (data) => decompress(data, "deflate", "string"),
1380
- });
1381
-
1382
- const serializer = new DataStoreSerializer([fooStore, barStore], {
1383
- addChecksum: true,
1384
- ensureIntegrity: true,
1385
- });
1386
-
1387
- async function exportMyDataPls() {
1388
- // first, make sure the persistent data of all stores is loaded into their caches:
1389
- await serializer.loadStoresData();
1390
-
1391
- // now serialize the data:
1392
- const serializedData = await serializer.serialize();
1393
- // create a file and download it:
1394
- const blob = new Blob([serializedData], { type: "application/json" });
1395
- const url = URL.createObjectURL(blob);
1396
- const a = document.createElement("a");
1397
- a.href = url;
1398
- a.download = `data_export-${new Date().toISOString()}.json`;
1399
- a.click();
1400
- a.remove();
1401
-
1402
- // `serialize()` exports a stringified object that looks similar to this:
1403
- // [
1404
- // {
1405
- // "id": "foo-data",
1406
- // "data": "{\"foo\":\"hello\"}", // not compressed or encoded because encodeData and decodeData are not set
1407
- // "formatVersion": 1,
1408
- // "encoded": false,
1409
- // "checksum": "420deadbeef69"
1410
- // },
1411
- // {
1412
- // "id": "bar-data",
1413
- // "data": "eJyrVkrKTFeyUkrOKM1LLy1WqgUAMvAF6g==", // compressed because encodeData and decodeData are set
1414
- // "formatVersion": 2,
1415
- // "encoded": true,
1416
- // "checksum": "69beefdead420"
1417
- // }
1418
- // ]
1419
- }
1420
-
1421
- async function importMyDataPls() {
1422
- // grab the data from the file by using the system file picker or a text field or something similar
1423
- const data = await getDataFromSomewhere();
1424
-
1425
- try {
1426
- // import the data and run migrations if necessary
1427
- await serializer.deserialize(data);
1428
- }
1429
- catch(err) {
1430
- console.error(err);
1431
- alert(`Data import failed: ${err}`);
1432
- }
1433
- }
1434
-
1435
- async function resetMyDataPls() {
1436
- // reset the data of all stores in both the cache and the persistent storage
1437
- await serializer.resetStoresData();
1438
- }
1439
- ```
1440
- </details>
1441
-
1442
- <br>
1443
-
1444
- ### Dialog
1445
- Usage:
1446
- ```ts
1447
- new Dialog(options: DialogOptions)
1448
- ```
1449
-
1450
- A class that creates a customizable modal dialog with a title (optional), body and footer (optional).
1451
- There are tons of options for customization, like changing the close behavior, translating strings and more.
1452
-
1453
- The options object has the following properties:
1454
- | Property | Description |
1455
- | :-- | :-- |
1456
- | `id: string` | A unique internal identification string for this instance. If two Dialogs share the same ID, they will overwrite each other. |
1457
- | `width: number` | The target and maximum width of the dialog in pixels. |
1458
- | `height: number` | The target and maximum height of the dialog in pixels. |
1459
- | `renderBody: () => HTMLElement \| Promise<HTMLElement>` | Called to render the body of the dialog. |
1460
- | `renderHeader?: () => HTMLElement \| Promise<HTMLElement>` | (Optional) Called to render the header of the dialog. Leave undefined for a blank header. |
1461
- | `renderFooter?: () => HTMLElement \| Promise<HTMLElement>` | (Optional) Called to render the footer of the dialog. Leave undefined for no footer. |
1462
- | `closeOnBgClick?: boolean` | (Optional) Whether the dialog should close when the background is clicked. Defaults to `true`. |
1463
- | `closeOnEscPress?: boolean` | (Optional) Whether the dialog should close when the escape key is pressed. Defaults to `true`. |
1464
- | `destroyOnClose?: boolean` | (Optional) Whether the dialog should be destroyed when it's closed. Defaults to `false`. |
1465
- | `unmountOnClose?: boolean` | (Optional) Whether the dialog should be unmounted when it's closed. Defaults to `true`. Superseded by `destroyOnClose`. |
1466
- | `removeListenersOnDestroy?: boolean` | (Optional) Whether all listeners should be removed when the dialog is destroyed. Defaults to `true`. |
1467
- | `small?: boolean` | (Optional) Whether the dialog should have a smaller overall appearance. Defaults to `false`. |
1468
- | `verticalAlign?: "top" \| "center" \| "bottom"` | (Optional) Where to align or anchor the dialog vertically. Defaults to `"center"`. |
1469
- | `strings?: Partial<typeof defaultStrings>` | (Optional) Strings used in the dialog (used for translations). Defaults to the default English strings (importable with the name `defaultStrings`). |
1470
- | `dialogCss?: string` | (Optional) CSS to apply to the dialog. Defaults to the default (importable with the name `defaultDialogCss`). |
1471
-
1472
- <br>
1473
-
1474
- ### Methods:
1475
- #### `Dialog.open()`
1476
- Usage: `open(): Promise<void>`
1477
- Opens the dialog.
1478
- If the dialog is not mounted yet, it will be mounted before opening.
1479
-
1480
- <br>
1481
-
1482
- #### `Dialog.close()`
1483
- Usage: `close(): void`
1484
- Closes the dialog.
1485
- If `options.destroyOnClose` is set to `true`, [`Dialog.destroy()`](#dialogdestroy) will be called immediately after closing.
1486
-
1487
- <br>
1488
-
1489
- #### `Dialog.mount()`
1490
- Usage: `mount(): Promise<void>`
1491
- Mounts the dialog to the DOM by calling the render functions provided in the options object.
1492
- After calling, the dialog will exist in the DOM but will be invisible until [`Dialog.open()`](#dialogopen) is called.
1493
- Call this before opening the dialog to avoid a rendering delay.
1494
-
1495
- <br>
1496
-
1497
- #### `Dialog.unmount()`
1498
- Usage: `unmount(): void`
1499
- Closes the dialog first if it's open, then removes it from the DOM.
1500
-
1501
- <br>
1502
-
1503
- #### `Dialog.remount()`
1504
- Usage: `remount(): Promise<void>`
1505
- Unmounts and mounts the dialog again.
1506
- The render functions in the options object will be called again.
1507
- May cause a flickering effect due to the rendering delay.
1508
-
1509
- <br>
1510
-
1511
- #### `Dialog.isOpen()`
1512
- Usage: `isOpen(): boolean`
1513
- Returns `true` if the dialog is open, else `false`.
1514
-
1515
- <br>
1516
-
1517
- #### `Dialog.isMounted()`
1518
- Usage: `isMounted(): boolean`
1519
- Returns `true` if the dialog is mounted, else `false`.
1520
-
1521
- <br>
1522
-
1523
- #### `Dialog.destroy()`
1524
- Usage: `destroy(): void`
1525
- Destroys the dialog.
1526
- Removes all listeners by default and closes and unmounts the dialog.
1527
-
1528
- <br>
1529
-
1530
- #### `Dialog.getCurrentDialogId()`
1531
- Usage: `static getCurrentDialogId(): string`
1532
- Static method that returns the ID of the currently open dialog.
1533
- Needs to be called without creating an instance of the class.
1534
-
1535
- <br>
1536
-
1537
- #### `Dialog.getOpenDialogs()`
1538
- Usage: `static getOpenDialogs(): string[]`
1539
- Static method that returns an array of the IDs of all open dialogs.
1540
- Needs to be called without creating an instance of the class.
1541
-
1542
- <details><summary><b>Example - click to view</b></summary>
1543
-
1544
- ```ts
1545
- import { Dialog } from "@sv443-network/userutils";
1546
-
1547
- const fooDialog = new Dialog({
1548
- id: "foo-dialog",
1549
- width: 400,
1550
- height: 300,
1551
- renderHeader() {
1552
- const header = document.createElement("div");
1553
- header.textContent = "This is the header";
1554
- return header;
1555
- },
1556
- renderBody() {
1557
- const body = document.createElement("div");
1558
- body.textContent = "This is the body";
1559
- return body;
1560
- },
1561
- renderFooter() {
1562
- const footer = document.createElement("div");
1563
- footer.textContent = "This is the footer";
1564
- return footer;
1565
- },
1566
- closeOnBgClick: true,
1567
- closeOnEscPress: true,
1568
- destroyOnClose: false,
1569
- unmountOnClose: true,
1570
- removeListenersOnDestroy: true,
1571
- small: false,
1572
- verticalAlign: "center",
1573
- strings: {
1574
- closeDialogTooltip: "Click to close",
1575
- },
1576
- dialogCss: getMyCustomDialogCss(),
1577
- });
1578
-
1579
- fooDialog.on("close", () => {
1580
- console.log("Dialog closed");
1581
- });
1582
-
1583
- fooDialog.on("open", () => {
1584
- console.log("Currently open dialogs:", Dialog.getOpenDialogs());
1585
- });
1586
-
1587
- fooDialog.open();
1588
- ```
1589
- </details>
1590
-
1591
- <br>
1592
-
1593
- ### NanoEmitter
1594
- Usage:
1595
- ```ts
1596
- new NanoEmitter<TEventMap = EventsMap>(options?: NanoEmitterOptions): NanoEmitter<TEventMap>
1597
- ```
1598
-
1599
- A class that provides a minimalistic event emitter with a tiny footprint powered by [nanoevents.](https://npmjs.com/package/nanoevents)
1600
- The `TEventMap` generic is used to define the events that can be emitted and listened to.
1601
-
1602
- The main intention behind this class is to extend it in your own classes to provide a simple event system directly built into the class.
1603
- However in a functional environment you can also just create instances for use as standalone event emitters throughout your project.
1604
-
1605
- The options object has the following properties:
1606
- | Property | Description |
1607
- | :-- | :-- |
1608
- | `publicEmit?: boolean` | (Optional) If set to true, allows emitting events through the public method `emit()` (`false` by default). |
1609
-
1610
- Methods:
1611
- `on<K extends keyof TEventMap>(event: K, listener: TEventMap[K]): void`
1612
- Registers a listener function for the given event.
1613
- May be called multiple times for the same event.
1614
-
1615
- `once<K extends keyof TEventMap>(event: K, listener: TEventMap[K]): void`
1616
- Registers a listener function for the given event that will only be called once.
1617
-
1618
- `emit<K extends keyof TEventMap>(event: K, ...args: Parameters<TEventMap[K]>): boolean`
1619
- Emits an event with the given arguments from outside the class instance if `publicEmit` is set to `true`.
1620
- If `publicEmit` is set to `true`, this method will return `true` if the event was emitted.
1621
- If it is set to `false`, it will always return `false` and you will need to use `this.events.emit()` from inside the class instead.
1622
-
1623
- `unsubscribeAll(): void`
1624
- Removes all listeners from all events.
1625
-
1626
- <br>
1627
-
1628
- <details><summary><b>Object oriented example - click to view</b></summary>
1629
-
1630
- ```ts
1631
- import { NanoEmitter } from "@sv443-network/userutils";
1632
-
1633
- // map of events for strong typing - the functions always return void
1634
- interface MyEventMap {
1635
- foo: (bar: string) => void;
1636
- baz: (qux: number) => void;
1637
- }
1638
-
1639
- class MyClass extends NanoEmitter<MyEventMap> {
1640
- constructor() {
1641
- super({
1642
- // allow emitting events from outside the class
1643
- publicEmit: true,
1644
- });
1645
-
1646
- this.once("baz", (qux) => {
1647
- console.log("baz event (inside, once):", qux);
1648
- });
1649
- }
1650
-
1651
- public doStuff() {
1652
- this.emit("foo", "hello");
1653
- this.emit("baz", 42);
1654
- this.emit("foo", "world");
1655
- this.emit("baz", 69);
1656
- }
1657
- }
1658
-
1659
- const myInstance = new MyClass();
1660
- myInstance.doStuff();
1661
-
1662
- myInstance.on("foo", (bar) => {
1663
- console.log("foo event (outside):", bar);
1664
- });
1665
-
1666
- // only works if publicEmit is set to true
1667
- myInstance.emit("baz", "hello from the outside");
1668
-
1669
- myInstance.unsubscribeAll();
1670
- ```
1671
- </details>
1672
-
1673
- <br>
1674
-
1675
- <details><summary><b>Functional example - click to view</b></summary>
1676
-
1677
- ```ts
1678
- import { NanoEmitter } from "@sv443-network/userutils";
1679
-
1680
- // map of events for strong typing - the functions always return void
1681
- interface MyEventMap {
1682
- foo: (bar: string) => void;
1683
- baz: (qux: number) => void;
1684
- }
1685
-
1686
- const myEmitter = new NanoEmitter<MyEventMap>({
1687
- // allow emitting events from outside the class
1688
- publicEmit: true,
1689
- });
1690
-
1691
- myEmitter.on("foo", (bar) => {
1692
- console.log("foo event:", bar);
1693
- });
1694
-
1695
- myEmitter.once("baz", (qux) => {
1696
- console.log("baz event (once):", qux);
1697
- });
1698
-
1699
- function doStuff() {
1700
- // only works if publicEmit is set to true
1701
- myEmitter.emit("foo", "hello");
1702
- myEmitter.emit("baz", 42);
1703
- myEmitter.emit("foo", "world");
1704
- myEmitter.emit("baz", 69);
1705
-
1706
- myEmitter.emit("foo", "hello from the outside");
1707
-
1708
- myEmitter.unsubscribeAll();
1709
- }
1710
-
1711
- doStuff();
1712
- ```
1713
- </details>
1714
-
1715
- <br>
1716
-
1717
- ### autoPlural()
1718
- Usage:
1719
- ```ts
1720
- autoPlural(str: string, num: number | Array | NodeList): string
1721
- ```
1722
-
1723
- Automatically pluralizes a string if the given number is not 1.
1724
- If an array or NodeList is passed, the amount of contained items will be used.
1725
-
1726
- <details><summary><b>Example - click to view</b></summary>
1727
-
1728
- ```ts
1729
- import { autoPlural } from "@sv443-network/userutils";
1730
-
1731
- autoPlural("apple", 0); // "apples"
1732
- autoPlural("apple", 1); // "apple"
1733
- autoPlural("apple", 2); // "apples"
1734
-
1735
- autoPlural("apple", [1]); // "apple"
1736
- autoPlural("apple", [1, 2]); // "apples"
1737
-
1738
- const items = [1, 2, 3, 4, "foo", "bar"];
1739
- console.log(`Found ${items.length} ${autoPlural("item", items)}`); // "Found 6 items"
1740
- ```
1741
- </details>
1742
-
1743
- <br>
1744
-
1745
- ### pauseFor()
1746
- Usage:
1747
- ```ts
1748
- pauseFor(ms: number): Promise<void>
1749
- ```
1750
-
1751
- Pauses async execution for a given amount of time.
1752
-
1753
- <details><summary><b>Example - click to view</b></summary>
1754
-
1755
- ```ts
1756
- import { pauseFor } from "@sv443-network/userutils";
1757
-
1758
- async function run() {
1759
- console.log("Hello");
1760
- await pauseFor(3000); // waits for 3 seconds
1761
- console.log("World");
1762
- }
1763
- ```
1764
- </details>
1765
-
1766
- <br>
1767
-
1768
- ### debounce()
1769
- Usage:
1770
- ```ts
1771
- debounce(func: Function, timeout?: number, edge?: "falling" | "rising"): Function
1772
- ```
1773
-
1774
- Returns a debounced wrapper function, meaning that the given `func` will only be called once after or before a given amount of time.
1775
- This is very useful for functions that are called repeatedly, like event listeners, to remove a substantial amount of unnecessary calls.
1776
- All parameters passed to the returned function will be passed along to the input `func`
1777
-
1778
- The `timeout` will default to 300ms if left undefined.
1779
-
1780
- The `edge` ("falling" by default) determines if the function should be called after the timeout has passed or before it.
1781
- In simpler terms, this results in "falling" edge functions being called once at the very end of a sequence of calls, and "rising" edge functions being called once at the beginning and possibly multiple times following that, but at the very least they're spaced apart by what's passed in `timeout`.
1782
-
1783
- This diagram can hopefully help bring the difference across:
1784
- <details><summary><b>Click to view the diagram</b></summary>
1785
-
1786
- ![debounce function edge diagram](./.github/assets/debounce.png)
1787
-
1788
- </details>
1789
-
1790
- <br>
1791
-
1792
- <details><summary><b>Example - click to view</b></summary>
1793
-
1794
- ```ts
1795
- import { debounce } from "@sv443-network/userutils";
1796
-
1797
- // uses "falling" edge by default:
1798
- window.addEventListener("resize", debounce((event) => {
1799
- console.log("Window was resized:", event);
1800
- }, 500)); // 500ms timeout
1801
-
1802
- // using "rising" edge:
1803
- const myFunc = debounce((event) => {
1804
- console.log("Body was scrolled:", event);
1805
- }, 100, "rising"); // 100ms timeout
1806
-
1807
- document.body.addEventListener("scroll", myFunc);
1808
- ```
1809
- </details>
1810
-
1811
- <br>
1812
-
1813
- ### fetchAdvanced()
1814
- Usage:
1815
- ```ts
1816
- fetchAdvanced(input: string | Request | URL, options?: {
1817
- timeout?: number,
1818
- // any other options from fetch()
1819
- }): Promise<Response>
1820
- ```
1821
-
1822
- A drop-in replacement for the native `fetch()` function that adds options like a timeout property.
1823
- The timeout will default to 10 seconds if left undefined. Set it to a negative number to disable the timeout.
1824
- Pass an [AbortController's signal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to the `signal` property to be able to abort the request before it finishes or the timeout kicks in.
1825
-
1826
- <details><summary><b>Example - click to view</b></summary>
1827
-
1828
- ```ts
1829
- import { fetchAdvanced } from "@sv443-network/userutils";
1830
-
1831
- const { signal, abort } = new AbortController();
1832
-
1833
- fetchAdvanced("https://jokeapi.dev/joke/Any?safe-mode", {
1834
- // times out after 5 seconds:
1835
- timeout: 5000,
1836
- // also accepts any other fetch options like headers and signal:
1837
- headers: {
1838
- "Accept": "text/plain",
1839
- },
1840
- // makes the request abortable:
1841
- signal,
1842
- }).then(async (response) => {
1843
- console.log("Fetch data:", await response.text());
1844
- }).catch((err) => {
1845
- console.error("Fetch error:", err);
1846
- });
1847
-
1848
- document.querySelector("button#cancel")?.addEventListener("click", () => {
1849
- abort();
1850
- });
1851
- ```
1852
- </details>
1853
-
1854
- <br>
1855
-
1856
- ### insertValues()
1857
- Usage:
1858
- ```ts
1859
- insertValues(input: string, ...values: Stringifiable[]): string
1860
- ```
1861
-
1862
- Inserts values into a string in the format `%n`, where `n` is the number of the value, starting at 1.
1863
- The values will be stringified using `toString()` (see [Stringifiable](#stringifiable)) before being inserted into the input string.
1864
- If not enough values are passed, the remaining placeholders will be left untouched.
1865
-
1866
- <details><summary><b>Example - click to view</b></summary>
1867
-
1868
- ```ts
1869
- import { insertValues } from "@sv443-network/userutils";
1870
-
1871
- insertValues("Hello, %1!", "World"); // "Hello, World!"
1872
- insertValues("Hello, %1! My name is %2.", "World", "John"); // "Hello, World! My name is John."
1873
- insertValues("Testing %1", { toString: () => "foo" }); // "Testing foo"
1874
-
1875
- // using an array for the values and not passing enough arguments:
1876
- const values = ["foo", "bar", "baz"];
1877
- insertValues("Testing %1, %2, %3 and %4", ...values); // "Testing foo, bar and baz and %4"
1878
- ```
1879
- </details>
1880
-
1881
- <br>
1882
-
1883
- ### compress()
1884
- Usage:
1885
- ```ts
1886
- compress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType?: "base64"): Promise<string>
1887
- compress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType: "arrayBuffer"): Promise<ArrayBuffer>
1888
- ```
1889
-
1890
- Compresses a string or ArrayBuffer using the specified compression format. Most browsers should support at least `gzip` and `deflate`
1891
- The `outputType` dictates which format the output will be in. It will default to `base64` if left undefined.
1892
-
1893
- ⚠️ You need to provide the `@grant unsafeWindow` directive if you are using the `base64` output type or you will get a TypeError.
1894
- ⚠️ Not all browsers might support compression. Please check [on this page](https://developer.mozilla.org/en-US/docs/Web/API/CompressionStream#browser_compatibility) for compatibility and supported compression formats.
1895
-
1896
- <details><summary><b>Example - click to view</b></summary>
1897
-
1898
- ```ts
1899
- import { compress } from "@sv443-network/userutils";
1900
-
1901
- // using gzip:
1902
-
1903
- const fooGz = await compress("Hello, World!", "gzip");
1904
- const barGz = await compress("Hello, World!".repeat(20), "gzip");
1905
-
1906
- // not as efficient with short strings but can save quite a lot of space with larger strings:
1907
- console.log(fooGz); // "H4sIAAAAAAAAE/NIzcnJ11EIzy/KSVEEANDDSuwNAAAA"
1908
- console.log(barGz); // "H4sIAAAAAAAAE/NIzcnJ11EIzy/KSVH0GJkcAKOPcmYEAQAA"
1909
-
1910
- // depending on the type of data you might want to use a different compression format like deflate:
1911
-
1912
- const fooDeflate = await compress("Hello, World!", "deflate");
1913
- const barDeflate = await compress("Hello, World!".repeat(20), "deflate");
1914
-
1915
- // again, it's not as efficient initially but gets better with longer inputs:
1916
- console.log(fooDeflate); // "eJzzSM3JyddRCM8vyklRBAAfngRq"
1917
- console.log(barDeflate); // "eJzzSM3JyddRCM8vyklR9BiZHAAIEVg1"
1918
- ```
1919
- </details>
1920
-
1921
- <br>
1922
-
1923
- ### decompress()
1924
- Usage:
1925
- ```ts
1926
- decompress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType?: "string"): Promise<string>
1927
- decompress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType: "arrayBuffer"): Promise<ArrayBuffer>
1928
- ```
1929
-
1930
- Decompresses a string or ArrayBuffer that has been previously [compressed](#compress) using the specified compression format. Most browsers should support at least `gzip` and `deflate`
1931
- The `outputType` dictates which format the output will be in. It will default to `string` if left undefined.
1932
-
1933
- ⚠️ You need to provide the `@grant unsafeWindow` directive if you are using the `string` output type or you will get a TypeError.
1934
- ⚠️ Not all browsers might support decompression. Please check [on this page](https://developer.mozilla.org/en-US/docs/Web/API/DecompressionStream#browser_compatibility) for compatibility and supported compression formats.
1935
-
1936
- <details><summary><b>Example - click to view</b></summary>
1937
-
1938
- ```ts
1939
- import { compress, decompress } from "@sv443-network/userutils";
1940
-
1941
- const compressed = await compress("Hello, World!".repeat(20), "gzip");
1942
-
1943
- console.log(compressed); // "H4sIAAAAAAAAE/NIzcnJ11EIzy/KSVH0GJkcAKOPcmYEAQAA"
1944
-
1945
- const decompressed = await decompress(compressed, "gzip");
1946
-
1947
- console.log(decompressed); // "Hello, World!"
1948
- ```
1949
- </details>
1950
-
1951
- <br>
1952
-
1953
- ### computeHash()
1954
- Usage:
1955
- ```ts
1956
- computeHash(input: string | ArrayBuffer, algorithm?: string): Promise<string>
1957
- ```
1958
-
1959
- Computes a hash / checksum of a string or ArrayBuffer using the specified algorithm ("SHA-256" by default).
1960
- The algorithm must be supported by the [SubtleCrypto API](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest).
1961
-
1962
- ⚠️ This function needs to be called in a secure context (HTTPS) due to the use of the SubtleCrypto API.
1963
- ⚠️ If you use this for cryptography, make sure to use a secure algorithm (under no circumstances use SHA-1) and to [salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) your input data.
1964
-
1965
- <details><summary><b>Example - click to view</b></summary>
1966
-
1967
- ```ts
1968
- import { computeHash } from "@sv443-network/userutils";
1969
-
1970
- async function run() {
1971
- const hash1 = await computeHash("Hello, World!");
1972
- const hash2 = await computeHash("Hello, World!");
1973
-
1974
- console.log(hash1); // dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
1975
- console.log(hash1 === hash2); // true (same input = same output)
1976
-
1977
- const hash3 = await computeHash("Hello, world!"); // lowercase "w"
1978
- console.log(hash3); // 315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3
1979
- }
1980
-
1981
- run();
1982
- ```
1983
- </details>
1984
-
1985
- <br>
1986
-
1987
- ### randomId()
1988
- Usage:
1989
- ```ts
1990
- randomId(length?: number, radix?: number, enhancedEntropy?: boolean, randomCase?: boolean): string
1991
- ```
1992
-
1993
- Generates a random ID of a given length and [radix (base).](https://en.wikipedia.org/wiki/Radix)
1994
-
1995
- The default length is 16 and the default radix is 16 (hexadecimal).
1996
- You may change the radix to get digits from different numerical systems.
1997
- Use 2 for binary, 8 for octal, 10 for decimal, 16 for hexadecimal and 36 for alphanumeric.
1998
-
1999
- If `enhancedEntropy` is set to true (false by default), the [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) is used for generating the random numbers.
2000
- Note that this makes the function call take longer, but the generated IDs will have a higher entropy.
2001
-
2002
- If `randomCase` is set to true (which it is by default), the generated ID will contain both upper and lower case letters.
2003
- This randomization is also affected by the `enhancedEntropy` setting, unless there are no alphabetic characters in the output in which case it will be skipped.
2004
-
2005
- ⚠️ This is not suitable for generating anything related to cryptography! Use [SubtleCrypto's `generateKey()`](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey) for that instead.
2006
-
2007
- <details><summary><b>Example - click to view</b></summary>
2008
-
2009
- ```ts
2010
- import { randomId } from "@sv443-network/userutils";
2011
-
2012
- randomId(); // "1bda419a73629d4f" (length 16, radix 16)
2013
- randomId(10); // "f86cd354a4" (length 10, radix 16)
2014
- randomId(10, 2); // "1010001101" (length 10, radix 2)
2015
- randomId(10, 10); // "0183428506" (length 10, radix 10)
2016
- randomId(10, 36, false, true); // "z46jFPa37R" (length 10, radix 36, random case)
2017
-
2018
-
2019
- function benchmark(enhancedEntropy: boolean, randomCase: boolean) {
2020
- const timestamp = Date.now();
2021
- for(let i = 0; i < 10_000; i++)
2022
- randomId(16, 36, enhancedEntropy, randomCase);
2023
- console.log(`Generated 10k in ${Date.now() - timestamp}ms`)
2024
- }
2025
-
2026
- // using Math.random():
2027
- benchmark(false, false); // Generated 10k in 239ms
2028
- benchmark(false, true); // Generated 10k in 248ms
2029
-
2030
- // using crypto.getRandomValues():
2031
- benchmark(true, false); // Generated 10k in 1076ms
2032
- benchmark(true, true); // Generated 10k in 1054ms
2033
-
2034
- // 3rd and 4th have a similar time, but in reality the 4th blocks the event loop for much longer
2035
- ```
2036
- </details>
2037
-
2038
- <br><br>
2039
-
2040
- <!-- #region Arrays -->
2041
- ## Arrays:
2042
-
2043
- ### randomItem()
2044
- Usage:
2045
- ```ts
2046
- randomItem(array: Array): any
2047
- ```
2048
-
2049
- Returns a random item from an array.
2050
- Returns undefined if the array is empty.
2051
-
2052
- <details><summary><b>Example - click to view</b></summary>
2053
-
2054
- ```ts
2055
- import { randomItem } from "@sv443-network/userutils";
2056
-
2057
- randomItem(["foo", "bar", "baz"]); // "bar"
2058
- randomItem([ ]); // undefined
2059
- ```
2060
- </details>
2061
-
2062
- <br>
2063
-
2064
- ### randomItemIndex()
2065
- Usage:
2066
- ```ts
2067
- randomItemIndex(array: Array): [item: any, index: number]
2068
- ```
2069
-
2070
- Returns a tuple of a random item and its index from an array.
2071
- If the array is empty, it will return undefined for both values.
2072
-
2073
- <details><summary><b>Example - click to view</b></summary>
2074
-
2075
- ```ts
2076
- import { randomItemIndex } from "@sv443-network/userutils";
2077
-
2078
- randomItemIndex(["foo", "bar", "baz"]); // ["bar", 1]
2079
- randomItemIndex([ ]); // [undefined, undefined]
2080
-
2081
- // using array destructuring:
2082
- const [item, index] = randomItemIndex(["foo", "bar", "baz"]); // ["bar", 1]
2083
- // or if you only want the index:
2084
- const [, index] = randomItemIndex(["foo", "bar", "baz"]); // 1
2085
- ```
2086
- </details>
2087
-
2088
- <br>
2089
-
2090
- ### takeRandomItem()
2091
- Usage:
2092
- ```ts
2093
- takeRandomItem(array: Array): any
2094
- ```
2095
-
2096
- Returns a random item from an array and mutates the array by removing the item.
2097
- Returns undefined if the array is empty.
2098
-
2099
- <details><summary><b>Example - click to view</b></summary>
2100
-
2101
- ```ts
2102
- import { takeRandomItem } from "@sv443-network/userutils";
2103
-
2104
- const arr = ["foo", "bar", "baz"];
2105
- takeRandomItem(arr); // "bar"
2106
- console.log(arr); // ["foo", "baz"]
2107
- ```
2108
- </details>
2109
-
2110
- <br>
2111
-
2112
- ### randomizeArray()
2113
- Usage:
2114
- ```ts
2115
- randomizeArray(array: Array): Array
2116
- ```
2117
-
2118
- Returns a copy of an array with its items in a random order.
2119
- If the array is empty, a new, empty array will be returned.
2120
-
2121
- <details><summary><b>Example - click to view</b></summary>
2122
-
2123
- ```ts
2124
- import { randomizeArray } from "@sv443-network/userutils";
2125
-
2126
- const foo = [1, 2, 3, 4, 5, 6];
2127
-
2128
- console.log(randomizeArray(foo)); // [3, 1, 5, 2, 4, 6]
2129
- console.log(randomizeArray(foo)); // [4, 5, 2, 1, 6, 3]
2130
-
2131
- console.log(foo); // [1, 2, 3, 4, 5, 6] - original array is not mutated
2132
- ```
2133
- </details>
2134
-
2135
- <br><br>
2136
-
2137
- <!-- #region Translation -->
2138
- ## Translation:
2139
- This is a very lightweight translation function that can be used to translate simple strings.
2140
- Pluralization is not supported but can be achieved manually by adding variations to the translations, identified by a different suffix. See the example section of [`tr.addLanguage()`](#traddlanguage) for an example on how this might be done.
2141
-
2142
- <br>
2143
-
2144
- ### tr()
2145
- Usage:
2146
- ```ts
2147
- tr(key: string, ...values: Stringifiable[]): string
2148
- ```
2149
-
2150
- The function returns the translation of the passed key in the language added by [`tr.addLanguage()`](#traddlanguage) and set by [`tr.setLanguage()`](#trsetlanguage)
2151
- Should the translation contain placeholders in the format `%n`, where `n` is the number of the value starting at 1, they will be replaced with the respective item of the `values` rest parameter.
2152
- The items of the `values` rest parameter will be stringified using `toString()` (see [Stringifiable](#stringifiable)) before being inserted into the translation.
2153
-
2154
- If the key is not found or no language has been added or set before calling this function, it will return the key itself.
2155
- If the key is found and the translation contains placeholders but no values are passed, it will return the translation as-is, including unmodified placeholders.
2156
- If the key is found, the translation doesn't contain placeholders but values are still passed, they will be ignored and the translation will be returned as-is.
2157
-
2158
- <details><summary><b>Example - click to view</b></summary>
2159
-
2160
- ```ts
2161
- import { tr } from "@sv443-network/userutils";
2162
-
2163
- tr.addLanguage("en", {
2164
- "welcome": "Welcome",
2165
- "welcome_name": "Welcome, %1",
2166
- });
2167
- tr.addLanguage("de", {
2168
- "welcome": "Willkommen",
2169
- "welcome_name": "Willkommen, %1",
2170
- });
2171
-
2172
- // this has to be called at least once before calling tr()
2173
- tr.setLanguage("en");
2174
-
2175
- console.log(tr("welcome")); // "Welcome"
2176
- console.log(tr("welcome_name", "John")); // "Welcome, John"
2177
- console.log(tr("non_existent_key")); // "non_existent_key"
2178
-
2179
- // language can be changed at any time, synchronously
2180
- tr.setLanguage("de");
2181
-
2182
- console.log(tr("welcome")); // "Willkommen"
2183
- console.log(tr("welcome_name", "John")); // "Willkommen, John"
2184
- ```
2185
- </details>
2186
-
2187
- <br>
2188
-
2189
- ### tr.forLang()
2190
- Usage:
2191
- ```ts
2192
- tr.forLang(language: string, key: string, ...values: Stringifiable[]): string
2193
- ```
2194
-
2195
- Returns the translation of the passed key in the specified language. Otherwise behaves exactly like [`tr()`](#tr)
2196
- This function does not change the currently active language set by [`tr.setLanguage()`](#trsetlanguage)
2197
-
2198
- <details><summary><b>Example - click to view</b></summary>
2199
-
2200
- ```ts
2201
- import { tr } from "@sv443-network/userutils";
2202
-
2203
- tr.addLanguage("en", {
2204
- "welcome_name": "Welcome, %1",
2205
- });
2206
-
2207
- tr.addLanguage("de", {
2208
- "welcome_name": "Willkommen, %1",
2209
- });
2210
-
2211
- // the language is set to "en"
2212
- tr.setLanguage("en");
2213
-
2214
- console.log(tr("welcome_name", "John")); // "Welcome, John"
2215
- // no need to call tr.setLanguage():
2216
- console.log(tr.forLang("de", "welcome_name", "John")); // "Willkommen, John"
2217
- ```
2218
- </details>
2219
-
2220
- <br>
2221
-
2222
- ### tr.addLanguage()
2223
- Usage:
2224
- ```ts
2225
- tr.addLanguage(language: string, translations: Record<string, string>): void
2226
- ```
2227
-
2228
- Adds or overwrites a language and its associated translations to the translation function.
2229
- The passed language can be any unique identifier, though I highly recommend sticking to a standard like [BCP 47 / RFC 5646](https://www.rfc-editor.org/rfc/rfc5646.txt) (which is used by the [`Intl` namespace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) and methods like [`Number.toLocaleString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString)), or [ISO 639-1.](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes)
2230
- The passed translations should be a flat object (no nested objects are allowed for now), where the key is the translation key used in `tr()` and the value is the translation itself.
2231
- If `tr.addLanguage()` is called multiple times with the same language, the previous translations of that language will be overwritten.
2232
-
2233
- The translation values may contain placeholders in the format `%n`, where `n` is the number of the value starting at 1.
2234
- These can be used to inject values into the translation when calling `tr()`
2235
-
2236
- <details><summary><b>Example - click to view</b></summary>
2237
-
2238
- ```ts
2239
- import { tr } from "@sv443-network/userutils";
2240
-
2241
- // add a language with associated translations:
2242
-
2243
- tr.addLanguage("de", {
2244
- "color": "Farbe",
2245
- });
2246
-
2247
-
2248
- // with placeholders:
2249
-
2250
- tr.addLanguage("en", {
2251
- "welcome_generic": "Welcome!",
2252
- "welcome_name": "Welcome, %1!",
2253
- "welcome_extended": "Welcome, %1!\nYour last login was on %2\nYou have %3 unread messages",
2254
- });
2255
-
2256
-
2257
- // can be used for different locales too:
2258
-
2259
- tr.addLanguage("en-US", {
2260
- "fries": "fries",
2261
- "color": "color",
2262
- });
2263
-
2264
- tr.addLanguage("en-GB", {
2265
- "fries": "chips",
2266
- "color": "colour",
2267
- });
2268
-
2269
-
2270
- // apply default values for different locales to reduce redundancy in shared translation values:
2271
-
2272
- const translation_de = {
2273
- "greeting": "Guten Tag!",
2274
- "foo": "Foo",
2275
- };
2276
-
2277
- tr.addLanguage("de-DE", translation_de);
2278
-
2279
- tr.addLanguage("de-CH", {
2280
- // overwrite the "greeting" but keep other keys as they are:
2281
- ...translation_de,
2282
- "greeting": "Grüezi!",
2283
- });
2284
-
2285
- tr.addLanguage("de-AT", {
2286
- // overwrite "greeting" again but keep other keys as they are:
2287
- ...translation_de,
2288
- "greeting": "Grüß Gott!",
2289
- });
2290
-
2291
-
2292
- // example for custom pluralization:
2293
-
2294
- tr.addLanguage("en", {
2295
- "cart_items_added-0": "No items were added to the cart",
2296
- "cart_items_added-1": "Added %1 item to the cart",
2297
- "cart_items_added-n": "Added %1 items to the cart",
2298
- });
2299
-
2300
- type Numberish = number | Array<unknown> | NodeList | { length: number } | { size: number };
2301
-
2302
- /** Returns the translation key with a custom pluralization identifier added to it for the given number of items (or size of Array/NodeList or anything else with a `length` or `size` property) */
2303
- function pl(key: string, num: Numberish): string {
2304
- if(typeof num !== "number") {
2305
- if("length" in num)
2306
- num = num.length;
2307
- else if("size" in num)
2308
- num = num.size;
2309
- }
2310
-
2311
- if(num === 0)
2312
- return `${key}-0`;
2313
- else if(num === 1)
2314
- return `${key}-1`;
2315
- else
2316
- return `${key}-n`; // will also be the fallback for non-numeric values
2317
- };
2318
-
2319
- const items = [];
2320
- console.log(tr(pl("cart_items_added", items), items.length)); // "No items were added to the cart"
2321
-
2322
- items.push("foo");
2323
- console.log(tr(pl("cart_items_added", items), items.length)); // "Added 1 item to the cart"
2324
-
2325
- items.push("bar");
2326
- console.log(tr(pl("cart_items_added", items), items.length)); // "Added 2 items to the cart"
2327
-
2328
- // you will need to catch cases like this manually or in your own implementation of `pl()`:
2329
- console.log(tr(pl("cart_items_added", NaN), NaN)); // "Added NaN items to the cart"
2330
- ```
2331
- </details>
2332
-
2333
- <br>
2334
-
2335
- ### tr.setLanguage()
2336
- Usage:
2337
- ```ts
2338
- tr.setLanguage(language: string): void
2339
- ```
2340
-
2341
- Synchronously sets the language that will be used for translations.
2342
- No validation is done on the passed language, so make sure it is correct and it has been added with `tr.addLanguage()` before calling `tr()`
2343
-
2344
- For an example, see [`tr()`](#tr)
2345
-
2346
- <br>
2347
-
2348
- ### tr.getLanguage()
2349
- Usage:
2350
- ```ts
2351
- tr.getLanguage(): string | undefined
2352
- ```
2353
-
2354
- Returns the currently active language set by [`tr.setLanguage()`](#trsetlanguage)
2355
- If no language has been set yet, it will return undefined.
2356
-
2357
- <br>
2358
-
2359
- ### tr.getTranslations()
2360
- Usage:
2361
- ```ts
2362
- tr.getTranslations(language?: string): Record<string, string> | undefined
2363
- ```
2364
-
2365
- Returns the translations of the specified language.
2366
- If no language is specified, it will return the translations of the currently active language set by [`tr.setLanguage()`](#trsetlanguage)
2367
- If no translations are found, it will return undefined.
2368
-
2369
- <details><summary><b>Example - click to view</b></summary>
2370
-
2371
- ```ts
2372
- import { tr } from "@sv443-network/userutils";
2373
-
2374
- tr.addLanguage("en", {
2375
- "welcome": "Welcome",
2376
- });
2377
-
2378
- console.log(tr.getTranslations()); // undefined
2379
- tr.setLanguage("en");
2380
- console.log(tr.getTranslations()); // { "welcome": "Welcome" }
2381
-
2382
- console.log(tr.getTranslations("en")); // { "welcome": "Welcome" }
2383
-
2384
- console.log(tr.getTranslations("de")); // undefined
2385
- ```
2386
- </details>
2387
-
2388
- <br><br>
2389
-
2390
- ## Colors:
2391
- The color functions are used to manipulate and convert colors in various formats.
2392
-
2393
- ### hexToRgb()
2394
- Usage:
2395
- ```ts
2396
- hexToRgb(hex: string): [red: number, green: number, blue: number, alpha?: number]
2397
- ```
2398
-
2399
- Converts a hex color string to an RGB or RGBA color tuple array.
2400
- The values of R, G and B will be in the range of 0-255, while the alpha value will be in the range of 0-1.
2401
- Accepts the formats `#RRGGBB`, `#RRGGBBAA`, `#RGB` and `#RGBA`, with or without the hash symbol.
2402
-
2403
- <details><summary><b>Example - click to view</b></summary>
2404
-
2405
- ```ts
2406
- import { hexToRgb } from "@sv443-network/userutils";
2407
-
2408
- hexToRgb("#aaff85aa"); // [170, 255, 133, 0.6666666666666666]
2409
- hexToRgb("#ff0000"); // [255, 0, 0, undefined]
2410
- hexToRgb("0032ef"); // [0, 50, 239, undefined]
2411
- hexToRgb("#0f0"); // [0, 255, 0, undefined]
2412
- hexToRgb("0f0f"); // [0, 255, 0, 1]
2413
- ```
2414
- </details>
2415
-
2416
- <br>
2417
-
2418
- ### rgbToHex()
2419
- Usage:
2420
- ```ts
2421
- rgbToHex(red: number, green: number, blue: number, alpha?: number, withHash?: boolean, upperCase?: boolean): string
2422
- ```
2423
-
2424
- Converts RGB or RGBA color values to a hex color string.
2425
- The `withHash` parameter determines if the hash symbol should be included in the output (true by default).
2426
- The `upperCase` parameter determines if the output should be in uppercase (false by default).
2427
-
2428
- <details><summary><b>Example - click to view</b></summary>
2429
-
2430
- ```ts
2431
- import { rgbToHex } from "@sv443-network/userutils";
2432
-
2433
- rgbToHex(255, 0, 0); // "#ff0000" (with hash symbol, lowercase)
2434
- rgbToHex(255, 0, 0, 0.5, false); // "ff000080" (with alpha, no hash symbol, lowercase)
2435
- rgbToHex(255, 0, 0, undefined, true, true); // "#FF0000" (no alpha, with hash symbol, uppercase)
2436
- ```
2437
- </details>
2438
-
2439
- <br>
2440
-
2441
- ### lightenColor()
2442
- Usage:
2443
- ```ts
2444
- lightenColor(color: string, percent: number, upperCase?: boolean): string
2445
- ```
2446
-
2447
- Lightens a CSS color value (in hex, RGB or RGBA format) by a given percentage.
2448
- Will not exceed the maximum range (00-FF or 0-255).
2449
- If the `upperCase` parameter is set to true (default is false), the output will be in uppercase.
2450
- Throws an error if the color format is invalid or not supported.
2451
-
2452
- <details><summary><b>Example - click to view</b></summary>
2453
-
2454
- ```ts
2455
- import { lightenColor } from "@sv443-network/userutils";
2456
-
2457
- lightenColor("#ff0000", 20); // "#ff3333"
2458
- lightenColor("#ff0000", 20, true); // "#FF3333"
2459
- lightenColor("rgb(0, 255, 0)", 50); // "rgb(128, 255, 128)"
2460
- lightenColor("rgba(0, 255, 0, 0.5)", 50); // "rgba(128, 255, 128, 0.5)"
2461
- ```
2462
- </details>
2463
-
2464
- <br>
2465
-
2466
- ### darkenColor()
2467
- Usage:
2468
- ```ts
2469
- darkenColor(color: string, percent: number, upperCase?: boolean): string
2470
- ```
2471
-
2472
- Darkens a CSS color value (in hex, RGB or RGBA format) by a given percentage.
2473
- Will not exceed the maximum range (00-FF or 0-255).
2474
- If the `upperCase` parameter is set to true (default is false), the output will be in uppercase.
2475
- Throws an error if the color format is invalid or not supported.
2476
-
2477
- <details><summary><b>Example - click to view</b></summary>
2478
-
2479
- ```ts
2480
- import { darkenColor } from "@sv443-network/userutils";
2481
-
2482
- darkenColor("#ff0000", 20); // "#cc0000"
2483
- darkenColor("#ff0000", 20, true); // "#CC0000"
2484
- darkenColor("rgb(0, 255, 0)", 50); // "rgb(0, 128, 0)"
2485
- darkenColor("rgba(0, 255, 0, 0.5)", 50); // "rgba(0, 128, 0, 0.5)"
2486
- ```
2487
- </details>
2488
-
2489
- <br><br>
2490
-
2491
- <!-- #region Utility types -->
2492
- ## Utility types:
2493
- UserUtils also offers some utility types that can be used in TypeScript projects.
2494
- They don't alter the runtime behavior of the code, but they can be used to make the code more readable and to prevent errors.
2495
-
2496
- ### Stringifiable
2497
- This type describes any value that either is a string itself or can be converted to a string.
2498
- To be considered stringifiable, the object needs to have a `toString()` method that returns a string.
2499
- Most primitives have this method, but something like undefined or null does not (they can only be used in the `String()` constructor or string interpolation).
2500
- Having this method allows not just explicit conversion by calling it, but also implicit conversion by passing it into the `String()` constructor or by interpolating it in a template string.
2501
-
2502
- <details><summary><b>Example - click to view</b></summary>
2503
-
2504
- ```ts
2505
- import type { Stringifiable } from "@sv443-network/userutils";
2506
-
2507
- function logSomething(value: Stringifiable) {
2508
- console.log(`Log: ${value}`); // implicit conversion to a string
2509
- }
2510
-
2511
- const fooObject = {
2512
- toString: () => "hello world",
2513
- };
2514
-
2515
- const barObject = {
2516
- baz: "",
2517
- };
2518
-
2519
- logSomething("foo"); // "Log: foo"
2520
- logSomething(42); // "Log: 42"
2521
- logSomething(true); // "Log: true"
2522
- logSomething(Symbol(1)); // "Log: Symbol(1)"
2523
- logSomething(fooObject); // "Log: hello world"
2524
-
2525
- logSomething(barObject); // Type error
2526
- ```
2527
- </details>
2528
-
2529
- <br>
2530
-
2531
- ## NonEmptyArray
2532
- Usage:
2533
- ```ts
2534
- NonEmptyArray<TItem = unknown>
2535
- ```
2536
-
2537
- This generic type describes an array that has at least one item.
2538
- Use the generic parameter to specify the type of the items in the array.
2539
-
2540
- <details><summary><b>Example - click to view</b></summary>
2541
-
2542
- ```ts
2543
- import type { NonEmptyArray } from "@sv443-network/userutils";
2544
-
2545
- function logFirstItem(array: NonEmptyArray<string>) {
2546
- console.log(parseInt(array[0]));
2547
- }
2548
-
2549
- function somethingElse(array: NonEmptyArray) {
2550
- // array is typed as NonEmptyArray<unknown> when not passing a
2551
- // generic parameter, so this throws a TS error:
2552
- console.log(parseInt(array[0])); // Argument of type 'unknown' is not assignable to parameter of type 'string'
2553
- }
2554
-
2555
- logFirstItem(["04abc", "69"]); // 4
2556
- ```
2557
- </details>
2558
-
2559
- <br>
2560
-
2561
- ## NonEmptyString
2562
- Usage:
2563
- ```ts
2564
- NonEmptyString<TString extends string>
2565
- ```
2566
-
2567
- This generic type describes a string that has at least one character.
2568
-
2569
- <details><summary><b>Example - click to view</b></summary>
2570
-
2571
- ```ts
2572
- import type { NonEmptyString } from "@sv443-network/userutils";
2573
-
2574
- function convertToNumber<T extends string>(str: NonEmptyString<T>) {
2575
- console.log(parseInt(str));
2576
- }
2577
-
2578
- convertToNumber("04abc"); // "4"
2579
- convertToNumber(""); // type error: Argument of type 'string' is not assignable to parameter of type 'never'
2580
- ```
2581
- </details>
2582
-
2583
- <br>
2584
-
2585
- ## LooseUnion
2586
- Usage:
2587
- ```ts
2588
- LooseUnion<TUnion extends string | number | object>
2589
- ```
2590
-
2591
- A generic type that offers autocomplete in the IDE for the passed union but also allows any value of the same type to be passed.
2592
- Supports unions of strings, numbers and objects.
2593
-
2594
- <details><summary><b>Example - click to view</b></summary>
2595
-
2596
- ```ts
2597
- function foo(bar: LooseUnion<"a" | "b" | "c">) {
2598
- console.log(bar);
2599
- }
2600
-
2601
- // when typing the following, autocomplete suggests "a", "b" and "c"
2602
- // foo("
2603
-
2604
- foo("a"); // included in autocomplete, no type error
2605
- foo(""); // *not* included in autocomplete, still no type error
2606
- foo(1); // type error: Argument of type '1' is not assignable to parameter of type 'LooseUnion<"a" | "b" | "c">'
2607
- ```
2608
- </details>
2609
-
2610
- <br>
2611
-
2612
- ## Prettify
2613
- Usage:
2614
- ```ts
2615
- Prettify<T>
2616
- ```
2617
-
2618
- A generic type that makes TypeScript and your IDE display the type in a more readable way.
2619
- This is especially useful for types that reference other types or are very complex.
2620
- It will also make a variable show its type's structure instead of just the type name (see example).
2621
-
2622
- <details><summary><b>Example - click to view</b></summary>
2623
-
2624
- ```ts
2625
- // tooltip shows all constituent types, leaving you to figure it out yourself:
2626
- // type Foo = {
2627
- // a: number;
2628
- // } & Omit<{
2629
- // b: string;
2630
- // c: boolean;
2631
- // }, "c">
2632
- type Foo = {
2633
- a: number;
2634
- } & Omit<{
2635
- b: string;
2636
- c: boolean;
2637
- }, "c">;
2638
-
2639
- // tooltip shows just the type name:
2640
- // const foo: Foo
2641
- const foo: Foo = {
2642
- a: 1,
2643
- b: "2"
2644
- };
2645
-
2646
- // tooltip shows the actual type structure:
2647
- // type Bar = {
2648
- // a: number;
2649
- // b: string;
2650
- // }
2651
- type Bar = Prettify<Foo>;
2652
-
2653
- // tooltip again shows the actual type structure:
2654
- // const bar: {
2655
- // a: number;
2656
- // b: string;
2657
- // }
2658
- const bar: Bar = {
2659
- a: 1,
2660
- b: "2"
2661
- };
2662
- ```
2663
- </details>
2664
-
2665
194
  <br><br><br><br>
2666
195
 
2667
196
  <!-- #region Footer -->
2668
197
  <div style="text-align: center;" align="center">
2669
198
 
2670
199
  Made with ❤️ by [Sv443](https://github.com/Sv443)
2671
- If you like this library, please consider [supporting development](https://github.com/sponsors/Sv443)
200
+ If you like this library, please consider [supporting the development](https://github.com/sponsors/Sv443)
2672
201
 
2673
202
  </div>