@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.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';
1
+ import { createNanoEvents } from 'nanoevents';
2
2
 
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
@@ -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,475 @@ 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;
605
+ var NanoEmitter = class {
606
+ constructor(options = {}) {
607
+ __publicField(this, "events", createNanoEvents());
608
+ __publicField(this, "eventUnsubscribes", []);
609
+ __publicField(this, "emitterOptions");
610
+ this.emitterOptions = __spreadValues({
611
+ publicEmit: false
612
+ }, options);
613
+ }
614
+ /** Subscribes to an event - returns a function that unsubscribes the event listener */
615
+ on(event, cb) {
616
+ let unsub;
617
+ const unsubProxy = () => {
618
+ if (!unsub)
619
+ return;
620
+ unsub();
621
+ this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => u !== unsub);
622
+ };
623
+ unsub = this.events.on(event, cb);
624
+ this.eventUnsubscribes.push(unsub);
625
+ return unsubProxy;
626
+ }
627
+ /** Subscribes to an event and calls the callback or resolves the Promise only once */
628
+ once(event, cb) {
629
+ return new Promise((resolve) => {
630
+ let unsub;
631
+ const onceProxy = (...args) => {
632
+ unsub();
633
+ cb == null ? void 0 : cb(...args);
634
+ resolve(args);
635
+ };
636
+ unsub = this.on(event, onceProxy);
637
+ });
638
+ }
639
+ /** Emits an event on this instance - Needs `publicEmit` to be set to true in the constructor! */
640
+ emit(event, ...args) {
641
+ if (this.emitterOptions.publicEmit) {
642
+ this.events.emit(event, ...args);
643
+ return true;
644
+ }
645
+ return false;
646
+ }
647
+ /** Unsubscribes all event listeners */
648
+ unsubscribeAll() {
649
+ for (const unsub of this.eventUnsubscribes)
650
+ unsub();
651
+ this.eventUnsubscribes = [];
421
652
  }
