Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/content embed: interoperate with the search and replace mechanism of the host note

Adorian Doranaa54104edb8e
diff --git a/apps/client/src/services/collapsible.spec.ts b/apps/client/src/services/collapsible.spec.ts
index 01a1463615..8bd6a71475 100644
--- a/apps/client/src/services/collapsible.spec.ts
+++ b/apps/client/src/services/collapsible.spec.ts
@@ -39,6 +39,22 @@ describe("expandAncestorDetails", () => {
expect(match.closest("details")?.open).toBe(true);
});
+ it("opens no ancestor outside the boundary", () => {
+ const match = mount(`
+ <details class="outer"><summary>o</summary>
+ <div class="boundary">
+ <details class="inner"><summary>i</summary><span class="m">hit</span></details>
+ </div>
+ </details>`, ".m");
+ const boundary = match.closest(".boundary");
+ if (!boundary) throw new Error("No boundary.");
+
+ revealElement(match, boundary);
+
+ expect(match.closest<HTMLDetailsElement>("details.inner")?.open).toBe(true);
+ expect(match.closest<HTMLDetailsElement>("details.outer")?.open).toBe(false);
+ });
+
it("is a no-op when there is no <details> ancestor", () => {
const match = mount(`<p><span class="m">hit</span></p>`, ".m");
expect(() => expandAncestorDetails(match)).not.toThrow();
diff --git a/apps/client/src/services/collapsible.ts b/apps/client/src/services/collapsible.ts
index a7e0f16cab..734be1f9a0 100644
--- a/apps/client/src/services/collapsible.ts
+++ b/apps/client/src/services/collapsible.ts
@@ -1,9 +1,12 @@
import { revealTab } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";
-/** Open every collapsed `<details>` ancestor of `el` so content inside it becomes visible. */
-export function expandAncestorDetails(el: Element) {
+/**
+ * Open every collapsed `<details>` ancestor of `el` inside `boundary` so content inside it becomes
+ * visible.
+ */
+export function expandAncestorDetails(el: Element, boundary?: Element) {
let details = el.closest("details");
- while (details) {
+ while (details && (!boundary || boundary.contains(details))) {
if (!details.open) {
details.open = true;
}
@@ -11,8 +14,11 @@ export function expandAncestorDetails(el: Element) {
}
}
-/** Shows `el` wherever it is hidden: opens the `<details>` and shows the tabs that enclose it. */
-export function revealElement(el: Element) {
- expandAncestorDetails(el);
+/**
+ * Shows `el` wherever it is hidden: opens the `<details>` inside `boundary` and shows the tabs that
+ * enclose it. A text editor around `boundary` reveals its own blocks, as their open state is saved.
+ */
+export function revealElement(el: Element, boundary?: Element) {
+ expandAncestorDetails(el, boundary);
revealTab(el);
}
diff --git a/apps/client/src/widgets/find.ts b/apps/client/src/widgets/find.ts
index e4f3f58c80..0f50956ddb 100644
--- a/apps/client/src/widgets/find.ts
+++ b/apps/client/src/widgets/find.ts
@@ -373,6 +373,7 @@ export default class FindWidget extends NoteContextAwareWidget {
this.$currentFound.text(nextFound + 1);
await this.handler?.findNext(direction, currentFound, nextFound);
+ this.updateReplaceButton();
}
}
@@ -386,15 +387,37 @@ export default class FindWidget extends NoteContextAwareWidget {
return { totalFound: 0, currentFound: 0 };
}
const { totalFound, currentFound } = await this.handler.performFind(searchTerm, matchCase, wholeWord);
-
- this.$totalFound.text(totalFound);
- this.$currentFound.text(currentFound);
+ this.showResult({ totalFound, currentFound });
this.searchTerm = searchTerm;
return { totalFound, currentFound };
}
+ /**
+ * Marks the counters as out of date, as when the content of an embed changed, so that the next
+ * Enter searches again.
+ */
+ invalidateResults() {
+ if (this.$widget.is(":visible")) {
+ this.$totalFound.text("?");
+ }
+ }
+
+ private showResult({ totalFound, currentFound }: FindResult) {
+ this.$totalFound.text(totalFound);
+ this.$currentFound.text(currentFound);
+ this.updateReplaceButton();
+ }
+
+ /** Disables "Replace" while the current match is in content that cannot change. */
+ private updateReplaceButton() {
+ const canReplace = this.handler && "canReplace" in this.handler
+ ? this.handler.canReplace()
+ : true;
+ this.$replaceButton.prop("disabled", !canReplace);
+ }
+
async closeSearch() {
if (this.$widget.is(":visible")) {
this.$widget.hide();
@@ -413,14 +436,20 @@ export default class FindWidget extends NoteContextAwareWidget {
async replace() {
const replaceText = String(this.$replaceTextInput.val());
if (this.handler && "replace" in this.handler) {
- await this.handler.replace(replaceText);
+ const result = await this.handler.replace(replaceText);
+ if (result) {
+ this.showResult(result);
+ }
}
}
async replaceAll() {
const replaceText = String(this.$replaceTextInput.val());
if (this.handler && "replace" in this.handler) {
- await this.handler.replaceAll(replaceText);
+ const result = await this.handler.replaceAll(replaceText);
+ if (result) {
+ this.showResult(result);
+ }
}
}
diff --git a/apps/client/src/widgets/find_in_code.ts b/apps/client/src/widgets/find_in_code.ts
index 5dc8536ba6..c53566fb8f 100644
--- a/apps/client/src/widgets/find_in_code.ts
+++ b/apps/client/src/widgets/find_in_code.ts
@@ -1,8 +1,11 @@
// 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
+import type VanillaCodeMirror from "@triliumnext/codemirror";
+
import utils from "../services/utils.js";
import type FindWidget from "./find.js";
+import type { FindOptions, FindTarget } from "./merged_find";
const FIND_RESULT_SELECTED_CSS_CLASSNAME = "ck-find-result_selected";
const FIND_RESULT_CSS_CLASSNAME = "ck-find-result";
@@ -88,3 +91,88 @@ export default class FindInCode {
}
}
+
+/** Searches a code editor, such as the editor of a code note in an embed. */
+export class CodeMirrorFindTarget implements FindTarget {
+
+ private search: { term: string; options: FindOptions } | null = null;
+
+ constructor(private readonly view: VanillaCodeMirror) {}
+
+ async find(term: string, options: FindOptions) {
+ this.search = { term, options };
+ if (!this.isAlive()) {
+ return 0;
+ }
+
+ const { totalFound } = await this.view.performFind(
+ term, options.matchCase, options.wholeWord, false
+ );
+ return totalFound;
+ }
+
+ highlight(index: number | null) {
+ if (!this.isAlive()) {
+ return;
+ }
+
+ if (index === null) {
+ this.view.clearActiveMatch();
+ } else {
+ void this.view.findNext(0, 0, index);
+ }
+ }
+
+ getFirstMatchBelow(top: number) {
+ const { view } = this;
+ const index = view.getSearchMatches()
+ .findIndex((match) => view.lineBlockAt(match.from).top + view.documentTop >= top);
+ return index >= 0 ? index : null;
+ }
+
+ canReplace() {
+ return true;
+ }
+
+ async replace(index: number, text: string) {
+ if (this.isAlive()) {
+ await this.view.findNext(0, 0, index);
+ await this.view.replace(text);
+ }
+ return this.searchAgain();
+ }
+
+ async replaceAll(text: string) {
+ if (this.isAlive()) {
+ await this.view.replaceAll(text);
+ }
+ return this.searchAgain();
+ }
+
+ close(index: number | null) {
+ if (!this.isAlive()) {
+ return false;
+ }
+
+ const match = index === null ? undefined : this.view.getSearchMatches()[index];
+ this.view.cleanSearch();
+ if (!match) {
+ return false;
+ }
+
+ this.view.dispatch({ selection: { anchor: match.from, head: match.to } });
+ this.view.focus();
+ return true;
+ }
+
+ /** Searches again after a replace, whose matches the editor does not follow. */
+ private async searchAgain() {
+ return this.search ? this.find(this.search.term, this.search.options) : 0;
+ }
+
+ /** Whether the editor is still in the page, which a destroyed one leaves. */
+ private isAlive() {
+ return this.view.dom.isConnected;
+ }
+
+}
diff --git a/apps/client/src/widgets/find_in_html.spec.ts b/apps/client/src/widgets/find_in_html.spec.ts
index 4a9d2f5990..78a7ebab21 100644
--- a/apps/client/src/widgets/find_in_html.spec.ts
+++ b/apps/client/src/widgets/find_in_html.spec.ts
@@ -1,7 +1,26 @@
import { applyTabs } from "@triliumnext/ckeditor5/src/plugins/tabs/tabs_read_only.js";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import FindInHtml from "./find_in_html.js";
+import type FindWidget from "./find";
+import FindInHtml, { HtmlFindTarget, HtmlNoteFindTarget } from "./find_in_html.js";
+import MergedFind from "./merged_find";
+import { registerEmbedFindTarget } from "./type_widgets/text/content_embed_tools";
+
+const OPTIONS = { matchCase: false, wholeWord: false };
+const CONTENT = "<p>needle before</p>"
+ + "<figure class=\"include-note\"><div class=\"include-note-wrapper\">"
+ + "<div class=\"include-note-title-row\">needle title</div>"
+ + "<div class=\"include-note-content\">"
+ + "<details><summary>s</summary><p>needle inside</p></details>"
+ + "</div></div><figcaption>needle caption</figcaption></figure>"
+ + "<details><summary>s</summary><p>needle hidden</p></details>";
+
+const cleanups: (() => void)[] = [];
+
+afterEach(() => {
+ for (const cleanup of cleanups.splice(0)) cleanup();
+ document.body.replaceChildren();
+});
/**
* Builds a FindInHtml wired to a real (happy-dom) content element, so mark.js can mutate it.
@@ -15,7 +34,8 @@ function setup(html: string) {
const parent = {
noteContext: {
getContentElement: async () => $(container)
- }
+ },
+ invalidateResults: vi.fn()
} as any;
return { finder: new FindInHtml(parent), container };
@@ -53,22 +73,16 @@ describe("FindInHtml", () => {
expect(container.querySelectorAll(".find-result-secondary").length).toBe(2);
});
- it("findBoxClosed unmarks the shared instance once, clearing primary + secondary together", async () => {
+ it("findBoxClosed clears the primary and the secondary marks together", async () => {
const { finder, container } = setup("<p>alpha beta gamma</p>");
await finder.performFind("alpha", false, false);
await finder.highlightExtraTokens([ "beta" ]);
expect(container.querySelectorAll(".ck-find-result, .find-result-secondary").length).toBe(2);
- // Secondary marks reuse the same mark.js instance as the seed pass, so a single unmark()
- // in findBoxClosed clears both. (happy-dom can't actually unwrap mark.js spans, so the
- // cleanup is asserted at the call level rather than via the DOM.)
- const markInstance = (finder as unknown as { mark: { unmark: () => void } }).mark;
- const unmarkSpy = vi.spyOn(markInstance, "unmark");
-
await finder.findBoxClosed(1, 0);
- expect(unmarkSpy).toHaveBeenCalledTimes(1);
+ expect(container.innerHTML).toBe("<p>alpha beta gamma</p>");
});
it("highlightExtraTokens is a no-op before a find has run (no mark instance yet)", async () => {
@@ -109,4 +123,100 @@ describe("FindInHtml", () => {
expect(result.totalFound).toBe(1);
expect(activeTitle()).toBe("B");
});
+
+ it("drives the find bar, and marks it stale as embeds change", async () => {
+ const { content, embed } = mount();
+ const parent = {
+ noteContext: { getContentElement: async () => [ content ] },
+ invalidateResults: vi.fn()
+ };
+ const handler = new FindInHtml(parent as unknown as FindWidget);
+
+ expect(await handler.performFind("needle", false, false))
+ .toEqual({ totalFound: 3, currentFound: 1 });
+ await handler.findNext(1, 1, 2);
+ const selected = content.querySelector(".ck-find-result_selected");
+ expect(selected?.closest("details")?.open).toBe(true);
+ await handler.highlightExtraTokens([ "before", "" ]);
+ expect(content.querySelector(".find-result-secondary")?.textContent).toBe("before");
+
+ cleanups.push(registerEmbedFindTarget(embed, new HtmlFindTarget(embed)));
+ expect(parent.invalidateResults).toHaveBeenCalledOnce();
+ await handler.findBoxClosed(3, 3);
+ expect(content.querySelector(".ck-find-result, .find-result-secondary")).toBeNull();
+ cleanups.push(registerEmbedFindTarget(content, new HtmlFindTarget(content)));
+ expect(parent.invalidateResults).toHaveBeenCalledOnce();
+ });
});
+
+describe("HtmlNoteFindTarget", () => {
+ it("searches the content of a note around its embeds, and reveals a match", async () => {
+ const { content, embed } = mount();
+ const target = new HtmlNoteFindTarget(content);
+
+ expect(await target.find("needle", OPTIONS)).toBe(3);
+ expect(embed.querySelectorAll(".include-note-wrapper .ck-find-result")).toHaveLength(0);
+ expect(target.getEmbeds()).toEqual([ embed ]);
+ expect(target.countMatchesBefore(embed)).toBe(1);
+ expect(target.canReplace()).toBe(false);
+ expect(await target.replaceAll()).toBe(3);
+
+ target.highlight(2);
+ const selected = content.querySelector(".ck-find-result_selected");
+ expect(selected?.textContent).toBe("needle");
+ expect(selected?.closest("details")?.open).toBe(true);
+ expect(target.getFirstMatchBelow(-Infinity)).toBe(0);
+ expect(target.getFirstMatchBelow(Infinity)).toBeNull();
+ target.highlight(null);
+ expect(content.querySelector(".ck-find-result_selected")).toBeNull();
+
+ expect(target.close()).toBe(false);
+ expect(content.querySelector(".ck-find-result")).toBeNull();
+ expect(await target.find("", OPTIONS)).toBe(0);
+ });
+
+ it("leaves the matches of an embed to the target of its content", async () => {
+ const { content, embed } = mount();
+ const box = embed.querySelector<HTMLElement>(".include-note-content");
+ if (!box) throw new Error("The embed has no content box.");
+ cleanups.push(registerEmbedFindTarget(box, new HtmlFindTarget(box)));
+ const find = new MergedFind(new HtmlNoteFindTarget(content));
+
+ expect(await find.find("needle", OPTIONS)).toBe(4);
+ expect(box.querySelectorAll(".ck-find-result")).toHaveLength(1);
+
+ find.highlight(1);
+ expect(box.querySelector("details")?.open).toBe(true);
+ expect(content.querySelector<HTMLDetailsElement>(":scope > details")?.open).toBe(false);
+ });
+
+ it("opens a collapsed block around an embed, and no block around its own content", async () => {
+ document.body.innerHTML = "<details><summary>s</summary><div class=\"content\">"
+ + "<figure class=\"include-note\"><div class=\"inner\"><p>needle</p></div></figure>"
+ + "</div></details>";
+ const outer = document.querySelector("details");
+ const content = document.querySelector<HTMLElement>(".content");
+ const inner = document.querySelector<HTMLElement>(".inner");
+ const embed = document.querySelector<HTMLElement>(".include-note");
+ if (!outer || !content || !inner || !embed) throw new Error("Incomplete fixture.");
+
+ const innerTarget = new HtmlFindTarget(inner);
+ await innerTarget.find("needle", OPTIONS);
+ innerTarget.highlight(0);
+ expect(outer.open).toBe(false);
+
+ new HtmlNoteFindTarget(content).revealEmbed(embed);
+ expect(outer.open).toBe(false);
+ new HtmlNoteFindTarget(document.body).revealEmbed(embed);
+ expect(outer.open).toBe(true);
+ });
+});
+
+function mount() {
+ const content = document.createElement("div");
+ content.innerHTML = CONTENT;
+ document.body.append(content);
+ const embed = content.querySelector<HTMLElement>(".include-note");
+ if (!embed) throw new Error("The content has no embed.");
+ return { content, embed };
+}
diff --git a/apps/client/src/widgets/find_in_html.ts b/apps/client/src/widgets/find_in_html.ts
index 67b5aac2cf..e982f31d0f 100644
--- a/apps/client/src/widgets/find_in_html.ts
+++ b/apps/client/src/widgets/find_in_html.ts
@@ -6,7 +6,10 @@ import type Mark from "mark.js";
import { revealElement } from "../services/collapsible.js";
import utils from "../services/utils.js";
import type FindWidget from "./find.js";
-import type { FindResult } from "./find.js";
+import MergedFind, {
+ type FindOptions, type FindTarget, getScrollingContainerTop, type HostFindTarget, toFindResult
+} from "./merged_find";
+import { watchEmbedFindTargets } from "./type_widgets/text/content_embed_tools";
const FIND_RESULT_SELECTED_CSS_CLASSNAME = "ck-find-result_selected";
const FIND_RESULT_CSS_CLASSNAME = "ck-find-result";
@@ -14,73 +17,39 @@ const FIND_RESULT_CSS_CLASSNAME = "ck-find-result";
// FindWidget's style block. Deliberately distinct from FIND_RESULT_CSS_CLASSNAME so these marks are
// not counted as primary matches and Enter/F3 keeps cycling only the seed.
const FIND_RESULT_SECONDARY_CSS_CLASSNAME = "find-result-secondary";
+// The content of an embed searches itself, and its title row is not searched.
+const EMBED_EXCLUSION = [ ".include-note-wrapper", ".include-note-wrapper *" ];
+/** "Search in note" in the rendered content of a note, such as a read-only text note. */
export default class FindInHtml {
private parent: FindWidget;
- private currentIndex: number;
- private $results: JQuery<HTMLElement> | null;
- private mark?: Mark;
+ private target: HtmlNoteFindTarget | null = null;
+ private find: MergedFind | null = null;
+ private current: number | null = null;
+ private stopWatching: (() => void) | null = null;
constructor(parent: FindWidget) {
this.parent = parent;
- this.currentIndex = 0;
- this.$results = null;
}
async performFind(searchTerm: string, matchCase: boolean, wholeWord: boolean) {
const $content = await this.parent?.noteContext?.getContentElement();
- if (!$content || !$content.length) {
- return Promise.resolve({ totalFound: 0, currentFound: 0 });
+ const content = $content?.[0];
+ if (!content) {
+ return toFindResult(0, null);
}
- if (!this.mark) {
- this.mark = new (await import("mark.js")).default($content[0]);
- }
+ const find = this.getFind(content);
+ const totalFound = await find.find(searchTerm, { matchCase, wholeWord });
+ this.current = totalFound ? find.getStartMatch(getScrollingContainerTop(content)) : null;
+ find.highlight(this.current);
+ return toFindResult(totalFound, this.current);
+ }
- const wholeWordChar = wholeWord ? "\\b" : "";
- const regExp = new RegExp(wholeWordChar + utils.escapeRegExp(searchTerm) + wholeWordChar, matchCase ? "g" : "gi");
-
- return new Promise<FindResult>((res) => {
- this.mark!.unmark({
- done: () => {
- this.mark!.markRegExp(regExp, {
- element: "span",
- className: FIND_RESULT_CSS_CLASSNAME,
- done: async () => {
- this.$results = $content.find(`.${FIND_RESULT_CSS_CLASSNAME}`);
- const scrollingContainer = $content[0].closest('.scrolling-container');
- const containerTop = scrollingContainer?.getBoundingClientRect().top ?? 0;
- const closestIndex = this.$results.toArray().findIndex(el => el.getBoundingClientRect().top >= containerTop);
- this.currentIndex = closestIndex >= 0 ? closestIndex : 0;
-
- await this.jumpTo();
-
- res({
- totalFound: this.$results.length,
- currentFound: this.$results.length > 0 ? this.currentIndex + 1 : 0
- });
- }
- });
- }
- });
- });
- }
-
- async findNext(direction: -1 | 1, currentFound: number, nextFound: number) {
- if (this.$results?.length) {
- this.currentIndex += direction;
-
- if (this.currentIndex < 0) {
- this.currentIndex = this.$results.length - 1;
- }
-
- if (this.currentIndex > this.$results.length - 1) {
- this.currentIndex = 0;
- }
-
- await this.jumpTo();
- }
+ async findNext(_direction: -1 | 1, _currentFound: number, nextFound: number) {
+ this.current = nextFound;
+ this.find?.highlight(nextFound);
}
/**
@@ -89,42 +58,178 @@ export default class FindInHtml {
* only the primary (seed) matches counted by {@link performFind}.
*
* Only this read-only HTML handler supports the multi-token pass; the editable CKEditor and
- * CodeMirror handlers stay seed-only, because their find engines highlight a single term. These
- * marks reuse the mark.js instance created by {@link performFind}, so any later `unmark()`
- * clears them too. mark.js escapes each keyword, so a regex metacharacter cannot inject.
+ * CodeMirror handlers stay seed-only, because their find engines highlight a single term.
+ */
+ async highlightExtraTokens(tokens: string[]) {
+ await this.target?.highlightExtraTokens(tokens);
+ }
+
+ async findBoxClosed(_totalFound: number, _currentFound: number) {
+ this.stopWatching?.();
+ this.stopWatching = null;
+ this.find?.close(null);
+ this.current = null;
+ }
+
+ /** The search of `content`, which follows the embeds that it holds. */
+ private getFind(content: HTMLElement) {
+ if (!this.find || this.target?.root !== content) {
+ this.find?.close(null);
+ this.stopWatching?.();
+ this.stopWatching = null;
+ this.target = new HtmlNoteFindTarget(content);
+ this.find = new MergedFind(this.target);
+ }
+
+ this.stopWatching ??= watchEmbedFindTargets(content, () => this.parent.invalidateResults());
+ return this.find;
+ }
+
+}
+
+/** Searches rendered content, which it cannot change, by marking up its matches. */
+export class HtmlFindTarget implements FindTarget {
+
+ private mark: Mark | null = null;
+ protected matches: HTMLElement[] = [];
+ /** The elements that wrap the matches and the extra tokens, which `unmark()` removes. */
+ private markElements: HTMLElement[] = [];
+ private current: HTMLElement | null = null;
+
+ /** Searches `root`, apart from the elements that the `exclude` selectors match. */
+ constructor(readonly root: HTMLElement, private readonly exclude: string[] = []) {}
+
+ async find(term: string, { matchCase, wholeWord }: FindOptions) {
+ const mark = await this.getMark();
+ this.unmark();
+ if (!term) {
+ return 0;
+ }
+
+ const wholeWordChar = wholeWord ? "\\b" : "";
+ const regExp = new RegExp(
+ wholeWordChar + utils.escapeRegExp(term) + wholeWordChar,
+ matchCase ? "g" : "gi"
+ );
+ await new Promise<void>((done) => mark.markRegExp(regExp, {
+ element: "span",
+ className: FIND_RESULT_CSS_CLASSNAME,
+ exclude: this.exclude,
+ each: (element) => this.addMarkElement(element, this.matches),
+ done: () => done()
+ }));
+ return this.matches.length;
+ }
+
+ highlight(index: number | null) {
+ this.current?.classList.remove(FIND_RESULT_SELECTED_CSS_CLASSNAME);
+ this.current = index === null ? null : this.matches[index] ?? null;
+ if (!this.current) {
+ return;
+ }
+
+ // Reveal matches inside collapsed <details> and inactive tabs, like native find-in-page.
+ // Must precede scrollIntoView so the target is laid out first (#10616).
+ revealElement(this.current, this.root);
+ this.current.scrollIntoView({ block: "center", inline: "center" });
+ this.current.classList.add(FIND_RESULT_SELECTED_CSS_CLASSNAME);
+ }
+
+ getFirstMatchBelow(top: number) {
+ const index = this.matches.findIndex((match) => match.getBoundingClientRect().top >= top);
+ return index >= 0 ? index : null;
+ }
+
+ canReplace() {
+ return false;
+ }
+
+ async replace() {
+ return this.matches.length;
+ }
+
+ async replaceAll() {
+ return this.matches.length;
+ }
+
+ close() {
+ this.unmark();
+ return false;
+ }
+
+ /**
+ * Highlights `tokens` with the muted secondary style, which the primary matches keep
+ * cycling through. mark.js escapes each keyword, so a regex metacharacter cannot inject.
*/
async highlightExtraTokens(tokens: string[]) {
- const mark = this.mark;
const cleaned = tokens.filter((token) => token.length > 0);
- if (!mark || cleaned.length === 0) {
+ if (!this.mark || cleaned.length === 0) {
return;
}
- return new Promise<void>((res) => {
- mark.mark(cleaned, {
- element: "span",
- className: FIND_RESULT_SECONDARY_CSS_CLASSNAME,
- separateWordSearch: false,
- done: () => res()
- });
- });
- }
-
- async findBoxClosed(totalFound: number, currentFound: number) {
- // A single unmark() clears both the primary (seed) marks and any secondary marks from
- // highlightExtraTokens, since they share this mark.js instance.
- this.mark?.unmark();
- }
-
- async jumpTo() {
- if (this.$results?.length) {
- const $current = this.$results.eq(this.currentIndex);
- this.$results.removeClass(FIND_RESULT_SELECTED_CSS_CLASSNAME);
- // Reveal matches inside collapsed <details> and inactive tabs, like native find-in-page.
- // Must precede scrollIntoView so the target is laid out first (#10616).
- revealElement($current[0]);
- $current[0].scrollIntoView({ block: 'center', inline: 'center'});
- $current.addClass(FIND_RESULT_SELECTED_CSS_CLASSNAME);
+ const { mark } = this;
+ await new Promise<void>((done) => mark.mark(cleaned, {
+ element: "span",
+ className: FIND_RESULT_SECONDARY_CSS_CLASSNAME,
+ separateWordSearch: false,
+ exclude: this.exclude,
+ each: (element) => this.addMarkElement(element),
+ done: () => done()
+ }));
+ }
+
+ private async getMark() {
+ this.mark ??= new (await import("mark.js")).default(this.root);
+ return this.mark;
+ }
+
+ private addMarkElement(element: Element, list?: HTMLElement[]) {
+ if (element instanceof HTMLElement) {
+ this.markElements.push(element);
+ list?.push(element);
+ }
+ }
+
+ /**
+ * Unwraps the elements of this target only. `Mark.unmark()` would remove the marks of every
+ * target in its root, such as those of the embeds in a note.
+ */
+ private unmark() {
+ for (const element of this.markElements) {
+ const parent = element.parentNode;
+ if (!parent) continue;
+
+ element.replaceWith(...element.childNodes);
+ parent.normalize();
+ }
+ this.markElements = [];
+ this.matches = [];
+ this.current = null;
+ }
+
+}
+
+/** Searches the rendered content of a note, whose embeds search their own content. */
+export class HtmlNoteFindTarget extends HtmlFindTarget implements HostFindTarget {
+
+ constructor(root: HTMLElement) {
+ super(root, EMBED_EXCLUSION);
+ }
+
+ getEmbeds() {
+ return [ ...this.root.querySelectorAll<HTMLElement>(".include-note") ]
+ .filter((embed) => !embed.parentElement?.closest(".include-note"));
+ }
+
+ countMatchesBefore(embed: HTMLElement) {
+ return this.matches.filter(
+ (match) => embed.compareDocumentPosition(match) & Node.DOCUMENT_POSITION_PRECEDING
+ ).length;
+ }
+
+ revealEmbed(embed: HTMLElement | null) {
+ if (embed) {
+ revealElement(embed, this.root);
}
}
}
diff --git a/apps/client/src/widgets/find_in_text.spec.ts b/apps/client/src/widgets/find_in_text.spec.ts
new file mode 100644
index 0000000000..4814d39390
--- /dev/null
+++ b/apps/client/src/widgets/find_in_text.spec.ts
@@ -0,0 +1,174 @@
+import type { CKTextEditor } from "@triliumnext/ckeditor5";
+import FindReveal from "@triliumnext/ckeditor5/src/plugins/find_reveal.js";
+import {
+ ClassicEditor, type Editor, Essentials, FindAndReplaceEditing, Paragraph
+} from "ckeditor5";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type FindWidget from "./find";
+import FindInText, { TextEditorFindTarget } from "./find_in_text";
+import MergedFind, { type FindTarget } from "./merged_find";
+import { registerEmbedFindTarget } from "./type_widgets/text/content_embed_tools";
+
+const OPTIONS = { matchCase: false, wholeWord: false };
+const CONTENT = "<p>needle one</p>"
+ + "<figure class=\"include-note\"><figcaption>needle caption</figcaption></figure>"
+ + "<p>needle two</p>";
+
+let editor: ClassicEditor;
+let cleanups: (() => void)[];
+
+beforeEach(async () => {
+ const element = document.createElement("div");
+ document.body.append(element);
+ editor = await ClassicEditor.create(element, {
+ licenseKey: "GPL",
+ plugins: [ Essentials, Paragraph, FindAndReplaceEditing, FindReveal, EmbedSchema ]
+ });
+ editor.setData(CONTENT);
+ cleanups = [];
+});
+
+afterEach(async () => {
+ for (const cleanup of cleanups) cleanup();
+ if (editor.state !== "destroyed") await editor.destroy();
+ document.body.replaceChildren();
+});
+
+describe("TextEditorFindTarget", () => {
+ it("places the matches of an embed between the text before it and its caption", async () => {
+ const embedTarget = registerEmbedTarget(2);
+ const find = new MergedFind(new TextEditorFindTarget(asTextEditor(editor)));
+
+ expect(await find.find("needle", OPTIONS)).toBe(5);
+
+ find.highlight(0);
+ expect(highlightedText()).toBe("needle one");
+ find.highlight(2);
+ expect(embedTarget.highlight).toHaveBeenLastCalledWith(1);
+ expect(highlightedText()).toBeNull();
+ expect(editor.plugins.get(FindReveal).position?.path).toEqual([ 1, 0 ]);
+ find.highlight(3);
+ expect(highlightedText()).toBe("needle caption");
+ find.highlight(4);
+ expect(highlightedText()).toBe("needle two");
+ expect(embedTarget.highlight).toHaveBeenLastCalledWith(null);
+ });
+
+ it("starts at a match at the selection, or at the first match below a line", async () => {
+ const target = new TextEditorFindTarget(asTextEditor(editor));
+ await target.find("needle", OPTIONS);
+ expect(target.getSelectedMatch()).toBeNull();
+ expect(target.getFirstMatchBelow(-Infinity)).toBe(0);
+ expect(target.getFirstMatchBelow(Infinity)).toBeNull();
+
+ const lastParagraph = editor.model.document.getRoot()?.getChild(2);
+ if (!lastParagraph?.is("element")) throw new Error("Expected a third paragraph.");
+ editor.model.change((writer) => writer.setSelection(lastParagraph, "in"));
+ expect(target.getSelectedMatch()).toBe(2);
+ });
+
+ it("replaces one match or all of them, and closes on a match", async () => {
+ const target = new TextEditorFindTarget(asTextEditor(editor));
+ await target.find("needle", OPTIONS);
+
+ expect(target.canReplace(0)).toBe(true);
+ expect(target.canReplace(3)).toBe(false);
+ expect(await target.replace(0, "pin")).toBe(2);
+ expect(editor.getData()).toContain("<p>pin one</p>");
+ expect(await target.replaceAll("pin")).toBe(0);
+ expect(editor.getData()).not.toContain("needle");
+
+ await target.find("pin", OPTIONS);
+ // happy-dom has no layout to scroll.
+ const scroll = vi.spyOn(editor.editing.view, "scrollToTheSelection")
+ .mockImplementation(() => {});
+ expect(target.close(2)).toBe(true);
+ expect(scroll).toHaveBeenCalledOnce();
+ const selection = editor.model.document.selection.getFirstRange();
+ expect(selection?.start.path).toEqual([ 2, 0 ]);
+ expect(selection?.end.path).toEqual([ 2, 3 ]);
+ expect(editor.plugins.get(FindAndReplaceEditing).state?.results.length).toBe(0);
+ expect(target.close(null)).toBe(false);
+ });
+
+ it("finds nothing once its editor is destroyed", async () => {
+ const target = new TextEditorFindTarget(asTextEditor(editor));
+ await editor.destroy();
+
+ expect(await target.find("needle", OPTIONS)).toBe(0);
+ expect(target.getEmbeds()).toEqual([]);
+ expect(() => target.highlight(0)).not.toThrow();
+ expect(() => target.revealEmbed(null)).not.toThrow();
+ expect(target.close(null)).toBe(false);
+ });
+});
+
+describe("FindInText", () => {
+ it("drives the find bar, and marks it stale as embeds change", async () => {
+ const parent = {
+ noteContext: { getTextEditor: async () => editor },
+ invalidateResults: vi.fn()
+ };
+ const handler = new FindInText(parent as unknown as FindWidget);
+ registerEmbedTarget(1, false);
+
+ expect(await handler.performFind("needle", false, false))
+ .toEqual({ totalFound: 4, currentFound: 1 });
+ await handler.findNext(1, 0, 1);
+ expect(handler.canReplace()).toBe(false);
+ await handler.findNext(1, 1, 3);
+ expect(handler.canReplace()).toBe(true);
+ expect(await handler.replace("pin")).toEqual({ totalFound: 3, currentFound: 1 });
+ expect(editor.getData()).toContain("<p>pin two</p>");
+ expect(await handler.replaceAll("pin")).toEqual({ totalFound: 1, currentFound: 1 });
+
+ registerEmbedTarget(0);
+ expect(parent.invalidateResults).toHaveBeenCalledOnce();
+ await handler.findBoxClosed(1, 1);
+ registerEmbedTarget(0);
+ expect(parent.invalidateResults).toHaveBeenCalledOnce();
+ });
+});
+
+/** A `contentEmbed` with a caption, as the editor saves an embed. */
+function EmbedSchema(target: Editor) {
+ target.model.schema.register("contentEmbed", { inheritAllFrom: "$blockObject" });
+ target.model.schema.register("caption", {
+ allowIn: "contentEmbed", allowContentOf: "$block", isLimit: true
+ });
+ target.conversion.elementToElement({
+ model: "contentEmbed", view: { name: "figure", classes: "include-note" }
+ });
+ target.conversion.elementToElement({ model: "caption", view: "figcaption" });
+}
+
+/** Lets a fake target with `count` matches search the embed of the editor. */
+function registerEmbedTarget(count: number, isEditable = true) {
+ const embed = editor.editing.view.getDomRoot()?.querySelector<HTMLElement>(".include-note");
+ if (!embed) throw new Error("The editor shows no embed.");
+ const target = {
+ find: vi.fn(async () => count),
+ highlight: vi.fn((_index: number | null) => {}),
+ getFirstMatchBelow: () => null,
+ canReplace: () => isEditable,
+ replace: async () => count,
+ replaceAll: async () => count,
+ close: () => false
+ } satisfies FindTarget;
+ cleanups.push(registerEmbedFindTarget(embed, target));
+ return target;
+}
+
+/** The text of the block that holds the highlighted match, or `null` without one. */
+function highlightedText() {
+ const state = editor.plugins.get(FindAndReplaceEditing).state;
+ const block = state?.highlightedResult?.marker?.getStart().parent;
+ if (!block?.is("element")) return null;
+ return [ ...block.getChildren() ]
+ .map((child) => (child.is("$text") ? child.data : "")).join("");
+}
+
+function asTextEditor(textEditor: ClassicEditor) {
+ return textEditor as unknown as CKTextEditor;
+}
diff --git a/apps/client/src/widgets/find_in_text.ts b/apps/client/src/widgets/find_in_text.ts
index 049dd9f215..560d3c5508 100644
--- a/apps/client/src/widgets/find_in_text.ts
+++ b/apps/client/src/widgets/find_in_text.ts
@@ -1,12 +1,19 @@
-import type { FindAndReplaceState, FindCommandResult } from "@triliumnext/ckeditor5";
-import type { FindResult } from "./find.js";
+import type { CKTextEditor, FindResultType, ModelElement } from "@triliumnext/ckeditor5";
+
import type FindWidget from "./find.js";
+import MergedFind, {
+ type FindOptions, getScrollingContainerTop, type HostFindTarget, toFindResult
+} from "./merged_find";
+import { watchEmbedFindTargets } from "./type_widgets/text/content_embed_tools";
+/** "Search in note" in an editable text note, with the content of its embeds. */
export default class FindInText {
private parent: FindWidget;
- private findResult?: FindCommandResult | null;
- private editingState?: FindAndReplaceState;
+ private target: TextEditorFindTarget | null = null;
+ private find: MergedFind | null = null;
+ private current: number | null = null;
+ private stopWatching: (() => void) | null = null;
constructor(parent: FindWidget) {
this.parent = parent;
@@ -16,133 +23,245 @@ export default class FindInText {
return this.parent?.noteContext?.getTextEditor();
}
- async performFind(searchTerm: string, matchCase: boolean, wholeWord: boolean): Promise<FindResult> {
- // Do this even if the searchTerm is empty so the markers are cleared and
- // the counters updated
+ async performFind(searchTerm: string, matchCase: boolean, wholeWord: boolean) {
const textEditor = await this.getTextEditor();
if (!textEditor) {
- return { currentFound: 0, totalFound: 0 };
- }
-
- const model = textEditor.model;
- let findResult: FindCommandResult | null = null;
- let totalFound = 0;
- let currentFound = -1;
-
- // Clear
- const findAndReplaceEditing = textEditor.plugins.get("FindAndReplaceEditing");
- findAndReplaceEditing.state?.clear(model);
- findAndReplaceEditing.stop();
- this.editingState = findAndReplaceEditing.state;
- if (searchTerm !== "") {
- // 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
- // searchTerm = escapeRegExp(searchTerm);
- // let re = new RegExp(searchTerm, 'gi');
- // let m = text.match(re);
- // totalFound = m ? m.length : 0;
- const options = { matchCase: matchCase, wholeWords: wholeWord };
- findResult = textEditor.execute("find", searchTerm, options);
- totalFound = findResult.results.length;
- const selection = model.document.selection;
- // If text is selected, highlight the corresponding result;
- // otherwise, highlight the first visible result in the scrolling container.
- if (!selection.isCollapsed) {
- const cursorPos = selection.getFirstPosition();
- for (let i = 0; i < findResult.results.length; ++i) {
- const marker = findResult.results.get(i)?.marker;
- const fromPos = marker?.getStart();
- if (cursorPos && fromPos?.compareWith(cursorPos) !== "before") {
- currentFound = i;
- break;
- }
- }
- } else {
- const editorEl = textEditor?.sourceElement;
- const findResultElement = editorEl?.querySelectorAll(".ck-find-result");
- const scrollingContainer = editorEl?.closest('.scrolling-container');
- const containerTop = scrollingContainer?.getBoundingClientRect().top ?? 0;
- const closestIndex = Array.from(findResultElement ?? []).findIndex((el: Element) => el.getBoundingClientRect().top >= containerTop);
- currentFound = closestIndex >= 0 ? closestIndex : 0;
- }
+ return toFindResult(0, null);
}
- this.findResult = findResult;
+ const find = this.getFind(textEditor);
+ const totalFound = await find.find(searchTerm, { matchCase, wholeWord });
+ this.current = totalFound
+ ? find.getStartMatch(getScrollingContainerTop(textEditor.sourceElement))
+ : null;
+ find.highlight(this.current);
+ return toFindResult(totalFound, this.current);
+ }
- // Calculate curfound if not already, highlight it as
- // selected
- if (totalFound > 0) {
- currentFound = Math.max(0, currentFound);
- // 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 < currentFound; ++i) {
- textEditor?.execute("findNext");
- }
+ async findNext(_direction: number, _currentFound: number, nextFound: number) {
+ this.current = nextFound;
+ this.find?.highlight(nextFound);
+ }
+
+ /** Whether "Replace" replaces the current match, which a match in read-only content is not. */
+ canReplace() {
+ return this.current !== null && !!this.find?.canReplace(this.current);
+ }
+
+ async replace(replaceText: string) {
+ const { find, current } = this;
+ if (!find || current === null) {
+ return;
}
- return {
- totalFound,
- currentFound: Math.min(currentFound + 1, totalFound)
- };
+ const totalFound = await find.replace(current, replaceText);
+ // The match after the replaced one takes its number.
+ this.current = totalFound ? current % totalFound : null;
+ find.highlight(this.current);
+ return toFindResult(totalFound, this.current);
}
- async findNext(direction: number, currentFound: number, nextFound: number) {
- const textEditor = await this.getTextEditor();
+ async replaceAll(replaceText: string) {
+ const { find } = this;
+ if (!find) {
+ return;
+ }
+
+ const totalFound = await find.replaceAll(replaceText);
+ this.current = totalFound ? Math.min(this.current ?? 0, totalFound - 1) : null;
+ find.highlight(this.current);
+ return toFindResult(totalFound, this.current);
+ }
- // 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 (direction > 0) {
- textEditor?.execute("findNext");
- } else {
- textEditor?.execute("findPrevious");
+ async findBoxClosed(_totalFound: number, _currentFound: number) {
+ this.stopWatching?.();
+ this.stopWatching = null;
+ const isFocused = this.find?.close(this.current) ?? false;
+ this.current = null;
+ if (!isFocused) {
+ (await this.getTextEditor())?.focus();
}
}
- async findBoxClosed(totalFound: number, currentFound: number) {
- const textEditor = await this.getTextEditor();
- if (!textEditor) {
- return;
+ /** The search of `textEditor`, which follows the embeds that it holds. */
+ private getFind(textEditor: CKTextEditor) {
+ if (!this.find || this.target?.editor !== textEditor) {
+ this.find?.close(null);
+ this.stopWatching?.();
+ this.stopWatching = null;
+ this.target = new TextEditorFindTarget(textEditor);
+ this.find = new MergedFind(this.target);
}
- if (totalFound > 0) {
- // Clear the markers and set the caret to the
- // current occurrence
- const model = textEditor.model;
- const range = this.findResult?.results?.get(currentFound)?.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();
- if (range) {
- model.change((writer) => {
- writer.setSelection(range);
- });
- }
- textEditor.editing.view.scrollToTheSelection();
+ const root = textEditor.editing.view.getDomRoot();
+ if (!this.stopWatching && root) {
+ this.stopWatching = watchEmbedFindTargets(root, () => this.parent.invalidateResults());
}
+ return this.find;
+ }
+
+}
+
+/** Searches a text editor with its find and replace commands. */
+export class TextEditorFindTarget implements HostFindTarget {
+
+ /** The matches, sorted by position: the find commands keep them in no particular order. */
+ private results: FindResultType[] = [];
+ private embeds = new Map<HTMLElement, ModelElement>();
+
+ constructor(readonly editor: CKTextEditor) {}
- this.findResult = null;
+ async find(term: string, { matchCase, wholeWord }: FindOptions) {
+ const finder = this.getFinder();
+ this.results = [];
+ finder?.stop();
+ if (!finder || !term) {
+ return 0;
+ }
- textEditor.focus();
+ const { results } = this.editor.execute("find", term, { matchCase, wholeWords: wholeWord });
+ // `find` highlights its first match, and `MergedFind` picks the current one instead.
+ if (finder.state) {
+ finder.state.highlightedResult = null;
+ }
+ this.results = sortByPosition([ ...results ]);
+ return this.results.length;
}
- async replace(replaceText: string) {
- if (this.editingState !== undefined && this.editingState.highlightedResult !== null) {
- const textEditor = await this.getTextEditor();
- textEditor?.execute("replace", replaceText, this.editingState.highlightedResult);
+ highlight(index: number | null) {
+ const state = this.getFinder()?.state;
+ if (state) {
+ state.highlightedResult = index === null ? null : this.results[index] ?? null;
}
}
- async replaceAll(replaceText: string) {
- if (this.editingState !== undefined && this.editingState.results.length > 0) {
- const textEditor = await this.getTextEditor();
- textEditor?.execute("replaceAll", replaceText, this.editingState.results);
+ getFirstMatchBelow(top: number) {
+ const { mapper, view } = this.editor.editing;
+ const index = this.results.findIndex((result) => {
+ const range = result.marker?.getRange();
+ const domRange = range && view.domConverter.viewRangeToDom(mapper.toViewRange(range));
+ return !!domRange && domRange.getBoundingClientRect().top >= top;
+ });
+ return index >= 0 ? index : null;
+ }
+
+ getSelectedMatch() {
+ const selection = this.editor.model.document.selection;
+ const start = selection.getFirstPosition();
+ if (selection.isCollapsed || !start) {
+ return null;
}
+
+ const index = this.results.findIndex(
+ (result) => !result.marker?.getStart().isBefore(start)
+ );
+ return index >= 0 ? index : null;
+ }
+
+ canReplace(index: number) {
+ const result = this.results[index];
+ const { plugins } = this.editor;
+ return !!result && (
+ !plugins.has("FindInLinkWidgets") || plugins.get("FindInLinkWidgets").canReplace(result)
+ );
}
+
+ async replace(index: number, text: string) {
+ const result = this.results[index];
+ if (result) {
+ this.editor.execute("replace", text, result);
+ }
+ return this.readResults();
+ }
+
+ async replaceAll(text: string) {
+ const state = this.getFinder()?.state;
+ if (state) {
+ this.editor.execute("replaceAll", text, state.results);
+ }
+ return this.readResults();
+ }
+
+ close(index: number | null) {
+ const range = index === null ? undefined : this.results[index]?.marker?.getRange();
+ this.getFinder()?.stop();
+ this.results = [];
+ if (!range) {
+ return false;
+ }
+
+ this.editor.model.change((writer) => writer.setSelection(range));
+ this.editor.editing.view.scrollToTheSelection();
+ this.editor.focus();
+ return true;
+ }
+
+ getEmbeds() {
+ this.embeds.clear();
+ if (!this.isAlive()) {
+ return [];
+ }
+
+ const { model, editing } = this.editor;
+ for (const root of model.document.getRoots()) {
+ for (const item of model.createRangeIn(root).getItems()) {
+ if (!item.is("element", "contentEmbed")) continue;
+
+ const viewElement = editing.mapper.toViewElement(item);
+ const embed = viewElement && editing.view.domConverter.mapViewToDom(viewElement);
+ if (embed instanceof HTMLElement) {
+ this.embeds.set(embed, item);
+ }
+ }
+ }
+ return [ ...this.embeds.keys() ];
+ }
+
+ countMatchesBefore(embed: HTMLElement) {
+ const element = this.embeds.get(embed);
+ if (!element) {
+ return 0;
+ }
+
+ const contentStart = this.editor.model.createPositionAt(element, 0);
+ const index = this.results.findIndex(
+ (result) => !result.marker?.getStart().isBefore(contentStart)
+ );
+ return index >= 0 ? index : this.results.length;
+ }
+
+ revealEmbed(embed: HTMLElement | null) {
+ const element = embed ? this.embeds.get(embed) : undefined;
+ if (this.isAlive() && this.editor.plugins.has("FindReveal")) {
+ this.editor.plugins.get("FindReveal")
+ .show(element ? this.editor.model.createPositionAt(element, 0) : null);
+ }
+ }
+
+ /** Takes the matches that the find commands left, as a replace removes the ones it replaced. */
+ private readResults() {
+ const state = this.getFinder()?.state;
+ this.results = state ? sortByPosition([ ...state.results ]) : [];
+ return this.results.length;
+ }
+
+ /** The find plugin of the editor, or `null` once the editor is destroyed. */
+ private getFinder() {
+ return this.isAlive() ? this.editor.plugins.get("FindAndReplaceEditing") : null;
+ }
+
+ private isAlive() {
+ return this.editor.state !== "destroyed";
+ }
+
+}
+
+function sortByPosition(results: FindResultType[]) {
+ return results.sort((first, second) => {
+ const start = first.marker?.getStart();
+ const otherStart = second.marker?.getStart();
+ return start && otherStart ? POSITION_ORDER[start.compareWith(otherStart)] : 0;
+ });
}
+
+const POSITION_ORDER = { before: -1, same: 0, after: 1, different: 0 } as const;
diff --git a/apps/client/src/widgets/merged_find.spec.ts b/apps/client/src/widgets/merged_find.spec.ts
new file mode 100644
index 0000000000..d943c87c91
--- /dev/null
+++ b/apps/client/src/widgets/merged_find.spec.ts
@@ -0,0 +1,223 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import MergedFind, { type FindTarget, type HostFindTarget } from "./merged_find";
+import {
+ registerEmbedFindTarget, revealContentEmbed
+} from "./type_widgets/text/content_embed_tools";
+
+vi.mock("./type_widgets/text/content_embed_tools", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./type_widgets/text/content_embed_tools")>()),
+ revealContentEmbed: vi.fn()
+}));
+
+const OPTIONS = { matchCase: false, wholeWord: false };
+
+let log: string[];
+let cleanups: (() => void)[];
+
+beforeEach(() => {
+ log = [];
+ cleanups = [];
+ vi.mocked(revealContentEmbed).mockImplementation((embed, isRevealed) => {
+ log.push(`${embed.id}.box(${isRevealed})`);
+ });
+});
+
+afterEach(() => {
+ for (const cleanup of cleanups) cleanup();
+ document.body.replaceChildren();
+ vi.clearAllMocks();
+});
+
+describe("MergedFind", () => {
+ it("searches the host and the embeds that have a target as one document", async () => {
+ const { find, host, targets } = setUp();
+
+ expect(await find.find("needle", OPTIONS)).toBe(8);
+ expect(host.find).toHaveBeenCalledWith("needle", OPTIONS);
+ expect(targets.a.find).toHaveBeenCalledWith("needle", OPTIONS);
+
+ const order: string[] = [];
+ for (let index = 0; index < 8; index++) {
+ log = [];
+ find.highlight(index);
+ order.push(log.find((entry) => !entry.includes("null") && entry.includes(".highlight"))
+ ?? "");
+ }
+ expect(order).toEqual([
+ "host.highlight(0)", "host.highlight(1)", "a.highlight(0)", "a.highlight(1)",
+ "c.highlight(0)", "host.highlight(2)", "host.highlight(3)", "host.highlight(4)"
+ ]);
+ });
+
+ it("reveals the embed of a match before highlighting it, and hides it once left", async () => {
+ const { find } = setUp();
+ await find.find("needle", OPTIONS);
+
+ find.highlight(1);
+ log = [];
+ find.highlight(2);
+ expect(log).toEqual([
+ "host.revealEmbed(a)", "a.box(true)", "a.highlight(0)", "host.highlight(null)"
+ ]);
+
+ log = [];
+ find.highlight(4);
+ expect(log).toEqual([
+ "host.revealEmbed(c)", "c.box(true)", "c.highlight(0)",
+ "a.highlight(null)", "a.box(false)"
+ ]);
+
+ log = [];
+ find.highlight(5);
+ expect(log).toEqual([
+ "host.highlight(2)", "c.highlight(null)", "c.box(false)", "host.revealEmbed(null)"
+ ]);
+
+ log = [];
+ find.highlight(null);
+ expect(log).toEqual([ "host.highlight(null)" ]);
+ });
+
+ it("starts at the selection of the host, else at the first match below the top", async () => {
+ const { find, host, targets } = setUp();
+ await find.find("needle", OPTIONS);
+
+ host.getSelectedMatch = () => 3;
+ expect(find.getStartMatch(100)).toBe(6);
+
+ host.getSelectedMatch = () => null;
+ host.firstBelow = 2;
+ targets.a.firstBelow = 1;
+ expect(find.getStartMatch(100)).toBe(3);
+ expect(targets.a.getFirstMatchBelow).toHaveBeenCalledWith(100);
+
+ host.firstBelow = null;
+ targets.a.firstBelow = null;
+ expect(find.getStartMatch(100)).toBe(0);
+ });
+
+ it("replaces matches only where the content can change", async () => {
+ const { find, host, targets } = setUp({ isAReadOnly: true });
+ await find.find("needle", OPTIONS);
+
+ expect(find.canReplace(2)).toBe(false);
+ expect(await find.replace(2, "pin")).toBe(8);
+ expect(targets.a.replace).not.toHaveBeenCalled();
+
+ expect(find.canReplace(5)).toBe(true);
+ expect(await find.replace(5, "pin")).toBe(7);
+ expect(host.replace).toHaveBeenCalledWith(2, "pin");
+
+ expect(await find.replaceAll("pin")).toBe(2);
+ expect(host.replaceAll).toHaveBeenCalledWith("pin");
+ expect(targets.c.replaceAll).toHaveBeenCalledWith("pin");
+ find.highlight(1);
+ expect(log.at(-1)).toBe("a.highlight(1)");
+ });
+
+ it("closes every target, the one of the current match on that match", async () => {
+ const { find, host, targets } = setUp();
+ await find.find("needle", OPTIONS);
+ find.highlight(3);
+ targets.a.close.mockReturnValue(true);
+
+ expect(find.close(3)).toBe(true);
+ expect(targets.a.close).toHaveBeenCalledWith(1);
+ expect(targets.c.close).toHaveBeenCalledWith(null);
+ expect(host.close).toHaveBeenCalledWith(null);
+ expect(log).toContain("a.box(false)");
+ expect(find.canReplace(0)).toBe(false);
+ });
+
+ it("closes the targets of embeds that left, and ignores an overtaken search", async () => {
+ const { find, host, targets, unregisterA } = setUp();
+ await find.find("needle", OPTIONS);
+ unregisterA();
+
+ let finishSlowSearch: (count: number) => void = () => {};
+ host.find.mockImplementationOnce(() => new Promise((resolve) => {
+ finishSlowSearch = resolve;
+ }));
+ const slowSearch = find.find("slow", OPTIONS);
+ expect(targets.a.close).toHaveBeenCalledWith(null);
+
+ host.count = 1;
+ expect(await find.find("fast", OPTIONS)).toBe(2);
+ finishSlowSearch(5);
+ await slowSearch;
+ expect(find.canReplace(1)).toBe(true);
+ expect(find.canReplace(2)).toBe(false);
+ expect(targets.a.find).toHaveBeenCalledTimes(1);
+ });
+});
+
+/**
+ * A host with five matches and four embeds: `a` with two matches after the second match of the
+ * host, `b` with no target, `c` with one match right after `a`, and `d` with none.
+ */
+function setUp({ isAReadOnly = false } = {}) {
+ const embeds = Object.fromEntries([ "a", "b", "c", "d" ].map((id) => [ id, createEmbed(id) ]));
+ const matchesBefore = new Map([
+ [ embeds.a, 2 ], [ embeds.b, 2 ], [ embeds.c, 2 ], [ embeds.d, 4 ]
+ ]);
+ const hostTarget = createTarget("host", 5);
+ const host = Object.assign(hostTarget, {
+ getEmbeds: vi.fn(() => Object.values(embeds)),
+ countMatchesBefore: vi.fn((embed: HTMLElement) => (
+ Math.min(matchesBefore.get(embed) ?? 0, hostTarget.count)
+ )),
+ revealEmbed: vi.fn((embed: HTMLElement | null) => {
+ log.push(`host.revealEmbed(${embed?.id ?? null})`);
+ }),
+ getSelectedMatch: (): number | null => null
+ }) satisfies HostFindTarget;
+ const targets = {
+ a: createTarget("a", 2, !isAReadOnly),
+ c: createTarget("c", 1),
+ d: createTarget("d", 0)
+ };
+ const unregisterA = register(embeds.a, targets.a);
+ register(embeds.c, targets.c);
+ register(embeds.d, targets.d);
+
+ return { find: new MergedFind(host), host, targets, unregisterA };
+}
+
+function createTarget(name: string, initialCount: number, isEditable = true) {
+ const target = {
+ count: initialCount,
+ firstBelow: null as number | null,
+ find: vi.fn(async (_term: string, _options: typeof OPTIONS) => target.count),
+ highlight: vi.fn((index: number | null) => {
+ log.push(`${name}.highlight(${index})`);
+ }),
+ getFirstMatchBelow: vi.fn((_top: number) => target.firstBelow),
+ canReplace: vi.fn((_index: number) => isEditable),
+ replace: vi.fn(async (_index: number, _text: string) => --target.count),
+ replaceAll: vi.fn(async (_text: string) => {
+ if (isEditable) target.count = 0;
+ return target.count;
+ }),
+ close: vi.fn((_index: number | null) => false)
+ } satisfies FindTarget & { count: number; firstBelow: number | null };
+ return target;
+}
+
+function createEmbed(id: string) {
+ const embed = document.createElement("figure");
+ embed.className = "include-note";
+ embed.id = id;
+ embed.innerHTML = `<div class="include-note-wrapper"><div class="include-note-content">`
+ + `<div class="content"></div></div></div>`;
+ document.body.append(embed);
+ return embed;
+}
+
+function register(embed: HTMLElement | undefined, target: FindTarget) {
+ const content = embed?.querySelector<HTMLElement>(".content");
+ if (!content) throw new Error("The embed has no content.");
+ const unregister = registerEmbedFindTarget(content, target);
+ cleanups.push(unregister);
+ return unregister;
+}
diff --git a/apps/client/src/widgets/merged_find.ts b/apps/client/src/widgets/merged_find.ts
new file mode 100644
index 0000000000..f8df4548fa
--- /dev/null
+++ b/apps/client/src/widgets/merged_find.ts
@@ -0,0 +1,255 @@
+import type { FindResult } from "./find";
+import { getEmbedFindTarget, revealContentEmbed } from "./type_widgets/text/content_embed_tools";
+
+/** The options of a search of "Search in note". */
+export interface FindOptions {
+ matchCase: boolean;
+ wholeWord: boolean;
+}
+
+/**
+ * What "Search in note" searches: a text editor, the rendered content of a note, a code editor or
+ * the content of an embed. Its matches are numbered from 0, in document order.
+ */
+export interface FindTarget {
+ /**
+ * Searches for `term` and returns the number of matches, none of them the current one. An empty
+ * `term` removes the matches.
+ */
+ find(term: string, options: FindOptions): Promise<number>;
+ /** Makes match `index` the current one and scrolls to it. `null` leaves no current match. */
+ highlight(index: number | null): void;
+ /** The first match at or below `top`, a client Y coordinate, or `null` when all are above. */
+ getFirstMatchBelow(top: number): number | null;
+ /** Whether `replace()` replaces match `index`, which a match in read-only content is not. */
+ canReplace(index: number): boolean;
+ /** Replaces match `index` with `text`, and returns the number of matches left. */
+ replace(index: number, text: string): Promise<number>;
+ /** Replaces each match that `canReplace()` allows, and returns the number of matches left. */
+ replaceAll(text: string): Promise<number>;
+ /**
+ * Removes the matches. With `index`, selects that match and focuses the target where it can,
+ * and returns whether it did.
+ */
+ close(index: number | null): boolean;
+}
+
+/** Content with embeds, whose matches `MergedFind` places among the matches of the content. */
+export interface HostFindTarget extends FindTarget {
+ /** The embeds in the content, in document order. */
+ getEmbeds(): HTMLElement[];
+ /** The number of matches before the content of `embed`. Matches in its caption come after. */
+ countMatchesBefore(embed: HTMLElement): number;
+ /**
+ * Shows `embed` wherever the content hides it, as a collapsed block does, while one of its
+ * matches is the current one. `null` hides it again.
+ */
+ revealEmbed(embed: HTMLElement | null): void;
+ /** The match at the selection, where the find starts, or `null`. */
+ getSelectedMatch?(): number | null;
+}
+
+/**
+ * Searches `host` and its embeds as one document. The content of each embed finds its own
+ * matches, which come between the matches of `host` around the embed.
+ */
+export default class MergedFind implements FindTarget {
+
+ private embeds: EmbedSearch[] = [];
+ private hostCount = 0;
+ private runs: Run[] = [];
+ private total = 0;
+ private current: Run | null = null;
+ private searchId = 0;
+
+ constructor(readonly host: HostFindTarget) {}
+
+ async find(term: string, options: FindOptions) {
+ const searchId = ++this.searchId;
+ this.highlight(null);
+ const embeds = this.host.getEmbeds().flatMap((embed) => {
+ const target = getEmbedFindTarget(embed);
+ return target ? [ { embed, target, count: 0 } ] : [];
+ });
+ for (const { target } of this.embeds) {
+ if (!embeds.some((embed) => embed.target === target)) {
+ target.close(null);
+ }
+ }
+ this.embeds = embeds;
+
+ const [ hostCount, ...counts ] = await Promise.all([
+ this.host.find(term, options),
+ ...embeds.map(({ target }) => target.find(term, options))
+ ]);
+ if (searchId === this.searchId) {
+ this.hostCount = hostCount;
+ for (const [ index, embed ] of embeds.entries()) {
+ embed.count = counts[index] ?? 0;
+ }
+ this.layOut();
+ }
+ return this.total;
+ }
+
+ highlight(index: number | null) {
+ const match = index === null ? null : this.locate(index);
+ const next = match?.run ?? null;
+ const previous = this.current;
+
+ // The content of an embed shows before its target scrolls to the match.
+ if (next?.embed && next.embed !== previous?.embed) {
+ this.host.revealEmbed(next.embed);
+ revealContentEmbed(next.embed, true);
+ }
+ if (match) {
+ match.run.target.highlight(match.local);
+ }
+ if (previous && previous.target !== next?.target) {
+ previous.target.highlight(null);
+ }
+ if (previous?.embed && previous.embed !== next?.embed) {
+ revealContentEmbed(previous.embed, false);
+ if (!next?.embed) {
+ this.host.revealEmbed(null);
+ }
+ }
+ this.current = next;
+ }
+
+ getFirstMatchBelow(top: number) {
+ const candidates = [
+ this.toIndex(this.host, this.host.getFirstMatchBelow(top)),
+ ...this.embeds.map(({ target }) => this.toIndex(target, target.getFirstMatchBelow(top)))
+ ].filter((index) => index !== null);
+ return candidates.length ? Math.min(...candidates) : null;
+ }
+
+ /**
+ * The match where the find starts, while there are matches: the one at the selection of the
+ * host, otherwise the first at or below `top`, a client Y coordinate.
+ */
+ getStartMatch(top: number) {
+ const selected = this.toIndex(this.host, this.host.getSelectedMatch?.() ?? null);
+ return selected ?? this.getFirstMatchBelow(top) ?? 0;
+ }
+
+ canReplace(index: number) {
+ const match = this.locate(index);
+ return !!match && match.run.target.canReplace(match.local);
+ }
+
+ async replace(index: number, text: string) {
+ const match = this.locate(index);
+ if (!match?.run.target.canReplace(match.local)) {
+ return this.total;
+ }
+
+ const { target } = match.run;
+ const count = await target.replace(match.local, text);
+ if (target === this.host) {
+ this.hostCount = count;
+ }
+ for (const embed of this.embeds) {
+ if (embed.target === target) {
+ embed.count = count;
+ }
+ }
+ this.layOut();
+ return this.total;
+ }
+
+ async replaceAll(text: string) {
+ this.hostCount = await this.host.replaceAll(text);
+ for (const embed of this.embeds) {
+ embed.count = await embed.target.replaceAll(text);
+ }
+ this.layOut();
+ return this.total;
+ }
+
+ close(index: number | null) {
+ const match = index === null ? null : this.locate(index);
+ this.highlight(null);
+
+ let isFocused = false;
+ for (const target of [ this.host, ...this.embeds.map((embed) => embed.target) ]) {
+ const isClosedOnMatch = target.close(target === match?.run.target ? match.local : null);
+ isFocused ||= isClosedOnMatch;
+ }
+ this.embeds = [];
+ this.hostCount = 0;
+ this.layOut();
+ return isFocused;
+ }
+
+ /** Splits the matches of the host around each embed with matches. */
+ private layOut() {
+ const runs: Run[] = [];
+ let total = 0;
+ let hostIndex = 0;
+ const add = (
+ target: FindTarget, embed: HTMLElement | null, first: number, count: number
+ ) => {
+ if (count > 0) {
+ runs.push({ target, embed, first, count, start: total });
+ total += count;
+ }
+ };
+
+ for (const { embed, target, count } of this.embeds) {
+ const before = Math.max(this.host.countMatchesBefore(embed), hostIndex);
+ add(this.host, null, hostIndex, before - hostIndex);
+ hostIndex = before;
+ add(target, embed, 0, count);
+ }
+ add(this.host, null, hostIndex, this.hostCount - hostIndex);
+
+ this.runs = runs;
+ this.total = total;
+ }
+
+ private locate(index: number) {
+ const run = this.runs.find(({ start, count }) => index >= start && index < start + count);
+ return run ? { run, local: run.first + index - run.start } : null;
+ }
+
+ private toIndex(target: FindTarget, local: number | null) {
+ if (local === null) {
+ return null;
+ }
+ const run = this.runs.find((candidate) => candidate.target === target
+ && local >= candidate.first && local < candidate.first + candidate.count);
+ return run ? run.start + local - run.first : null;
+ }
+
+}
+
+/** The counters of the find bar for `total` matches, of which `current` is the current one. */
+export function toFindResult(total: number, current: number | null): FindResult {
+ return { totalFound: total, currentFound: current === null ? 0 : current + 1 };
+}
+
+/** The top of the scrolling container around `element`, as a client Y coordinate. */
+export function getScrollingContainerTop(element: Element | null | undefined) {
+ return element?.closest(".scrolling-container")?.getBoundingClientRect().top ?? 0;
+}
+
+/** An embed whose content a target searches, and the number of matches it found. */
+interface EmbedSearch {
+ embed: HTMLElement;
+ target: FindTarget;
+ count: number;
+}
+
+/**
+ * Consecutive matches of one target: `count` matches from its match `first`, which are the matches
+ * from `start` of the whole document. `embed` is the embed of the target, `null` for the host.
+ */
+interface Run {
+ target: FindTarget;
+ embed: HTMLElement | null;
+ first: number;
+ count: number;
+ start: number;
+}
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index b01963051f..9708f1fa69 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -1693,7 +1693,9 @@ export function useImperativeSearchHighlighlighting(
// Reveal matches that landed inside collapsed <details> blocks, which are highlighted in
// the DOM but hidden until the block is expanded.
- el.querySelectorAll<HTMLElement>(".ck-find-result").forEach(expandAncestorDetails);
+ for (const match of el.querySelectorAll<HTMLElement>(".ck-find-result")) {
+ expandAncestorDetails(match);
+ }
};
}
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
index 6486278ed9..f0342b3f11 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
@@ -13,7 +13,8 @@ import LoadResults from "../../../services/load_results";
import options from "../../../services/options";
import { buildNote } from "../../../test/easy-froca";
import { ParentComponent } from "../../react/react_utils";
-import { getContentEmbedTools } from "../text/content_embed_tools";
+import { CodeMirrorFindTarget } from "../../find_in_code";
+import { getContentEmbedTools, getEmbedFindTarget } from "../text/content_embed_tools";
import CodeEmbed from "./CodeEmbed";
const renderCodePreview = vi.hoisted(() => vi.fn(async (content: string, _mime: string) => {
@@ -71,6 +72,36 @@ describe("CodeEmbed", () => {
expect(getContent()).toBe("# print(1)");
});
+ it("lets the find search the editor while the toggle is on", async () => {
+ const { figure } = await mount(buildCodeNote("print(1)\nprint(2)"), buildEditor(), {
+ isEditable: true
+ });
+ const view = await findView(figure);
+ const target = getEmbedFindTarget(figure);
+ if (!(target instanceof CodeMirrorFindTarget)) throw new Error("Expected a code target.");
+
+ expect(await target.find("print", { matchCase: false, wholeWord: false })).toBe(2);
+ expect(figure.querySelectorAll(".cm-activeMatch")).toHaveLength(0);
+ act(() => target.highlight(1));
+ expect(figure.querySelectorAll(".cm-activeMatch")).toHaveLength(1);
+ act(() => target.highlight(null));
+ expect(figure.querySelectorAll(".cm-activeMatch")).toHaveLength(0);
+ expect(target.getFirstMatchBelow(-Infinity)).toBe(0);
+ expect(target.getFirstMatchBelow(Infinity)).toBeNull();
+
+ expect(await target.replace(1, "log")).toBe(1);
+ expect(view.state.doc.toString()).toBe("print(1)\nlog(2)");
+ expect(target.close(0)).toBe(true);
+ expect([ view.state.selection.main.from, view.state.selection.main.to ]).toEqual([ 0, 5 ]);
+
+ await act(async () => {
+ delete figure.dataset.editable;
+ await Promise.resolve();
+ });
+ expect(getEmbedFindTarget(figure)).toBeNull();
+ expect(await target.find("print", { matchCase: false, wholeWord: false })).toBe(0);
+ });
+
it("releases the editor and previews the edited content once the toggle goes off", async () => {
const editor = buildEditor();
const { figure } = await mount(buildCodeNote("a"), editor, { isEditable: true });
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
index 7d1221ac26..060903f777 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
@@ -3,9 +3,11 @@ import { useEffect, useLayoutEffect, useRef } from "preact/hooks";
import type FNote from "../../../entities/fnote";
import type { ContentEditor } from "../../../services/content_renderer";
+import { CodeMirrorFindTarget } from "../../find_in_code";
import {
useNoteLabelInt, useNoteLabelOptionalBool, useTriliumOptionBool
} from "../../react/hooks";
+import { registerEmbedFindTarget } from "../text/content_embed_tools";
import { useEmbedCaretNavigation } from "../text/editable_embed";
import { CodeEditor } from "./Code";
@@ -30,6 +32,14 @@ export default function CodeEmbedEditor({
const [ noteWrapLines ] = useNoteLabelOptionalBool(note, "wrapLines");
useEmbedCaretNavigation(() => viewRef.current);
+ // Runs after the effects of `CodeMirror`, which creates the view.
+ useEffect(() => {
+ const view = viewRef.current;
+ if (!view) return;
+
+ return registerEmbedFindTarget(view.dom, new CodeMirrorFindTarget(view));
+ }, []);
+
// Runs after the effects of `CodeMirror`, which empties the document as it mounts.
useEffect(() => {
const view = viewRef.current;
diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx
index 38498ca0c2..dd047ec9c3 100644
--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.spec.tsx
@@ -39,7 +39,10 @@ vi.mock("../../../services/shortcuts", async (importOriginal) => ({
removeIndividualBinding
}));
-import { registerContentEmbedTools } from "./content_embed_tools";
+import { HtmlFindTarget } from "../../find_in_html";
+import {
+ getEmbedFindTarget, registerContentEmbedTools, revealContentEmbed
+} from "./content_embed_tools";
import ContentEmbed, {
getNoteActions,
type ContentEmbedProps,
@@ -293,6 +296,34 @@ describe("ContentEmbed", () => {
expect(contentBox().hidden).toBe(false);
});
+ it("lets the find search text, and shows a collapsed box for a current match", async () => {
+ container.classList.add("include-note");
+ renderBox({ boxSize: "expandable" });
+ const target = getEmbedFindTarget(container);
+ expect(target).toBeInstanceOf(HtmlFindTarget);
+ expect(await target?.find("body", { matchCase: false, wholeWord: false })).toBe(1);
+ target?.close(null);
+
+ act(() => revealContentEmbed(container, true));
+ expect(contentBox().hidden).toBe(false);
+ expect(button("include-note-toggle").getAttribute("aria-expanded")).toBe("true");
+ act(() => revealContentEmbed(container, false));
+ expect(contentBox().hidden).toBe(true);
+
+ // Collapsing drops the reveal, and expanding keeps the box open once the find moves on.
+ act(() => revealContentEmbed(container, true));
+ click(button("include-note-toggle"));
+ expect(contentBox().hidden).toBe(true);
+ click(button("include-note-toggle"));
+ act(() => revealContentEmbed(container, true));
+ act(() => revealContentEmbed(container, false));
+ expect(contentBox().hidden).toBe(false);
+
+ act(() => render(null, container));
+ renderBox({ contentType: "book" });
+ expect(getEmbedFindTarget(container)).toBeNull();
+ });
+
it("toggles an expandable box on a click on its title row, but its buttons and link", () => {
const titleRow = () => {
const row = container.querySelector<HTMLElement>(".include-note-title-row");
diff --git a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx
index d37aaa524c..726279cbdf 100644
--- a/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ContentEmbed.tsx
@@ -14,10 +14,12 @@ import { Badge } from "../../react/Badge";
import { useFocusWithin } from "../../react/hooks";
import Icon from "../../react/Icon";
import OverlayControlGroup, { OverlayControlButton } from "../../react/OverlayControlGroup";
+import { HtmlFindTarget } from "../../find_in_html";
import ScrollableLabel from "../../react/ScrollableLabel";
import {
- type ContentEmbedEvent, getContentEmbedTools, showContentEmbedFullscreen,
- useIsContentEmbedEditable, watchContentEmbedTools
+ type ContentEmbedEvent, getContentEmbedTools, registerEmbedFindTarget,
+ showContentEmbedFullscreen, useContentEmbedFindReveal, useIsContentEmbedEditable,
+ watchContentEmbedTools
} from "./content_embed_tools";
import { findTextEditorAround } from "./editable_embed";
@@ -68,9 +70,15 @@ export default function ContentEmbed({
useFullscreenEvents(contentRef);
useWindowShortcuts(contentRef);
const [ isExpanded, setIsExpanded ] = useState(false);
+ const [ isRevealed, setIsRevealed ] = useContentEmbedFindReveal(contentRef);
+ const isOpen = isExpanded || isRevealed;
const focusContentAfterRender = useFocusAfterRender(contentRef);
const isExpandable = boxSize === "expandable";
const hasFullscreen = !isExcerpt && (boxSize === "medium" || boxSize === "full");
+ const toggleExpanded = () => {
+ setIsExpanded(!isOpen);
+ setIsRevealed(false);
+ };
useLayoutEffect(() => {
contentRef.current?.append(content);
@@ -80,6 +88,12 @@ export default function ContentEmbed({
};
}, [ content ]);
+ // While an editor in the content is open, the target of the editor searches instead.
+ useEffect(() => {
+ if (!SEARCHABLE_CONTENT_TYPES.has(contentType)) return;
+ return registerEmbedFindTarget(content, new HtmlFindTarget(content));
+ }, [ content, contentType ]);
+
useLayoutEffect(() => {
// The box mounts after an upload, by which time the focus can have left the editor.
const editable = contentRef.current?.closest(".ck-editor__editable");
@@ -94,20 +108,20 @@ export default function ContentEmbed({
className="include-note-title-row"
onClick={(e) => {
if (isExpandable && isTogglingClick(e)) {
- setIsExpanded(!isExpanded);
+ toggleExpanded();
}
}}
onContextMenu={(e) => openMenuOnRightClick(e, notePath, viewScope)}
>
{isExpandable && (
<ActionButton
- className={clsx("include-note-toggle", isExpanded && "expanded")}
+ className={clsx("include-note-toggle", isOpen && "expanded")}
icon="bx bx-chevron-right"
text=""
- aria-expanded={isExpanded}
+ aria-expanded={isOpen}
onClick={(e) => {
e.stopPropagation();
- setIsExpanded(!isExpanded);
+ toggleExpanded();
}}
/>
)}
@@ -151,7 +165,7 @@ export default function ContentEmbed({
<div
ref={contentRef}
className={`include-note-content type-${contentType}`}
- hidden={isExpandable && !isExpanded}
+ hidden={isExpandable && !isOpen}
tabIndex={-1}
>
{hasFullscreen && (
@@ -338,6 +352,9 @@ function useFocusAfterRender(ref: RefObject<HTMLElement | null>) {
const FOCUSABLE_SELECTOR = "[tabindex], a[href], iframe, webview, "
+ ":is(button, input, select, textarea):not(:disabled)";
+/** The content types whose rendered content "Search in note" searches. */
+const SEARCHABLE_CONTENT_TYPES = new Set([ "text", "code", "markdown" ]);
+
/**
* The element that a click at (`x`, `y`) would focus: the closest focusable element under that
* point in `content`, which is focusable itself.
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx
index 68b4fca049..15be00e85e 100644
--- a/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/TextEmbed.spec.tsx
@@ -1,3 +1,4 @@
+import type { CKTextEditor } from "@triliumnext/ckeditor5";
import { render } from "preact";
import { useContext } from "preact/hooks";
import { act } from "preact/test-utils";
@@ -11,10 +12,12 @@ import froca from "../../../services/froca";
import LoadResults from "../../../services/load_results";
import type { ContentEditor } from "../../../services/content_renderer";
import { buildNote } from "../../../test/easy-froca";
+import { TextEditorFindTarget } from "../../find_in_text";
+import MergedFind from "../../merged_find";
import { useTriliumEvent } from "../../react/hooks";
import { ParentComponent } from "../../react/react_utils";
import type { TypeWidgetProps } from "../type_widget";
-import { getContentEmbedTools } from "./content_embed_tools";
+import { getContentEmbedTools, getEmbedFindTarget } from "./content_embed_tools";
import { NestedEmbedContext } from "./editable_embed";
import TextEmbed from "./TextEmbed";
@@ -72,6 +75,25 @@ afterEach(() => {
});
describe("TextEmbed", () => {
+ it("lets the find search its text editor once the editor is ready", async () => {
+ const { figure } = await mount(buildTextNote("ready"), buildEditor(), { isEditable: true });
+ await vi.waitFor(() => expect(editorProps).toHaveBeenCalled(), { timeout: 5000 });
+ const { parentComponent, ntxId } = editorProps.mock.calls[0][0] as TypeWidgetProps;
+ const root = figure.querySelector<HTMLElement>(".ck-editor__editable");
+ const editor = { editing: { view: { getDomRoot: () => root } } } as unknown as CKTextEditor;
+
+ act(() => {
+ parentComponent?.handleEvent("textEditorRefreshed", { ntxId: "_other", editor });
+ });
+ expect(getEmbedFindTarget(figure)).toBeNull();
+ act(() => {
+ parentComponent?.handleEvent("textEditorRefreshed", { ntxId, editor });
+ });
+ const target = getEmbedFindTarget(figure);
+ expect(target instanceof MergedFind && target.host instanceof TextEditorFindTarget
+ && target.host.editor).toBe(editor);
+ });
+
it("uses the floating toolbar inside an editor that has one", async () => {
const { figure } = await mount(buildTextNote("floating"), buildEditor(), { isEditable: true });
await vi.waitFor(() => expect(editorProps).toHaveBeenCalled(), { timeout: 5000 });
diff --git a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx
index c0198d2081..ab2c3fd086 100644
--- a/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/text/TextEmbedEditor.tsx
@@ -1,7 +1,8 @@
import "./TextEmbedEditor.css";
+import type { CKTextEditor } from "@triliumnext/ckeditor5";
import { createPortal, type RefObject } from "preact";
-import { useLayoutEffect, useRef } from "preact/hooks";
+import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
import type Component from "../../../components/component";
import type NoteContext from "../../../components/note_context";
@@ -9,8 +10,11 @@ import type FNote from "../../../entities/fnote";
import {
announceEmbeddedNoteClosing, EmbeddedNoteScope, useEmbeddedNoteContext
} from "../../EmbeddedNotePane";
+import { TextEditorFindTarget } from "../../find_in_text";
import { SaveStatusBadge } from "../../layout/NoteBadges";
-import { useLegacyComponentElement, useNoteContext } from "../../react/hooks";
+import MergedFind from "../../merged_find";
+import { useLegacyComponentElement, useNoteContext, useTriliumEvent } from "../../react/hooks";
+import { registerEmbedFindTarget } from "./content_embed_tools";
import EditableText, { getBlockData } from "./EditableText";
import {
findTextEditorIn, NestedEmbedContext, useEmbedBadgeSlot, useEmbedCaretNavigation
@@ -95,6 +99,7 @@ function ScopedEditor({ rootRef, note, block, onBlockChange }: ScopedEditorProps
// The plugins of the editor find their host by the element of its component.
useLegacyComponentElement(rootRef);
const badgeSlot = useEmbedBadgeSlot(rootRef);
+ useEditorFindTarget(ntxId);
return (
<div ref={rootRef} className="text-embed-editor">
@@ -114,6 +119,26 @@ function ScopedEditor({ rootRef, note, block, onBlockChange }: ScopedEditorProps
);
}
+/**
+ * Lets "Search in note" search the text editor of `ntxId` and its embeds, once the editor is
+ * ready, in place of the preview of the embed.
+ */
+function useEditorFindTarget(ntxId: string | null | undefined) {
+ const [ editor, setEditor ] = useState<CKTextEditor | null>(null);
+ useTriliumEvent("textEditorRefreshed", ({ ntxId: editorNtxId, editor: refreshedEditor }) => {
+ if (editorNtxId === ntxId) {
+ setEditor(refreshedEditor);
+ }
+ });
+
+ useEffect(() => {
+ const root = editor?.editing.view.getDomRoot();
+ if (!editor || !root) return;
+
+ return registerEmbedFindTarget(root, new MergedFind(new TextEditorFindTarget(editor)));
+ }, [ editor ]);
+}
+
/**
* Saves what is left in the editor of `ntxId`, and resolves to whether the save succeeded. The
* editor reports a failed save in the save state of its note context.
diff --git a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts b/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts
index 27d3562891..b8af5e4ead 100644
--- a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts
+++ b/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts
@@ -1,7 +1,10 @@
import type { EmbedEdge } from "@triliumnext/ckeditor5";
import type { RefObject } from "preact";
+import { flushSync } from "preact/compat";
import { useEffect, useRef, useState } from "preact/hooks";
+import type { FindTarget } from "../../merged_find";
+
/** A button that the content of an embed adds to the toolbar of the embed. */
export interface ContentEmbedTool {
id: string;
@@ -63,6 +66,11 @@ export interface EmbedCaretTarget {
const providers = new Map<HTMLElement, ContentEmbedToolProvider>();
const watchers = new Set<{ container: HTMLElement; callback: () => void }>();
const caretTargets = new Map<HTMLElement, EmbedCaretTarget>();
+const findTargets = new Map<HTMLElement, FindTarget>();
+const findWatchers = new Set<{ container: HTMLElement; callback: () => void }>();
+
+/** The event that `revealContentEmbed()` dispatches on the content box of an embed. */
+const FIND_REVEAL_EVENT = "contentEmbedFindReveal";
/**
* Adds the buttons of `provider` to the toolbar of the embed that contains `element`, until the
@@ -127,6 +135,85 @@ export function enterContentEmbed(embed: HTMLElement, edge: EmbedEdge) {
return false;
}
+/**
+ * Lets "Search in note" search the content of the embed that contains `element` with `target`,
+ * until the returned function is called. Of the targets in one embed, the innermost one searches
+ * it, as the editor of an included note does rather than the preview around it.
+ */
+export function registerEmbedFindTarget(element: HTMLElement, target: FindTarget) {
+ findTargets.set(element, target);
+ notifyFindWatchers(element);
+ return () => {
+ findTargets.delete(element);
+ notifyFindWatchers(element);
+ };
+}
+
+/** The target that searches the content of `embed`, or `null` for content that is not searched. */
+export function getEmbedFindTarget(embed: HTMLElement) {
+ let found: [ HTMLElement, FindTarget ] | null = null;
+ for (const entry of findTargets) {
+ const [ element ] = entry;
+ if (element.closest(".include-note") === embed && (!found || found[0].contains(element))) {
+ found = entry;
+ }
+ }
+ return found?.[1] ?? null;
+}
+
+/**
+ * Calls `callback` when the targets that search the embeds inside `container` change, as when the
+ * editor of an included note replaces its preview. Stops when the returned function is called.
+ */
+export function watchEmbedFindTargets(container: HTMLElement, callback: () => void) {
+ const watcher = { container, callback };
+ findWatchers.add(watcher);
+ return () => {
+ findWatchers.delete(watcher);
+ };
+}
+
+/**
+ * Shows the content of `embed` while a match of "Search in note" in it is the current one, as a
+ * collapsed Expandable embed hides its content. `false` hides it again.
+ */
+export function revealContentEmbed(embed: HTMLElement, isRevealed: boolean) {
+ const box = [ ...embed.querySelectorAll(".include-note-content") ]
+ .find((element) => element.closest(".include-note") === embed);
+ box?.dispatchEvent(new CustomEvent(FIND_REVEAL_EVENT, { detail: isRevealed }));
+}
+
+/**
+ * Whether "Search in note" shows the content box in `contentRef`, for a match in it, and the
+ * setter that stops showing it, as the user collapsing the embed does.
+ */
+export function useContentEmbedFindReveal(contentRef: RefObject<HTMLElement | null>) {
+ const [ isRevealed, setIsRevealed ] = useState(false);
+
+ useEffect(() => {
+ const box = contentRef.current;
+ if (!box) return;
+
+ const onReveal = (event: Event) => {
+ // The find scrolls to the match right after, which must show by then.
+ flushSync(() => setIsRevealed(event instanceof CustomEvent && event.detail === true));
+ };
+ box.addEventListener(FIND_REVEAL_EVENT, onReveal);
+ return () => box.removeEventListener(FIND_REVEAL_EVENT, onReveal);
+ }, [ contentRef ]);
+
+ return [ isRevealed, setIsRevealed ] as const;
+}
+
+function notifyFindWatchers(element: HTMLElement) {
+ for (const { container, callback } of findWatchers) {
+ // An element that left the page can have been in any container.
+ if (!element.isConnected || container.contains(element)) {
+ callback();
+ }
+ }
+}
+
function notifyWatchers(element: HTMLElement) {
for (const { container, callback } of watchers) {
if (container.contains(element)) {
diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.json
index 5a96e60c0c..06cb67c674 100644
--- a/apps/server/src/assets/help/help_content.json
+++ b/apps/server/src/assets/help/help_content.json
@@ -91,7 +91,7 @@
"_help_ZjLYv08Rp3qC": "<figure class=\"image image-style-align-right image_resized\" style=\"width:53.13%;\"><img style=\"aspect-ratio:895/694;\" src=\"{{helpAssets}}/User%20Guide/Basic%20Concepts%20and%20Features/Navigation/Quick%20edit_image.png\" width=\"895\" height=\"694\"></figure><p><em>Quick edit</em> provides an alternative to the standard tab-based navigation and editing.</p><p>Instead of clicking on a note which switches the&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>&nbsp;to the newly selected note, or navigating between two different&nbsp;<a class=\"reference-link\" href=\"#root/_help_3seOhtN8uLIY\">Tabs</a>, the <em>Quick edit</em> feature opens as a popup window that can be easily dismissed.</p><p>This feature is also well integrated with&nbsp;<a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>&nbsp;such as the calendar view, which makes it easy to edit entries without having to go back and forth between the child note and the calendar.</p><h2>Feature highlights</h2><ul><li>All note types are supported, including&nbsp;<a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>.</li><li>Note that the&nbsp;<a class=\"reference-link\" href=\"#root/_help_0ESUbbAxVnoK\">Note List</a>&nbsp;will not be displayed, except for notes of type&nbsp;<a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>.</li><li>For&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;notes, depending on user preference, both the floating and classic editors are supported. See&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>.</li><li>The title and the note and the icon are editable, just like a normal tab.</li><li>The note's actions and its menu are shown in the header of the popup, as in the title row of a tab.<ul><li>When other notes link to the note, a button with a link icon lists the <a class=\"reference-link\" href=\"#root/_help_wfGXLmm7x27z\">Backlinks</a>. Pressing one opens that note in the popup.</li><li>The menu items that only work in a tab are not shown: <em>Search in note</em>, <em>Note map</em>, <em>Full width</em> and <em>Convert into attachment</em>.</li><li>A help page opened from the popup, such as through the help button of the note type, opens in a second popup on top of it. Closing that popup returns to the note being edited.</li></ul></li><li>The&nbsp;<a class=\"reference-link\" href=\"#root/_help_OFXdgB2nNk1F\">Promoted Attributes</a>&nbsp;are also displayed.<ul><li>This integrates well with&nbsp;<a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>&nbsp;where there are predefined attributes such as the <em>Start date</em> and <em>End date</em>, allowing for easy editing.</li></ul></li></ul><h2>Accessing the quick edit</h2><ul><li>From the&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>:<ul><li>Right click on a note and select <em>Quick edit</em>.</li><li>or, press <kbd>Ctrl</kbd>+<kbd>Right click</kbd> on a note.</li></ul></li><li>On&nbsp;<a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a>: <ul><li>Right click and select <em>Quick edit</em>.</li><li>or, press <kbd>Ctrl</kbd>+<kbd>Right click</kbd> on the link.</li></ul></li><li>On a&nbsp;<a class=\"reference-link\" href=\"#root/_help_lgKX7r3aL30x\">Note Tooltip</a>, press the quick edit icon.</li><li>In&nbsp;<a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>:<ul><li>For&nbsp;<a class=\"reference-link\" href=\"#root/_help_xWbu3jpNWapp\">Calendar</a>:<ul><li>Clicking on an event will open that event for quick editing.</li><li>If the calendar is for the&nbsp;<a class=\"reference-link\" href=\"#root/_help_l0tKav7yLHGF\">Day Notes</a>&nbsp;root, clicking on the day number will open the popup for that day note.</li></ul></li><li>For&nbsp;<a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a>:<ul><li>Clicking on a marker will open that marker, but only if the map is in read-only mode.</li></ul></li></ul></li></ul><h2>Handling of read-only notes</h2><p>The Quick edit feature has a unique behavior for&nbsp;<a class=\"reference-link\" href=\"#root/_help_CoFPLs3dRlXc\">Read-Only Notes</a>: </p><ul><li>If the note is read-only due to performance reasons (auto read-only), then the note is made editable for quick editing.</li><li>If the note has been manually set to read-only, then the note is read-only to prevent accidental change.<ul><li>In this case, the note can still be edited by on-screen instructions.</li></ul></li></ul>",
"_help_9sRHySam5fXb": "<p>Workspace is a concept built up on top of <a href=\"#root/_help_OR8WJ7Iz9K4U\">note hoisting</a>. It is based on the idea that a user has several distinct spheres of interest. An example might be \"Personal\" and \"Work\", these two spheres are quite distinct and don't interact together. When I focus on Work, I don't really care about personal notes.</p><p>So far workspace consists of these features:</p><ul><li><p><a href=\"#root/_help_OR8WJ7Iz9K4U\">note hoisting</a> - you can \"zoom\" into a workspace subtree to focus only on the relevant notes</p></li><li><p>easy entering of workspace:&nbsp;</p><p><img src=\"{{helpAssets}}/User%20Guide/Basic%20Concepts%20and%20Features/Navigation/1_Workspaces_image.jpg\"></p></li><li><p>visual identification of workspace in tabs:<br><img src=\"{{helpAssets}}/User%20Guide/Basic%20Concepts%20and%20Features/Navigation/Workspaces_image.jpg\"></p></li></ul><h3>Configuration</h3><figure class=\"table\"><table><thead><tr><th>Label</th><th>Description</th></tr></thead><tbody><tr><td><code>workspace</code></td><td>Marks this note as a workspace, button to enter the workspace is controlled by this</td></tr><tr><td><code>workspaceIconClass</code></td><td>defines box icon CSS class which will be used in tab when hoisted to this note</td></tr><tr><td><code>workspaceTabBackgroundColor</code></td><td>CSS color used in the note tab when hoisted to this note, use any CSS color format, e.g. \"lightblue\" or \"#ddd\". See <a href=\"https://www.w3schools.com/cssref/css_colors.asp\">https://www.w3schools.com/cssref/css_colors.asp</a>.</td></tr><tr><td><code>workspaceCalendarRoot</code></td><td>Marking a note with this label will define a new per-workspace calendar for&nbsp;<a class=\"reference-link\" href=\"#root/_help_l0tKav7yLHGF\">Day Notes</a>. If there's no such note, the global calendar will be used.</td></tr><tr><td><code>workspaceTemplate</code></td><td>This note will appear in the selection of available template when creating new note, but only when hoisted into a workspace containing this template</td></tr><tr><td><code>workspaceSearchHome</code></td><td>new search notes will be created as children of this note when hoisted to some ancestor of this workspace note</td></tr><tr><td><code>workspaceInbox</code></td><td>Default inbox location for new notes when hoisted to some ancestor of this workspace note. See&nbsp;<a class=\"reference-link\" href=\"#root/_help_S0Fos78ZfcY7\">Note Inbox</a>&nbsp;for more information.</td></tr></tbody></table></figure>",
"_help_xWtq5NUHOwql": "<figure class=\"image image-style-align-right image_resized\" style=\"width:50.46%;\"><img style=\"aspect-ratio:538/290;\" src=\"{{helpAssets}}/User%20Guide/Basic%20Concepts%20and%20Features/Navigation/Similar%20Notes_image.png\" width=\"538\" height=\"290\"></figure><p>The Similar Notes feature tries to identify notes that relate to the current note by looking at the content of the notes, their relationships, as well as the date they were created.</p><p>To access the list of similar notes:</p><ul><li>Go to the&nbsp;<a class=\"reference-link\" href=\"#root/_help_KRlZFoIH0j6p\">Connections tab</a>&nbsp;in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_RnaPdbciOfeq\">Right Sidebar</a>&nbsp;and look for the corresponding section.</li><li>Alternatively, press the&nbsp;<span class=\"tn-icon bx bx-info-circle\"></span> in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a>&nbsp;and select <em>Show similar notes</em> which will open a pane at the bottom.</li></ul><h2>Interaction</h2><ul><li>Hover over a note to see a short preview of the note.</li><li>Click over a note to open it in the current view.</li><li><kbd>Ctrl</kbd> + click a note to open it in a separate tab.</li></ul>",
- "_help_McngOG2jbUWX": "<figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:898/93;\" src=\"{{helpAssets}}/User%20Guide/Basic%20Concepts%20and%20Features/Navigation/Search%20in%20note_image.png\" width=\"898\" height=\"93\"></figure><p>Local search allows you to search within the currently displayed note.&nbsp;</p><h2>Alternatives</h2><ul><li>Pressing <kbd>Ctrl</kbd>+<kbd>F</kbd> while in a browser while not focused in a&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;or a&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note will trigger the browser's native search. This will also find text that is part of Trilium's UI.</li><li>Pressing <kbd>Ctrl</kbd>+<kbd>F</kbd> in a&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;note will reveal&nbsp;<a class=\"reference-link\" href=\"#root/_help_MI26XDLSAlCD\">CKEditor</a>'s search functionality.</li></ul><h2>Accessing the search</h2><ul><li>On desktop, press<kbd>Ctrl</kbd> + <kbd>F</kbd>.</li><li>From the&nbsp;<a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a>, look for the context menu and select <em>Search in note</em>.</li></ul><h2>Interaction</h2><ul><li>Finding:<ul><li>Fill in the <em>Find in text…</em> with the text to search for.</li><li>The search will be executed automatically in the background.</li><li>Use up and down arrows of the text box to navigate between results.</li></ul></li><li>Replacing:<ul><li>Fill in the <em>Find in text</em>… field with the text to replace.</li><li>Fill in the <em>Replace with…</em> field the text to replace it with.</li><li>Press <em>Replace</em> to replace only the current result.</li><li>Press <em>Replace all</em> to replace all of them at once.</li></ul></li><li>Options:<ul><li><em>Case sensitive</em> – the search will distinguish upper case characters from lower case (e.g. searching for Hello will not match <code>hello</code>).</li><li><em>Match words</em> - the search will find only exact word matches (e.g. searching for <code>Java</code> will not match <code>JavaScript</code>).</li></ul></li></ul>",
+ "_help_McngOG2jbUWX": "<figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:898/93;\" src=\"{{helpAssets}}/User%20Guide/Basic%20Concepts%20and%20Features/Navigation/Search%20in%20note_image.png\" width=\"898\" height=\"93\"></figure><p>Local search allows you to search within the currently displayed note.&nbsp;</p><h2>Alternatives</h2><ul><li>Pressing <kbd>Ctrl</kbd>+<kbd>F</kbd> while in a browser while not focused in a&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;or a&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note will trigger the browser's native search. This will also find text that is part of Trilium's UI.</li><li>Pressing <kbd>Ctrl</kbd>+<kbd>F</kbd> in a&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;note will reveal&nbsp;<a class=\"reference-link\" href=\"#root/_help_MI26XDLSAlCD\">CKEditor</a>'s search functionality.</li></ul><h2>Accessing the search</h2><ul><li>On desktop, press<kbd>Ctrl</kbd> + <kbd>F</kbd>.</li><li>From the&nbsp;<a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a>, look for the context menu and select <em>Search in note</em>.</li></ul><h2>Interaction</h2><ul><li>Finding:<ul><li>Fill in the <em>Find in text…</em> with the text to search for.</li><li>The search will be executed automatically in the background.</li><li>Use up and down arrows of the text box to navigate between results.</li></ul></li><li>Replacing:<ul><li>Fill in the <em>Find in text</em>… field with the text to replace.</li><li>Fill in the <em>Replace with…</em> field the text to replace it with.</li><li>Press <em>Replace</em> to replace only the current result.</li><li>Press <em>Replace all</em> to replace all of them at once.</li></ul></li><li>Options:<ul><li><em>Case sensitive</em> – the search will distinguish upper case characters from lower case (e.g. searching for Hello will not match <code>hello</code>).</li><li><em>Match words</em> - the search will find only exact word matches (e.g. searching for <code>Java</code> will not match <code>JavaScript</code>).</li></ul></li></ul><h2>Included notes</h2><p>In a <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> note, the search also finds the text of the notes included with&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>, in the order they appear in the note.</p><ul><li>The text of included text and code notes and of embedded code files, such as a <code>.js</code> or <code>.txt</code> attachment, is searched. The title of an include and the content of other notes, such as a collection or a drawing, are not.</li><li>The up and down arrows move through the results of an include as through the rest of the note.</li><li>A result in a collapsed <em>Expandable</em> include expands the include while that result is the current one, and collapses it again once the search moves on.</li><li><em>Replace</em> and <em>Replace all</em> change an included note only while its <em>Editable</em> button is on. While the current result is in an include that cannot be edited, <em>Replace</em> is disabled, and <em>Replace all</em> leaves such results unchanged.</li></ul>",
"_help_A9Oc6YKKc65v": "<p>This is supposed to be a complete list of keyboard shortcuts. Note that some of these may work only in certain contexts (e.g. in tree pane or note editor).</p><h2>Configuring keyboard shortcuts</h2><p>It is also possible to configure most keyboard shortcuts in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>Shortcuts</em>.</p><p>On the&nbsp;<a class=\"reference-link\" href=\"#root/_help_poXkQfguuA0U\">Desktop Installation</a>, it's also possible to make shortcuts global by pressing on the globe icon near the key combination, which makes the shortcut work even without Trilium being in focus.</p><h3>Keyboard layouts</h3><p>Shortcuts follow the characters printed on the keys of the active keyboard layout. On a French AZERTY keyboard, for example, <kbd>Ctrl</kbd>+<kbd>Z</kbd> is the key labeled Z.</p><p>On a layout that doesn't type Latin letters, such as Russian, Greek or Hebrew, a key that types a letter of that alphabet counts as the key at the same position on a US QWERTY keyboard. <kbd>Ctrl</kbd>+<kbd>J</kbd> is then the key that types <code>о</code> on a Russian keyboard, so shortcuts keep working without switching the layout first.</p><p>Keys that type punctuation still follow their own character. On a Russian keyboard, the key that types <code>.</code> triggers <kbd>Ctrl</kbd>+<kbd>.</kbd>, not the shortcut of the US key at its position.</p><h2>Shortcut reference</h2><aside class=\"admonition note\"><p>All these shortcuts indicate the default key-bindings which can be changed individually from&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>Shortcuts.</em></p></aside><h3>Tree</h3><p>See the corresponding section:&nbsp;<a class=\"reference-link\" href=\"#root/_help_DvdZhoQZY9Yd\">Keyboard shortcuts</a></p><h3>Note navigation</h3><ul><li><kbd>Alt</kbd>+<kbd>←</kbd>, <kbd>Alt</kbd>+<kbd>→</kbd> – go back / forwards in the history</li><li><kbd>Ctrl</kbd>+<kbd>J</kbd> – show <a href=\"#root/_help_MMiBEQljMQh2\">\"Jump to\" dialog</a></li><li><kbd>Ctrl</kbd>+<kbd>.</kbd> – scroll to current note (useful when you scroll away from your note or your focus is currently in the editor)</li><li><kbd>Backspace</kbd> – jumps to parent note</li><li><kbd>Alt</kbd>+<kbd>C</kbd> – collapse whole note tree</li><li><kbd>Alt</kbd>+<kbd>-</kbd> (alt with minus sign) – collapse subtree (if some subtree takes too much space on tree pane you can collapse it)</li><li>you can define a <a href=\"#root/_help_zEY4DaJG4YT5\">label</a> <code>#keyboardShortcut</code> with e.g. value <code>Ctrl + I</code> . Pressing this keyboard combination will then bring you to the note on which it is defined. Note that Trilium must be reloaded/restarted (<kbd>Ctrl</kbd>+<kbd>R</kbd> ) for changes to be in effect.</li></ul><p>See demo of some of these features in <a href=\"#root/_help_MMiBEQljMQh2\">note navigation</a>.</p><h3>Tabs</h3><ul><li><kbd>Ctrl</kbd> + <kbd>🖱 Left click</kbd> – (or middle mouse click) on note link opens note in a new tab</li></ul><p>Only in desktop (electron build):</p><ul><li><kbd>Ctrl</kbd>+<kbd>T</kbd> – opens empty tab</li><li><kbd>Ctrl</kbd>+<kbd>W</kbd> – closes active tab</li><li><kbd>Ctrl</kbd>+<kbd>Tab</kbd> – activates next tab</li><li><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Tab</kbd> – activates previous tab</li></ul><h3>Splits</h3><p><a class=\"reference-link\" href=\"#root/_help_luNhaphA37EO\">Split View</a>&nbsp;can also be controlled through keyboard actions, such as:</p><ul><li>Creating a new split</li><li>Closing the active split</li><li>Moving a split left/right</li><li>Focusing the split to the left/right.</li></ul><p>All these keyboard shortcuts do not have a default set, go to&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>Shortcuts</em> and look for the <em>Split View</em> category.</p><h3>Context menus</h3><p>Every context menu can be operated from the keyboard, however it was opened, for example with the <kbd>Menu</kbd> key in a text note to reach the spelling suggestions. These keys are fixed and cannot be changed in the options.</p><ul><li><kbd>↑</kbd>, <kbd>↓</kbd> – move to the previous / next item, skipping disabled ones and wrapping around at either end</li><li><kbd>Home</kbd>, <kbd>End</kbd> – move to the first / last item</li><li><kbd>→</kbd> – open the submenu of the current item, or move to the next column in a submenu laid out in columns</li><li><kbd>←</kbd> – move to the previous column, or close the submenu and go back to its item</li><li><kbd>Enter</kbd> or <kbd>Space</kbd> – run the current item, or open its submenu</li><li><kbd>Esc</kbd> – close the innermost submenu, then the menu itself</li><li>typing the first letters of an item – jump to the next item whose title starts with them</li></ul><p>With a right-to-left language, <kbd>←</kbd> and <kbd>→</kbd> swap roles.</p><h3>Creating notes</h3><ul><li><kbd>Ctrl</kbd>+<kbd>O</kbd> – creates new note after the current note</li><li><kbd>Ctrl</kbd>+<kbd>P</kbd> – creates new sub-note into current note</li><li><kbd>F2</kbd> – edit the&nbsp;<a class=\"reference-link\" href=\"#root/_help_TBwsyfadTA18\">Branch prefix</a>&nbsp;of current note clone</li></ul><h3>Editing notes</h3><aside class=\"admonition note\"><p>For keyboard shortcuts specific to&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;notes, refer to&nbsp;<a class=\"reference-link\" href=\"#root/_help_oiVPnW8QfnvS\">Keyboard shortcuts</a>&nbsp;and&nbsp;<a class=\"reference-link\" href=\"#root/_help_QrtTYPmdd1qq\">Markdown-like formatting</a>.</p></aside><ul><li>Enter in tree pane switches from tree pane into note title. Enter from note title switches focus to text editor. <kbd>Ctrl</kbd>+<kbd>.</kbd> switches back from editor to tree pane.</li><li><kbd>Ctrl</kbd>+<kbd>.</kbd> – jump away from the editor to tree pane and scroll to current note</li></ul><h3>Runtime shortcuts</h3><p>These are hooked in Electron to be similar to native browser keyboard shortcuts.</p><ul><li><kbd>F5</kbd>, <kbd>Ctrl</kbd>+<kbd>R</kbd> – reloads Trilium front-end</li><li><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd> – show developer tools</li><li><kbd>Ctrl</kbd>+<kbd>F</kbd> – show search dialog</li><li><kbd>Ctrl</kbd>+<kbd>-</kbd> – zoom out</li><li><kbd>Ctrl</kbd>+<kbd>=</kbd> – zoom in</li></ul><h3>Other</h3><ul><li><kbd>Alt</kbd>+<kbd>O</kbd> – show SQL console (use only if you know what you're doing)</li><li><kbd>Alt</kbd>+<kbd>M</kbd> – distraction-free mode - display only note editor, everything else is hidden</li><li><kbd>F11 </kbd> – toggle full screen</li><li><kbd>Ctrl</kbd>+<kbd>S</kbd> – toggle <a href=\"#root/_help_eIg8jdvaoNNd\">search</a> form in tree pane</li><li><kbd>Alt</kbd>+<kbd>A</kbd> – show note <a href=\"#root/_help_zEY4DaJG4YT5\">attributes</a> dialog</li></ul>",
"_help_Wy267RK4M69c": "<h2>Default Themes</h2><p>Trilium comes with a couple pre-installed color themes, with the default being a light theme. To switch to a dark theme or any other available theme, navigate to the <span class=\"tn-icon bx bx-cog\"></span> Options menu (accessible via the app icon in the top-left corner), select the Appearance tab, and choose your preferred theme.</p><p><img src=\"{{helpAssets}}/User%20Guide/Basic%20Concepts%20and%20Features/Themes_dark-theme.png\" alt=\"Dark Theme\"></p><p>While a dark theme is active, Trilium asks the Dark Reader browser extension not to darken the page a second time. Dark Reader still darkens the light themes. After switching from a dark theme to a light one, reload the page (<kbd>Ctrl</kbd>+<kbd>R</kbd>) for Dark Reader to take effect again.</p><h2>Creating Custom CSS Themes</h2><p>Trilium supports custom user themes, allowing you to personalize the application's appearance. To create a custom theme, follow these steps:</p><ol><li><strong>Create a CSS Code Note</strong>: Start by creating a new <a href=\"#root/_help_6f9hih2hXXZk\">code note</a> with the <code>CSS</code> type.</li><li><strong>Annotate with</strong> <code>#appTheme</code>: Add the <a href=\"#root/_help_zEY4DaJG4YT5\">attribute</a> <code>#appTheme=my-theme-name</code> to your note, where <code>my-theme-name</code> is the name of your custom theme.</li><li><strong>Define Your Styles</strong>: Write your custom CSS within the note.</li></ol><details class=\"trilium-collapsible\" open=\"\"><summary>Example of a custom theme</summary><pre><code class=\"language-text-x-trilium-auto\">@font-face {\n font-family: 'Raleway';\n font-style: normal;\n font-weight: 400;\n src: url('/custom/fonts/raleway.woff2') format('woff2');\n}\n\n:root {\n --main-font-family: 'Raleway' !important;\n --main-font-size: normal;\n --tree-font-family: inherit;\n --tree-font-size: normal;\n --detail-font-family: inherit;\n --detail-font-size: normal;\n --detail-text-font-family: 'Garamond' !important;\n\n --main-background-color: #404552;\n --main-text-color: #AFB8C6;\n --main-border-color: #AFB8C6;\n --accented-background-color: #383C4A;\n --more-accented-background-color: #2F343F;\n --header-background-color: #383C4A;\n --button-background-color: #2F343F;\n --button-disabled-background-color: #404552;\n --button-border-color: #333;\n --button-text-color: #AFB8C6;\n --button-border-radius: 2px;\n --primary-button-background-color: #6c757d;\n --primary-button-text-color: white;\n --primary-button-border-color: #6c757d;\n --muted-text-color: #86919F;\n --input-text-color: #AFB8C6;\n --input-background-color: #404552;\n --hover-item-text-color: white;\n --hover-item-background-color: #4877B1;\n --active-item-text-color: white;\n --active-item-background-color: #4877B1;\n --menu-text-color: #AFB8C6;\n --menu-background-color: #383C4A;\n --tooltip-background-color: #383C4A;\n --link-color: lightskyblue;\n --modal-background-color: #404552;\n --modal-backdrop-color: black;\n --scrollbar-border-color: rgba(175, 184, 198, 0.5);\n}\n\nbody .note-detail-text {\n font-size: 120%;\n}\n\nbody .CodeMirror {\n filter: invert(100%) hue-rotate(180deg);\n}</code></pre><p>&nbsp;</p></details><p>&nbsp;</p><h3>Activating Your Custom Theme</h3><p>Once you've created your custom theme:</p><ol><li>Go to \"Menu\" -&gt; \"Options\" (<span class=\"tn-icon bx bx-cog\"></span>) -&gt; \"Appearance.\"</li><li>In the theme selection dropdown, you should see your custom theme listed under the name you provided with the <code>#appTheme</code> <a href=\"#root/_help_zEY4DaJG4YT5\">label</a>.</li><li>Select your custom theme to activate it.</li></ol><p>If you make changes to your theme, press Ctrl + R to reload the frontend and apply your updates.</p><h3>Sharing and Importing Themes</h3><p>Custom themes can be exported as <code>.tar</code> archives, which can be shared with other users. However, be cautious when importing themes from untrusted sources, as they may contain executable scripts that could pose security risks.</p><p>An example user theme, <em>Steel Blue</em>, is available in the demo document.</p><p><img src=\"{{helpAssets}}/User%20Guide/Basic%20Concepts%20and%20Features/Themes_steel-blue.png\" alt=\"Steel Blue Theme\"></p><h3>Using Custom CSS for Specific Purposes</h3><p>In addition to full themes, Trilium allows for custom CSS that isn't tied to a theme. This can be particularly useful in scripting contexts, where you might want to modify specific UI elements, such as changing the colors of notes in the tree view.</p><h3>Applying Custom CSS</h3><p>To use custom CSS:</p><ol><li><strong>Create a CSS Code Note</strong>: Create a new&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note with the <code>CSS</code> type.</li><li><strong>Add the</strong> <code>appCss</code> <strong>Label</strong>: Annotate the note with the <code>#appCss</code> <a href=\"#root/_help_zEY4DaJG4YT5\">label</a>.</li><li><strong>Write Your CSS</strong>: Add your custom CSS rules to the note.</li></ol><p>For example:</p><pre><code class=\"language-text-x-trilium-auto\">/* Custom CSS to style specific elements */\n.tree-item {\n color: #ff6347; /* Change tree item color */\n}</code></pre><p>When Trilium's frontend starts, all notes labeled with <code>appCss</code> are automatically included in the style element of the HTML page.</p><p>After making changes, press Ctrl + R to reload the frontend and apply your new styles.</p><p><img src=\"{{helpAssets}}/User%20Guide/Basic%20Concepts%20and%20Features/Themes_image.jpg\"></p><h3>Styling Specific Notes in the Tree</h3><p>To apply specific styles to certain notes in the tree:</p><ul><li><strong>Use the</strong> <code>cssClass</code> <strong>Attribute</strong>: Add the <code>cssClass</code> <a href=\"#root/_help_zEY4DaJG4YT5\">attribute</a> to a note, and assign it a value representing the desired CSS class.</li><li><strong>Define an</strong> <code>iconClass</code>: You can also define a custom icon for a note using the <code>iconClass</code> attribute, selecting from <a href=\"https://boxicons.com\">Box Icons</a> or your own custom classes.</li></ul><p>For example, if you want to style notes of a specific type, such as notes containing PNG images, you can target them with classes like <code>type-image mime-image-png</code>.</p><h3>User-Provided Themes</h3><p>A gallery of user-created themes is available, showcasing the variety of customizations that the Trilium community has developed. For more information, check the&nbsp;<a class=\"reference-link\" href=\"#root/_help_VbjZvtUek0Ln\">Theme Gallery</a>.</p><h3>Asset Path Management</h3><p>When referencing built-in assets like images in your custom themes or CSS, you can avoid hardcoding version numbers by using the <code>vX</code> alias. For example, instead of specifying <code>/assets/v0.57.0-beta/images/icon-grey.png</code>, you can use <code>/assets/vX/images/icon-grey.png</code> to keep your theme compatible with future versions of Trilium.</p>",
"_help_VbjZvtUek0Ln": "<p>These are user-created themes which were made publicly available:</p><h2>Legacy Themes</h2><p>These themes may or may not be compatible with the latest versions of TriliumNext and are based on the original/legacy theme.</p><figure class=\"table\"><table><thead><tr><th>Theme</th><th>Author</th></tr></thead><tbody><tr><td><a href=\"https://github.com/tobealive/trilium-midnight-theme\">Midnight</a></td><td><a href=\"https://github.com/tobealive\">tobealive</a></td></tr><tr><td><a href=\"https://github.com/tobealive/trilum-eote-theme\">EOTE</a></td><td><a href=\"https://github.com/tobealive\">tobealive</a></td></tr><tr><td><a href=\"https://github.com/Abourass/TriliumThemes\">Trilium Themes</a></td><td><a href=\"https://github.com/Abourass\">Abourass</a></td></tr><tr><td><a href=\"https://github.com/ZMonk91/Material-Dark-Trilium\">MaterialDark</a></td><td><a href=\"https://github.com/ZMonk91\">ZMonk91</a></td></tr><tr><td><a href=\"https://github.com/jaroet/trilium-theme-lightslategray\">lightslategray</a></td><td><a href=\"https://github.com/jaroet\">jaroet</a></td></tr><tr><td><a href=\"https://github.com/raphwriter/trilium-theme-melon\">melon-4</a></td><td><a href=\"https://github.com/raphwriter\">raphwriter</a></td></tr><tr><td><a href=\"https://github.com/Engr-AllanG/trilium-themes\">Neon_Dark</a></td><td><a href=\"https://github.com/Engr-AllanG\">Engr-AllanG</a></td></tr><tr><td><a href=\"https://github.com/Engr-AllanG/trilium-themes\">Coder_Dark</a></td><td><a href=\"https://github.com/Engr-AllanG\">Engr-AllanG</a></td></tr><tr><td><a href=\"https://github.com/idelem/trilium-theme-velvet\">velvet</a></td><td><a href=\"https://github.com/idelem\">idelem</a></td></tr><tr><td><a href=\"https://github.com/SADAVA/trilium-notes-theme-dark-plus\">Dark Plus</a></td><td><a href=\"https://github.com/SADAVA\">SADAVA</a></td></tr><tr><td><a href=\"https://github.com/WKSu/trilium-solarized-theme\">Solarized</a></td><td><a href=\"https://github.com/WKSu\">WKSu</a></td></tr><tr><td><a href=\"https://github.com/en3r0/Trilium-Nord-Theme\">Nord</a></td><td><a href=\"https://github.com/en3r0\">en3r0</a></td></tr><tr><td><a href=\"https://github.com/AllanZyne/trilium-bear-theme\">Bear Note Light</a></td><td><a href=\"https://github.com/AllanZyne\">AllanZyne</a></td></tr><tr><td><a href=\"https://github.com/AllanZyne/trilium-bear-theme\">Bear Note Dark</a></td><td><a href=\"https://github.com/AllanZyne\">AllanZyne</a></td></tr><tr><td><a href=\"https://github.com/Sebiann/miku-hatsune-trilium-theme\">Miku Hatsune</a></td><td><a href=\"https://github.com/Sebiann\">Sebiann</a></td></tr><tr><td><a href=\"https://github.com/cwilliams5/Midnight-Trilium-Dark-Mode\">Midnight</a></td><td><a href=\"https://github.com/cwilliams5\">cwilliams5</a></td></tr><tr><td><a href=\"https://github.com/SiriusXT/trilium-theme-blue\">Blue</a> (light)</td><td><a href=\"https://github.com/SiriusXT\">SiriusXT</a></td></tr><tr><td><a href=\"https://github.com/SiriusXT/trilium-theme-blue\">Blue</a> (dark)</td><td><a href=\"https://github.com/SiriusXT\">SiriusXT</a></td></tr></tbody></table></figure><aside class=\"admonition tip\"><p>If you would like to add your theme to this gallery, write a new post in <a href=\"https://github.com/TriliumNext/Trilium/discussions/categories/show-and-tell\">👐 Show and tell</a>.</p></aside>",
@@ -134,7 +134,7 @@
"_help_0Ofbk1aSuVRu": "<figure class=\"image image-style-align-right image_resized\" style=\"width:50.47%;\"><img style=\"aspect-ratio:880/553;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Images/Image%20references_image.png\" width=\"880\" height=\"553\"></figure><p>Image references are an easy way to embed the preview of another note type into a&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;note.</p><h2>Supported note types</h2><ul><li><a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a></li><li><a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a></li><li><a class=\"reference-link\" href=\"#root/_help_gBbsAeiuUxI5\">Mind Map</a></li></ul><h2>Steps</h2><ol><li>Go to one of the supported notes (listed above) and look for the&nbsp;<span class=\"tn-icon bx bx-copy\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_1P8QXI5edXNd\">Note buttons</a>&nbsp;area.</li><li>Go to a&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;note and use the Paste function to insert the reference to that note.</li></ol><h2>Interaction</h2><ul><li>Double-clicking an image reference from a text note will automatically open the target note.</li><li>Clicking an image reference while <kbd>Ctrl</kbd> is pressed will open the target note in a new tab.</li><li>Modifying the target note should also update the image reference. If that doesn't happen, consider&nbsp;<a class=\"reference-link\" href=\"#root/_help_s8alTXmpFR61\">Refreshing the application</a>.</li></ul>",
"_help_VRoP0g1uHHc2": "<figure class=\"image image-style-align-center image_resized\" style=\"width:76.29%;\"><img style=\"aspect-ratio:1479/865;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/In-editor%20AI%20assistant_image.png\" width=\"1479\" height=\"865\"></figure><p>The AI assistant works on the text you are already writing: select a passage and have it rewritten, translated or turned into a table, or ask for new content at the cursor. Unlike the <a href=\"#root/_help_LrKznOtw9cQD\">AI chat</a>, it does not open a conversation window, the result is previewed in place and only enters the note when you accept it.</p><h2>Requirements</h2><p>The assistant is only available once at least one provider is configured in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>AI / LLM</em>, with at least one model selected for it. Until then the toolbar entry is not shown at all.</p><h2>Accessing the AI assistant</h2><p>To access the AI assistant:</p><ul><li>Look for the&nbsp;<span class=\"tn-icon cke cke-trilium-ai\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>. Press the button itself to enter the <em>Ask AI</em> mode or press the arrow key next to it to access the quick commands and the model selection.</li><li>Look for <em>AI assistant</em> or any of the <em>AI</em>-prefixed quick commands in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</li><li>Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>K</kbd>.</li><li>Select a text and choose the <em>AI assistant</em> option in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_jcQVxzYybYgz\">Note contextual menu</a>.</li></ul><h2>What the assistant works on</h2><figure class=\"table\"><table><thead><tr><th>Situation</th><th>What is sent</th></tr></thead><tbody><tr><td>Text is selected</td><td>The selection.</td></tr><tr><td>Nothing is selected, and you pick a quick action</td><td>The paragraph the cursor is in.</td></tr><tr><td>Nothing is selected, and you type your own prompt</td><td>Nothing, the response is new content written at the cursor.</td></tr></tbody></table></figure><p>In all cases the assistant also sends the text before and after the target, so that the model can tell what it is writing into: asked to <em>Continue writing</em> or to summarize, a model that can only see the selected words is guessing at the document around them. This surrounding text is context only, it is never rewritten.</p><aside class=\"admonition important\"><p>That means a single run sends more than the passage you highlighted. See&nbsp;<a class=\"reference-link\" href=\"#root/_help_cRRrdZjgyhNc\">Privacy</a>&nbsp;for exactly what leaves your machine.</p></aside><h2>Quick actions</h2><p>The arrow beside the toolbar button opens a menu of ready-made instructions, grouped by what they do.</p><ul><li>The <em>Reformat</em> actions produce real Trilium content rather than plain text: <em>Diagram</em> inserts a Mermaid diagram, <em>Callout</em> an admonition, and <em>Collapsible</em> a collapsible block.</li><li>The <em>Translate</em> group lists the <a href=\"#root/_help_veGu4faJErEM\">content languages</a> you have enabled, or a predefined list if no content languages are set. It can be filled from within the editor, the last entry of the submenu opens the language configuration directly.</li></ul><p>Actions that need something to work on are greyed out when there is nothing to work on (for example an empty paragraph with no selection).</p><h2>Asking for something specific</h2><p>Choosing <em>Ask AI…</em> (<span class=\"tn-icon bx bx-message-square-dots\"></span>) opens a prompt where you can describe the change in your own words, for example: \"make this less formal\", \"add a row for 2024\", \"write an intro paragraph for this section\". Press <kbd>Enter</kbd> or the <span class=\"tn-icon cke cke-arrow-up\"></span> send button to run it.</p><p>Once a response arrives you can keep going in the same prompt, and the assistant treats it as a conversation rather than as a fresh request: after <em>Translate this to German</em>, asking for <em>make it shorter</em> shortens the German, not the original.</p><h2>Reviewing the result</h2><p>The response streams in as it is generated, and can be interrupted at any point by pressing the <em>Stop</em> (<span class=\"tn-icon cke cke-stop\"></span>) button; whatever arrived before that stays usable.</p><p>Nothing is written into the note until you say so. The review offers:</p><ul><li><em>Result</em>, which displays the response as it will be inserted.</li><li><em>Changes</em>, which displays an inline diff against the original, with insertions and deletions marked. When the model rewrote the passage rather than editing it, the review opens on <em>Result</em> instead: a diff of two texts with little in common is harder to read than the answer itself.</li><li><em>Try again</em> (<span class=\"tn-icon cke cke-refresh\"></span>), to re-run the same instruction.</li><li><em>Replace</em>, which substitutes the original passage</li><li><em>Insert below</em>, which keeps the original and adds the response after it.</li></ul><p>Trilium also reports the model that produced it, the tokens consumed and, for providers that report it, the price.</p><p>If you ask for a correction and there is nothing to correct, the assistant will indicate it instead of showing a blank diff.</p><h2>Choosing the model</h2><p>The bottom of the quick actions menu shows which model the assistant runs on, and lets you pick another from the models you selected in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>AI / LLM</em>, grouped by provider.</p><p>The model can also be changed while asking for something specific, or after the assistant has generated its response (i.e. if the response needs a better model).</p><p>This choice is separate from the model used by the chat, and is remembered across notes and devices. Left unset, the assistant follows the first configured provider.</p>",
"_help_mVEYwt20exhO": "<p><em>Quick actions</em> are a feature of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_VRoP0g1uHHc2\">In-editor AI assistant</a>&nbsp;for&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;notes which automatically triggers an LLM suggestion based on a defined prompt. The built-in quick actions come with a predefined prompt, but it is also possible to define your own quick actions.</p><h2>Creating a custom quick action</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>: </p><ol><li>Right-click the note where you want to place the quick action.</li><li>Select <em>Insert child note</em>.</li><li>Select <em>More</em> → <em>AI Quick Action</em>. The entry appears only when AI is enabled.</li></ol><p>Afterwards, simply type in the content of the note the desired prompt. The text can be formatted in the same manner as a normal text note and it will be passed to the LLM as Markdown.</p><p>The title of the note will become the title of the quick action.</p><p>Of note:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;notes work too.</li><li>An empty note is ignored.</li><li><a class=\"reference-link\" href=\"#root/_help_MKmLg5x6xkor\">Archived Notes</a>&nbsp;are also excluded.</li></ul><h2>Using a quick action</h2><p>Once a quick action is defined, the action will appear under the <em>Quick Actions</em> dropdown in a group called <em>Custom</em>.</p>",
- "_help_nBAXQFj20hS1": "<p>Text notes can \"include\" another note as a read-only widget or an interactive widget, depending on the type of note.</p><p>This can be useful for e.g. including a dynamically generated chart (from scripts &amp; \"render HTML\" note) or other more advanced use cases.</p><h2>Including a note</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the&nbsp;<span class=\"tn-icon cke cke-trilium-note\"></span> button. There is also a keyboard shortcut defined for it but it is not allocated by default.</p><p>To include a note that is already linked, right-click a reference link to it in a text note being edited and select <em>Convert link to an included note</em>, at the end of the menu. The include gets the box size that suits the note, as one added from the button does.</p><p>An <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> can be included the same way, from the context menu of a link to it (see <em>Embedding an attachment</em> there).</p><p>A link to blocks of a text note is converted the same way, with <em>Convert link to note excerpt</em>, and the include then shows only those blocks. See <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>.</p><h2>Box sizes</h2><p>The box size sets how much of the included note is shown.</p><ul><li><em>Tiny</em> shows a single row instead of the content: the note's icon, its title with the path to the note above it, and buttons to act on the note. The included note is never rendered, so wherever the note is shown outside the editor, such as in print, in a tooltip or on a shared page, a <em>Tiny</em> include appears as a link to the included note.</li><li><em>Small</em> and <em>Medium</em> show the content in a box of limited height. Text scrolls inside the box, while a picture, a diagram or a video is scaled down to fit it.</li><li><em>Full</em> shows the whole content.</li><li><em>Expandable</em> shows only the title until its <span class=\"tn-icon bx bx-chevron-right\"></span> arrow is pressed. In a read-only note, a click anywhere on the title row other than its buttons and link expands or collapses it as well.</li></ul><p>A new include gets the size that suits what it shows:</p><ul><li><em>Tiny</em> for a note or an attachment that has no preview, such as a relation map or an archive.</li><li><em>Small</em> for audio.</li><li><em>Full</em> for a code note or a code file, such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment, and for an excerpt of the blocks of a text note.</li><li><em>Medium</em> for anything else.</li></ul><p>The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the <em>Box size</em> menu in its toolbar, or the <em>Size</em> submenu of its <em>More actions</em> menu.</p><h2>Resizing</h2><p>A <em>Small</em>, <em>Medium</em> or <em>Expandable</em> include can be resized to any width and height. A <em>Tiny</em> or <em>Full</em> include always fits its content.</p><ul><li>To resize an include, select it and drag the handle in its bottom-right corner. To change only the width or only the height, drag the middle of its right or bottom edge instead, where a touch screen shows a handle too. In right-to-left text, the handle is in the bottom-left corner and the width changes from the left edge.</li><li>Resizing works with a mouse, a pen or a finger.</li><li>While the height changes, moving the handle near the top or the bottom of the note scrolls the note.</li><li>An include narrower than the note is centered, so changing its width moves both of its sides. Making it as wide as the note returns it to the full width.</li><li>To cancel a resize, press <kbd>Esc</kbd> before releasing the handle.</li><li>To reset the size, double-click the corner handle, or double-tap it on a touch screen. Double-clicking the right or bottom edge resets only the width or the height.</li><li>Choosing a box size resets the height. Choosing <em>Tiny</em> or <em>Full</em> resets the width too.</li><li>While an <em>Expandable</em> include is collapsed, only its width can be changed.</li></ul><h2>Caption</h2><p>An include can have a caption, shown centered at the bottom of its box. The caption is part of the text note, so it can be formatted like the rest of the text, for example in bold or with a link.</p><ul><li>To add a caption, select the include, press the <span class=\"tn-icon cke cke-caption\"></span> <em>Toggle caption on</em> button in its toolbar and type the caption.</li><li>To remove the caption, press the same button again. Pressing it once more brings back the text it had, as long as the note stays open.</li><li>A <em>Tiny</em> include has no caption. Switching an include to <em>Tiny</em> removes its caption, and switching it back to a larger size restores the caption, as long as the note stays open.</li><li>An <em>Expandable</em> include shows its caption under the title while the content is collapsed, and under the content once it is expanded.</li></ul><h2>Title</h2><p>The title row of an include links to the included note and holds its buttons. To show only the content, select the include and press the <span class=\"tn-icon bx bx-window-alt\"></span> <em>Show title</em> button in its toolbar. Pressing it again shows the title.</p><ul><li>While the title is hidden, the <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> button in the toolbar of the include opens the menu of the included note.</li><li>A <em>Tiny</em> or <em>Expandable</em> include always shows its title, and its toolbar has no <em>Show title</em> button.</li></ul><h2>Opening an included note</h2><p>To open an included note in a new tab, press the <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> button at the end of its title. An embedded attachment has the same button.</p><p>The <span class=\"tn-icon bx bx-dots-vertical-rounded\"></span> <em>More actions</em> button at the end of the title row opens the same menu as right-clicking anywhere on the title row: the other places to open the note in and, for an embedded attachment, the actions on the attachment.</p><p>In a note being edited, the menu also has the commands of the include's toolbar: the <em>Size</em> submenu, <em>Show title</em> and <em>Show caption</em>, each checked while it is in effect, and <em>Convert to link</em> at the end. A drawing canvas, an included text or code note and an embedded code file also have <em>Editable</em>, above <em>Size</em>. For an embedded attachment they follow its first group of actions; for an included note they end the menu.</p><p>To show an include of size <em>Medium</em> or <em>Full</em> on the whole screen, press the <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em> button at the end of its title. An excerpt of the blocks of a note has an <span class=\"tn-icon bx bx-pencil\"></span> <em>Edit excerpt</em> button there instead; see <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>. To return, press <span class=\"tn-icon bx bx-exit\"></span> <em>Exit fullscreen</em> in the top-right corner, or <kbd>Esc</kbd>.</p><p>A <em>Tiny</em> include has these buttons instead, followed by the same <em>More actions</em> button:</p><ul><li>For a note, <span class=\"tn-icon bx bx-edit\"></span> <em>Quick edit</em> opens the note in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, and <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> opens it in a new tab.</li><li>For an embedded attachment, <span class=\"tn-icon bx bx-file-find\"></span> <em>Open externally</em> opens the file in another application, and <span class=\"tn-icon bx bx-download\"></span> <em>Download</em> downloads it. The size of the file is shown under its title.</li></ul><h2>Converting an include to a link</h2><p>To replace an include with a link to the included note, select it and press the <span class=\"tn-icon cke cke-link\"></span> <em>Convert to link</em> button in its toolbar, or choose <em>Convert to link</em> at the end of its <em>More actions</em> menu. An embedded attachment turns into a link to the attachment the same way.</p><h2>Included notes in the share functionality</h2><p>If a <a href=\"#root/_help_R9pX4DGra2Vt\">shared note</a> contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself. The caption of an include is shown under the included content. A <em>Tiny</em> include is shown as a link to the included note instead, and so is an include that would show a note already shown around it, such as a note that includes itself. The same goes for a printed or exported note.</p><p>For this to work, the included notes must also be shared, otherwise they will not be shown. However, the included notes can still be hidden from the note tree via <code>#shareHiddenFromTree</code>.</p><h2>Interactive notes</h2><p>Since v0.104.0, included notes might become interactive depending on their note type:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>&nbsp;(e.g.&nbsp;<a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a>) will render fully interactive, including creating new notes.</li><li><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a>&nbsp;will also display the results.</li><li><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a>&nbsp;provides an interactive preview of the website.</li></ul><h2>Included images</h2><p>An included image, whether an image note or an image attachment, is shown in the image viewer, which zooms and pans it:</p><ul><li>To zoom, press the <span class=\"tn-icon bx bx-plus-circle\"></span> <em>Zoom in</em> and <span class=\"tn-icon bx bx-minus-circle\"></span> <em>Zoom out</em> buttons in the bottom-right corner of the image, or pinch on a touch screen. The percentage between them resets the zoom.</li><li>To zoom with the mouse wheel, click the image first. Until then, the mouse wheel scrolls the note.</li><li>To pan an image that is zoomed in, drag it. At its fitted size, dragging the image on a touch screen scrolls the note.</li><li>To return to the fitted size, double-click the image.</li></ul><p>In a <em>Small</em> or <em>Medium</em> box, the image is scaled down to fit the height of the box. In fullscreen, it fits the screen.</p><h2>Editing an include in place</h2><p>An included text note, an included code note and an embedded code file such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment can be edited without leaving the note that includes them. A code note or file is shown with syntax highlighting until then.</p><ul><li>To edit, select the include and turn on the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or check <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. Turn <em>Editable</em> off to return to the preview.</li><li>While <em>Editable</em> is on, the arrow keys move the caret into the include and back out, as through the rest of the text. Entering from above or from the left puts the caret at the start of the include, and entering from below or from the right puts it at the end. A collapsed <em>Expandable</em> include is skipped.</li><li>While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.</li><li>Code is edited in the same code editor as a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note, with its theme, indentation and line wrapping settings.</li><li>The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.</li><li>An include of <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a> edits only the referenced blocks.</li><li>Editing is not available in a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, for an included note marked <code>#readOnly</code>, or for an attachment of another note.</li></ul><h2>Drawing canvases</h2><p>A drawing canvas is an Excalidraw canvas, like the one of a <a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a> note, drawn directly in the text note. It is not a note of its own: the drawing is kept in a <code>Canvas.excalidraw</code> <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> of the text note and is saved together with the text.</p><ul><li>To insert a drawing canvas, open the <span class=\"tn-icon cke cke-plus\"></span> <em>Insert</em> menu of the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> and choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em>, above <em>Mermaid diagram</em>. It is also available as <em>Drawing canvas</em> in the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>. The canvas is added empty and editable, in a <em>Medium</em> box with its title hidden, and takes the focus, ready for drawing.</li><li>To draw or write over an image, select the image and press the <span class=\"tn-icon bx bxs-pen\"></span> <em>Convert image to a drawing canvas</em> button of its toolbar. The image is replaced by an editable drawing canvas in a <em>Medium</em> box, with its title hidden and the focus in it. The image sits at its original size in the middle of the canvas, zoomed so that all of it shows, and is locked so that it cannot be selected or moved by accident. While it is locked, the canvas can be zoomed in on the image but not zoomed out past it or scrolled beyond its edges. To move or resize the image anyway, right-click it and choose <em>Unlock</em>. The caption of the image is kept, but not its alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.</li><li>An Excalidraw file (<code>.excalidraw</code>) attached with the <span class=\"tn-icon cke cke-paper-clip\"></span><em>Attach file</em> button becomes a drawing canvas too, in a <em>Medium</em> box titled with the file name. It starts with <em>Editable</em> off, so the drawing shows but cannot be changed until <em>Editable</em> is turned on (see below).</li><li>To draw on a canvas that does not have the focus, click it first. Until then, touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.</li><li>The mouse wheel and the touchpad scroll the note over a canvas too, as over the text. To zoom, use the zoom buttons of the canvas toolbar; to move around the drawing, use the <span class=\"tn-icon bx bxs-hand\"></span> <em>Hand</em> tool. In fullscreen, the mouse wheel moves and zooms the drawing instead.</li><li>The canvas toolbar replaces the Excalidraw menu: <em>Export image</em>, <em>Find on canvas</em>, <em>Library</em> and <em>Help</em> are at the end of its <span class=\"tn-icon bx bx-category\"></span> <em>More tools</em> menu. In fullscreen, the Excalidraw menu shows again.</li><li>A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.</li><li>To protect a finished drawing from accidental changes, select it and turn off the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or uncheck <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. The drawing then shows as a still picture, at the zoom and position it had, and can no longer be changed, zoomed or moved. To draw again, turn <em>Editable</em> back on.</li><li>The box sizes, resizing, the caption and the title work as for an included note, but the toolbar of a drawing leaves the box size, <em>Show title</em> and <em>Convert to link</em> to its <em>More actions</em> menu.</li><li>In the desktop layout, Excalidraw keeps its desktop interface however small the box is. In the mobile layout, a narrow or short box switches it to a compact interface. For more room, choose <em>Full</em>, or show the title and press <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em>.</li><li>Pictures added to the drawing are stored in the same attachment. A converted image is kept as an image attachment of the note instead, named with a generated code.</li><li>In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the drawing shows as a still picture too.</li><li>On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, the drawing is shown as a picture at its own size, whatever the size of its box, in light or dark colors to match the page. Each change to the drawing saves this picture as an SVG image attachment of the note, also named with a generated code.</li></ul><h3>Limitations</h3><ul><li>The Excalidraw shape library is not saved for a drawing canvas.</li><li>Outside the editor, for example in a tooltip, when printing or in the list of attachments, the drawing is shown as a picture.</li><li>A drawing has no picture for shared pages until its first change, except one converted from an image. Until then, for example for an attached <code>.excalidraw</code> file, a shared page shows a link to download the drawing instead.</li><li>In Safari, the picture of a drawing on a shared page follows the light or dark appearance of the system rather than the theme chosen on the page.</li><li>A copy of a drawing canvas pasted in the same note shares the drawing with the original, so a change to one shows in the other only after the note is opened again. A copy pasted in another note gets a drawing of its own.</li></ul>",
+ "_help_nBAXQFj20hS1": "<p>Text notes can \"include\" another note as a read-only widget or an interactive widget, depending on the type of note.</p><p>This can be useful for e.g. including a dynamically generated chart (from scripts &amp; \"render HTML\" note) or other more advanced use cases.</p><h2>Including a note</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the&nbsp;<span class=\"tn-icon cke cke-trilium-note\"></span> button. There is also a keyboard shortcut defined for it but it is not allocated by default.</p><p>To include a note that is already linked, right-click a reference link to it in a text note being edited and select <em>Convert link to an included note</em>, at the end of the menu. The include gets the box size that suits the note, as one added from the button does.</p><p>An <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> can be included the same way, from the context menu of a link to it (see <em>Embedding an attachment</em> there).</p><p>A link to blocks of a text note is converted the same way, with <em>Convert link to note excerpt</em>, and the include then shows only those blocks. See <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>.</p><h2>Box sizes</h2><p>The box size sets how much of the included note is shown.</p><ul><li><em>Tiny</em> shows a single row instead of the content: the note's icon, its title with the path to the note above it, and buttons to act on the note. The included note is never rendered, so wherever the note is shown outside the editor, such as in print, in a tooltip or on a shared page, a <em>Tiny</em> include appears as a link to the included note.</li><li><em>Small</em> and <em>Medium</em> show the content in a box of limited height. Text scrolls inside the box, while a picture, a diagram or a video is scaled down to fit it.</li><li><em>Full</em> shows the whole content.</li><li><em>Expandable</em> shows only the title until its <span class=\"tn-icon bx bx-chevron-right\"></span> arrow is pressed. In a read-only note, a click anywhere on the title row other than its buttons and link expands or collapses it as well.</li></ul><p>A new include gets the size that suits what it shows:</p><ul><li><em>Tiny</em> for a note or an attachment that has no preview, such as a relation map or an archive.</li><li><em>Small</em> for audio.</li><li><em>Full</em> for a code note or a code file, such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment, and for an excerpt of the blocks of a text note.</li><li><em>Medium</em> for anything else.</li></ul><p>The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the <em>Box size</em> menu in its toolbar, or the <em>Size</em> submenu of its <em>More actions</em> menu.</p><h2>Resizing</h2><p>A <em>Small</em>, <em>Medium</em> or <em>Expandable</em> include can be resized to any width and height. A <em>Tiny</em> or <em>Full</em> include always fits its content.</p><ul><li>To resize an include, select it and drag the handle in its bottom-right corner. To change only the width or only the height, drag the middle of its right or bottom edge instead, where a touch screen shows a handle too. In right-to-left text, the handle is in the bottom-left corner and the width changes from the left edge.</li><li>Resizing works with a mouse, a pen or a finger.</li><li>While the height changes, moving the handle near the top or the bottom of the note scrolls the note.</li><li>An include narrower than the note is centered, so changing its width moves both of its sides. Making it as wide as the note returns it to the full width.</li><li>To cancel a resize, press <kbd>Esc</kbd> before releasing the handle.</li><li>To reset the size, double-click the corner handle, or double-tap it on a touch screen. Double-clicking the right or bottom edge resets only the width or the height.</li><li>Choosing a box size resets the height. Choosing <em>Tiny</em> or <em>Full</em> resets the width too.</li><li>While an <em>Expandable</em> include is collapsed, only its width can be changed.</li></ul><h2>Caption</h2><p>An include can have a caption, shown centered at the bottom of its box. The caption is part of the text note, so it can be formatted like the rest of the text, for example in bold or with a link.</p><ul><li>To add a caption, select the include, press the <span class=\"tn-icon cke cke-caption\"></span> <em>Toggle caption on</em> button in its toolbar and type the caption.</li><li>To remove the caption, press the same button again. Pressing it once more brings back the text it had, as long as the note stays open.</li><li>A <em>Tiny</em> include has no caption. Switching an include to <em>Tiny</em> removes its caption, and switching it back to a larger size restores the caption, as long as the note stays open.</li><li>An <em>Expandable</em> include shows its caption under the title while the content is collapsed, and under the content once it is expanded.</li></ul><h2>Title</h2><p>The title row of an include links to the included note and holds its buttons. To show only the content, select the include and press the <span class=\"tn-icon bx bx-window-alt\"></span> <em>Show title</em> button in its toolbar. Pressing it again shows the title.</p><ul><li>While the title is hidden, the <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> button in the toolbar of the include opens the menu of the included note.</li><li>A <em>Tiny</em> or <em>Expandable</em> include always shows its title, and its toolbar has no <em>Show title</em> button.</li></ul><h2>Opening an included note</h2><p>To open an included note in a new tab, press the <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> button at the end of its title. An embedded attachment has the same button.</p><p>The <span class=\"tn-icon bx bx-dots-vertical-rounded\"></span> <em>More actions</em> button at the end of the title row opens the same menu as right-clicking anywhere on the title row: the other places to open the note in and, for an embedded attachment, the actions on the attachment.</p><p>In a note being edited, the menu also has the commands of the include's toolbar: the <em>Size</em> submenu, <em>Show title</em> and <em>Show caption</em>, each checked while it is in effect, and <em>Convert to link</em> at the end. A drawing canvas, an included text or code note and an embedded code file also have <em>Editable</em>, above <em>Size</em>. For an embedded attachment they follow its first group of actions; for an included note they end the menu.</p><p>To show an include of size <em>Medium</em> or <em>Full</em> on the whole screen, press the <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em> button at the end of its title. An excerpt of the blocks of a note has an <span class=\"tn-icon bx bx-pencil\"></span> <em>Edit excerpt</em> button there instead; see <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>. To return, press <span class=\"tn-icon bx bx-exit\"></span> <em>Exit fullscreen</em> in the top-right corner, or <kbd>Esc</kbd>.</p><p>A <em>Tiny</em> include has these buttons instead, followed by the same <em>More actions</em> button:</p><ul><li>For a note, <span class=\"tn-icon bx bx-edit\"></span> <em>Quick edit</em> opens the note in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, and <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> opens it in a new tab.</li><li>For an embedded attachment, <span class=\"tn-icon bx bx-file-find\"></span> <em>Open externally</em> opens the file in another application, and <span class=\"tn-icon bx bx-download\"></span> <em>Download</em> downloads it. The size of the file is shown under its title.</li></ul><h2>Converting an include to a link</h2><p>To replace an include with a link to the included note, select it and press the <span class=\"tn-icon cke cke-link\"></span> <em>Convert to link</em> button in its toolbar, or choose <em>Convert to link</em> at the end of its <em>More actions</em> menu. An embedded attachment turns into a link to the attachment the same way.</p><h2>Included notes in the share functionality</h2><p>If a <a href=\"#root/_help_R9pX4DGra2Vt\">shared note</a> contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself. The caption of an include is shown under the included content. A <em>Tiny</em> include is shown as a link to the included note instead, and so is an include that would show a note already shown around it, such as a note that includes itself. The same goes for a printed or exported note.</p><p>For this to work, the included notes must also be shared, otherwise they will not be shown. However, the included notes can still be hidden from the note tree via <code>#shareHiddenFromTree</code>.</p><h2>Interactive notes</h2><p>Since v0.104.0, included notes might become interactive depending on their note type:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>&nbsp;(e.g.&nbsp;<a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a>) will render fully interactive, including creating new notes.</li><li><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a>&nbsp;will also display the results.</li><li><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a>&nbsp;provides an interactive preview of the website.</li></ul><h2>Included images</h2><p>An included image, whether an image note or an image attachment, is shown in the image viewer, which zooms and pans it:</p><ul><li>To zoom, press the <span class=\"tn-icon bx bx-plus-circle\"></span> <em>Zoom in</em> and <span class=\"tn-icon bx bx-minus-circle\"></span> <em>Zoom out</em> buttons in the bottom-right corner of the image, or pinch on a touch screen. The percentage between them resets the zoom.</li><li>To zoom with the mouse wheel, click the image first. Until then, the mouse wheel scrolls the note.</li><li>To pan an image that is zoomed in, drag it. At its fitted size, dragging the image on a touch screen scrolls the note.</li><li>To return to the fitted size, double-click the image.</li></ul><p>In a <em>Small</em> or <em>Medium</em> box, the image is scaled down to fit the height of the box. In fullscreen, it fits the screen.</p><h2>Editing an include in place</h2><p>An included text note, an included code note and an embedded code file such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment can be edited without leaving the note that includes them. A code note or file is shown with syntax highlighting until then.</p><ul><li>To edit, select the include and turn on the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or check <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. Turn <em>Editable</em> off to return to the preview.</li><li>While <em>Editable</em> is on, the arrow keys move the caret into the include and back out, as through the rest of the text. Entering from above or from the left puts the caret at the start of the include, and entering from below or from the right puts it at the end. A collapsed <em>Expandable</em> include is skipped.</li><li>While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.</li><li>Code is edited in the same code editor as a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note, with its theme, indentation and line wrapping settings.</li><li>The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.</li><li>An include of <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a> edits only the referenced blocks.</li><li>Editing is not available in a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, for an included note marked <code>#readOnly</code>, or for an attachment of another note.</li><li><a class=\"reference-link\" href=\"#root/_help_McngOG2jbUWX\">Search in note</a> finds the text of included text and code notes among the results of the note around them, and replaces it while <em>Editable</em> is on.</li></ul><h2>Drawing canvases</h2><p>A drawing canvas is an Excalidraw canvas, like the one of a <a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a> note, drawn directly in the text note. It is not a note of its own: the drawing is kept in a <code>Canvas.excalidraw</code> <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> of the text note and is saved together with the text.</p><ul><li>To insert a drawing canvas, open the <span class=\"tn-icon cke cke-plus\"></span> <em>Insert</em> menu of the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> and choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em>, above <em>Mermaid diagram</em>. It is also available as <em>Drawing canvas</em> in the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>. The canvas is added empty and editable, in a <em>Medium</em> box with its title hidden, and takes the focus, ready for drawing.</li><li>To draw or write over an image, select the image and press the <span class=\"tn-icon bx bxs-pen\"></span> <em>Convert image to a drawing canvas</em> button of its toolbar. The image is replaced by an editable drawing canvas in a <em>Medium</em> box, with its title hidden and the focus in it. The image sits at its original size in the middle of the canvas, zoomed so that all of it shows, and is locked so that it cannot be selected or moved by accident. While it is locked, the canvas can be zoomed in on the image but not zoomed out past it or scrolled beyond its edges. To move or resize the image anyway, right-click it and choose <em>Unlock</em>. The caption of the image is kept, but not its alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.</li><li>An Excalidraw file (<code>.excalidraw</code>) attached with the <span class=\"tn-icon cke cke-paper-clip\"></span><em>Attach file</em> button becomes a drawing canvas too, in a <em>Medium</em> box titled with the file name. It starts with <em>Editable</em> off, so the drawing shows but cannot be changed until <em>Editable</em> is turned on (see below).</li><li>To draw on a canvas that does not have the focus, click it first. Until then, touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.</li><li>The mouse wheel and the touchpad scroll the note over a canvas too, as over the text. To zoom, use the zoom buttons of the canvas toolbar; to move around the drawing, use the <span class=\"tn-icon bx bxs-hand\"></span> <em>Hand</em> tool. In fullscreen, the mouse wheel moves and zooms the drawing instead.</li><li>The canvas toolbar replaces the Excalidraw menu: <em>Export image</em>, <em>Find on canvas</em>, <em>Library</em> and <em>Help</em> are at the end of its <span class=\"tn-icon bx bx-category\"></span> <em>More tools</em> menu. In fullscreen, the Excalidraw menu shows again.</li><li>A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.</li><li>To protect a finished drawing from accidental changes, select it and turn off the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or uncheck <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. The drawing then shows as a still picture, at the zoom and position it had, and can no longer be changed, zoomed or moved. To draw again, turn <em>Editable</em> back on.</li><li>The box sizes, resizing, the caption and the title work as for an included note, but the toolbar of a drawing leaves the box size, <em>Show title</em> and <em>Convert to link</em> to its <em>More actions</em> menu.</li><li>In the desktop layout, Excalidraw keeps its desktop interface however small the box is. In the mobile layout, a narrow or short box switches it to a compact interface. For more room, choose <em>Full</em>, or show the title and press <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em>.</li><li>Pictures added to the drawing are stored in the same attachment. A converted image is kept as an image attachment of the note instead, named with a generated code.</li><li>In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the drawing shows as a still picture too.</li><li>On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, the drawing is shown as a picture at its own size, whatever the size of its box, in light or dark colors to match the page. Each change to the drawing saves this picture as an SVG image attachment of the note, also named with a generated code.</li></ul><h3>Limitations</h3><ul><li>The Excalidraw shape library is not saved for a drawing canvas.</li><li>Outside the editor, for example in a tooltip, when printing or in the list of attachments, the drawing is shown as a picture.</li><li>A drawing has no picture for shared pages until its first change, except one converted from an image. Until then, for example for an attached <code>.excalidraw</code> file, a shared page shows a link to download the drawing instead.</li><li>In Safari, the picture of a drawing on a shared page follows the light or dark appearance of the system rather than the theme chosen on the page.</li><li>A copy of a drawing canvas pasted in the same note shares the drawing with the original, so a change to one shows in the other only after the note is opened again. A copy pasted in another note gets a drawing of its own.</li></ul>",
"_help_CohkqWQC1iBv": "<p>Press the&nbsp;<span class=\"tn-icon cke cke-plus\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>&nbsp;to reveal special inserable items and blocks such as symbols, Math expressions and separators.</p><h2>Bookmarks</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_oSuaNgyyKnhu\">Anchors</a>&nbsp;section.</p><h2>Emoji</h2><figure class=\"image image-style-align-right image_resized\" style=\"width:42.4%;\"><img style=\"aspect-ratio:366/410;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_plus.png\" width=\"366\" height=\"410\"></figure><p>This feature allows inserting Unicode emoji characters. Simply select a category and a desired emoji to insert it.</p><p>Emojis can also be searched by their English name and the skin tone can be selected via a combo box to the right.</p><p>There is also the possibility of inserting emojis directly by typing <code>:</code> followed by a name of an emoji, triggering the display of a list of emojis. Simply use the arrow keys to select one and press <kbd>Enter</kbd> or <kbd>Tab</kbd> to insert it.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_plus.png\" width=\"272\" height=\"187\"><h2>Symbols</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:346/322;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_image.png\" width=\"346\" height=\"322\"></figure><p>Pressing the&nbsp;<span class=\"tn-icon cke cke-special-characters\"></span> button will reveal a popup window displaying a list of characters that are generally more difficult to insert directly from the keyboard, such as a subset of emojis, quotation characters, etc.</p><p>Interaction:</p><ul><li>Click on a character to insert it at the current cursor position.</li><li>The window can be dragged around by the top bar where the title is, to avoid it getting in the way of the text.</li><li>Click on the <em>Category</em> selector to filter the characters.</li></ul><h2>Multicolumn layout</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a>&nbsp;page.</p><h2>Math equations</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a>&nbsp;page.</p><h2>Drawing canvas</h2><p>Choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em> to draw on an Excalidraw canvas inside the text. See <em>Drawing canvases</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><h2>Mermaid diagram</h2><p>Press the&nbsp;<span class=\"tn-icon cke cke-trilium-mermaid-insert\"></span> button to create an inline Mermaid diagram.</p><p>This feature is quite similar to the&nbsp;<a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a>&nbsp;note types and is meant as an alternative to it for simple diagrams. For more complex diagrams, use the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>&nbsp;feature for a dedicated Mermaid note.</p><figure class=\"image\"><img style=\"aspect-ratio:1174/358;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Insert%20buttons_image.png\" width=\"1174\" height=\"358\"></figure><h2>Horizontal ruler</h2><p>This feature will display a horizontal line, generally useful to separate different sections of the text. To do so, press the&nbsp;<span class=\"tn-icon cke cke-horizontal-line\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_image.png\" width=\"502\" height=\"95\"><p>Alternatively, it's possible to insert a horizontal ruler by typing <code>---</code>.</p><h2>Page break</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:371/79;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/3_Insert%20buttons_image.png\" width=\"371\" height=\"79\"></figure><p>Page breaks provide a way to force the next paragraph or block (table, image, etc.) to be displayed onto the next page when printing (either to a real printer to <a href=\"#root/_help_NRnIZmSMc5sj\">when exporting to PDF</a>).</p><p>Page breaks are marked in the editor with the words <em>Page break</em>, but they will not actually be shown when printed.</p><ul><li>To insert a page break, press the&nbsp;<span class=\"tn-icon cke cke-page-break\"></span> in the formatting toolbar.</li><li>To insert many page breaks at once, insert a page break first, click on it and press <kbd>Ctrl</kbd>+<kbd>C</kbd>. Then use <kbd>Ctrl</kbd>+<kbd>V</kbd>, to paste as many times as needed.</li></ul><h2>Date and time</h2><p>The <span class=\"tn-icon cke cke-trilium-date-time\"></span> button inserts the current date and time at the cursor, replacing the selected text if there is any. The inserted text takes the formatting of the text around it, so a date inserted inside bold text is bold too.</p><ul><li>To insert the date in the default format, press the button itself or press <kbd>Alt</kbd>+<kbd>T</kbd>.</li><li>To insert it in another format, press the arrow next to the button and pick a format from the list. Each entry shows the current date and time in that format: the default one, the date or the time alone, the date written out, and ISO 8601.</li><li>The same formats are offered by the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>: type <code>/date</code>, <code>/time</code>, <code>/now</code> or <code>/today</code>. The <em>Insert date/time</em> entry uses the default format, and shows what it inserts underneath; the other entries show their output in the title.</li></ul><p>The default format can be changed in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text Notes</em> → <em>Editor</em> → <em>Date/time format</em>, using <a href=\"https://day.js.org/docs/en/display/format\">Day.js format tokens</a> (for example <code>DD.MM.YYYY HH:mm</code>).</p><h2>Icons</h2><p>Icons just like the ones for the <a href=\"#root/_help_p9kXRFAkwN4o\">note icon</a> can be inserted in text. For more information see&nbsp;<a class=\"reference-link\" href=\"#root/_help_hD8GawVuazff\">Icons</a>.</p>",
"_help_hD8GawVuazff": "<p>Icons just like the <a href=\"#root/_help_hD8GawVuazff\">note icons</a> can be inserted in the content of a note, including from any other <a href=\"#root/_help_gOKqSJgXLcIj\">custom icon packs</a>.</p><h2>Features</h2><ul><li>The icon can be formatted through the<a class=\"reference-link\" href=\"#root/_help_Gr6xFaF6ioJ5\">General formatting</a>&nbsp;tools of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>:<ul><li>Foreground/icon color</li><li>Background color/highlight</li><li>Font size</li></ul></li><li>Custom&nbsp;<a class=\"reference-link\" href=\"#root/_help_gOKqSJgXLcIj\">Icon Packs</a>&nbsp;are also supported.<ul><li>For emojis, prefer the Emoji functionality from&nbsp;<a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a>.</li></ul></li><li>When an icon is clicked a floating toolbar appears with the following functions:<ul><li><span class=\"tn-icon bx bx-sticker\"></span>&nbsp;which changes the icon.</li><li><span class=\"tn-icon bx bx-reflect-horizontal\"></span>&nbsp;which applies transforms: rotate (90 / 180 / 270) and flip horizontal/vertical. Only one transform can be used per icon.</li></ul></li></ul><h2>Usage</h2><ul><li>The in-app help/user guide makes use of these icons in order to illustrate buttons in the UI.</li><li>The&nbsp;<a class=\"reference-link\" href=\"#root/_help_GnhlmrATVqcH\">Microsoft OneNote</a>&nbsp;importer also makes use of them for the&nbsp;<a class=\"reference-link\" href=\"#root/_help_LpvyEIBIAAj7\">Tags</a>.</li></ul><h2>Inserting an icon</h2><p>There are two ways to insert an icon:</p><ul><li>Via the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>&nbsp;look for the&nbsp;<span class=\"tn-icon bx bx-plus\"></span> icon and then the&nbsp;<span class=\"tn-icon bx bx-sticker\"></span> icon.</li><li>Via&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>, type <code>/icon</code>.</li></ul><p>An icon picker will appear, search for an icon and click it to insert it in the document.</p><h2>Finding notes by their icons</h2><p>An icon can be <a href=\"#root/_help_eIg8jdvaoNNd\">searched</a>. A note containing a&nbsp;<span class=\"tn-icon bx bx-star\"></span> icon can be found by searching for <code>star</code>, or its <code>iconClass</code> (<code>bx-star</code>).</p><p>To find the name of the icon, hover the mouse over an icon while in the icon picker.</p><h2>Markdown rendering</h2><p>When exporting to&nbsp;<a class=\"reference-link\" href=\"#root/_help_Oau6X9rCuegd\">Markdown</a>, the item will render as raw HTML representation of the icon as is used by Trilium:</p><pre><code class=\"language-text-html\">&lt;span class=\"tn-icon bx bx-star\"&gt;&lt;/span&gt;</code></pre>",
"_help_oiVPnW8QfnvS": "<h2>Trilium-specific shortcuts</h2><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Bring up inline formatting toolbar (arrow keys ←,→ to navigate, Enter to apply)</td><td>Alt+F10</td><td>⌥+F10</td></tr><tr><td>Bring up block formatting toolbar</td><td>Alt+F10</td><td>⌥+F10</td></tr><tr><td>Create <a href=\"#root/_help_QEAPj01N5f7w\">external link</a></td><td>Ctrl+K</td><td>⌘+K</td></tr><tr><td>Create <a href=\"#root/_help_QEAPj01N5f7w\">internal (note) link</a></td><td>Ctrl+L</td><td>⌘+L</td></tr><tr><td>Inserts current date and time at caret position</td><td>Alt+T</td><td>⌥+T</td></tr><tr><td>Increase paragraph indentation</td><td>Tab</td><td>⇥</td></tr><tr><td>Decrease paragraph indentation</td><td>Shift + Tab</td><td>⇧ + ⇥</td></tr><tr><td>Mark selected text as <a href=\"#root/_help_UYuUB1ZekNQU\">keyboard shortcut</a></td><td>Ctrl + Alt + K</td><td>⌘+ ⌥+ K</td></tr><tr><td>Insert&nbsp;<a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a></td><td>Ctrl + M</td><td>⌘+ M</td></tr><tr><td>Move blocks (lists, paragraphs, etc.) up</td><td>Ctrl+↑</td><td>⌘+↑</td></tr><tr><td>Alt+↑</td><td>⌥+↑</td><td></td></tr><tr><td>Move blocks (lists, paragraphs, etc.) down</td><td>Ctrl+↑</td><td>⌘+↑</td></tr><tr><td>Alt+↓</td><td>⌥+↓</td><td></td></tr><tr><td>Move the selected content to another column of a <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a></td><td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td><td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td></tr><tr><td>Move the current column of a multicolumn layout</td><td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td><td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td></tr><tr><td>Add a column after or before the current one in a multicolumn layout</td><td>Ctrl+Enter, Ctrl+Shift+Enter</td><td>⌘+Enter, ⌘+⇧+Enter</td></tr><tr><td>Move the selected content to another tab in <a class=\"reference-link\" href=\"#root/_help_EK2ckIZ74tbT\">Content tabs</a></td><td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td><td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td></tr><tr><td>Move the current tab of a tabs block</td><td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td><td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td></tr><tr><td>Add a tab after or before the current one in a tabs block</td><td>Ctrl+Enter, Ctrl+Shift+Enter</td><td>⌘+Enter, ⌘+⇧+Enter</td></tr></tbody></table></figure><h2>Common shortcuts</h2><aside class=\"admonition tip\"><p>This section of keyboard shortcuts presents a subset of the keyboard shortcuts as supported by the editor technology we are using,&nbsp;<a class=\"reference-link\" href=\"#root/_help_MI26XDLSAlCD\">CKEditor</a>. The shortcuts were taken from the <a href=\"https://ckeditor.com/docs/ckeditor5/latest/features/accessibility.html#keyboard-shortcuts\">official documentation</a>. Note that not all the shortcuts in the original documentation are applicable (due to using a different configuration).</p></aside><h3>Content editing</h3><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Insert a hard break (a new paragraph)</td><td>Enter</td><td></td></tr><tr><td>Insert a soft break (a <code>&lt;br&gt;</code> element)</td><td>Shift+Enter</td><td>⇧Enter</td></tr><tr><td>Copy selected content</td><td>Ctrl+C</td><td>⌘C</td></tr><tr><td>Paste content</td><td>Ctrl+V</td><td>⌘V</td></tr><tr><td>Paste content as plain text</td><td>Ctrl+Shift+V</td><td>⌘⇧V</td></tr><tr><td>Undo</td><td>Ctrl+Z</td><td>⌘Z</td></tr><tr><td>Redo</td><td>Ctrl+Y, Ctrl+Shift+Z</td><td>⌘Y, ⌘⇧Z</td></tr><tr><td>Bold text</td><td>Ctrl+B</td><td>⌘B</td></tr><tr><td>Change text case</td><td>Shift+F3</td><td>⇧F3 (may require Fn)</td></tr><tr><td>Create link</td><td>Ctrl+K</td><td>⌘K</td></tr><tr><td>Move out of a link</td><td>←←, →→</td><td></td></tr><tr><td>Move out of an inline code style</td><td>←←, →→</td><td></td></tr><tr><td>Select all</td><td>Ctrl+A</td><td>⌘A</td></tr><tr><td>Find in the document</td><td>Ctrl+F</td><td>⌘F</td></tr><tr><td>Copy text formatting</td><td>Ctrl+Shift+C</td><td>⌘⇧C</td></tr><tr><td>Paste text formatting</td><td>Ctrl+Shift+V</td><td>⌘⇧V</td></tr><tr><td>Italic text</td><td>Ctrl+I</td><td>⌘I</td></tr><tr><td>Strikethrough text</td><td>Ctrl+Shift+X</td><td>⌘⇧X</td></tr><tr><td>Underline text</td><td>Ctrl+U</td><td>⌘U</td></tr><tr><td>Revert autoformatting action</td><td>Backspace</td><td></td></tr></tbody></table></figure><h3>Interacting with blocks</h3><p>Blocks are images, tables, blockquotes, annotations.</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Insert a new paragraph directly after a widget</td><td>Enter</td><td></td></tr><tr><td>Insert a new paragraph directly before a widget</td><td>Shift+Enter</td><td>⇧Enter</td></tr><tr><td>Move the caret to allow typing directly before a widget</td><td>↑, ←</td><td></td></tr><tr><td>Move the caret to allow typing directly after a widget</td><td>↓, →</td><td></td></tr><tr><td>After entering a nested editable, move the selection to the closest ancestor widget. For example: move from an image caption to the whole image widget.</td><td>Tab then Esc</td><td></td></tr></tbody></table></figure><p>Specifically for lists:</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Increase list item indent</td><td>⇥</td><td></td></tr><tr><td>Decrease list item indent</td><td>Shift+⇥</td><td>⇧⇥</td></tr></tbody></table></figure><p>In tables:</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Move the selection to the next cell</td><td>⇥</td><td></td></tr><tr><td>Move the selection to the previous cell</td><td>Shift+⇥</td><td>⇧⇥</td></tr><tr><td>Insert a new table row (when in the last cell of a table)</td><td>⇥</td><td></td></tr><tr><td>Navigate through the table</td><td>↑, →, ↓, ←</td><td></td></tr></tbody></table></figure><h3>General UI shortcuts</h3><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Close contextual balloons, dropdowns, and dialogs</td><td>Esc</td><td></td></tr><tr><td>Open the accessibility help dialog</td><td>Alt+0</td><td>⌥0</td></tr><tr><td>Move focus between form fields (inputs, buttons, etc.)</td><td>⇥, Shift+⇥</td><td>⇥, ⇧⇥</td></tr><tr><td>Move focus to the toolbar, navigate between toolbars</td><td>Alt+F10</td><td>⌥F10 (may require Fn)</td></tr><tr><td>Navigate through the toolbar or menu bar</td><td>↑, →, ↓, ←</td><td></td></tr><tr><td>Navigate to the next focusable field or an element outside the editor</td><td>Tab, Shift+Tab</td><td></td></tr><tr><td>Execute the currently focused button. Executing buttons that interact with the editor content moves the focus back to the content.</td><td>Enter, Space</td><td></td></tr><tr><td>Move focus in and out of an active dialog window</td><td>Ctrl+F6</td><td>⌘F6 (may require Fn)</td></tr></tbody></table></figure>",
diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search in note.md b/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search in note.md
index 7aa15dfc80..0b6ea7aae5 100644
--- a/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search in note.md
+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search in note.md
@@ -26,4 +26,13 @@ Local search allows you to search within the currently displayed note. 
* Press _Replace all_ to replace all of them at once.
* Options:
* _Case sensitive_ – the search will distinguish upper case characters from lower case (e.g. searching for Hello will not match `hello`).
- * _Match words_ - the search will find only exact word matches (e.g. searching for `Java` will not match `JavaScript`).
\ No newline at end of file
+ * _Match words_ - the search will find only exact word matches (e.g. searching for `Java` will not match `JavaScript`).
+
+## Included notes
+
+In a <a class="reference-link" href="../../Note%20Types/Text.md">Text</a> note, the search also finds the text of the notes included with <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a>, in the order they appear in the note.
+
+* The text of included text and code notes and of embedded code files, such as a `.js` or `.txt` attachment, is searched. The title of an include and the content of other notes, such as a collection or a drawing, are not.
+* The up and down arrows move through the results of an include as through the rest of the note.
+* A result in a collapsed _Expandable_ include expands the include while that result is the current one, and collapses it again once the search moves on.
+* _Replace_ and _Replace all_ change an included note only while its _Editable_ button is on. While the current result is in an include that cannot be edited, _Replace_ is disabled, and _Replace all_ leaves such results unchanged.
\ No newline at end of file
diff --git a/docs/User Guide/User Guide/Note Types/Text/Include Note.md b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
index d53b4fc0c7..6c0d7e0afa 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Include Note.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
@@ -115,6 +115,7 @@ An included text note, an included code note and an embedded code file such as a
* The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.
* An include of <a class="reference-link" href="Block%20references.md">Block references</a> edits only the referenced blocks.
* Editing is not available in a [read-only note](../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md), for an included note marked `#readOnly`, or for an attachment of another note.
+* <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/Navigation/Search%20in%20note.md">Search in note</a> finds the text of included text and code notes among the results of the note around them, and replaces it while _Editable_ is on.
## Drawing canvases
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 37cc94ebd5..b444003855 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -13,7 +13,7 @@ import { CLASSIC_EDITOR_PLUGINS, CORE_PLUGINS, POPUP_EDITOR_PLUGINS } from "./pl
import { BalloonEditor, DecoupledEditor, FindAndReplaceEditing, FindCommand } from "ckeditor5";
export { onTextEditorError } from "./editor_errors.js";
export { CHAT_INPUT_PLUGINS, MEMO_PLUGINS } from "./plugins.js";
-export type { CKEditorError, EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, TextTransformationConfig, TextTypingTransformationDescription } from "ckeditor5";
+export type { CKEditorError, EditorConfig, FindResultType, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, TextTransformationConfig, TextTypingTransformationDescription } from "ckeditor5";
export type { ClipboardImageEmbedConfig } from "./plugins/clipboard_image_embed.js";
export type { ImageEditingSourceConfig } from "./plugins/image_editing_source.js";
export type { FileUploadData, FileUploadEvent } from "./plugins/file_upload/fileuploadediting.js";
@@ -38,6 +38,8 @@ import "./plugins/file_upload/uploadfileplugin.js";
import "./plugins/block_reference/block_reference.js";
import "./plugins/content_embed/content_embed.js";
import "./plugins/content_embed/content_embed_caret.js";
+import "./plugins/find_in_link_widgets.js";
+import "./plugins/find_reveal.js";
import "./plugins/math/math.js";
import "./plugins/tabs/tabs.js";
import "./plugins/multicolumn/multicolumn.js";
diff --git a/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts b/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts
index c458d34372..3f95c94b7f 100644
--- a/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts
+++ b/packages/ckeditor5/src/plugins/collapsible/collapsible_editing.ts
@@ -1,6 +1,7 @@
-import { Plugin, Enter, Delete, enableViewPlaceholder, type ViewDocumentEnterEvent, type ViewDocumentDeleteEvent, type ViewDocumentArrowKeyEvent } from "ckeditor5";
+import { Plugin, Enter, Delete, enableViewPlaceholder, type ModelPosition, type ViewDocumentEnterEvent, type ViewDocumentDeleteEvent, type ViewDocumentArrowKeyEvent } from "ckeditor5";
import { ContentHintManager, type HintHandle } from "../../content_hint_manager.js";
import { renderShortcut } from "../../shortcut.js";
+import FindReveal from "../find_reveal.js";
import BlockDragHandle from "./block_drag_handle.js";
import CollapsibleCommand from "./collapsible_command.js";
import { OPEN_ATTRIBUTE, TRANSIENT_OPEN_ATTRIBUTE } from "./constants.js";
@@ -76,7 +77,7 @@ export default class CollapsibleEditing extends Plugin {
}
public static get requires() {
- return [Enter, Delete] as const;
+ return [ Enter, Delete, FindReveal ] as const;
}
private keydownListeners: Array<{ root: HTMLElement, handler: (e: KeyboardEvent) => void }> = [];
@@ -1187,28 +1188,24 @@ export default class CollapsibleEditing extends Plugin {
* Follow the find-and-replace highlight: when it lands inside a collapsed
* block, open that block (and any collapsed ancestors) just enough to show
* the match; re-collapse the moment the highlight leaves. Purely editing-view
- * state — see {@link findRevealed}. No-op when the editor has no find plugin.
+ * state — see {@link findRevealed}.
*/
private registerFindReveal() {
- if (!this.editor.plugins.has("FindAndReplaceEditing")) return;
- const findEditing: any = this.editor.plugins.get("FindAndReplaceEditing");
- const state = findEditing?.state;
- /* v8 ignore next -- FindAndReplaceEditing always exposes a state with an observable on flag */
- if (!state?.on) return;
- this.listenTo(state, "change:highlightedResult", (_evt: any, _name: any, highlighted: any) => {
- this.syncFindReveal(highlighted);
+ const findReveal = this.editor.plugins.get(FindReveal);
+ this.listenTo(findReveal, "change:position", (_evt, _name, position) => {
+ this.syncFindReveal(position);
});
}
/**
- * Reconcile {@link findRevealed} with the block(s) the current highlight sits
- * in. Ancestors newly holding the highlight get revealed; blocks that no
- * longer hold it are re-collapsed. A `null` highlight (search cleared/closed)
+ * Reconcile {@link findRevealed} with the block(s) that hold `position`, the
+ * match the find shows. Ancestors newly holding it get revealed; blocks that no
+ * longer hold it are re-collapsed. A `null` position (search cleared/closed)
* collapses everything.
*/
- private syncFindReveal(highlighted: any) {
+ private syncFindReveal(position: ModelPosition | null) {
const wanted = new Set<any>();
- for (let node = highlighted?.marker?.getStart?.()?.parent; node; node = node.parent) {
+ for (let node: any = position?.parent; node; node = node.parent) {
// A persisted-open block is already visible — nothing transient to do.
if (node.is?.("element", "details") && !this.isDetailsOpen(node)) {
wanted.add(node);
diff --git a/packages/ckeditor5/src/plugins/collapsible/find_reveal.spec.ts b/packages/ckeditor5/src/plugins/collapsible/find_reveal.spec.ts
index 34fef33340..1250dbf9b4 100644
--- a/packages/ckeditor5/src/plugins/collapsible/find_reveal.spec.ts
+++ b/packages/ckeditor5/src/plugins/collapsible/find_reveal.spec.ts
@@ -1,5 +1,7 @@
import { ClassicEditor, Essentials, FindAndReplace, Paragraph, _getModelData as getModelData } from "ckeditor5";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { createTestEditor } from "../../../test/editor-kit.js";
+import FindReveal from "../find_reveal.js";
import CollapsibleEditing from "./collapsible_editing.js";
import { TRANSIENT_OPEN_ATTRIBUTE } from "./constants.js";
@@ -147,4 +149,24 @@ describe("collapsible find-in-note reveal", () => {
expect(isTransient()).toBe(false);
expect(editor.getData()).toContain("open");
});
+
+ it("opens the blocks around a position that FindReveal shows, as for an embed", async () => {
+ const revealEditor = await createTestEditor([
+ Essentials, Paragraph, FindAndReplace, FindReveal, CollapsibleEditing
+ ]);
+ revealEditor.setData(twoSiblings);
+ const details = revealEditor.model.document.getRoot()?.getChild(1);
+ const body = details?.is("element") ? details.getChild(1) : null;
+ if (!body) throw new Error("Expected the second block to have a body.");
+ const openStates = () => [ ...revealEditor.editing.view.getDomRoot()
+ ?.querySelectorAll<HTMLDetailsElement>("details.trilium-collapsible") ?? [] ]
+ .map((block) => block.open);
+
+ revealEditor.plugins.get(FindReveal).show(revealEditor.model.createPositionAt(body, 0));
+ expect(openStates()).toEqual([ false, true ]);
+
+ revealEditor.plugins.get(FindReveal).show(null);
+ expect(openStates()).toEqual([ false, false ]);
+ expect(revealEditor.getData()).not.toContain("open");
+ });
});
diff --git a/packages/ckeditor5/src/plugins/collapsible_list_items.spec.ts b/packages/ckeditor5/src/plugins/collapsible_list_items.spec.ts
index 1ae134ff7f..a11a5c5d0e 100644
--- a/packages/ckeditor5/src/plugins/collapsible_list_items.spec.ts
+++ b/packages/ckeditor5/src/plugins/collapsible_list_items.spec.ts
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it } from "vitest";
import { createTestEditor, getEditorElement } from "../../test/editor-kit.js";
import CollapsibleListItems, { LIST_COLLAPSED_ATTRIBUTE, ToggleListCollapseCommand } from "./collapsible_list_items.js";
+import FindReveal from "./find_reveal.js";
// Lists are flat in the model: sibling blocks related by listIndent/listItemId.
const LIST_FIXTURE =
@@ -641,6 +642,24 @@ describe("CollapsibleListItems", () => {
expect(getComputedStyle(nested).display).toBe("none");
});
+ it("reveals a collapsed item around a position that FindReveal shows", async () => {
+ const findEditor = await createTestEditor([
+ CollapsibleListItems, List, TodoList, Paragraph, Typing, Undo, FindAndReplace,
+ FindReveal
+ ]);
+ setModelData(findEditor.model, LIST_FIXTURE);
+ findEditor.execute("toggleListCollapse");
+ const { li } = collapsedItem(findEditor);
+ const findReveal = findEditor.plugins.get(FindReveal);
+
+ findReveal.show(findEditor.model.createPositionAt(getBlock(findEditor, 1), 0));
+ expect(li.classList.contains("trilium-list-temporarily-expanded")).toBe(true);
+
+ findReveal.show(null);
+ expect(li.classList.contains("trilium-list-temporarily-expanded")).toBe(false);
+ expect(getBlock(findEditor, 0).getAttribute(LIST_COLLAPSED_ATTRIBUTE)).toBe(true);
+ });
+
it("does not permanently expand when the search closes with the highlight inside the item", async () => {
const findEditor = await createCollapsedFindEditor();
const { nested } = collapsedItem(findEditor);
diff --git a/packages/ckeditor5/src/plugins/collapsible_list_items.ts b/packages/ckeditor5/src/plugins/collapsible_list_items.ts
index 6baf1be0cc..e54c684b1c 100644
--- a/packages/ckeditor5/src/plugins/collapsible_list_items.ts
+++ b/packages/ckeditor5/src/plugins/collapsible_list_items.ts
@@ -3,16 +3,15 @@ import "../theme/collapsible_list_items.css";
import {
Command,
DomEventObserver,
- FindAndReplaceEditing,
ListEditing,
MouseObserver,
Plugin,
type Editor,
type EnterCommand,
- type FindResultType,
type ListSplitCommand,
type ModelElement,
type ModelNode,
+ type ModelPosition,
type ModelWriter,
type ViewDocumentDomEventData,
type ViewDocumentEnterEvent,
@@ -21,6 +20,8 @@ import {
type ViewElement
} from "ckeditor5";
+import FindReveal from "./find_reveal.js";
+
export const LIST_COLLAPSED_ATTRIBUTE = "listCollapsed";
const COLLAPSED_DATA_ATTRIBUTE = "data-trilium-collapsed";
@@ -56,7 +57,7 @@ export default class CollapsibleListItems extends Plugin {
private _findClosing = false;
static get requires() {
- return [ListEditing] as const;
+ return [ ListEditing, FindReveal ] as const;
}
init() {
@@ -99,39 +100,23 @@ export default class CollapsibleListItems extends Plugin {
* inside them, re-collapsing once the highlight moves away — the same treatment collapsible
* `<details>` blocks get. Unlike {@link _enableAutoExpand} (which permanently drops the
* collapsed state when the caret enters a hidden block), this is view-only and never touches
- * the persisted attribute: search must not rewrite the user's collapsed layout. No-op when
- * the editor has no find plugin.
+ * the persisted attribute: search must not rewrite the user's collapsed layout.
*/
private _enableFindReveal() {
- const editor = this.editor;
- if (!editor.plugins.has(FindAndReplaceEditing)) {
- return;
- }
- // Wire up on "ready", not here: FindAndReplaceEditing may load after this plugin and only
- // creates its state in its own init(), so the state isn't available yet at this point.
- this.listenTo(editor, "ready", () => {
- const state = editor.plugins.get(FindAndReplaceEditing).state;
- /* v8 ignore next 3 -- by "ready" FindAndReplaceEditing has initialized and always has a state; the guard only satisfies the optional type. */
- if (!state) {
- return;
- }
- this.listenTo(state, "change:highlightedResult", (_evt, _name, highlighted) => {
- this._syncFindReveal(highlighted as FindResultType | null);
- });
+ const findReveal = this.editor.plugins.get(FindReveal);
+ this.listenTo(findReveal, "change:position", (_evt, _name, position) => {
+ this._syncFindReveal(position);
});
}
/**
- * Reconcile {@link _findRevealed} with the collapsed items hiding the current highlight:
- * reveal ancestors newly hiding it, re-collapse ones that no longer do. A `null` highlight
- * (search cleared) collapses everything.
+ * Reconcile {@link _findRevealed} with the collapsed items hiding `position`, the match the
+ * find shows: reveal ancestors newly hiding it, re-collapse ones that no longer do. A `null`
+ * position (search cleared) collapses everything.
*/
- private _syncFindReveal(highlighted: FindResultType | null) {
+ private _syncFindReveal(position: ModelPosition | null) {
const wanted = new Set<ModelElement>();
- // Split from `highlighted` so a cleared highlight (null) leaves `marker` undefined, keeping
- // the marker-absent path reachable rather than short-circuited away on the first `?.`.
- const marker = highlighted?.marker;
- const block = marker?.getStart().parent;
+ const block = position?.parent;
// getCollapsedAncestors tolerates any block (a non-list block has no collapsed ancestors),
// so no list-specific guard is needed beyond narrowing the position parent to an element.
if (block?.is("element")) {
@@ -140,11 +125,11 @@ export default class CollapsibleListItems extends Plugin {
}
}
- // A cleared highlight means find is closing (or moving off): flag the current microtask so
+ // A cleared position means find is closing (or moving off): flag the current microtask so
// the caret it is about to drop on the match doesn't permanently expand the item that
// {@link _enableAutoExpand} would otherwise open. Reset after the tick, so it only affects
// that synchronous caret landing and never a later real navigation.
- if (!highlighted) {
+ if (!position) {
this._findClosing = true;
void Promise.resolve().then(() => {
this._findClosing = false;
diff --git a/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts b/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts
index 43b2baf14e..f26caede85 100644
--- a/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts
+++ b/packages/ckeditor5/src/plugins/find_in_link_widgets.spec.ts
@@ -310,6 +310,19 @@ describe("FindInLinkWidgets", () => {
expect(editor.getData()).toContain('class="reference-link"');
expect(editor.getData()).not.toContain("broken");
});
+
+ it("tells which results the replace commands replace", () => {
+ setModelData(
+ editor.model,
+ '<paragraph><reference href="#root/ref"></reference> match</paragraph>'
+ );
+ editor.execute("find", "match");
+
+ const results = [ ...editor.plugins.get(FindAndReplaceEditing).state?.results ?? [] ];
+ const plugin = editor.plugins.get(FindInLinkWidgets);
+ expect(resultElementNames(results)).toEqual([ "reference", "text" ]);
+ expect(results.map((result) => plugin.canReplace(result))).toEqual([ false, true ]);
+ });
});
function findCount(
diff --git a/packages/ckeditor5/src/plugins/find_in_link_widgets.ts b/packages/ckeditor5/src/plugins/find_in_link_widgets.ts
index 56b9e067ed..7500ed8b87 100644
--- a/packages/ckeditor5/src/plugins/find_in_link_widgets.ts
+++ b/packages/ckeditor5/src/plugins/find_in_link_widgets.ts
@@ -219,6 +219,11 @@ export default class FindInLinkWidgets extends Plugin {
state.highlightedResult = state.results.first;
}
+ /** Whether the replace commands replace `result`, which a match in a link widget is not. */
+ canReplace(result: FindResultType): boolean {
+ return !isWidgetResult(result as MarkedFindResult);
+ }
+
}
/** Reports every match as a character range, as `findByTextCallback()` does. */
@@ -274,3 +279,9 @@ function isWidgetResult(value: MarkedFindResult): boolean {
}
const SEARCHABLE_WIDGETS = new Set([ "reference", "linkMention", "linkEmbed" ]);
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [FindInLinkWidgets.pluginName]: FindInLinkWidgets;
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/find_reveal.spec.ts b/packages/ckeditor5/src/plugins/find_reveal.spec.ts
new file mode 100644
index 0000000000..ea36295787
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/find_reveal.spec.ts
@@ -0,0 +1,60 @@
+import { Essentials, FindAndReplaceEditing, Paragraph } from "ckeditor5";
+import { describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../test/editor-kit.js";
+import FindReveal from "./find_reveal.js";
+
+describe("FindReveal", () => {
+ it("follows the highlighted find result", async () => {
+ const editor = await createTestEditor([
+ Essentials, Paragraph, FindAndReplaceEditing, FindReveal
+ ]);
+ const findReveal = editor.plugins.get(FindReveal);
+ editor.setData("<p>one needle</p><p>two needle</p>");
+
+ editor.execute("find", "needle");
+ expect(findReveal.position?.path).toEqual([ 0, 4 ]);
+
+ editor.execute("findNext");
+ expect(findReveal.position?.path).toEqual([ 1, 4 ]);
+
+ editor.plugins.get(FindAndReplaceEditing).stop();
+ expect(findReveal.position).toBeNull();
+ });
+
+ it("reveals a shown position while no result is highlighted", async () => {
+ const editor = await createTestEditor([
+ Essentials, Paragraph, FindAndReplaceEditing, FindReveal
+ ]);
+ const findReveal = editor.plugins.get(FindReveal);
+ const state = editor.plugins.get(FindAndReplaceEditing).state;
+ editor.setData("<p>one needle</p><p>two</p>");
+ const root = editor.model.document.getRoot();
+ if (!root || !state) throw new Error("The editor has no root or no find state.");
+ const shown = editor.model.createPositionAt(root.getChild(1) ?? root, 0);
+
+ findReveal.show(shown);
+ expect(findReveal.position).toBe(shown);
+
+ editor.execute("find", "needle");
+ expect(findReveal.position?.path).toEqual([ 0, 4 ]);
+
+ state.highlightedResult = null;
+ expect(findReveal.position).toBe(shown);
+
+ findReveal.show(null);
+ expect(findReveal.position).toBeNull();
+ });
+
+ it("reveals only shown positions in an editor without the find plugin", async () => {
+ const editor = await createTestEditor([ Essentials, Paragraph, FindReveal ]);
+ const findReveal = editor.plugins.get(FindReveal);
+ const root = editor.model.document.getRoot();
+ if (!root) throw new Error("The editor has no root.");
+ const shown = editor.model.createPositionAt(root, 0);
+
+ expect(findReveal.position).toBeNull();
+ findReveal.show(shown);
+ expect(findReveal.position).toBe(shown);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/find_reveal.ts b/packages/ckeditor5/src/plugins/find_reveal.ts
new file mode 100644
index 0000000000..49a8cca2d3
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/find_reveal.ts
@@ -0,0 +1,62 @@
+import { FindAndReplaceEditing, type ModelPosition, Plugin } from "ckeditor5";
+
+/**
+ * The position that "Search in note" shows: the start of the highlighted find result, or the
+ * position that `show()` sets for a match that no find result marks, such as a match inside a
+ * content embed. Plugins that hide content, such as collapsible blocks and tabs, reveal what holds
+ * this position.
+ */
+export default class FindReveal extends Plugin {
+
+ static get pluginName() {
+ return "FindReveal" as const;
+ }
+
+ /**
+ * The position to reveal, or `null` while the find shows no match.
+ *
+ * @observable
+ * @readonly
+ */
+ declare position: ModelPosition | null;
+
+ private highlighted: ModelPosition | null = null;
+ private shown: ModelPosition | null = null;
+
+ init() {
+ this.set("position", null);
+
+ // FindAndReplaceEditing can load after this plugin, and creates its state in its init().
+ this.listenTo(this.editor, "ready", () => {
+ const plugins = this.editor.plugins;
+ const state = plugins.has(FindAndReplaceEditing)
+ ? plugins.get(FindAndReplaceEditing).state
+ : undefined;
+ if (!state) {
+ return;
+ }
+
+ this.listenTo(state, "change:highlightedResult", (_evt, _name, result) => {
+ this.highlighted = result?.marker?.getStart() ?? null;
+ this.update();
+ });
+ });
+ }
+
+ /** Reveals `position` while no find result is highlighted. `null` stops revealing it. */
+ show(position: ModelPosition | null) {
+ this.shown = position;
+ this.update();
+ }
+
+ private update() {
+ this.position = this.highlighted ?? this.shown;
+ }
+
+}
+
+declare module "ckeditor5" {
+ interface PluginsMap {
+ [FindReveal.pluginName]: FindReveal;
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_editing.spec.ts b/packages/ckeditor5/src/plugins/tabs/tabs_editing.spec.ts
index 67b6aff637..6cd8e217dd 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_editing.spec.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_editing.spec.ts
@@ -8,6 +8,8 @@ import {
} from "ckeditor5";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { createTestEditor } from "../../../test/editor-kit.js";
+import FindReveal from "../find_reveal.js";
import Tabs from "./tabs.js";
const TWO_TABS =
@@ -64,6 +66,25 @@ describe("TabsEditing", () => {
expect(activeTitles()).toEqual(["Linux"]);
});
+ it("shows the tab around a position that FindReveal shows", async () => {
+ const revealEditor = await createTestEditor([
+ Essentials, FindAndReplaceEditing, Paragraph, FindReveal, Tabs
+ ]);
+ revealEditor.setData(TWO_TABS);
+ const tabs = revealEditor.model.document.getRoot()?.getChild(0);
+ const linuxTab = tabs?.is("element") ? tabs.getChild(1) : null;
+ if (!linuxTab?.is("element")) throw new Error("Expected a second tab.");
+ const activeTabs = () => [ ...revealEditor.editing.view.getDomRoot()
+ ?.querySelectorAll(".trilium-tab-title--active") ?? [] ]
+ .map(title => title.textContent);
+ expect(activeTabs()).toEqual([ "Windows" ]);
+
+ revealEditor.plugins.get(FindReveal)
+ .show(revealEditor.model.createPositionAt(linuxTab, "end"));
+
+ expect(activeTabs()).toEqual([ "Linux" ]);
+ });
+
it("leaves Enter outside a title to the editor, and attribute changes to the post-fixer", () => {
const panel = linux().getChild(1) as ModelElement;
editor.model.change(writer => writer.setSelection(panel.getChild(0) as ModelElement, "end"));
diff --git a/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts b/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
index 9b56d641ad..c001bbc611 100644
--- a/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
+++ b/packages/ckeditor5/src/plugins/tabs/tabs_editing.ts
@@ -16,6 +16,7 @@ import {
} from "ckeditor5";
import { BLOCK_ID } from "../block_reference/block_reference_editing.js";
+import FindReveal from "../find_reveal.js";
import {
ALIGNMENT_ATTRIBUTE, ALIGNMENT_DATA_ATTRIBUTE, CLASSES, DEFAULT_TAB_ALIGNMENT, ELEMENTS,
parseTabAlignment, TABS_WIDGET_PROPERTY
@@ -37,7 +38,7 @@ export default class TabsEditing extends Plugin {
}
public static get requires() {
- return [TabsTitleBar, Widget] as const;
+ return [ TabsTitleBar, Widget, FindReveal ] as const;
}
/** The tab each tabs block shows, keyed by the `tabs` model element. */
@@ -326,16 +327,11 @@ export default class TabsEditing extends Plugin {
}, { priority: "lowest" });
}
- /** Shows the tab that holds the highlighted find-in-note result, without moving the caret. */
+ /** Shows the tab that holds the match the find shows, without moving the caret. */
private registerFindReveal() {
- const plugins = this.editor.plugins;
- const state = plugins.has("FindAndReplaceEditing") ? plugins.get("FindAndReplaceEditing").state : undefined;
- if (!state) {
- return;
- }
-
- this.listenTo(state, "change:highlightedResult", (_evt, _name, highlighted) => {
- this.showTabsAround(highlighted?.marker?.getStart());
+ const findReveal = this.editor.plugins.get(FindReveal);
+ this.listenTo(findReveal, "change:position", (_evt, _name, position) => {
+ this.showTabsAround(position);
});
}
diff --git a/packages/codemirror/src/find_replace.spec.ts b/packages/codemirror/src/find_replace.spec.ts
index f378233edf..ed0a113b08 100644
--- a/packages/codemirror/src/find_replace.spec.ts
+++ b/packages/codemirror/src/find_replace.spec.ts
@@ -85,7 +85,31 @@ describe("SearchHighlighter", () => {
expect(SearchHighlighter.deco(search)).toBe(search.matches);
});
+ it("leaves every match inactive when asked not to activate one", () => {
+ const search = highlighterFor("foo\nfoo\nfoo", 4);
+ search.searchFor("foo", false, false, false);
+
+ expect(search.totalFound).toBe(3);
+ expect(search.currentFound).toBe(0);
+ expect(search.activeMatch).toBeUndefined();
+ expect(search.matchRanges).toEqual([
+ { from: 0, to: 3 }, { from: 4, to: 7 }, { from: 8, to: 11 }
+ ]);
+ });
+
describe("navigation", () => {
+ it("clears the active match and keeps the others", () => {
+ const search = highlighterFor("foo foo foo");
+ search.searchFor("foo", false, false);
+ search.scrollToMatch(1);
+
+ search.clearActiveMatch();
+
+ expect(search.currentFound).toBe(0);
+ expect(search.activeMatch).toBeUndefined();
+ expect(decorationCount(search)).toBe(3);
+ });
+
it("moves the active match and ignores an out-of-range index", () => {
const search = highlighterFor("foo foo foo");
search.searchFor("foo", false, false);
diff --git a/packages/codemirror/src/find_replace.ts b/packages/codemirror/src/find_replace.ts
index cb68217bdc..a4c9fc37df 100644
--- a/packages/codemirror/src/find_replace.ts
+++ b/packages/codemirror/src/find_replace.ts
@@ -5,7 +5,7 @@ import { Range, RangeSet, StateEffect } from "@codemirror/state";
const searchMatchDecoration = Decoration.mark({ class: "cm-searchMatch" });
const activeMatchDecoration = Decoration.mark({ class: "cm-activeMatch" });
-interface Match {
+export interface Match {
from: number;
to: number;
}
@@ -28,7 +28,16 @@ export class SearchHighlighter {
this.matches = RangeSet.empty;
}
- searchFor(searchTerm: string, matchCase: boolean, wholeWord: boolean) {
+ /** The matches of the search, in document order. */
+ get matchRanges(): readonly Match[] {
+ return this.parsedMatches;
+ }
+
+ /**
+ * Highlights the matches of `searchTerm`. While `isActivating`, the match nearest the cursor
+ * becomes the active one and scrolls into view.
+ */
+ searchFor(searchTerm: string, matchCase: boolean, wholeWord: boolean, isActivating = true) {
if (!searchTerm) {
this.matches = RangeSet.empty;
return;
@@ -46,7 +55,19 @@ export class SearchHighlighter {
});
this.searchRegexp = regex;
this.#updateSearchData(this.view);
- this.#scrollToMatchNearestSelection();
+ if (isActivating) {
+ this.#scrollToMatchNearestSelection();
+ } else {
+ this.clearActiveMatch();
+ }
+ }
+
+ /** Leaves no match active, keeping every match highlighted. */
+ clearActiveMatch() {
+ this.activeMatch = undefined;
+ this.currentFound = 0;
+ // An empty transaction redraws the decorations.
+ this.view.dispatch({});
}
replaceActiveMatch(replacementText: string) {
diff --git a/packages/codemirror/src/index.spec.ts b/packages/codemirror/src/index.spec.ts
index 04d2458ae3..4563f7d18e 100644
--- a/packages/codemirror/src/index.spec.ts
+++ b/packages/codemirror/src/index.spec.ts
@@ -462,9 +462,29 @@ describe("CodeMirror", () => {
expect(editor.getText()).toBe("foo bar foo");
});
+ it("finds without activating a match, and clears the active match on request", async () => {
+ editor = build();
+ editor.setText("foo bar foo");
+
+ const result = await editor.performFind("foo", false, false, false);
+ expect(result).toEqual({ totalFound: 2, currentFound: 0 });
+ expect(editor.contentDOM.querySelectorAll(".cm-searchMatch")).toHaveLength(2);
+ expect(editor.contentDOM.querySelectorAll(".cm-activeMatch")).toHaveLength(0);
+ expect(editor.getSearchMatches()).toEqual([ { from: 0, to: 3 }, { from: 8, to: 11 } ]);
+
+ await editor.findNext(1, 0, 1);
+ expect(editor.contentDOM.querySelectorAll(".cm-activeMatch")).toHaveLength(1);
+
+ editor.clearActiveMatch();
+ expect(editor.contentDOM.querySelectorAll(".cm-activeMatch")).toHaveLength(0);
+ expect(editor.contentDOM.querySelectorAll(".cm-searchMatch")).toHaveLength(2);
+ });
+
it("does nothing when cleaning a search that never ran", () => {
editor = build();
expect(() => editor?.cleanSearch()).not.toThrow();
+ expect(() => editor?.clearActiveMatch()).not.toThrow();
+ expect(editor.getSearchMatches()).toEqual([]);
});
it("does nothing when replace is called before a search", async () => {
diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.ts
index e83e0d3557..c36bcf671b 100644
--- a/packages/codemirror/src/index.ts
+++ b/packages/codemirror/src/index.ts
@@ -377,7 +377,13 @@ export default class CodeMirror extends EditorView {
});
}
- async performFind(searchTerm: string, matchCase: boolean, wholeWord: boolean) {
+ /**
+ * Highlights the matches of `searchTerm`. While `isActivating`, the match nearest the cursor
+ * becomes the active one and scrolls into view.
+ */
+ async performFind(
+ searchTerm: string, matchCase: boolean, wholeWord: boolean, isActivating = true
+ ) {
const plugin = createSearchHighlighter();
this.dispatch({
effects: this.searchHighlightCompartment.reconfigure(plugin)
@@ -386,7 +392,7 @@ export default class CodeMirror extends EditorView {
// Wait for the plugin to activate in the next render cycle
await new Promise(requestAnimationFrame);
const instance = this.plugin(plugin);
- instance?.searchFor(searchTerm, matchCase, wholeWord);
+ instance?.searchFor(searchTerm, matchCase, wholeWord, isActivating);
this.searchPlugin = instance;
/* v8 ignore next 4 -- the plugin was just installed via the compartment above and the
@@ -410,6 +416,16 @@ export default class CodeMirror extends EditorView {
this.searchPlugin?.replaceAll(replaceText);
}
+ /** Leaves no match of the search active, keeping every match highlighted. */
+ clearActiveMatch() {
+ this.searchPlugin?.clearActiveMatch();
+ }
+
+ /** The matches of the search, in document order. */
+ getSearchMatches() {
+ return this.searchPlugin?.matchRanges ?? [];
+ }
+
cleanSearch() {
if (this.searchPlugin) {
this.dispatch({