-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
99 lines (76 loc) · 3.13 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
91
92
93
94
95
96
97
98
99
const debug = require("debug")("metalsmith:section");
const multimatch = require("multimatch");
/* eslint-disable id-length */
// Expose `plugin`.
module.exports = plugin;
/**
* Metalsmith plugin to section html into named chunks
*
* @param {Object} opts - Options to pass to the plugin.
* @param {string} opts.pattern - The pattern used to match to the file paths.
* @param {string} opts.prefix - The token to split the html into sections by.
* @param {boolean} opts.removeFromContents - Whether or not to remove sections from the content metaData.
* @param {string} opts.metaDataKey - What property to store result in the metadata.
* @return {function} The plugin function
*/
function plugin(opts)
{
opts = opts || {};
opts.pattern = opts.pattern || ["**/*.html"];
opts.prefix = opts.prefix || "section:::";
opts.removeFromContents = opts.removeFromContents || true;
opts.metaDataKey = opts.metaDataKey || "sections"
debug("myplugin options: %s", JSON.stringify(opts));
return function parse(files, metalsmith, done)
{
setImmediate(done);
Object.keys(files).forEach((file) =>
{
if (multimatch(file, opts.pattern).length)
{
const data = files[file];
debug("converting file: %s", file, opts.prefix);
const re = new RegExp(`<.*>${opts.prefix}`,"g");
const dataString = data.contents.toString()
const strings = dataString.split(re);
if (strings.length <= 1) return
data[opts.metaDataKey] = {}
if (opts.removeFromContents)
{
debug("remaining content:",strings[0])
files[file].contents = Buffer.from(strings[0])
}
for (let i = 1; i + 1 <= strings.length; i += 1)
{
const string = strings[i]
const name = string.match(/^(.*?)<\/.*>/)[1].trim()
const section = string.replace(/^(.*?)<\/.*>/,"").trim()
// if we already have something for that key
if (data[opts.metaDataKey][name])
{
const currentValue = data[opts.metaDataKey][name]
// if its a string, stick it in an array
if (typeof currentValue === "string")
{
data[opts.metaDataKey][name] = [
currentValue,
section
]
}
// if its an array append the new value
else if (Array.isArray(currentValue))
{
data[opts.metaDataKey][name].push(section)
}
}
// if this is new
else
{
data[opts.metaDataKey][name] = section;
}
debug(name, section)
}
}
});
};
}