653
+ };
654
+
655
+ // lib/Dialog.ts
656
+ var defaultDialogCss = `.uu-no-select {
657
+ user-select: none;
422
658
  }
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;
659
+
660
+ .uu-dialog-bg {
661
+ --uu-dialog-bg: #333333;
662
+ --uu-dialog-bg-highlight: #252525;
663
+ --uu-scroll-indicator-bg: rgba(10, 10, 10, 0.7);
664
+ --uu-dialog-separator-color: #797979;
665
+ --uu-dialog-border-radius: 10px;
430
666
  }
431
- function addGlobalStyle(style) {
432
- const styleElem = document.createElement("style");
433
- styleElem.innerHTML = style;
434
- document.head.appendChild(styleElem);
435
- return styleElem;
667
+
668
+ .uu-dialog-bg {
669
+ display: block;
670
+ position: fixed;
671
+ width: 100%;
672
+ height: 100%;
673
+ top: 0;
674
+ left: 0;
675
+ z-index: 5;
676
+ background-color: rgba(0, 0, 0, 0.6);
436
677
  }
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);
678
+
679
+ .uu-dialog {
680
+ --uu-calc-dialog-height: calc(min(100vh - 40px, var(--uu-dialog-height-max)));
681
+ position: absolute;
682
+ display: flex;
683
+ flex-direction: column;
684
+ width: calc(min(100% - 60px, var(--uu-dialog-width-max)));
685
+ border-radius: var(--uu-dialog-border-radius);
686
+ height: auto;
687
+ max-height: var(--uu-calc-dialog-height);
688
+ left: 50%;
689
+ top: 50%;
690
+ transform: translate(-50%, -50%);
691
+ z-index: 6;
692
+ color: #fff;
693
+ background-color: var(--uu-dialog-bg);
445
694
  }
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
- }
695
+
696
+ .uu-dialog.align-top {
697
+ top: 0;
698
+ transform: translate(-50%, 40px);
462
699
  }
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);
700
+
701
+ .uu-dialog.align-bottom {
702
+ top: 100%;
703
+ transform: translate(-50%, -100%);
480
704
  }
481
- function interceptWindowEvent(eventName, predicate = () => true) {
482
- return interceptEvent(getUnsafeWindow(), eventName, predicate);
705
+
706
+ .uu-dialog-body {
707
+ font-size: 1.5rem;
708
+ padding: 20px;
483
709
  }
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
- };
710
+
711
+ .uu-dialog-body.small {
712
+ padding: 15px;
490
713
  }
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() {
714
+
715
+ #uu-dialog-opts {
716
+ display: flex;
717
+ flex-direction: column;
718
+ position: relative;
719
+ padding: 30px 0px;
720
+ overflow-y: auto;
721
+ }
722
+
723
+ .uu-dialog-header {
724
+ display: flex;
725
+ justify-content: space-between;
726
+ align-items: center;
727
+ margin-bottom: 6px;
728
+ padding: 15px 20px 15px 20px;
729
+ background-color: var(--uu-dialog-bg);
730
+ border: 2px solid var(--uu-dialog-separator-color);
731
+ border-style: none none solid none !important;
732
+ border-radius: var(--uu-dialog-border-radius) var(--uu-dialog-border-radius) 0px 0px;
733
+ }
734
+
735
+ .uu-dialog-header.small {
736
+ padding: 10px 15px;
737
+ border-style: none none solid none !important;
738
+ }
739
+
740
+ .uu-dialog-header-pad {
741
+ content: " ";
742
+ min-height: 32px;
743
+ }
744
+
745
+ .uu-dialog-header-pad.small {
746
+ min-height: 24px;
747
+ }
748
+
749
+ .uu-dialog-titlecont {
750
+ display: flex;
751
+ align-items: center;
752
+ }
753
+
754
+ .uu-dialog-titlecont-no-title {
755
+ display: flex;
756
+ justify-content: flex-end;
757
+ align-items: center;
758
+ }
759
+
760
+ .uu-dialog-title {
761
+ position: relative;
762
+ display: inline-block;
763
+ font-size: 22px;
764
+ }
765
+
766
+ .uu-dialog-close {
767
+ cursor: pointer;
768
+ }
769
+
770
+ .uu-dialog-header-img,
771
+ .uu-dialog-close
772
+ {
773
+ width: 32px;
774
+ height: 32px;
775
+ }
776
+
777
+ .uu-dialog-header-img.small,
778
+ .uu-dialog-close.small
779
+ {
780
+ width: 24px;
781
+ height: 24px;
782
+ }
783
+
784
+ .uu-dialog-footer {
785
+ font-size: 17px;
786
+ text-decoration: underline;
787
+ }
788
+
789
+ .uu-dialog-footer.hidden {
790
+ display: none;
791
+ }
792
+
793
+ .uu-dialog-footer-cont {
794
+ margin-top: 6px;
795
+ padding: 15px 20px;
796
+ background: var(--uu-dialog-bg);
797
+ background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, var(--uu-dialog-bg) 30%, var(--uu-dialog-bg) 100%);
798
+ border: 2px solid var(--uu-dialog-separator-color);
799
+ border-style: solid none none none !important;
800
+ border-radius: 0px 0px var(--uu-dialog-border-radius) var(--uu-dialog-border-radius);
801
+ }
802
+
803
+ .uu-dialog-footer-buttons-cont button:not(:last-of-type) {
804
+ margin-right: 15px;
805
+ }`;
806
+ var currentDialogId = null;
807
+ var openDialogs = [];
808
+ var defaultStrings = {
809
+ closeDialogTooltip: "Click to close the dialog"
810
+ };
811
+ var Dialog = class _Dialog extends NanoEmitter {
812
+ constructor(options) {
813
+ super();
814
+ /** Options passed to the dialog in the constructor */
815
+ __publicField(this, "options");
816
+ /** ID that gets added to child element IDs - has to be unique and conform to HTML ID naming rules! */
817
+ __publicField(this, "id");
818
+ /** Strings used in the dialog (used for translations) */
819
+ __publicField(this, "strings");
820
+ __publicField(this, "dialogOpen", false);
821
+ __publicField(this, "dialogMounted", false);
822
+ const _a = options, { strings } = _a, opts = __objRest(_a, ["strings"]);
823
+ this.strings = __spreadValues(__spreadValues({}, defaultStrings), strings != null ? strings : {});
824
+ this.options = __spreadValues({
825
+ closeOnBgClick: true,
826
+ closeOnEscPress: true,
827
+ destroyOnClose: false,
828
+ unmountOnClose: true,
829
+ removeListenersOnDestroy: true,
830
+ small: false,
831
+ verticalAlign: "center"
832
+ }, opts);
833
+ this.id = opts.id;
834
+ }
835
+ //#region public
836
+ /** Call after DOMContentLoaded to pre-render the dialog and invisibly mount it in the DOM */
837
+ mount() {
838
+ return __async(this, null, function* () {
839
+ var _a;
840
+ if (this.dialogMounted)
841
+ return;
842
+ this.dialogMounted = true;
843
+ if (!document.querySelector("style.uu-dialog-css"))
844
+ addGlobalStyle((_a = this.options.dialogCss) != null ? _a : defaultDialogCss).classList.add("uu-dialog-css");
845
+ const bgElem = document.createElement("div");
846
+ bgElem.id = `uu-${this.id}-dialog-bg`;
847
+ bgElem.classList.add("uu-dialog-bg");
848
+ if (this.options.closeOnBgClick)
849
+ bgElem.ariaLabel = bgElem.title = this.getString("closeDialogTooltip");
850
+ bgElem.style.setProperty("--uu-dialog-width-max", `${this.options.width}px`);
851
+ bgElem.style.setProperty("--uu-dialog-height-max", `${this.options.height}px`);
852
+ bgElem.style.visibility = "hidden";
853
+ bgElem.style.display = "none";
854
+ bgElem.inert = true;
855
+ bgElem.appendChild(yield this.getDialogContent());
856
+ document.body.appendChild(bgElem);
857
+ this.attachListeners(bgElem);
858
+ this.events.emit("render");
859
+ return bgElem;
860
+ });
861
+ }
862
+ /** Closes the dialog and clears all its contents (unmounts elements from the DOM) in preparation for a new rendering call */
863
+ unmount() {
864
+ var _a;
865
+ this.close();
866
+ this.dialogMounted = false;
867
+ const clearSelectors = [
868
+ `#uu-${this.id}-dialog-bg`,
869
+ `#uu-style-dialog-${this.id}`
870
+ ];
871
+ for (const sel of clearSelectors)
872
+ (_a = document.querySelector(sel)) == null ? void 0 : _a.remove();
873
+ this.events.emit("clear");
874
+ }
875
+ /** Clears the DOM of the dialog and then renders it again */
876
+ remount() {
877
+ return __async(this, null, function* () {
878
+ this.unmount();
879
+ yield this.mount();
880
+ });
881
+ }
882
+ /**
883
+ * Opens the dialog - also mounts it if it hasn't been mounted yet
884
+ * Prevents default action and immediate propagation of the passed event
885
+ */
886
+ open(e) {
887
+ return __async(this, null, function* () {
888
+ var _a;
889
+ e == null ? void 0 : e.preventDefault();
890
+ e == null ? void 0 : e.stopImmediatePropagation();
891
+ if (this.isOpen())
892
+ return;
893
+ this.dialogOpen = true;
894
+ if (openDialogs.includes(this.id))
895
+ throw new Error(`A dialog with the same ID of '${this.id}' already exists and is open!`);
896
+ if (!this.isMounted())
897
+ yield this.mount();
898
+ const dialogBg = document.querySelector(`#uu-${this.id}-dialog-bg`);
899
+ if (!dialogBg)
900
+ return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
901
+ dialogBg.style.visibility = "visible";
902
+ dialogBg.style.display = "block";
903
+ dialogBg.inert = false;
904
+ currentDialogId = this.id;
905
+ openDialogs.unshift(this.id);
906
+ for (const dialogId of openDialogs)
907
+ if (dialogId !== this.id)
908
+ (_a = document.querySelector(`#uu-${dialogId}-dialog-bg`)) == null ? void 0 : _a.setAttribute("inert", "true");
909
+ document.body.classList.remove("uu-no-select");
910
+ document.body.setAttribute("inert", "true");
911
+ this.events.emit("open");
912
+ return dialogBg;
913
+ });
914
+ }
915
+ /** Closes the dialog - prevents default action and immediate propagation of the passed event */
916
+ close(e) {
917
+ var _a, _b;
918
+ e == null ? void 0 : e.preventDefault();
919
+ e == null ? void 0 : e.stopImmediatePropagation();
920
+ if (!this.isOpen())
921
+ return;
922
+ this.dialogOpen = false;
923
+ const dialogBg = document.querySelector(`#uu-${this.id}-dialog-bg`);
924
+ if (!dialogBg)
925
+ return console.warn(`Couldn't find background element for dialog with ID '${this.id}'`);
926
+ dialogBg.style.visibility = "hidden";
927
+ dialogBg.style.display = "none";
928
+ dialogBg.inert = true;
929
+ openDialogs.splice(openDialogs.indexOf(this.id), 1);
930
+ currentDialogId = (_a = openDialogs[0]) != null ? _a : null;
931
+ if (currentDialogId)
932
+ (_b = document.querySelector(`#uu-${currentDialogId}-dialog-bg`)) == null ? void 0 : _b.removeAttribute("inert");
933
+ if (openDialogs.length === 0) {
934
+ document.body.classList.add("uu-no-select");
935
+ document.body.removeAttribute("inert");
936
+ }
937
+ this.events.emit("close");
938
+ if (this.options.destroyOnClose)
939
+ this.destroy();
940
+ else if (this.options.unmountOnClose)
941
+ this.unmount();
942
+ }
943
+ /** Returns true if the dialog is currently open */
944
+ isOpen() {
945
+ return this.dialogOpen;
946
+ }
947
+ /** Returns true if the dialog is currently mounted */
948
+ isMounted() {
949
+ return this.dialogMounted;
950
+ }
951
+ /** Clears the DOM of the dialog and removes all event listeners */
952
+ destroy() {
953
+ this.unmount();
954
+ this.events.emit("destroy");
955
+ this.options.removeListenersOnDestroy && this.unsubscribeAll();
956
+ }
957
+ //#region static
958
+ /** Returns the ID of the top-most dialog (the dialog that has been opened last) */
959
+ static getCurrentDialogId() {
960
+ return currentDialogId;
961
+ }
962
+ /** Returns the IDs of all currently open dialogs, top-most first */
963
+ static getOpenDialogs() {
964
+ return openDialogs;
965
+ }
966
+ //#region protected
967
+ getString(key) {
968
+ var _a;
969
+ return (_a = this.strings[key]) != null ? _a : defaultStrings[key];
970
+ }
971
+ /** Called once to attach all generic event listeners */
972
+ attachListeners(bgElem) {
973
+ if (this.options.closeOnBgClick) {
974
+ bgElem.addEventListener("click", (e) => {
501
975
  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;
976
+ if (this.isOpen() && ((_a = e.target) == null ? void 0 : _a.id) === `uu-${this.id}-dialog-bg`)
977
+ this.close(e);
978
+ });
979
+ }
980
+ if (this.options.closeOnEscPress) {
981
+ document.body.addEventListener("keydown", (e) => {
982
+ if (e.key === "Escape" && this.isOpen() && _Dialog.getCurrentDialogId() === this.id)
983
+ this.close(e);
984
+ });
985
+ }
986
+ }
987
+ //#region protected
988
+ /**
989
+ * Adds generic, accessible interaction listeners to the passed element.
990
+ * All listeners have the default behavior prevented and stop propagation (for keyboard events only as long as the captured key is valid).
991
+ * @param listenerOptions Provide a {@linkcode listenerOptions} object to configure the listeners
992
+ */
993
+ onInteraction(elem, listener, listenerOptions) {
994
+ const _a = listenerOptions != null ? listenerOptions : {}, { preventDefault = true, stopPropagation = true } = _a, listenerOpts = __objRest(_a, ["preventDefault", "stopPropagation"]);
995
+ const interactionKeys = ["Enter", " ", "Space"];
996
+ const proxListener = (e) => {
997
+ if (e instanceof KeyboardEvent) {
998
+ if (interactionKeys.includes(e.key)) {
999
+ preventDefault && e.preventDefault();
1000
+ stopPropagation && e.stopPropagation();
1001
+ } else
1002
+ return;
1003
+ } else if (e instanceof MouseEvent) {
1004
+ preventDefault && e.preventDefault();
1005
+ stopPropagation && e.stopPropagation();
509
1006
  }
1007
+ (listenerOpts == null ? void 0 : listenerOpts.once) && e.type === "keydown" && elem.removeEventListener("click", proxListener, listenerOpts);
1008
+ (listenerOpts == null ? void 0 : listenerOpts.once) && e.type === "click" && elem.removeEventListener("keydown", proxListener, listenerOpts);
1009
+ listener(e);
1010
+ };
1011
+ elem.addEventListener("click", proxListener, listenerOpts);
1012
+ elem.addEventListener("keydown", proxListener, listenerOpts);
1013
+ }
1014
+ /** Returns the dialog content element and all its children */
1015
+ getDialogContent() {
1016
+ return __async(this, null, function* () {
1017
+ var _a, _b, _c, _d;
1018
+ const header = (_b = (_a = this.options).renderHeader) == null ? void 0 : _b.call(_a);
1019
+ const footer = (_d = (_c = this.options).renderFooter) == null ? void 0 : _d.call(_c);
1020
+ const dialogWrapperEl = document.createElement("div");
1021
+ dialogWrapperEl.id = `uu-${this.id}-dialog`;
1022
+ dialogWrapperEl.classList.add("uu-dialog");
1023
+ dialogWrapperEl.ariaLabel = dialogWrapperEl.title = "";
1024
+ dialogWrapperEl.role = "dialog";
1025
+ dialogWrapperEl.setAttribute("aria-labelledby", `uu-${this.id}-dialog-title`);
1026
+ dialogWrapperEl.setAttribute("aria-describedby", `uu-${this.id}-dialog-body`);
1027
+ if (this.options.verticalAlign !== "center")
1028
+ dialogWrapperEl.classList.add(`align-${this.options.verticalAlign}`);
1029
+ const headerWrapperEl = document.createElement("div");
1030
+ headerWrapperEl.classList.add("uu-dialog-header");
1031
+ this.options.small && headerWrapperEl.classList.add("small");
1032
+ if (header) {
1033
+ const headerTitleWrapperEl = document.createElement("div");
1034
+ headerTitleWrapperEl.id = `uu-${this.id}-dialog-title`;
1035
+ headerTitleWrapperEl.classList.add("uu-dialog-title-wrapper");
1036
+ headerTitleWrapperEl.role = "heading";
1037
+ headerTitleWrapperEl.ariaLevel = "1";
1038
+ headerTitleWrapperEl.appendChild(header instanceof Promise ? yield header : header);
1039
+ headerWrapperEl.appendChild(headerTitleWrapperEl);
1040
+ } else {
1041
+ const padEl = document.createElement("div");
1042
+ padEl.classList.add("uu-dialog-header-pad", this.options.small ? "small" : "");
1043
+ headerWrapperEl.appendChild(padEl);
1044
+ }
1045
+ if (this.options.renderCloseBtn) {
1046
+ const closeBtnEl = yield this.options.renderCloseBtn();
1047
+ closeBtnEl.classList.add("uu-dialog-close");
1048
+ this.options.small && closeBtnEl.classList.add("small");
1049
+ closeBtnEl.tabIndex = 0;
1050
+ if (closeBtnEl.hasAttribute("alt"))
1051
+ closeBtnEl.setAttribute("alt", this.getString("closeDialogTooltip"));
1052
+ closeBtnEl.title = closeBtnEl.ariaLabel = this.getString("closeDialogTooltip");
1053
+ this.onInteraction(closeBtnEl, () => this.close());
1054
+ headerWrapperEl.appendChild(closeBtnEl);
1055
+ }
1056
+ dialogWrapperEl.appendChild(headerWrapperEl);
1057
+ const dialogBodyElem = document.createElement("div");
1058
+ dialogBodyElem.id = `uu-${this.id}-dialog-body`;
1059
+ dialogBodyElem.classList.add("uu-dialog-body");
1060
+ this.options.small && dialogBodyElem.classList.add("small");
1061
+ const body = this.options.renderBody();
1062
+ dialogBodyElem.appendChild(body instanceof Promise ? yield body : body);
1063
+ dialogWrapperEl.appendChild(dialogBodyElem);
1064
+ if (footer) {
1065
+ const footerWrapper = document.createElement("div");
1066
+ footerWrapper.classList.add("uu-dialog-footer-cont");
1067
+ dialogWrapperEl.appendChild(footerWrapper);
1068
+ footerWrapper.appendChild(footer instanceof Promise ? yield footer : footer);
1069
+ }
1070
+ return dialogWrapperEl;
510
1071
  });
511
1072
  }
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
- }
1073
+ };
534
1074
 
