forked from awinogradov/dom-objects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
44 lines (37 loc) · 1.39 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
type DataAttribute<T> =`data-${T extends string ? T : string}`;
type DataAttributeQuery<T extends string, V, K extends string = DataAttribute<T>> = `[${K}="${V extends string ? V: string}"]`;
interface DomObjectsOptions<T extends string> {
/**
* This attribute will be passed as [data-{attributeName}].
* Ex: [data-cy], [data-test-id] and etc.
*/
attributeName: T;
}
interface DomObjectsResult<T extends string, V extends string> {
add<V1 extends string>(name: V1): DomObjectsResult<T, V1>;
attr?: {
[K in DataAttribute<T>]: V;
};
query: DataAttributeQuery<T, V>;
}
export const configureDomObjects = <T extends string>({ attributeName }: DomObjectsOptions<T>) => {
return <V extends string>(name: V) => {
const dataAttr = `data-${attributeName}`;
const queue: string[] = [name];
const getMethods = (currentQueue: string[]) => ({
get attr() {
return {
[dataAttr]: currentQueue[currentQueue.length - 1],
};
},
get query() {
return currentQueue.map((s) => `[${dataAttr}="${s}"]`).join(" ");
},
add(name: string) {
const nextQueue = currentQueue.concat(name);
return getMethods(nextQueue);
},
});
return getMethods(queue) as DomObjectsResult<T, V>;
};
};