forked from rehypejs/rehype-minify
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
63 lines (57 loc) · 1.39 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
/**
* rehype plugin to remove empty attributes.
*
* ## What is this?
*
* This package is a plugin that removes whole attributes when their value is
* empty.
*
* ## When should I use this?
*
* You can use this plugin when you want to improve the transfer size of HTML
* documents.
*
* ## API
*
* ### `unified().use(rehypeRemoveEmptyAttribute)`
*
* Remove empty attributes.
* There are no options.
*
* @example
* <label for id=""></label>
*/
/**
* @typedef {import('hast').Root} Root
*/
import {visit} from 'unist-util-visit'
import {isElement} from 'hast-util-is-element'
import {isEventHandler} from 'hast-util-is-event-handler'
import {schema} from './schema.js'
const own = {}.hasOwnProperty
/**
* Remove empty attributes, if possible.
*
* @type {import('unified').Plugin<Array<void>, Root>}
*/
export default function rehypeRemoveEmptyAttribute() {
return (tree) => {
visit(tree, 'element', (node) => {
const props = node.properties || {}
/** @type {string} */
let prop
for (prop in props) {
if (own.call(props, prop)) {
const value = props[prop]
if (
(value === '' || (Array.isArray(value) && value.length === 0)) &&
(isEventHandler(prop) ||
(own.call(schema, prop) && isElement(node, schema[prop])))
) {
props[prop] = null
}
}
}
})
}
}