/
preventWidows.js
80 lines (68 loc) · 1.88 KB
/
preventWidows.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
const posthtml = require('posthtml')
const {get, isEmpty} = require('lodash')
const {removeWidows} = require('string-remove-widows')
module.exports = async (html, config = {}) => {
if (isEmpty(config)) {
return removeWidows(html).res
}
const posthtmlOptions = get(config, 'build.posthtml.options', {recognizeNoValueAttribute: true})
return posthtml([removeWidowsPlugin(config)]).process(html, posthtmlOptions).then(result => result.html)
}
const removeWidowsPlugin = options => tree => {
const {attrName = 'prevent-widows', ...removeWidowsOptions} = get(options, 'widowWords', options)
removeWidowsOptions.minWordCount = removeWidowsOptions.minWordCount || 3
// Ignore defaults
const mappings = [
// Jinja-like
{
heads: '{{',
tails: '}}'
},
{
heads: ['{% if', '{%- if'],
tails: ['{% endif', '{%- endif']
},
{
heads: ['{% for', '{%- for'],
tails: ['{% endfor', '{%- endfor']
},
{
heads: ['{%', '{%-'],
tails: ['%}', '-%}']
},
{
heads: '{#',
tails: '#}'
},
// ASP/Hexo-like
{
heads: ['<%', '<%=', '<%-'],
tails: ['%>', '=%>', '-%>']
},
// MSO comments
{
heads: '<!--[',
tails: ']>'
},
// <![endif]-->
{
heads: '<![',
tails: ']--><'
}
]
if (Array.isArray(removeWidowsOptions.ignore)) {
removeWidowsOptions.ignore.forEach(pair => mappings.push(pair))
}
if (typeof removeWidowsOptions.ignore !== 'string') {
removeWidowsOptions.ignore = mappings
}
const process = node => {
if (node.attrs && Object.keys(node.attrs).includes(attrName)) {
const widowsRemovedString = removeWidows(tree.render(node.content), removeWidowsOptions).res
node.content = tree.render(tree.parser(widowsRemovedString))
node.attrs[attrName] = false
}
return node
}
return tree.walk(process)
}