findwidget cleanup

This commit is contained in:
zadam 2022-05-15 12:09:30 +02:00
parent 36308c307b
commit 6778e1e60e

View File

@ -38,7 +38,7 @@ const waitForEnter = (findWidgetDelayMillis < 0);
// tabIndex=-1 on the checkbox labels is necessary so when clicking on the label // 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 // 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 // of undefined. It's -1 instead of > 0, so they don't tabstop
const TEMPLATE = ` const TPL = `
<div style="contain: none;"> <div style="contain: none;">
<div id="findBox" style="padding: 10px; border-top: 1px solid var(--main-border-color); "> <div id="findBox" style="padding: 10px; border-top: 1px solid var(--main-border-color); ">
<input type="text" id="input"> <input type="text" id="input">
@ -63,22 +63,20 @@ const FIND_RESULT_SELECTED_CSS_CLASSNAME = "ck-find-result_selected";
const FIND_RESULT_CSS_CLASSNAME = "ck-find-result"; const FIND_RESULT_CSS_CLASSNAME = "ck-find-result";
export default class FindWidget extends NoteContextAwareWidget { export default class FindWidget extends NoteContextAwareWidget {
constructor(...args) { doRender() {
super(...args); this.$widget = $(TPL);
this.$widget = $(TEMPLATE);
this.$findBox = this.$widget.find('#findBox'); this.$findBox = this.$widget.find('#findBox');
this.$findBox.hide();
this.$input = this.$widget.find('#input'); this.$input = this.$widget.find('#input');
this.$curFound = this.$widget.find('#curFound'); this.$curFound = this.$widget.find('#curFound');
this.$numFound = this.$widget.find('#numFound'); this.$numFound = this.$widget.find('#numFound');
this.$caseCheck = this.$widget.find("#caseCheck"); this.$caseCheck = this.$widget.find("#caseCheck");
this.$wordCheck = this.$widget.find("#wordCheck"); this.$wordCheck = this.$widget.find("#wordCheck");
this.findResult = null; this.findResult = null;
this.prevFocus = null;
this.needle = null; this.needle = null;
let findWidget = this;
// XXX Use api.bindGlobalShortcut? // XXX Use api.bindGlobalShortcut?
$(window).keydown(async function (e){ $(window).keydown(async (e) => {
if ((e.key === 'F3') || if ((e.key === 'F3') ||
// Note that for ctrl+f to work, needs to be disabled in Trilium's // Note that for ctrl+f to work, needs to be disabled in Trilium's
// shortcut config menu // shortcut config menu
@ -89,12 +87,12 @@ export default class FindWidget extends NoteContextAwareWidget {
// Only writeable text and code supported // Only writeable text and code supported
const readOnly = note.getAttribute("label", "readOnly"); const readOnly = note.getAttribute("label", "readOnly");
if (!readOnly && (note.type === "code" || note.type === "text")) { if (!readOnly && (note.type === "code" || note.type === "text")) {
if (findWidget.$findBox.is(":hidden")) { if (this.$findBox.is(":hidden")) {
findWidget.$findBox.show(); this.$findBox.show();
findWidget.$input.focus(); this.$input.focus();
findWidget.$numFound.text(0); this.$numFound.text(0);
findWidget.$curFound.text(0); this.$curFound.text(0);
// Initialize the input field to the text selection, if any // Initialize the input field to the text selection, if any
if (note.type === "code") { if (note.type === "code") {
@ -104,20 +102,20 @@ export default class FindWidget extends NoteContextAwareWidget {
// the words under the cursor. This occludes the search // the words under the cursor. This occludes the search
// markers style, save it, disable it. Will be restored when // markers style, save it, disable it. Will be restored when
// the focus is back into the note // the focus is back into the note
findWidget.oldHighlightSelectionMatches = codeEditor.getOption("highlightSelectionMatches"); this.oldHighlightSelectionMatches = codeEditor.getOption("highlightSelectionMatches");
codeEditor.setOption("highlightSelectionMatches", false); codeEditor.setOption("highlightSelectionMatches", false);
// Fill in the findbox with the current selection if any // Fill in the findbox with the current selection if any
const selectedText = codeEditor.getSelection() const selectedText = codeEditor.getSelection()
if (selectedText !== "") { if (selectedText !== "") {
findWidget.$input.val(selectedText); this.$input.val(selectedText);
} }
// Directly perform the search if there's some text to find, // Directly perform the search if there's some text to find,
// without delaying or waiting for enter // without delaying or waiting for enter
const needle = findWidget.$input.val(); const needle = this.$input.val();
if (needle !== "") { if (needle !== "") {
findWidget.$input.select(); this.$input.select();
await findWidget.performFind(needle); await this.performFind(needle);
} }
} else { } else {
const textEditor = await getActiveContextTextEditor(); const textEditor = await getActiveContextTextEditor();
@ -128,15 +126,15 @@ export default class FindWidget extends NoteContextAwareWidget {
for (const item of range.getItems()) { for (const item of range.getItems()) {
// Fill in the findbox with the current selection if // Fill in the findbox with the current selection if
// any // any
findWidget.$input.val(item.data); this.$input.val(item.data);
break; break;
} }
// Directly perform the search if there's some text to // Directly perform the search if there's some text to
// find, without delaying or waiting for enter // find, without delaying or waiting for enter
const needle = findWidget.$input.val(); const needle = this.$input.val();
if (needle !== "") { if (needle !== "") {
findWidget.$input.select(); this.$input.select();
await findWidget.performFind(needle); await this.performFind(needle);
} }
} }
} }
@ -147,18 +145,18 @@ export default class FindWidget extends NoteContextAwareWidget {
return true; return true;
}); });
findWidget.$input.keydown(async function (e) { this.$input.keydown(async e => {
if ((e.metaKey || e.ctrlKey) && ((e.key === 'F') || (e.key === 'f'))) { if ((e.metaKey || e.ctrlKey) && ((e.key === 'F') || (e.key === 'f'))) {
// If ctrl+f is pressed when the findbox is shown, select the // If ctrl+f is pressed when the findbox is shown, select the
// whole input to find // whole input to find
findWidget.$input.select(); this.$input.select();
} else if ((e.key === 'Enter') || (e.key === 'F3')) { } else if ((e.key === 'Enter') || (e.key === 'F3')) {
const needle = findWidget.$input.val(); const needle = this.$input.val();
if (waitForEnter && (findWidget.needle !== needle)) { if (waitForEnter && (this.needle !== needle)) {
await findWidget.performFind(needle); await this.performFind(needle);
} }
let numFound = parseInt(findWidget.$numFound.text()); const numFound = parseInt(this.$numFound.text());
let curFound = parseInt(findWidget.$curFound.text()) - 1; const curFound = parseInt(this.$curFound.text()) - 1;
if (numFound > 0) { if (numFound > 0) {
let delta = e.shiftKey ? -1 : 1; let delta = e.shiftKey ? -1 : 1;
@ -170,8 +168,8 @@ export default class FindWidget extends NoteContextAwareWidget {
nextFound = numFound - 1; nextFound = numFound - 1;
} }
let needle = findWidget.$input.val(); let needle = this.$input.val();
findWidget.$curFound.text(nextFound + 1); this.$curFound.text(nextFound + 1);
const note = appContext.tabManager.getActiveContextNote(); const note = appContext.tabManager.getActiveContextNote();
if (note.type === "code") { if (note.type === "code") {
@ -182,23 +180,23 @@ export default class FindWidget extends NoteContextAwareWidget {
// Dehighlight current, highlight & scrollIntoView next // Dehighlight current, highlight & scrollIntoView next
// //
let marker = findWidget.findResult[curFound]; let marker = this.findResult[curFound];
let pos = marker.find(); let pos = marker.find();
marker.clear(); marker.clear();
marker = doc.markText( marker = doc.markText(
pos.from, pos.to, pos.from, pos.to,
{ "className" : FIND_RESULT_CSS_CLASSNAME } { "className" : FIND_RESULT_CSS_CLASSNAME }
); );
findWidget.findResult[curFound] = marker; this.findResult[curFound] = marker;
marker = findWidget.findResult[nextFound]; marker = this.findResult[nextFound];
pos = marker.find(); pos = marker.find();
marker.clear(); marker.clear();
marker = doc.markText( marker = doc.markText(
pos.from, pos.to, pos.from, pos.to,
{ "className" : FIND_RESULT_SELECTED_CSS_CLASSNAME } { "className" : FIND_RESULT_SELECTED_CSS_CLASSNAME }
); );
findWidget.findResult[nextFound] = marker; this.findResult[nextFound] = marker;
codeEditor.scrollIntoView(pos.from); codeEditor.scrollIntoView(pos.from);
} else { } else {
@ -218,7 +216,7 @@ export default class FindWidget extends NoteContextAwareWidget {
e.preventDefault(); e.preventDefault();
return false; return false;
} else if (e.key === 'Escape') { } else if (e.key === 'Escape') {
let numFound = parseInt(findWidget.$numFound.text()); let numFound = parseInt(this.$numFound.text());
const note = appContext.tabManager.getActiveContextNote(); const note = appContext.tabManager.getActiveContextNote();
if (note.type === "code") { if (note.type === "code") {
@ -233,48 +231,43 @@ export default class FindWidget extends NoteContextAwareWidget {
// e.preventDefault(); // e.preventDefault();
}); });
findWidget.$input.on('input', function (e) { this.$input.on('input', () => {
// XXX This should clear the previous search immediately in all cases // XXX This should clear the previous search immediately in all cases
// (the search is stale when waitforenter but also while the // (the search is stale when waitforenter but also while the
// delay is running for non waitforenter case) // delay is running for non waitforenter case)
if (!waitForEnter) { if (!waitForEnter) {
// Clear the previous timeout if any, it's ok if timeoutId is // Clear the previous timeout if any, it's ok if timeoutId is
// null or undefined // null or undefined
clearTimeout(findWidget.timeoutId); clearTimeout(this.timeoutId);
// Defer the search a few millis so the search doesn't start // Defer the search a few millis so the search doesn't start
// immediately, as this can cause search word typing lag with // immediately, as this can cause search word typing lag with
// one or two-char searchwords and long notes // one or two-char searchwords and long notes
// See https://github.com/antoniotejada/Trilium-FindWidget/issues/1 // See https://github.com/antoniotejada/Trilium-FindWidget/issues/1
const needle = findWidget.$input.val(); const needle = this.$input.val();
const matchCase = findWidget.$caseCheck.prop("checked"); const matchCase = this.$caseCheck.prop("checked");
const wholeWord = findWidget.$wordCheck.prop("checked"); const wholeWord = this.$wordCheck.prop("checked");
findWidget.timeoutId = setTimeout(async function () { this.timeoutId = setTimeout(async () => {
findWidget.timeoutId = null; this.timeoutId = null;
await findWidget.performFind(needle, matchCase, wholeWord); await this.performFind(needle, matchCase, wholeWord);
}, findWidgetDelayMillis); }, findWidgetDelayMillis);
} }
}); });
findWidget.$caseCheck.change(function() { this.$caseCheck.change(() => this.performFind());
findWidget.performFind(); this.$wordCheck.change(() => this.performFind());
});
findWidget.$wordCheck.change(function() {
findWidget.performFind();
});
// Note blur doesn't bubble to parent div, but the parent div needs to // 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 // detect when any of the children are not focused and hide. Use
// focusout instead which does bubble to the parent div. // focusout instead which does bubble to the parent div.
findWidget.$findBox.focusout(async function (e) { this.$findBox.focusout(async (e) => {
// e.relatedTarget is the new focused element, note it can be null // e.relatedTarget is the new focused element, note it can be null
// if nothing is being focused // if nothing is being focused
if (findWidget.$findBox[0].contains(e.relatedTarget)) { if (this.$findBox[0].contains(e.relatedTarget)) {
// The focused element is inside this div, ignore // The focused element is inside this div, ignore
return; return;
} }
findWidget.$findBox.hide(); this.$findBox.hide();
// Restore any state, if there's a current occurrence clear markers // Restore any state, if there's a current occurrence clear markers
// and scroll to and select the last occurrence // and scroll to and select the last occurrence
@ -282,37 +275,37 @@ export default class FindWidget extends NoteContextAwareWidget {
// XXX Switching to a different tab with crl+tab doesn't invoke // XXX Switching to a different tab with crl+tab doesn't invoke
// blur and leaves a stale search which then breaks when // blur and leaves a stale search which then breaks when
// navigating it // navigating it
let numFound = parseInt(findWidget.$numFound.text()); let numFound = parseInt(this.$numFound.text());
let curFound = parseInt(findWidget.$curFound.text()) - 1; let curFound = parseInt(this.$curFound.text()) - 1;
const note = appContext.tabManager.getActiveContextNote(); const note = appContext.tabManager.getActiveContextNote();
if (note.type === "code") { if (note.type === "code") {
let codeEditor = await getActiveContextCodeEditor(); let codeEditor = await getActiveContextCodeEditor();
if (numFound > 0) { if (numFound > 0) {
let doc = codeEditor.doc; let doc = codeEditor.doc;
let pos = findWidget.findResult[curFound].find(); let pos = this.findResult[curFound].find();
// Note setting the selection sets the cursor to // Note setting the selection sets the cursor to
// the end of the selection and scrolls it into // the end of the selection and scrolls it into
// view // view
doc.setSelection(pos.from, pos.to); doc.setSelection(pos.from, pos.to);
// Clear all markers // Clear all markers
codeEditor.operation(function() { codeEditor.operation(() => {
for (let i = 0; i < findWidget.findResult.length; ++i) { for (let i = 0; i < this.findResult.length; ++i) {
let marker = findWidget.findResult[i]; let marker = this.findResult[i];
marker.clear(); marker.clear();
} }
}); });
} }
// Restore the highlightSelectionMatches setting // Restore the highlightSelectionMatches setting
codeEditor.setOption("highlightSelectionMatches", findWidget.oldHighlightSelectionMatches); codeEditor.setOption("highlightSelectionMatches", this.oldHighlightSelectionMatches);
findWidget.findResult = null; this.findResult = null;
findWidget.needle = null; this.needle = null;
} else { } else {
if (numFound > 0) { if (numFound > 0) {
const textEditor = await getActiveContextTextEditor(); const textEditor = await getActiveContextTextEditor();
// Clear the markers and set the caret to the // Clear the markers and set the caret to the
// current occurrence // current occurrence
const model = textEditor.model; const model = textEditor.model;
let range = findWidget.findResult.results.get(curFound).marker.getRange(); let range = this.findResult.results.get(curFound).marker.getRange();
// From // From
// https://github.com/ckeditor/ckeditor5/blob/b95e2faf817262ac0e1e21993d9c0bde3f1be594/packages/ckeditor5-find-and-replace/src/findandreplace.js#L92 // 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 // XXX Roll our own since already done for codeEditor and
@ -324,14 +317,16 @@ export default class FindWidget extends NoteContextAwareWidget {
writer.setSelection(range, 0); writer.setSelection(range, 0);
}); });
textEditor.editing.view.scrollToTheSelection(); textEditor.editing.view.scrollToTheSelection();
findWidget.findResult = null; this.findResult = null;
findWidget.needle = null; this.needle = null;
} else { } else {
findWidget.findResult = null; this.findResult = null;
findWidget.needle = null; this.needle = null;
} }
} }
}); });
return this.$widget;
} }
async performTextNoteFind(needle, matchCase, wholeWord) { async performTextNoteFind(needle, matchCase, wholeWord) {
@ -400,9 +395,9 @@ export default class FindWidget extends NoteContextAwareWidget {
// Clear all markers // Clear all markers
if (this.findResult != null) { if (this.findResult != null) {
const findWidget = this; const findWidget = this;
codeEditor.operation(function() { codeEditor.operation(() => {
for (let i = 0; i < findWidget.findResult.length; ++i) { for (let i = 0; i < this.findResult.length; ++i) {
const marker = findWidget.findResult[i]; const marker = this.findResult[i];
marker.clear(); marker.clear();
} }
}); });
@ -428,7 +423,7 @@ export default class FindWidget extends NoteContextAwareWidget {
// script, batch them inside an operation so they become // script, batch them inside an operation so they become
// unnoticeable. Alternatively, an overlay could be used, see // unnoticeable. Alternatively, an overlay could be used, see
// https://codemirror.net/addon/search/match-highlighter.js ? // https://codemirror.net/addon/search/match-highlighter.js ?
codeEditor.operation(function() { codeEditor.operation(() => {
for (let i = 0; i < text.length; ++i) { for (let i = 0; i < text.length; ++i) {
// Fetch next match if it's the first time or // Fetch next match if it's the first time or
// if past the current match start // if past the current match start
@ -520,11 +515,6 @@ export default class FindWidget extends NoteContextAwareWidget {
&& !this.note.hasLabel('noFindWidget'); && !this.note.hasLabel('noFindWidget');
} }
doRender() {
this.$findBox.hide();
return this.$widget;
}
async entitiesReloadedEvent({loadResults}) { async entitiesReloadedEvent({loadResults}) {
if (loadResults.isNoteContentReloaded(this.noteId)) { if (loadResults.isNoteContentReloaded(this.noteId)) {
this.refresh(); this.refresh();