forked from rehypejs/rehype-minify
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
65 lines (59 loc) · 1.65 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
/**
* rehype plugin to minify language attributes.
*
* ## What is this?
*
* This package is a plugin that can minify the contents of language tags:
* [BCP 47 tags](https://github.com/wooorm/bcp-47).
*
* ## When should I use this?
*
* You can use this plugin when you want to improve the size of HTML documents.
*
* ## API
*
* ### `unified().use(rehypeMinifyLanguage)`
*
* Minify language attributes.
* There are no options.
*
* @example
* <span lang="en-US">Color</span>
* <a href="https://nl.wikipedia.org/wiki/HyperText_Markup_Language" hreflang="nld-NL">HTML</a>
* <span xml:lang="pt-BR">ótimo</span>
* <track src="colour.vtt" srclang="en-GB" label="English (UK)">
*/
/**
* @typedef {import('hast').Root} Root
*/
import {bcp47Normalize} from 'bcp-47-normalize'
import {visit} from 'unist-util-visit'
import {hasProperty} from 'hast-util-has-property'
const fields = ['hrefLang', 'lang', 'srcLang', 'xmlLang']
/**
* Minify language attributes.
*
* @type {import('unified').Plugin<Array<void>, Root>}
*/
export default function rehypeMinifyLanguage() {
return (tree) => {
visit(tree, 'element', (node) => {
const props = node.properties
let index = -1
while (++index < fields.length) {
const prop = fields[index]
if (
props &&
hasProperty(node, prop) &&
typeof props[prop] === 'string'
) {
// BCP 47 tags are case-insensitive, but in this project we prefer
// lowercase which *should* help GZIP.
props[prop] = String(
bcp47Normalize(String(props[prop])) || props[prop]
).toLowerCase()
}
}
})
}
}