This repository was archived by the owner on Jul 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataAttribute.ts
55 lines (52 loc) · 1.76 KB
/
dataAttribute.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
45
46
47
48
49
50
51
52
53
54
55
import camelCaseToDashCase from '../strings/camelCaseToDashCase';
export interface DataAttribute {
readonly asObject: (value?: unknown) => { [K: string]: string };
readonly assign: <T extends Element = Element>(element: T) => T;
readonly asString: (value?: unknown) => string;
readonly get: <T extends Element = Element>(element: T) => string | null;
readonly has: <T extends Element = Element>(element: T) => boolean;
readonly name: () => string;
readonly remove: <T extends Element = Element>(element: T) => T;
readonly toJSON: () => { [K: string]: string };
readonly toString: () => string;
readonly value: (value?: unknown) => string;
}
const dataAttribute = (attribute: string, prefix?: string): DataAttribute => {
const currentName = camelCaseToDashCase(
prefix ? `data-${prefix}-${attribute}` : `data-${attribute}`,
);
let currentValue = '';
const value: DataAttribute['value'] = v => {
if (typeof v !== 'undefined') currentValue = `${v}`;
return currentValue;
};
const asObject: DataAttribute['asObject'] = v => ({
[currentName]: value(v),
});
const assign: DataAttribute['assign'] = e => {
e.setAttribute(currentName, currentValue);
return e;
};
const asString: DataAttribute['asString'] = v =>
`${currentName}="${value(v)}"`;
const get: DataAttribute['get'] = e => e.getAttribute(currentName);
const has: DataAttribute['has'] = e => get(e) !== null;
const name: DataAttribute['name'] = () => currentName;
const remove: DataAttribute['remove'] = e => {
e.removeAttribute(currentName);
return e;
};
return {
asObject,
assign,
asString,
get,
has,
name,
remove,
toString: () => asString(),
toJSON: () => asObject(),
value,
};
};
export default dataAttribute;