-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
search.js
333 lines (279 loc) · 8.44 KB
/
search.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import {
getAndRemoveConfig,
getAndRemoveDocsifyIgnoreConfig,
} from '../../core/render/utils.js';
import { markdownToTxt } from './markdown-to-txt.js';
import Dexie from 'dexie';
let INDEXES = {};
const db = new Dexie('docsify');
db.version(1).stores({
search: 'slug, title, body, path, indexKey',
expires: 'key, value',
});
async function saveData(maxAge, expireKey) {
INDEXES = Object.values(INDEXES).flatMap(innerData =>
Object.values(innerData),
);
await db.search.bulkPut(INDEXES);
await db.expires.put({ key: expireKey, value: Date.now() + maxAge });
}
async function getData(key, isExpireKey = false) {
if (isExpireKey) {
const item = await db.expires.get(key);
return item ? item.value : 0;
}
const item = await db.search.where({ indexKey: key }).toArray();
return item ? item : null;
}
const LOCAL_STORAGE = {
EXPIRE_KEY: 'docsify.search.expires',
INDEX_KEY: 'docsify.search.index',
};
function resolveExpireKey(namespace) {
return namespace
? `${LOCAL_STORAGE.EXPIRE_KEY}/${namespace}`
: LOCAL_STORAGE.EXPIRE_KEY;
}
function resolveIndexKey(namespace) {
return namespace
? `${LOCAL_STORAGE.INDEX_KEY}/${namespace}`
: LOCAL_STORAGE.INDEX_KEY;
}
function escapeHtml(string) {
const entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
};
return String(string).replace(/[&<>"']/g, s => entityMap[s]);
}
function getAllPaths(router) {
const paths = [];
Docsify.dom
.findAll('.sidebar-nav a:not(.section-link):not([data-nosearch])')
.forEach(node => {
const href = node.href;
const originHref = node.getAttribute('href');
const path = router.parse(href).path;
if (
path &&
paths.indexOf(path) === -1 &&
!Docsify.util.isAbsolutePath(originHref)
) {
paths.push(path);
}
});
return paths;
}
function getTableData(token) {
if (!token.text && token.type === 'table') {
token.rows.unshift(token.header);
token.text = token.rows
.map(columns => columns.map(r => r.text).join(' | '))
.join(' |\n ');
}
return token.text;
}
function getListData(token) {
if (!token.text && token.type === 'list') {
token.text = token.raw;
}
return token.text;
}
export function genIndex(path, content = '', router, depth, indexKey) {
const tokens = window.marked.lexer(content);
const slugify = window.Docsify.slugify;
const index = {};
let slug;
let title = '';
tokens.forEach((token, tokenIndex) => {
if (token.type === 'heading' && token.depth <= depth) {
const { str, config } = getAndRemoveConfig(token.text);
const text = getAndRemoveDocsifyIgnoreConfig(token.text).content;
if (config.id) {
slug = router.toURL(path, { id: slugify(config.id) });
} else {
slug = router.toURL(path, { id: slugify(escapeHtml(text)) });
}
if (str) {
title = getAndRemoveDocsifyIgnoreConfig(str).content;
}
index[slug] = {
slug,
title: title,
body: '',
path: path,
indexKey: indexKey,
};
} else {
if (tokenIndex === 0) {
slug = router.toURL(path);
index[slug] = {
slug,
title: path !== '/' ? path.slice(1) : 'Home Page',
body: markdownToTxt(token.text || ''),
path: path,
indexKey: indexKey,
};
}
if (!slug) {
return;
}
if (!index[slug]) {
index[slug] = { slug, title: '', body: '' };
} else if (index[slug].body) {
token.text = getTableData(token);
token.text = getListData(token);
index[slug].body += '\n' + markdownToTxt(token.text || '');
} else {
token.text = getTableData(token);
token.text = getListData(token);
index[slug].body = markdownToTxt(token.text || '');
}
index[slug].path = path;
index[slug].indexKey = indexKey;
}
});
slugify.clear();
return index;
}
export function ignoreDiacriticalMarks(keyword) {
if (keyword && keyword.normalize) {
return keyword.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
}
return keyword;
}
/**
* @param {String} query Search query
* @returns {Array} Array of results
*/
export function search(query) {
const matchingResults = [];
query = query.trim();
let keywords = query.split(/[\s\-,\\/]+/);
if (keywords.length !== 1) {
keywords = [query, ...keywords];
}
for (const post of INDEXES) {
let matchesScore = 0;
let resultStr = '';
let handlePostTitle = '';
let handlePostContent = '';
const postTitle = post.title && post.title.trim();
const postContent = post.body && post.body.trim();
const postUrl = post.slug || '';
if (postTitle) {
keywords.forEach(keyword => {
// From https://github.com/sindresorhus/escape-string-regexp
const regEx = new RegExp(
escapeHtml(ignoreDiacriticalMarks(keyword)).replace(
/[|\\{}()[\]^$+*?.]/g,
'\\$&',
),
'gi',
);
let indexTitle = -1;
let indexContent = -1;
handlePostTitle = postTitle
? escapeHtml(ignoreDiacriticalMarks(postTitle))
: postTitle;
handlePostContent = postContent
? escapeHtml(ignoreDiacriticalMarks(postContent))
: postContent;
indexTitle = postTitle ? handlePostTitle.search(regEx) : -1;
indexContent = postContent ? handlePostContent.search(regEx) : -1;
if (indexTitle >= 0 || indexContent >= 0) {
matchesScore += indexTitle >= 0 ? 3 : indexContent >= 0 ? 2 : 0;
if (indexContent < 0) {
indexContent = 0;
}
let start = 0;
let end = 0;
start = indexContent < 11 ? 0 : indexContent - 10;
end = start === 0 ? 100 : indexContent + keyword.length + 90;
if (handlePostContent && end > handlePostContent.length) {
end = handlePostContent.length;
}
const matchContent =
handlePostContent &&
handlePostContent
.substring(start, end)
.replace(regEx, word => /* html */ `<mark>${word}</mark>`);
resultStr += matchContent;
}
});
if (matchesScore > 0) {
const matchingPost = {
title: handlePostTitle,
content: postContent ? resultStr : '',
url: postUrl,
score: matchesScore,
};
matchingResults.push(matchingPost);
}
}
}
return matchingResults.sort((r1, r2) => r2.score - r1.score);
}
export async function init(config, vm) {
const isAuto = config.paths === 'auto';
const paths = isAuto ? getAllPaths(vm.router) : config.paths;
let namespaceSuffix = '';
// only in auto mode
if (paths.length && isAuto && config.pathNamespaces) {
const path = paths[0];
if (Array.isArray(config.pathNamespaces)) {
namespaceSuffix =
config.pathNamespaces.filter(
prefix => path.slice(0, prefix.length) === prefix,
)[0] || namespaceSuffix;
} else if (config.pathNamespaces instanceof RegExp) {
const matches = path.match(config.pathNamespaces);
if (matches) {
namespaceSuffix = matches[0];
}
}
const isExistHome = paths.indexOf(namespaceSuffix + '/') === -1;
const isExistReadme = paths.indexOf(namespaceSuffix + '/README') === -1;
if (isExistHome && isExistReadme) {
paths.unshift(namespaceSuffix + '/');
}
} else if (paths.indexOf('/') === -1 && paths.indexOf('/README') === -1) {
paths.unshift('/');
}
const expireKey = resolveExpireKey(config.namespace) + namespaceSuffix;
const indexKey = resolveIndexKey(config.namespace) + namespaceSuffix;
const isExpired = (await getData(expireKey, true)) < Date.now();
INDEXES = await getData(indexKey);
if (isExpired) {
INDEXES = {};
} else if (!isAuto) {
return;
}
const len = paths.length;
let count = 0;
paths.forEach(path => {
const pathExists = Array.isArray(INDEXES)
? INDEXES.some(obj => obj.path === path)
: false;
if (pathExists) {
return count++;
}
Docsify.get(vm.router.getFile(path), false, vm.config.requestHeaders).then(
async result => {
INDEXES[path] = genIndex(
path,
result,
vm.router,
config.depth,
indexKey,
);
if (len === ++count) {
await saveData(config.maxAge, expireKey);
}
},
);
});
}