@sv443-network/userutils 7.1.0 → 7.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -108,6 +108,197 @@ function randomizeArray(array) {
108
108
  return retArray;
109
109
  }
110
110
 
111
+ // lib/dom.ts
112
+ function getUnsafeWindow() {
113
+ try {
114
+ return unsafeWindow;
115
+ } catch (e) {
116
+ return window;
117
+ }
118
+ }
119
+ function addParent(element, newParent) {
120
+ const oldParent = element.parentNode;
121
+ if (!oldParent)
122
+ throw new Error("Element doesn't have a parent node");
123
+ oldParent.replaceChild(newParent, element);
124
+ newParent.appendChild(element);
125
+ return newParent;
126
+ }
127
+ function addGlobalStyle(style) {
128
+ const styleElem = document.createElement("style");
129
+ setInnerHtmlUnsafe(styleElem, style);
130
+ document.head.appendChild(styleElem);
131
+ return styleElem;
132
+ }
133
+ function preloadImages(srcUrls, rejects = false) {
134
+ const promises = srcUrls.map((src) => new Promise((res, rej) => {
135
+ const image = new Image();
136
+ image.src = src;
137
+ image.addEventListener("load", () => res(image));
138
+ image.addEventListener("error", (evt) => rejects && rej(evt));
139
+ }));
140
+ return Promise.allSettled(promises);
141
+ }
142
+ function openInNewTab(href, background) {
143
+ try {
144
+ GM.openInTab(href, background);
145
+ } catch (e) {
146
+ const openElem = document.createElement("a");
147
+ Object.assign(openElem, {
148
+ className: "userutils-open-in-new-tab",
149
+ target: "_blank",
150
+ rel: "noopener noreferrer",
151
+ href
152
+ });
153
+ openElem.style.display = "none";
154
+ document.body.appendChild(openElem);
155
+ openElem.click();
156
+ setTimeout(openElem.remove, 50);
157
+ }
158
+ }
159
+ function interceptEvent(eventObject, eventName, predicate = () => true) {
160
+ Error.stackTraceLimit = Math.max(Error.stackTraceLimit, 100);
161
+ if (isNaN(Error.stackTraceLimit))
162
+ Error.stackTraceLimit = 100;
163
+ (function(original) {
164
+ eventObject.__proto__.addEventListener = function(...args) {
165
+ var _a, _b;
166
+ const origListener = typeof args[1] === "function" ? args[1] : (_b = (_a = args[1]) == null ? void 0 : _a.handleEvent) != null ? _b : () => void 0;
167
+ args[1] = function(...a) {
168
+ if (args[0] === eventName && predicate(Array.isArray(a) ? a[0] : a))
169
+ return;
170
+ else
171
+ return origListener.apply(this, a);
172
+ };
173
+ original.apply(this, args);
174
+ };
175
+ })(eventObject.__proto__.addEventListener);
176
+ }
177
+ function interceptWindowEvent(eventName, predicate = () => true) {
178
+ return interceptEvent(getUnsafeWindow(), eventName, predicate);
179
+ }
180
+ function isScrollable(element) {
181
+ const { overflowX, overflowY } = getComputedStyle(element);
182
+ return {
183
+ vertical: (overflowY === "scroll" || overflowY === "auto") && element.scrollHeight > element.clientHeight,
184
+ horizontal: (overflowX === "scroll" || overflowX === "auto") && element.scrollWidth > element.clientWidth
185
+ };
186
+ }
187
+ function observeElementProp(element, property, callback) {
188
+ const elementPrototype = Object.getPrototypeOf(element);
189
+ if (elementPrototype.hasOwnProperty(property)) {
190
+ const descriptor = Object.getOwnPropertyDescriptor(elementPrototype, property);
191
+ Object.defineProperty(element, property, {
192
+ get: function() {
193
+ var _a;
194
+ return (_a = descriptor == null ? void 0 : descriptor.get) == null ? void 0 : _a.apply(this, arguments);
195
+ },
196
+ set: function() {
197
+ var _a;
198
+ const oldValue = this[property];
199
+ (_a = descriptor == null ? void 0 : descriptor.set) == null ? void 0 : _a.apply(this, arguments);
200
+ const newValue = this[property];
201
+ if (typeof callback === "function") {
202
+ callback.bind(this, oldValue, newValue);
203
+ }
204
+ return newValue;
205
+ }
206
+ });
207
+ }
208
+ }
209
+ function getSiblingsFrame(refElement, siblingAmount, refElementAlignment = "center-top", includeRef = true) {
210
+ var _a, _b;
211
+ const siblings = [...(_b = (_a = refElement.parentNode) == null ? void 0 : _a.childNodes) != null ? _b : []];
212
+ const elemSiblIdx = siblings.indexOf(refElement);
213
+ if (elemSiblIdx === -1)
214
+ throw new Error("Element doesn't have a parent node");
215
+ if (refElementAlignment === "top")
216
+ return [...siblings.slice(elemSiblIdx + Number(!includeRef), elemSiblIdx + siblingAmount + Number(!includeRef))];
217
+ else if (refElementAlignment.startsWith("center-")) {
218
+ const halfAmount = (refElementAlignment === "center-bottom" ? Math.ceil : Math.floor)(siblingAmount / 2);
219
+ const startIdx = Math.max(0, elemSiblIdx - halfAmount);
220
+ const topOffset = Number(refElementAlignment === "center-top" && siblingAmount % 2 === 0 && includeRef);
221
+ const btmOffset = Number(refElementAlignment === "center-bottom" && siblingAmount % 2 !== 0 && includeRef);
222
+ const startIdxWithOffset = startIdx + topOffset + btmOffset;
223
+ return [
224
+ ...siblings.filter((_, idx) => includeRef || idx !== elemSiblIdx).slice(startIdxWithOffset, startIdxWithOffset + siblingAmount)
225
+ ];
226
+ } else if (refElementAlignment === "bottom")
227
+ return [...siblings.slice(elemSiblIdx - siblingAmount + Number(includeRef), elemSiblIdx + Number(includeRef))];
228
+ return [];
229
+ }
230
+ var ttPolicy;
231
+ function setInnerHtmlUnsafe(element, html) {
232
+ var _a, _b, _c;
233
+ if (!ttPolicy && typeof ((_a = window == null ? void 0 : window.trustedTypes) == null ? void 0 : _a.createPolicy) === "function") {
234
+ ttPolicy = window.trustedTypes.createPolicy("_uu_set_innerhtml_unsafe", {
235
+ createHTML: (unsafeHtml) => unsafeHtml
236
+ });
237
+ }
238
+ element.innerHTML = (_c = (_b = ttPolicy == null ? void 0 : ttPolicy.createHTML) == null ? void 0 : _b.call(ttPolicy, html)) != null ? _c : html;
239
+ return element;
240
+ }
241
+
242
+ // lib/crypto.ts
243
+ function compress(input, compressionFormat, outputType = "string") {
244
+ return __async(this, null, function* () {
245
+ const byteArray = typeof input === "string" ? new TextEncoder().encode(input) : input;
246
+ const comp = new CompressionStream(compressionFormat);
247
+ const writer = comp.writable.getWriter();
248
+ writer.write(byteArray);
249
+ writer.close();
250
+ const buf = yield new Response(comp.readable).arrayBuffer();
251
+ return outputType === "arrayBuffer" ? buf : ab2str(buf);
252
+ });
253
+ }
254
+ function decompress(input, compressionFormat, outputType = "string") {
255
+ return __async(this, null, function* () {
256
+ const byteArray = typeof input === "string" ? str2ab(input) : input;
257
+ const decomp = new DecompressionStream(compressionFormat);
258
+ const writer = decomp.writable.getWriter();
259
+ writer.write(byteArray);
260
+ writer.close();
261
+ const buf = yield new Response(decomp.readable).arrayBuffer();
262
+ return outputType === "arrayBuffer" ? buf : new TextDecoder().decode(buf);
263
+ });
264
+ }
265
+ function ab2str(buf) {
266
+ return getUnsafeWindow().btoa(
267
+ new Uint8Array(buf).reduce((data, byte) => data + String.fromCharCode(byte), "")
268
+ );
269
+ }
270
+ function str2ab(str) {
271
+ return Uint8Array.from(getUnsafeWindow().atob(str), (c) => c.charCodeAt(0));
272
+ }
273
+ function computeHash(input, algorithm = "SHA-256") {
274
+ return __async(this, null, function* () {
275
+ let data;
276
+ if (typeof input === "string") {
277
+ const encoder = new TextEncoder();
278
+ data = encoder.encode(input);
279
+ } else
280
+ data = input;
281
+ const hashBuffer = yield crypto.subtle.digest(algorithm, data);
282
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
283
+ const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
284
+ return hashHex;
285
+ });
286
+ }
287
+ function randomId(length = 16, radix = 16, enhancedEntropy = false) {
288
+ if (enhancedEntropy) {
289
+ const arr = new Uint8Array(length);
290
+ crypto.getRandomValues(arr);
291
+ return Array.from(
292
+ arr,
293
+ (v) => mapRange(v, 0, 255, 0, radix).toString(radix).substring(0, 1)
294
+ ).join("");
295
+ }
296
+ return Array.from(
297
+ { length },
298
+ () => Math.floor(Math.random() * radix).toString(radix)
299
+ ).join("");
300
+ }
301
+
111
302
  // lib/DataStore.ts
