forked from rehypejs/rehype-minify
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (74 loc) · 2.12 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
/**
* rehype plugin to minify `content` attributes on `<meta>` elements.
*
* ## What is this?
*
* This package is a plugin that can minify the value of the `content` attribute
* of `<meta>` elements.
*
* Note that `meta[name=theme-color]` and `meta[name=msapplication-TileColor]`
* are handled by
* [`rehype-minify-meta-color`](https://github.com/rehypejs/rehype-minify/tree/main/packages/rehype-minify-meta-color).
*
* ## When should I use this?
*
* You can use this plugin when you want to improve the size of HTML documents.
*
* ## API
*
* ### `unified().use(rehypeMinifyMetaContent)`
*
* Minify `content` attributes on `meta` elements.
* There are no options.
*
* @example
* <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
* <meta name="keywords" content="foo, bar baz, qux">
*/
/**
* @typedef {import('hast').Root} Root
*/
import {parse, stringify} from 'comma-separated-tokens'
import {visit} from 'unist-util-visit'
import {isElement} from 'hast-util-is-element'
import {hasProperty} from 'hast-util-has-property'
const lists = new Set([
'viewport',
'keywords',
'robots',
'apple-itunes-app',
'apple-media-service-subscription'
])
/**
* Minify `content` on `meta` elements.
*
* Note: `meta[name=theme-color]` and `meta[name=msapplication-TileColor]`
* are handled by `rehype-minify-meta-color`.
*
* @type {import('unified').Plugin<Array<void>, Root>}
*/
export default function rehypeMinifyMetaContent() {
return (tree) => {
visit(tree, 'element', (node) => {
const props = node.properties || {}
const name = String(props.name || '')
let value = props.content
if (
isElement(node, 'meta') &&
hasProperty(node, 'content') &&
typeof value === 'string'
) {
if (name === 'viewport') {
value = value
.replace(/(\d+\.\d+)/, (d) => String(Number(d)))
.replace(/user-scalable=\s*yes/, '')
// Fall through.
}
if (lists.has(name)) {
value = stringify(parse(value), {padLeft: false})
}
props.content = value
}
})
}
}