docs:修复文档搜索功能;显示大写;跳转到对应的 title (#1318)

This commit is contained in:
吴多益 2021-01-04 22:44:24 +08:00 committed by GitHub
parent 8822111f4f
commit c1d91c8ac8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 37 additions and 603 deletions

View File

@ -53,15 +53,41 @@ export default class DocSearch extends React.Component {
let results = [];
for (let doc of this.docs) {
let index = doc.body.indexOf(query);
let bodyTest = new RegExp(query, 'i');
const match = bodyTest.exec(doc.body);
if (index !== -1) {
if (match) {
// title hash
const beforeLines = doc.body
.substring(0, match.index)
.split('\n')
.reverse();
let hash = '';
for (const line of beforeLines) {
if (line.startsWith('##')) {
hash =
'#' +
line
.trim()
.replace(/#/g, '')
.trim()
.toLowerCase()
.replace(/ /g, '-');
break;
}
}
results.push({
title: doc.title,
path: doc.path,
path: doc.path + hash,
abstract: doc.body
.substring(Math.max(0, index - 20), index + 60)
.replace(query, `<strong>${query}</strong>`)
.substring(Math.max(0, match.index - 20), match.index + 60)
.replace(
bodyTest,
`<strong>${doc.body.substring(
match.index,
match.index + query.length
)}</strong>`
)
});
} else if (doc.title.toLowerCase().indexOf(query) !== -1) {
results.push({

File diff suppressed because one or more lines are too long

View File

@ -28,10 +28,11 @@ glob('./docs/**/*.md', {}, function (er, docs) {
body: content
.replace(/<\!---.+-->/g, '')
.replace(/!?\[.*\]\(.*\)/g, '')
.replace(/\n/g, '')
.replace(/```[^`]*```/g, '')
.toLowerCase(),
path: doc.slice(1).replace('.md', '')
.replace(/```[^`]*```/g, ''),
path: doc
.slice(1)
.replace('.md', '')
.replace('/docs/zh-CN/', '/zh-CN/docs/')
});
}
fs.writeFileSync('./examples/docs.json', JSON.stringify(resultData));