billy-herrington-utils 2.0.6 → 2.1.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.
Files changed (42) hide show
  1. package/README.md +360 -62
  2. package/dist/billy-herrington-utils.es.js +275 -6267
  3. package/dist/billy-herrington-utils.es.js.map +1 -1
  4. package/dist/billy-herrington-utils.umd.js +321 -6269
  5. package/dist/billy-herrington-utils.umd.js.map +1 -1
  6. package/dist/index.d.ts +69 -190
  7. package/package.json +18 -7
  8. package/src/index.ts +1 -44
  9. package/src/types/index.ts +7 -0
  10. package/src/utils/arrays/index.ts +11 -5
  11. package/src/utils/async/index.ts +0 -88
  12. package/src/utils/dom/{observers.ts → dom-observers.ts} +3 -3
  13. package/src/utils/dom/index.ts +97 -16
  14. package/src/utils/events/index.ts +2 -37
  15. package/src/utils/events/on-hover.ts +42 -0
  16. package/src/utils/events/tick.ts +27 -0
  17. package/src/utils/fetch/index.ts +30 -28
  18. package/src/utils/index.ts +39 -0
  19. package/src/utils/objects/index.ts +19 -18
  20. package/src/utils/objects/memoize.ts +25 -0
  21. package/src/utils/observers/index.ts +4 -28
  22. package/src/utils/observers/lazy-image-loader.ts +27 -0
  23. package/src/utils/parsers/index.ts +2 -20
  24. package/src/utils/parsers/time-parser.ts +28 -0
  25. package/src/utils/strings/regexes.ts +12 -8
  26. package/src/types/globals.d.ts +0 -0
  27. package/src/userscripts/data-manager/data-filter.ts +0 -110
  28. package/src/userscripts/data-manager/index.ts +0 -141
  29. package/src/userscripts/infinite-scroll/index.ts +0 -106
  30. package/src/userscripts/pagination-parsing/index.ts +0 -55
  31. package/src/userscripts/pagination-parsing/pagination-strategies/PaginationStrategy.ts +0 -42
  32. package/src/userscripts/pagination-parsing/pagination-strategies/PaginationStrategyDataParams.ts +0 -66
  33. package/src/userscripts/pagination-parsing/pagination-strategies/PaginationStrategyPathnameParams.ts +0 -77
  34. package/src/userscripts/pagination-parsing/pagination-strategies/PaginationStrategySearchParams.ts +0 -56
  35. package/src/userscripts/pagination-parsing/pagination-strategies/PaginationStrategyTrash.ts +0 -33
  36. package/src/userscripts/pagination-parsing/pagination-strategies/index.ts +0 -5
  37. package/src/userscripts/pagination-parsing/pagination-utils/index.ts +0 -69
  38. package/src/userscripts/router/router.ts +0 -71
  39. package/src/userscripts/rules/index.ts +0 -241
  40. package/src/userscripts/types/index.ts +0 -19
  41. package/src/utils/device/index.ts +0 -3
  42. package/src/utils/userscript/index.ts +0 -10
package/dist/index.d.ts CHANGED
@@ -1,59 +1,15 @@
1
- import { JabronioGUI } from 'jabroni-outfit';
2
- import { JabronioStore } from 'jabroni-outfit';
3
- import { JabroniTypes } from 'jabroni-outfit';
4
- import { setupScheme } from 'jabroni-outfit';
5
- import { StoreState } from 'jabroni-outfit';
6
-
7
- export declare class AsyncPool {
8
- private max;
9
- private pool;
10
- private cur;
11
- private finished;
12
- private _resolve?;
13
- static doNAsyncAtOnce(max?: number, pool?: Array<AsyncPoolTask | (() => Promise<void>)>): Promise<boolean>;
14
- constructor(max?: number, pool?: Array<AsyncPoolTask>);
15
- private getHighPriorityFirst;
16
- private runTask;
17
- private runTasks;
18
- run(): Promise<boolean>;
19
- push(x: AsyncPoolTask | (() => Promise<void>)): void;
20
- }
1
+ declare type AnyFunction = (...args: any[]) => any;
21
2
 
