@sv443-network/userutils 7.0.1 → 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.
@@ -8,7 +8,7 @@
8
8
  // ==UserLibrary==
9
9
  // @name UserUtils
10
10
  // @description 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
11
- // @version 7.0.1
11
+ // @version 7.2.0
12
12
  // @license MIT
13
13
  // @copyright Sv443 (https://github.com/Sv443)
14
14
 
@@ -128,6 +128,197 @@ var UserUtils = (function (exports) {
128
128
  return retArray;
129
129
  }
130
130
 
131
+ // lib/dom.ts
132
+ function getUnsafeWindow() {
133
+ try {
134
+ return unsafeWindow;
135
+ } catch (e) {
136
+ return window;
137
+ }
138
+ }
139
+ function addParent(element, newParent) {
140
+ const oldParent = element.parentNode;
141
+ if (!oldParent)
142
+ throw new Error("Element doesn't have a parent node");
143
+ oldParent.replaceChild(newParent, element);
144
+ newParent.appendChild(element);
145
+ return newParent;
146
+ }
147
+ function addGlobalStyle(style) {
148
+ const styleElem = document.createElement("style");
149
+ setInnerHtmlUnsafe(styleElem, style);
150
+ document.head.appendChild(styleElem);
151
+ return styleElem;
152
+ }
153
+ function preloadImages(srcUrls, rejects = false) {
154
+ const promises = srcUrls.map((src) => new Promise((res, rej) => {
155
+ const image = new Image();
156
+ image.src = src;
157
+ image.addEventListener("load", () => res(image));
158
+ image.addEventListener("error", (evt) => rejects && rej(evt));
159
+ }));
160
+ return Promise.allSettled(promises);
161
+ }
162
+ function openInNewTab(href, background) {
163
+ try {
164
+ GM.openInTab(href, background);
165
+ } catch (e) {
166
+ const openElem = document.createElement("a");
167
+ Object.assign(openElem, {
168
+ className: "userutils-open-in-new-tab",
169
+ target: "_blank",
170
+ rel: "noopener noreferrer",
171
+ href
172
+ });
173
+ openElem.style.display = "none";
174
+ document.body.appendChild(openElem);
175
+ openElem.click();
176
+ setTimeout(openElem.remove, 50);
177
+ }
178
+ }
179
+ function interceptEvent(eventObject, eventName, predicate = () => true) {
180
+ Error.stackTraceLimit = Math.max(Error.stackTraceLimit, 100);
181
+ if (isNaN(Error.stackTraceLimit))
182
+ Error.stackTraceLimit = 100;
183
+ (function(original) {
184
+ eventObject.__proto__.addEventListener = function(...args) {
185
+ var _a, _b;
186
+ const origListener = typeof args[1] === "function" ? args[1] : (_b = (_a = args[1]) == null ? void 0 : _a.handleEvent) != null ? _b : () => void 0;
187
+ args[1] = function(...a) {
188
+ if (args[0] === eventName && predicate(Array.isArray(a) ? a[0] : a))
189
+ return;
190
+ else
191
+ return origListener.apply(this, a);
192
+ };
193
+ original.apply(this, args);
194
+ };
195
+ })(eventObject.__proto__.addEventListener);
196
+ }
197
+ function interceptWindowEvent(eventName, predicate = () => true) {
198
+ return interceptEvent(getUnsafeWindow(), eventName, predicate);
199
+ }
200
+ function isScrollable(element) {
201
+ const { overflowX, overflowY } = getComputedStyle(element);
202
+ return {
203
+ vertical: (overflowY === "scroll" || overflowY === "auto") && element.scrollHeight > element.clientHeight,
204
+ horizontal: (overflowX === "scroll" || overflowX === "auto") && element.scrollWidth > element.clientWidth
205
+ };
206
+ }
207
+ function observeElementProp(element, property, callback) {
208
+ const elementPrototype = Object.getPrototypeOf(element);
209
+ if (elementPrototype.hasOwnProperty(property)) {
210
+ const descriptor = Object.getOwnPropertyDescriptor(elementPrototype, property);
211
+ Object.defineProperty(element, property, {
212
+ get: function() {
213
+ var _a;
214
+ return (_a = descriptor == null ? void 0 : descriptor.get) == null ? void 0 : _a.apply(this, arguments);
215
+ },
216
+ set: function() {
217
+ var _a;
218
+ const oldValue = this[property];
219
+ (_a = descriptor == null ? void 0 : descriptor.set) == null ? void 0 : _a.apply(this, arguments);
220
+ const newValue = this[property];
221
+ if (typeof callback === "function") {
222
+ callback.bind(this, oldValue, newValue);
223
+ }
224
+ return newValue;
225
+ }
226
+ });
227
+ }
228
+ }
229
+ function getSiblingsFrame(refElement, siblingAmount, refElementAlignment = "center-top", includeRef = true) {
230
+ var _a, _b;
231
+ const siblings = [...(_b = (_a = refElement.parentNode) == null ? void 0 : _a.childNodes) != null ? _b : []];
232
+ const elemSiblIdx = siblings.indexOf(refElement);
233
+ if (elemSiblIdx === -1)
234
+ throw new Error("Element doesn't have a parent node");
235
+ if (refElementAlignment === "top")
236
+ return [...siblings.slice(elemSiblIdx + Number(!includeRef), elemSiblIdx + siblingAmount + Number(!includeRef))];
237
+ else if (refElementAlignment.startsWith("center-")) {
238
+ const halfAmount = (refElementAlignment === "center-bottom" ? Math.ceil : Math.floor)(siblingAmount / 2);
239
+ const startIdx = Math.max(0, elemSiblIdx - halfAmount);
240
+ const topOffset = Number(refElementAlignment === "center-top" && siblingAmount % 2 === 0 && includeRef);
241
+ const btmOffset = Number(refElementAlignment === "center-bottom" && siblingAmount % 2 !== 0 && includeRef);
242
+ const startIdxWithOffset = startIdx + topOffset + btmOffset;
243
+ return [
244
+ ...siblings.filter((_, idx) => includeRef || idx !== elemSiblIdx).slice(startIdxWithOffset, startIdxWithOffset + siblingAmount)
245
+ ];
246
+ } else if (refElementAlignment === "bottom")
247
+ return [...siblings.slice(elemSiblIdx - siblingAmount + Number(includeRef), elemSiblIdx + Number(includeRef))];
248
+ return [];
249
+ }
250
+ var ttPolicy;
251
+ function setInnerHtmlUnsafe(element, html) {
252
+ var _a, _b, _c;
253
+ if (!ttPolicy && typeof ((_a = window == null ? void 0 : window.trustedTypes) == null ? void 0 : _a.createPolicy) === "function") {
254
+ ttPolicy = window.trustedTypes.createPolicy("_uu_set_innerhtml_unsafe", {
255
+ createHTML: (unsafeHtml) => unsafeHtml
256
+ });
257
+ }
258
+ element.innerHTML = (_c = (_b = ttPolicy == null ? void 0 : ttPolicy.createHTML) == null ? void 0 : _b.call(ttPolicy, html)) != null ? _c : html;
259
+ return element;
260
+ }
261
+
262
+ // lib/crypto.ts
263
+ function compress(input, compressionFormat, outputType = "string") {
264
+ return __async(this, null, function* () {
265
+ const byteArray = typeof input === "string" ? new TextEncoder().encode(input) : input;
266
+ const comp = new CompressionStream(compressionFormat);
267
+ const writer = comp.writable.getWriter();
268
+ writer.write(byteArray);
269
+ writer.close();
270
+ const buf = yield new Response(comp.readable).arrayBuffer();
271
+ return outputType === "arrayBuffer" ? buf : ab2str(buf);
272
+ });
273
+ }
274
+ function decompress(input, compressionFormat, outputType = "string") {
275
+ return __async(this, null, function* () {
276
+ const byteArray = typeof input === "string" ? str2ab(input) : input;
277
+ const decomp = new DecompressionStream(compressionFormat);
278
+ const writer = decomp.writable.getWriter();
279
+ writer.write(byteArray);
280
+ writer.close();
281
+ const buf = yield new Response(decomp.readable).arrayBuffer();
282
+ return outputType === "arrayBuffer" ? buf : new TextDecoder().decode(buf);
283
+ });
284
+ }
285
+ function ab2str(buf) {
286
+ return getUnsafeWindow().btoa(
287
+ new Uint8Array(buf).reduce((data, byte) => data + String.fromCharCode(byte), "")
288
+ );
289
+ }
290
+ function str2ab(str) {
291
+ return Uint8Array.from(getUnsafeWindow().atob(str), (c) => c.charCodeAt(0));
292
+ }
293
+ function computeHash(input, algorithm = "SHA-256") {
294
+ return __async(this, null, function* () {
295
+ let data;
296
+ if (typeof input === "string") {
297
+ const encoder = new TextEncoder();
298
+ data = encoder.encode(input);
299
+ } else
300
+ data = input;
301
+ const hashBuffer = yield crypto.subtle.digest(algorithm, data);
302
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
303
+ const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
304
+ return hashHex;
305
+ });
306
+ }
307
+ function randomId(length = 16, radix = 16, enhancedEntropy = false) {
308
+ if (enhancedEntropy) {
309
+ const arr = new Uint8Array(length);
310
+ crypto.getRandomValues(arr);
311
+ return Array.from(
312
+ arr,
313
+ (v) => mapRange(v, 0, 255, 0, radix).toString(radix).substring(0, 1)
314
+ ).join("");
315
+ }
316
+ return Array.from(
317
+ { length },
318
+ () => Math.floor(Math.random() * radix).toString(radix)
319
+ ).join("");
320
+ }
321
+
131
322
  // lib/DataStore.ts
132
323
  var DataStore = class {
133
324
  /**
@@ -432,125 +623,494 @@ Has: ${checksum}`);
432
623
  }
433
624
  };
434
625
 
435
- // lib/dom.ts
436
- function getUnsafeWindow() {
437
- try {
438
- return unsafeWindow;
439
- } catch (e) {
440
- return window;
626
+ // node_modules/nanoevents/index.js
627
+ var createNanoEvents = () => ({
628
+ emit(event, ...args) {
629
+ for (let i = 0, callbacks = this.events[event] || [], length = callbacks.length; i < length; i++) {
630
+ callbacks[i](...args);
631
+ }
632
+ },
633
+ events: {},
634
+ on(event, cb) {
635
+ var _a;
636
+ ((_a = this.events)[event] || (_a[event] = [])).push(cb);
637
+ return () => {
638
+ var _a2;
639
+ this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
640
+ };
441
641
  }
442
- }
443
- function addParent(element, newParent) {
444
- const oldParent = element.parentNode;
445
- if (!oldParent)
446
- throw new Error("Element doesn't have a parent node");
447
- oldParent.replaceChild(newParent, element);
448
- newParent.appendChild(element);
449
- return newParent;
450
- }
451
- function addGlobalStyle(style) {
452
- const styleElem = document.createElement("style");
453
- styleElem.innerHTML = style;
454
- document.head.appendChild(styleElem);
455
- return styleElem;
456
- }
457
- function preloadImages(srcUrls, rejects = false) {
458
- const promises = srcUrls.map((src) => new Promise((res, rej) => {
459
- const image = new Image();
460
- image.src = src;
461
- image.addEventListener("load", () => res(image));
462
- image.addEventListener("error", (evt) => rejects && rej(evt));
463
- }));
464
- return Promise.allSettled(promises);
465
- }
466
- function openInNewTab(href, background) {
467
- try {
468
- GM.openInTab(href, background);
469
- } catch (e) {
470
- const openElem = document.createElement("a");
471
- Object.assign(openElem, {
472
- className: "userutils-open-in-new-tab",
473
- target: "_blank",
474
- rel: "noopener noreferrer",
475
- href
642
+ });
643
+
644
+ // lib/NanoEmitter.ts
645
+ var NanoEmitter = class {
646
+ constructor(options = {}) {
647
+ __publicField(this, "events", createNanoEvents());
648
+ __publicField(this, "eventUnsubscribes", []);
649
+ __publicField(this, "emitterOptions");
650
+ this.emitterOptions = __spreadValues({
651
+ publicEmit: false
652
+ }, options);
653
+ }
654
+ /** Subscribes to an event - returns a function that unsubscribes the event listener */
655
+ on(event, cb) {
656
+ let unsub;
657
+ const unsubProxy = () => {
658
+ if (!unsub)
659
+ return;
660
+ unsub();
661
+ this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => u !== unsub);
662
+ };
663
+ unsub = this.events.on(event, cb);
664
+ this.eventUnsubscribes.push(unsub);
665
+ return unsubProxy;
666
+ }
667
+ /** Subscribes to an event and calls the callback or resolves the Promise only once */
668
+ once(event, cb) {
669
+ return new Promise((resolve) => {
670
+ let unsub;
671
+ const onceProxy = (...args) => {
672
+ unsub();
673
+ cb == null ? void 0 : cb(...args);
674
+ resolve(args);
675
+ };
676
+ unsub = this.on(event, onceProxy);
476
677
  });
477
- openElem.style.display = "none";
478
- document.body.appendChild(openElem);
479
- openElem.click();
480
- setTimeout(openElem.remove, 50);
481
678
  }
482
- }
483
- function interceptEvent(eventObject, eventName, predicate = () => true) {
484
- Error.stackTraceLimit = Math.max(Error.stackTraceLimit, 100);
485
- if (isNaN(Error.stackTraceLimit))
486
- Error.stackTraceLimit = 100;
487
- (function(original) {
488
- eventObject.__proto__.addEventListener = function(...args) {
489
- var _a, _b;
490
- const origListener = typeof args[1] === "function" ? args[1] : (_b = (_a = args[1]) == null ? void 0 : _a.handleEvent) != null ? _b : () => void 0;
491
- args[1] = function(...a) {
492
- if (args[0] === eventName && predicate(Array.isArray(a) ? a[0] : a))
679
+ /** Emits an event on this instance - Needs `publicEmit` to be set to true in the constructor! */
680
+ emit(event, ...args) {
681
+ if (this.emitterOptions.publicEmit) {
682
+ this.events.emit(event, ...args);
683
+ return true;
684
+ }
685
+ return false;
686
+ }
687
+ /** Unsubscribes all event listeners */
688
+ unsubscribeAll() {
689
+ for (const unsub of this.eventUnsubscribes)
690
+ unsub();
691
+ this.eventUnsubscribes = [];
692
+ }
693
+ };
694
+
695
+ // lib/Dialog.ts
696
+ var defaultDialogCss = `.uu-no-select {
697
+ user-select: none;
698
+ }
699
+
700
+ .uu-dialog-bg {
701
+ --uu-dialog-bg: #333333;
702
+ --uu-dialog-bg-highlight: #252525;
703
+ --uu-scroll-indicator-bg: rgba(10, 10, 10, 0.7);
704
+ --uu-dialog-separator-color: #797979;
705
+ --uu-dialog-border-radius: 10px;
706
+ }
707
+
708
+ .uu-dialog-bg {
709
+ display: block;
710
+ position: fixed;
711
+ width: 100%;
712
+ height: 100%;
713
+ top: 0;
714
+ left: 0;
715
+ z-index: 5;
716
+ background-color: rgba(0, 0, 0, 0.6);
717
+ }
718
+
719
+ .uu-dialog {
720
+ --uu-calc-dialog-height: calc(min(100vh - 40px, var(--uu-dialog-height-max)));
721
+ position: absolute;
722
+ display: flex;
723
+ flex-direction: column;
724
+ width: calc(min(100% - 60px, var(--uu-dialog-width-max)));
725
+ border-radius: var(--uu-dialog-border-radius);
726
+ height: auto;
727
+ max-height: var(--uu-calc-dialog-height);
728
+ left: 50%;
729
+ top: 50%;
730
+ transform: translate(-50%, -50%);
731
+ z-index: 6;
732
+ color: #fff;
733
+ background-color: var(--uu-dialog-bg);
734
+ }
735
+
736
+ .uu-dialog.align-top {
737
+ top: 0;
738
+ transform: translate(-50%, 40px);
739
+ }
740
+
741
+ .uu-dialog.align-bottom {
742
+ top: 100%;
743
+ transform: translate(-50%, -100%);
744
+ }
745
+
746
+ .uu-dialog-body {
747
+ font-size: 1.5rem;
748
+ padding: 20px;
749
+ }
750
+
751
+ .uu-dialog-body.small {
752
+ padding: 15px;
753
+ }
754
+
755
+ #uu-dialog-opts {
756
+ display: flex;
757
+ flex-direction: column;
758
+ position: relative;
759
+ padding: 30px 0px;
760
+ overflow-y: auto;
761
+ }
762
+
763
+ .uu-dialog-header {
764
+ display: flex;
765
+ justify-content: space-between;
766
+ align-items: center;
767
+ margin-bottom: 6px;
768
+ padding: 15px 20px 15px 20px;
769
+ background-color: var(--uu-dialog-bg);
770
+ border: 2px solid var(--uu-dialog-separator-color);
771
+ border-style: none none solid none !important;
772
+ border-radius: var(--uu-dialog-border-radius) var(--uu-dialog-border-radius) 0px 0px;
773
+ }
774
+
775
+ .uu-dialog-header.small {
776
+ padding: 10px 15px;
777
+ border-style: none none solid none !important;
778
+ }
779
+
780
+ .uu-dialog-header-pad {
781
+ content: " ";
782
+ min-height: 32px;
783
+ }
784
+
785
+ .uu-dialog-header-pad.small {
786
+ min-height: 24px;
787
+ }
788
+
789
+ .uu-dialog-titlecont {
790
+ display: flex;
791
+ align-items: center;
792
+ }
793
+
794
+ .uu-dialog-titlecont-no-title {
795
+ display: flex;
796
+ justify-content: flex-end;
797
+ align-items: center;
798
+ }
799
+
800
+ .uu-dialog-title {
801
+ position: relative;
802
+ display: inline-block;
803
+ font-size: 22px;
804
+ }
805
+
806
+ .uu-dialog-close {
807
+ cursor: pointer;
808
+ }
809
+
810
+ .uu-dialog-header-img,
811
+ .uu-dialog-close
812
+ {
813
+ width: 32px;
814
+ height: 32px;
815
+ }
816
+
817
+ .uu-dialog-header-img.small,
818
+ .uu-dialog-close.small
819
+ {
820
+ width: 24px;
821
+ height: 24px;
822
+ }
823
+
824
+ .uu-dialog-footer {
825
+ font-size: 17px;
826
+ text-decoration: underline;
827
+ }
828
+
829
+ .uu-dialog-footer.hidden {
830
+ display: none;
831
+ }
832
+
833
+ .uu-dialog-footer-cont {
834
+ margin-top: 6px;
835
+ padding: 15px 20px;
836
+ background: var(--uu-dialog-bg);
837
+ background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, var(--uu-dialog-bg) 30%, var(--uu-dialog-bg) 100%);
838
+ border: 2px solid var(--uu-dialog-separator-color);
839
+ border-style: solid none none none !important;
840
+ border-radius: 0px 0px var(--uu-dialog-border-radius) var(--uu-dialog-border-radius);
841
+ }
842
+
843
+ .uu-dialog-footer-buttons-cont button:not(:last-of-type) {
844
+ margin-right: 15px;
845
+ }`;
846
+ exports.currentDialogId = null;
847
+ var openDialogs = [];
848
+ var defaultStrings = {
849
+ closeDialogTooltip: "Click to close the dialog"
850
+ };
851
+ var Dialog = class _Dialog extends NanoEmitter {
852
+ constructor(options) {
853
+ super();
854
+ /** Options passed to the dialog in the constructor */
855
+ __publicField(this, "options");
856
+ /** ID that gets added to child element IDs - has to be unique and conform to HTML ID naming rules! */
857
+ __publicField(this, "id");
858
+ /** Strings used in the dialog (used for translations) */
859
+ __publicField(this, "strings");
860
+ __publicField(this, "dialogOpen", false);
861
+ __publicField(this, "dialogMounted", false);
862
+ const _a = options, { strings } = _a, opts = __objRest(_a, ["strings"]);
863
+ this.strings = __spreadValues(__spreadValues({}, defaultStrings), strings != null ? strings : {});
864
+ this.options = __spreadValues({
865
+ closeOnBgClick: true,
866
+ closeOnEscPress: true,
867
+ destroyOnClose: false,
868
+ unmountOnClose: true,
869
+ removeListenersOnDestroy: true,
870
+ small: false,
871
+ verticalAlign: "center"
872
+ }, opts);
873
+ this.id = opts.id;
874
+ }
875
+ //#region public
876
+ /** Call after DOMContentLoaded to pre-render the dialog and invisibly mount it in the DOM */
877
+ mount() {
878
+ return __async(this, null, function* () {
879
+ var _a;
880
+ if (this.dialogMounted)
881
+ return;
882
+ this.dialogMounted = true;
883
+ if (!document.querySelector("style.uu-dialog-css"))
884
+ addGlobalStyle((_a = this.options.dialogCss) != null ? _a : defaultDialogCss).classList.add("uu-dialog-css");
885
+ const bgElem = document.createElement("div");
886
+ bgElem.id = `uu-${this.id}-dialog-bg`;
887
+ bgElem.classList.add("uu-dialog-bg");
888
+ if (this.options.closeOnBgClick)
889
+ bgElem.ariaLabel = bgElem.title = this.getString("closeDialogTooltip");
890
+ bgElem.style.setProperty("--uu-dialog-width-max", `${this.options.width}px`);
891
+ bgElem.style.setProperty("--uu-dialog-height-max", `${this.options.height}px`);
892
+ bgElem.style.visibility = "hidden";
893
+ bgElem.style.display = "none";
894
+ bgElem.inert = true;
895
+ bgElem.appendChild(yield this.getDialogContent());
896
+ document.body.appendChild(bgElem);
897
+ this.attachListeners(bgElem);
898
+ this.events.emit("render");
899
+ return bgElem;
900
+ });
901
+ }
902
+ /** Closes the dialog and clears all its contents (unmounts elements from the DOM) in preparation for a new rendering call */
903
+ unmount() {
904
+ var _a;
905
+ this.close();
906
+ this.dialogMounted = false;
907
+ const clearSelectors = [
908
+ `#uu-${this.id}-dialog-bg`,
909
+ `#uu-style-dialog-${this.id}`
910
+ ];
911
+ for (const sel of clearSelectors)
912
+ (_a = document.querySelector(sel)) == null ? void 0 : _a.remove();
913
+ this.events.emit("clear");
914
+ }
915
+ /** Clears the DOM of the dialog and then renders it again */
916
+ remount() {
917
+ return __async(this, null, function* () {
918
+ this.unmount();
919
+ yield this.mount();
920
+ });
921
+ }
922
+ /**
923
+ * Opens the dialog - also mounts it if it hasn't been mounted yet
924
+ * Prevents default action and immediate propagation of the passed event
925
+ */
926
+ open(e) {
927
+ return __async(this, null, function* () {
928
+ var _a;
929
+ e == null ? void 0 : e.preventDefault();
930
+ e == null ? void 0 : e.stopImmediatePropagation();
931
+ if (this.isOpen())
932
+ return;
933
+ this.dialogOpen = true;
934
+ if (openDialogs.includes(this.id))
935
+ throw new Error(`A dialog with the same ID of '${this.id}' already exists and is open!`);
936
+ if (!this.isMounted())
937
+ yield this.mount();
938
+ const dialogBg = document.querySelector(`#uu-${this.id}-dialog-bg`);
939
+ if (!dialogBg)
940
+ return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
941
+ dialogBg.style.visibility = "visible";
942
+ dialogBg.style.display = "block";
943
+ dialogBg.inert = false;
944
+ exports.currentDialogId = this.id;
945
+ openDialogs.unshift(this.id);
946
+ for (const dialogId of openDialogs)
947
+ if (dialogId !== this.id)
948
+ (_a = document.querySelector(`#uu-${dialogId}-dialog-bg`)) == null ? void 0 : _a.setAttribute("inert", "true");
949
+ document.body.classList.remove("uu-no-select");
950
+ document.body.setAttribute("inert", "true");
951
+ this.events.emit("open");
952
+ return dialogBg;
953
+ });
954
+ }
955
+ /** Closes the dialog - prevents default action and immediate propagation of the passed event */
956
+ close(e) {
957
+ var _a, _b;
958
+ e == null ? void 0 : e.preventDefault();
959
+ e == null ? void 0 : e.stopImmediatePropagation();
960
+ if (!this.isOpen())
961
+ return;
962
+ this.dialogOpen = false;
963
+ const dialogBg = document.querySelector(`#uu-${this.id}-dialog-bg`);
964
+ if (!dialogBg)
965
+ return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
966
+ dialogBg.style.visibility = "hidden";
967
+ dialogBg.style.display = "none";
968
+ dialogBg.inert = true;
969
+ openDialogs.splice(openDialogs.indexOf(this.id), 1);
970
+ exports.currentDialogId = (_a = openDialogs[0]) != null ? _a : null;
971
+ if (exports.currentDialogId)
972
+ (_b = document.querySelector(`#uu-${exports.currentDialogId}-dialog-bg`)) == null ? void 0 : _b.removeAttribute("inert");
973
+ if (openDialogs.length === 0) {
974
+ document.body.classList.add("uu-no-select");
975
+ document.body.removeAttribute("inert");
976
+ }
977
+ this.events.emit("close");
978
+ if (this.options.destroyOnClose)
979
+ this.destroy();
980
+ else if (this.options.unmountOnClose)
981
+ this.unmount();
982
+ }
983
+ /** Returns true if the dialog is currently open */
984
+ isOpen() {
985
+ return this.dialogOpen;
986
+ }
987
+ /** Returns true if the dialog is currently mounted */
988
+ isMounted() {
989
+ return this.dialogMounted;
990
+ }
991
+ /** Clears the DOM of the dialog and removes all event listeners */
992
+ destroy() {
993
+ this.unmount();
994
+ this.events.emit("destroy");
995
+ this.options.removeListenersOnDestroy && this.unsubscribeAll();
996
+ }
997
+ //#region static
998
+ /** Returns the ID of the top-most dialog (the dialog that has been opened last) */
999
+ static getCurrentDialogId() {
1000
+ return exports.currentDialogId;
1001
+ }
1002
+ /** Returns the IDs of all currently open dialogs, top-most first */
1003
+ static getOpenDialogs() {
1004
+ return openDialogs;
1005
+ }
1006
+ //#region protected
1007
+ getString(key) {
1008
+ var _a;
1009
+ return (_a = this.strings[key]) != null ? _a : defaultStrings[key];
1010
+ }
1011
+ /** Called once to attach all generic event listeners */
1012
+ attachListeners(bgElem) {
1013
+ if (this.options.closeOnBgClick) {
1014
+ bgElem.addEventListener("click", (e) => {
1015
+ var _a;
1016
+ if (this.isOpen() && ((_a = e.target) == null ? void 0 : _a.id) === `uu-${this.id}-dialog-bg`)
1017
+ this.close(e);
1018
+ });
1019
+ }
1020
+ if (this.options.closeOnEscPress) {
1021
+ document.body.addEventListener("keydown", (e) => {
1022
+ if (e.key === "Escape" && this.isOpen() && _Dialog.getCurrentDialogId() === this.id)
1023
+ this.close(e);
1024
+ });
1025
+ }
1026
+ }
1027
+ //#region protected
1028
+ /**
1029
+ * Adds generic, accessible interaction listeners to the passed element.
1030
+ * All listeners have the default behavior prevented and stop propagation (for keyboard events only as long as the captured key is valid).
1031
+ * @param listenerOptions Provide a {@linkcode listenerOptions} object to configure the listeners
1032
+ */
1033
+ onInteraction(elem, listener, listenerOptions) {
1034
+ const _a = listenerOptions != null ? listenerOptions : {}, { preventDefault = true, stopPropagation = true } = _a, listenerOpts = __objRest(_a, ["preventDefault", "stopPropagation"]);
1035
+ const interactionKeys = ["Enter", " ", "Space"];
1036
+ const proxListener = (e) => {
1037
+ if (e instanceof KeyboardEvent) {
1038
+ if (interactionKeys.includes(e.key)) {
1039
+ preventDefault && e.preventDefault();
1040
+ stopPropagation && e.stopPropagation();
1041
+ } else
493
1042
  return;
494
- else
495
- return origListener.apply(this, a);
496
- };
497
- original.apply(this, args);
1043
+ } else if (e instanceof MouseEvent) {
1044
+ preventDefault && e.preventDefault();
1045
+ stopPropagation && e.stopPropagation();
1046
+ }
1047
+ (listenerOpts == null ? void 0 : listenerOpts.once) && e.type === "keydown" && elem.removeEventListener("click", proxListener, listenerOpts);
1048
+ (listenerOpts == null ? void 0 : listenerOpts.once) && e.type === "click" && elem.removeEventListener("keydown", proxListener, listenerOpts);
1049
+ listener(e);
498
1050
  };
499
- })(eventObject.__proto__.addEventListener);
500
- }
501
- function interceptWindowEvent(eventName, predicate = () => true) {
502
- return interceptEvent(getUnsafeWindow(), eventName, predicate);
503
- }
504
- function isScrollable(element) {
505
- const { overflowX, overflowY } = getComputedStyle(element);
506
- return {
507
- vertical: (overflowY === "scroll" || overflowY === "auto") && element.scrollHeight > element.clientHeight,
508
- horizontal: (overflowX === "scroll" || overflowX === "auto") && element.scrollWidth > element.clientWidth
509
- };
510
- }
511
- function observeElementProp(element, property, callback) {
512
- const elementPrototype = Object.getPrototypeOf(element);
513
- if (elementPrototype.hasOwnProperty(property)) {
514
- const descriptor = Object.getOwnPropertyDescriptor(elementPrototype, property);
515
- Object.defineProperty(element, property, {
516
- get: function() {
517
- var _a;
518
- return (_a = descriptor == null ? void 0 : descriptor.get) == null ? void 0 : _a.apply(this, arguments);
519
- },
520
- set: function() {
521
- var _a;
522
- const oldValue = this[property];
523
- (_a = descriptor == null ? void 0 : descriptor.set) == null ? void 0 : _a.apply(this, arguments);
524
- const newValue = this[property];
525
- if (typeof callback === "function") {
526
- callback.bind(this, oldValue, newValue);
527
- }
528
- return newValue;
1051
+ elem.addEventListener("click", proxListener, listenerOpts);
1052
+ elem.addEventListener("keydown", proxListener, listenerOpts);
1053
+ }
1054
+ /** Returns the dialog content element and all its children */
1055
+ getDialogContent() {
1056
+ return __async(this, null, function* () {
1057
+ var _a, _b, _c, _d;
1058
+ const header = (_b = (_a = this.options).renderHeader) == null ? void 0 : _b.call(_a);
1059
+ const footer = (_d = (_c = this.options).renderFooter) == null ? void 0 : _d.call(_c);
1060
+ const dialogWrapperEl = document.createElement("div");
1061
+ dialogWrapperEl.id = `uu-${this.id}-dialog`;
1062
+ dialogWrapperEl.classList.add("uu-dialog");
1063
+ dialogWrapperEl.ariaLabel = dialogWrapperEl.title = "";
1064
+ dialogWrapperEl.role = "dialog";
1065
+ dialogWrapperEl.setAttribute("aria-labelledby", `uu-${this.id}-dialog-title`);
1066
+ dialogWrapperEl.setAttribute("aria-describedby", `uu-${this.id}-dialog-body`);
1067
+ if (this.options.verticalAlign !== "center")
1068
+ dialogWrapperEl.classList.add(`align-${this.options.verticalAlign}`);
1069
+ const headerWrapperEl = document.createElement("div");
1070
+ headerWrapperEl.classList.add("uu-dialog-header");
1071
+ this.options.small && headerWrapperEl.classList.add("small");
1072
+ if (header) {
1073
+ const headerTitleWrapperEl = document.createElement("div");
1074
+ headerTitleWrapperEl.id = `uu-${this.id}-dialog-title`;
1075
+ headerTitleWrapperEl.classList.add("uu-dialog-title-wrapper");
1076
+ headerTitleWrapperEl.role = "heading";
1077
+ headerTitleWrapperEl.ariaLevel = "1";
1078
+ headerTitleWrapperEl.appendChild(header instanceof Promise ? yield header : header);
1079
+ headerWrapperEl.appendChild(headerTitleWrapperEl);
1080
+ } else {
1081
+ const padEl = document.createElement("div");
1082
+ padEl.classList.add("uu-dialog-header-pad", this.options.small ? "small" : "");
1083
+ headerWrapperEl.appendChild(padEl);
529
1084
  }
1085
+ if (this.options.renderCloseBtn) {
1086
+ const closeBtnEl = yield this.options.renderCloseBtn();
1087
+ closeBtnEl.classList.add("uu-dialog-close");
1088
+ this.options.small && closeBtnEl.classList.add("small");
1089
+ closeBtnEl.tabIndex = 0;
1090
+ if (closeBtnEl.hasAttribute("alt"))
1091
+ closeBtnEl.setAttribute("alt", this.getString("closeDialogTooltip"));
1092
+ closeBtnEl.title = closeBtnEl.ariaLabel = this.getString("closeDialogTooltip");
1093
+ this.onInteraction(closeBtnEl, () => this.close());
1094
+ headerWrapperEl.appendChild(closeBtnEl);
1095
+ }
1096
+ dialogWrapperEl.appendChild(headerWrapperEl);
1097
+ const dialogBodyElem = document.createElement("div");
1098
+ dialogBodyElem.id = `uu-${this.id}-dialog-body`;
1099
+ dialogBodyElem.classList.add("uu-dialog-body");
1100
+ this.options.small && dialogBodyElem.classList.add("small");
1101
+ const body = this.options.renderBody();
1102
+ dialogBodyElem.appendChild(body instanceof Promise ? yield body : body);
1103
+ dialogWrapperEl.appendChild(dialogBodyElem);
1104
+ if (footer) {
1105
+ const footerWrapper = document.createElement("div");
1106
+ footerWrapper.classList.add("uu-dialog-footer-cont");
1107
+ dialogWrapperEl.appendChild(footerWrapper);
1108
+ footerWrapper.appendChild(footer instanceof Promise ? yield footer : footer);
1109
+ }
1110
+ return dialogWrapperEl;
530
1111
  });
531
1112
  }
532
- }
533
- function getSiblingsFrame(refElement, siblingAmount, refElementAlignment = "center-top", includeRef = true) {
534
- var _a, _b;
535
- const siblings = [...(_b = (_a = refElement.parentNode) == null ? void 0 : _a.childNodes) != null ? _b : []];
536
- const elemSiblIdx = siblings.indexOf(refElement);
537
- if (elemSiblIdx === -1)
538
- throw new Error("Element doesn't have a parent node");
539
- if (refElementAlignment === "top")
540
- return [...siblings.slice(elemSiblIdx + Number(!includeRef), elemSiblIdx + siblingAmount + Number(!includeRef))];
541
- else if (refElementAlignment.startsWith("center-")) {
542
- const halfAmount = (refElementAlignment === "center-bottom" ? Math.ceil : Math.floor)(siblingAmount / 2);
543
- const startIdx = Math.max(0, elemSiblIdx - halfAmount);
544
- const topOffset = Number(refElementAlignment === "center-top" && siblingAmount % 2 === 0 && includeRef);
545
- const btmOffset = Number(refElementAlignment === "center-bottom" && siblingAmount % 2 !== 0 && includeRef);
546
- const startIdxWithOffset = startIdx + topOffset + btmOffset;
547
- return [
548
- ...siblings.filter((_, idx) => includeRef || idx !== elemSiblIdx).slice(startIdxWithOffset, startIdxWithOffset + siblingAmount)
549
- ];
550
- } else if (refElementAlignment === "bottom")
551
- return [...siblings.slice(elemSiblIdx - siblingAmount + Number(includeRef), elemSiblIdx + Number(includeRef))];
552
- return [];
553
- }
1113
+ };
554
1114
 
555
1115
  // lib/misc.ts
556
1116
  function autoPlural(word, num) {
@@ -558,6 +1118,13 @@ Has: ${checksum}`);
558
1118
  num = num.length;
559
1119
  return `${word}${num === 1 ? "" : "s"}`;
560
1120
  }
1121
+ function insertValues(input, ...values) {
1122
+ return input.replace(/%\d/gm, (match) => {
1123
+ var _a, _b;
1124
+ const argIndex = Number(match.substring(1)) - 1;
1125
+ return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
1126
+ });
1127
+ }
561
1128
  function pauseFor(time) {
562
1129
  return new Promise((res) => {
563
1130
  setTimeout(() => res(), time);
@@ -596,71 +1163,6 @@ Has: ${checksum}`);
596
1163
  }
597
1164
  });
598
1165
  }
