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
feat(bulk_actions): complete the "Execute script" field
Elian Doran252a31c661d6
diff --git a/apps/client/src/widgets/bulk_actions/execute_script.css b/apps/client/src/widgets/bulk_actions/execute_script.cssnew file mode 100644index 0000000000..227b1beeb0--- /dev/null+++ b/apps/client/src/widgets/bulk_actions/execute_script.css@@ -0,0 +1,34 @@+.bulk-action-fields > .bulk-action-script {+ > pre {+ margin: 0;+ padding: 0;+ }++ .cm-editor {+ max-height: 12em;+ background: transparent;+ font-size: inherit;+ }++ .cm-scroller {+ overflow: auto;+ line-height: inherit;+ }++ .cm-content {+ padding: 0;+ caret-color: var(--input-text-color);+ }++ .cm-line {+ padding: 0;+ }++ .cm-activeLine {+ background: transparent;+ }++ .cm-gutters {+ display: none;+ }+}diff --git a/apps/client/src/widgets/bulk_actions/execute_script.tsx b/apps/client/src/widgets/bulk_actions/execute_script.tsxindex eddf727d75..309360005f 100644--- a/apps/client/src/widgets/bulk_actions/execute_script.tsx+++ b/apps/client/src/widgets/bulk_actions/execute_script.tsx@@ -1,26 +1,48 @@-import { useState } from "preact/hooks";+import "./execute_script.css";++import type VanillaCodeMirror from "@triliumnext/codemirror";+import { SCRIPT_MIME_BACKEND } from "@triliumnext/codemirror/src/type_completion/index";+import { lazy, Suspense } from "preact/compat";+import { useRef, useState } from "preact/hooks";+import { t } from "../../services/i18n.js";-import FormTextBox from "../react/FormTextBox.jsx";import AbstractBulkAction, { ActionDefinition } from "./abstract_bulk_action.js";import BulkAction, { useSaveAction } from "./BulkAction.jsx";function ExecuteScriptBulkActionComponent({ bulkAction, actionDef }: { bulkAction: AbstractBulkAction, actionDef: ActionDefinition }) {- const [ script, setScript ] = useState(actionDef.script);+ const [ script, setScript ] = useState(actionDef.script ?? "");+ // `CodeEditor` replaces its document whenever `content` changes, so it only receives the+ // script the row opens with.+ const [ initialScript ] = useState(script);+ const editorRef = useRef<VanillaCodeMirror>(null);useSaveAction(bulkAction, { script });return (<BulkActionbulkAction={bulkAction}>- <FormTextBox- placeholder="note.title = note.title + '- suffix';"- required- currentValue={script} onChange={setScript}- />+ <div className="bulk-action-script form-control tn-input-field">+ <Suspense fallback={null}>+ <CodeEditor+ ntxId={null}+ editorRef={editorRef}+ content={initialScript}+ mime={SCRIPT_MIME_BACKEND}+ bulkActionNote+ lineWrapping+ placeholder="note.title = note.title + '- suffix';"+ onContentChanged={() => setScript(editorRef.current?.getText() ?? "")}+ />+ </Suspense>+ </div></BulkAction>);}+/** The editor and its TypeScript completion, loaded only once a script action is shown. */+const CodeEditor = lazy(() => import("../type_widgets/code/Code")+ .then(({ CodeEditor: editor }) => ({ default: editor })));+export default class ExecuteScriptBulkAction extends AbstractBulkAction {static get actionName() {diff --git a/apps/client/src/widgets/dialogs/bulk_actions.spec.tsx b/apps/client/src/widgets/dialogs/bulk_actions.spec.tsxindex ce1d78afad..d957535e3a 100644--- a/apps/client/src/widgets/dialogs/bulk_actions.spec.tsx+++ b/apps/client/src/widgets/dialogs/bulk_actions.spec.tsx@@ -188,7 +188,7 @@ describe("BulkActionsDialog", () => {deleteNote: { required: [], names: [] },saveRevision: { required: [ false ], names: [ false ] },deleteRevisions: { required: [], names: [] },- executeScript: { required: [ true ], names: [ false ] }+ executeScript: { required: [], names: [] }};buildNote({id: "_bulkAction",diff --git a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsxindex 469238e3db..740b41237f 100644--- a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx@@ -15,9 +15,11 @@ export interface CodeMirrorProps extends Omit<EditorConfig, "parent"> {* Gates the `api.req`/`api.res`/`api.pathParams` completions for backend scripts.*/customRequestHandler?: boolean;+ /** Whether the script is a bulk action's, which runs with the processed note as `note`. */+ bulkActionNote?: boolean;}-export default function CodeMirror({ className, content, mime, editorRef: externalEditorRef, containerRef: externalContainerRef, onInitialized, lineWrapping, customRequestHandler, allowKeyboardSuggestions, ...extraOpts }: CodeMirrorProps) {+export default function CodeMirror({ className, content, mime, editorRef: externalEditorRef, containerRef: externalContainerRef, onInitialized, lineWrapping, customRequestHandler, bulkActionNote, allowKeyboardSuggestions, ...extraOpts }: CodeMirrorProps) {const parentRef = useSyncedRef(externalContainerRef);const codeEditorRef = useRef<VanillaCodeMirror | undefined>(undefined);@@ -53,8 +55,11 @@ export default function CodeMirror({ className, content, mime, editorRef: extern// React to custom-request-handler status, which gates the backend api.req/res/pathParams completions.useEffect(() => {- codeEditorRef.current?.setScriptApiContext({ customRequestHandler: !!customRequestHandler });- }, [ customRequestHandler ]);+ codeEditorRef.current?.setScriptApiContext({+ customRequestHandler: !!customRequestHandler,+ bulkActionNote: !!bulkActionNote+ });+ }, [ customRequestHandler, bulkActionNote ]);// React to the language switching between prose and code, which decides whether the// on-screen keyboard is allowed to suggest words.diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Bulk Actions.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Bulk Actions.htmlindex fb6ac8b4e9..449dd906c6 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Bulk Actions.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Bulk Actions.html@@ -214,6 +214,10 @@<ul><li>For more complex scenarios, it is possible to type in a JavaScript expressionin order to apply the necessary changes.</li>+ <li>The script runs on the server once for each note, with that note available+ as <code>note</code> and the backend script API as <code>api</code>. The field+ completes both as you type and underlines mistakes, as the editor of a+ backend script note does.</li><li>Examples:<ul><li>diff --git a/docs/User Guide/User Guide/Advanced Usage/Bulk Actions.md b/docs/User Guide/User Guide/Advanced Usage/Bulk Actions.mdindex ed5fca011f..c11e58dc3b 100644--- a/docs/User Guide/User Guide/Advanced Usage/Bulk Actions.md+++ b/docs/User Guide/User Guide/Advanced Usage/Bulk Actions.md@@ -89,6 +89,7 @@ These actions operate the <a class="reference-link" href="Attributes/Relations.* **Execute script*** For more complex scenarios, it is possible to type in a JavaScript expression in order to apply the necessary changes.+ * The script runs on the server once for each note, with that note available as `note` and the backend script API as `api`. The field completes both as you type and underlines mistakes, as the editor of a backend script note does.* Examples:* To apply a suffix (`- suffix` in this example), to the note title:diff --git a/packages/codemirror/src/type_completion/index.spec.ts b/packages/codemirror/src/type_completion/index.spec.tsindex 7ff81f93e2..17cb9d516c 100644--- a/packages/codemirror/src/type_completion/index.spec.ts+++ b/packages/codemirror/src/type_completion/index.spec.ts@@ -7,11 +7,12 @@ import {renderHoverTooltip,SCRIPT_MIME_BACKEND,SCRIPT_MIME_FRONTEND,- SCRIPT_MIME_JSX+ SCRIPT_MIME_JSX,+ type ScriptApiContext} from "./index.js";/** Returns completions at the `|` marker in `source` (the marker is stripped). */-function completionsAtMarker(mime: string, source: string, context?: { customRequestHandler?: boolean }) {+function completionsAtMarker(mime: string, source: string, context?: ScriptApiContext) {const offset = source.indexOf("|");// Strip exactly the marker at `offset` (not the first `|` in the string, which// may differ if the snippet legitimately contains a `|` operator earlier).@@ -312,6 +313,28 @@ describe("backend note (ScriptBNote) surface", () => {}, TIMEOUT);});+describe("bulk action script (note global)", () => {+ const BULK_ACTION = { bulkActionNote: true };++ it("declares the note being processed as a backend note, next to the api", async () => {+ const names = await completionsAtMarker(SCRIPT_MIME_BACKEND, "note.|", BULK_ACTION);+ expect(names).toContain("setLabel");+ expect(names).toContain("title");++ const codes = await getScriptDiagnosticCodes(+ SCRIPT_MIME_BACKEND,+ "if (note.hasLabel('done')) return;\nnote.title = api.getNote('root')?.title + note.title;",+ BULK_ACTION+ );+ expect(codes).toEqual([]);+ }, TIMEOUT);++ it("declares no note global in other backend scripts", async () => {+ const codes = await getScriptDiagnosticCodes(SCRIPT_MIME_BACKEND, "note.title;");+ expect(codes).toContain(TS_NAME_NOT_FOUND);+ }, TIMEOUT);+});+describe("backend custom request handler api (req/res/pathParams)", () => {const HANDLER = { customRequestHandler: true };diff --git a/packages/codemirror/src/type_completion/index.ts b/packages/codemirror/src/type_completion/index.tsindex 01b2e630de..a5da7c795b 100644--- a/packages/codemirror/src/type_completion/index.ts+++ b/packages/codemirror/src/type_completion/index.ts@@ -41,6 +41,11 @@ export interface ScriptApiContext {* when this is true.*/customRequestHandler?: boolean;+ /**+ * Whether the script is a bulk action's "Execute script", which the server runs once per note+ * with that note in scope as `note`. Declares `note` as a backend note.+ */+ bulkActionNote?: boolean;}/**@@ -156,7 +161,8 @@ async function createEnv(mime: string, context: ScriptApiContext = {}) {const apiType = context.customRequestHandler? "BackendApi": `Omit<BackendApi, ${CUSTOM_REQUEST_HANDLER_MEMBERS.map((m) => `"${m}"`).join(" | ")}>`;- fsMap.set(API_GLOBALS_PATH, `import type { BackendApi } from "./trilium-script-api";\ndeclare global {\n // eslint-disable-next-line no-var\n var api: ${apiType};\n}\n`);+ const noteGlobal = context.bulkActionNote ? " var note: ScriptBNote;\n" : "";+ fsMap.set(API_GLOBALS_PATH, `import type { BackendApi, ScriptBNote } from "./trilium-script-api";\ndeclare global {\n // eslint-disable-next-line no-var\n var api: ${apiType};\n${noteGlobal}}\n`);rootFiles.push(API_TYPES_PATH);}