Skip to content

Build your personal knowledge base with Trilium Notes

refactor(client): show the API log inside the code editor

Elian Doran2f686c47b3a5
diff --git a/apps/client/src/layouts/desktop_layout.tsx b/apps/client/src/layouts/desktop_layout.tsx
index 4b1a77fcca..9481e2bf07 100644
--- a/apps/client/src/layouts/desktop_layout.tsx
+++ b/apps/client/src/layouts/desktop_layout.tsx
@@ -2,7 +2,6 @@ import type { AppContext } from "../components/app_context.js";
import type { WidgetsByParent } from "../services/bundle.js";
import options from "../services/options.js";
import utils from "../services/utils.js";
-import ApiLog from "../widgets/api_log.jsx";
import GlobalMenu from "../widgets/buttons/global_menu.jsx";
import LeftPaneToggle from "../widgets/buttons/left_pane_toggle.js";
import RightPaneToggle from "../widgets/buttons/right_pane_toggle.jsx";
@@ -136,7 +135,6 @@ export default class DesktopLayout {
.child(<SearchResult />)
.child(<ScrollPadding />)
)
- .child(<ApiLog />)
.child(new FindWidget())
.child(...this.customWidgets.get("note-detail-pane"))
)
diff --git a/apps/client/src/layouts/mobile_layout.tsx b/apps/client/src/layouts/mobile_layout.tsx
index 303ab05001..39c8bc8790 100644
--- a/apps/client/src/layouts/mobile_layout.tsx
+++ b/apps/client/src/layouts/mobile_layout.tsx
@@ -1,7 +1,6 @@
import "./mobile_layout.css";
import type AppContext from "../components/app_context.js";
-import ApiLog from "../widgets/api_log.jsx";
import GlobalMenuWidget from "../widgets/buttons/global_menu.js";
import CloseZenModeButton from "../widgets/close_zen_button.js";
import NoteList from "../widgets/collections/NoteList.jsx";
@@ -84,7 +83,6 @@ export default class MobileLayout {
.child(<SearchResult />)
.child(<ScrollPadding />)
)
- .child(<ApiLog />)
.child(<MobileEditorToolbar />)
.child(new FindWidget())
)
diff --git a/apps/client/src/widgets/api_log.tsx b/apps/client/src/widgets/api_log.tsx
deleted file mode 100644
index ba0f8e095c..0000000000
--- a/apps/client/src/widgets/api_log.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { useEffect, useState } from "preact/hooks";
-import "./api_log.css";
-import { useNoteContext, useTriliumEvent } from "./react/hooks";
-import ActionButton from "./react/ActionButton";
-import { t } from "../services/i18n";
-
-/**
- * Displays the messages that are logged by the current note via `api.log`, for frontend and backend scripts.
- */
-export default function ApiLog() {
- const { note, noteId } = useNoteContext();
- const [ messages, setMessages ] = useState<string[]>();
-
- useTriliumEvent("apiLogMessages", ({ messages, noteId: eventNoteId }) => {
- if (eventNoteId !== noteId) return;
- setMessages(messages);
- });
-
- // Clear when navigating away.
- useEffect(() => setMessages(undefined), [ note ]);
-
- const isEnabled = note?.mime.startsWith("application/javascript;env=") && messages?.length;
- return (
- <div className={`api-log-widget ${!isEnabled ? "hidden-ext" : ""}`}>
- {isEnabled && (
- <>
- <ActionButton
- icon="bx bx-x"
- className="close-api-log-button"
- text={t("api_log.close")}
- onClick={() => setMessages(undefined)}
- />
-
- <div className="api-log-container">
- {messages.join("\n")}
- </div>
- </>
- )}
- </div>
- )
-}
diff --git a/apps/client/src/widgets/api_log.css b/apps/client/src/widgets/type_widgets/code/ApiLog.css
similarity index 88%
rename from apps/client/src/widgets/api_log.css
rename to apps/client/src/widgets/type_widgets/code/ApiLog.css
index 1a49324080..b29bb20a31 100644
--- a/apps/client/src/widgets/api_log.css
+++ b/apps/client/src/widgets/type_widgets/code/ApiLog.css
@@ -1,5 +1,7 @@
.api-log-widget {
- flex-grow: 1;
+ flex-shrink: 0;
+ display: flex;
+ flex-direction: column;
max-height: 40%;
position: relative;
border-top: 1px solid var(--main-border-color);
@@ -8,7 +10,7 @@
.api-log-container {
overflow: auto;
- height: 100%;
+ min-height: 0;
font-family: var(--monospace-font-family);
font-size: 0.8em;
white-space: pre;
diff --git a/apps/client/src/widgets/type_widgets/code/ApiLog.tsx b/apps/client/src/widgets/type_widgets/code/ApiLog.tsx
new file mode 100644
index 0000000000..9530eed2c8
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/code/ApiLog.tsx
@@ -0,0 +1,44 @@
+import "./ApiLog.css";
+
+import { useEffect, useState } from "preact/hooks";
+
+import FNote from "../../../entities/fnote";
+import { t } from "../../../services/i18n";
+import ActionButton from "../../react/ActionButton";
+import { useNoteProperty, useTriliumEvent } from "../../react/hooks";
+
+/**
+ * Displays the messages that a frontend or backend script note logs via `api.log()`, below its editor.
+ */
+export default function ApiLog({ note }: { note: FNote }) {
+ const [ messages, setMessages ] = useState<string[]>();
+ const mime = useNoteProperty(note, "mime");
+
+ useTriliumEvent("apiLogMessages", ({ messages, noteId }) => {
+ if (noteId === note.noteId) {
+ setMessages(messages);
+ }
+ });
+
+ // Clears the log when the editor moves to another note, but not on mount, which can run after a message arrives.
+ useEffect(() => () => setMessages(undefined), [ note ]);
+
+ if (!mime?.startsWith("application/javascript;env=") || !messages?.length) {
+ return null;
+ }
+
+ return (
+ <div className="api-log-widget">
+ <ActionButton
+ icon="bx bx-x"
+ className="close-api-log-button"
+ text={t("api_log.close")}
+ onClick={() => setMessages(undefined)}
+ />
+
+ <div className="api-log-container">
+ {messages.join("\n")}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/code/Code.spec.tsx b/apps/client/src/widgets/type_widgets/code/Code.spec.tsx
index ab76ed9796..f71ed03ff2 100644
--- a/apps/client/src/widgets/type_widgets/code/Code.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/code/Code.spec.tsx
@@ -1,13 +1,14 @@
// @vitest-environment jsdom
import { render } from "preact";
import { act } from "preact/test-utils";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import FNote from "../../../entities/fnote";
+import search from "../../../services/search";
import { buildNote } from "../../../test/easy-froca";
import { renderInto } from "../../../test/render";
import { ParentComponent } from "../../react/react_utils";
-import { EditableCode } from "./Code";
+import { EditableCode, ReadOnlyCode } from "./Code";
describe("EditableCode", () => {
const parent = { registerHandler() {}, removeHandler() {}, componentId: "c" } as any;
@@ -54,3 +55,54 @@ describe("EditableCode", () => {
expect(onContentChanged).toHaveBeenCalledTimes(1);
});
});
+
+describe("API log", () => {
+ const handlers = new Map<string, (data: unknown) => void>();
+ const parent = {
+ registerHandler(name: string, handler: (data: unknown) => void) { handlers.set(name, handler); },
+ removeHandler() {},
+ componentId: "c"
+ } as any;
+
+ beforeEach(() => {
+ vi.spyOn(search, "searchForNotes").mockResolvedValue([]);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("shows what the script note logs below the editable and the read-only editor, until closed or switched away", async () => {
+ for (const Editor of [ EditableCode, ReadOnlyCode ]) {
+ const script = { type: "code", mime: "application/javascript;env=frontend", content: "api.log(1)" } as const;
+ const note = buildNote({ ...script, title: "Script" });
+ const otherNote = buildNote({ ...script, title: "Other script" });
+ const show = (shown: FNote) => (
+ <ParentComponent.Provider value={parent}>
+ <Editor note={shown} ntxId="ntx" parentComponent={parent} noteContext={undefined} viewScope={undefined} />
+ </ParentComponent.Provider>
+ );
+ const log = (noteId: string) => act(() => handlers.get("apiLogMessages")?.({ noteId, messages: [ "first", "second" ] }));
+
+ let container: HTMLElement | undefined;
+ await act(async () => { container = renderInto(show(note)); });
+
+ log(otherNote.noteId);
+ expect(container?.querySelector(".api-log-container")).toBeNull();
+
+ log(note.noteId);
+ expect(container?.querySelector(".api-log-container")?.textContent).toBe("first\nsecond");
+
+ await act(async () => {
+ if (container) render(show(otherNote), container);
+ });
+ expect(container?.querySelector(".api-log-container")).toBeNull();
+
+ log(otherNote.noteId);
+ const closeButton = container?.querySelector<HTMLElement>(".close-api-log-button");
+ expect(closeButton).not.toBeNull();
+ act(() => closeButton?.click());
+ expect(container?.querySelector(".api-log-container")).toBeNull();
+ }
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/code/Code.tsx b/apps/client/src/widgets/type_widgets/code/Code.tsx
index b457b06c4b..a60e863a50 100644
--- a/apps/client/src/widgets/type_widgets/code/Code.tsx
+++ b/apps/client/src/widgets/type_widgets/code/Code.tsx
@@ -14,6 +14,7 @@ import { useColorScheme, useEditorSpacedUpdate, useKeyboardShortcuts, useLegacyI
import { refToJQuerySelector } from "../../react/react_utils";
import { CODE_THEME_DEFAULT_PREFIX as DEFAULT_PREFIX } from "../constants";
import { TypeWidgetProps } from "../type_widget";
+import ApiLog from "./ApiLog";
import CodeMirror, { CodeMirrorProps } from "./CodeMirror";
import { useSnippetSlashCommands } from "./snippets";
@@ -60,17 +61,20 @@ export function ReadOnlyCode({ note, viewScope, ntxId, noteContext, editorRef }:
useSearchTermsConsumer(note, noteContext, ntxId);
return (
- <CodeEditor
- ntxId={ntxId}
- editorRef={editorRef}
- className="note-detail-readonly-code-content"
- content={content}
- mime={mime ?? "text/plain"}
- readOnly
- {...(noteTabWidth != null && { indentSize: noteTabWidth })}
- {...(noteUseTabs != null && { useTabs: noteUseTabs })}
- {...(noteWrapLines != null && { lineWrapping: noteWrapLines })}
- />
+ <>
+ <CodeEditor
+ ntxId={ntxId}
+ editorRef={editorRef}
+ className="note-detail-readonly-code-content"
+ content={content}
+ mime={mime ?? "text/plain"}
+ readOnly
+ {...(noteTabWidth != null && { indentSize: noteTabWidth })}
+ {...(noteUseTabs != null && { useTabs: noteUseTabs })}
+ {...(noteWrapLines != null && { lineWrapping: noteWrapLines })}
+ />
+ <ApiLog note={note} />
+ </>
);
}
@@ -157,29 +161,32 @@ export function EditableCode({ note, ntxId, noteContext, debounceUpdate, parentC
);
return (
- <CodeEditor
- ntxId={ntxId}
- editorRef={combinedEditorRef} containerRef={containerRef}
- mime={mime ?? "text/plain"}
- customRequestHandler={customRequestHandler != null}
- className="note-detail-code-editor"
- placeholder={placeholder ?? t("editable_code.placeholder")}
- vimKeybindings={vimKeymapEnabled}
- tabIndex={300}
- onContentChanged={() => {
- if (debounceUpdate) {
- spacedUpdate.resetUpdateTimer();
- }
- spacedUpdate.scheduleUpdate();
- if (editorRef.current && onContentChanged) {
- onContentChanged(editorRef.current.getText());
- }
- }}
- {...editorProps}
- {...(noteTabWidth != null && { indentSize: noteTabWidth })}
- {...(noteUseTabs != null && { useTabs: noteUseTabs })}
- {...(noteWrapLines != null && { lineWrapping: noteWrapLines })}
- />
+ <>
+ <CodeEditor
+ ntxId={ntxId}
+ editorRef={combinedEditorRef} containerRef={containerRef}
+ mime={mime ?? "text/plain"}
+ customRequestHandler={customRequestHandler != null}
+ className="note-detail-code-editor"
+ placeholder={placeholder ?? t("editable_code.placeholder")}
+ vimKeybindings={vimKeymapEnabled}
+ tabIndex={300}
+ onContentChanged={() => {
+ if (debounceUpdate) {
+ spacedUpdate.resetUpdateTimer();
+ }
+ spacedUpdate.scheduleUpdate();
+ if (editorRef.current && onContentChanged) {
+ onContentChanged(editorRef.current.getText());
+ }
+ }}
+ {...editorProps}
+ {...(noteTabWidth != null && { indentSize: noteTabWidth })}
+ {...(noteUseTabs != null && { useTabs: noteUseTabs })}
+ {...(noteWrapLines != null && { lineWrapping: noteWrapLines })}
+ />
+ <ApiLog note={note} />
+ </>
);
}
diff --git a/apps/client/src/widgets/type_widgets/code/code.css b/apps/client/src/widgets/type_widgets/code/code.css
index dcaad4cf6b..8becb1a3bc 100644
--- a/apps/client/src/widgets/type_widgets/code/code.css
+++ b/apps/client/src/widgets/type_widgets/code/code.css
@@ -2,12 +2,15 @@
.note-detail-readonly-code {
min-height: 50px;
position: relative;
+ display: flex;
+ flex-direction: column;
}
/* Fills the wrapper in the full-height layout so the editor's own scroller can scroll; resolves
to auto in the flowing layout, where the wrapper has no set height. */
.note-detail-readonly-code .note-detail-readonly-code-content {
height: 100%;
+ min-height: 0;
}
/* #endregion */
@@ -15,6 +18,8 @@
.note-detail-code {
position: relative;
height: 100%;
+ display: flex;
+ flex-direction: column;
}
.note-detail-code-editor {