373 lines
13 KiB
TypeScript
Raw Normal View History

/**
* (c) Antonio Tejada 2022
2022-05-14 22:33:45 +02:00
* https://github.com/antoniotejada/Trilium-FindWidget
*/
2024-09-13 11:10:59 +08:00
import { t } from "../services/i18n.js";
import NoteContextAwareWidget from "./note_context_aware_widget.js";
import attributeService from "../services/attributes.js";
2022-05-16 23:56:43 +02:00
import FindInText from "./find_in_text.js";
import FindInCode from "./find_in_code.js";
2022-05-25 23:38:06 +02:00
import FindInHtml from "./find_in_html.js";
import type { EventData } from "../components/app_context.js";
const findWidgetDelayMillis = 200;
2025-01-09 18:07:02 +02:00
const waitForEnter = findWidgetDelayMillis < 0;
export interface FindResult {
totalFound: number;
currentFound: number;
}
2023-05-05 23:41:11 +02:00
// tabIndex=-1 on the checkbox labels is necessary, so when clicking on the label,
2022-05-14 21:06:14 +02:00
// the focusout handler is called with relatedTarget equal to the label instead
2022-05-14 22:33:45 +02:00
// of undefined. It's -1 instead of > 0, so they don't tabstop
const TPL = /*html*/`
<div class='find-replace-widget' style="contain: none; border-top: 1px solid var(--main-border-color);">
2022-05-15 22:51:26 +02:00
<style>
.find-widget-box, .replace-widget-box {
padding: 2px 10px 2px 10px;
2022-05-15 22:51:26 +02:00
align-items: center;
}
.find-widget-box > *, .replace-widget-box > *{
2022-05-15 22:51:26 +02:00
margin-right: 15px;
}
.find-widget-box, .replace-widget-box {
2022-05-15 22:51:26 +02:00
display: flex;
}
2022-05-15 22:51:26 +02:00
.find-widget-found-wrapper {
justify-content: center;
min-width: 60px;
padding: 0 4px;
font-size: .85em;
text-align: center;
2022-05-15 22:51:26 +02:00
}
.find-widget-search-term-input-group, .replace-widget-replacetext-input {
max-width: 350px;
2022-05-17 23:22:28 +02:00
}
2022-05-17 23:22:28 +02:00
.find-widget-spacer {
flex-grow: 1;
}
2022-05-15 22:51:26 +02:00
</style>
<div class="find-widget-box">
<div class="input-group find-widget-search-term-input-group">
2025-01-09 18:07:02 +02:00
<input type="text" class="form-control find-widget-search-term-input" placeholder="${t("find.find_placeholder")}">
2024-09-03 18:42:03 +02:00
<button class="btn btn-outline-secondary bx bxs-chevron-up find-widget-previous-button" type="button"></button>
<div class="find-widget-found-wrapper input-group-text">
<span>
<span class="find-widget-current-found">0</span>
/
<span class="find-widget-total-found">0</span>
<span>
</div>
2024-09-03 18:42:03 +02:00
<button class="btn btn-outline-secondary bx bxs-chevron-down find-widget-next-button" type="button"></button>
</div>
2022-05-15 22:51:26 +02:00
<div class="form-check">
<label tabIndex="-1" class="form-check-label tn-checkbox">
<input type="checkbox" class="form-check-input find-widget-case-sensitive-checkbox">
2025-01-09 18:07:02 +02:00
${t("find.case_sensitive")}
</label>
2022-05-15 22:51:26 +02:00
</div>
<div class="form-check">
<label tabIndex="-1" class="form-check-label tn-checkbox">
<input type="checkbox" class="form-check-input find-widget-match-words-checkbox">
2025-01-09 18:07:02 +02:00
${t("find.match_words")}
</label>
2022-05-15 22:51:26 +02:00
</div>
2022-05-17 23:22:28 +02:00
<div class="find-widget-spacer"></div>
2022-05-17 23:22:28 +02:00
<div class="find-widget-close-button"><button class="btn icon-action bx bx-x"></button></div>
2022-05-14 22:33:45 +02:00
</div>
<div class="replace-widget-box" style='display: none'>
2025-01-09 18:07:02 +02:00
<input type="text" class="form-control replace-widget-replacetext-input" placeholder="${t("find.replace_placeholder")}">
<button class="btn btn-sm replace-widget-replaceall-button" type="button">${t("find.replace_all")}</button>
<button class="btn btn-sm replace-widget-replace-button" type="button">${t("find.replace")}</button>
</div>
</div>`;
2022-05-16 23:56:43 +02:00
export default class FindWidget extends NoteContextAwareWidget {
private searchTerm: string | null;
private textHandler: FindInText;
private codeHandler: FindInCode;
private htmlHandler: FindInHtml;
private handler?: FindInText | FindInCode | FindInHtml;
private timeoutId?: number | null;
private $input!: JQuery<HTMLElement>;
private $currentFound!: JQuery<HTMLElement>;
private $totalFound!: JQuery<HTMLElement>;
private $caseSensitiveCheckbox!: JQuery<HTMLElement>;
private $matchWordsCheckbox!: JQuery<HTMLElement>;
private $previousButton!: JQuery<HTMLElement>;
private $nextButton!: JQuery<HTMLElement>;
private $closeButton!: JQuery<HTMLElement>;
private $replaceWidgetBox!: JQuery<HTMLElement>;
private $replaceTextInput!: JQuery<HTMLElement>;
private $replaceAllButton!: JQuery<HTMLElement>;
private $replaceButton!: JQuery<HTMLElement>;
2022-05-16 23:56:43 +02:00
constructor() {
super();
2022-05-17 23:22:28 +02:00
this.searchTerm = null;
this.textHandler = new FindInText(this);
this.codeHandler = new FindInCode(this);
2022-05-25 23:38:06 +02:00
this.htmlHandler = new FindInHtml(this);
}
async noteSwitched() {
await super.noteSwitched();
await this.closeSearch();
2022-05-16 23:56:43 +02:00
}
2022-05-15 12:09:30 +02:00
doRender() {
this.$widget = $(TPL);
this.$widget.hide();
2025-01-09 18:07:02 +02:00
this.$input = this.$widget.find(".find-widget-search-term-input");
this.$currentFound = this.$widget.find(".find-widget-current-found");
this.$totalFound = this.$widget.find(".find-widget-total-found");
2022-05-15 22:51:26 +02:00
this.$caseSensitiveCheckbox = this.$widget.find(".find-widget-case-sensitive-checkbox");
this.$caseSensitiveCheckbox.on("change", () => this.performFind());
2022-05-15 22:51:26 +02:00
this.$matchWordsCheckbox = this.$widget.find(".find-widget-match-words-checkbox");
this.$matchWordsCheckbox.on("change", () => this.performFind());
this.$previousButton = this.$widget.find(".find-widget-previous-button");
this.$previousButton.on("click", () => this.findNext(-1));
this.$nextButton = this.$widget.find(".find-widget-next-button");
this.$nextButton.on("click", () => this.findNext(1));
2022-05-17 23:22:28 +02:00
this.$closeButton = this.$widget.find(".find-widget-close-button");
this.$closeButton.on("click", () => this.closeSearch());
this.$replaceWidgetBox = this.$widget.find(".replace-widget-box");
this.$replaceTextInput = this.$widget.find(".replace-widget-replacetext-input");
this.$replaceAllButton = this.$widget.find(".replace-widget-replaceall-button");
this.$replaceAllButton.on("click", () => this.replaceAll());
this.$replaceButton = this.$widget.find(".replace-widget-replace-button");
this.$replaceButton.on("click", () => this.replace());
this.$input.on("keydown", async (e) => {
2025-01-09 18:07:02 +02:00
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
2022-05-15 12:09:30 +02:00
this.$input.select();
2025-01-09 18:07:02 +02:00
} else if (e.key === "Enter" || e.key === "F3") {
await this.findNext(e?.shiftKey ? -1 : 1);
e.preventDefault();
return false;
2022-05-26 16:29:54 +02:00
}
});
this.$widget.on("keydown", async (e) => {
2025-01-09 18:07:02 +02:00
if (e.key === "Escape") {
2022-05-17 23:22:28 +02:00
await this.closeSearch();
}
});
2025-01-09 18:07:02 +02:00
this.$input.on("input", () => this.startSearch());
2022-05-14 21:06:14 +02:00
2022-05-15 12:09:30 +02:00
return this.$widget;
}
2022-05-25 23:38:06 +02:00
async findInTextEvent() {
if (!this.isActiveNoteContext()) {
return;
}
if (!["text", "code", "render"].includes(this.note?.type ?? "")) {
2022-05-25 23:38:06 +02:00
return;
}
this.handler = await this.getHandler();
2025-01-09 18:07:02 +02:00
const isReadOnly = await this.noteContext?.isReadOnly();
2023-05-18 13:41:32 +02:00
2025-01-09 18:07:02 +02:00
let selectedText = "";
if (this.note?.type === "code" && this.noteContext) {
if (isReadOnly){
const $content = await this.noteContext.getContentElement();
selectedText = $content.find('.cm-matchhighlight').first().text();
} else {
const codeEditor = await this.noteContext.getCodeEditor();
selectedText = codeEditor.getSelection();
}
2025-01-09 18:07:02 +02:00
} else {
selectedText = window.getSelection()?.toString() || "";
}
this.$widget.show();
2022-05-25 23:38:06 +02:00
this.$input.focus();
if (["text", "code"].includes(this.note?.type ?? "") && !isReadOnly) {
this.$replaceWidgetBox.show();
2025-01-09 18:07:02 +02:00
} else {
this.$replaceWidgetBox.hide();
}
2022-05-25 23:38:06 +02:00
const isAlreadyVisible = this.$widget.is(":visible");
2022-05-25 23:38:06 +02:00
if (isAlreadyVisible) {
2023-05-18 13:41:32 +02:00
if (selectedText) {
this.$input.val(selectedText);
}
if (this.$input.val()) {
await this.performFind();
}
2023-05-18 13:41:32 +02:00
2022-05-25 23:38:06 +02:00
this.$input.select();
} else {
this.$totalFound.text(0);
this.$currentFound.text(0);
2023-05-18 13:41:32 +02:00
this.$input.val(selectedText);
if (selectedText) {
this.$input.select();
await this.performFind();
}
2022-05-25 23:38:06 +02:00
}
}
async readOnlyTemporarilyDisabledEvent({ noteContext }: EventData<"readOnlyTemporarilyDisabled">) {
if (this.isNoteContext(noteContext.ntxId)) {
await this.closeSearch();
}
}
async getHandler() {
if (this.note?.type === "render") {
return this.htmlHandler;
}
const readOnly = await this.noteContext?.isReadOnly();
if (readOnly) {
return this.htmlHandler;
} else {
return this.note?.type === "code" ? this.codeHandler : this.textHandler;
}
}
2022-05-16 23:56:43 +02:00
startSearch() {
// XXX This should clear the previous search immediately in all cases
// (the search is stale when waitforenter but also while the
2023-05-05 23:41:11 +02:00
// delay is running for the non waitforenter case)
2022-05-16 23:56:43 +02:00
if (!waitForEnter) {
// Clear the previous timeout if any, it's ok if timeoutId is
// null or undefined
clearTimeout(this.timeoutId as unknown as NodeJS.Timeout); // TODO: Fix once client is separated from Node.js types.
2022-05-16 23:56:43 +02:00
// 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
this.timeoutId = setTimeout(async () => {
this.timeoutId = null;
2022-05-17 23:22:28 +02:00
await this.performFind();
}, findWidgetDelayMillis) as unknown as number; // TODO: Fix once client is separated from Node.js types.
2022-05-16 23:56:43 +02:00
}
}
/**
* @param direction +1 for next, -1 for previous
*/
async findNext(direction: 1 | -1) {
2025-01-09 18:07:02 +02:00
if (this.$totalFound.text() == "?") {
2024-08-30 11:42:55 +00:00
await this.performFind();
2025-01-09 18:07:02 +02:00
return;
2024-08-30 11:42:55 +00:00
}
2022-05-16 23:56:43 +02:00
const searchTerm = this.$input.val();
if (waitForEnter && this.searchTerm !== searchTerm) {
2022-05-17 23:22:28 +02:00
await this.performFind();
2022-05-16 23:56:43 +02:00
}
const totalFound = parseInt(this.$totalFound.text());
const currentFound = parseInt(this.$currentFound.text()) - 1;
if (totalFound > 0) {
let nextFound = currentFound + direction;
// Wrap around
if (nextFound > totalFound - 1) {
nextFound = 0;
} else if (nextFound < 0) {
nextFound = totalFound - 1;
}
this.$currentFound.text(nextFound + 1);
await this.handler?.findNext(direction, currentFound, nextFound);
2022-05-16 23:56:43 +02:00
}
}
2022-05-17 23:22:28 +02:00
/** Perform the find and highlight the find results. */
async performFind() {
const searchTerm = String(this.$input.val());
2022-05-17 23:22:28 +02:00
const matchCase = this.$caseSensitiveCheckbox.prop("checked");
const wholeWord = this.$matchWordsCheckbox.prop("checked");
2022-05-16 23:56:43 +02:00
2025-03-19 22:39:49 +02:00
if (!this.handler) {
return;
}
const { totalFound, currentFound } = await this.handler.performFind(searchTerm, matchCase, wholeWord);
2022-05-16 23:56:43 +02:00
this.$totalFound.text(totalFound);
this.$currentFound.text(currentFound);
this.searchTerm = searchTerm;
}
async closeSearch() {
if (this.$widget.is(":visible")) {
this.$widget.hide();
2022-05-16 23:56:43 +02:00
2022-05-25 23:38:06 +02:00
// Restore any state, if there's a current occurrence clear markers
// and scroll to and select the last occurrence
const totalFound = parseInt(this.$totalFound.text());
const currentFound = parseInt(this.$currentFound.text()) - 1;
2022-05-16 23:56:43 +02:00
2022-05-25 23:38:06 +02:00
this.searchTerm = null;
2022-05-26 16:29:54 +02:00
await this.handler?.findBoxClosed(totalFound, currentFound);
}
}
2022-05-16 23:56:43 +02:00
async replace() {
const replaceText = String(this.$replaceTextInput.val());
if (this.handler && "replace" in this.handler) {
await this.handler.replace(replaceText);
}
}
async replaceAll() {
const replaceText = String(this.$replaceTextInput.val());
if (this.handler && "replace" in this.handler) {
await this.handler.replaceAll(replaceText);
}
}
2022-05-17 23:22:28 +02:00
isEnabled() {
return super.isEnabled() && ["text", "code", "render"].includes(this.note?.type ?? "");
2022-05-17 23:22:28 +02:00
}
2024-08-30 11:42:55 +00:00
async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {
if (this.noteId && loadResults.isNoteContentReloaded(this.noteId)) {
2025-01-09 18:07:02 +02:00
this.$totalFound.text("?");
} else if (loadResults.getAttributeRows().find((attr) => attr.type === "label"
&& (attr.name?.toLowerCase() ?? "").includes("readonly")
&& attributeService.isAffecting(attr, this.note))) {
this.closeSearch();
2024-09-13 11:10:59 +08:00
}
2024-08-30 11:42:55 +00:00
}
}