forked from rehypejs/rehype-minify
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (80 loc) · 2 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
84
85
86
87
88
89
90
/**
* rehype plugin to minify whitespace in attributes.
*
* ## What is this?
*
* This package is a plugin that can remove unneeded whitespace around the
* values of certain attributes.
*
* ## When should I use this?
*
* You can use this plugin when you want to improve the size of HTML documents.
*
* ## API
*
* ### `unified().use(rehypeMinifyAttributeWhitespace)`
*
* Minify whitespace in attributes.
* There are no options.
*
* @example
* <a href=" http://example.com "></a>
*/
/**
* @typedef {import('hast').Root} Root
* @typedef {import('hast').Element} Element
*/
import {visit} from 'unist-util-visit'
import {hasProperty} from 'hast-util-has-property'
import {isElement} from 'hast-util-is-element'
import {isEventHandler} from 'hast-util-is-event-handler'
import {schema} from './schema.js'
const own = {}.hasOwnProperty
/**
* Minify whitespace in attributes.
*
* @type {import('unified').Plugin<Array<void>, Root>}
*/
export default function rehypeMinifyAttributeWhitespace() {
return (tree) => {
visit(tree, 'element', (node) => {
const props = node.properties || {}
/** @type {string} */
let prop
for (prop in props) {
if (
hasProperty(node, prop) &&
(isEventHandler(prop) ||
(own.call(schema, prop) && isElement(node, schema[prop])))
) {
props[prop] = minify(props[prop])
}
}
})
}
}
/**
* @param {null|undefined|string|number|boolean|Array<string|number>} value
*/
function minify(value) {
return Array.isArray(value) ? all(value) : one(value)
}
/**
* @param {Array<string|number>} value
*/
function all(value) {
let index = -1
/** @type {Array<string|number>} */
const result = []
while (++index < value.length) {
// @ts-expect-error: input matches output.
result[index] = one(value[index])
}
return result
}
/**
* @param {null|undefined|string|number|boolean} value
*/
function one(value) {
return typeof value === 'string' ? String(value).trim() : value
}