Skip to content

Build your personal knowledge base with Trilium Notes

Merge remote-tracking branch 'origin/main' into react/type_widgets

Elian Doran5e83e6fa3486
diff --cc apps/client/src/components/app_context.ts
index 322e727040,7bc544e7eb..ecdd589be5
--- a/apps/client/src/components/app_context.ts
+++ b/apps/client/src/components/app_context.ts
@@@ -30,10 -33,6 +30,10 @@@ import { ColumnComponent } from "tabula
import { ChooseNoteTypeCallback } from "../widgets/dialogs/note_type_chooser.jsx";
import type RootContainer from "../widgets/containers/root_container.js";
import { SqlExecuteResults } from "@triliumnext/commons";
+import { AddLinkOpts } from "../widgets/dialogs/add_link.jsx";
+import { IncludeNoteOpts } from "../widgets/dialogs/include_note.jsx";
+import { ReactWrappedWidget } from "../widgets/basic_widget.js";
- import { TypeWidget } from "../widgets/note_types.jsx";
++import type { MarkdownImportOpts } from "../widgets/dialogs/markdown_import.jsx";
interface Layout {
getRootWidget: (appContext: AppContext) => RootContainer;
@@@ -222,9 -221,9 +222,9 @@@ export type CommandMappings =
showPasswordNotSet: CommandData;
showProtectedSessionPasswordDialog: CommandData;
showUploadAttachmentsDialog: CommandData & { noteId: string };
- showIncludeNoteDialog: CommandData & { textTypeWidget: EditableTextTypeWidget };
- showAddLinkDialog: CommandData & { textTypeWidget: EditableTextTypeWidget, text: string };
- showPasteMarkdownDialog: CommandData & { textTypeWidget: EditableTextTypeWidget };
+ showIncludeNoteDialog: CommandData & IncludeNoteOpts;
+ showAddLinkDialog: CommandData & AddLinkOpts;
++ showPasteMarkdownDialog: CommandData & MarkdownImportOpts;
closeProtectedSessionPasswordDialog: CommandData;
copyImageReferenceToClipboard: CommandData;
copyImageToClipboard: CommandData;
diff --cc apps/client/src/translations/de/translation.json
index e34982c6a9,6ff9525ff2..4f7e9801f0
--- a/apps/client/src/translations/de/translation.json
+++ b/apps/client/src/translations/de/translation.json
@@@ -989,9 -989,9 +989,9 @@@
},
"protected_session": {
"enter_password_instruction": "Um die geschützte Notiz anzuzeigen, musst du dein Passwort eingeben:",
- "start_session_button": "Starte eine geschützte Sitzung <kbd>Eingabetaste</kbd>",
+ "start_session_button": "Starte eine geschützte Sitzung",
"started": "Geschützte Sitzung gestartet.",
- "wrong_password": "Passwort flasch.",
+ "wrong_password": "Passwort falsch.",
"protecting-finished-successfully": "Geschützt erfolgreich beendet.",
"unprotecting-finished-successfully": "Ungeschützt erfolgreich beendet.",
"protecting-in-progress": "Schützen läuft: {{count}}",
diff --cc apps/client/src/widgets/dialogs/markdown_import.tsx
index d14d6fb117,43b20d3785..8de49e3302
--- a/apps/client/src/widgets/dialogs/markdown_import.tsx
+++ b/apps/client/src/widgets/dialogs/markdown_import.tsx
@@@ -1,5 -1,5 +1,4 @@@
--import { useCallback, useRef, useState } from "preact/hooks";
--import appContext from "../../components/app_context";
++import { useRef, useState } from "preact/hooks";
import { t } from "../../services/i18n";
import server from "../../services/server";
import toast from "../../services/toast";
@@@ -7,6 -7,7 +6,12 @@@ import utils from "../../services/utils
import Modal from "../react/Modal";
import Button from "../react/Button";
import { useTriliumEvent } from "../react/hooks";
+ import EditableTextTypeWidget from "../type_widgets/editable_text";
++import { CKEditorApi } from "../type_widgets/text/CKEditorWithWatchdog";
++
++export interface MarkdownImportOpts {
++ editorApi: CKEditorApi;
++}
interface RenderMarkdownResponse {
htmlContent: string;
@@@ -14,39 -15,34 +19,36 @@@
export default function MarkdownImportDialog() {
const markdownImportTextArea = useRef<HTMLTextAreaElement>(null);
- const [textTypeWidget, setTextTypeWidget] = useState<EditableTextTypeWidget>();
++ const editorApiRef = useRef<CKEditorApi>(null);
++ const [ textTypeWidget, setTextTypeWidget ] = useState<EditableTextTypeWidget>();
const [ text, setText ] = useState("");
const [ shown, setShown ] = useState(false);
- const triggerImport = useCallback(() => {
- if (appContext.tabManager.getActiveContextNoteType() !== "text") {
- return;
- }
-
- useTriliumEvent("showPasteMarkdownDialog", ({ textTypeWidget }) => {
++ useTriliumEvent("showPasteMarkdownDialog", ({ editorApi }) => {
+ setTextTypeWidget(textTypeWidget);
if (utils.isElectron()) {
const { clipboard } = utils.dynamicRequire("electron");
const text = clipboard.readText();
--
- convertMarkdownToHtml(text);
- convertMarkdownToHtml(text, textTypeWidget);
++
++ convertMarkdownToHtml(text, editorApi);
} else {
++ editorApiRef.current = editorApi;
setShown(true);
}
- }, []);
-
- useTriliumEvent("importMarkdownInline", triggerImport);
- useTriliumEvent("pasteMarkdownIntoText", triggerImport);
-
- async function sendForm() {
- await convertMarkdownToHtml(text);
- setText("");
- setShown(false);
- }
+ });
return (
<Modal
className="markdown-import-dialog" title={t("markdown_import.dialog_title")} size="lg"
- footer={<Button className="markdown-import-button" text={t("markdown_import.import_button")} onClick={sendForm} keyboardShortcut="Ctrl+Space" />}
+ footer={<Button className="markdown-import-button" text={t("markdown_import.import_button")} onClick={() => setShown(false)} keyboardShortcut="Ctrl+Enter" />}
onShown={() => markdownImportTextArea.current?.focus()}
- onHidden={() => setShown(false) }
+ onHidden={async () => {
- if (textTypeWidget) {
- await convertMarkdownToHtml(text, textTypeWidget);
++ if (editorApiRef.current) {
++ await convertMarkdownToHtml(text, editorApiRef.current);
+ }
+ setShown(false);
+ setText("");
+ }}
show={shown}
>
<p>{t("markdown_import.modal_body_text")}</p>
@@@ -63,19 -59,10 +65,8 @@@
)
}
- async function convertMarkdownToHtml(markdownContent: string) {
-async function convertMarkdownToHtml(markdownContent: string, textTypeWidget: EditableTextTypeWidget) {
++async function convertMarkdownToHtml(markdownContent: string, textTypeWidget: CKEditorApi) {
const { htmlContent } = await server.post<RenderMarkdownResponse>("other/render-markdown", { markdownContent });
-
- const textEditor = await appContext.tabManager.getActiveContext()?.getTextEditor();
- if (!textEditor) {
- return;
- }
-
- const viewFragment = textEditor.data.processor.toView(htmlContent);
- const modelFragment = textEditor.data.toModel(viewFragment);
-
- textEditor.model.insertContent(modelFragment, textEditor.model.document.selection);
- textEditor.editing.view.focus();
--
- await textTypeWidget.addHtmlToEditor(htmlContent);
-
++ textTypeWidget.addHtmlToEditor(htmlContent);
toast.showMessage(t("markdown_import.import_success"));
--}
++}
diff --cc apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
index ec37168311,0000000000..a90620711a
mode 100644,000000..100644
--- a/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
+++ b/apps/client/src/widgets/type_widgets/text/CKEditorWithWatchdog.tsx
@@@ -1,205 -1,0 +1,226 @@@
+import { HTMLProps, RefObject, useEffect, useImperativeHandle, useRef, useState } from "preact/compat";
+import { PopupEditor, ClassicEditor, EditorWatchdog, type WatchdogConfig, CKTextEditor, TemplateDefinition } from "@triliumnext/ckeditor5";
+import { buildConfig, BuildEditorOptions } from "./config";
+import { useLegacyImperativeHandlers, useSyncedRef } from "../../react/hooks";
+import link from "../../../services/link";
+import froca from "../../../services/froca";
+
+export type BoxSize = "small" | "medium" | "full";
+
+export interface CKEditorApi {
+ /** returns true if user selected some text, false if there's no selection */
+ hasSelection(): boolean;
+ getSelectedText(): string;
+ addLink(notePath: string, linkTitle: string | null, externalLink?: boolean): void;
+ addLinkToEditor(linkHref: string, linkTitle: string): void;
++ addHtmlToEditor(html: string): void;
+ addIncludeNote(noteId: string, boxSize?: BoxSize): void;
+ addImage(noteId: string): Promise<void>;
+}
+
+interface CKEditorWithWatchdogProps extends Pick<HTMLProps<HTMLDivElement>, "className" | "tabIndex"> {
+ content: string | undefined;
+ contentLanguage: string | null | undefined;
+ isClassicEditor?: boolean;
+ watchdogRef: RefObject<EditorWatchdog>;
+ watchdogConfig?: WatchdogConfig;
+ onNotificationWarning?: (evt: any, data: any) => void;
+ onWatchdogStateChange?: (watchdog: EditorWatchdog<any>) => void;
+ onChange: () => void;
+ /** 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[];
+ containerRef?: RefObject<HTMLDivElement>;
+}
+
+export default function CKEditorWithWatchdog({ containerRef: externalContainerRef, content, 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);
+ const [ editor, setEditor ] = useState<CKTextEditor>();
+
+ useImperativeHandle(editorApi, () => ({
+ hasSelection() {
+ const model = watchdogRef.current?.editor?.model;
+ const selection = model?.document.selection;
+
+ return !selection?.isCollapsed;
+ },
+ getSelectedText() {
+ const range = watchdogRef.current?.editor?.model.document.selection.getFirstRange();
+ let text = "";
+
+ if (!range) {
+ return text;
+ }
+
+ for (const item of range.getItems()) {
+ if ("data" in item && item.data) {
+ text += item.data;
+ }
+ }
+
+ return text;
+ },
+ addLink(notePath, linkTitle, externalLink) {
+ const editor = watchdogRef.current?.editor;
+ if (!editor) return;
+
+ if (linkTitle) {
+ if (this.hasSelection()) {
+ editor.execute("link", externalLink ? `${notePath}` : `#${notePath}`);
+ } else {
+ this.addLinkToEditor(externalLink ? `${notePath}` : `#${notePath}`, linkTitle);
+ }
+ } else {
+ editor.execute("referenceLink", { href: "#" + notePath });
+ }
+
+ editor.editing.view.focus();
+ },
+ addLinkToEditor(linkHref, linkTitle) {
+ watchdogRef.current?.editor?.model.change((writer) => {
+ const insertPosition = watchdogRef.current?.editor?.model.document.selection.getFirstPosition();
+ if (insertPosition) {
+ writer.insertText(linkTitle, { linkHref: linkHref }, insertPosition);
+ }
+ });
+ },
+ addIncludeNote(noteId, boxSize) {
+ const editor = watchdogRef.current?.editor;
+ if (!editor) return;
+
+ editor?.model.change((writer) => {
+ // Insert <includeNote>*</includeNote> at the current selection position
+ // in a way that will result in creating a valid model structure
+ editor?.model.insertContent(
+ writer.createElement("includeNote", {
+ noteId: noteId,
+ boxSize: boxSize
+ })
+ );
+ });
+ },
++ addHtmlToEditor(html: string) {
++ const editor = watchdogRef.current?.editor;
++ if (!editor) return;
++
++ editor.model.change((writer) => {
++ const viewFragment = editor.data.processor.toView(html);
++ const modelFragment = editor.data.toModel(viewFragment);
++ const insertPosition = editor.model.document.selection.getLastPosition();
++
++ if (insertPosition) {
++ const range = editor.model.insertContent(modelFragment, insertPosition);
++
++ if (range) {
++ writer.setSelection(range.end);
++ }
++ }
++ });
++
++ editor.editing.view.focus();
++ },
+ async addImage(noteId) {
+ const editor = watchdogRef.current?.editor;
+ if (!editor) return;
+
+ const note = await froca.getNote(noteId);
+ if (!note) return;
+
+ editor.model.change(() => {
+ const encodedTitle = encodeURIComponent(note.title);
+ const src = `api/images/${note.noteId}/${encodedTitle}`;
+
+ editor?.execute("insertImage", { source: src });
+ });
+ },
+ }));
+
+ useLegacyImperativeHandlers({
+ async loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string | null = null) {
+ await link.loadReferenceLinkTitle($el, href);
+ }
+ })
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+ const watchdog = buildWatchdog(!!isClassicEditor, watchdogConfig);
+ watchdogRef.current = watchdog;
+ externalWatchdogRef.current = watchdog;
+ watchdog.setCreator(async () => {
+ const editor = await buildEditor(container, !!isClassicEditor, {
+ forceGplLicense: false,
+ isClassicEditor: !!isClassicEditor,
+ contentLanguage: contentLanguage ?? null,
+ templates
+ });
+
+ setEditor(editor);
+
+ // Inspector integration.
+ if (import.meta.env.VITE_CKEDITOR_ENABLE_INSPECTOR === "true") {
+ const CKEditorInspector = (await import("@ckeditor/ckeditor5-inspector")).default;
+ CKEditorInspector.attach(editor);
+ }
+
+ onEditorInitialized?.(editor);
+
+ return editor;
+ });
+
+ if (onWatchdogStateChange) {
+ watchdog.on("stateChange", () => onWatchdogStateChange(watchdog));
+ }
+
+ watchdog.create(container);
+
+ return () => watchdog.destroy();
+ }, [ contentLanguage, templates ]);
+
+ // React to content changes.
+ useEffect(() => editor?.setData(content ?? ""), [ editor, content ]);
+
+ // React to notification warning callback.
+ useEffect(() => {
+ if (!onNotificationWarning || !editor) return;
+ const notificationPlugin = editor.plugins.get("Notification");
+ notificationPlugin.on("show:warning", onNotificationWarning);
+ return () => notificationPlugin.off("show:warning", onNotificationWarning);
+ }, [ editor, onNotificationWarning ]);
+
+ // React to on change listener.
+ useEffect(() => {
+ if (!editor) return;
+ editor.model.document.on("change:data", onChange);
+ return () => editor.model.document.off("change:data", onChange);
+ }, [ editor, onChange ]);
+
+ return (
+ <div ref={containerRef} className={className} tabIndex={tabIndex} />
+ );
+}
+
+function buildWatchdog(isClassicEditor: boolean, watchdogConfig?: WatchdogConfig): EditorWatchdog<CKTextEditor> {
+ if (isClassicEditor) {
+ return new EditorWatchdog(ClassicEditor, watchdogConfig);
+ } else {
+ return new EditorWatchdog(PopupEditor, watchdogConfig);
+ }
+}
+
+async function buildEditor(element: HTMLElement, isClassicEditor: boolean, opts: BuildEditorOptions) {
+ const editorClass = isClassicEditor ? ClassicEditor : PopupEditor;
+ let config = await buildConfig(opts);
+ let editor = await editorClass.create(element, config);
+
+ if (editor.isReadOnly) {
+ editor.destroy();
+
+ opts.forceGplLicense = true;
+ config = await buildConfig(opts);
+ editor = await editorClass.create(element, config);
+ }
+ return editor;
+}
diff --cc apps/client/src/widgets/type_widgets/text/EditableText.tsx
index 388da1691d,0000000000..3550546c79
mode 100644,000000..100644
--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx
@@@ -1,411 -1,0 +1,417 @@@
+import { useEffect, useRef, useState } from "preact/hooks";
+import dialog from "../../../services/dialog";
+import toast from "../../../services/toast";
+import utils, { deferred, hasTouchBar, isMobile } from "../../../services/utils";
+import { useEditorSpacedUpdate, useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteLabel, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";
+import { TypeWidgetProps } from "../type_widget";
+import CKEditorWithWatchdog, { CKEditorApi } from "./CKEditorWithWatchdog";
+import "./EditableText.css";
+import { CKTextEditor, ClassicEditor, EditorWatchdog, TemplateDefinition } from "@triliumnext/ckeditor5";
+import Component from "../../../components/component";
+import options from "../../../services/options";
+import { loadIncludedNote, refreshIncludedNote, setupImageOpening } from "./utils";
+import getTemplates, { updateTemplateCache } from "./snippets.js";
+import appContext from "../../../components/app_context";
+import link, { parseNavigationStateFromUrl } from "../../../services/link";
+import note_create from "../../../services/note_create";
+import TouchBar, { TouchBarButton, TouchBarGroup, TouchBarSegmentedControl } from "../../react/TouchBar";
+import { RefObject } from "preact";
+import { buildSelectedBackgroundColor } from "../../../components/touch_bar";
+
+/**
+ * The editor can operate into two distinct modes:
+ *
+ * - Ballon block mode, in which there is a floating toolbar for the selected text, but another floating button for the entire block (i.e. paragraph).
+ * - Decoupled mode, in which the editing toolbar is actually added on the client side (in {@link ClassicEditorToolbar}), see https://ckeditor.com/docs/ckeditor5/latest/examples/framework/bottom-toolbar-editor.html for an example on how the decoupled editor works.
+ */
+export default function EditableText({ note, parentComponent, ntxId, noteContext }: TypeWidgetProps) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [ content, setContent ] = useState<string>();
+ const watchdogRef = useRef<EditorWatchdog>(null);
+ const editorApiRef = useRef<CKEditorApi>(null);
+ const refreshTouchBarRef = useRef<() => void>(null);
+ const [ language ] = useNoteLabel(note, "language");
+ const [ textNoteEditorType ] = useTriliumOption("textNoteEditorType");
+ const [ codeBlockWordWrap ] = useTriliumOptionBool("codeBlockWordWrap");
+ const isClassicEditor = isMobile() || textNoteEditorType === "ckeditor-classic";
+ const initialized = useRef(deferred<void>());
+ const spacedUpdate = useEditorSpacedUpdate({
+ note,
+ noteContext,
+ getData() {
+ const editor = watchdogRef.current?.editor;
+ if (!editor) {
+ // There is nothing to save, most likely a result of the editor crashing and reinitializing.
+ return;
+ }
+
+ const content = editor.getData() ?? "";
+
+ // if content is only tags/whitespace (typically <p>&nbsp;</p>), then just make it empty,
+ // this is important when setting a new note to code
+ return {
+ content: utils.isHtmlEmpty(content) ? "" : content
+ };
+ },
+ onContentChange(newContent) {
+ setContent(newContent);
+ }
+ });
+ const templates = useTemplates();
+
+ useTriliumEvent("scrollToEnd", () => {
+ const editor = watchdogRef.current?.editor;
+ if (!editor) return;
+
+ editor.model.change((writer) => {
+ const rootItem = editor.model.document.getRoot();
+ if (rootItem) {
+ writer.setSelection(writer.createPositionAt(rootItem, "end"));
+ }
+ });
+ editor.editing.view.focus();
+ });
+
+ useTriliumEvent("focusOnDetail", async ({ ntxId: eventNtxId }) => {
+ if (eventNtxId !== ntxId) return;
+ const editor = await waitForEditor();
+ editor?.editing.view.focus();
+ });
+
+ useLegacyImperativeHandlers({
+ addLinkToTextCommand() {
+ if (!editorApiRef.current) return;
+ parentComponent?.triggerCommand("showAddLinkDialog", {
+ text: editorApiRef.current.getSelectedText(),
+ hasSelection: editorApiRef.current.hasSelection(),
+ async addLink(notePath, linkTitle, externalLink) {
+ await waitForEditor();
+ return editorApiRef.current?.addLink(notePath, linkTitle, externalLink);
+ }
+ });
+ },
++ pasteMarkdownIntoTextCommand() {
++ if (!editorApiRef.current) return;
++ parentComponent?.triggerCommand("showPasteMarkdownDialog", {
++ editorApi: editorApiRef.current,
++ });
++ },
+ // Include note functionality note
+ addIncludeNoteToTextCommand() {
+ if (!editorApiRef.current) return;
+ parentComponent?.triggerCommand("showIncludeNoteDialog", {
+ editorApi: editorApiRef.current,
+ });
+ },
+ loadIncludedNote,
+ // Creating notes in @-completion
+ async createNoteForReferenceLink(title: string) {
+ const notePath = noteContext?.notePath;
+ if (!notePath) return;
+
+ const resp = await note_create.createNoteWithTypePrompt(notePath, {
+ activate: false,
+ title: title
+ });
+
+ if (!resp || !resp.note) return;
+ return resp.note.getBestNotePathString();
+ },
+ // Keyboard shortcut
+ async followLinkUnderCursorCommand() {
+ const editor = await waitForEditor();
+ const selection = editor?.model.document.selection;
+ const selectedElement = selection?.getSelectedElement();
+
+ if (selectedElement?.name === "reference") {
+ const { notePath } = parseNavigationStateFromUrl(selectedElement.getAttribute("href") as string | undefined);
+
+ if (notePath) {
+ await appContext.tabManager.getActiveContext()?.setNote(notePath);
+ return;
+ }
+ }
+
+ if (!selection?.hasAttribute("linkHref")) {
+ return;
+ }
+
+ const selectedLinkUrl = selection.getAttribute("linkHref") as string;
+ const notePath = link.getNotePathFromUrl(selectedLinkUrl);
+
+ if (notePath) {
+ await appContext.tabManager.getActiveContext()?.setNote(notePath);
+ } else {
+ window.open(selectedLinkUrl, "_blank");
+ }
+ },
+ async cutIntoNoteCommand() {
+ const note = appContext.tabManager.getActiveContextNote();
+ if (!note) return;
+
+ // without await as this otherwise causes deadlock through component mutex
+ const parentNotePath = appContext.tabManager.getActiveContextNotePath();
+ if (noteContext && parentNotePath) {
+ note_create.createNote(parentNotePath, {
+ isProtected: note.isProtected,
+ saveSelection: true,
+ textEditor: await noteContext?.getTextEditor()
+ });
+ }
+ },
+ async saveNoteDetailNowCommand() {
+ // used by cutToNote in CKEditor build
+ spacedUpdate.updateNowIfNecessary();
+ }
+ });
+
+ useTriliumEvent("refreshIncludedNote", ({ noteId }) => {
+ if (!containerRef.current) return;
+ refreshIncludedNote(containerRef.current, noteId);
+ });
+
+ useTriliumEvent("executeWithTextEditor", async ({ callback, resolve, ntxId: eventNtxId }) => {
+ if (eventNtxId !== ntxId) return;
+ const editor = await waitForEditor() as CKTextEditor | undefined;
+ if (!editor) return;
+ if (callback) callback(editor);
+ resolve(editor);
+ });
+
+ async function waitForEditor() {
+ await initialized.current;
+ const editor = watchdogRef.current?.editor;
+ if (!editor) return;
+ return editor;
+ }
+
+ async function addTextToEditor(text: string) {
+ const editor = await waitForEditor();
+ editor?.model.change((writer) => {
+ const insertPosition = editor.model.document.selection.getLastPosition();
+ if (insertPosition) {
+ writer.insertText(text, insertPosition);
+ }
+ });
+ }
+
+ useKeyboardShortcuts("text-detail", containerRef, parentComponent);
+ useTriliumEvent("insertDateTimeToText", ({ ntxId: eventNtxId }) => {
+ if (eventNtxId !== ntxId) return;
+ const date = new Date();
+ const customDateTimeFormat = options.get("customDateTimeFormat");
+ const dateString = utils.formatDateTime(date, customDateTimeFormat);
+
+ addTextToEditor(dateString);
+ });
+ useTriliumEvent("addTextToActiveEditor", ({ text }) => {
+ if (!noteContext?.isActive()) return;
+ addTextToEditor(text);
+ });
+
+ return (
+ <>
+ {note && !!templates && <CKEditorWithWatchdog
+ containerRef={containerRef}
+ className={`note-detail-editable-text-editor use-tn-links ${codeBlockWordWrap ? "word-wrap" : ""}`}
+ tabIndex={300}
+ content={content}
+ contentLanguage={language}
+ isClassicEditor={isClassicEditor}
+ editorApi={editorApiRef}
+ watchdogRef={watchdogRef}
+ watchdogConfig={{
+ // An average number of milliseconds between the last editor errors (defaults to 5000). When the period of time between errors is lower than that and the crashNumberLimit is also reached, the watchdog changes its state to crashedPermanently, and it stops restarting the editor. This prevents an infinite restart loop.
+ minimumNonErrorTimePeriod: 5000,
+ // A threshold specifying the number of errors (defaults to 3). After this limit is reached and the time between last errors is shorter than minimumNonErrorTimePeriod, the watchdog changes its state to crashedPermanently, and it stops restarting the editor. This prevents an infinite restart loop.
+ crashNumberLimit: 10,
+ // A minimum number of milliseconds between saving the editor data internally (defaults to 5000). Note that for large documents, this might impact the editor performance.
+ saveInterval: 5000
+ }}
+ templates={templates}
+ onNotificationWarning={onNotificationWarning}
+ onWatchdogStateChange={onWatchdogStateChange}
+ onChange={() => spacedUpdate.scheduleUpdate()}
+ onEditorInitialized={(editor) => {
+ console.log("Editor has been initialized!", parentComponent, editor);
+
+ if (isClassicEditor) {
+ setupClassicEditor(editor, parentComponent);
+ }
+
+ if (hasTouchBar) {
+ const handler = () => refreshTouchBarRef.current?.();
+ for (const event of [ "bold", "italic", "underline", "paragraph", "heading" ]) {
+ editor.commands.get(event)?.on("change", handler);
+ }
+ }
+
+ if (containerRef.current) {
+ setupImageOpening(containerRef.current, false);
+ }
+
+ initialized.current.resolve();
+ }}
+ />}
+
+ <EditableTextTouchBar watchdogRef={watchdogRef} refreshTouchBarRef={refreshTouchBarRef} />
+ </>
+ )
+}
+
+function useTemplates() {
+ const [ templates, setTemplates ] = useState<TemplateDefinition[]>();
+
+ useEffect(() => {
+ getTemplates().then(setTemplates);
+ }, []);
+
+ useTriliumEvent("entitiesReloaded", async ({ loadResults }) => {
+ await updateTemplateCache(loadResults, setTemplates);
+ });
+
+ return templates;
+}
+
+function onWatchdogStateChange(watchdog: EditorWatchdog) {
+ const currentState = watchdog.state;
+ logInfo(`CKEditor state changed to ${currentState}`);
+
+ if (!["crashed", "crashedPermanently"].includes(currentState)) {
+ return;
+ }
+
+ logError(`CKEditor crash logs: ${JSON.stringify(watchdog.crashes, null, 4)}`);
+
+ if (currentState === "crashedPermanently") {
+ dialog.info(`Editing component keeps crashing. Please try restarting Trilium. If problem persists, consider creating a bug report.`);
+ watchdog.editor?.enableReadOnlyMode("crashed-editor");
+ }
+}
+
+function onNotificationWarning(data, evt) {
+ const title = data.title;
+ const message = data.message.message;
+
+ if (title && message) {
+ toast.showErrorTitleAndMessage(data.title, data.message.message);
+ } else if (title) {
+ toast.showError(title || message);
+ }
+
+ evt.stop();
+}
+
+function setupClassicEditor(editor: CKTextEditor, parentComponent: Component | undefined) {
+ if (!parentComponent) return;
+ const $classicToolbarWidget = findClassicToolbar(parentComponent);
+
+ $classicToolbarWidget.empty();
+ if ($classicToolbarWidget.length) {
+ const toolbarView = (editor as ClassicEditor).ui.view.toolbar;
+ if (toolbarView.element) {
+ $classicToolbarWidget[0].appendChild(toolbarView.element);
+ }
+ }
+
+ if (utils.isMobile()) {
+ $classicToolbarWidget.addClass("visible");
+
+ // Reposition all dropdowns to point upwards instead of downwards.
+ // See https://ckeditor.com/docs/ckeditor5/latest/examples/framework/bottom-toolbar-editor.html for more info.
+ const toolbarView = (editor as ClassicEditor).ui.view.toolbar;
+ for (const item of toolbarView.items) {
+ if (!("panelView" in item)) continue;
+
+ item.on("change:isOpen", () => {
+ if (!("isOpen" in item) || !item.isOpen) return;
+
+ // @ts-ignore
+ item.panelView.position = item.panelView.position.replace("s", "n");
+ });
+ }
+ }
+}
+
+function findClassicToolbar(parentComponent: Component): JQuery<HTMLElement> {
+ const $widget = $(parentComponent.$widget);
+
+ if (!utils.isMobile()) {
+ const $parentSplit = $widget.parents(".note-split.type-text");
+
+ if ($parentSplit.length) {
+ // The editor is in a normal tab.
+ return $parentSplit.find("> .ribbon-container .classic-toolbar-widget");
+ } else {
+ // The editor is in a popup.
+ return $widget.closest(".modal-body").find(".classic-toolbar-widget");
+ }
+ } else {
+ return $("body").find(".classic-toolbar-widget");
+ }
+}
+
+function EditableTextTouchBar({ watchdogRef, refreshTouchBarRef }: { watchdogRef: RefObject<EditorWatchdog | null>, refreshTouchBarRef: RefObject<() => void> }) {
+ const [ headingSelectedIndex, setHeadingSelectedIndex ] = useState<number>();
+
+ function refresh() {
+ let headingSelectedIndex: number | undefined = undefined;
+ const editor = watchdogRef.current?.editor;
+ const headingCommand = editor?.commands.get("heading");
+ const paragraphCommand = editor?.commands.get("paragraph");
+ if (paragraphCommand?.value) {
+ headingSelectedIndex = 0;
+ } else if (headingCommand?.value === "heading2") {
+ headingSelectedIndex = 1;
+ } else if (headingCommand?.value === "heading3") {
+ headingSelectedIndex = 2;
+ }
+ setHeadingSelectedIndex(headingSelectedIndex);
+ }
+
+ useEffect(refresh, []);
+ refreshTouchBarRef.current = refresh;
+
+ return (
+ <TouchBar>
+ <TouchBarSegmentedControl
+ segments={[
+ { label: "P" },
+ { label: "H2" },
+ { label: "H3" }
+ ]}
+ onChange={(selectedIndex) => {
+ const editor = watchdogRef.current?.editor;
+ switch (selectedIndex) {
+ case 0:
+ editor?.execute("paragraph")
+ break;
+ case 1:
+ editor?.execute("heading", { value: "heading2" });
+ break;
+ case 2:
+ editor?.execute("heading", { value: "heading3" });
+ break;
+ }
+ }}
+ selectedIndex={headingSelectedIndex}
+ mode="buttons"
+ />
+
+ <TouchBarGroup>
+ <TouchBarCommandButton watchdogRef={watchdogRef} command="bold" icon="NSTouchBarTextBoldTemplate" />
+ <TouchBarCommandButton watchdogRef={watchdogRef} command="italic" icon="NSTouchBarTextItalicTemplate" />
+ <TouchBarCommandButton watchdogRef={watchdogRef} command="underline" icon="NSTouchBarTextUnderlineTemplate" />
+ </TouchBarGroup>
+ </TouchBar>
+ )
+}
+
+function TouchBarCommandButton({ watchdogRef, icon, command }: { watchdogRef: RefObject<EditorWatchdog | null>, icon: string, command: string }) {
+ const editor = watchdogRef.current?.editor;
+ return (<TouchBarButton
+ icon={icon}
+ click={() => editor?.execute(command)}
+ backgroundColor={buildSelectedBackgroundColor(editor?.commands.get(command)?.value as boolean)}
+ />);
+}
diff --cc pnpm-lock.yaml
index 6b667b9f0d,a93b37fe76..c7fddc7043
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@@ -14920,26 -15431,26 +15431,24 @@@ snapshots
transitivePeerDependencies:
- supports-color
- '@ckeditor/[email protected]':
+ '@ckeditor/[email protected]':
dependencies:
- '@ckeditor/ckeditor5-core': 47.1.0
- '@ckeditor/ckeditor5-icons': 47.1.0
- '@ckeditor/ckeditor5-typing': 47.1.0
- '@ckeditor/ckeditor5-ui': 47.1.0
- '@ckeditor/ckeditor5-utils': 47.1.0
- ckeditor5: 47.1.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
- transitivePeerDependencies:
- - supports-color
+ '@ckeditor/ckeditor5-core': 47.2.0
+ '@ckeditor/ckeditor5-icons': 47.2.0
+ '@ckeditor/ckeditor5-typing': 47.2.0
+ '@ckeditor/ckeditor5-ui': 47.2.0
+ '@ckeditor/ckeditor5-utils': 47.2.0
+ ckeditor5: 47.2.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
- transitivePeerDependencies:
- - supports-color
- '@ckeditor/[email protected]':
+ '@ckeditor/[email protected]':
dependencies:
- '@ckeditor/ckeditor5-core': 47.1.0
- '@ckeditor/ckeditor5-enter': 47.1.0
- '@ckeditor/ckeditor5-icons': 47.1.0
- '@ckeditor/ckeditor5-typing': 47.1.0
- '@ckeditor/ckeditor5-ui': 47.1.0
- '@ckeditor/ckeditor5-utils': 47.1.0
- ckeditor5: 47.1.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
+ '@ckeditor/ckeditor5-core': 47.2.0
+ '@ckeditor/ckeditor5-enter': 47.2.0
+ '@ckeditor/ckeditor5-icons': 47.2.0
+ '@ckeditor/ckeditor5-typing': 47.2.0
+ '@ckeditor/ckeditor5-ui': 47.2.0
+ '@ckeditor/ckeditor5-utils': 47.2.0
+ ckeditor5: 47.2.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
transitivePeerDependencies:
- supports-color
@@@ -14990,31 -15501,31 +15499,33 @@@
transitivePeerDependencies:
- supports-color
- '@ckeditor/[email protected]':
+ '@ckeditor/[email protected]':
dependencies:
- '@ckeditor/ckeditor5-core': 47.1.0
- '@ckeditor/ckeditor5-engine': 47.1.0
- '@ckeditor/ckeditor5-ui': 47.1.0
- '@ckeditor/ckeditor5-utils': 47.1.0
- '@ckeditor/ckeditor5-widget': 47.1.0
+ '@ckeditor/ckeditor5-core': 47.2.0
+ '@ckeditor/ckeditor5-engine': 47.2.0
+ '@ckeditor/ckeditor5-ui': 47.2.0
+ '@ckeditor/ckeditor5-utils': 47.2.0
+ '@ckeditor/ckeditor5-widget': 47.2.0
es-toolkit: 1.39.5
- '@ckeditor/[email protected]':
+ '@ckeditor/[email protected]':
dependencies:
- '@ckeditor/ckeditor5-core': 47.1.0
- '@ckeditor/ckeditor5-utils': 47.1.0
- ckeditor5: 47.1.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
+ '@ckeditor/ckeditor5-core': 47.2.0
+ '@ckeditor/ckeditor5-utils': 47.2.0
+ ckeditor5: 47.2.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
++ transitivePeerDependencies:
++ - supports-color
- '@ckeditor/[email protected](patch_hash=2361d8caad7d6b5bddacc3a3b4aa37dbfba260b1c1b22a450413a79c1bb1ce95)':
+ '@ckeditor/[email protected](patch_hash=2361d8caad7d6b5bddacc3a3b4aa37dbfba260b1c1b22a450413a79c1bb1ce95)':
dependencies:
- '@ckeditor/ckeditor5-clipboard': 47.1.0
- '@ckeditor/ckeditor5-core': 47.1.0
- '@ckeditor/ckeditor5-engine': 47.1.0
- '@ckeditor/ckeditor5-enter': 47.1.0
- '@ckeditor/ckeditor5-icons': 47.1.0
- '@ckeditor/ckeditor5-ui': 47.1.0
- '@ckeditor/ckeditor5-utils': 47.1.0
- ckeditor5: 47.1.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
+ '@ckeditor/ckeditor5-clipboard': 47.2.0
+ '@ckeditor/ckeditor5-core': 47.2.0
+ '@ckeditor/ckeditor5-engine': 47.2.0
+ '@ckeditor/ckeditor5-enter': 47.2.0
+ '@ckeditor/ckeditor5-icons': 47.2.0
+ '@ckeditor/ckeditor5-ui': 47.2.0
+ '@ckeditor/ckeditor5-utils': 47.2.0
+ ckeditor5: 47.2.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
transitivePeerDependencies:
- supports-color
@@@ -15223,51 -15737,51 +15737,51 @@@
transitivePeerDependencies:
- supports-color
- '@ckeditor/[email protected]':
+ '@ckeditor/[email protected]':
dependencies:
- '@ckeditor/ckeditor5-core': 47.1.0
- '@ckeditor/ckeditor5-engine': 47.1.0
- '@ckeditor/ckeditor5-ui': 47.1.0
- '@ckeditor/ckeditor5-utils': 47.1.0
- ckeditor5: 47.1.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
+ '@ckeditor/ckeditor5-core': 47.2.0
+ '@ckeditor/ckeditor5-engine': 47.2.0
+ '@ckeditor/ckeditor5-ui': 47.2.0
+ '@ckeditor/ckeditor5-utils': 47.2.0
+ ckeditor5: 47.2.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
es-toolkit: 1.39.5
- '@ckeditor/[email protected]':
+ '@ckeditor/[email protected]':
dependencies:
- '@ckeditor/ckeditor5-core': 47.1.0
- '@ckeditor/ckeditor5-engine': 47.1.0
- '@ckeditor/ckeditor5-ui': 47.1.0
- '@ckeditor/ckeditor5-utils': 47.1.0
- ckeditor5: 47.1.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
+ '@ckeditor/ckeditor5-core': 47.2.0
+ '@ckeditor/ckeditor5-engine': 47.2.0
+ '@ckeditor/ckeditor5-ui': 47.2.0
+ '@ckeditor/ckeditor5-utils': 47.2.0
+ ckeditor5: 47.2.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
es-toolkit: 1.39.5
++ transitivePeerDependencies:
++ - supports-color
- '@ckeditor/[email protected]':
+ '@ckeditor/[email protected]':
dependencies:
- '@ckeditor/ckeditor5-core': 47.1.0
- '@ckeditor/ckeditor5-engine': 47.1.0
- '@ckeditor/ckeditor5-ui': 47.1.0
- '@ckeditor/ckeditor5-utils': 47.1.0
- ckeditor5: 47.1.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
+ '@ckeditor/ckeditor5-core': 47.2.0
+ '@ckeditor/ckeditor5-engine': 47.2.0
+ '@ckeditor/ckeditor5-ui': 47.2.0
+ '@ckeditor/ckeditor5-utils': 47.2.0
+ ckeditor5: 47.2.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
es-toolkit: 1.39.5
- '@ckeditor/[email protected]':
+ '@ckeditor/[email protected]':
dependencies:
- '@ckeditor/ckeditor5-core': 47.1.0
- '@ckeditor/ckeditor5-engine': 47.1.0
- '@ckeditor/ckeditor5-ui': 47.1.0
- '@ckeditor/ckeditor5-utils': 47.1.0
- ckeditor5: 47.1.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
+ '@ckeditor/ckeditor5-core': 47.2.0
+ '@ckeditor/ckeditor5-engine': 47.2.0
+ '@ckeditor/ckeditor5-ui': 47.2.0
+ '@ckeditor/ckeditor5-utils': 47.2.0
+ ckeditor5: 47.2.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
es-toolkit: 1.39.5
-- transitivePeerDependencies:
-- - supports-color
- '@ckeditor/[email protected]':
+ '@ckeditor/[email protected]':
dependencies:
- '@ckeditor/ckeditor5-core': 47.1.0
- '@ckeditor/ckeditor5-engine': 47.1.0
- '@ckeditor/ckeditor5-ui': 47.1.0
- '@ckeditor/ckeditor5-utils': 47.1.0
- ckeditor5: 47.1.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
+ '@ckeditor/ckeditor5-core': 47.2.0
+ '@ckeditor/ckeditor5-engine': 47.2.0
+ '@ckeditor/ckeditor5-ui': 47.2.0
+ '@ckeditor/ckeditor5-utils': 47.2.0
+ ckeditor5: 47.2.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
es-toolkit: 1.39.5
transitivePeerDependencies:
- supports-color
@@@ -15299,27 -15813,27 +15813,29 @@@
transitivePeerDependencies:
- supports-color
- '@ckeditor/[email protected]':
+ '@ckeditor/[email protected]':
dependencies:
- '@ckeditor/ckeditor5-utils': 47.1.0
+ '@ckeditor/ckeditor5-utils': 47.2.0
es-toolkit: 1.39.5
- '@ckeditor/[email protected]':
+ '@ckeditor/[email protected]':
dependencies:
- '@ckeditor/ckeditor5-core': 47.1.0
- '@ckeditor/ckeditor5-engine': 47.1.0
- '@ckeditor/ckeditor5-utils': 47.1.0
+ '@ckeditor/ckeditor5-core': 47.2.0
+ '@ckeditor/ckeditor5-engine': 47.2.0
+ '@ckeditor/ckeditor5-utils': 47.2.0
++ transitivePeerDependencies:
++ - supports-color
- '@ckeditor/[email protected]':
+ '@ckeditor/[email protected]':
dependencies:
- '@ckeditor/ckeditor5-clipboard': 47.1.0
- '@ckeditor/ckeditor5-core': 47.1.0
- '@ckeditor/ckeditor5-enter': 47.1.0
- '@ckeditor/ckeditor5-select-all': 47.1.0
- '@ckeditor/ckeditor5-typing': 47.1.0
- '@ckeditor/ckeditor5-ui': 47.1.0
- '@ckeditor/ckeditor5-undo': 47.1.0
- ckeditor5: 47.1.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
+ '@ckeditor/ckeditor5-clipboard': 47.2.0
+ '@ckeditor/ckeditor5-core': 47.2.0
+ '@ckeditor/ckeditor5-enter': 47.2.0
+ '@ckeditor/ckeditor5-select-all': 47.2.0
+ '@ckeditor/ckeditor5-typing': 47.2.0
+ '@ckeditor/ckeditor5-ui': 47.2.0
+ '@ckeditor/ckeditor5-undo': 47.2.0
+ ckeditor5: 47.2.0(patch_hash=8331a09d41443b39ea1c784daaccfeb0da4f9065ed556e7de92e9c77edd9eb41)
transitivePeerDependencies:
- supports-color