forked from dart-lang/dart-pad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search_controller.dart
465 lines (423 loc) · 15.7 KB
/
search_controller.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
import 'dart:async';
import 'dart:html';
import 'package:mdc_web/mdc_web.dart';
import '../dart_pad.dart';
import '../editing/editor.dart';
import '../elements/analysis_results_controller.dart';
import '../elements/button.dart';
import '../elements/elements.dart';
class SearchController {
final EditorFactory editorFactory;
final Editor editor;
final MDCSnackbar snackbar;
/// The find/replace dialog box
final DElement _searchDialog =
DElement(querySelector('#search-dialog') as DivElement);
final List<String> searchHistory = [];
final List<String> replaceHistory = [];
static const int keyCodeUp = 38;
static const int keyCodeDown = 40;
static const int keyCodeEnter = 13;
static const int keyCodeEscape = 27;
SearchController(this.editorFactory, this.editor, this.snackbar) {
initUi();
initKeyBindings();
hide();
editorFactory
.registerSearchUpdateCallback(editorUpdatedSearchAnnotationsCallback);
}
void initKeyBindings() {
keys.bind(['ctrl-f', 'macctrl-f'], () {
userOpenFindDialogHotkey();
}, 'Find');
keys.bind(['ctrl-h', 'macctrl-h'], () {
userOpenReplaceDialogHotkey();
}, 'Replace');
keys.bind(['f4', 'ctrl-g', 'macctrl-g'], () {
userFindNextHotkey();
}, 'Find Next');
keys.bind(['shift-f4', 'shift-ctrl-g', 'shift-macctrl-g'], () {
userFindPreviousHotkey();
}, 'Find Previous');
}
void editorUpdatedSearchAnnotationsCallback() {
final Map<String, dynamic> res =
editor.getMatchesFromSearchQueryUpdatedCallback();
final int total = res['total'] as int;
final int curMatchNum = res['curMatchNum'] as int;
updateSearchResults(curMatchNum: curMatchNum, total: total);
}
void updateSearchResults({int curMatchNum = -1, int total = 0}) {
if (total == 0) {
searchResultsSpan.innerText = 'No results';
if (findText.isNotEmpty) {
searchResultsSpan.classes.add('no-results');
} else {
searchResultsSpan.classes
.remove('no-results'); // leave it white when empty search
}
} else {
final String resultMsg =
'${(curMatchNum >= 0 ? (curMatchNum + 1).toString() : "?")} of $total';
searchResultsSpan.innerText = resultMsg;
searchResultsSpan.classes.remove('no-results');
}
}
DElement get searchDialogDiv => _searchDialog;
bool get hidden => !_searchDialog.hasClass('revealed');
void hide() {
_searchDialog.toggleClass('revealed', false);
clearSearch();
}
void show() {
_searchDialog.clearAttr('hidden');
_searchDialog.toggleClass('revealed', true);
//this should be happening anyway (from filling find input) executeFind();
if (findText.isEmpty) {
findPreviousButton.disabled = findNextButton.disabled =
replaceAndFindNextButton.disabled = replaceAllButton.disabled = true;
} else {
findPreviousButton.disabled = findNextButton.disabled =
replaceAndFindNextButton.disabled = replaceAllButton.disabled = false;
}
}
final DivElement replaceRowDiv = querySelector('#replace-row') as DivElement;
final InputElement findTextInput =
querySelector('#find-text')! as InputElement;
final InputElement replaceTextInput =
querySelector('#replace-text')! as InputElement;
final ButtonElement findMatchCaseButton =
querySelector('#find-match-case') as ButtonElement;
final ButtonElement findWholeWordButton =
querySelector('#find-wholeword') as ButtonElement;
final ButtonElement findRegExButton =
querySelector('#find-regex') as ButtonElement;
final SpanElement searchResultsSpan =
querySelector('#search-results') as SpanElement;
final MDCButton replaceAndFindNextButton =
MDCButton(querySelector('#replace-once') as ButtonElement, isIcon: true);
final MDCButton replaceAllButton =
MDCButton(querySelector('#replace-all') as ButtonElement, isIcon: true);
final ButtonElement ourOpenReplaceIcon =
querySelector('#open-replace') as ButtonElement;
final MDCButton openReplaceButton =
MDCButton(querySelector('#open-replace') as ButtonElement, isIcon: true);
final MDCButton findPreviousButton =
MDCButton(querySelector('#find-previous') as ButtonElement, isIcon: true);
final MDCButton findNextButton =
MDCButton(querySelector('#find-next') as ButtonElement, isIcon: true);
final MDCButton findCloseButton =
MDCButton(querySelector('#find-close') as ButtonElement, isIcon: true);
bool get matchCase =>
findMatchCaseButton.getAttribute('aria-pressed') == 'true';
bool get wholeWord =>
findWholeWordButton.getAttribute('aria-pressed') == 'true';
bool get regExMatch => findRegExButton.getAttribute('aria-pressed') == 'true';
String get findText => findTextInput.value ?? '';
String get replaceText => replaceTextInput.value ?? '';
void initUi() {
findNextButton.onClick.listen((_) => userFindNextHotkey());
findPreviousButton.onClick.listen((_) => userFindPreviousHotkey());
findCloseButton.onClick.listen((_) => hide());
replaceAndFindNextButton.onClick
.listen((_) => userReplaceAndFindNextHotkey());
replaceAllButton.onClick.listen((_) => userReplaceAllHotkey());
// For each find search option we toggle it when pressed and update search highlights
findMatchCaseButton.onClick.listen((_) {
final String stateBeforeToggle =
findMatchCaseButton.getAttribute('aria-pressed') ?? 'false';
findMatchCaseButton.setAttribute(
'aria-pressed', (stateBeforeToggle == 'false') ? 'true' : 'false');
executeFind(highlightOnly: true);
});
findWholeWordButton.onClick.listen((_) {
final String stateBeforeToggle =
findWholeWordButton.getAttribute('aria-pressed') ?? 'false';
findWholeWordButton.setAttribute(
'aria-pressed', (stateBeforeToggle == 'false') ? 'true' : 'false');
executeFind(highlightOnly: true);
});
findRegExButton.onClick.listen((_) {
final String stateBeforeToggle =
findRegExButton.getAttribute('aria-pressed') ?? 'false';
findRegExButton.setAttribute(
'aria-pressed', (stateBeforeToggle == 'false') ? 'true' : 'false');
executeFind(highlightOnly: true);
});
openReplaceButton.onClick.listen((_) {
if (replaceRowDiv.style.display == 'none') {
openReplace();
} else {
closeReplace();
}
});
// we put this on change and input to catch edge cases
findTextInput.onChange.listen((event) {
if (findText.isEmpty) {
findPreviousButton.disabled = findNextButton.disabled =
replaceAndFindNextButton.disabled =
replaceAllButton.disabled = true;
} else {
findPreviousButton.disabled = findNextButton.disabled =
replaceAndFindNextButton.disabled =
replaceAllButton.disabled = false;
}
});
// update highlighted matches as user types
findTextInput.onInput.listen((event) {
if (findText.isEmpty) {
findPreviousButton.disabled = findNextButton.disabled =
replaceAndFindNextButton.disabled =
replaceAllButton.disabled = true;
clearSearch();
updateSearchResults();
} else {
findPreviousButton.disabled = findNextButton.disabled =
replaceAndFindNextButton.disabled =
replaceAllButton.disabled = false;
}
executeFind(highlightOnly: true);
});
// focus/blur behavior of find/replace inputs, change prompts when empty
findTextInput.onFocus.listen((_) {
findTextInput.setAttribute(
'placeholder', 'Find (\u2191\u2193 for history)');
});
findTextInput.onBlur.listen((_) {
if (findText.isEmpty) {
findTextInput.setAttribute('placeholder', 'Find');
}
});
replaceTextInput.onFocus.listen((_) {
replaceTextInput.setAttribute(
'placeholder', 'Replace (\u2191\u2193 for history)');
});
replaceTextInput.onBlur.listen((_) {
final String current = replaceText;
if (current.isEmpty) {
replaceTextInput.setAttribute('placeholder', 'Replace');
}
});
// handle Arrow keys (history navigation) and
// (we must preventDefault for arrow keys also)
// Enter presses (Find next shortcut) in Find/Replace inputs
// ESC closes dialog, we can only trap it on our inputs since
// editor needs it for vim..
findTextInput.onKeyDown.listen((event) {
final int keyCode = event.keyCode;
if (keyCode == keyCodeUp || keyCode == keyCodeDown) {
arrowKeysNavigateFindTextHistory(keyCode);
event
.preventDefault(); // so arrow keys don't mess with cursor in input element
} else if (keyCode == keyCodeEnter) {
userFindNextHotkey();
} else if (keyCode == keyCodeEscape) {
hide();
}
});
replaceTextInput.onKeyDown.listen((event) {
final int keyCode = event.keyCode;
if (keyCode == keyCodeUp || keyCode == keyCodeDown) {
arrowKeysNavigateReplaceTextHistory(keyCode);
event
.preventDefault(); // so arrow keys don't mess with cursor in input element
} else if (keyCode == keyCodeEnter) {
userReplaceAndFindNextHotkey();
} else if (keyCode == keyCodeEscape) {
hide();
}
});
}
void addFindTextToSearchHistory() {
if (findText.isNotEmpty && !searchHistory.contains(findText)) {
searchHistory.add(findText);
}
}
void addReplaceTextToReplaceHistory() {
if (replaceText.isNotEmpty && !replaceHistory.contains(replaceText)) {
replaceHistory.add(replaceText);
}
}
void arrowKeysNavigateFindTextHistory(int keyCode) {
if (keyCode == keyCodeUp || keyCode == keyCodeDown) {
// first figure out where we are in the history
if (!searchHistory.contains(findText)) {
addFindTextToSearchHistory();
}
int searchHistoryPos = searchHistory.indexOf(findText);
if (keyCode == keyCodeUp) {
searchHistoryPos--;
} else {
searchHistoryPos++;
}
if (searchHistoryPos < 0) {
searchHistoryPos = 0;
} else if (searchHistoryPos >= searchHistory.length) {
searchHistoryPos = searchHistory.length - 1;
}
setFindAndCursorAtEnd(searchHistory[searchHistoryPos]);
}
}
void arrowKeysNavigateReplaceTextHistory(int keyCode) {
if (keyCode == keyCodeUp || keyCode == keyCodeDown) {
// first figure out where we are in the history
if (!replaceHistory.contains(replaceText)) {
addReplaceTextToReplaceHistory();
}
int replaceHistoryPos = replaceHistory.indexOf(replaceText);
if (keyCode == keyCodeUp) {
replaceHistoryPos--;
} else {
replaceHistoryPos++;
}
if (replaceHistoryPos < 0) {
replaceHistoryPos = 0;
} else if (replaceHistoryPos >= replaceHistory.length) {
replaceHistoryPos = replaceHistory.length - 1;
}
setReplaceAndCursorAtEnd(replaceHistory[replaceHistoryPos]);
}
}
bool get somethingSelected {
return editor.document.somethingSelected;
}
String? get selectedText {
if (!somethingSelected) return null;
return editor.document.selection;
}
void userOpenFindDialogHotkey() {
if (!somethingSelected) {
// for FIND, if there is nothing selected, try and grab
// the token we are on (or near) and use that
setFindSelectAllFocus(
findStr: editor.getTokenWeAreOnOrNear(), forceExecuteFind: true);
} else {
setFindSelectAllFocus(findStr: selectedText, forceExecuteFind: true);
}
if (hidden) {
// dialog currently hidden, so bring it up in FIND mode (hide replace)
closeReplace();
show();
}
}
void userOpenReplaceDialogHotkey() {
if (somethingSelected) {
// something selected, we put it in the find and select the replace text
setFindAndCursorAtEnd(selectedText, forceExecuteFind: true);
addFindTextToSearchHistory();
replaceSelectAllFocus();
} else {
// nothing selected, so just select all the find text and focus
// (replace hotkey does no token finding)
setFindSelectAllFocus(forceExecuteFind: true);
}
openReplace();
if (hidden) {
show();
}
}
void userFindNextHotkey() {
if (findText.isNotEmpty) {
executeFind(highlightOnly: false);
addFindTextToSearchHistory();
}
}
void userFindPreviousHotkey() {
if (findText.isNotEmpty) {
executeFind(reverse: true, highlightOnly: false);
addFindTextToSearchHistory();
}
}
void userReplaceAndFindNextHotkey() {
// what happens depends on whats selected..
if (somethingSelected && selectedText == findText) {
// matches find text, so execute replace
executeReplace();
addReplaceTextToReplaceHistory();
}
userFindNextHotkey();
}
void userReplaceAllHotkey() {
executeReplace(replaceAll: true);
addReplaceTextToReplaceHistory();
executeFind(highlightOnly: true);
}
void setFindSelectAllFocus({String? findStr, bool forceExecuteFind = false}) {
if (forceExecuteFind || findStr != null && findStr.isNotEmpty) {
if (forceExecuteFind || findStr != findTextInput.value) {
findTextInput.value = findStr ?? findTextInput.value;
executeFind(highlightOnly: true);
}
addFindTextToSearchHistory();
}
// queue up a second attempt at select all because sometimes browser flakes on first
// (this sometimes happens on the first time the search dialog is opened)
Timer(Duration(milliseconds: 20), () {
findTextInput.focus();
findTextInput.select();
});
findTextInput.focus();
findTextInput.select();
}
void setFindAndCursorAtEnd(String? newFindText,
{bool forceExecuteFind = false}) {
if (forceExecuteFind || newFindText != null) {
if (forceExecuteFind || newFindText != findTextInput.value) {
findTextInput.value = newFindText ?? findTextInput.value;
executeFind(highlightOnly: true);
}
}
findTextInput.setSelectionRange(9999, 9999);
}
void replaceSelectAllFocus() {
replaceTextInput.focus();
replaceTextInput.select();
}
void setReplaceAndCursorAtEnd(String? newReplaceText) {
if (newReplaceText != null) replaceTextInput.value = newReplaceText;
replaceTextInput.setSelectionRange(9999, 9999);
}
void closeReplace() {
if (replaceRowDiv.style.display != 'none') {
replaceRowDiv.style.display = 'none';
ourOpenReplaceIcon.innerText = 'chevron_right';
}
}
void openReplace() {
if (replaceRowDiv.style.display != 'flex') {
replaceRowDiv.style.display = 'flex';
ourOpenReplaceIcon.innerText = 'expand_more';
}
}
void executeFind({bool reverse = false, bool highlightOnly = true}) {
final String query = findTextInput.value ?? '';
if (query != '') {
final Map<String, dynamic> res = editor.startSearch(
query, reverse, highlightOnly, matchCase, wholeWord, regExMatch);
final int total = res['total'] as int;
final int curMatchNum = res['curMatchNum'] as int;
updateSearchResults(curMatchNum: curMatchNum, total: total);
} else {
clearSearch();
updateSearchResults();
}
}
/// There is currently selected text that matches the findText, so execute
/// a replacement of that text with the replaceText
void executeReplace({bool replaceAll = false}) {
if (replaceAll) {
editor.searchAndReplace(
findText, replaceText, replaceAll, matchCase, wholeWord, regExMatch);
executeFind(highlightOnly: true);
} else {
editor.document.replaceSelection(replaceText, 'around');
}
}
/// Clears the search query so that there is no active search or highlighting
void clearSearch() {
editor.clearActiveSearch();
}
void showSnackbar(String message) {
snackbar.showMessage(message);
}
}