599
- function insertValues(input, ...values) {
600
- return input.replace(/%\d/gm, (match) => {
601
- var _a, _b;
602
- const argIndex = Number(match.substring(1)) - 1;
603
- return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
604
- });
605
- }
606
- function compress(input, compressionFormat, outputType = "string") {
607
- return __async(this, null, function* () {
608
- const byteArray = typeof input === "string" ? new TextEncoder().encode(input) : input;
609
- const comp = new CompressionStream(compressionFormat);
610
- const writer = comp.writable.getWriter();
611
- writer.write(byteArray);
612
- writer.close();
613
- const buf = yield new Response(comp.readable).arrayBuffer();
614
- return outputType === "arrayBuffer" ? buf : ab2str(buf);
615
- });
616
- }
617
- function decompress(input, compressionFormat, outputType = "string") {
618
- return __async(this, null, function* () {
619
- const byteArray = typeof input === "string" ? str2ab(input) : input;
620
- const decomp = new DecompressionStream(compressionFormat);
621
- const writer = decomp.writable.getWriter();
622
- writer.write(byteArray);
623
- writer.close();
624
- const buf = yield new Response(decomp.readable).arrayBuffer();
625
- return outputType === "arrayBuffer" ? buf : new TextDecoder().decode(buf);
626
- });
627
- }
628
- function ab2str(buf) {
629
- return getUnsafeWindow().btoa(
630
- new Uint8Array(buf).reduce((data, byte) => data + String.fromCharCode(byte), "")
631
- );
632
- }
633
- function str2ab(str) {
634
- return Uint8Array.from(getUnsafeWindow().atob(str), (c) => c.charCodeAt(0));
635
- }
636
- function computeHash(input, algorithm = "SHA-256") {
637
- return __async(this, null, function* () {
638
- let data;
639
- if (typeof input === "string") {
640
- const encoder = new TextEncoder();
641
- data = encoder.encode(input);
642
- } else
643
- data = input;
644
- const hashBuffer = yield crypto.subtle.digest(algorithm, data);
645
- const hashArray = Array.from(new Uint8Array(hashBuffer));
646
- const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
647
- return hashHex;
648
- });
649
- }
650
- function randomId(length = 16, radix = 16, enhancedEntropy = false) {
651
- if (enhancedEntropy) {
652
- const arr = new Uint8Array(length);
653
- crypto.getRandomValues(arr);
654
- return Array.from(
655
- arr,
656
- (v) => mapRange(v, 0, 255, 0, radix).toString(radix).substring(0, 1)
657
- ).join("");
658
- }
659
- return Array.from(
660
- { length },
661
- () => Math.floor(Math.random() * radix).toString(radix)
662
- ).join("");
663
- }
664
1166
 
