-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
83 lines (69 loc) · 2.11 KB
/
index.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import {
escapeHTMLEntities,
} from '../../dist/esm/value/index.js';
/**
* Generates a string of HTML attributes.
*
* This function represents the original implementation transpiled from PHP.
*
* @see https://github.com/mcaskill/php-html-build-attributes/tree/v1.2.1 mcaskill/php-html-build-attributes
*
* @param object attrs
* @param function [escape=escapeHTMLEntities]
* @returns string
*/
export function html_build_attributes(attrs, escape = escapeHTMLEntities)
{
const html = [];
for (let [ key, val ] of Object.entries(attrs)) {
if (typeof key === 'string') {
key = key.trim();
if (key.length === 0) {
continue;
}
}
const valType = typeof val;
if (valType === 'function') {
val = val();
}
if (val == null) {
continue;
}
if (valType === 'object' && valType.toArray === 'function') {
val = val.toArray();
}
if (valType === 'boolean') {
if (val) {
html.push(key);
}
continue;
} else if (Array.isArray(val)) {
val = val.reduce(function (tokens, token) {
const tokenType = typeof token;
if (tokenType === 'string') {
token = token.trim();
if (token.length > 0) {
tokens.push(token);
}
} else if (tokenType === 'number') {
tokens.push(token);
}
return tokens;
}, []).join(' ');
if (val.length === 0) {
continue;
}
} else if (valType !== 'string' && valType !== 'number') {
if (valType === 'object' && valType.toString === 'function') {
val = val.toString();
} else {
val = JSON.stringify(val);
}
}
if (typeof escape === 'function') {
val = escape(val);
}
html.push(`${key}="${val}"`);
}
return html.join(' ');
}