22
- declare interface AsyncPoolTask {
23
- v: () => Promise<void>;
24
- p: number;
25
- }
3
+ export declare function checkHomogenity<T extends HTMLElement>(a: T, b: T, options: {
4
+ id?: boolean;
5
+ className?: boolean;
6
+ }): boolean;
26
7
 
27
- export declare function chunks<T>(arr: Array<T>, n: number): Array<Array<T>>;
8
+ export declare function chunks<T>(arr: T[], size: number): T[][];
28
9
 
29
10
  export declare function circularShift(n: number, c?: number, s?: number): number;
30
11
 
31
- export declare function computeAsyncOneAtTime(iterable: Iterable<() => Promise<void>>): Promise<void[]>;
32
-
33
- export declare function copyAttributes(target: HTMLElement, source: HTMLElement): void;
34
-
35
- declare type CustomSelector<R> = {
36
- handle: (el: DataElement, state: StoreState, $preDefineResult?: R) => boolean;
37
- $preDefine?: (state: StoreState) => R;
38
- };
39
-
40
- declare type DataElement = Record<string, string | number | boolean | HTMLElement>;
41
-
42
- export declare class DataManager {
43
- private rules;
44
- private state;
45
- private data;
46
- private lazyImgLoader;
47
- private dataFilter;
48
- constructor(rules: RulesGlobal, state: StoreState);
49
- isFiltered(el: HTMLElement): boolean;
50
- applyFilters: (filters?: {
51
- [key: string]: boolean;
52
- }, offset?: number) => void;
53
- filterAll: (offset?: number) => void;
54
- parseData: (html: HTMLElement, container?: HTMLElement, removeDuplicates?: boolean, shouldLazify?: boolean) => void;
55
- sortBy<K extends keyof DataElement>(key: K): void;
56
- }
12
+ export declare function copyAttributes<T extends Element = HTMLElement>(target: T, source: T): void;
57
13
 
