Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/text editor/link editor: add support for anchors
Adorian Dorane37f8f178107
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 416d8f9159..5052aee221 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -75,7 +75,10 @@"display_inline": "Inline","display_card": "Card","display_embed": "YouTube embed",- "page_title": "Title of the web page"+ "page_title": "Title of the web page",+ "anchors": "Anchors",+ "target_anchor": "Target anchor",+ "no_anchors": "No anchors available."},"branch_prefix": {"edit_branch_prefix": "Edit branch prefix",diff --git a/apps/client/src/widgets/dialogs/add_link.css b/apps/client/src/widgets/dialogs/add_link.cssindex 82b9a680b8..4d51923753 100644--- a/apps/client/src/widgets/dialogs/add_link.css+++ b/apps/client/src/widgets/dialogs/add_link.css@@ -50,4 +50,22 @@width: fit-content;margin: 0 auto 1rem;}++ .add-link-anchors .tn-card-body {+ border-radius: var(--card-border-radius);+ height: 150px;+ overflow-y: auto;++ > .tn-card-section {+ flex-shrink: 0;+ }++ > .tn-card-choice:focus-visible {+ outline-offset: -2px;+ }++ > .add-link-no-anchors {+ flex-grow: 1;+ }+ }}diff --git a/apps/client/src/widgets/dialogs/add_link.spec.tsx b/apps/client/src/widgets/dialogs/add_link.spec.tsxindex 971e6e6c55..802768c799 100644--- a/apps/client/src/widgets/dialogs/add_link.spec.tsx+++ b/apps/client/src/widgets/dialogs/add_link.spec.tsx@@ -112,6 +112,14 @@ describe("AddLinkDialog", () => {return container.querySelector<HTMLSelectElement>(".add-link-display select");}+ function anchorRows() {+ return [ ...container.querySelectorAll<HTMLElement>(".add-link-anchors .tn-card-choice") ];+ }++ function checkedAnchor() {+ return anchorRows().find((row) => row.getAttribute("aria-checked") === "true")?.textContent;+ }+function displays() {return [ ...displaySelect()?.options ?? [] ].map((option) => option.textContent);}@@ -392,6 +400,69 @@ describe("AddLinkDialog", () => {expect(choice()).toStrictEqual([]);expect(container.querySelector(".note-autocomplete")).not.toBeNull();});++ it("links an anchor of the document, read as its name unless given a text", async () => {+ await open({ anchors: [ "intro", "outro" ] });+ expect(choice().map((button) => button.textContent?.trim()))+ .toStrictEqual([ "add_link.web_link", "add_link.note", "add_link.anchors" ]);+ expect(choice()[2]?.querySelector(".bx-bookmark")).not.toBeNull();+ expect(current()).toBe("add_link.note");++ await act(async () => choice()[2]?.click());+ expect(current()).toBe("add_link.anchors");+ expect(container.querySelector(".note-autocomplete")).toBeNull();+ expect(headings()).toStrictEqual([ "add_link.target_anchor" ]);+ const titleCard = field("text")?.closest(".tn-card");+ expect(titleCard?.nextElementSibling?.classList.contains("add-link-anchors")).toBe(true);+ expect(anchorRows().map((row) => row.textContent)).toStrictEqual([ "intro", "outro" ]);+ expect(anchorRows().every((row) => row.querySelector(".tn-card-choice-icon.bx-bookmark")))+ .toBe(true);+ expect(checkedAnchor()).toBeUndefined();++ await act(async () => anchorRows()[1]?.click());+ expect(checkedAnchor()).toBe("outro");+ expect(field("text")?.placeholder).toBe("outro");+ await submit();+ expect(addLink).toHaveBeenLastCalledWith("#outro", "outro", true);++ await open({ anchors: [ "intro", "outro" ] });+ await act(async () => choice()[2]?.click());+ await act(async () => anchorRows()[0]?.click());+ // Another page drops the checked anchor.+ await act(async () => choice()[1]?.click());+ await act(async () => choice()[2]?.click());+ expect(checkedAnchor()).toBeUndefined();+ await act(async () => anchorRows()[0]?.click());+ await type(field("text"), "Read the intro");+ await submit();+ expect(addLink).toHaveBeenLastCalledWith("#intro", "Read the intro", true);+ });++ it("opens an edited anchor link on its anchor; a selection hides the title", async () => {+ await open({+ anchors: [ "intro", "outro" ], currentAnchor: "outro", currentTitle: "See the end"+ });+ expect(container.querySelector(".modal-title")?.textContent).toBe("add_link.edit_link");+ expect(current()).toBe("add_link.anchors");+ expect(checkedAnchor()).toBe("outro");+ expect(field("text")?.value).toBe("See the end");+ await submit();+ expect(addLink).toHaveBeenLastCalledWith("#outro", "See the end", true);++ await open({ text: "chosen words", hasSelection: true, anchors: [ "intro" ] });+ await act(async () => choice()[2]?.click());+ expect(field("text")).toBeNull();+ expect(container.querySelectorAll(".tn-card")).toHaveLength(1);+ await act(async () => anchorRows()[0]?.click());+ await submit();+ expect(addLink).toHaveBeenLastCalledWith("#intro", "intro", true);++ await open({ anchors: [] });+ await act(async () => choice()[2]?.click());+ expect(anchorRows()).toStrictEqual([]);+ expect(container.querySelector(".add-link-anchors .no-items")?.textContent)+ .toBe("add_link.no_anchors");+ });});describe("AddLinkBalloon", () => {@@ -464,6 +535,31 @@ describe("AddLinkBalloon", () => {expect(onClose).toHaveBeenCalledOnce();expect(addLink).toHaveBeenCalledExactlyOnceWith("https://example.com/page", "Page", true);});++ it("focuses the title of the Anchors page and applies once an anchor is checked", async () => {+ const edited = await show({+ anchors: [ "intro" ], currentAnchor: "intro", currentTitle: "Intro"+ });+ const title = edited.querySelector<HTMLInputElement>(".add-link-text input");+ expect(document.activeElement).toBe(title);+ expect([ title?.selectionStart, title?.selectionEnd ]).toStrictEqual([ 0, 5 ]);+ await submit(edited);+ expect(addLink).toHaveBeenLastCalledWith("#intro", "Intro", true);+ expect(onClose).toHaveBeenCalledOnce();++ const form = await show({ anchors: [ "intro" ] });+ const buttons = form.querySelectorAll<HTMLButtonElement>(".tn-segmented-choice button");+ await act(async () => buttons[2]?.click());+ expect(document.activeElement).toBe(form.querySelector(".add-link-text input"));+ await submit(form);+ expect(onClose).toHaveBeenCalledOnce();++ const row = form.querySelector<HTMLElement>(".add-link-anchors .tn-card-choice");+ await act(async () => row?.click());+ await submit(form);+ expect(onClose).toHaveBeenCalledTimes(2);+ expect(addLink).toHaveBeenLastCalledWith("#intro", "intro", true);+ });});async function type(input: HTMLInputElement | null, value: string) {diff --git a/apps/client/src/widgets/dialogs/add_link.tsx b/apps/client/src/widgets/dialogs/add_link.tsxindex 0e67cbd53f..44d405a804 100644--- a/apps/client/src/widgets/dialogs/add_link.tsx+++ b/apps/client/src/widgets/dialogs/add_link.tsx@@ -13,21 +13,22 @@ import tree from "../../services/tree";import { isMobile } from "../../services/utils";import { logError } from "../../services/ws";import Button from "../react/Button";-import { Card, OptionCardSection } from "../react/Card";+import { Card, CardSection, ChoiceCardSection, OptionCardSection } from "../react/Card";import FormSelect from "../react/FormSelect";import FormTextBox from "../react/FormTextBox";import FormToggle from "../react/FormToggle";import { useTriliumEvent } from "../react/hooks";import Modal from "../react/Modal";import { suspendModalFocusTraps } from "../react/modal_focustrap";+import NoItems from "../react/NoItems";import NoteAutocomplete, { type NoteAutocompleteHandle } from "../react/NoteAutocomplete";import { refToJQuerySelector } from "../react/react_utils";-import SegmentedChoice from "../react/SegmentedChoice";+import SegmentedChoice, { type SegmentedChoiceOption } from "../react/SegmentedChoice";type LinkType = "reference-link" | "external-link" | "hyper-link";-/** What the link points at: a note, or an address outside Trilium. */-export type LinkTarget = "note" | "url";+/** What the link points at: a note, an address outside Trilium, or an anchor in the document. */+export type LinkTarget = "note" | "url" | "anchor";function findAnchorIds(content: string): string[] {const re = /<a\b([^>]*)>(<\/a>)?/g;@@ -76,11 +77,18 @@ export interface AddLinkOpts {currentTitle?: string;/** The anchor within the note that the link being edited points at. */currentBookmark?: string;+ /**+ * The anchors in the document that the link goes into. When given, the dialog has an Anchors+ * page that links to one of them.+ */+ anchors?: string[];+ /** The anchor in `anchors` that the link being edited points at. */+ currentAnchor?: string;/*** The side a new link opens on, the note side by default. A selected URL opens on the web link* side.*/- target?: LinkTarget;+ target?: Exclude<LinkTarget, "anchor">;/*** Repoints a reference link to a missing note. The dialog is titled "Fix link", searches for* `text`, and offers only notes, always as a reference link.@@ -190,8 +198,10 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {const [ target, setTarget ] = useState<LinkTarget>("note");const [ webLink, setWebLink ] = useState("");const [ display, setDisplay ] = useState<LinkDisplayMode>("plain");+ const [ anchor, setAnchor ] = useState("");const [ isShowPending, setIsShowPending ] = useState(false);const webLinkRef = useRef<HTMLInputElement>(null);+ const titleRef = useRef<HTMLInputElement>(null);// The text of the link being edited, while it stands in for the picked note's title.const keptTitleRef = useRef<string | null>(null);const initialBookmarkRef = useRef("");@@ -208,9 +218,10 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {}const initialWebLink = opts ? getInitialWebLink(opts) : null;- setTarget(initialWebLink !== null ? "url" : "note");+ setTarget(getInitialTarget(opts, initialWebLink));setWebLink(initialWebLink ?? "");setDisplay(opts?.display ?? "plain");+ setAnchor(opts?.currentAnchor ?? "");keptTitleRef.current = opts?.currentTitle ?? null;previewTitleRef.current = opts?.currentLink && opts.display && opts.display !== "plain"? opts.currentTitle ?? null : null;@@ -241,6 +252,7 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {setNoteTitle("");setLinkTitle("");setLinkType(opts?.hasSelection ? "hyper-link" : "reference-link");+ setAnchor("");if (next === "url") {changeWebLink(text);} else {@@ -253,6 +265,8 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {if (!autoFocus) return;if (target === "url") {webLinkRef.current?.focus();+ } else if (target === "anchor") {+ titleRef.current?.focus();} else {autocompleteRef.current?.focus();}@@ -347,10 +361,11 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {}, [ isShowPending ]);async function fillAndFocus() {- if (target === "url") {+ if (target === "url" || target === "anchor") {+ const field = target === "url" ? webLinkRef.current : titleRef.current;if (autoFocus) {- webLinkRef.current?.focus();- webLinkRef.current?.select();+ field?.focus();+ field?.select();}return;}@@ -390,7 +405,16 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {/** Applies the link picked, through `opts.addLink` or `opts.addLinkPreview`. */function applyLink() {- if (!opts || !suggestion) return;+ if (!opts) return;++ if (target === "anchor") {+ // An anchor link without a text of its own reads as the anchor's name. `true` keeps+ // the href as it is.+ if (anchor) opts.addLink(`#${anchor}`, linkTitle.trim() || anchor, true);+ return;+ }++ if (!suggestion) return;if (suggestion.notePath) {// Handle note link, optionally with a bookmark anchor@@ -421,23 +445,69 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {const autocompleteRef = useRef<HTMLInputElement>(null);const handleRef = useRef<NoteAutocompleteHandle>(null);+ const isEditing = !!opts?.currentLink || !!opts?.currentAnchor;const title = opts?.fixLink ? t("add_link.fix_link")- : opts?.currentLink ? t("add_link.edit_link") : t("add_link.add_link");+ : isEditing ? t("add_link.edit_link") : t("add_link.add_link");const buttonText = opts?.fixLink ? t("add_link.button_fix_link")- : opts?.currentLink ? t("add_link.button_edit_link") : t("add_link.button_add_link");+ : isEditing ? t("add_link.button_edit_link") : t("add_link.button_add_link");++ /** The text the link reads as while the title field is empty. */+ function getTitlePlaceholder() {+ if (target === "anchor") return anchor || undefined;+ if (target !== "url") return undefined;+ return isPreview ? t("add_link.page_title") : suggestion?.externalLink;+ }const titleSection = (<OptionCardSectionclassName="add-link-text" name="link-title" label={t("add_link.link_title")}><FormTextBox+ inputRef={titleRef}currentValue={linkTitle}- placeholder={target !== "url" ? undefined- : isPreview ? t("add_link.page_title") : suggestion?.externalLink}+ placeholder={getTitlePlaceholder()}onChange={setLinkTitle}/></OptionCardSection>);++ const targets: SegmentedChoiceOption<LinkTarget>[] = [+ { value: "url", label: t("add_link.web_link"), icon: "bx-globe" },+ { value: "note", label: t("add_link.note"), iconSvg: internalLinkIcon }+ ];+ if (opts?.anchors) {+ targets.push({ value: "anchor", label: t("add_link.anchors"), icon: "bx-bookmark" });+ }+ const switcher = !opts?.fixLink && (+ <SegmentedChoice<LinkTarget>+ className="add-link-target"+ options={targets}+ currentValue={target}+ onChange={(next) => changeTarget(next)}+ />+ );++ const anchors = opts?.anchors ?? [];+ const anchorPage = (<>+ {showsTitle && <Card>{titleSection}</Card>}++ <Card className="add-link-anchors" heading={t("add_link.target_anchor")}>+ {anchors.length > 0 ? anchors.map((name) => (+ <ChoiceCardSection+ key={name}+ icon="bx bx-bookmark"+ isChecked={name === anchor}+ onCheck={() => setAnchor(name)}+ >+ {name}+ </ChoiceCardSection>+ )) : (+ <CardSection className="add-link-no-anchors">+ <NoItems icon="bx bx-bookmark" text={t("add_link.no_anchors")} size="small" />+ </CardSection>+ )}+ </Card>+ </>);const displays = [{ value: "plain", title: t("add_link.display_plain") },{ value: "inline", title: t("add_link.display_inline") },@@ -450,23 +520,16 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {return {title,buttonText,- hasLink: !!suggestion,+ hasLink: target === "anchor" ? !!anchor : !!suggestion,/** Fills and focuses the fields, once the form is on screen. */onShown: () => setIsShowPending(true),applyLink,reset,- body: (<>- {!opts?.fixLink && (- <SegmentedChoice<LinkTarget>- className="add-link-target"- options={[- { value: "url", label: t("add_link.web_link"), icon: "bx-globe" },- { value: "note", label: t("add_link.note"), iconSvg: internalLinkIcon }- ]}- currentValue={target}- onChange={(next) => changeTarget(next)}- />- )}+ body: target === "anchor" ? (<>+ {switcher}+ {anchorPage}+ </>) : (<>+ {switcher}<Card>{target === "url" ? (@@ -575,6 +638,17 @@ function useAddLinkForm(opts: AddLinkOpts | undefined) {};}+/**+ * The page the dialog opens on: Anchors for an edited anchor link, Web link when there is an+ * `initialWebLink`, and Note otherwise.+ */+function getInitialTarget(+ opts: AddLinkOpts | undefined, initialWebLink: string | null+): LinkTarget {+ if (opts?.currentAnchor) return "anchor";+ return initialWebLink !== null ? "url" : "note";+}+/*** The address the dialog opens on, on the web link side: the external link being edited, a* selected text that is a URL, or an empty one for `target: "url"`. `null` opens it on the notediff --git a/apps/client/src/widgets/react/Card.css b/apps/client/src/widgets/react/Card.cssindex 5feffe7845..9a850e310a 100644--- a/apps/client/src/widgets/react/Card.css+++ b/apps/client/src/widgets/react/Card.css@@ -108,6 +108,23 @@}}+.tn-card-choice {+ display: flex;+ align-items: center;+ gap: 8px;+ cursor: pointer;++ .tn-card-choice-label {+ min-width: 0;+ overflow-wrap: anywhere;+ }++ .tn-card-choice-check {+ flex-shrink: 0;+ margin-inline-start: auto;+ }+}+.tn-card-section-link {display: flex;align-items: center;diff --git a/apps/client/src/widgets/react/Card.spec.tsx b/apps/client/src/widgets/react/Card.spec.tsxindex babfec75f6..fb00770a4e 100644--- a/apps/client/src/widgets/react/Card.spec.tsx+++ b/apps/client/src/widgets/react/Card.spec.tsx@@ -4,7 +4,9 @@ import { describe, expect, it, vi } from "vitest";import contextMenu, { type ContextMenuOptions, type MenuItem } from "../../menus/context_menu";import { renderInto } from "../../test/render";-import { Card, CardFrame, CardSection, ItemCreationRow, OptionCardSection } from "./Card";+import {+ Card, CardFrame, CardSection, ChoiceCardSection, ItemCreationRow, OptionCardSection+} from "./Card";import { FilterProvider } from "./filter";const menuState = vi.hoisted(() => ({ dismissedByLastPress: false }));@@ -153,6 +155,40 @@ describe("OptionCardSection", () => {});});+describe("ChoiceCardSection", () => {+ it("is a radio that a click, Enter or Space checks, with a check mark once checked", () => {+ const onCheck = vi.fn();+ const container = renderInto(+ <Card>+ <ChoiceCardSection isChecked={false} onCheck={onCheck} icon="bx bx-bookmark">+ intro+ </ChoiceCardSection>+ <ChoiceCardSection isChecked onCheck={vi.fn()}>outro</ChoiceCardSection>+ </Card>+ );+ const [ unchecked, checked ] =+ [ ...container.querySelectorAll<HTMLElement>(".tn-card-choice") ];+ expect([ unchecked, checked ].map((section) => [+ section?.getAttribute("role"),+ section?.getAttribute("aria-checked"),+ section?.tabIndex,+ section?.textContent?.trim(),+ !!section?.querySelector(".tn-card-choice-icon.bx-bookmark"),+ !!section?.querySelector(".tn-card-choice-check.bx-check")+ ])).toStrictEqual([+ [ "radio", "false", 0, "intro", true, false ],+ [ "radio", "true", 0, "outro", false, true ]+ ]);++ unchecked?.click();+ const prevented = [ "Enter", " ", "a" ].map((key) => !unchecked?.dispatchEvent(+ new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true })+ ));+ expect(prevented).toStrictEqual([ true, true, false ]);+ expect(onCheck).toHaveBeenCalledTimes(3);+ });+});+describe("a segment that leads somewhere", () => {it("becomes a link carrying a chevron, rather than a section", () => {const container = renderInto(<OptionCardSection label="Backup" href="#root/_hidden/_options/_optionsBackup" />);diff --git a/apps/client/src/widgets/react/Card.tsx b/apps/client/src/widgets/react/Card.tsxindex 0cf5b70ca7..196fb50453 100644--- a/apps/client/src/widgets/react/Card.tsx+++ b/apps/client/src/widgets/react/Card.tsx@@ -276,6 +276,47 @@ function holdsSmallControl(element: HTMLElement) {// #endregion+// #region Choice Card Section++export interface ChoiceCardSectionProps {+ isChecked: boolean;+ onCheck: () => void;+ /** An icon class, `bx` prefix included, shown before the label. */+ icon?: string;+ className?: string;+ children: ComponentChildren;+}++/**+ * One segment of a card that lists exclusive choices. A click, Enter or Space checks it, and the+ * checked segment shows a check mark.+ */+export function ChoiceCardSection(+ { isChecked, onCheck, icon, className, children }: ChoiceCardSectionProps+) {+ return (+ <section+ className={clsx("tn-card-section tn-card-highlight-on-hover tn-card-choice", className)}+ role="radio"+ aria-checked={isChecked}+ tabIndex={0}+ onClick={onCheck}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ onCheck();+ }+ }}+ >+ {icon && <Icon icon={icon} className="tn-card-choice-icon" />}+ <span className="tn-card-choice-label">{children}</span>+ {isChecked && <Icon icon="bx bx-check" className="tn-card-choice-check" />}+ </section>+ );+}++// #endregion+// #region Item Creation Rowinterface ItemCreationRowButtonBase {diff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.tsxindex fd5efba361..bdd6093841 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx@@ -1,7 +1,7 @@import {- type CKEditorError, CKTextEditor, ClassicEditor, getLinkAtSelection, type IconPickerRequest,- type LinkAtSelection, type LinkDialogRequest, type LinkDisplayMode, onTextEditorError,- PopupEditor, replaceLinkAtSelection, SnippetDefinition+ type CKEditorError, CKTextEditor, ClassicEditor, getAnchorNames, getLinkAtSelection,+ type IconPickerRequest, type LinkAtSelection, type LinkDialogRequest, type LinkDisplayMode,+ onTextEditorError, PopupEditor, replaceLinkAtSelection, SnippetDefinition} from "@triliumnext/ckeditor5";import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";import { createPortal, HTMLAttributes, RefObject } from "preact";@@ -23,6 +23,8 @@ export interface CKEditorApi {getSelectedText(): string;/** The link around the caret or the selected link preview, or `null` outside one. */getCurrentLink(): LinkAtSelection | null;+ /** The names of the anchors in the document. */+ getAnchors(): string[];addLink(notePath: string, linkTitle: string | null, externalLink?: boolean): void;/*** Rewrites the link around the caret or the selected link preview, as {@link addLink} would@@ -201,6 +203,10 @@ export default function CKEditor({const editor = editorRef.current;return editor ? getLinkAtSelection(editor) : null;},+ getAnchors() {+ const editor = editorRef.current;+ return editor ? getAnchorNames(editor) : [];+ },async updateLink(notePath, linkTitle, externalLink) {const editor = editorRef.current;if (!editor) return;diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.tsindex 16f54b0dc3..ecd603c4cc 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts@@ -443,14 +443,25 @@ describe("parseLinkHref", () => {currentLink: { externalLink: "https://example.com/#top" }, currentBookmark: undefined});});++ it("reads a link to one of the document's anchors as that anchor", () => {+ expect(parseLinkHref("#intro", [ "intro" ])).toStrictEqual({ currentAnchor: "intro" });+ expect(parseLinkHref("#intro", [ "outro" ])).toStrictEqual({+ currentLink: { notePath: "intro" }, currentBookmark: undefined+ });+ expect(parseLinkHref("https://example.com/#intro", [ "intro" ])).toStrictEqual({+ currentLink: { externalLink: "https://example.com/#intro" }, currentBookmark: undefined+ });+ });});describe("getAddLinkOpts", () => {- function createApi(currentLink: LinkAtSelection | null) {+ function createApi(currentLink: LinkAtSelection | null, anchors: string[] = []) {return {hasSelection: vi.fn(() => true),getSelectedText: vi.fn(() => "chosen words"),getCurrentLink: vi.fn(() => currentLink),+ getAnchors: vi.fn(() => anchors),addLink: vi.fn(),updateLink: vi.fn(),addLinkPreview: vi.fn(),@@ -504,6 +515,19 @@ describe("getAddLinkOpts", () => {.toHaveBeenCalledExactlyOnceWith("https://example.com", "inline", null);});+ it("offers the document's anchors, and edits a link to one of them as that anchor", () => {+ expect(getAddLinkOpts(createApi(null, [ "intro" ]), ready)).toMatchObject({+ anchors: [ "intro" ]+ });++ const api = createApi({ href: "#intro", text: "Start", display: "plain" }, [ "intro" ]);+ const opts = getAddLinkOpts(api, ready);+ expect(opts).toMatchObject({+ anchors: [ "intro" ], currentAnchor: "intro", currentTitle: "Start"+ });+ expect(opts.currentLink).toBeUndefined();+ });+it("opens a new link on the side and with the display it is asked for", () => {const opts = getAddLinkOpts(createApi(null), ready, { target: "url", display: "embed" });expect(opts).toMatchObject({ target: "url", display: "embed" });diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex e940d35297..c71dfda3e4 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -598,6 +598,7 @@ export function getAddLinkOpts(api.addLinkPreview(...args);}+ const anchors = api.getAnchors();const currentLink = api.getCurrentLink();if (currentLink) {return {@@ -605,7 +606,8 @@ export function getAddLinkOpts(hasSelection: false,currentTitle: currentLink.text,display: currentLink.display,- ...parseLinkHref(currentLink.href),+ anchors,+ ...parseLinkHref(currentLink.href, anchors),async addLink(notePath, linkTitle, externalLink) {await ready();await api.updateLink(notePath, linkTitle, externalLink);@@ -619,6 +621,7 @@ export function getAddLinkOpts(hasSelection: api.hasSelection(),target,display,+ anchors,async addLink(notePath, linkTitle, externalLink) {await ready();api.addLink(notePath, linkTitle, externalLink);@@ -628,10 +631,16 @@ export function getAddLinkOpts(}/**- * What a link's `href` opens the Add link dialog on: the note, with the anchor it points at, or- * the address.+ * What a link's `href` opens the Add link dialog on: one of the document's `anchors`, the note+ * with the anchor it points at, or the address.*/-export function parseLinkHref(href: string): Pick<AddLinkOpts, "currentLink" | "currentBookmark"> {+export function parseLinkHref(+ href: string, anchors: string[] = []+): Pick<AddLinkOpts, "currentLink" | "currentBookmark" | "currentAnchor"> {+ if (href.startsWith("#") && anchors.includes(href.slice(1))) {+ return { currentAnchor: href.slice(1) };+ }+if (!href.startsWith("#")) {return { currentLink: { externalLink: href }, currentBookmark: undefined };}diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.jsonindex 62025a2d9a..eb1ed6152b 100644--- a/apps/server/src/assets/help/help_content.json+++ b/apps/server/src/assets/help/help_content.json@@ -115,7 +115,7 @@"_help_i6dbnitykE5D": "<h2>Inspiration for the name “Trilium”</h2><blockquote><p>Naming software is hard. I lived in Ontario when I first started the project and Trillium (the flower) is sort of a provincial logo, many institutions in Ontario are named \"Trillium [something]\". So I kept hearing/reading it almost everyday, I liked the sound of it and its nature motif, so I just reused it.</p><p><em>– Zadam (original Trilium maintainer)</em></p></blockquote><aside class=\"admonition note\"><p>Despite the fact that the Trillium flower has two “l\"s, the Trilium application only has one.</p></aside><h2>How do I create a folder?</h2><p>Trilium has no separate folder type: any note can have child notes, so any note can act as a folder. A note can hold its own content and have children at the same time, unlike a file system, which separates files from directories.</p><p>To organize notes into a folder:</p><ol><li>Create a note that acts as the folder, for example \"Projects\".</li><li>Right-click it in the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a> and select <em>Insert child note</em>, or hover over it and press the <span class=\"tn-icon bx bx-plus\"></span> button.</li><li>To move existing notes into it, drag them onto it in the tree.</li></ol><p>The children of a note are listed at the end of its content (see <a class=\"reference-link\" href=\"#root/_help_0ESUbbAxVnoK\">Note List</a>).</p><p>If you want the note to look like a folder, with no content of its own and only its children shown, make it a collection instead: right-click in the tree, select <em>Insert child note</em> → <em>Collection</em>, then choose <a class=\"reference-link\" href=\"#root/_help_8QqnMzx393bx\">Grid View</a> or <a class=\"reference-link\" href=\"#root/_help_mULW0Q3VojwY\">List View</a>. See <a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a> for the other views, such as tables, boards and calendars.</p><h2>macOS support</h2><p>Originally, Trilium Notes considered the macOS build unsupported. TriliumNext commits to make the experience on macOS as good as possible.</p><p>if you find any platform-specific issues, feel free to <a href=\"#root/_help_wy8So3yZZlH9\">report them</a>.</p><h2>Translation / localisation support</h2><p>The original Trilium Notes application did not support multiple languages. Since we believe that internationalisation is a core part of an application, we have added support for it.</p><p>Contributions to translations are welcome.</p><h2>Multi-user support</h2><p>Common request is to allow multiple users collaborate, share notes etc. So far I'm resisting this because of these reasons:</p><ul><li>it's a huge feature, or rather a Pandora's box of collaboration features like user management, permissions, conflict resolution, real-time editing of a note by multiple people etc. This would be a huge amount of work. Trilium Notes is project made mostly by one person in free time and that's unlikely to change in the future.</li><li>given its size it would probably pivot the attention away from my main focus which is a personal note-taking</li><li>the assumption that only single person has access to the app simplifies many things, or just outright makes them possible. In multi-user app, our <a href=\"#root/_help_CdNpE2pqjmI6\">scripting</a>support would be a XSS security hole, while with the single user assumption it's an endless customizable tool.</li></ul><h2>How to open multiple documents in one Trilium instance</h2><p>This is normally not supported - one Trilium process can open only a single instance of a <a href=\"#root/_help_wX4HbRucYSDD\">database</a>. However, you can run two Trilium processes (from one installation), each connected to a separate document. To achieve this, you need to set a location for the <a href=\"#root/_help_tAassRL4RSQL\">data directory</a> in the <code>TRILIUM_DATA_DIR</code> environment variable and separate port on <code>TRILIUM_PORT</code> environment variable. How to do that depends on the platform, in Unix-based systems you can achieve that by running command such as this:</p><pre><code class=\"language-text-x-sh\">TRILIUM_DATA_DIR=/home/me/path/to/data/dir TRILIUM_PORT=12345 trilium </code></pre><p>You can save this command into a <code>.sh</code> script file or make an alias. Do this similarly for a second instance with different data directory and port.</p><h2>Can I use Dropbox / Google Drive / OneDrive to sync data across multiple computers.</h2><p>No.</p><p>These general purpose sync apps are not suitable to sync database files which are open and being worked on by another application. The result is that they will corrupt the database file, resulting in data loss and this message in the Trilium logs:</p><pre><code class=\"language-text-x-trilium-auto\">SqliteError: database disk image is malformed</code></pre><p>The only supported way to sync Trilium's data across the network is to use a <a href=\"#root/_help_cbkrhQjrkKrh\">sync/web server</a>.</p><h2>Why database instead of flat files?</h2><p>Trilium stores notes in a <a href=\"#root/_help_wX4HbRucYSDD\">database</a> which is an SQLite database. People often ask why doesn't Trilium rather use flat files for note storage - it's fair question since flat files are easily interoperable, work with SCM/git etc.</p><p>Short answer is that file systems are simply not powerful enough for what we want to achieve with Trilium. Using filesystem would mean fewer features with probably more problems.</p><p>More detailed answer:</p><ul><li><a href=\"#root/_help_IakOLONlIfGI\">clones</a> are what you might call \"hard directory link\" in filesystem lingo, but this concept is not implemented in any filesystem</li><li>filesystems make a distinction between directory and file while there's intentionally no such difference in Trilium</li><li>files are stored in no particular order and user can't change this</li><li>Trilium allows storing note <a href=\"#root/_help_zEY4DaJG4YT5\">attributes</a> which could be represented in extended user attributes but their support differs greatly among different filesystems / operating systems</li><li>Trilium makes links / relations between different notes which can be quickly retrieved / navigated (e.g. for <a href=\"#root/_help_BCkXAVs63Ttv\">note map</a>). There's no such support in file systems which means these would have to be stored in some kind of side-car files (mini-databases).</li><li>Filesystems are generally not transactional. While this is not completely required for a note-taking application, having transactions make it way easier to keep notes and their metadata in predictable and consistent state.</li></ul><h2>Search-related Questions</h2><h3>Why does search sometimes find results with typos?</h3><p>Trilium uses a progressive search strategy that includes fuzzy matching when exact matches return fewer than 5 results. This finds notes despite minor typos in your search query. You can use fuzzy search operators (<code>~=</code> for fuzzy exact match and <code>~*</code> for fuzzy contains). See the <a class=\"reference-link\" href=\"#root/_help_eIg8jdvaoNNd\">Search</a> documentation for details.</p><h3>How can I search for notes when I'm not sure of the exact spelling?</h3><p>Use the fuzzy search operators:</p><ul><li><code>#title ~= \"projct\"</code> - finds notes with titles like \"project\" despite the typo</li><li><code>note.content ~* \"algoritm\"</code> - finds content containing \"algorithm\" or similar words</li></ul><h3>Why do some search results appear before others with lower scores?</h3><p>Trilium places exact matches before fuzzy matches. When you search for \"project\", notes containing exactly \"project\" appear before notes with variations like \"projects\" or \"projection\", regardless of other scoring factors.</p><h3>How can I make my searches faster?</h3><ol><li>Use the \"Fast search\" option to search only titles and attributes (not content)</li><li>Limit search scope using the \"Ancestor\" field</li><li>Set a result limit to prevent loading too many results</li><li>For large databases, consider archiving old notes to reduce search scope</li></ol>","_help_KSZ04uQ2D1St": "<p>One of the core features of Trilium is that it supports multiple types of notes, depending on the need.</p><h2>Creating a new note with a different type via the note tree</h2><p>The default note type in Trilium (e.g. when creating a new note) is <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>, since it's for general use.</p><p>To create a new note of a different type, head to the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a> and right click an existing note where to place the new one and select:</p><ul><li><em>Insert note after</em>, to put the new note underneath the one selected.</li><li><em>Insert child note</em>, to insert the note as a child of the selected note.</li></ul><p>The note types created less often, <a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a>, <a class=\"reference-link\" href=\"#root/_help_HcABDtFCkbFN\">Render Note</a>, <a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a> and <a class=\"reference-link\" href=\"#root/_help_bdUJEHsAPYQR\">Note Map</a>, are in the <em>More</em> submenu.</p><p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types_image.png\"></p><h2>Creating a new note of a different type via add link or new tab</h2><ul><li>When adding a <a href=\"#root/_help_QEAPj01N5f7w\">link</a> in a <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> note, type the desired title of the new note and press Enter. Afterwards the type of the note will be asked.</li><li>Similarly, when creating a new tab, type the desired title and press Enter.</li></ul><p>The note type is chosen from the same menu as in the note tree, with its submenus (code languages, snippets, collections and the note types created less often) and its search box: type to narrow the list, then press <kbd>Enter</kbd> to create the first match. <kbd>Enter</kbd> right away creates a Text note.</p><h2>Changing the type of a note</h2><p>It is possible to change the type of a note after it has been created via <a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a> → <em>Note type</em>. This feature can also be used to edit the <a href=\"#root/_help_4FahAwuGTAwC\">source of a note</a>.</p><aside class=\"admonition note\"><p>Note that it's generally a good idea to change the note type only if the note is empty</p></aside><h2>Supported note types</h2><p>The following note types are supported by Trilium:</p><figure class=\"table\"><table><thead><tr><th>Note Type</th><th>Description</th></tr></thead><tbody><tr><td><a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a></td><td>The default note type, which allows for rich text formatting, images, admonitions and right-to-left support.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a></td><td>Uses a mono-space font and can be used to store larger chunks of code or plain text than a text note, and has better syntax highlighting.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a></td><td>Stores the information about a search (the search text, criteria, etc.) for later use. Can be used for quick filtering of a large amount of notes, for example. The search can easily be triggered.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a></td><td>Allows easy creation of notes and relations between them. Can be used for mainly relational data such as a family tree.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_bdUJEHsAPYQR\">Note Map</a></td><td>Displays the relationships between the notes, whether via relations or their hierarchical structure.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_HcABDtFCkbFN\">Render Note</a></td><td>Used in <a class=\"reference-link\" href=\"#root/_help_CdNpE2pqjmI6\">Scripting</a>, it displays the HTML content of another note. This allows displaying any kind of content, provided there is a script behind it to generate it.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a></td><td>Displays the children of the note either as a grid, a list, or for a more specialized case: a calendar. <br> <br>Generally useful for easy reading of short notes.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a></td><td>Displays diagrams such as bar charts, flow charts, state diagrams, etc. Requires a bit of technical knowledge since the diagrams are written in a specialized format.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a></td><td>Allows easy drawing of sketches, diagrams, handwritten content. Uses the same technology behind <a href=\"https://excalidraw.com\">excalidraw.com</a>.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a></td><td>Displays the content of an external web page, similar to a browser.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_gBbsAeiuUxI5\">Mind Map</a></td><td>Easy for brainstorming ideas, by placing them in a hierarchical layout.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a></td><td>Displays the children of the note as a geographical map, one use-case would be to plan vacations. It even has basic support for tracks. Notes can also be created from it.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_W8vYD3Q1zjCR\">File</a></td><td>Represents an uploaded file such as PDFs, images, video or audio files.</td></tr></tbody></table></figure>","_help_iPIMuisry3hd": "<p>The default note type in Trilium, text notes allow for rich formatting, tables, images, admonitions and a handful of other features.</p><h2>Formatting bars</h2><p>Most of the interaction with text notes is done via the built-in toolbars. Depending on preference, there are two different layouts:</p><ul><li>The <em>Floating toolbar</em> is hidden by default and only appears when needed. In this mode there are actually two different toolbars:<br><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/1_Text_image.png\" width=\"496\" height=\"91\"><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/2_Text_image.png\" width=\"812\" height=\"114\"></li><li>A toolbar that appears when text is selected. This provides text-level formatting such as bold, italic, text colors, inline code, etc.<br><em><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text_image.png\" width=\"1109\" height=\"124\"></em></li></ul><p>Fore more information see <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>.</p><h2>Features and formatting</h2><p>Here's a list of various features supported by text notes:</p><figure class=\"table\"><table><thead><tr><th>Dedicated article</th><th>Feature</th></tr></thead><tbody><tr><td><a class=\"reference-link\" href=\"#root/_help_Gr6xFaF6ioJ5\">General formatting</a></td><td><ul><li>Headings (section titles, paragraph)</li><li>Font size</li><li>Bold, italic, underline, strike-through</li><li>Superscript, subscript</li><li>Font color & background color</li><li>Remove formatting</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_S6Xx8QIWTV66\">Lists</a></td><td><ul><li>Bulleted lists</li><li>Numbered lists</li><li>To-do lists</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_NwBbFdNZ9h7O\">Block quotes & admonitions</a></td><td><ul><li>Block quotes</li><li>Admonitions</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_NdowYOC1GFKS\">Tables</a></td><td><ul><li>Basic tables</li><li>Merging cells</li><li>Styling tables and cells.</li><li>Table captions</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_UYuUB1ZekNQU\">Developer-specific formatting</a></td><td><ul><li>Inline code</li><li>Code blocks</li><li>Keyboard shortcuts</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_AgjCISero73a\">Footnotes</a></td><td><ul><li>Footnotes</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_mT0HEkOsz6i1\">Images</a></td><td><ul><li>Images</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_QEAPj01N5f7w\">Links</a></td><td><ul><li>External links</li><li>Internal Trilium links</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a></td><td><ul><li>Include note</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a></td><td><ul><li>Links to blocks of a note</li><li>Including blocks of a note</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a></td><td><ul><li>Symbols</li><li><a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a></li><li>Mermaid diagrams</li><li>Horizontal ruler</li><li>Page break</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_dEHYtoWWi8ct\">Other features</a></td><td><ul><li>Indentation<ul><li>Markdown import</li></ul></li><li><a class=\"reference-link\" href=\"#root/_help_2x0ZAX9ePtzV\">Cut to subnote</a></li><li><a class=\"reference-link\" href=\"#root/_help_0vgWgxQAWj4a\">Sorting</a></li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_gLt3vA97tMcp\">Premium features</a></td><td><ul><li><a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a></li><li><a class=\"reference-link\" href=\"#root/_help_KC1HB96bqqHX\">Templates</a></li><li><a class=\"reference-link\" href=\"#root/_help_5wZallV2Qo1t\">Format Painter</a></li></ul></td></tr></tbody></table></figure><h2>Read-Only vs. Editing Mode</h2><p>Text notes are usually opened in edit mode. However, they may open in read-only mode if the note is too big or the note is explicitly marked as read-only. For more information, see <a class=\"reference-link\" href=\"#root/_help_CoFPLs3dRlXc\">Read-Only Notes</a>.</p><h2>Keyboard shortcuts</h2><p>There are numerous keyboard shortcuts to format the text without having to use the mouse. For a reference of all the key combinations, see <a class=\"reference-link\" href=\"#root/_help_A9Oc6YKKc65v\">Keyboard Shortcuts</a>. In addition, see <a class=\"reference-link\" href=\"#root/_help_QrtTYPmdd1qq\">Markdown-like formatting</a> as an alternative to the keyboard shortcuts.</p><h2>Content width</h2><p>For readability purposes on wider screens, the width of text notes is limited via a configurable option. See <a class=\"reference-link\" href=\"#root/_help_t596jLvPrqkS\">Content width</a> for more information.</p><h2>Converting to a Markdown note</h2><p>Text notes can be converted to <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> notes. See <a class=\"reference-link\" href=\"#root/_help_jludwdW7N4hg\">Converting between note types</a>.</p><h2>Technical details</h2><p>For the text editing functionality, Trilium uses a commercial product (with an open-source base) called <a class=\"reference-link\" href=\"#root/_help_MI26XDLSAlCD\">CKEditor</a>. This brings the benefit of having a powerful WYSIWYG (What You See Is What You Get) editor.</p>",- "_help_oSuaNgyyKnhu": "<aside class=\"admonition note\"><p>This feature used to be called <em>Bookmarks</em> (as it is the official name in the editor we are using), but in order not to collide with the concept of <a class=\"reference-link\" href=\"#root/_help_u3YFHC9tQlpm\">Bookmarks</a>, we have renamed it to <em>Anchors.</em></p></aside><p>Anchors allows creating <a href=\"#root/_help_QEAPj01N5f7w\">links</a> to a certain part of a note, such as referencing a particular heading or section within a note.</p><p>This feature was introduced in TriliumNext v0.94.0 and augmented in v0.103.0 to support linking across notes.</p><h2>Interaction</h2><ul><li>To create a anchor:<ul><li>Place the cursor at the desired position where to place the anchor.</li><li>Look for the <span class=\"tn-icon bx bx-plus\"></span> button in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, and then press the <span class=\"tn-icon cke cke-bookmark\"></span> button.</li><li>Alternatively, use <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a> and look for <em>anchor</em>.</li></ul></li><li>To place a link to a anchor:<ul><li>Place the cursor at the desired position of the link.</li><li>From the <a href=\"#root/_help_QEAPj01N5f7w\">link</a> pane, select the <em>Anchors</em> section and select the desired anchor.</li></ul></li></ul><h2>Linking across notes</h2><p>Trilium v0.103.0 introduces cross-note Anchors, which makes it possible to create <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> which point to a specific anchor in that document.</p><h3>Compatibility with documents from previous versions</h3><p>For notes created prior to Trilium v0.103.0, you might notice that the Anchors might not be identified. This limitation is intentional in order not to have to re-process all the notes, looking for anchors.</p><p>To fix this, simply go that note and make any change (e.g. inserting a space), this will trigger the recalculation of the links.</p><h3>Linking to anchors through the <em>Add link</em> dialog</h3><ol><li>Create an anchor in the target note using the same process as described above.</li><li>In another note, press <kbd>Ctrl</kbd>+<kbd>L</kbd> to insert an internal link. Select the target note containing Anchors.</li><li>If the target note contains Anchors, a section will appear underneath the note selector with the list of Anchors.</li><li>Add the link normally.</li></ol><p>Clicking on a reference link pointing to a anchor will automatically scroll to the desired section.</p><h3>Linking to anchors through the bookmark toolbar</h3><ol><li>Create an anchor in the target note using the same process as described above.</li><li>Click on the anchor to reveal the anchor's floating toolbar.</li><li>Click on the <span class=\"tn-icon cke cke-trilium-copy\"></span> <em>Copy anchor reference link</em> button.</li><li>Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.</li></ol><aside class=\"admonition note\"><p>Use this method only to insert <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> between two documents. To link to an anchor on the same note, use the <em>Insert link</em> dialog (<kbd>Ctrl</kbd>+<kbd>K</kbd>) and select the <em>Anchors</em> item instead.</p></aside>",+ "_help_oSuaNgyyKnhu": "<aside class=\"admonition note\"><p>This feature used to be called <em>Bookmarks</em> (as it is the official name in the editor we are using), but in order not to collide with the concept of <a class=\"reference-link\" href=\"#root/_help_u3YFHC9tQlpm\">Bookmarks</a>, we have renamed it to <em>Anchors.</em></p></aside><p>Anchors allows creating <a href=\"#root/_help_QEAPj01N5f7w\">links</a> to a certain part of a note, such as referencing a particular heading or section within a note.</p><p>This feature was introduced in TriliumNext v0.94.0 and augmented in v0.103.0 to support linking across notes.</p><h2>Interaction</h2><ul><li>To create an anchor:<ul><li>Place the cursor at the desired position where to place the anchor.</li><li>Look for the <span class=\"tn-icon bx bx-plus\"></span> button in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, and then press the <span class=\"tn-icon cke cke-bookmark\"></span> button.</li><li>Alternatively, use <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a> and look for <em>anchor</em>.</li></ul></li><li>To place a link to an anchor in the same note:<ul><li>Place the cursor at the desired position of the link, or select the text to turn into a link.</li><li>Press <kbd>Ctrl</kbd>+<kbd>K</kbd> or the <span class=\"tn-icon cke cke-link\"></span> button in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, then select <em>Anchors</em> at the top of the <a href=\"#root/_help_QEAPj01N5f7w\"><em>Add link</em> dialog</a>.</li><li>Under <em>Target anchor</em>, click the desired anchor to check it. Optionally, type a <em>Link title</em>; without one, the link shows the anchor's name.</li><li>Press <kbd>Enter</kbd> or <em>Add link</em> to confirm.</li></ul></li><li>To change a link to an anchor, place the cursor inside it and press <kbd>Ctrl</kbd>+<kbd>K</kbd>. Since v0.107.0, the <em>Edit link</em> dialog opens on <em>Anchors</em>, with the linked anchor checked.</li></ul><h2>Linking across notes</h2><p>Trilium v0.103.0 introduces cross-note Anchors, which makes it possible to create <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> which point to a specific anchor in that document.</p><h3>Compatibility with documents from previous versions</h3><p>For notes created prior to Trilium v0.103.0, you might notice that the Anchors might not be identified. This limitation is intentional in order not to have to re-process all the notes, looking for anchors.</p><p>To fix this, simply go that note and make any change (e.g. inserting a space), this will trigger the recalculation of the links.</p><h3>Linking to anchors through the <em>Add link</em> dialog</h3><ol><li>Create an anchor in the target note using the same process as described above.</li><li>In another note, press <kbd>Ctrl</kbd>+<kbd>L</kbd> to insert an internal link. Select the target note containing Anchors.</li><li>If the target note contains Anchors, a section will appear underneath the note selector with the list of Anchors.</li><li>Add the link normally.</li></ol><p>Clicking on a reference link pointing to an anchor will automatically scroll to the desired section.</p><h3>Linking to anchors through the bookmark toolbar</h3><ol><li>Create an anchor in the target note using the same process as described above.</li><li>Click on the anchor to reveal the anchor's floating toolbar.</li><li>Click on the <span class=\"tn-icon cke cke-trilium-copy\"></span> <em>Copy anchor reference link</em> button.</li><li>Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.</li></ol><aside class=\"admonition note\"><p>Use this method only to insert <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> between two documents. To link to an anchor on the same note, use the <em>Add link</em> dialog (<kbd>Ctrl</kbd>+<kbd>K</kbd>) and select <em>Anchors</em> at its top instead.</p></aside>","_help_oI7GoyilXXAr": "<h2>Automatic replacements</h2><p>As you type in a text note, certain character sequences are replaced with the typographic symbol they represent. Typing <code>(c)</code> gives you <code>©</code>, <code>...</code> gives you <code>…</code>, and <code>\"quote\"</code> gives you <code>“quote”</code>.</p><p>These replacements are not applied inside code blocks or inline code, and pasted text is never affected, only text you type. If you have pasted a code snippet, or written one inside a code block, its characters are left exactly as they are.</p><h3>Undoing a replacement</h3><p>Once an automatic replacement takes place, it can be undone by:</p><ul><li>Pressing <kbd>Backspace</kbd> immediately after a replacement undoes it and restores what you typed.<ul><li>Note that this consumes the undo, so a further <kbd>Ctrl</kbd>+<kbd>Z</kbd> might delete your typed text.</li><li>Pressing <kbd>Space</kbd> or changing the cursor position disables this functionality.</li></ul></li><li>Pressing <kbd>Ctrl</kbd>+<kbd>Z</kbd>, which works even after pressing space.</li></ul><h3>Replacement groups & configuration</h3><p>Each group can be turned off in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text notes</em> → <em>Automatic replacements</em>.</p><figure class=\"table\"><table><thead><tr><th>Group</th><th>What it replaces</th></tr></thead><tbody><tr><td>Punctuation</td><td><code>...</code> with an ellipsis (<code>…</code>), and <code>--</code> and <code>---</code> <em>surrounded by spaces</em> with an en dash (<code>–</code>) and an em dash (<code>—</code>)</td></tr><tr><td>Mathematical symbols</td><td>fractions such as <code>1/2</code> with <code>½</code>, and the operators <code><=</code>, <code>>=</code>, <code>!=</code>, <code><-</code> and <code>-></code> with <code>≤</code>, <code>≥</code>, <code>≠</code>, <code>←</code> and <code>→</code></td></tr><tr><td>Copyright and trademark</td><td><code>(c)</code>, <code>(r)</code> and <code>(tm)</code> with <code>©</code>, <code>®</code> and <code>™</code></td></tr><tr><td>Quotation marks</td><td>straight quotes with typographic ones — see below</td></tr></tbody></table></figure><h2>Quotation marks</h2><p>Quotation marks are configured separately from the rest, with one setting for the <strong>double</strong> quote key and one for the <strong>single</strong> quote key, because which pair belongs on which key differs between conventions: British typography traditionally sets a quotation in <code>‘…’</code> where American sets it in <code>“…”</code>.</p><p>Each offers:</p><ul><li><em>Based on the note's content language</em> (the default) — English gives <code>“quote”</code>, German <code>„quote“</code>, French <code>« quote »</code>, Japanese <code>「quote」</code>. See <a class=\"reference-link\" href=\"#root/_help_veGu4faJErEM\">Content language & Right-to-left support</a> for how a note's language is decided.</li><li><em>Disabled,</em> straight quotes stay straight.</li><li>A specific pair_:_ <code>“…”</code>, <code>‘…’</code>, <code>„…“</code>, <code>„…”</code>, <code>«…»</code>, <code>« … »</code>, <code>‹…›</code>, <code>「…」</code>, <code>『…』</code>. Choosing one applies it to every note, regardless of its content language.</li></ul><h2>Custom replacements</h2><p>You can add your own under <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text notes</em> → <em>Automatic replacements</em> → <em>Custom replacements</em>. Type the text to replace and the replacement, then press Enter. Existing ones are shown as chips and removed with the × on each.</p><p>A custom replacement is applied when the text is typed as a whole word and followed by a space, so longer words that begin with it are left alone — a <code>TN</code> replacement does not rewrite the end of <code>BTN</code>, and <code>TNT</code> can still be typed.</p><p>Capitalization follows what you type, unless the replacement has capitals of its own:</p><figure class=\"table\"><table><thead><tr><th><strong>Replacement you defined</strong></th><th><strong>You type</strong></th><th><strong>You get</strong></th></tr></thead><tbody><tr><td><code>teh</code> → <code>the</code></td><td><code>teh</code> / <code>Teh</code> / <code>TEH</code></td><td><code>the</code> / <code>The</code> / <code>THE</code></td></tr><tr><td><code>TN</code> → <code>Trilium Notes</code></td><td><code>TN</code> or <code>tn</code></td><td><code>Trilium Notes</code> (unchanged, it has capitals)</td></tr></tbody></table></figure><p>Of note:</p><ul><li>The text to replace is matched literally; it is not a pattern.</li><li>Typing a \"text to replace\" that already exists in the list of replacements will update the existing one instead. It's not possible to have multiple replacements for the same text.</li><li>The same “text to replace” with different capitalization (e.g. <code>TN</code> and <code>tn</code> co-existing) doesn't work because it would interfere with the capitalization rules above.</li></ul><h2>Characters that only look replaced (ligatures)</h2><p>If you see <code>!=</code> displayed as <code>≠</code> or <code>-></code> as <code>→</code> inside a code block, that is not a replacement since replacements never run there (unless a code block is applied to an existing text). It is a <em>font ligature</em>: the default monospace font draws certain character pairs as a single symbol. The underlying text is unchanged, and copying it out gives you back <code>!=</code> and <code>-></code>.</p><p>This can be turned off with <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a><em>→ Appearance → Fonts → Programming ligatures.</em></p>","_help_NwBbFdNZ9h7O": "<h2>Block quotes</h2><p>As the name suggests, block quotes can be useful to cite one or more paragraphs.</p><p>To create a block quote, press <span class=\"tn-icon cke cke-quote\"></span> from the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>. It's also possible to type <kbd>></kbd>, followed by a space to create one (but only if the cursor is at the beginning of a line).</p><p>Inside the quote block, other block items can be inserted such as tables, images, or even other block quotes or admonitions.</p><h2>Admonitions</h2><p>Admonitions are a way to highlight information to the reader. Other names for it include <em>call-outs</em> and <em>info/warning/alert boxes</em>.</p><figure class=\"image image-style-align-center\"><img style=\"aspect-ratio:959/547;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Block%20quotes%20%26%20admonitions_image.png\" width=\"959\" height=\"547\"></figure><p>From a functional point of view, admonitions act very similarly to a block quote, just with different styling. This includes the ability to insert other elements in it such as headings, tables, images, etc.</p><h3>Inserting a new admonition</h3><p>In the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>:</p><p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Block%20quotes%20%26%20admonitions_image.png\"></p><p>It's possible to insert an admonition simply by typing:</p><ul><li><code>!!! note</code></li><li><code>!!! tip</code></li><li><code>!!! important</code></li><li><code>!!! caution</code></li><li><code>!!! warning</code></li></ul><p>In addition to that, it's also possible to type <code>!!!</code> followed by any text, case in which a default admonition type will appear (note) with the entered text inside it.</p><h3>Interaction</h3><p>By design, admonitions act very similar to block quotes.</p><ul><li>Selecting a text and pressing the admonition button will turn that text into an admonition.</li><li>If selecting multiple admonitions, pressing the admonition button will automatically merge them into one.</li></ul><p>Inside an admonition:</p><ul><li>Pressing <kbd>Backspace</kbd> while the admonition is empty will remove it.</li><li>Pressing <kbd>Enter</kbd> will start a new paragraph. Pressing it twice will exit out of the admonition.</li><li>Headings and other block content including tables can be inserted inside the admonition.</li></ul><h3>Types of admonitions</h3><p>There are currently five types of admonitions: <em>Note</em>, <em>Tip</em>, <em>Important</em>, <em>Caution</em>, <em>Warning</em>.</p><p>These types were inspired by GitHub's support for this feature and there are currently no plans for adjusting it or allowing the user to customize them.</p><h3>Markdown support</h3><p>See <a class=\"reference-link\" href=\"#root/_help_rJ9grSgoExl9\">Supported syntax</a>.</p>","_help_klC3ilXa9kUE": "<p>Block references are <a href=\"#root/_help_QEAPj01N5f7w\">links</a> to a block of a text note, such as a paragraph, a heading, a list item or a table, or to a range of consecutive blocks. A block reference can be pasted in another note as a link, or turned into an <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a> that shows only the referenced blocks.</p><h2>Copying a reference</h2><ol><li>Place the cursor in the block to reference. To reference several consecutive blocks, select them.</li><li>Right-click the block handle, the sequence of dots to the left of the block (see <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>). Alternatively, right-click the text and open the <em>Copy</em> submenu.</li><li>Select <em>Copy reference to this block</em>, or <em>Copy reference to these blocks</em> for a selection. The referenced blocks flash briefly.</li><li>Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.</li></ol><p>Inside a <a class=\"reference-link\" href=\"#root/_help_EK2ckIZ74tbT\">Content tabs</a> block, the reference points to the whole block. To link to a single tab, use <em>Copy link to tab</em> instead. Inside a <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a>, the reference points to the blocks in the column, and an include shows them without the layout around them.</p><p>The link shows the title of the note, followed by the beginning of the referenced text. A link to blocks of the same note shows only the beginning of the referenced text.</p><p>If the note is <a href=\"#root/_help_R9pX4DGra2Vt\">shared</a>, the menu of the block handle also offers <em>Copy public link to this block</em>. It copies the web address of the shared page with the reference added, to send to people who read the note outside Trilium. Opening the address scrolls the shared page to the referenced blocks and flashes them.</p><p>The <em>Paste</em> submenu of the context menu offers two more ways to insert a copied reference:</p><ul><li><em>Paste reference as a link</em> inserts only the link, even when the reference was copied as plain text or along with other content.</li><li><em>Paste reference as an excerpt</em> inserts an include of the referenced blocks, as described below.</li></ul><p>In a browser, the context menu of the text editor opens only when right-clicking selected text. Elsewhere the browser shows its own menu.</p><h2>Following a reference</h2><p>Clicking a block reference opens the note, scrolls to the referenced blocks and flashes them. If a referenced block was deleted, an error message is shown instead, along with the blocks of the range that still exist.</p><h2>Including the referenced blocks</h2><p>To show the referenced blocks inside another note, right-click the link in a note being edited and select <em>Convert link to note excerpt</em>, or paste the copied reference with <em>Paste</em> → <em>Paste reference as an excerpt</em>. The include shows only the referenced blocks, not the rest of the note, and marks them with an <em>Excerpt</em> badge in its title. It starts at the <em>Full</em> box size, so all the referenced blocks are visible. To see the whole note, press the <span class=\"tn-icon bx bx-link-external\"></span> button in the same title, which opens the note in a new tab. Converting the include back to a link keeps the reference.</p><p>To edit the referenced blocks without leaving the note, press the <span class=\"tn-icon bx bx-pencil\"></span> <em>Edit excerpt</em> button in the title of the include, or turn on <em>Editable</em> (<span class=\"tn-icon bx bx-edit-alt\"></span>) in its toolbar, as for any <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>. Press the button again to stop editing. The changes are saved to the referenced blocks, and the rest of the note stays as it is. The button is grayed out where the blocks cannot be edited, such as in a read-only note. An excerpt has no <em>Fullscreen</em> button.</p><p>If a referenced block was deleted, the include shows <em>Broken reference</em>.</p><h2>Limitations</h2><ul><li>References can be copied only from a note being edited, and not in the mobile layout.</li><li>An include of a range that covers only part of a list or a quote, such as from its second item to a paragraph after it, cannot be edited in place.</li><li>Deleting a block breaks the references to it.</li><li>Block references are not kept when exporting to Markdown. On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, a block reference opens the whole note.</li></ul>",diff --git a/docs/User Guide/User Guide/Note Types/Text/Anchors.md b/docs/User Guide/User Guide/Note Types/Text/Anchors.mdindex 32714dd4ec..2b35522573 100644--- a/docs/User Guide/User Guide/Note Types/Text/Anchors.md+++ b/docs/User Guide/User Guide/Note Types/Text/Anchors.md@@ -8,13 +8,16 @@ This feature was introduced in TriliumNext v0.94.0 and augmented in v0.103.0 to## Interaction-* To create a anchor:+* To create an anchor:* Place the cursor at the desired position where to place the anchor.* Look for the <span class="tn-icon bx bx-plus"></span> button in the <a class="reference-link" href="Formatting%20toolbar.md">Formatting toolbar</a>, and then press the <span class="tn-icon cke cke-bookmark"></span> button.* Alternatively, use <a class="reference-link" href="Slash%20Commands.md">Slash Commands</a> and look for _anchor_.-* To place a link to a anchor:- * Place the cursor at the desired position of the link.- * From the [link](Links.md) pane, select the _Anchors_ section and select the desired anchor.+* To place a link to an anchor in the same note:+ * Place the cursor at the desired position of the link, or select the text to turn into a link.+ * Press <kbd>Ctrl</kbd>+<kbd>K</kbd> or the <span class="tn-icon cke cke-link"></span> button in the <a class="reference-link" href="Formatting%20toolbar.md">Formatting toolbar</a>, then select _Anchors_ at the top of the [_Add link_ dialog](Links.md).+ * Under _Target anchor_, click the desired anchor to check it. Optionally, type a _Link title_; without one, the link shows the anchor's name.+ * Press <kbd>Enter</kbd> or _Add link_ to confirm.+* To change a link to an anchor, place the cursor inside it and press <kbd>Ctrl</kbd>+<kbd>K</kbd>. Since v0.107.0, the _Edit link_ dialog opens on _Anchors_, with the linked anchor checked.## Linking across notes@@ -33,7 +36,7 @@ To fix this, simply go that note and make any change (e.g. inserting a space), t3. If the target note contains Anchors, a section will appear underneath the note selector with the list of Anchors.4. Add the link normally.-Clicking on a reference link pointing to a anchor will automatically scroll to the desired section.+Clicking on a reference link pointing to an anchor will automatically scroll to the desired section.### Linking to anchors through the bookmark toolbar@@ -43,4 +46,4 @@ Clicking on a reference link pointing to a anchor will automatically scroll to t4. Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.> [!NOTE]-> Use this method only to insert <a class="reference-link" href="Links/Internal%20(reference)%20links.md">Internal (reference) links</a> between two documents. To link to an anchor on the same note, use the _Insert link_ dialog (<kbd>Ctrl</kbd>+<kbd>K</kbd>) and select the _Anchors_ item instead.\ No newline at end of file+> Use this method only to insert <a class="reference-link" href="Links/Internal%20(reference)%20links.md">Internal (reference) links</a> between two documents. To link to an anchor on the same note, use the _Add link_ dialog (<kbd>Ctrl</kbd>+<kbd>K</kbd>) and select _Anchors_ at its top instead.\ No newline at end of filediff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 503a97a9f7..c34fa31a74 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -29,7 +29,9 @@ export type { InlineEmbedSource } from "./plugins/content_embed/inline_source.jsexport type { ContentEmbedHost } from "./plugins/content_embed/content_embed.js";export type { AttachmentLinkChange } from "./plugins/referencelink.js";export type { ChildNoteHost } from "./plugins/child_note.js";-export { getLinkAtSelection, replaceLinkAtSelection } from "./plugins/internallink.js";+export {+ getAnchorNames, getLinkAtSelection, replaceLinkAtSelection+} from "./plugins/internallink.js";export type { LinkAtSelection, LinkDialogRequest } from "./plugins/internallink.js";export type { default as TriliumEmojiMention, EmojiSuggestion } from "./plugins/mention/emoji_mention.js";export type { default as TriliumSlashCommands, SlashCommandConfig, SlashCommandDefinition, SlashCommandItem } from "./plugins/mention/slash_commands.js";diff --git a/packages/ckeditor5/src/plugins/internallink.spec.ts b/packages/ckeditor5/src/plugins/internallink.spec.tsindex 800a1f4b73..27fa5a5faa 100644--- a/packages/ckeditor5/src/plugins/internallink.spec.ts+++ b/packages/ckeditor5/src/plugins/internallink.spec.ts@@ -1,13 +1,14 @@import {- _getModelData as getModelData, _setModelData as setModelData, Bold, ButtonView, ClassicEditor, CodeBlock,- ContextualBalloon, Essentials, keyCodes, type KeystrokeHandler, Link, LinkEditing, LinkUI,- Paragraph+ _getModelData as getModelData, _setModelData as setModelData, Bold, Bookmark, ButtonView,+ ClassicEditor, CodeBlock, ContextualBalloon, Essentials, keyCodes, type KeystrokeHandler,+ Link, LinkEditing, LinkUI, Paragraph} from "ckeditor5";import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../test/editor-kit.js";import InternalLinkPlugin, {- COMMAND_NAME, getLinkAtSelection, type LinkDialogRequest, replaceLinkAtSelection+ COMMAND_NAME, getAnchorNames, getLinkAtSelection, type LinkDialogRequest,+ replaceLinkAtSelection} from "./internallink.js";import LinkEmbedEditing from "./link_embed/link_embed_editing.js";@@ -118,6 +119,26 @@ describe("InternalLinkPlugin", () => {});});+describe("the anchors of the document", () => {+ it("lists each name once, sorted, as anchors come and go", async () => {+ const editor = await createTestEditor(+ [ Essentials, Paragraph, Bookmark, InternalLinkPlugin ]+ );+ const zeta = "<bookmark bookmarkId=\"zeta\"></bookmark>";+ setModelData(editor.model, `<paragraph>a${zeta}<bookmark bookmarkId="Alpha"></bookmark>`+ + `[]b${zeta}</paragraph>`);+ expect(getAnchorNames(editor)).toStrictEqual([ "Alpha", "zeta" ]);++ setModelData(editor.model, `<paragraph>a${zeta}[]</paragraph>`);+ expect(getAnchorNames(editor)).toStrictEqual([ "zeta" ]);+ });++ it("lists none in an editor without anchors", async () => {+ const editor = await createTestEditor([ Essentials, Paragraph, InternalLinkPlugin ]);+ expect(getAnchorNames(editor)).toStrictEqual([]);+ });+});+describe("the link at the selection", () => {let editor: ClassicEditor;let getTitle: ReturnType<typeof vi.fn>;diff --git a/packages/ckeditor5/src/plugins/internallink.ts b/packages/ckeditor5/src/plugins/internallink.tsindex 9bfa94abfe..6d907061d2 100644--- a/packages/ckeditor5/src/plugins/internallink.ts+++ b/packages/ckeditor5/src/plugins/internallink.ts@@ -1,6 +1,6 @@import {- ButtonView, Command, ContextualBalloon, findAttributeRange, IconLink, IconPencil, LinkUI,- ModelLiveRange, Plugin+ BookmarkEditing, ButtonView, Command, ContextualBalloon, findAttributeRange, IconLink,+ IconPencil, LinkUI, ModelLiveRange, Plugin} from 'ckeditor5';import type { Editor, LinkCommand, ModelRange, View } from 'ckeditor5';import HostedBalloon from '../hosted_balloon.js';@@ -262,6 +262,16 @@ export async function replaceLinkAtSelection(editor: Editor, href: string, text:});}+/** The names of the anchors in the document, sorted as the anchor list of `LinkUI` sorts them. */+export function getAnchorNames(editor: Editor): string[] {+ if (!editor.plugins.has(BookmarkEditing)) {+ return [];+ }++ const names = editor.plugins.get(BookmarkEditing).getAllBookmarkNames();+ return [ ...names ].sort((a, b) => a.localeCompare(b));+}+function findLinkAtSelection(editor: Editor): { href: string; range: ModelRange } | null {const model = editor.model;const preview = getSelectedLinkWidget(editor);