112
303
  var DataStore = class {
113
304
  /**
@@ -411,126 +602,6 @@ Has: ${checksum}`);
411
602
  });
412
603
  }
413
604
  };
414
-
415
- // lib/dom.ts
416
- function getUnsafeWindow() {
417
- try {
418
- return unsafeWindow;
419
- } catch (e) {
420
- return window;
421
- }
422
- }
423
- function addParent(element, newParent) {
424
- const oldParent = element.parentNode;
425
- if (!oldParent)
426
- throw new Error("Element doesn't have a parent node");
427
- oldParent.replaceChild(newParent, element);
428
- newParent.appendChild(element);
429
- return newParent;
430
- }
431
- function addGlobalStyle(style) {
432
- const styleElem = document.createElement("style");
433
- styleElem.innerHTML = style;
434
- document.head.appendChild(styleElem);
435
- return styleElem;
436
- }
437
- function preloadImages(srcUrls, rejects = false) {
438
- const promises = srcUrls.map((src) => new Promise((res, rej) => {
439
- const image = new Image();
440
- image.src = src;
441
- image.addEventListener("load", () => res(image));
442
- image.addEventListener("error", (evt) => rejects && rej(evt));
443
- }));
444
- return Promise.allSettled(promises);
445
- }
446
- function openInNewTab(href, background) {
447
- try {
448
- GM.openInTab(href, background);
449
- } catch (e) {
450
- const openElem = document.createElement("a");
451
- Object.assign(openElem, {
452
- className: "userutils-open-in-new-tab",
453
- target: "_blank",
454
- rel: "noopener noreferrer",
455
- href
456
- });
457
- openElem.style.display = "none";
458
- document.body.appendChild(openElem);
459
- openElem.click();
460
- setTimeout(openElem.remove, 50);
461
- }
462
- }
463
- function interceptEvent(eventObject, eventName, predicate = () => true) {
464
- Error.stackTraceLimit = Math.max(Error.stackTraceLimit, 100);
465
- if (isNaN(Error.stackTraceLimit))
466
- Error.stackTraceLimit = 100;
467
- (function(original) {
468
- eventObject.__proto__.addEventListener = function(...args) {
469
- var _a, _b;
470
- const origListener = typeof args[1] === "function" ? args[1] : (_b = (_a = args[1]) == null ? void 0 : _a.handleEvent) != null ? _b : () => void 0;
471
- args[1] = function(...a) {
472
- if (args[0] === eventName && predicate(Array.isArray(a) ? a[0] : a))
473
- return;
474
- else
475
- return origListener.apply(this, a);
476
- };
477
- original.apply(this, args);
478
- };
479
- })(eventObject.__proto__.addEventListener);
480
- }
481
- function interceptWindowEvent(eventName, predicate = () => true) {
482
- return interceptEvent(getUnsafeWindow(), eventName, predicate);
483
- }
484
- function isScrollable(element) {
485
- const { overflowX, overflowY } = getComputedStyle(element);
486
- return {
487
- vertical: (overflowY === "scroll" || overflowY === "auto") && element.scrollHeight > element.clientHeight,
488
- horizontal: (overflowX === "scroll" || overflowX === "auto") && element.scrollWidth > element.clientWidth
489
- };
490
- }
491
- function observeElementProp(element, property, callback) {
492
- const elementPrototype = Object.getPrototypeOf(element);
493
- if (elementPrototype.hasOwnProperty(property)) {
494
- const descriptor = Object.getOwnPropertyDescriptor(elementPrototype, property);
495
- Object.defineProperty(element, property, {
496
- get: function() {
497
- var _a;
498
- return (_a = descriptor == null ? void 0 : descriptor.get) == null ? void 0 : _a.apply(this, arguments);
499
- },
500
- set: function() {
501
- var _a;
502
- const oldValue = this[property];
503
- (_a = descriptor == null ? void 0 : descriptor.set) == null ? void 0 : _a.apply(this, arguments);
504
- const newValue = this[property];
505
- if (typeof callback === "function") {
506
- callback.bind(this, oldValue, newValue);
507
- }
508
- return newValue;
509
- }
510
- });
511
- }
512
- }
513
- function getSiblingsFrame(refElement, siblingAmount, refElementAlignment = "center-top", includeRef = true) {
514
- var _a, _b;
515
- const siblings = [...(_b = (_a = refElement.parentNode) == null ? void 0 : _a.childNodes) != null ? _b : []];
516
- const elemSiblIdx = siblings.indexOf(refElement);
517
- if (elemSiblIdx === -1)
518
- throw new Error("Element doesn't have a parent node");
519
- if (refElementAlignment === "top")
520
- return [...siblings.slice(elemSiblIdx + Number(!includeRef), elemSiblIdx + siblingAmount + Number(!includeRef))];
521
- else if (refElementAlignment.startsWith("center-")) {
522
- const halfAmount = (refElementAlignment === "center-bottom" ? Math.ceil : Math.floor)(siblingAmount / 2);
523
- const startIdx = Math.max(0, elemSiblIdx - halfAmount);
524
- const topOffset = Number(refElementAlignment === "center-top" && siblingAmount % 2 === 0 && includeRef);
525
- const btmOffset = Number(refElementAlignment === "center-bottom" && siblingAmount % 2 !== 0 && includeRef);
526
- const startIdxWithOffset = startIdx + topOffset + btmOffset;
527
- return [
528
- ...siblings.filter((_, idx) => includeRef || idx !== elemSiblIdx).slice(startIdxWithOffset, startIdxWithOffset + siblingAmount)
529
- ];
530
- } else if (refElementAlignment === "bottom")
531
- return [...siblings.slice(elemSiblIdx - siblingAmount + Number(includeRef), elemSiblIdx + Number(includeRef))];
532
- return [];
533
- }
534
605
  var NanoEmitter = class {
535
606
  constructor(options = {}) {
536
607
  __publicField(this, "events", createNanoEvents());
@@ -756,9 +827,8 @@ var Dialog = class _Dialog extends NanoEmitter {
756
827
  destroyOnClose: false,
757
828
  unmountOnClose: true,
758
829
  removeListenersOnDestroy: true,
759
- smallHeader: false,
760
- verticalAlign: "center",
761
- dialogCss: defaultDialogCss
830
+ small: false,
831
+ verticalAlign: "center"
762
832
  }, opts);
763
833
  this.id = opts.id;
764
834
  }
@@ -766,11 +836,12 @@ var Dialog = class _Dialog extends NanoEmitter {
766
836
  /** Call after DOMContentLoaded to pre-render the dialog and invisibly mount it in the DOM */
767
837
  mount() {
768
838
  return __async(this, null, function* () {
839
+ var _a;
769
840
  if (this.dialogMounted)
770
841
  return;
771
842
  this.dialogMounted = true;
772
843
  if (!document.querySelector("style.uu-dialog-css"))
773
- addGlobalStyle(this.options.dialogCss).classList.add("uu-dialog-css");
844
+ addGlobalStyle((_a = this.options.dialogCss) != null ? _a : defaultDialogCss).classList.add("uu-dialog-css");
774
845
  const bgElem = document.createElement("div");
775
846
  bgElem.id = `uu-${this.id}-dialog-bg`;
776
847
  bgElem.classList.add("uu-dialog-bg");
@@ -1007,6 +1078,13 @@ function autoPlural(word, num) {
1007
1078
  num = num.length;
1008
1079
  return `${word}${num === 1 ? "" : "s"}`;
1009
1080
  }
1081
+ function insertValues(input, ...values) {
1082
+ return input.replace(/%\d/gm, (match) => {
1083
+ var _a, _b;
1084
+ const argIndex = Number(match.substring(1)) - 1;
1085
+ return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
1086
+ });
1087
+ }
1010
1088
  function pauseFor(time) {
1011
1089
  return new Promise((res) => {
1012
1090
  setTimeout(() => res(), time);
@@ -1045,71 +1123,6 @@ function fetchAdvanced(_0) {
1045
1123
  }
1046
1124
  });
1047
1125
  }
1048
- function insertValues(input, ...values) {
1049
- return input.replace(/%\d/gm, (match) => {
1050
- var _a, _b;
1051
- const argIndex = Number(match.substring(1)) - 1;
1052
- return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
1053
- });
1054
- }
1055
- function compress(input, compressionFormat, outputType = "string") {
1056
- return __async(this, null, function* () {
1057
- const byteArray = typeof input === "string" ? new TextEncoder().encode(input) : input;
1058
- const comp = new CompressionStream(compressionFormat);
1059
- const writer = comp.writable.getWriter();
1060
- writer.write(byteArray);
1061
- writer.close();
1062
- const buf = yield new Response(comp.readable).arrayBuffer();
1063
- return outputType === "arrayBuffer" ? buf : ab2str(buf);
1064
- });
1065
- }
1066
- function decompress(input, compressionFormat, outputType = "string") {
1067
- return __async(this, null, function* () {
1068
- const byteArray = typeof input === "string" ? str2ab(input) : input;
1069
- const decomp = new DecompressionStream(compressionFormat);
1070
- const writer = decomp.writable.getWriter();
1071
- writer.write(byteArray);
1072
- writer.close();
1073
- const buf = yield new Response(decomp.readable).arrayBuffer();
1074
- return outputType === "arrayBuffer" ? buf : new TextDecoder().decode(buf);
1075
- });
1076
- }
1077
- function ab2str(buf) {
1078
- return getUnsafeWindow().btoa(
1079
- new Uint8Array(buf).reduce((data, byte) => data + String.fromCharCode(byte), "")
1080
- );
1081
- }
1082
- function str2ab(str) {
1083
- return Uint8Array.from(getUnsafeWindow().atob(str), (c) => c.charCodeAt(0));
1084
- }
1085
- function computeHash(input, algorithm = "SHA-256") {
1086
- return __async(this, null, function* () {
1087
- let data;
1088
- if (typeof input === "string") {
1089
- const encoder = new TextEncoder();
1090
- data = encoder.encode(input);
1091
- } else
1092
- data = input;
1093
- const hashBuffer = yield crypto.subtle.digest(algorithm, data);
1094
- const hashArray = Array.from(new Uint8Array(hashBuffer));
1095
- const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
1096
- return hashHex;
1097
- });
1098
- }
1099
- function randomId(length = 16, radix = 16, enhancedEntropy = false) {
1100
- if (enhancedEntropy) {
1101
- const arr = new Uint8Array(length);
1102
- crypto.getRandomValues(arr);
1103
- return Array.from(
1104
- arr,
1105
- (v) => mapRange(v, 0, 255, 0, radix).toString(radix).substring(0, 1)
1106
- ).join("");
1107
- }
1108
- return Array.from(
1109
- { length },
1110
- () => Math.floor(Math.random() * radix).toString(radix)
1111
- ).join("");
1112
- }
1113
1126
 
1114
1127
  // lib/SelectorObserver.ts
1115
1128
  var domLoaded = false;
@@ -1312,4 +1325,4 @@ tr.getLanguage = () => {
1312
1325
  return curLang;
1313
1326
  };
1314
1327
 
1315
- export { DataStore, DataStoreSerializer, Dialog, NanoEmitter, SelectorObserver, addGlobalStyle, addParent, autoPlural, clamp, compress, computeHash, currentDialogId, debounce, decompress, defaultDialogCss, defaultStrings, fetchAdvanced, getSiblingsFrame, getUnsafeWindow, insertValues, interceptEvent, interceptWindowEvent, isScrollable, mapRange, observeElementProp, openDialogs, openInNewTab, pauseFor, preloadImages, randRange, randomId, randomItem, randomItemIndex, randomizeArray, takeRandomItem, tr };
1328
+ export { DataStore, DataStoreSerializer, Dialog, NanoEmitter, SelectorObserver, addGlobalStyle, addParent, autoPlural, clamp, compress, computeHash, currentDialogId, debounce, decompress, defaultDialogCss, defaultStrings, fetchAdvanced, getSiblingsFrame, getUnsafeWindow, insertValues, interceptEvent, interceptWindowEvent, isScrollable, mapRange, observeElementProp, openDialogs, openInNewTab, pauseFor, preloadImages, randRange, randomId, randomItem, randomItemIndex, randomizeArray, setInnerHtmlUnsafe, takeRandomItem, tr };
@@ -1,5 +1,5 @@
1
1
  import { NanoEmitter } from "./NanoEmitter.js";
2
- export declare const defaultDialogCss = ".uu-no-select {\n user-select: none;\n}\n\n.uu-dialog-bg {\n --uu-dialog-bg: #333333;\n --uu-dialog-bg-highlight: #252525;\n --uu-scroll-indicator-bg: rgba(10, 10, 10, 0.7);\n --uu-dialog-separator-color: #797979;\n --uu-dialog-border-radius: 10px;\n}\n\n.uu-dialog-bg {\n display: block;\n position: fixed;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n z-index: 5;\n background-color: rgba(0, 0, 0, 0.6);\n}\n\n.uu-dialog {\n --uu-calc-dialog-height: calc(min(100vh - 40px, var(--uu-dialog-height-max)));\n position: absolute;\n display: flex;\n flex-direction: column;\n width: calc(min(100% - 60px, var(--uu-dialog-width-max)));\n border-radius: var(--uu-dialog-border-radius);\n height: auto;\n max-height: var(--uu-calc-dialog-height);\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%);\n z-index: 6;\n color: #fff;\n background-color: var(--uu-dialog-bg);\n}\n\n.uu-dialog.align-top {\n top: 0;\n transform: translate(-50%, 40px);\n}\n\n.uu-dialog.align-bottom {\n top: 100%;\n transform: translate(-50%, -100%);\n}\n\n.uu-dialog-body {\n font-size: 1.5rem;\n padding: 20px;\n}\n\n.uu-dialog-body.small {\n padding: 15px;\n}\n\n#uu-dialog-opts {\n display: flex;\n flex-direction: column;\n position: relative;\n padding: 30px 0px;\n overflow-y: auto;\n}\n\n.uu-dialog-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 6px;\n padding: 15px 20px 15px 20px;\n background-color: var(--uu-dialog-bg);\n border: 2px solid var(--uu-dialog-separator-color);\n border-style: none none solid none !important;\n border-radius: var(--uu-dialog-border-radius) var(--uu-dialog-border-radius) 0px 0px;\n}\n\n.uu-dialog-header.small {\n padding: 10px 15px;\n border-style: none none solid none !important;\n}\n\n.uu-dialog-header-pad {\n content: \" \";\n min-height: 32px;\n}\n\n.uu-dialog-header-pad.small {\n min-height: 24px;\n}\n\n.uu-dialog-titlecont {\n display: flex;\n align-items: center;\n}\n\n.uu-dialog-titlecont-no-title {\n display: flex;\n justify-content: flex-end;\n align-items: center;\n}\n\n.uu-dialog-title {\n position: relative;\n display: inline-block;\n font-size: 22px;\n}\n\n.uu-dialog-close {\n cursor: pointer;\n}\n\n.uu-dialog-header-img,\n.uu-dialog-close\n{\n width: 32px;\n height: 32px;\n}\n\n.uu-dialog-header-img.small,\n.uu-dialog-close.small\n{\n width: 24px;\n height: 24px;\n}\n\n.uu-dialog-footer {\n font-size: 17px;\n text-decoration: underline;\n}\n\n.uu-dialog-footer.hidden {\n display: none;\n}\n\n.uu-dialog-footer-cont {\n margin-top: 6px;\n padding: 15px 20px;\n background: var(--uu-dialog-bg);\n background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, var(--uu-dialog-bg) 30%, var(--uu-dialog-bg) 100%);\n border: 2px solid var(--uu-dialog-separator-color);\n border-style: solid none none none !important;\n border-radius: 0px 0px var(--uu-dialog-border-radius) var(--uu-dialog-border-radius);\n}\n\n.uu-dialog-footer-buttons-cont button:not(:last-of-type) {\n margin-right: 15px;\n}";
2
+ export declare const defaultDialogCss: string;
3
3
  /** ID of the last opened (top-most) dialog */
4
4
  export declare let currentDialogId: string | null;
5
5
  /** IDs of all currently open dialogs, top-most first */
@@ -56,43 +56,16 @@ export declare class Dialog extends NanoEmitter<{
56
56
  destroy: () => void;
57
57
  }> {
58
58
  /** Options passed to the dialog in the constructor */
59
- readonly options: {
60
- /** ID that gets added to child element IDs - has to be unique and conform to HTML ID naming rules! */
61
- id: string;
62
- /** Target and max width of the dialog in pixels */
63
- width: number;
64
- /** Target and max height of the dialog in pixels */
65
- height: number;
66
- closeOnBgClick: boolean;
67
- closeOnEscPress: boolean;
68
- destroyOnClose: boolean;
69
- unmountOnClose: boolean;
70
- removeListenersOnDestroy: boolean;
71
- /** Whether the dialog should have a smaller overall appearance - defaults to false */
72
- small?: boolean | undefined;
73
- verticalAlign: string;
74
- dialogCss: string;
75
- /** Called to render the body of the dialog */
76
- renderBody: () => HTMLElement | Promise<HTMLElement>;
77
- /** Called to render the header of the dialog - leave undefined for a blank header */
78
- renderHeader?: (() => HTMLElement | Promise<HTMLElement>) | undefined;
79
- /** Called to render the footer of the dialog - leave undefined for no footer */
80
- renderFooter?: (() => HTMLElement | Promise<HTMLElement>) | undefined;
81
- /** Called to render the close button of the dialog - leave undefined for no close button */
82
- renderCloseBtn?: (() => HTMLElement | Promise<HTMLElement>) | undefined;
83
- smallHeader: boolean;
84
- };
59
+ readonly options: DialogOptions;
85
60
  /** ID that gets added to child element IDs - has to be unique and conform to HTML ID naming rules! */
86
61
  readonly id: string;
87
62
  /** Strings used in the dialog (used for translations) */
88
- strings: {
89
- closeDialogTooltip: string;
90
- };
63
+ strings: typeof defaultStrings;
91
64
  protected dialogOpen: boolean;
92
65
  protected dialogMounted: boolean;
93
66
  constructor(options: DialogOptions);
94
67
  /** Call after DOMContentLoaded to pre-render the dialog and invisibly mount it in the DOM */
95
- mount(): Promise<HTMLDivElement | undefined>;
68
+ mount(): Promise<HTMLElement | void>;
96
69
  /** Closes the dialog and clears all its contents (unmounts elements from the DOM) in preparation for a new rendering call */
97
70
  unmount(): void;
98
71
  /** Clears the DOM of the dialog and then renders it again */
@@ -101,7 +74,7 @@ export declare class Dialog extends NanoEmitter<{
101
74
  * Opens the dialog - also mounts it if it hasn't been mounted yet
102
75
  * Prevents default action and immediate propagation of the passed event
103
76
  */
104
- open(e?: MouseEvent | KeyboardEvent): Promise<void | HTMLElement>;
77
+ open(e?: MouseEvent | KeyboardEvent): Promise<HTMLElement | void>;
105
78
  /** Closes the dialog - prevents default action and immediate propagation of the passed event */
106
79
  close(e?: MouseEvent | KeyboardEvent): void;
107
80
  /** Returns true if the dialog is currently open */
@@ -127,5 +100,5 @@ export declare class Dialog extends NanoEmitter<{
127
100
  stopPropagation?: boolean;
128
101
  }): void;
129
102
  /** Returns the dialog content element and all its children */
130
- protected getDialogContent(): Promise<HTMLDivElement>;
103
+ protected getDialogContent(): Promise<HTMLElement>;
131
104
  }
@@ -1,11 +1,11 @@
1
- import { type DefaultEvents, type EventsMap, type Unsubscribe } from "nanoevents";
1
+ import { type DefaultEvents, type Emitter, type EventsMap, type Unsubscribe } from "nanoevents";
2
2
  export interface NanoEmitterOptions {
3
3
  /** If set to true, allows emitting events through the public method emit() */
4
4
  publicEmit: boolean;
5
5
  }
6
6
  /** Class that can be extended or instantiated by itself to create an event emitter with helper methods and a strongly typed event map */
7
7
  export declare class NanoEmitter<TEvtMap extends EventsMap = DefaultEvents> {
8
- protected readonly events: import("nanoevents").Emitter<TEvtMap>;
8
+ protected readonly events: Emitter<TEvtMap>;
9
9
  protected eventUnsubscribes: Unsubscribe[];
10
10
  protected emitterOptions: NanoEmitterOptions;
11
11
  constructor(options?: Partial<NanoEmitterOptions>);
@@ -0,0 +1,18 @@
1
+ /** Converts a hex color string to a tuple of RGB values */
2
+ export declare function hexToRgb(hex: string): [red: number, green: number, blue: number];
3
+ /** Converts RGB values to a hex color string */
4
+ export declare function rgbToHex(red: number, green: number, blue: number, withHash?: boolean, upperCase?: boolean): string;
5
+ /**
6
+ * Lightens a CSS color value (in hex, RGB or RGBA format) by a given percentage.
7
+ * Will not exceed the maximum range (00-FF or 0-255).
8
+ * @returns Returns the new color value in the same format as the input
9
+ * @throws Throws if the color format is invalid or not supported
10
+ */
11
+ export declare function lightenColor(color: string, percent: number): string;
12
+ /**
13
+ * Darkens a CSS color value (in hex, RGB or RGBA format) by a given percentage.
14
+ * Will not exceed the maximum range (00-FF or 0-255).
15
+ * @returns Returns the new color value in the same format as the input
16
+ * @throws Throws if the color format is invalid or not supported
17
+ */
18
+ export declare function darkenColor(color: string, percent: number): string;
@@ -0,0 +1,24 @@
1
+ /** Compresses a string or an ArrayBuffer using the provided {@linkcode compressionFormat} and returns it as a base64 string */
2
+ export declare function compress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType?: "string"): Promise<string>;
3
+ /** Compresses a string or an ArrayBuffer using the provided {@linkcode compressionFormat} and returns it as an ArrayBuffer */
4
+ export declare function compress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType: "arrayBuffer"): Promise<ArrayBuffer>;
5
+ /** Decompresses a previously compressed base64 string or ArrayBuffer, with the format passed by {@linkcode compressionFormat}, converted to a string */
6
+ export declare function decompress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType?: "string"): Promise<string>;
7
+ /** Decompresses a previously compressed base64 string or ArrayBuffer, with the format passed by {@linkcode compressionFormat}, converted to an ArrayBuffer */
8
+ export declare function decompress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType: "arrayBuffer"): Promise<ArrayBuffer>;
9
+ /**
10
+ * Creates a hash / checksum of the given {@linkcode input} string or ArrayBuffer using the specified {@linkcode algorithm} ("SHA-256" by default).
11
+ *
12
+ * ⚠️ Uses the SubtleCrypto API so it needs to run in a secure context (HTTPS).
13
+ * ⚠️ 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.
14
+ */
15
+ export declare function computeHash(input: string | ArrayBuffer, algorithm?: string): Promise<string>;
16
+ /**
17
+ * Generates a random ID with the specified length and radix (16 characters and hexadecimal by default)
18
+ *
19
+ * ⚠️ 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.
20
+ * @param length The length of the ID to generate (defaults to 16)
21
+ * @param radix The [radix](https://en.wikipedia.org/wiki/Radix) of each digit (defaults to 16 which is hexadecimal. Use 2 for binary, 10 for decimal, 36 for alphanumeric, etc.)
22
+ * @param enhancedEntropy If set to true, uses [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) for better cryptographic randomness (this also makes it take MUCH longer to generate)
23
+ */
24
+ export declare function randomId(length?: number, radix?: number, enhancedEntropy?: boolean): string;
package/dist/lib/dom.d.ts CHANGED
@@ -63,3 +63,11 @@ export declare function observeElementProp<TElem extends Element = HTMLElement,
63
63
  * @returns An array of sibling elements
64
64
  */
65
65
  export declare function getSiblingsFrame<TSibling extends Element = HTMLElement>(refElement: Element, siblingAmount: number, refElementAlignment?: "center-top" | "center-bottom" | "top" | "bottom", includeRef?: boolean): TSibling[];
66
+ /**
67
+ * Sets the innerHTML property of the provided element without any sanitation or validation.
68
+ * Uses a [Trusted Types policy](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API) on Chromium-based browsers to trick the browser into thinking the HTML is safe.
69
+ * Use this 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.
70
+ *
71
+ * ⚠️ This function does not perform any sanitization and should thus be used with utmost caution, as it can easily lead to XSS vulnerabilities!
72
+ */
73
+ export declare function setInnerHtmlUnsafe<TElement extends Element = HTMLElement>(element: TElement, html: string): TElement;
@@ -1,4 +1,5 @@
1
1
  export * from "./array.js";
2
+ export * from "./crypto.js";
2
3
  export * from "./DataStore.js";
3
4
  export * from "./DataStoreSerializer.js";
4
5
  export * from "./Dialog.js";
@@ -5,6 +5,13 @@ import type { Stringifiable } from "./types.js";
5
5
  * @param num If this is an array or NodeList, the amount of items is used
6
6
  */
7
7
  export declare function autoPlural(word: Stringifiable, num: number | unknown[] | NodeList): string;
8
+ /**
9
+ * Inserts the passed values into a string at the respective placeholders.
10
+ * The placeholder format is `%n`, where `n` is the 1-indexed argument number.
11
+ * @param input The string to insert the values into
12
+ * @param values The values to insert, in order, starting at `%1`
13
+ */
14
+ export declare function insertValues(input: string, ...values: Stringifiable[]): string;
8
15
  /** Pauses async execution for the specified time in ms */
9
16
  export declare function pauseFor(time: number): Promise<void>;
10
17
  /**
@@ -23,34 +30,3 @@ export type FetchAdvancedOpts = Omit<RequestInit & Partial<{
23
30
  }>, "signal">;
24
31
  /** Calls the fetch API with special options like a timeout */
25
32
  export declare function fetchAdvanced(input: RequestInfo | URL, options?: FetchAdvancedOpts): Promise<Response>;
26
- /**
27
- * Inserts the passed values into a string at the respective placeholders.
28
- * The placeholder format is `%n`, where `n` is the 1-indexed argument number.
29
- * @param input The string to insert the values into
30
- * @param values The values to insert, in order, starting at `%1`
31
- */
32
- export declare function insertValues(input: string, ...values: Stringifiable[]): string;
33
- /** Compresses a string or an ArrayBuffer using the provided {@linkcode compressionFormat} and returns it as a base64 string */
34
- export declare function compress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType?: "string"): Promise<string>;
35
- /** Compresses a string or an ArrayBuffer using the provided {@linkcode compressionFormat} and returns it as an ArrayBuffer */
36
- export declare function compress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType: "arrayBuffer"): Promise<ArrayBuffer>;
37
- /** Decompresses a previously compressed base64 string or ArrayBuffer, with the format passed by {@linkcode compressionFormat}, converted to a string */
38
- export declare function decompress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType?: "string"): Promise<string>;
39
- /** Decompresses a previously compressed base64 string or ArrayBuffer, with the format passed by {@linkcode compressionFormat}, converted to an ArrayBuffer */
40
- export declare function decompress(input: string | ArrayBuffer, compressionFormat: CompressionFormat, outputType: "arrayBuffer"): Promise<ArrayBuffer>;
41
- /**
42
- * Creates a hash / checksum of the given {@linkcode input} string or ArrayBuffer using the specified {@linkcode algorithm} ("SHA-256" by default).
43
- *
44
- * ⚠️ Uses the SubtleCrypto API so it needs to run in a secure context (HTTPS).
45
- * ⚠️ 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.
46
- */
47
- export declare function computeHash(input: string | ArrayBuffer, algorithm?: string): Promise<string>;
48
- /**
49
- * Generates a random ID with the specified length and radix (16 characters and hexadecimal by default)
50
- *
51
- * ⚠️ 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.
52
- * @param length The length of the ID to generate (defaults to 16)
53
- * @param radix The [radix](https://en.wikipedia.org/wiki/Radix) of each digit (defaults to 16 which is hexadecimal. Use 2 for binary, 10 for decimal, 36 for alphanumeric, etc.)
54
- * @param enhancedEntropy If set to true, uses [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) for better cryptographic randomness (this also makes it take MUCH longer to generate)
55
- */
56
- export declare function randomId(length?: number, radix?: number, enhancedEntropy?: boolean): string;
@@ -1,3 +1,13 @@
1
+ export type TrustedTypesPolicy = {
2
+ createHTML?: (dirty: string) => string;
3
+ };
4
+ declare global {
5
+ interface Window {
6
+ trustedTypes: {
7
+ createPolicy(name: string, policy: TrustedTypesPolicy): TrustedTypesPolicy;
8
+ };
9
+ }
10
+ }
1
11
  /** Represents any value that is either a string itself or can be converted to one (implicitly and explicitly) because it has a toString() method */
2
12
  export type Stringifiable = string | {
3
13
  toString(): string;