-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathsearch.dart
477 lines (398 loc) · 12.9 KB
/
search.dart
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert';
import 'dart:html';
import 'dart:js_util' as js_util;
void init() {
final document = window.document;
var searchBox = document.getElementById('search-box') as InputElement?;
var searchBody = document.getElementById('search-body') as InputElement?;
var searchSidebar =
document.getElementById('search-sidebar') as InputElement?;
void disableSearch() {
print('Could not activate search functionality.');
searchBox?.placeholder = 'Failed to initialize search';
searchBody?.placeholder = 'Failed to initialize search';
searchSidebar?.placeholder = 'Failed to initialize search';
}
var body = document.querySelector('body')!;
// If dartdoc did not add a base-href tag, we will need to add the relative
// path ourselves.
var htmlBase = '';
if (body.attributes['data-using-base-href'] == 'false') {
// Dartdoc stores the htmlBase in 'body[data-base-href]'.
htmlBase = body.attributes['data-base-href'] ?? '';
}
window.fetch('${htmlBase}index.json').then((response) async {
int code = js_util.getProperty(response, 'status');
if (code == 404) {
disableSearch();
return;
}
var textPromise = js_util.callMethod<Object>(response, 'text', []);
var text = await promiseToFuture<String>(textPromise);
var jsonIndex = (jsonDecode(text) as List).cast<Map<String, dynamic>>();
final index = jsonIndex.map((entry) => IndexItem.fromMap(entry)).toList();
// Initialize all three search fields.
if (searchBox != null) {
initializeSearch(searchBox, index, htmlBase);
}
if (searchBody != null) {
initializeSearch(searchBody, index, htmlBase);
}
if (searchSidebar != null) {
initializeSearch(searchSidebar, index, htmlBase);
}
});
}
const weights = {
'library': 2,
'class': 2,
'mixin': 3,
'extension': 3,
'typedef': 3,
'method': 4,
'accessor': 4,
'operator': 4,
'constant': 4,
'property': 4,
'constructor': 4,
};
List<IndexItem> findMatches(List<IndexItem> index, String query) {
if (query.isEmpty) {
return [];
}
var allMatches = <SearchMatch>[];
for (var element in index) {
void score(int value) {
value -= (element.overriddenDepth ?? 0) * 10;
var weightFactor = weights[element.type] ?? 4;
allMatches.add(SearchMatch(element, value / weightFactor));
}
var name = element.name;
var qualifiedName = element.qualifiedName;
var lowerName = name.toLowerCase();
var lowerQualifiedName = qualifiedName.toLowerCase();
var lowerQuery = query.toLowerCase();
if (name == query || qualifiedName == query || name == 'dart:$query') {
score(2000);
} else if (lowerName == 'dart:$lowerQuery') {
score(1800);
} else if (lowerName == lowerQuery || lowerQualifiedName == lowerQuery) {
score(1700);
} else if (query.length > 1) {
if (name.startsWith(query) || qualifiedName.startsWith(query)) {
score(750);
} else if (lowerName.startsWith(lowerQuery) ||
lowerQualifiedName.startsWith(lowerQuery)) {
score(650);
} else if (name.contains(query) || qualifiedName.contains(query)) {
score(500);
} else if (lowerName.contains(lowerQuery) ||
lowerQualifiedName.contains(query)) {
score(400);
}
}
}
allMatches.sort((SearchMatch a, SearchMatch b) {
var x = (b.score - a.score).round();
if (x == 0) {
return a.element.name.length - b.element.name.length;
}
return x;
});
return allMatches.map((match) => match.element).toList();
}
const minLength = 1;
const suggestionLimit = 10;
void initializeSearch(
InputElement input,
List<IndexItem> index,
String htmlBase,
) {
input.disabled = false;
input.setAttribute('placeholder', 'Search API Docs');
// Handle grabbing focus when the users types / outside of the input
document.addEventListener('keypress', (Event event) {
if (event is! KeyEvent) {
return;
}
if (event.code == 'Slash' && document.activeElement is! InputElement) {
event.preventDefault();
input.focus();
}
});
// Prepare elements
var wrapper = document.createElement('div');
wrapper.classes.add('tt-wrapper');
input.replaceWith(wrapper);
var inputHint = document.createElement('input') as InputElement;
inputHint.setAttribute('type', 'text');
inputHint.setAttribute('autocomplete', 'off');
inputHint.setAttribute('readonly', 'true');
inputHint.setAttribute('spellcheck', 'false');
inputHint.setAttribute('tabindex', '-1');
inputHint.classes
..add('typeahead')
..add('tt-hint');
wrapper.append(inputHint);
input.setAttribute('autocomplete', 'off');
input.setAttribute('spellcheck', 'false');
input.classes.add('tt-input');
wrapper.append(input);
var listBox = document.createElement('div');
listBox.setAttribute('role', 'listbox');
listBox.setAttribute('aria-expanded', 'false');
listBox.style.display = 'none';
listBox.classes.add('tt-menu');
var presentation = document.createElement('div');
presentation.classes.add('tt-elements');
listBox.append(presentation);
wrapper.append(listBox);
// Set up various search functionality.
String highlight(String text, String query) {
final sanitizedText = const HtmlEscape().convert(query);
return text.replaceAll(
query, "<strong class='tt-highlight'>$sanitizedText</strong>");
}
Element createSuggestion(String query, IndexItem match) {
var suggestion = document.createElement('div');
suggestion.setAttribute('data-href', match.href ?? '');
suggestion.classes.add('tt-suggestion');
var suggestionTitle = document.createElement('span');
suggestionTitle.classes.add('tt-suggestion-title');
suggestionTitle.innerHtml =
highlight('${match.name} ${match.type.toLowerCase()}', query);
suggestion.append(suggestionTitle);
if (match.enclosedBy != null) {
var fromLib = document.createElement('div');
fromLib.classes.add('search-from-lib');
fromLib.innerHtml = 'from ${highlight(match.enclosedBy!.name, query)}';
suggestion.append(fromLib);
}
suggestion.addEventListener('mousedown', (event) {
event.preventDefault();
});
suggestion.addEventListener('click', (event) {
if (match.href != null) {
window.location.assign('$htmlBase${match.href}');
event.preventDefault();
}
});
return suggestion;
}
String? storedValue;
var actualValue = '';
String? hint;
var suggestionElements = <Element>[];
var suggestionsInfo = <IndexItem>[];
int? selectedElement;
void setHint(String? value) {
hint = value;
inputHint.value = value ?? '';
}
void showSuggestions() {
if (presentation.hasChildNodes()) {
listBox.style.display = 'block';
listBox.setAttribute('aria-expanded', 'true');
}
}
void hideSuggestions() {
listBox.style.display = 'none';
listBox.setAttribute('aria-expanded', 'false');
}
void updateSuggestions(String query, List<IndexItem> suggestions) {
suggestionsInfo = [];
suggestionElements = [];
presentation.text = '';
if (suggestions.length < minLength) {
setHint(null);
hideSuggestions();
return;
}
for (final suggestion in suggestions) {
var element = createSuggestion(query, suggestion);
suggestionElements.add(element);
presentation.append(element);
}
suggestionsInfo = suggestions;
setHint(query + suggestions[0].name.substring(query.length));
selectedElement = null;
showSuggestions();
}
void handle(String? newValue, [bool forceUpdate = false]) {
if (actualValue == newValue && !forceUpdate) {
return;
}
if (newValue == null || newValue.isEmpty) {
updateSuggestions('', []);
return;
}
var suggestions = findMatches(index, newValue);
if (suggestions.length > suggestionLimit) {
suggestions = suggestions.sublist(0, suggestionLimit);
}
actualValue = newValue;
updateSuggestions(newValue, suggestions);
}
// Hook up events
input.addEventListener('focus', (Event event) {
handle(input.value, true);
});
input.addEventListener('blur', (Event event) {
selectedElement = null;
if (storedValue != null) {
input.value = storedValue;
storedValue = null;
}
hideSuggestions();
setHint(null);
});
input.addEventListener('input', (event) {
handle(input.value);
});
input.addEventListener('keydown', (Event event) {
if (suggestionElements.isEmpty) {
return;
}
if (event is! KeyEvent) {
return;
}
if (event.code == 'Enter') {
var selectingElement = selectedElement ?? 0;
var href = suggestionElements[selectingElement].dataset['href'];
if (href != null) {
window.location.assign('$htmlBase$href');
}
return;
}
if (event.code == 'Tab') {
if (selectedElement == null) {
// The user wants to fill the field with the hint
if (hint != null) {
input.value = hint;
handle(hint);
event.preventDefault();
}
} else {
// The user wants to fill the input field with their currently selected suggestion
handle(suggestionsInfo[selectedElement!].name);
storedValue = null;
selectedElement = null;
event.preventDefault();
}
return;
}
var lastIndex = suggestionElements.length - 1;
var previousSelectedElement = selectedElement;
if (event.code == 'ArrowUp') {
if (selectedElement == null) {
selectedElement = lastIndex;
} else if (selectedElement == 0) {
selectedElement = null;
} else {
selectedElement = (selectedElement! - 1);
}
} else if (event.code == 'ArrowDown') {
if (selectedElement == null) {
selectedElement = 0;
} else if (selectedElement == lastIndex) {
selectedElement = null;
} else {
selectedElement = (selectedElement! + 1);
}
} else {
if (storedValue != null) {
storedValue = null;
handle(input.value);
}
return;
}
if (previousSelectedElement != null) {
suggestionElements[previousSelectedElement].classes.remove('tt-cursor');
}
if (selectedElement != null) {
var selected = suggestionElements[selectedElement!];
selected.classes.add('tt-cursor');
// Guarantee the selected element is visible
if (selectedElement == 0) {
listBox.scrollTop = 0;
} else if (selectedElement == lastIndex) {
listBox.scrollTop = listBox.scrollHeight;
} else {
var offsetTop = selected.offsetTop;
var parentOffsetHeight = listBox.offsetHeight;
if (offsetTop < parentOffsetHeight ||
parentOffsetHeight < (offsetTop + selected.offsetHeight)) {
selected.scrollIntoView();
}
}
// Store the actual input value to display their currently selected item.
storedValue ??= input.value;
input.value = suggestionsInfo[selectedElement!].name;
setHint('');
} else if (storedValue != null && previousSelectedElement != null) {
// They are moving back to the input field, so return the stored value.
input.value = storedValue;
setHint(storedValue! +
suggestionsInfo[0].name.substring(storedValue!.length));
storedValue = null;
}
event.preventDefault();
});
}
class SearchMatch {
final IndexItem element;
final double score;
SearchMatch(this.element, this.score);
}
class IndexItem {
final String name;
final String qualifiedName;
final String type;
final String? href;
final int? overriddenDepth;
final EnclosedBy? enclosedBy;
IndexItem._({
required this.name,
required this.qualifiedName,
required this.type,
this.href,
this.overriddenDepth,
this.enclosedBy,
});
// "name":"dartdoc",
// "qualifiedName":"dartdoc",
// "href":"dartdoc/dartdoc-library.html",
// "type":"library",
// "overriddenDepth":0,
// "packageName":"dartdoc"
// ["enclosedBy":{"name":"Accessor","type":"class"}]
factory IndexItem.fromMap(Map<String, dynamic> data) {
// Note that this map also contains 'packageName', but we're not currently
// using that info.
EnclosedBy? enclosedBy;
if (data['enclosedBy'] != null) {
final map = data['enclosedBy'] as Map<String, dynamic>;
enclosedBy = EnclosedBy._(name: map['name'], type: map['type']);
}
return IndexItem._(
name: data['name'],
qualifiedName: data['qualifiedName'],
href: data['href'],
type: data['type'],
overriddenDepth: data['overriddenDepth'],
enclosedBy: enclosedBy,
);
}
}
class EnclosedBy {
final String name;
final String type;
// ["enclosedBy":{"name":"Accessor","type":"class"}]
EnclosedBy._({
required this.name,
required this.type,
});
}