forked from framework7io/framework7-website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate-search-index.js
88 lines (80 loc) · 2.4 KB
/
generate-search-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
const jsdom = require('jsdom').jsdom;
const jQuery = require('jquery');
const fs = require('fs');
const files = fs.readdirSync('./docs/');
const searchData = [];
function generateTitleHash(title) {
return title.trim()
.replace(/\ /g, '-')
.replace(/\//g, '-')
.replace(/"/g, '')
.replace(/'/g, '-')
.replace(/:/g, '')
.replace(/,/g, '')
.replace(/\./g, '')
.replace(/\+/g, '')
.replace(/---/g, '-')
.replace(/--/g, '-')
.toLowerCase().replace(/\-&-/g,'-');
}
function addSection(section) {
if (section.text) {
section.text = section.text.map((el) => {
return el
.replace(/([ ]{2,})/g, ' ')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/([\n ]{2,})/g, '\n')
.replace(/([\n]{2,})/g, '\n');
}).join('\n').replace(/([\n ]{2,})/g, '\n');
}
searchData.push(section);
}
files.forEach((file) => {
if (file.indexOf('.') === 0) return;
const content = fs.readFileSync(`./docs/${file}`, 'utf8');
const document = jsdom(content, {});
const window = document.defaultView;
const $ = jQuery(window);
const $docsContent = $('.docs-content');
$docsContent.find('pre code.html, pre code.css').parent('pre').remove();
const docs = 'Framework7 API';
const page = $docsContent.find('h1').text();
const url = `/docs/${file}`;
let section;
const $nextAll = $docsContent.find('h1').nextAll();
for (let i = 0; i < $nextAll.length; i += 1) {
const $el = $nextAll.eq(i);
if ($el.is('pre')) continue;
if ($el.hasClass('with-device')) continue;
if ($el.is('h2')) {
if (section) addSection(section);
section = {
docs,
page,
};
section.section = $el.text().trim();
section.pageUrl = url;
section.sectionUrl = `${url}#${generateTitleHash(section.section)}`
} else if (section) {
if (!section.text) section.text = [];
let text = '';
if ($el.is('h3')) {
text += `${$el.text().trim()}`;
}
if ($el.is('table')) {
text += $.makeArray($el.find('tr'))
.map((row) => {
return $.makeArray($(row).find('td')).map(cell => $(cell).text().trim()).join(' | ')
})
.join('\n')
}
else text += $el.text().trim();
section.text.push(text);
}
}
if (section) {
addSection(section);
}
});
fs.writeFileSync('./search-index.json', JSON.stringify(searchData, null, 2))