58
14
  export declare function downloader(options?: {
59
15
  append: string;
@@ -64,50 +20,23 @@ export declare function downloader(options?: {
64
20
 
65
21
  export declare function exterminateVideo(video: HTMLVideoElement): void;
66
22
 
67
- export declare const fetchHtml: (url: string) => Promise<HTMLElement>;
68
-
69
- export declare const fetchText: (url: string) => Promise<string>;
23
+ export declare const fetchHtml: (input: RequestInfo | URL) => Promise<HTMLElement>;
70
24
 
71
- export declare function fetchWith(url: string, options?: {
72
- html?: boolean;
73
- mobile?: boolean;
74
- }): Promise<string | HTMLElement>;
75
-
76
- export declare function findNextSibling(el: HTMLElement): Element | null;
77
-
78
- declare type GeneratorResult = {
79
- url: string;
80
- offset: number;
81
- };
25
+ export declare const fetchJson: (input: RequestInfo | URL) => Promise<JSON>;
82
26
 
83
- export declare function getAllUniqueParents(elements: HTMLCollection | HTMLElement[]): HTMLElement[];
27
+ export declare const fetchText: (input: RequestInfo | URL) => Promise<string>;
84
28
 
85
- export declare function getPaginationStrategy(options: Partial<PaginationStrategy>): PaginationStrategy;
29
+ export declare function fetchWith<T extends JSON | string | HTMLElement>(input: RequestInfo | URL, options: {
30
+ init?: RequestInit;
31
+ type: 'json' | 'html' | 'text';
32
+ mobile?: boolean;
33
+ }): Promise<T>;
86
34
 
87
- export declare class InfiniteScroller {
88
- enabled: boolean;
89
- delay: number;
90
- paginationOffset: number;
91
- writeHistory: boolean;
92
- parseData?: (document: HTMLElement) => void;
93
- rules: RulesGlobal;
94
- private observer?;
95
- private paginationGenerator;
96
- constructor(options: InfiniteScrollerOptions);
97
- dispose(): void;
98
- setObserver(observable: HTMLElement): this;
99
- private onScrollCBs;
100
- onScroll(callback: (scroller: InfiniteScroller) => void, initCall?: boolean): this;
101
- private _onScroll;
102
- generatorConsumer: () => Promise<boolean>;
103
- doScroll(url: string, offset: number): Promise<void>;
104
- private createPaginationGenerator;
105
- static create(store: JabronioStore, rules: RulesGlobal, parseData: (document: HTMLElement) => void): InfiniteScroller;
106
- }
35
+ export declare function findNextSibling<T extends Element = HTMLElement>(e: T): Element | null;
107
36
 
108
- declare type InfiniteScrollerOptions = Pick<InfiniteScroller, 'rules'> & Partial<InfiniteScroller>;
37
+ export declare function getCommonParents(elements: HTMLCollection | HTMLElement[]): HTMLElement[];
109
38
 
110
- export declare function isMob(): boolean;
39
+ export declare function instantiateTemplate(sourceSelector: string, attributeUpdates: Record<string, string>, contentUpdates: Record<string, string>): string;
111
40
 
112
41
  export declare class LazyImgLoader {
113
42
  lazyImgObserver: Observer;
@@ -117,16 +46,19 @@ export declare class LazyImgLoader {
117
46
  delazify: (target: HTMLImageElement) => void;
118
47
  }
119
48
 
120
- export declare function listenEvents(dom: HTMLElement, events: Array<string>, callback: (e: Event) => void): void;
49
+ export declare function memoize<T extends AnyFunction>(fn: T): MemoizedFunction<T>;
121
50
 
122
- export declare const MOBILE_UA: string;
51
+ declare interface MemoizedFunction<T extends AnyFunction> extends CallableFunction {
52
+ (...args: Parameters<T>): ReturnType<T>;
53
+ clear: () => void;
54
+ }
123
55
 
124
56
  export declare function objectToFormData<T extends {}>(obj: T): FormData;
125
57
 
126
58
  export declare class Observer {
127
59
  private callback;
128
60
  observer: IntersectionObserver;
129
- private timeout;
61
+ private timeout?;
130
62
  constructor(callback: (entry: Element) => void);
131
63
  observe(target: Element): void;
132
64
  throttle(target: Element, throttleTime: number): void;
@@ -135,118 +67,60 @@ export declare class Observer {
135
67
  static observeWhile(target: Element, callback: () => Promise<boolean> | boolean, throttleTime: number): Observer;
136
68
  }
137
69
 
138
- declare type OffsetGenerator = Generator<GeneratorResult> | AsyncGenerator<GeneratorResult>;
139
-
140
- export declare class PaginationStrategy {
141
- doc: Document;
142
- url: URL;
143
- paginationSelector: string;
144
- searchParamSelector: string;
145
- static _pathnameSelector: RegExp;
146
- pathnameSelector: RegExp;
147
- dataparamSelector: string;
148
- fixPaginationLast?: (n: number, offset?: number) => number;
149
- offsetMin: number;
150
- constructor(options?: Partial<PaginationStrategy>);
151
- getPaginationElement(): HTMLElement | null;
152
- get hasPagination(): boolean;
153
- getPaginationOffset(): number;
154
- getPaginationLast(): number;
155
- getPaginationUrlGenerator(): (_: number) => string;
70
+ export declare class OnHover {
71
+ private container;
72
+ private subjectSelector;
73
+ private onOver;
74
+ private onLeave?;
75
+ private handleLeaveEvent;
76
+ private handleEvent;
77
+ private target;
78
+ private leaveSubject;
79
+ private onOverFinally;
80
+ constructor(container: HTMLElement, subjectSelector: (target: HTMLElement) => boolean, onOver: (target: HTMLElement) => void | {
81
+ onOverCallback?: () => void;
82
+ leaveTarget?: HTMLElement;
83
+ }, onLeave?: ((target: HTMLElement) => void) | undefined);
84
+ static create(...args: ConstructorParameters<typeof OnHover>): OnHover;
156
85
  }
157
86
 
158
- export declare class PaginationStrategyDataParams extends PaginationStrategy {
159
- getPaginationLast(): number;
160
- getPaginationOffset(): number;
161
- getPaginationUrlGenerator(): (n: number) => string;
162
- static testLinks(doc?: HTMLElement | Document): boolean;
163
- }
164
-
165
- export declare class PaginationStrategyPathnameParams extends PaginationStrategy {
166
- extractPage: (a: HTMLAnchorElement | Location | string) => number;
167
- static checkLink(link: URL, pathnameSelector?: RegExp): boolean;
168
- static testLinks(links: URL[], options: Partial<PaginationStrategy>): boolean;
169
- getPaginationLast(): number;
170
- getPaginationOffset(): number;
171
- getPaginationUrlGenerator(url_?: URL): (offset: number) => string;
172
- }
173
-
174
- export declare class PaginationStrategySearchParams extends PaginationStrategy {
175
- extractPage: (a: HTMLAnchorElement | Location | URL | string) => number;
176
- getPaginationLast(): number;
177
- getPaginationOffset(): number;
178
- getPaginationUrlGenerator(): (offset: number) => string;
179
- static checkLink(link: URL, searchParamSelector?: string): boolean;
180
- static testLinks(links: URL[], searchParamSelector?: string): boolean;
181
- }
182
-
183
- export declare function parseCSSUrl(s: string): string;
87
+ export declare function parseCssUrl(s: string): string;
184
88
 
185
89
  export declare function parseDataParams(str: string): Record<string, string>;
186
90
 
187
- export declare function parseDom(html: string): HTMLElement;
91
+ export declare function parseHtml(html: string): HTMLElement;
188
92
 
189
93
  export declare function parseIntegerOr(n: string | number, or: number): number;
190
94
 
191
- export declare function querySelectorText(el: HTMLElement, selector?: string): string;
95
+ export declare function propsDifference<T extends Record<string, unknown>, U extends object>(obj1: T | U, obj2: T | U): {
96
+ d1: string[];
97
+ d2: string[];
98
+ };
192
99
 
193
- export declare function range(size: number, startAt?: number, step?: number): number[];
100
+ export declare function querySelectorLast<T extends Element = HTMLElement>(root: ParentNode | undefined, selector: string): T | undefined;
194
101
 
195
- export declare function replaceElementTag(e: HTMLElement, tagName: string): HTMLElement;
102
+ export declare function querySelectorLastNumber(selector: string, e?: ParentNode): number;
196
103
 
197
- export declare class RulesGlobal {
198
- delay?: number;
199
- alternativeGenerator?: () => OffsetGenerator;
200
- getThumbUrl(thumb: HTMLElement | HTMLAnchorElement): string;
201
- titleSelector: undefined | string;
202
- uploaderSelector: undefined | string;
203
- durationSelector: undefined | string;
204
- getThumbDataStrategy: 'default' | 'auto-select' | 'auto-text';
205
- getThumbDataCallback?: (thumb: HTMLElement, thumbData: ThumbData) => void;
206
- getThumbData(thumb: HTMLElement): ThumbData;
207
- getThumbImgDataAttrSelector: string | undefined;
208
- getThumbImgDataStrategy: 'default' | 'auto';
209
- getThumbImgData(thumb: HTMLElement): {
210
- img?: HTMLImageElement;
211
- imgSrc?: string;
212
- };
213
- containerSelector: string | (() => HTMLElement);
214
- intersectionObservable?: HTMLElement;
215
- get container(): HTMLElement;
216
- thumbsSelector: string;
217
- getThumbsStrategy: 'default' | 'auto';
218
- getThumbs(html: HTMLElement): HTMLElement[];
219
- paginationStrategyOptions: Partial<PaginationStrategy>;
220
- paginationStrategy: PaginationStrategy;
221
- get observable(): HTMLElement;
222
- mutationObservers: MutationObserver[];
223
- reset(): void;
224
- resetOnPaginationOrContainerDeath: boolean;
225
- resetOn(): void;
226
- customSelectors: Record<string, CustomSelector<any>>;
227
- animatePreview?: (doc?: HTMLElement) => void;
228
- storeOptions?: JabroniTypes.StoreStateOptions;
229
- customScheme?: JabroniTypes.SchemeInput;
230
- defaultSchemeOptions: Parameters<typeof setupScheme>[0];
231
- store: JabronioStore;
232
- gui: JabronioGUI;
233
- dataManager: DataManager;
234
- infiniteScroller?: InfiniteScroller;
235
- private resetInfiniteScroller;
236
- initialGrope: 'all-in-one' | 'all-in-all' | undefined;
237
- gropeInit(): void;
238
- constructor(options: Partial<RulesGlobal>);
104
+ export declare function querySelectorText(e: ParentNode, selector?: string): string;
105
+
106
+ export declare function range(size: number, start?: number, step?: number): number[];
107
+
108
+ export declare class RegexFilter {
109
+ private regexes;
110
+ constructor(str: string, flags?: string);
111
+ private compileSearchRegex;
112
+ hasEvery(str: string): boolean;
113
+ hasNone(str: string): boolean;
239
114
  }
240
115
 
116
+ export declare function removeClassesAndDataAttributes(element: HTMLElement, keyword: string): void;
117
+
118
+ export declare function replaceElementTag(e: HTMLElement, tagName: string): HTMLElement;
119
+
241
120
  export declare function sanitizeStr(s: string): string;
242
121
 
243
122
  export declare function splitWith(s: string, c?: string): Array<string>;
244
123
 
245
- declare type ThumbData = {
246
- title: string;
247
- duration?: number;
248
- };
249
-
250
124
  export declare class Tick {
251
125
  private delay;
252
126
  private startImmediate;
@@ -257,16 +131,21 @@ export declare class Tick {
257
131
  stop(): void;
258
132
  }
259
133
 
260
- export declare function timeToSeconds(t: string): number;
134
+ /**
135
+ * Converts a time string (HH:MM:SS or duration format) to total seconds.
136
+ * @param timeStr - The time string to convert.
137
+ * @returns The total number of seconds.
138
+ */
139
+ export declare function timeToSeconds(timeStr: string): number;
261
140
 
262
141
  export declare function wait(milliseconds: number): Promise<unknown>;
263
142
 
264
- export declare function waitForElementToAppear(parent: HTMLElement, selector: string, callback: (el: Element) => void): MutationObserver;
143
+ export declare function waitForElementToAppear(parent: ParentNode, selector: string, callback: (el: Element) => void): MutationObserver;
265
144
 
266
145
  export declare function waitForElementToDisappear(observable: HTMLElement, callback: () => void): MutationObserver;
267
146
 
268
147
  export declare function watchDomChangesWithThrottle(element: HTMLElement, callback: () => void, throttle?: number, times?: number, options?: MutationObserverInit): MutationObserver;
269
148
 
270
- export declare function watchElementChildrenCount(element: HTMLElement, callback: (observer: MutationObserver, count: number) => void): MutationObserver;
149
+ export declare function watchElementChildrenCount(element: ParentNode, callback: (observer: MutationObserver, count: number) => void): MutationObserver;
271
150
 
272
151
  export { }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "billy-herrington-utils",
3
3
  "description": "daddy told us not to be ashamed of our utils",
4
- "version": "2.0.6",
4
+ "version": "2.1.0",
5
5
  "license": "MIT",
6
6
  "keywords": [
7
7
  "utils",
@@ -9,7 +9,19 @@
9
9
  "dom",
10
10
  "fetch",
11
11
  "arrays",
12
- "typescript"
12
+ "typescript",
13
+ "async",
14
+ "promises",
15
+ "mutation-observer",
16
+ "throttle",
17
+ "memoize",
18
+ "lazy-loading",
19
+ "string-manipulation",
20
+ "formatting",
21
+ "html-parser",
22
+ "helpers",
23
+ "toolkit",
24
+ "dom-manipulation"
13
25
  ],
14
26
  "author": "smartacephale atm.mormon@protonmail.com (https://github.com/smartacephale)",
15
27
  "homepage": "https://github.com/smartacephale/billy-herrington-utils#readme",
@@ -41,10 +53,9 @@
41
53
  "preview": "vite preview"
42
54
  },
43
55
  "devDependencies": {
44
- "@types/tampermonkey": "^5.0.5",
45
- "jabroni-outfit": "^2.0.92",
46
- "typescript": "^5.5.3",
47
- "vite": "^6.4.1",
48
- "vite-plugin-dts": "^4.0.3"
56
+ "@types/node": "^25.2.3",
57
+ "typescript": "^5.9.3",
58
+ "vite": "^7.3.1",
59
+ "vite-plugin-dts": "^4.5.4"
49
60
  }
50
61
  }
package/src/index.ts CHANGED
@@ -1,44 +1 @@
1
- export { DataManager } from './userscripts/data-manager';
2
- export { InfiniteScroller } from './userscripts/infinite-scroll';
3
- export { getPaginationStrategy } from './userscripts/pagination-parsing';
4
- export {
5
- PaginationStrategy,
6
- PaginationStrategyDataParams,
7
- PaginationStrategyPathnameParams,
8
- PaginationStrategySearchParams,
9
- } from './userscripts/pagination-parsing/pagination-strategies';
10
- export { RulesGlobal } from './userscripts/rules';
11
- export { chunks, range } from './utils/arrays';
12
- export { AsyncPool, computeAsyncOneAtTime, wait } from './utils/async';
13
- export { isMob } from './utils/device';
14
- export {
15
- copyAttributes,
16
- downloader,
17
- exterminateVideo,
18
- findNextSibling,
19
- getAllUniqueParents,
20
- parseDom,
21
- querySelectorText,
22
- replaceElementTag,
23
- waitForElementToAppear,
24
- waitForElementToDisappear,
25
- watchDomChangesWithThrottle,
26
- watchElementChildrenCount,
27
- } from './utils/dom';
28
- export { listenEvents, Tick } from './utils/events';
29
- export {
30
- fetchHtml,
31
- fetchText,
32
- fetchWith,
33
- MOBILE_UA,
34
- objectToFormData,
35
- } from './utils/fetch';
36
- export { circularShift } from './utils/math';
37
- export { LazyImgLoader, Observer } from './utils/observers';
38
- export {
39
- parseCSSUrl,
40
- parseDataParams,
41
- parseIntegerOr,
42
- timeToSeconds,
43
- } from './utils/parsers';
44
- export { sanitizeStr, splitWith } from './utils/strings';
1
+ export * from './utils'
@@ -0,0 +1,7 @@
1
+ export type AnyFunction = (...args: any[]) => any;
2
+
3
+ export type NonFunctionKeys<T> = {
4
+ [K in keyof T]: T[K] extends AnyFunction ? never : K;
5
+ }[keyof T];
6
+
7
+ export type NonFunctionProperties<T> = Pick<T, NonFunctionKeys<T>>;
@@ -1,9 +1,15 @@
1
- export function chunks<T>(arr: Array<T>, n: number): Array<Array<T>> {
2
- return Array.from({ length: Math.ceil(arr.length / n) }, (_, i) =>
3
- arr.slice(i * n, i * n + n),
1
+ export function chunks<T>(arr: T[], size: number): T[][] {
2
+ return Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
3
+ arr.slice(i * size, i * size + size),
4
4
  );
5
5
  }
6
6
 
7
- export function range(size: number, startAt: number = 1, step: number = 1): number[] {
8
- return Array.from({ length: size }, (_, index) => startAt + index * step);
7
+ export function* irange(start: number = 1, step: number = 1) {
8
+ for (let i = start; ; i += step) {
9
+ yield i;
10
+ }
11
+ }
12
+
13
+ export function range(size: number, start: number = 1, step: number = 1): number[] {
14
+ return irange(start, step).take(size).toArray();
9
15
  }
@@ -1,91 +1,3 @@
1
- // https://2ality.com/2016/10/asynchronous-iteration.html
2
- export async function computeAsyncOneAtTime(iterable: Iterable<() => Promise<void>>) {
3
- const res = [];
4
- for await (const f of iterable) {
5
- try {
6
- const r = await f();
7
- res.push(r);
8
- } catch (e) {
9
- console.error(e);
10
- }
11
- }
12
- return res;
13
- }
14
-
15
1
  export function wait(milliseconds: number) {
16
2
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
17
3
  }
18
-
19
- interface AsyncPoolTask {
20
- v: () => Promise<void>;
21
- p: number;
22
- }
23
-
24
- export class AsyncPool {
25
- private cur = 0;
26
- private finished: Promise<boolean>;
27
- private _resolve?: (value: boolean | PromiseLike<boolean>) => void;
28
-
29
- public static async doNAsyncAtOnce(
30
- max = 1,
31
- pool: Array<AsyncPoolTask | (() => Promise<void>)> = [],
32
- ) {
33
- const spool = new AsyncPool(max);
34
- pool.forEach((f) => {
35
- spool.push(f);
36
- });
37
- return spool.run();
38
- }
39
-
40
- constructor(
41
- private max = 1,
42
- private pool: Array<AsyncPoolTask> = [],
43
- ) {
44
- this.finished = new Promise((resolve) => {
45
- this._resolve = resolve;
46
- });
47
- }
48
-
49
- private getHighPriorityFirst(p = 0): (() => Promise<void>) | undefined {
50
- if (p > 3 || this.pool.length === 0) return undefined;
51
- const i = this.pool.findIndex((e) => e.p === p);
52
- if (i >= 0) {
53
- const res = this.pool[i].v;
54
- this.pool.splice(i, 1);
55
- return res;
56
- }
57
- return this.getHighPriorityFirst(p + 1);
58
- }
59
-
60
- private async runTask() {
61
- this.cur++;
62
- const f = this.getHighPriorityFirst();
63
- try {
64
- await f?.();
65
- } catch (e) {
66
- console.error(e);
67
- }
68
- this.cur--;
69
- this.runTasks();
70
- }
71
-
72
- private runTasks() {
73
- if (!this.pool.length) {
74
- this._resolve?.(true);
75
- return;
76
- }
77
- if (this.cur < this.max) {
78
- this.runTask();
79
- this.runTasks();
80
- }
81
- }
82
-
83
- public async run() {
84
- this.runTasks();
85
- return this.finished;
86
- }
87
-
88
- public push(x: AsyncPoolTask | (() => Promise<void>)) {
89
- this.pool.push('p' in x ? x : { v: x, p: 0 });
90
- }
91
- }
@@ -1,5 +1,5 @@
1
1
  export function waitForElementToAppear(
2
- parent: HTMLElement,
2
+ parent: ParentNode,
3
3
  selector: string,
4
4
  callback: (el: Element) => void,
5
5
  ) {
@@ -28,7 +28,7 @@ export function waitForElementToDisappear(observable: HTMLElement, callback: ()
28
28
  }
29
29
 
30
30
  export function watchElementChildrenCount(
31
- element: HTMLElement,
31
+ element: ParentNode,
32
32
  callback: (observer: MutationObserver, count: number) => void,
33
33
  ) {
34
34
  let count = element.children.length;
@@ -67,7 +67,7 @@ export function watchDomChangesWithThrottle(
67
67
  if (lastMutationTime && now - lastMutationTime < throttle) {
68
68
  timeout && clearTimeout(timeout);
69
69
  }
70
- timeout = setTimeout(callback, throttle);
70
+ timeout = window.setTimeout(callback, throttle);
71
71
  lastMutationTime = now;
72
72
  });
73
73