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
refactor(ckeditor): replace premium Template with a GPL live-reloading snippets plugin
Elian Doran0c050f17c970
diff --git a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsxindex ad2faee5d1..915ad16d24 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx@@ -1,4 +1,4 @@-import { CKTextEditor, ClassicEditor, EditorWatchdog, PopupEditor, TemplateDefinition, type WatchdogConfig } from "@triliumnext/ckeditor5";+import { CKTextEditor, ClassicEditor, EditorWatchdog, PopupEditor, SnippetDefinition, type WatchdogConfig } from "@triliumnext/ckeditor5";import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";import { HTMLProps, RefObject, useEffect, useImperativeHandle, useRef, useState } from "preact/compat";@@ -32,13 +32,18 @@ interface CKEditorWithWatchdogProps extends Pick<HTMLProps<HTMLDivElement>, "cla/** Called upon whenever a new CKEditor instance is initialized, whether it's the first initialization, after a crash or after a config change that requires it (e.g. content language). */onEditorInitialized?: (editor: CKTextEditor) => void;editorApi: RefObject<CKEditorApi>;- templates: TemplateDefinition[];+ templates: SnippetDefinition[];containerRef?: RefObject<HTMLDivElement>;}export default function CKEditorWithWatchdog({ containerRef: externalContainerRef, contentLanguage, className, tabIndex, isClassicEditor, watchdogRef: externalWatchdogRef, watchdogConfig, onNotificationWarning, onWatchdogStateChange, onChange, onEditorInitialized, editorApi, templates }: CKEditorWithWatchdogProps) {const containerRef = useSyncedRef<HTMLDivElement>(externalContainerRef, null);const watchdogRef = useRef<EditorWatchdog>(null);+ // Keep the latest snippet definitions reachable from the (rarely re-running) build effect without+ // listing `templates` as one of its dependencies. Snippet changes are pushed into the live editor+ // instead of forcing a rebuild — see the "push snippet definitions" effect below.+ const templatesRef = useRef(templates);+ templatesRef.current = templates;const [ uiLanguage ] = useTriliumOption("locale");// Read purely as a rebuild trigger: the value is consumed by buildToolbarConfig() via options.get() at// editor-creation time, so the editor must be recreated when it changes.@@ -202,7 +207,7 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerReisClassicEditor: !!isClassicEditor,uiLanguage: uiLanguage as DISPLAYABLE_LOCALE_IDS,contentLanguage: contentLanguage ?? null,- templates+ templates: templatesRef.current});if (isStale) {@@ -246,7 +251,19 @@ export default function CKEditorWithWatchdog({ containerRef: externalContainerRereturn () => {isStale = true;};- }, [ contentLanguage, templates, uiLanguage, isClassicEditor, multilineToolbar ]);+ // `templates` is intentionally excluded: snippet changes are pushed into the live editor by the+ // effect below, so they must not trigger a full editor rebuild.+ }, [ contentLanguage, uiLanguage, isClassicEditor, multilineToolbar ]);++ // Push snippet ("template") definitions into the live editor instead of rebuilding it. The premium+ // Template plugin read its definitions once at init; TriliumSnippets keeps them in a live+ // collection, so add/remove/rename/re-icon all apply in place.+ useEffect(() => {+ if (!editor || !templates) return;+ if (editor.plugins.has("TriliumSnippets")) {+ editor.plugins.get("TriliumSnippets").updateDefinitions(templates);+ }+ }, [ editor, templates ]);// React to notification warning callback.diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 2e9e914ca1..6c799437f2 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -1,7 +1,7 @@import "./EditableText.css";import "./LinkEmbed.css";-import { CKTextEditor, EditorWatchdog, TemplateDefinition } from "@triliumnext/ckeditor5";+import { CKTextEditor, EditorWatchdog, SnippetDefinition } from "@triliumnext/ckeditor5";import { deferred } from "@triliumnext/commons";import { useCallback, useEffect, useRef, useState } from "preact/hooks";@@ -490,7 +490,7 @@ function placeCursorInNewTopParagraph(editor: CKTextEditor) {}function useTemplates() {- const [ templates, setTemplates ] = useState<TemplateDefinition[]>();+ const [ templates, setTemplates ] = useState<SnippetDefinition[]>();useEffect(() => {getTemplates().then(setTemplates);diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex d32dab89f3..e011556ddb 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -1,4 +1,4 @@-import { buildExtraCommands, type EditorConfig, getCkLocale, loadPremiumPlugins, TemplateDefinition } from "@triliumnext/ckeditor5";+import { buildExtraCommands, type EditorConfig, getCkLocale, loadPremiumPlugins, SnippetDefinition } from "@triliumnext/ckeditor5";import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en.json?url";import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";@@ -21,7 +21,7 @@ export interface BuildEditorOptions {isClassicEditor: boolean;uiLanguage: DISPLAYABLE_LOCALE_IDS;contentLanguage: string | null;- templates: TemplateDefinition[];+ templates: SnippetDefinition[];}export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfig> {@@ -177,7 +177,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfidropdownLimit: Number.MAX_SAFE_INTEGER,extraCommands: buildExtraCommands((key, params) => t(key, params), SAMPLE_DIAGRAMS)},- template: {+ snippets: {definitions: opts.templates},htmlSupport: {diff --git a/apps/client/src/widgets/type_widgets/text/snippets.ts b/apps/client/src/widgets/type_widgets/text/snippets.tsindex cf92a00948..2952487729 100644--- a/apps/client/src/widgets/type_widgets/text/snippets.ts+++ b/apps/client/src/widgets/type_widgets/text/snippets.ts@@ -2,7 +2,7 @@ import debounce from "../../../services/debounce.js";import froca from "../../../services/froca.js";import type LoadResults from "../../../services/load_results.js";import search from "../../../services/search.js";-import type { TemplateDefinition } from "@triliumnext/ckeditor5";+import type { SnippetDefinition } from "@triliumnext/ckeditor5";import type FNote from "../../../entities/fnote.js";import { escapeHtml } from "../../../services/utils.js";@@ -29,7 +29,7 @@ export default async function getTemplates() {// corrupts the parse and matches every note.const snippets = (await search.searchForNotes("#textSnippet OR #snippet")).filter((snippet) => snippet.type === "text" && !snippet.isArchived && snippet.isContentAvailable());- const definitions: TemplateDefinition[] = [];+ const definitions: SnippetDefinition[] = [];for (const snippet of snippets) {const { description } = await invalidateCacheFor(snippet);@@ -69,7 +69,7 @@ function buildIcon(snippet: FNote) {</svg>`}-async function handleContentUpdate(affectedNoteIds: string[], setTemplates: (value: TemplateDefinition[]) => void) {+async function handleContentUpdate(affectedNoteIds: string[], setTemplates: (value: SnippetDefinition[]) => void) {const updatedNoteIds = new Set(affectedNoteIds);const templateNoteIds = new Set(templateCache.keys());const affectedTemplateNoteIds = templateNoteIds.intersection(updatedNoteIds);@@ -103,7 +103,7 @@ async function handleContentUpdate(affectedNoteIds: string[], setTemplates: (val}}-export async function updateTemplateCache(loadResults: LoadResults, setTemplates: (value: TemplateDefinition[]) => void) {+export async function updateTemplateCache(loadResults: LoadResults, setTemplates: (value: SnippetDefinition[]) => void) {const affectedNoteIds = loadResults.getNoteIds();// React to creation or deletion of text snippets.diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 3d6a1bc301..88514b6226 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -11,7 +11,8 @@ export { CHAT_INPUT_PLUGINS, loadPremiumPlugins } from "./plugins.js";export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, WatchdogConfig, WatchdogState } from "ckeditor5";export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/mention/slash_commands.js";export type { TriliumMentionFeed } from "./plugins/mention/types.js";-export type { TemplateDefinition } from "ckeditor5-premium-features";+export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";+export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";export { default as buildExtraCommands } from "./extra_slash_commands.js";export { default as getCkLocale } from "./i18n.js";export * from "./utils.js";diff --git a/packages/ckeditor5/src/plugins.spec.ts b/packages/ckeditor5/src/plugins.spec.tsindex 0b95befa76..c7fc3cef8a 100644--- a/packages/ckeditor5/src/plugins.spec.ts+++ b/packages/ckeditor5/src/plugins.spec.ts@@ -95,14 +95,17 @@ describe("loadPremiumPlugins", () => {}});- it("includes Template and FormatPainter, but not SlashCommand", async () => {+ it("includes FormatPainter, but not SlashCommand or Template", async () => {const { SlashCommand, Template, FormatPainter } = await import("ckeditor5-premium-features");const plugins = await loadPremiumPlugins();- expect(plugins).toContain(Template);expect(plugins).toContain(FormatPainter);// `SlashCommand` requires the `Mention` façade, which would load upstream's `MentionUI`// alongside `TriliumMentionUI`; `TriliumSlashCommands` provides `/` instead.expect(plugins).not.toContain(SlashCommand);++ // `Template` is replaced by the GPL `TriliumSnippets` plugin, which additionally supports+ // live reloading of the snippet list without rebuilding the editor.+ expect(plugins).not.toContain(Template);});});diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.tsindex 135a073d95..2ae2f56fa1 100644--- a/packages/ckeditor5/src/plugins.ts+++ b/packages/ckeditor5/src/plugins.ts@@ -29,6 +29,7 @@ import { Math, AutoformatMath } from "@triliumnext/ckeditor5-math";import CopyAnchorLinkButton from "./plugins/copy_anchor_link.js";import CopyLinkUrlButton from "./plugins/copy_link_url.js";import ImageActions from "./plugins/image_actions.js";+import TriliumSnippets from "./plugins/snippets/snippets.js";// import "@triliumnext/ckeditor5-mermaid/index.css";// import "@triliumnext/ckeditor5-admonition/index.css";@@ -88,6 +89,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [CopyAnchorLinkButton,CopyLinkUrlButton,ImageActions,+ TriliumSnippets,];/**@@ -144,10 +146,14 @@ export async function loadPremiumPlugins(): Promise<(typeof Plugin)[]> {// `SlashCommand` is deliberately not among them: it `requires` the `Mention` façade, which loads// upstream's `MentionUI` next to `TriliumMentionUI` and leaves the two fighting over the same// balloon. `TriliumSlashCommands` provides `/` instead, for premium and GPL builds alike.- const { Template, FormatPainter } = await import('ckeditor5-premium-features');+ //+ // `Template` is likewise absent: the GPL `TriliumSnippets` plugin replaces it (see+ // `plugins/snippets/`), and additionally supports live reloading of the snippet list — the+ // premium plugin baked its definitions in at startup, forcing an editor rebuild on any change.+ const { FormatPainter } = await import('ckeditor5-premium-features');// Also load the CSS when premium features are usedawait import('ckeditor5-premium-features/ckeditor5-premium-features.css');- return [Template, FormatPainter];+ return [FormatPainter];}/**diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.tsindex d948b5010b..892ac26a6d 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts@@ -108,6 +108,15 @@ export default class TriliumSlashCommands extends Plugin {}}+// `EditorConfig.slashCommand` used to be typed by premium's `@ckeditor/ckeditor5-slash-command`+// augmentation, which reached the type graph via a premium type import. Now that Trilium owns the+// `/` palette (and no longer statically imports premium types), declare the config shape here.+declare module "ckeditor5" {+ interface EditorConfig {+ slashCommand?: SlashCommandConfig;+ }+}+/*** Whether an entry should be offered for the caret's current position.*diff --git a/packages/ckeditor5/src/plugins/snippets/snippetlistitembuttonview.ts b/packages/ckeditor5/src/plugins/snippets/snippetlistitembuttonview.tsnew file mode 100644index 0000000000..a2df6f2b88--- /dev/null+++ b/packages/ckeditor5/src/plugins/snippets/snippetlistitembuttonview.ts@@ -0,0 +1,120 @@+import { ButtonView, HighlightedTextView, type Locale, View } from "ckeditor5";++import type { SnippetDefinition } from "./snippetsconfig.js";++/**+ * A single row in the snippet dropdown list: a wide button showing the snippet's icon, its title and+ * (optionally) its description. Both the title and description can be highlighted to reflect the+ * current search query.+ *+ * Mirrors the row rendered by the premium `Template` plugin this replaces, so the visual layout and+ * search behaviour stay familiar.+ */+export default class SnippetListItemButtonView extends ButtonView {++ public readonly definition: SnippetDefinition;++ private textPartView: SnippetTextPartView | null = null;++ constructor(locale: Locale, definition: SnippetDefinition) {+ super(locale);++ this.definition = definition;++ this.set({+ withText: true,+ class: "ck-snippet-button",+ role: "option",+ icon: definition.icon+ });++ // Snippet icons carry the note's own colours (see `buildIcon` in the client), so don't let+ // the button's theme recolour them.+ this.iconView.isColorInherited = false;+ }++ public override render(): void {+ super.render();++ this.textPartView = new SnippetTextPartView(this.locale, this.definition, this.labelView.element?.id);++ // Swap the plain label for the richer title + description block.+ this.children.remove(this.labelView);+ this.children.add(this.textPartView);+ }++ /**+ * Returns whether the snippet matches the given search expression (by title or description),+ * or `null` when it does not match at all.+ */+ public isMatching(regExp: RegExp): { title: boolean; description: boolean } | null {+ const { title, description } = this.definition;+ const titleMatches = !!title.match(regExp);+ const descriptionMatches = !!description?.match(regExp);++ return titleMatches || descriptionMatches+ ? { title: titleMatches, description: descriptionMatches }+ : null;+ }++ public highlightText(regExp: RegExp | null): void {+ this.textPartView?.highlightText(regExp);+ }++ public override destroy(): void {+ super.destroy();+ this.labelView.destroy();+ }+}++/**+ * The title + optional description block placed inside a {@link SnippetListItemButtonView}.+ */+class SnippetTextPartView extends View {++ private readonly titleView: HighlightedTextView;+ private readonly descriptionView: HighlightedTextView | null;++ constructor(locale: Locale | undefined, definition: SnippetDefinition, labelId?: string) {+ super(locale);++ this.titleView = new HighlightedTextView();+ this.titleView.text = definition.title;+ this.titleView.extendTemplate({+ tag: "span",+ attributes: {+ class: ["ck-button__label"],+ id: labelId+ }+ });++ const children: View[] = [this.titleView];++ if (definition.description) {+ this.descriptionView = new HighlightedTextView();+ this.descriptionView.text = definition.description;+ this.descriptionView.extendTemplate({+ tag: "p",+ attributes: {+ class: ["ck-snippet__description"]+ }+ });+ children.push(this.descriptionView);+ } else {+ this.descriptionView = null;+ }++ this.setTemplate({+ tag: "div",+ attributes: {+ class: ["ck", "ck-snippet__text-part"]+ },+ children+ });+ }++ public highlightText(regExp: RegExp | null): void {+ this.titleView.highlightText(regExp);+ this.descriptionView?.highlightText(regExp);+ }+}diff --git a/packages/ckeditor5/src/plugins/snippets/snippetlistview.ts b/packages/ckeditor5/src/plugins/snippets/snippetlistview.tsnew file mode 100644index 0000000000..0db9fbef8c--- /dev/null+++ b/packages/ckeditor5/src/plugins/snippets/snippetlistview.ts@@ -0,0 +1,80 @@+import { type Collection, type FilteredView, ListItemView, ListView, type Locale } from "ckeditor5";++import type { SnippetDefinition } from "./snippetsconfig.js";+import SnippetListItemButtonView from "./snippetlistitembuttonview.js";++/**+ * The scrollable list of snippets shown inside the `insertTemplate` search dropdown.+ *+ * Its rows are **bound** to a live {@link Collection} of definitions: adding, removing or editing a+ * snippet note updates the collection, and the list re-renders in place — no editor rebuild. It+ * implements {@link FilteredView} so the surrounding {@link module:ui/search/text/searchtextview~SearchTextView}+ * can filter it by the user's query.+ */+export default class SnippetListView extends ListView implements FilteredView {++ constructor(locale: Locale, definitions: Collection<SnippetDefinition>, insert: (definition: SnippetDefinition) => void) {+ super(locale);++ this.extendTemplate({+ attributes: {+ role: "listbox",+ class: ["ck-snippet-list"]+ }+ });++ this.items.bindTo(definitions).using((definition) => {+ const item = new ListItemView(locale);+ const button = new SnippetListItemButtonView(locale, definition);++ button.on("execute", () => insert(definition));++ item.children.add(button);+ return item;+ });+ }++ public filter(regExp: RegExp | null): { resultsCount: number; totalItemsCount: number } {+ let resultsCount = 0;++ for (const item of this.items) {+ if (!(item instanceof ListItemView)) {+ continue;+ }++ const button = getButton(item);+ if (!button) {+ continue;+ }++ const isVisible = regExp ? !!button.isMatching(regExp) : true;++ item.isVisible = isVisible;+ button.highlightText(isVisible && regExp ? regExp : null);++ if (isVisible) {+ resultsCount++;+ }+ }++ return {+ resultsCount,+ totalItemsCount: this.items.length+ };+ }++ public override focus(): void {+ // Focus the first *visible* row so keyboard users skip rows hidden by the current filter.+ for (const item of this.items) {+ if (item instanceof ListItemView && item.isVisible) {+ getButton(item)?.focus();+ return;+ }+ }+ }+}++function getButton(item: ListItemView): SnippetListItemButtonView | null {+ const first = item.children.first;+ return first instanceof SnippetListItemButtonView ? first : null;+}diff --git a/packages/ckeditor5/src/plugins/snippets/snippets.ts b/packages/ckeditor5/src/plugins/snippets/snippets.tsnew file mode 100644index 0000000000..71990e97e9--- /dev/null+++ b/packages/ckeditor5/src/plugins/snippets/snippets.ts@@ -0,0 +1,47 @@+import { type Command, Plugin } from "ckeditor5";++import type { SnippetDefinition, SnippetsConfig } from "./snippetsconfig.js";+import SnippetsEditing from "./snippetsediting.js";+import SnippetsUI from "./snippetsui.js";++/**+ * Trilium's GPL replacement for the premium `Template` feature: a searchable dropdown of text+ * snippets (notes labelled `#snippet` / `#textSnippet`).+ *+ * The key difference from the premium plugin is **live reloading** — {@link updateDefinitions} pushes a+ * new snippet list into an already-open editor, so creating, deleting, renaming or re-icon-ing a+ * snippet note no longer forces the whole editor to be torn down and rebuilt.+ */+export default class TriliumSnippets extends Plugin {++ static get requires() {+ return [SnippetsEditing, SnippetsUI] as const;+ }++ static get pluginName() {+ return "TriliumSnippets" as const;+ }++ /**+ * Updates the snippet list on the live editor. The bound dropdown/menu re-render in place.+ */+ public updateDefinitions(definitions: ReadonlyArray<SnippetDefinition>): void {+ this.editor.plugins.get(SnippetsEditing).setDefinitions(definitions);+ }+}++declare module "ckeditor5" {+ interface EditorConfig {+ snippets?: SnippetsConfig;+ }++ interface PluginsMap {+ [TriliumSnippets.pluginName]: TriliumSnippets;+ [SnippetsEditing.pluginName]: SnippetsEditing;+ [SnippetsUI.pluginName]: SnippetsUI;+ }++ interface CommandsMap {+ insertTemplate: Command;+ }+}diff --git a/packages/ckeditor5/src/plugins/snippets/snippetsconfig.ts b/packages/ckeditor5/src/plugins/snippets/snippetsconfig.tsnew file mode 100644index 0000000000..cdf422b80d--- /dev/null+++ b/packages/ckeditor5/src/plugins/snippets/snippetsconfig.ts@@ -0,0 +1,29 @@+/**+ * The shape of a single text-snippet ("template") entry shown in the `insertTemplate` dropdown.+ *+ * Intentionally structurally compatible with the premium `TemplateDefinition` this plugin replaces,+ * so the client-side builder in `snippets.ts` does not have to change: `data` may be a plain HTML+ * string or a getter, which lets the content stay live (the getter reads a mutable cache) without+ * recreating the editor.+ */+export interface SnippetDefinition {+ /** The title of the snippet, shown as the primary label and used for search matching. */+ title: string;++ /**+ * The HTML inserted at the caret, or a callback returning it. A callback is evaluated on every+ * insertion, so snippet content can change at runtime without rebuilding the definition list.+ */+ data: (() => string) | string;++ /** Optional SVG string used as the entry icon. A generic icon is used when omitted. */+ icon?: string;++ /** Optional longer description shown under the title and also matched during search. */+ description?: string;+}++export interface SnippetsConfig {+ /** The list of snippet definitions displayed in the `insertTemplate` dropdown. */+ definitions?: Array<SnippetDefinition>;+}diff --git a/packages/ckeditor5/src/plugins/snippets/snippetsediting.ts b/packages/ckeditor5/src/plugins/snippets/snippetsediting.tsnew file mode 100644index 0000000000..32f5f35672--- /dev/null+++ b/packages/ckeditor5/src/plugins/snippets/snippetsediting.ts@@ -0,0 +1,66 @@+import { Collection, Command, Plugin } from "ckeditor5";++import type { SnippetDefinition } from "./snippetsconfig.js";++/**+ * The headless half of the snippets feature: it owns the command that inserts a snippet's HTML at the+ * caret, and a live {@link Collection} of snippet definitions that the UI renders from.+ *+ * The collection is the key to dynamic reloading. The premium `Template` plugin this replaces read+ * its definitions once at startup, so any change to a snippet note forced the whole editor to be+ * rebuilt. Here the client instead calls {@link setDefinitions} whenever snippet notes change, and the+ * bound UI updates in place.+ */+export default class SnippetsEditing extends Plugin {++ /**+ * The live list of snippet definitions. The UI binds its list rows to this collection, so+ * mutating it (via {@link setDefinitions}) reflects in the open editor without recreating it.+ */+ public readonly definitions = new Collection<SnippetDefinition>();++ static get pluginName() {+ return "SnippetsEditing" as const;+ }++ public init(): void {+ const editor = this.editor;++ editor.commands.add("insertTemplate", new InsertSnippetCommand(editor));++ const initial = editor.config.get("snippets.definitions") ?? [];+ this.setDefinitions(initial);+ }++ /**+ * Replaces the current snippet definitions. Safe to call on a live editor: the bound UI list+ * re-renders in place, so titles, icons, descriptions and additions/removals apply immediately.+ */+ public setDefinitions(definitions: ReadonlyArray<SnippetDefinition>): void {+ this.definitions.clear();+ this.definitions.addMany([...definitions]);+ }+}++/**+ * Inserts a snippet's HTML at the current selection. The payload is either an HTML string or a+ * callback returning one — the callback form lets snippet content stay live without rebuilding the+ * definition.+ */+class InsertSnippetCommand extends Command {++ public override execute(data: string | (() => string)): void {+ const editor = this.editor;+ const html = typeof data === "function" ? data() : data;++ if (typeof html !== "string") {+ return;+ }++ editor.model.change(() => {+ const viewFragment = editor.data.processor.toView(html);+ const modelFragment = editor.data.toModel(viewFragment);+ editor.model.insertContent(modelFragment);+ });+ }+}diff --git a/packages/ckeditor5/src/plugins/snippets/snippetsui.ts b/packages/ckeditor5/src/plugins/snippets/snippetsui.tsnew file mode 100644index 0000000000..fe56e72866--- /dev/null+++ b/packages/ckeditor5/src/plugins/snippets/snippetsui.ts@@ -0,0 +1,143 @@+import { createDropdown, type Locale, MenuBarMenuListItemButtonView, MenuBarMenuListItemView, MenuBarMenuListView, MenuBarMenuView, Plugin, SearchTextView } from "ckeditor5";++import SnippetsEditing from "./snippetsediting.js";+import SnippetListView from "./snippetlistview.js";+import templateIcon from "./theme/icons/template.svg?raw";+import "./theme/snippets.css";++/**+ * Registers the snippet UI: the `insertTemplate` toolbar dropdown (a searchable list) and the+ * `menuBar:insertTemplate` menu entry. Both render from {@link SnippetsEditing}'s live definition+ * collection, so snippet changes appear without recreating the editor.+ *+ * The user-facing strings deliberately reuse the same English source keys as the premium plugin this+ * replaces (`"Insert template"`, `"Search template"`, …) so the existing `translation_overrides.ts`+ * relabelling ("Insert text snippet" / "Search text snippet") keeps applying.+ */+export default class SnippetsUI extends Plugin {++ static get requires() {+ return [SnippetsEditing] as const;+ }++ static get pluginName() {+ return "SnippetsUI" as const;+ }++ public init(): void {+ const editor = this.editor;+ const t = editor.t;+ const editing = editor.plugins.get(SnippetsEditing);++ const insert = (data: string | (() => string)) => {+ editor.execute("insertTemplate", data);+ editor.editing.view.focus();+ };++ editor.ui.componentFactory.add("insertTemplate", (locale) => {+ const command = editor.commands.get("insertTemplate");+ const dropdownView = createDropdown(locale);++ const listView = new SnippetListView(locale, editing.definitions, (definition) => insert(definition.data));++ const searchView = new SearchTextView(locale, {+ filteredView: listView,+ queryView: {+ label: t("Search template")+ },+ class: "ck-snippet-form",+ infoView: {+ text: {+ notFound: {+ primary: (query) => t("No templates were found matching \"%0\".", query as string),+ secondary: t("Please try a different phrase or check the spelling.")+ },+ noSearchableItems: {+ primary: t("No templates available.")+ }+ }+ }+ });++ searchView.on("search", (evt, data: { query: string; resultsCount: number }) => {+ if (data.query?.length) {+ editor.ui.ariaLiveAnnouncer.announce(t("%0 templates found", data.resultsCount));+ }+ });++ if (command) {+ dropdownView.bind("isEnabled").to(command);+ }+ dropdownView.panelView.children.add(searchView);+ dropdownView.buttonView.set({+ label: t("Insert template"),+ icon: templateIcon,+ tooltip: true+ });++ // Clear the query (and thus the filter/highlight) each time the dropdown is closed.+ dropdownView.on("change:isOpen", (evt, name, isOpen) => {+ if (!isOpen) {+ searchView.reset();+ }+ });++ return dropdownView;+ });++ editor.ui.componentFactory.add("menuBar:insertTemplate", (locale) => {+ const command = editor.commands.get("insertTemplate");+ const menuView = new MenuBarMenuView(locale);+ menuView.buttonView.set({+ label: t("Template"),+ icon: templateIcon+ });++ const listView = new MenuBarMenuListView(locale);+ this._populateMenuList(locale, listView, menuView, insert);++ // Rebuild the menu whenever the snippet set changes (kept in sync with the toolbar list).+ this.listenTo(editing.definitions, "change", () => {+ this._populateMenuList(locale, listView, menuView, insert);+ });++ menuView.panelView.children.add(listView);+ if (command) {+ menuView.bind("isEnabled").to(command, "isEnabled");+ }++ return menuView;+ });+ }++ private _populateMenuList(locale: Locale, listView: MenuBarMenuListView, menuView: MenuBarMenuView, insert: (data: string | (() => string)) => void): void {+ const editor = this.editor;+ const t = editor.t;+ const definitions = editor.plugins.get(SnippetsEditing).definitions;++ listView.items.clear();++ if (!definitions.length) {+ const emptyItem = new MenuBarMenuListItemView(locale, menuView);+ const emptyButton = new MenuBarMenuListItemButtonView(locale);+ emptyButton.set({ label: t("No templates available."), isEnabled: false });+ emptyItem.children.add(emptyButton);+ listView.items.add(emptyItem);+ return;+ }++ for (const definition of definitions) {+ const item = new MenuBarMenuListItemView(locale, menuView);+ const button = new MenuBarMenuListItemButtonView(locale);+ button.set({+ class: "ck-snippet-button",+ label: definition.title,+ icon: definition.icon+ });+ button.delegate("execute").to(menuView);+ button.on("execute", () => insert(definition.data));+ item.children.add(button);+ listView.items.add(item);+ }+ }+}diff --git a/packages/ckeditor5/src/plugins/snippets/theme/icons/template.svg b/packages/ckeditor5/src/plugins/snippets/theme/icons/template.svgnew file mode 100644index 0000000000..c7df15ff6c--- /dev/null+++ b/packages/ckeditor5/src/plugins/snippets/theme/icons/template.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M8 0H3a2 2 0 0 0-2 2v15a2 2 0 0 0 2 2h5a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2M2.5 2a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v15a.5.5 0 0 1-.5.5H3a.5.5 0 0 1-.5-.5zM13 0h5a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-5a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2m0 1.5a.5.5 0 0 0-.5.5v5a.5.5 0 0 0 .5.5h5a.5.5 0 0 0 .5-.5V2a.5.5 0 0 0-.5-.5zm0 8.5h5a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-5a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2m0 1.5a.5.5 0 0 0-.5.5v5a.5.5 0 0 0 .5.5h5a.5.5 0 0 0 .5-.5v-5a.5.5 0 0 0-.5-.5z" clip-rule="evenodd"/></svg>diff --git a/packages/ckeditor5/src/plugins/snippets/theme/snippets.css b/packages/ckeditor5/src/plugins/snippets/theme/snippets.cssnew file mode 100644index 0000000000..d1ce69a488--- /dev/null+++ b/packages/ckeditor5/src/plugins/snippets/theme/snippets.css@@ -0,0 +1,111 @@+:root {+ --ck-snippet-dropdown-width: 345px;+ --ck-snippet-dropdown-height: 300px;+ --ck-snippet-icon-size: 45px;+}++/* Keep the note's own icon colours instead of the button's theme colour. */+.ck-button.ck-snippet-button .ck.ck-icon,+.ck-button.ck-snippet-button .ck.ck-icon * {+ color: unset;+}++.ck-button.ck-snippet-button .ck.ck-icon *:not([fill]) {+ fill: unset;+}++.ck.ck-snippet-form {+ width: var(--ck-snippet-dropdown-width);++ & > .ck-labeled-field-view {+ padding: var(--ck-spacing-large);+ }++ & > .ck-search__results {+ border-top: 1px solid var(--ck-color-base-border);+ }++ & > .ck-search__results > .ck.ck-list.ck-snippet-list {+ max-height: var(--ck-snippet-dropdown-height);+ padding: var(--ck-spacing-large);+ overflow: hidden auto;+ overscroll-behavior: contain;+ border-radius: 0;++ & > .ck.ck-list__item:not(.ck-hidden) ~ .ck.ck-list__item {+ margin-top: var(--ck-spacing-large);+ }++ & > .ck.ck-list__item > .ck.ck-button {+ display: grid;+ grid-template-columns: var(--ck-snippet-icon-size) 1fr;+ grid-template-rows: var(--ck-snippet-icon-size);+ grid-template-areas: "ck-snippet-icon ck-snippet-content";+ gap: var(--ck-spacing-large);+ align-items: center;+ width: 100%;+ margin: 0;+ padding: 0;+ overflow: hidden;+ border-radius: var(--ck-border-radius);++ &:not(:focus) {+ border-color: var(--ck-color-dropdown-panel-background);+ }++ & > .ck.ck-icon {+ grid-area: ck-snippet-icon;+ width: var(--ck-snippet-icon-size);+ height: auto;+ margin: 0;+ }++ & > .ck-snippet__text-part {+ grid-area: ck-snippet-content;+ display: flex;+ flex-direction: column;+ justify-content: space-evenly;+ min-width: 0;+ height: 100%;+ margin: 0;++ & > .ck.ck-button__label {+ display: block;+ overflow: hidden;+ font-weight: bold;+ font-size: var(--ck-font-size-base);+ line-height: 1.1;+ color: var(--ck-color-text);+ white-space: nowrap;+ text-overflow: ellipsis;+ }++ & .ck-snippet__description {+ display: -webkit-box;+ overflow: hidden;+ margin-top: var(--ck-spacing-tiny);+ font-size: 0.85em;+ line-height: 1.1;+ color: var(--ck-color-text);+ white-space: normal;+ text-overflow: ellipsis;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ }++ & mark {+ background: var(--ck-color-highlight-background);+ font: inherit;+ line-height: inherit;+ vertical-align: initial;+ }+ }+ }+ }+}++@media screen and (width <= 600px) {+ .ck.ck-snippet-form {+ --ck-snippet-dropdown-width: 260px;+ }+}diff --git a/packages/ckeditor5/src/translation_overrides.spec.ts b/packages/ckeditor5/src/translation_overrides.spec.tsindex cc547f0154..da8f1e8e2d 100644--- a/packages/ckeditor5/src/translation_overrides.spec.ts+++ b/packages/ckeditor5/src/translation_overrides.spec.ts@@ -21,9 +21,10 @@ describe("translation overrides", () => {expect(labels).not.toContain("Bookmark");});- it("register the text-snippet relabels for the premium template feature", () => {- // The Template feature is premium and not loaded here, so its relabel can't be exercised- // through the UI — assert the override dictionary carries it instead.+ it("register the text-snippet relabels for the snippets feature", () => {+ // The GPL `TriliumSnippets` plugin reuses the same English source strings the premium+ // Template feature used ("Insert template" / "Search template"), so these overrides relabel+ // its dropdown to "…text snippet". Assert the override dictionary carries them.const dictionary = window.CKEDITOR_TRANSLATIONS?.en?.dictionary ?? {};expect(dictionary["Insert template"]).toBe("Insert text snippet");expect(dictionary["Search template"]).toBe("Search text snippet");