/
plaintext.js
85 lines (69 loc) · 2.44 KB
/
plaintext.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
const path = require('path')
const posthtml = require('posthtml')
const {get, merge} = require('lodash')
const {stripHtml} = require('string-strip-html')
const defaultConfig = require('./posthtml/defaultConfig')
const self = {
handleCustomTags: (html, config = {}) => {
const posthtmlOptions = merge(defaultConfig, get(config, 'build.posthtml.options', {}))
const posthtmlPlugin = () => tree => {
const process = node => {
if (node.tag === 'plaintext') {
return {
tag: false,
content: ['']
}
}
if (node.tag === 'not-plaintext') {
return {
tag: false,
content: tree.render(node.content)
}
}
return node
}
return tree.walk(process)
}
return posthtml([posthtmlPlugin()]).process(html, {...posthtmlOptions, sync: true}).html
},
generate: async (html, destination, config) => {
const configDestinationPath = get(config, 'destination.path')
const extension = get(config, 'destination.extension', 'txt')
const plaintext = stripHtml(html, {
dumpLinkHrefsNearby: {
enabled: true
},
stripTogetherWithTheirContents: ['script', 'style', 'xml', 'not-plaintext'],
...get(config, 'options', {})
}).result
html = self.handleCustomTags(html, config)
// If we set plaintext.destination.path in config/fm
if (configDestinationPath) {
/**
* Using a file path will generate a single plaintext file,
* no matter how many templates there are.
*
* It will be based on the last-processed template.
*/
if (path.extname(configDestinationPath)) {
destination = configDestinationPath
return {html, plaintext, destination}
}
/**
* Using a directory-like path for plaintext.destination.path
*/
destination = path.join(configDestinationPath, path.basename(config.filepath, path.extname(config.filepath)) + '.' + extension)
return {html, plaintext, destination}
}
/**
* Use template's `permalink` Front Matter key,
* fall back to the original `destination`.
*/
destination = get(config, 'permalink', destination)
if (typeof destination === 'string') {
destination = path.join(path.dirname(destination), path.basename(destination, path.extname(destination)) + '.' + extension)
}
return {html, plaintext, destination}
}
}
module.exports = self