-
Notifications
You must be signed in to change notification settings - Fork 2
/
FindWidget.js
639 lines (578 loc) · 27.9 KB
/
FindWidget.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
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
/**
* Find in note replacement for Trilium ctrl+f search
* (c) Antonio Tejada 2022
*
* Features:
* - Find in writeable using ctrl+f and F3
* - Tested on Trilium Desktop 0.50.3
*
* Installation:
* - Create a code note of language JS Frontend with the contents of this file
* - Set the owned attributes (alt-a) to #widget
* - Set the owned attributes of any note you don't want to enable finding to
* #noFindWidget
* - Disable Ctrl+f shorcut in Trilium options
*
* Todo:
* - Refactoring/code cleanup
* - Regexp option
* - Find & Replace
*
* Note that many times some common code is replicated between CodeMirror and
* CKEditor codepaths because the CKEditor update is done inside a callback that
* is deferred so the code cannot be put outside of the callback or it will
* execute too early.
*
* See https://github.com/zadam/trilium/discussions/2806 for discussions
*/
function getNoteAttributeValue(note, attributeType, attributeName, defaultValue) {
let attribute = note.getAttribute(attributeType, attributeName);
let attributeValue = (attribute != null) ? attribute.value : defaultValue;
return attributeValue;
}
const findWidgetDelayMillis = parseInt(getNoteAttributeValue(api.startNote,
"label", "findWidgetDelayMillis", "200"));
const waitForEnter = (findWidgetDelayMillis < 0);
// tabIndex=-1 on the checkbox labels is necessary so when clicking on the label
// the focusout handler is called with relatedTarget equal to the label instead
// of undefined. It's -1 instead of > 0 so they don't tabstop
const TEMPLATE = `<div style="contain: none;">
<div id="findBox" style="padding: 10px; border-top: 1px solid var(--main-border-color); ">
<input type="text" id="input">
<label tabIndex="-1" id="caseLabel"><input type="checkbox" id="caseCheck"> case</label>
<label tabIndex="-1" id="wordLabel"><input type="checkbox" id="wordCheck"> word</label>
<label tabIndex="-1" id="regexpLabel"><input type="checkbox" id="regexpCheck" disabled> regexp</label>
<span style="font-weight: bold;" id="curFound">0</span>/<span style="font-weight: bold;" id="numFound">0</span>
</div>
</div>`;
const tag = "FindWidget";
const debugLevels = ["error", "warn", "info", "log", "debug"];
const debugLevel = debugLevels.indexOf(getNoteAttributeValue(api.startNote, "label",
"debugLevel", "info"));
let warn = function() {};
if (debugLevel >= debugLevels.indexOf("warn")) {
warn = console.warn.bind(console, tag + ": ");
}
let info = function() {};
if (debugLevel >= debugLevels.indexOf("info")) {
info = console.info.bind(console, tag + ": ");
}
let log = function() {};
if (debugLevel >= debugLevels.indexOf("log")) {
log = console.log.bind(console, tag + ": ");
}
let dbg = function() {};
if (debugLevel >= debugLevels.indexOf("debug")) {
dbg = console.debug.bind(console, tag + ": ");
}
function assert(e, msg) {
console.assert(e, tag + ": " + msg);
}
function debugbreak() {
debugger;
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function getActiveTabCodeEditor() {
// The code editor hierarchy is
// note-split data-ntx-id=XXXX
// ...
// note-detail-code component
// note-detail-code-editor
// CodeMirror
// See the discussion at https://github.com/zadam/trilium/discussions/2806#discussioncomment-2623695
// The component has a reference to the CodeMirror editor and ntxId is a
// per split noteContextId
// Note there can be multiple code editors, hidden, visible, per tab and per
// split, but the ntxId makes them unique to the active note in the tab
// manager
// This could use glob.appContext.getComponentByEl but it doesn't seem to
// be worth it
const activeNtxId = glob.appContext.tabManager.activeNtxId;
const component = $(".note-split[data-ntx-id=" + activeNtxId +
"] .note-detail-code").prop('component');
return component.codeEditor;
}
function getActiveTabTextEditor(callback) {
// Wrapper until this commit is available
// https://github.com/zadam/trilium/commit/11578b1bc3dda7f29a91281ec28b5fe6f6c63fef
api.getActiveTabTextEditor(function(textEditor) {
const textEditorNtxId = textEditor.sourceElement.parentElement.component.noteContext.ntxId;
if (glob.appContext.tabManager.activeNtxId == textEditorNtxId) {
callback(textEditor);
}
});
}
// ck-find-result and ck-find-result_selected are the styles ck-editor
// uses for highlighting matches, use the same one on CodeMirror
// for consistency
const FIND_RESULT_SELECTED_CSS_CLASSNAME = "ck-find-result_selected";
const FIND_RESULT_CSS_CLASSNAME = "ck-find-result";
class FindWidget extends api.NoteContextAwareWidget {
constructor(...args) {
super(...args);
this.$widget = $(TEMPLATE);
this.$findBox = this.$widget.find('#findBox');
this.$input = this.$widget.find('#input');
this.$curFound = this.$widget.find('#curFound');
this.$numFound = this.$widget.find('#numFound');
this.$caseCheck = this.$widget.find("#caseCheck");
this.$wordCheck = this.$widget.find("#wordCheck");
this.findResult = null;
this.prevFocus = null;
this.needle = null;
let findWidget = this;
findWidget.$input.keydown(function (e) {
log("keydown on input " + e.key);
if ((e.metaKey || e.ctrlKey) && ((e.key == 'F') || (e.key == 'f'))) {
// If ctrl+f is pressed when the findbox is shown, select the
// whole input to find
findWidget.$input.select();
} else if ((e.key == 'Enter') || (e.key == 'F3')) {
const needle = findWidget.$input.val();
if (waitForEnter && (findWidget.needle != needle)) {
findWidget.performFind(needle);
}
let numFound = parseInt(findWidget.$numFound.text());
let curFound = parseInt(findWidget.$curFound.text()) - 1;
dbg("Finding " + curFound + "/" + numFound + " occurrence of " + findWidget.$input.val());
if (numFound > 0) {
let delta = e.shiftKey ? -1 : 1;
let nextFound = curFound + delta;
// Wrap around
if (nextFound > numFound - 1) {
nextFound = 0;
} if (nextFound < 0) {
nextFound = numFound - 1;
}
findWidget.$curFound.text(nextFound + 1);
const note = api.getActiveTabNote();
if (note.type == "code") {
let codeEditor = getActiveTabCodeEditor();
let doc = codeEditor.doc;
//
// Dehighlight current, highlight & scrollIntoView next
//
let marker = findWidget.findResult[curFound];
let pos = marker.find();
marker.clear();
marker = doc.markText(
pos.from, pos.to,
{ "className" : FIND_RESULT_CSS_CLASSNAME }
);
findWidget.findResult[curFound] = marker;
marker = findWidget.findResult[nextFound];
pos = marker.find();
marker.clear();
marker = doc.markText(
pos.from, pos.to,
{ "className" : FIND_RESULT_SELECTED_CSS_CLASSNAME }
);
findWidget.findResult[nextFound] = marker;
codeEditor.scrollIntoView(pos.from);
} else {
assert(note.type == "text", "Expected text note, found " + note.type);
getActiveTabTextEditor(textEditor => {
// There are no parameters for findNext/findPrev
// See https://github.com/ckeditor/ckeditor5/blob/b95e2faf817262ac0e1e21993d9c0bde3f1be594/packages/ckeditor5-find-and-replace/src/findnextcommand.js#L57
// curFound wrap around above assumes findNext and
// findPrevious wraparound, which is what they do
if (delta > 0) {
textEditor.execute('findNext');
} else {
textEditor.execute('findPrevious');
}
});
}
}
e.preventDefault();
return false;
} else if (e.key == 'Escape') {
const note = api.getActiveTabNote();
if (note.type == "code") {
let codeEditor = getActiveTabCodeEditor();
codeEditor.focus();
} else {
assert(note.type == "text", "Expected text note, found " + note.type);
getActiveTabTextEditor(textEditor => {
textEditor.focus();
});
}
}
// e.preventDefault();
});
findWidget.$input.on('input', function (e) {
// XXX This should clear the previous search immediately in all cases
// (the search is stale when waitforenter but also while the
// delay is running for non waitforenter case)
if (!waitForEnter) {
// Clear the previous timeout if any, it's ok if timeoutId is
// null or undefined
clearTimeout(findWidget.timeoutId);
// Defer the search a few millis so the search doesn't start
// immediately, as this can cause search word typing lag with
// one or two-char searchwords and long notes
// See https://github.com/antoniotejada/Trilium-FindWidget/issues/1
const needle = findWidget.$input.val();
const matchCase = findWidget.$caseCheck.prop("checked");
const wholeWord = findWidget.$wordCheck.prop("checked");
findWidget.timeoutId = setTimeout(function () {
findWidget.timeoutId = null;
findWidget.performFind(needle, matchCase, wholeWord);
}, findWidgetDelayMillis);
}
});
findWidget.$caseCheck.change(function() {
log("caseCheck change");
findWidget.performFind();
});
findWidget.$wordCheck.change(function() {
log("wordCheck change");
findWidget.performFind();
});
// Note blur doesn't bubble to parent div, but the parent div needs to
// detect when any of the children are not focused and hide. Use
// focusout instead which does bubble to the parent div.
findWidget.$findBox.focusout(function (e) {
// e.relatedTarget is the new focused element, note it can be null
// if nothing is being focused
log(`focusout ${e.target.id} related ${e.relatedTarget?.id}`);
if (findWidget.$findBox[0].contains(e.relatedTarget)) {
// The focused element is inside this div, ignore
log("focusout to child, ignoring");
return;
}
findWidget.$findBox.hide();
// Restore any state, if there's a current occurrence clear markers
// and scroll to and select the last occurrence
// XXX Switching to a different tab with crl+tab doesn't invoke
// blur and leaves a stale search which then breaks when
// navigating it
let numFound = parseInt(findWidget.$numFound.text());
let curFound = parseInt(findWidget.$curFound.text()) - 1;
const note = api.getActiveTabNote();
if (note.type == "code") {
let codeEditor = getActiveTabCodeEditor();
if (numFound > 0) {
let doc = codeEditor.doc;
let pos = findWidget.findResult[curFound].find();
// Note setting the selection sets the cursor to
// the end of the selection and scrolls it into
// view
doc.setSelection(pos.from, pos.to);
// Clear all markers
codeEditor.operation(function() {
for (let i = 0; i < findWidget.findResult.length; ++i) {
let marker = findWidget.findResult[i];
marker.clear();
}
});
}
// Restore the highlightSelectionMatches setting
codeEditor.setOption("highlightSelectionMatches", findWidget.oldHighlightSelectionMatches);
findWidget.findResult = null;
findWidget.needle = null;
} else {
assert(note.type == "text", "Expected text note, found " + note.type);
if (numFound > 0) {
getActiveTabTextEditor(textEditor => {
// Clear the markers and set the caret to the
// current occurrence
const model = textEditor.model;
let range = findWidget.findResult.results.get(curFound).marker.getRange();
// From
// https://github.com/ckeditor/ckeditor5/blob/b95e2faf817262ac0e1e21993d9c0bde3f1be594/packages/ckeditor5-find-and-replace/src/findandreplace.js#L92
// XXX Roll our own since already done for codeEditor and
// will probably allow more refactoring?
let findAndReplaceEditing = textEditor.plugins.get('FindAndReplaceEditing');
findAndReplaceEditing.state.clear(model);
findAndReplaceEditing.stop();
model.change(writer => {
writer.setSelection(range, 0);
});
textEditor.editing.view.scrollToTheSelection();
findWidget.findResult = null;
findWidget.needle = null;
});
} else {
findWidget.findResult = null;
findWidget.needle = null;
}
}
});
}
performTextNoteFind(needle, matchCase, wholeWord) {
const findResult = this;
// Do this even if the needle is empty so the markers are cleared and
// the counters updated
getActiveTabTextEditor(textEditor => {
const model = textEditor.model;
let findResult = null;
let numFound = 0;
let curFound = -1;
// Clear
let findAndReplaceEditing = textEditor.plugins.get('FindAndReplaceEditing');
log("findAndReplace clearing");
findAndReplaceEditing.state.clear(model);
log("findAndReplace stopping");
findAndReplaceEditing.stop();
if (needle != "") {
// Parameters are callback/text, options.matchCase=false, options.wholeWords=false
// See https://github.com/ckeditor/ckeditor5/blob/b95e2faf817262ac0e1e21993d9c0bde3f1be594/packages/ckeditor5-find-and-replace/src/findcommand.js#L44
// XXX Need to use the callback version for regexp
// needle = escapeRegExp(needle);
// let re = new RegExp(needle, 'gi');
// let m = text.match(re);
// numFound = m ? m.length : 0;
log("findAndReplace starts");
const options = { "matchCase" : matchCase, "wholeWords" : wholeWord };
findResult = textEditor.execute('find', needle, options);
log("findAndReplace ends");
numFound = findResult.results.length;
// Find the result beyond the cursor
log("findAndReplace positioning");
let cursorPos = model.document.selection.getLastPosition();
for (let i = 0; i < findResult.results.length; ++i) {
let marker = findResult.results.get(i).marker;
let fromPos = marker.getStart();
if (fromPos.compareWith(cursorPos) != "before") {
curFound = i;
break;
}
}
log("findAndReplace positioned");
}
findWidget.findResult = findResult;
findWidget.$numFound.text(numFound);
// Calculate curfound if not already, highlight it as
// selected
if (numFound > 0) {
curFound = Math.max(0, curFound);
// XXX Do this accessing the private data?
// See
// https://github.com/ckeditor/ckeditor5/blob/b95e2faf817262ac0e1e21993d9c0bde3f1be594/packages/ckeditor5-find-and-replace/src/findnextcommand.js
for (let i = 0 ; i < curFound; ++i) {
textEditor.execute('findNext', needle);
}
}
findWidget.$curFound.text(curFound + 1);
this.needle = needle;
});
}
performCodeNoteFind(needle, matchCase, wholeWord) {
let findResult = null;
let numFound = 0;
let curFound = -1;
// See https://codemirror.net/addon/search/searchcursor.js for tips
let codeEditor = getActiveTabCodeEditor();
let doc = codeEditor.doc;
let text = doc.getValue();
// Clear all markers
if (this.findResult != null) {
const findWidget = this;
codeEditor.operation(function() {
for (let i = 0; i < findWidget.findResult.length; ++i) {
let marker = findWidget.findResult[i];
marker.clear();
}
});
}
if (needle != "") {
needle = escapeRegExp(needle);
// Find and highlight matches
// XXX Using \\b and not using the unicode flag probably doesn't
// work with non ascii alphabets, findAndReplace uses a more
// complicated regexp, see
// https://github.com/ckeditor/ckeditor5/blob/b95e2faf817262ac0e1e21993d9c0bde3f1be594/packages/ckeditor5-find-and-replace/src/utils.js#L145
const wholeWordChar = wholeWord ? "\\b" : "";
let re = new RegExp(wholeWordChar + needle + wholeWordChar,
'g' + (matchCase ? '' : 'i'));
let curLine = 0;
let curChar = 0;
let curMatch = null;
findResult = [];
// All those markText take several seconds on eg this ~500-line
// script, batch them inside an operation so they become
// unnoticeable. Alternatively, an overlay could be used, see
// https://codemirror.net/addon/search/match-highlighter.js ?
codeEditor.operation(function() {
for (let i = 0; i < text.length; ++i) {
// Fetch next match if it's the first time or
// if past the current match start
if ((curMatch == null) || (curMatch.index < i)) {
curMatch = re.exec(text);
if (curMatch == null) {
// No more matches
break;
}
}
// Create a non-selected highlight marker for the match, the
// selected marker highlight will be done later
if (i == curMatch.index) {
let fromPos = { "line" : curLine, "ch" : curChar };
// XXX If multiline is supported, this needs to
// recalculate curLine since the match may span
// lines
let toPos = { "line" : curLine, "ch" : curChar + curMatch[0].length};
// XXX or css = "color: #f3"
let marker = doc.markText( fromPos, toPos, { "className" : FIND_RESULT_CSS_CLASSNAME });
findResult.push(marker);
// Set the first match beyond the cursor as current
// match
if (curFound == -1) {
let cursorPos = codeEditor.getCursor();
if ((fromPos.line > cursorPos.line) ||
((fromPos.line == cursorPos.line) &&
(fromPos.ch >= cursorPos.ch))){
curFound = numFound;
}
}
numFound++;
}
// Do line and char position tracking
if (text[i] == "\n") {
curLine++;
curChar = 0;
} else {
curChar++;
}
}
});
}
this.findResult = findResult;
this.$numFound.text(numFound);
// Calculate curfound if not already, highlight it as selected
if (numFound > 0) {
curFound = Math.max(0, curFound)
let marker = findResult[curFound];
let pos = marker.find();
codeEditor.scrollIntoView(pos.to);
marker.clear();
findResult[curFound] = doc.markText( pos.from, pos.to,
{ "className" : FIND_RESULT_SELECTED_CSS_CLASSNAME }
);
}
this.$curFound.text(curFound + 1);
this.needle = needle;
}
/**
* Perform the find and highlight the find results.
*
* @param needle {string} optional parameter, taken from the input box if
* missing.
* @param matchCase {boolean} optional parameter, taken from the checkbox
* state if missing.
* @param wholeWord {boolean} optional parameter, taken from the checkbox
* state if missing.
*/
performFind(needle, matchCase, wholeWord) {
needle = (needle == undefined) ? this.$input.val() : needle;
matchCase = (matchCase === undefined) ? this.$caseCheck.prop("checked") : matchCase;
wholeWord = (wholeWord === undefined) ? this.$wordCheck.prop("checked") : wholeWord;
log(`performFind needle:${needle} case:${matchCase} word:${wholeWord}`);
const note = api.getActiveTabNote();
if (note.type == "code") {
this.performCodeNoteFind(needle, matchCase, wholeWord);
} else {
assert(note.type == "text", "Expected text note, found " + note.type);
this.performTextNoteFind(needle, matchCase, wholeWord);
}
}
get position() {
log("getPosition");
// higher value means position towards the bottom/right
return 100;
}
get parentWidget() {
log("getParentWidget");
return 'center-pane';
}
isEnabled() {
log("isEnabled");
return super.isEnabled()
&& ((this.note.type === 'text') || (this.note.type === 'code'))
&& !this.note.hasLabel('noFindWidget');
}
doRender() {
log("doRender");
this.$findBox.hide();
return this.$widget;
}
async refreshWithNote(note) {
log("refreshWithNote");
}
async entitiesReloadedEvent({loadResults}) {
log("entitiesReloadedEvent");
if (loadResults.isNoteContentReloaded(this.noteId)) {
this.refresh();
}
}
}
info(`Creating FindWidget debugLevel:${debugLevel} findWidgetDelayMillis:${findWidgetDelayMillis}`);
let findWidget = new FindWidget();
module.exports = findWidget;
// XXX Use api.bindGlobalShortcut?
$(window).keydown(function (e){
log("keydown on window " + e.key);
if ((e.key == 'F3') ||
// Note that for ctrl+f to work, needs to be disabled in Trilium's
// shortcut config menu
// XXX Maybe not if using bindShorcut?
((e.metaKey || e.ctrlKey) && ((e.key == 'f') || (e.key == 'F')))) {
const note = api.getActiveTabNote();
// Only writeable text and code supported
const readOnly = note.getAttribute("label", "readOnly");
if (!readOnly && ((note.type == "code") || (note.type == "text"))) {
if (findWidget.$findBox.is(":hidden")) {
findWidget.$findBox.show();
findWidget.$input.focus();
findWidget.$numFound.text(0);
findWidget.$curFound.text(0);
// Initialize the input field to the text selection, if any
if (note.type == "code") {
let codeEditor = getActiveTabCodeEditor();
// highlightSelectionMatches is the overlay that highlights
// the words under the cursor. This occludes the search
// markers style, save it, disable it. Will be restored when
// the focus is back into the note
findWidget.oldHighlightSelectionMatches = codeEditor.getOption("highlightSelectionMatches");
codeEditor.setOption("highlightSelectionMatches", false);
// Fill in the findbox with the current selection if any
const selectedText = codeEditor.getSelection()
if (selectedText != "") {
findWidget.$input.val(selectedText);
}
// Directly perform the search if there's some text to find,
// without delaying or waiting for enter
const needle = findWidget.$input.val();
if (needle != "") {
findWidget.$input.select();
findWidget.performFind(needle);
}
} else {
getActiveTabTextEditor(textEditor => {
const selection = textEditor.model.document.selection;
const range = selection.getFirstRange();
for (const item of range.getItems()) {
// Fill in the findbox with the current selection if
// any
findWidget.$input.val(item.data);
break;
}
// Directly perform the search if there's some text to
// find, without delaying or waiting for enter
const needle = findWidget.$input.val();
if (needle != "") {
findWidget.$input.select();
findWidget.performFind(needle);
}
});
}
}
e.preventDefault();
return false;
}
}
return true;
});