665
1167
  // lib/SelectorObserver.ts
666
1168
  var domLoaded = false;
@@ -865,6 +1367,8 @@ Has: ${checksum}`);
865
1367
 
866
1368
  exports.DataStore = DataStore;
867
1369
  exports.DataStoreSerializer = DataStoreSerializer;
1370
+ exports.Dialog = Dialog;
1371
+ exports.NanoEmitter = NanoEmitter;
868
1372
  exports.SelectorObserver = SelectorObserver;
869
1373
  exports.addGlobalStyle = addGlobalStyle;
870
1374
  exports.addParent = addParent;
@@ -874,6 +1378,8 @@ Has: ${checksum}`);
874
1378
  exports.computeHash = computeHash;
875
1379
  exports.debounce = debounce;
876
1380
  exports.decompress = decompress;
1381
+ exports.defaultDialogCss = defaultDialogCss;
1382
+ exports.defaultStrings = defaultStrings;
877
1383
  exports.fetchAdvanced = fetchAdvanced;
878
1384
  exports.getSiblingsFrame = getSiblingsFrame;
879
1385
  exports.getUnsafeWindow = getUnsafeWindow;
@@ -883,6 +1389,7 @@ Has: ${checksum}`);
883
1389
  exports.isScrollable = isScrollable;
884
1390
  exports.mapRange = mapRange;
885
1391
  exports.observeElementProp = observeElementProp;
1392
+ exports.openDialogs = openDialogs;
886
1393
  exports.openInNewTab = openInNewTab;
887
1394
  exports.pauseFor = pauseFor;
888
1395
  exports.preloadImages = preloadImages;
@@ -891,6 +1398,7 @@ Has: ${checksum}`);
891
1398
  exports.randomItem = randomItem;
892
1399
  exports.randomItemIndex = randomItemIndex;
893
1400
  exports.randomizeArray = randomizeArray;
1401
+ exports.setInnerHtmlUnsafe = setInnerHtmlUnsafe;
894
1402
  exports.takeRandomItem = takeRandomItem;
895
1403
  exports.tr = tr;
896
1404