535
1075
  // lib/misc.ts
536
1076
  function autoPlural(word, num) {
@@ -538,6 +1078,13 @@ function autoPlural(word, num) {
538
1078
  num = num.length;
539
1079
  return `${word}${num === 1 ? "" : "s"}`;
540
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
+ }
541
1088
  function pauseFor(time) {
542
1089
  return new Promise((res) => {
543
1090
  setTimeout(() => res(), time);
@@ -576,71 +1123,6 @@ function fetchAdvanced(_0) {
576
1123
  }
577
1124
  });
578
1125
  }
579
- function insertValues(input, ...values) {
580
- return input.replace(/%\d/gm, (match) => {
581
- var _a, _b;
582
- const argIndex = Number(match.substring(1)) - 1;
583
- return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
584
- });
585
- }
586
- function compress(input, compressionFormat, outputType = "string") {
587
- return __async(this, null, function* () {
588
- const byteArray = typeof input === "string" ? new TextEncoder().encode(input) : input;
589
- const comp = new CompressionStream(compressionFormat);
590
- const writer = comp.writable.getWriter();
591
- writer.write(byteArray);
592
- writer.close();
593
- const buf = yield new Response(comp.readable).arrayBuffer();
594
- return outputType === "arrayBuffer" ? buf : ab2str(buf);
595
- });
596
- }
597
- function decompress(input, compressionFormat, outputType = "string") {
598
- return __async(this, null, function* () {
599
- const byteArray = typeof input === "string" ? str2ab(input) : input;
600
- const decomp = new DecompressionStream(compressionFormat);
601
- const writer = decomp.writable.getWriter();
602
- writer.write(byteArray);
603
- writer.close();
604
- const buf = yield new Response(decomp.readable).arrayBuffer();
605
- return outputType === "arrayBuffer" ? buf : new TextDecoder().decode(buf);
606
- });
607
- }
608
- function ab2str(buf) {
609
- return getUnsafeWindow().btoa(
610
- new Uint8Array(buf).reduce((data, byte) => data + String.fromCharCode(byte), "")
611
- );
612
- }
613
- function str2ab(str) {
614
- return Uint8Array.from(getUnsafeWindow().atob(str), (c) => c.charCodeAt(0));
615
- }
616
- function computeHash(input, algorithm = "SHA-256") {
617
- return __async(this, null, function* () {
618
- let data;
619
- if (typeof input === "string") {
620
- const encoder = new TextEncoder();
621
- data = encoder.encode(input);
622
- } else
623
- data = input;
624
- const hashBuffer = yield crypto.subtle.digest(algorithm, data);
625
- const hashArray = Array.from(new Uint8Array(hashBuffer));
626
- const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
627
- return hashHex;
628
- });
629
- }
630
- function randomId(length = 16, radix = 16, enhancedEntropy = false) {
631
- if (enhancedEntropy) {
632
- const arr = new Uint8Array(length);
633
- crypto.getRandomValues(arr);
634
- return Array.from(
635
- arr,
636
- (v) => mapRange(v, 0, 255, 0, radix).toString(radix).substring(0, 1)
637
- ).join("");
638
- }
639
- return Array.from(
640
- { length },
641
- () => Math.floor(Math.random() * radix).toString(radix)
642
- ).join("");
643
- }
644
1126
 
645
1127
  // lib/SelectorObserver.ts
646
1128
  var domLoaded = false;
@@ -843,33 +1325,4 @@ tr.getLanguage = () => {
843
1325
  return curLang;
844
1326
  };
845
1327
 
846
- exports.DataStore = DataStore;
847
- exports.DataStoreSerializer = DataStoreSerializer;
848
- exports.SelectorObserver = SelectorObserver;
849
- exports.addGlobalStyle = addGlobalStyle;
850
- exports.addParent = addParent;
851
- exports.autoPlural = autoPlural;
852
- exports.clamp = clamp;
853
- exports.compress = compress;
854
- exports.computeHash = computeHash;
855
- exports.debounce = debounce;
856
- exports.decompress = decompress;
857
- exports.fetchAdvanced = fetchAdvanced;
858
- exports.getSiblingsFrame = getSiblingsFrame;
859
- exports.getUnsafeWindow = getUnsafeWindow;
860
- exports.insertValues = insertValues;
861
- exports.interceptEvent = interceptEvent;
862
- exports.interceptWindowEvent = interceptWindowEvent;
863
- exports.isScrollable = isScrollable;
864
- exports.mapRange = mapRange;
865
- exports.observeElementProp = observeElementProp;
866
- exports.openInNewTab = openInNewTab;
867
- exports.pauseFor = pauseFor;
868
- exports.preloadImages = preloadImages;
869
- exports.randRange = randRange;
870
- exports.randomId = randomId;
871
- exports.randomItem = randomItem;
872
- exports.randomItemIndex = randomItemIndex;
873
- exports.randomizeArray = randomizeArray;
874
- exports.takeRandomItem = takeRandomItem;
875
- exports.tr = 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 };