Skip to content

Build your personal knowledge base with Trilium Notes

Merge remote-tracking branch 'origin/main' into standalone

Elian Doran9b91ba52b8a7
diff --cc .gitignore
index bb746d9ec0,b2b45c35ba..6a649c027d
--- a/.gitignore
+++ b/.gitignore
@@@ -52,5 -52,4 +52,5 @@@ site
apps/*/coverage
scripts/translation/.language*.json
-.claude
+# AI
- .claude/settings.local.json
++.claude
diff --cc CLAUDE.md
index c99e5f74d2,d099f8a964..6be18da69a
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@@ -10,169 -10,118 +10,183 @@@ Trilium Notes is a hierarchical note-ta
## Development Commands
-### Setup
-- `pnpm install` - Install all dependencies
-- `corepack enable` - Enable pnpm if not available
-
-### Running Applications
-- `pnpm run server:start` - Start development server (http://localhost:8080)
-- `pnpm run server:start-prod` - Run server in production mode
-
-### Building
-- `pnpm run client:build` - Build client application
-- `pnpm run server:build` - Build server application
-- `pnpm run electron:build` - Build desktop application
-
-### Testing
-- `pnpm test:all` - Run all tests (parallel + sequential)
-- `pnpm test:parallel` - Run tests that can run in parallel
-- `pnpm test:sequential` - Run tests that must run sequentially (server, ckeditor5-mermaid, ckeditor5-math)
-- `pnpm coverage` - Generate coverage reports
-
-## Architecture Overview
-
-### Monorepo Structure
-- **apps/**: Runnable applications
- - `client/` - Frontend application (shared by server and desktop)
- - `server/` - Node.js server with web interface
- - `desktop/` - Electron desktop application
- - `web-clipper/` - Browser extension for saving web content
- - Additional tools: `db-compare`, `dump-db`, `edit-docs`
-
-- **packages/**: Shared libraries
- - `commons/` - Shared interfaces and utilities
- - `ckeditor5/` - Custom rich text editor with Trilium-specific plugins
- - `codemirror/` - Code editor customizations
- - `highlightjs/` - Syntax highlighting
- - Custom CKEditor plugins: `ckeditor5-admonition`, `ckeditor5-footnotes`, `ckeditor5-math`, `ckeditor5-mermaid`
-
-### Core Architecture Patterns
-
-#### Three-Layer Cache System
-- **Becca** (Backend Cache): Server-side entity cache (`apps/server/src/becca/`)
-- **Froca** (Frontend Cache): Client-side mirror of backend data (`apps/client/src/services/froca.ts`)
-- **Shaca** (Share Cache): Optimized cache for shared/published notes (`apps/server/src/share/`)
-
-#### Entity System
-Core entities are defined in `apps/server/src/becca/entities/`:
-- `BNote` - Notes with content and metadata
-- `BBranch` - Hierarchical relationships between notes (allows multiple parents)
-- `BAttribute` - Key-value metadata attached to notes
-- `BRevision` - Note version history
-- `BOption` - Application configuration
-
-#### Widget-Based UI
-Frontend uses a widget system (`apps/client/src/widgets/`):
-- `BasicWidget` - Base class for all UI components
-- `NoteContextAwareWidget` - Widgets that respond to note changes
-- `RightPanelWidget` - Widgets displayed in the right panel
+```bash
+# Setup
+corepack enable && pnpm install
+
+# Run
+pnpm server:start # Dev server at http://localhost:8080
+pnpm desktop:start # Electron dev app
+pnpm standalone:start # Standalone client dev
+
+# Build
+pnpm client:build # Frontend
+pnpm server:build # Backend
+pnpm desktop:build # Electron
+
+# Test
+pnpm test:all # All tests (parallel + sequential)
+pnpm test:parallel # Client + most package tests
+pnpm test:sequential # Server, ckeditor5-mermaid, ckeditor5-math (shared DB)
+pnpm --filter server test # Single package tests
+pnpm coverage # Coverage reports
+
+# Lint & Format
+pnpm dev:linter-check # ESLint check
+pnpm dev:linter-fix # ESLint fix
+pnpm dev:format-check # Format check (stricter stylistic rules)
+pnpm dev:format-fix # Format fix
+pnpm typecheck # TypeScript type check across all projects
+```
+
+**Running a single test file**: `pnpm --filter server test spec/etapi/search.spec.ts`
+
+## Main Applications
+
+The four main apps share `packages/trilium-core/` for business logic but differ in runtime:
+
+- **client** (`apps/client/`): Preact frontend with jQuery widget system. Shared UI layer used by both server and desktop.
+- **server** (`apps/server/`): Node.js backend (Express, better-sqlite3). Serves the client and provides REST/WebSocket APIs.
+- **desktop** (`apps/desktop/`): Electron wrapper around server + client, running both in a single process.
+- **standalone** (`apps/client-standalone/` + `apps/standalone-desktop/`): Runs the entire stack in the browser — server logic compiled to WASM via sql.js, executed in a service worker. No Node.js dependency at runtime.
+
+## Monorepo Structure
+
+```
+apps/
+ client/ # Preact frontend (shared by server, desktop, standalone)
+ server/ # Node.js backend (Express, better-sqlite3)
+ desktop/ # Electron (bundles server + client)
+ client-standalone/ # Standalone client (WASM + service workers, no Node.js)
+ standalone-desktop/ # Standalone desktop variant
+ web-clipper/ # Browser extension
+ website/ # Project website
+ db-compare/, dump-db/, edit-docs/, build-docs/, icon-pack-builder/
+
+packages/
+ trilium-core/ # Core business logic: entities, services, SQL, sync
+ commons/ # Shared interfaces and utilities
+ trilium-e2e/ # Shared Playwright E2E tests
+ ckeditor5/ # Custom rich text editor bundle
+ codemirror/ # Code editor integration
+ highlightjs/ # Syntax highlighting
+ share-theme/ # Theme for shared/published notes
+ ckeditor5-admonition/, ckeditor5-footnotes/, ckeditor5-math/, ckeditor5-mermaid/
+ ckeditor5-keyboard-marker/, express-partial-content/, pdfjs-viewer/, splitjs/
+ turndown-plugin-gfm/
+```
+
+Use `pnpm --filter <package-name> <command>` to run commands in specific packages.
+
+## Core Architecture
+
+### Three-Layer Cache System
+
+All data access goes through cache layers — never bypass with direct DB queries:
+
+- **Becca** (`packages/trilium-core/src/becca/`): Server-side entity cache. Access via `becca.notes[noteId]`.
+- **Froca** (`apps/client/src/services/froca.ts`): Client-side mirror synced via WebSocket. Access via `froca.getNote()`.
+- **Shaca** (`apps/server/src/share/`): Optimized cache for shared/published notes.
+
+**Critical**: Always use cache methods, not direct DB writes. Cache methods create `EntityChange` records needed for synchronization.
+
+### Entity System
+
+Core entities live in `packages/trilium-core/src/becca/entities/` (not `apps/server/`):
+
+- `BNote` — Notes with content and metadata
+- `BBranch` — Multi-parent tree relationships (cloning supported)
+- `BAttribute` — Key-value metadata (labels and relations)
+- `BRevision` — Version history
+- `BOption` — Application configuration
+- `BBlob` — Binary content storage
+
+Entities extend `AbstractBeccaEntity<T>` with built-in change tracking, hash generation, and date management.
+
+### Entity Change & Sync Protocol
+
+Every entity modification creates an `EntityChange` record driving sync:
+1. Login with HMAC authentication (document secret + timestamp)
+2. Push changes → Pull changes → Push again (conflict resolution)
+3. Content hash verification with retry loop
+
+Sync services: `packages/trilium-core/src/services/sync.ts`, `syncMutexService`, `syncUpdateService`.
+
+### Widget-Based UI
+
+Frontend widgets in `apps/client/src/widgets/`:
+- `BasicWidget` / `TypedBasicWidget` — Base classes (jQuery `this.$widget` for DOM)
+- `NoteContextAwareWidget` — Responds to note changes
+- `RightPanelWidget` — Sidebar widgets with position ordering
- Type-specific widgets in `type_widgets/` directory
+**Widget lifecycle**: `doRenderBody()` for initial render, `refreshWithNote()` for note changes, `entitiesReloadedEvent({loadResults})` for entity updates. Uses jQuery — don't mix React patterns.
+
#### Reusable Preact Components
- Common UI components are available in `apps/client/src/widgets/react/` — prefer reusing these over creating custom implementations:
+ Common UI components are available in `apps/client/src/widgets/react/` — **always** reuse these instead of writing raw HTML elements or custom implementations:
- `NoItems` - Empty state placeholder with icon and message (use for "no results", "too many items", error states)
- `ActionButton` - Consistent button styling with icon support
- - `FormTextBox` - Text input with validation and controlled input handling
+ - `FormTextBox` - Text input with validation and controlled input handling; `FormTextBoxWithUnit` for inputs with a unit suffix (e.g. "mm", "px")
+ - `FormSelect` - Dropdown/combobox taking an object array as data
- `Slider` - Range slider with label
- `Checkbox`, `RadioButton` - Form controls
- `CollapsibleSection` - Expandable content sections
+Fluent builder pattern: `.child()`, `.class()`, `.css()` chaining with position-based ordering.
+
+ **Do not use Bootstrap utility classes** (e.g. `form-control-sm`, `form-select-sm`, `input-group`) on these components — they manage their own styling internally. If you need to adjust sizing or layout, use props provided by the component or CSS custom properties, not Bootstrap overrides.
+
+ #### Component Styling
+ - **Avoid inline styles** — do not use the `style` attribute/prop on JSX elements unless absolutely necessary (e.g. a truly dynamic, computed value that cannot be expressed in CSS). Static layout, sizing, spacing, and visual properties must go in CSS.
+ - **Per-component CSS files**: each component should have a matching `.css` file (e.g. `my_dialog.tsx` → `my_dialog.css`), imported at the top of the component file.
+ - **CSS nesting for scoping**: since CSS modules are not available, scope styles using a root class and native CSS nesting. For example, a dialog with `className="my-dialog"` should have its styles nested under `.modal.my-dialog { … }`.
+ - **Reuse existing components** instead of building custom markup — prefer `FormTextBox`, `FormTextBoxWithUnit`, `FormSelect`, `Slider`, `Button`, etc. over hand-rolled `<input>`, `<select>`, or `<button>` elements.
+
+ #### API Architecture
+ - **Internal API**: REST endpoints in `apps/server/src/routes/api/`
+ - **ETAPI**: External API for third-party integrations (`apps/server/src/etapi/`)
+ - **WebSocket**: Real-time synchronization (`apps/server/src/services/ws.ts`)
+
-### Key Files for Understanding Architecture
+### API Architecture
+
+- **Internal API** (`apps/server/src/routes/api/`): REST endpoints, trusts frontend
+- **ETAPI** (`apps/server/src/etapi/`): External API with basic auth tokens — maintain backwards compatibility
+- **WebSocket** (`apps/server/src/services/ws.ts`): Real-time sync
+
+### Platform Abstraction
+
+`packages/trilium-core/src/services/platform.ts` defines `PlatformProvider` interface with implementations in `apps/desktop/`, `apps/server/`, and `apps/client-standalone/`. Singleton via `initPlatform()`/`getPlatform()`.
-1. **Application Entry Points**:
- - `apps/server/src/main.ts` - Server startup
- - `apps/client/src/desktop.ts` - Client initialization
+**PlatformProvider** provides:
+- `crash(message)` — Platform-specific fatal error handling
+- `getEnv(key)` — Environment variable access (server/desktop use `process.env`, standalone maps URL query params like `?safeMode` → `TRILIUM_SAFE_MODE`)
+- `isElectron`, `isMac`, `isWindows` — Platform detection flags
-2. **Core Services**:
- - `apps/server/src/becca/becca.ts` - Backend data management
- - `apps/client/src/services/froca.ts` - Frontend data synchronization
- - `apps/server/src/services/backend_script_api.ts` - Scripting API
+**Critical rules for `trilium-core`**:
+- **No `process.env` in core** — use `getPlatform().getEnv()` instead (not available in standalone/browser)
+- **No `import path from "path"` in core** — Node's `path` module is externalized in browser builds. Use `packages/trilium-core/src/services/utils/path.ts` for `extname()`/`basename()` equivalents
+- **No Node.js built-in modules in core** — core runs in both Node.js and the browser (standalone). Use platform-agnostic alternatives or platform providers
+- **Platform detection via functions** — `isElectron()`, `isMac()`, `isWindows()` from `utils/index.ts` are functions (not constants) that call `getPlatform()`. They can only be called after `initializeCore()`, not at module top-level. If used in static definitions, wrap in a closure: `value: () => isWindows() ? "0.9" : "1.0"`
+- **Barrel import caution** — `import { x } from "@triliumnext/core"` loads ALL core exports. Early-loading modules like `config.ts` should import specific subpaths (e.g. `@triliumnext/core/src/services/utils/index`) to avoid circular dependencies or initialization ordering issues
+- **Electron IPC** — In desktop mode, client API calls use Electron IPC (not HTTP). The IPC handler in `apps/server/src/routes/electron.ts` must be registered via `utils.isElectron` from the **server's** utils (which correctly checks `process.versions["electron"]`), not from core's utils
-3. **Database Schema**:
- - `apps/server/src/assets/db/schema.sql` - Core database structure
+### Binary Utilities
-4. **Configuration**:
- - `package.json` - Project dependencies and scripts
+Use utilities from `packages/trilium-core/src/services/utils/binary.ts` for string/buffer conversions instead of manual `TextEncoder`/`TextDecoder` or `Buffer.from()` calls:
-## Note Types and Features
+- **`wrapStringOrBuffer(input)`** — Converts `string` to `Uint8Array`, returns `Uint8Array` unchanged. Use when a function expects `Uint8Array` but receives `string | Uint8Array`.
+- **`unwrapStringOrBuffer(input)`** — Converts `Uint8Array` to `string`, returns `string` unchanged. Use when a function expects `string` but receives `string | Uint8Array`.
+- **`encodeBase64(input)`** / **`decodeBase64(input)`** — Base64 encoding/decoding that works in both Node.js and browser.
+- **`encodeUtf8(string)`** / **`decodeUtf8(buffer)`** — UTF-8 encoding/decoding.
-Trilium supports multiple note types, each with specialized widgets:
-- **Text**: Rich text with CKEditor5 (markdown import/export)
-- **Code**: Syntax-highlighted code editing with CodeMirror
-- **File**: Binary file attachments
-- **Image**: Image display with editing capabilities
-- **Canvas**: Drawing/diagramming with Excalidraw
-- **Mermaid**: Diagram generation
-- **Relation Map**: Visual note relationship mapping
-- **Web View**: Embedded web pages
-- **Doc/Book**: Hierarchical documentation structure
+Import via `import { binary_utils } from "@triliumnext/core"` or directly from the module.
-## Development Guidelines
+### Database
+
+SQLite via `better-sqlite3`. SQL abstraction in `packages/trilium-core/src/services/sql/` with `DatabaseProvider` interface, prepared statement caching, and transaction support.
+
+- Schema: `apps/server/src/assets/db/schema.sql`
+- Migrations: `apps/server/src/migrations/YYMMDD_HHMM__description.sql`
### Testing Strategy
- Server tests run sequentially due to shared database
diff --cc apps/build-docs/package.json
index dfaf54bd4c,86d4ceca0f..6868e7c039
--- a/apps/build-docs/package.json
+++ b/apps/build-docs/package.json
@@@ -14,13 -14,9 +14,13 @@@
"keywords": [],
"author": "Elian Doran <[email protected]>",
"license": "AGPL-3.0-only",
- "packageManager": "[email protected]",
+ "packageManager": "[email protected]",
+ "dependencies": {
+ "@triliumnext/core": "workspace:*",
+ "@triliumnext/server": "workspace:*"
+ },
"devDependencies": {
- "@redocly/cli": "2.28.0",
+ "@redocly/cli": "2.29.1",
"archiver": "7.0.1",
"fs-extra": "11.3.4",
"js-yaml": "4.1.1",
diff --cc apps/client/package.json
index 881510f8a2,4cf3fda988..9e806b71a8
--- a/apps/client/package.json
+++ b/apps/client/package.json
@@@ -88,6 -89,7 +89,7 @@@
"happy-dom": "20.9.0",
"lightningcss": "1.32.0",
"script-loader": "0.7.2",
- "vite-plugin-static-copy": "4.0.1"
+ "stylelint": "17.8.0",
+ "vite-plugin-static-copy": "4.1.0"
}
-}
+}
diff --cc apps/client/src/menus/tree_context_menu.ts
index 7b9f22121f,1c7a9dea53..6bbc638adf
--- a/apps/client/src/menus/tree_context_menu.ts
+++ b/apps/client/src/menus/tree_context_menu.ts
@@@ -31,446 -28,339 +31,447 @@@ let lastTargetNode: HTMLElement | null
// so they need to be added manually.
export type TreeCommandNames = FilteredCommandNames<ContextMenuCommandData> | "openBulkActionsDialog" | "searchInSubtree";
-export default class TreeContextMenu implements SelectMenuItemEventListener<TreeCommandNames> {
- private treeWidget: NoteTreeWidget;
- private node: Fancytree.FancytreeNode;
+/**
+ * Tree-agnostic context passed to the shared context-menu builder/handler.
+ * Fancytree's `TreeContextMenu` adapter and the mobile drill-down navigator both
+ * construct one of these from their native representations.
+ */
+export interface TreeContextMenuContext {
+ /** The note the menu is for. */
+ note: FNote;
+ /** The branch used to reach `note` in the current view (parent-to-child relation). */
+ branch: FBranch;
+ /** The note path to the target note in the current view. */
+ notePath: string;
+ /**
+ * Component responsible for dispatching tree commands (e.g. moveNotesTo,
+ * deleteNotes). Fancytree passes the tree widget itself; mobile passes its
+ * own parent component.
+ */
+ component: Component;
+ /** Branches to operate on in bulk-capable commands (defaults to [branch.branchId]). */
+ selectedOrActiveBranchIds?: string[];
+ /** Notes to operate on in bulk-capable commands (defaults to [note.noteId]). */
+ selectedOrActiveNoteIds?: string[];
+ /** Notes to use for archived / conversion-eligibility checks (defaults to [note]). */
+ selectedNotes?: FNote[];
+ /** Whether the note is currently spotlighted (Fancytree only). */
+ isSpotlighted?: boolean;
+ /**
+ * Which surface is showing the menu. Used to suppress items that don't make
+ * sense on a given surface (e.g. `expandSubtree` / `collapseSubtree` have no
+ * meaning in the mobile drill-down navigator). Defaults to `"desktop"`.
+ */
+ target?: "desktop" | "mobile";
+ /**
+ * Invoked right before any command's handler runs. Fancytree uses this to
+ * switch to the detail screen on mobile so dialogs/navigations are visible.
+ */
+ onBeforeCommand?: () => void;
+ /**
+ * Fancytree node for the target, when available. A handful of tree
+ * commands (cut/paste/export/expand/collapse/sort) read `node.data` or call
+ * tree-service helpers that expect a Fancytree node, so we forward it
+ * through the command payload for Fancytree callers. Omitted by mobile.
+ */
+ node?: Fancytree.FancytreeNode;
+}
- constructor(treeWidget: NoteTreeWidget, node: Fancytree.FancytreeNode) {
- this.treeWidget = treeWidget;
- this.node = node;
- }
+/**
+ * Normalize a caller-supplied context into its defaulted form.
+ */
+function resolveContext(ctx: TreeContextMenuContext) {
+ return {
+ ...ctx,
+ selectedOrActiveBranchIds: ctx.selectedOrActiveBranchIds ?? [ctx.branch.branchId],
+ selectedOrActiveNoteIds: ctx.selectedOrActiveNoteIds ?? [ctx.note.noteId],
+ selectedNotes: ctx.selectedNotes ?? [ctx.note],
+ isSpotlighted: ctx.isSpotlighted ?? false,
+ target: ctx.target ?? "desktop"
+ };
+}
- async show(e: PointerEvent | JQuery.TouchStartEvent | JQuery.ContextMenuEvent) {
- await contextMenu.show({
- x: e.pageX ?? 0,
- y: e.pageY ?? 0,
- items: await this.getMenuItems(),
- selectMenuItemHandler: (item, e) => this.selectMenuItemHandler(item),
- onHide: () => {
- lastTargetNode?.classList.remove('fancytree-menu-target');
- }
- });
- // It's placed after show to ensure the old target is cleared before showing the context menu again on repeated right-clicks.
- lastTargetNode?.classList.remove('fancytree-menu-target');
- lastTargetNode = this.node.span;
- lastTargetNode.classList.add('fancytree-menu-target');
- }
+/**
+ * Build the list of context menu items for `ctx`. Callers render via
+ * `contextMenu.show({ items })` and dispatch selections with
+ * `handleTreeContextMenuSelect`.
+ */
+export async function buildTreeContextMenuItems(ctx: TreeContextMenuContext): Promise<MenuItem<TreeCommandNames>[]> {
+ const resolved = resolveContext(ctx);
+ const { note, branch, selectedNotes, isSpotlighted, target } = resolved;
+ const isMobileTarget = target === "mobile";
+
+ const isNotRoot = note.noteId !== "root";
+ const isHoisted = note.noteId === appContext.tabManager.getActiveContext()?.hoistedNoteId;
+ const parentNote = isNotRoot ? await froca.getNote(branch.parentNoteId) : null;
+
+ const isArchived = selectedNotes.every((n) => n.isArchived);
+ const canToggleArchived = !selectedNotes.some((n) => n.isArchived !== isArchived);
+
+ // Multi-select-aware actions are disabled when multiple distinct notes are selected,
+ // the exception being when the only selection is the target itself.
+ const noSelectedNotes = resolved.selectedOrActiveNoteIds.length <= 1
+ || (resolved.selectedOrActiveNoteIds.length === 1 && resolved.selectedOrActiveNoteIds[0] === note.noteId);
+
+ const notSearch = note.type !== "search";
+ const hasSubtreeHidden = note.isLabelTruthy("subtreeHidden") ?? false;
+ const notOptionsOrHelp = !note.noteId.startsWith("_options") && !note.noteId.startsWith("_help");
+ const parentNotSearch = !parentNote || parentNote.type !== "search";
+ const insertNoteAfterEnabled = isNotRoot && !isHoisted && parentNotSearch;
+
+ const items: (MenuItem<TreeCommandNames> | null)[] = [
+ { title: t("tree-context-menu.open-in-a-new-tab"), command: "openInTab", shortcut: "Ctrl+Click", uiIcon: "bx bx-link-external", enabled: noSelectedNotes },
+ { title: t("tree-context-menu.open-in-a-new-split"), command: "openNoteInSplit", uiIcon: "bx bx-dock-right", enabled: noSelectedNotes },
+ { title: t("tree-context-menu.open-in-a-new-window"), command: "openNoteInWindow", uiIcon: "bx bx-window-open", enabled: noSelectedNotes },
+ { title: t("tree-context-menu.open-in-popup"), command: "openNoteInPopup", uiIcon: "bx bx-edit", enabled: noSelectedNotes },
+
+ isHoisted
+ ? null
+ : {
+ title: `${t("tree-context-menu.hoist-note")}`,
+ command: "toggleNoteHoisting",
+ keyboardShortcut: "toggleNoteHoisting",
+ uiIcon: "bx bxs-chevrons-up",
+ enabled: noSelectedNotes && notSearch
+ },
+ !isHoisted || !isNotRoot
+ ? null
+ : { title: t("tree-context-menu.unhoist-note"), command: "toggleNoteHoisting", keyboardShortcut: "toggleNoteHoisting", uiIcon: "bx bx-door-open" },
+
+ { kind: "separator" },
+
+ {
+ title: t("tree-context-menu.insert-note-after"),
+ command: "insertNoteAfter",
+ keyboardShortcut: "createNoteAfter",
+ uiIcon: "bx bx-plus",
+ items: insertNoteAfterEnabled ? await noteTypesService.getNoteTypeItems("insertNoteAfter") : null,
+ enabled: insertNoteAfterEnabled && noSelectedNotes && notOptionsOrHelp,
+ columns: 2
+ },
+
+ {
+ title: t("tree-context-menu.insert-child-note"),
+ command: "insertChildNote",
+ keyboardShortcut: "createNoteInto",
+ uiIcon: "bx bx-plus",
+ items: notSearch ? await noteTypesService.getNoteTypeItems("insertChildNote") : null,
+ enabled: notSearch && noSelectedNotes && notOptionsOrHelp && !hasSubtreeHidden && !isSpotlighted,
+ columns: 2
+ },
+
+ { kind: "separator" },
+
+ { title: t("tree-context-menu.protect-subtree"), command: "protectSubtree", uiIcon: "bx bx-check-shield", enabled: noSelectedNotes },
+
+ { title: t("tree-context-menu.unprotect-subtree"), command: "unprotectSubtree", uiIcon: "bx bx-shield", enabled: noSelectedNotes },
+
+ { kind: "separator" },
+
+ {
+ title: t("tree-context-menu.advanced"),
+ uiIcon: "bx bxs-wrench",
+ enabled: true,
+ items: [
+ { title: t("tree-context-menu.apply-bulk-actions"), command: "openBulkActionsDialog", uiIcon: "bx bx-list-plus", enabled: true },
+
+ { kind: "separator" },
+
+ {
+ title: t("tree-context-menu.edit-branch-prefix"),
+ command: "editBranchPrefix",
+ keyboardShortcut: "editBranchPrefix",
+ uiIcon: "bx bx-rename",
+ enabled: isNotRoot && parentNotSearch && notOptionsOrHelp
+ },
+ {
+ title: t("tree-context-menu.convert-to-attachment"),
+ command: "convertNoteToAttachment",
+ uiIcon: "bx bx-paperclip",
+ enabled: isNotRoot && !isHoisted && notOptionsOrHelp && selectedNotes.some((n) => n.isEligibleForConversionToAttachment())
+ },
- async getMenuItems(): Promise<MenuItem<TreeCommandNames>[]> {
- const note = this.node.data.noteId ? await froca.getNote(this.node.data.noteId) : null;
- const branch = froca.getBranch(this.node.data.branchId);
- const isNotRoot = note?.noteId !== "root";
- const isHoisted = note?.noteId === appContext.tabManager.getActiveContext()?.hoistedNoteId;
- const parentNote = isNotRoot && branch ? await froca.getNote(branch.parentNoteId) : null;
+ { kind: "separator" },
- // some actions don't support multi-note, so they are disabled when notes are selected,
- // the only exception is when the only selected note is the one that was right-clicked, then
- // it's clear what the user meant to do.
- const selNodes = this.treeWidget.getSelectedNodes();
- const selectedNotes = await froca.getNotes(selNodes.map(node => node.data.noteId));
- if (note && !selectedNotes.includes(note)) selectedNotes.push(note);
- const isArchived = selectedNotes.every(note => note.isArchived);
- const canToggleArchived = !selectedNotes.some(note => note.isArchived !== isArchived);
-
- const noSelectedNotes = selNodes.length === 0 || (selNodes.length === 1 && selNodes[0] === this.node);
-
- const notSearch = note?.type !== "search";
- const hasSubtreeHidden = note?.isLabelTruthy("subtreeHidden") ?? false;
- const isSpotlighted = this.node.extraClasses.includes("spotlighted-node");
- const notOptionsOrHelp = !note?.noteId.startsWith("_options") && !note?.noteId.startsWith("_help");
- const parentNotSearch = !parentNote || parentNote.type !== "search";
- const insertNoteAfterEnabled = isNotRoot && !isHoisted && parentNotSearch;
-
- const items: (MenuItem<TreeCommandNames> | null)[] = [
- { title: t("tree-context-menu.open-in-a-new-tab"), command: "openInTab", shortcut: "Ctrl+Click", uiIcon: "bx bx-link-external", enabled: noSelectedNotes },
- { title: t("tree-context-menu.open-in-a-new-split"), command: "openNoteInSplit", uiIcon: "bx bx-dock-right", enabled: noSelectedNotes },
- { title: t("tree-context-menu.open-in-a-new-window"), command: "openNoteInWindow", uiIcon: "bx bx-window-open", enabled: noSelectedNotes },
- { title: t("tree-context-menu.open-in-popup"), command: "openNoteInPopup", uiIcon: "bx bx-edit", enabled: noSelectedNotes },
-
- isHoisted
- ? null
- : {
- title: `${t("tree-context-menu.hoist-note")}`,
- command: "toggleNoteHoisting",
- keyboardShortcut: "toggleNoteHoisting",
- uiIcon: "bx bxs-chevrons-up",
+ !hasSubtreeHidden && !isMobileTarget && { title: t("tree-context-menu.expand-subtree"), command: "expandSubtree", keyboardShortcut: "expandSubtree", uiIcon: "bx bx-expand", enabled: noSelectedNotes },
+ !hasSubtreeHidden && !isMobileTarget && { title: t("tree-context-menu.collapse-subtree"), command: "collapseSubtree", keyboardShortcut: "collapseSubtree", uiIcon: "bx bx-collapse", enabled: noSelectedNotes },
+ {
+ title: hasSubtreeHidden ? t("tree-context-menu.show-subtree") : t("tree-context-menu.hide-subtree"),
+ uiIcon: "bx bx-show",
++ enabled: isNotRoot,
+ handler: async () => {
+ attributes.setBooleanWithInheritance(note, "subtreeHidden", !hasSubtreeHidden);
+ }
+ },
+ {
+ title: t("tree-context-menu.sort-by"),
+ command: "sortChildNotes",
+ keyboardShortcut: "sortChildNotes",
+ uiIcon: "bx bx-sort-down",
enabled: noSelectedNotes && notSearch
},
- !isHoisted || !isNotRoot
- ? null
- : { title: t("tree-context-menu.unhoist-note"), command: "toggleNoteHoisting", keyboardShortcut: "toggleNoteHoisting", uiIcon: "bx bx-door-open" },
-
- { kind: "separator" },
-
- {
- title: t("tree-context-menu.insert-note-after"),
- command: "insertNoteAfter",
- keyboardShortcut: "createNoteAfter",
- uiIcon: "bx bx-plus",
- items: insertNoteAfterEnabled ? await noteTypesService.getNoteTypeItems("insertNoteAfter") : null,
- enabled: insertNoteAfterEnabled && noSelectedNotes && notOptionsOrHelp,
- columns: 2
- },
- {
- title: t("tree-context-menu.insert-child-note"),
- command: "insertChildNote",
- keyboardShortcut: "createNoteInto",
- uiIcon: "bx bx-plus",
- items: notSearch ? await noteTypesService.getNoteTypeItems("insertChildNote") : null,
- enabled: notSearch && noSelectedNotes && notOptionsOrHelp && !hasSubtreeHidden && !isSpotlighted,
- columns: 2
- },
+ { kind: "separator" },
+
+ { title: t("tree-context-menu.copy-note-path-to-clipboard"), command: "copyNotePathToClipboard", uiIcon: "bx bx-directions", enabled: true },
+ { title: t("tree-context-menu.recent-changes-in-subtree"), command: "recentChangesInSubtree", uiIcon: "bx bx-history", enabled: noSelectedNotes && notOptionsOrHelp }
+ ].filter(Boolean) as MenuItem<TreeCommandNames>[]
+ },
+
+ { kind: "separator" },
+
+ {
+ title: t("tree-context-menu.cut"),
+ command: "cutNotesToClipboard",
+ keyboardShortcut: "cutNotesToClipboard",
+ uiIcon: "bx bx-cut",
+ enabled: isNotRoot && !isHoisted && parentNotSearch
+ },
+
+ { title: t("tree-context-menu.copy-clone"), command: "copyNotesToClipboard", keyboardShortcut: "copyNotesToClipboard", uiIcon: "bx bx-copy", enabled: isNotRoot && !isHoisted },
+
+ {
+ title: t("tree-context-menu.paste-into"),
+ command: "pasteNotesFromClipboard",
+ keyboardShortcut: "pasteNotesFromClipboard",
+ uiIcon: "bx bx-paste",
+ enabled: !clipboard.isClipboardEmpty() && notSearch && noSelectedNotes
+ },
+
+ {
+ title: t("tree-context-menu.paste-after"),
+ command: "pasteNotesAfterFromClipboard",
+ uiIcon: "bx bx-paste",
+ enabled: !clipboard.isClipboardEmpty() && isNotRoot && !isHoisted && parentNotSearch && noSelectedNotes
+ },
+
+ {
+ title: t("tree-context-menu.move-to"),
+ command: "moveNotesTo",
+ keyboardShortcut: "moveNotesTo",
+ uiIcon: "bx bx-transfer",
+ enabled: isNotRoot && !isHoisted && parentNotSearch
+ },
+
+ { title: t("tree-context-menu.clone-to"), command: "cloneNotesTo", keyboardShortcut: "cloneNotesTo", uiIcon: "bx bx-duplicate", enabled: isNotRoot && !isHoisted },
+
+ {
+ title: t("tree-context-menu.duplicate"),
+ command: "duplicateSubtree",
+ keyboardShortcut: "duplicateSubtree",
+ uiIcon: "bx bx-outline",
+ enabled: parentNotSearch && isNotRoot && !isHoisted && notOptionsOrHelp
+ },
+
+ {
+ title: !isArchived ? t("tree-context-menu.archive") : t("tree-context-menu.unarchive"),
+ uiIcon: !isArchived ? "bx bx-archive" : "bx bx-archive-out",
+ enabled: canToggleArchived,
+ handler: () => {
+ if (!selectedNotes.length) return;
+
+ if (selectedNotes.length == 1) {
+ const n = selectedNotes[0];
+ if (!isArchived) {
+ attributes.addLabel(n.noteId, "archived");
+ } else {
+ attributes.removeOwnedLabelByName(n, "archived");
+ }
+ } else {
+ const noteIds = selectedNotes.map((n) => n.noteId);
+ if (!isArchived) {
+ executeBulkActions(noteIds, [{
+ name: "addLabel", labelName: "archived"
+ }]);
+ } else {
+ executeBulkActions(noteIds, [{
+ name: "deleteLabel", labelName: "archived"
+ }]);
+ }
+ }
+ }
+ },
+ {
+ title: t("tree-context-menu.delete"),
+ command: "deleteNotes",
+ keyboardShortcut: "deleteNotes",
+ uiIcon: "bx bx-trash destructive-action-icon",
+ enabled: isNotRoot && !isHoisted && parentNotSearch && notOptionsOrHelp
+ },
- { kind: "separator" },
-
- { title: t("tree-context-menu.protect-subtree"), command: "protectSubtree", uiIcon: "bx bx-check-shield", enabled: noSelectedNotes },
-
- { title: t("tree-context-menu.unprotect-subtree"), command: "unprotectSubtree", uiIcon: "bx bx-shield", enabled: noSelectedNotes },
-
- { kind: "separator" },
-
- {
- title: t("tree-context-menu.advanced"),
- uiIcon: "bx bxs-wrench",
- enabled: true,
- items: [
- { title: t("tree-context-menu.apply-bulk-actions"), command: "openBulkActionsDialog", uiIcon: "bx bx-list-plus", enabled: true },
-
- { kind: "separator" },
-
- {
- title: t("tree-context-menu.edit-branch-prefix"),
- command: "editBranchPrefix",
- keyboardShortcut: "editBranchPrefix",
- uiIcon: "bx bx-rename",
- enabled: isNotRoot && parentNotSearch && notOptionsOrHelp
- },
- {
- title:
- t("tree-context-menu.convert-to-attachment"),
- command: "convertNoteToAttachment",
- uiIcon: "bx bx-paperclip",
- enabled: isNotRoot && !isHoisted && notOptionsOrHelp && selectedNotes.some(note => note.isEligibleForConversionToAttachment())
- },
-
- { kind: "separator" },
-
- !hasSubtreeHidden && { title: t("tree-context-menu.expand-subtree"), command: "expandSubtree", keyboardShortcut: "expandSubtree", uiIcon: "bx bx-expand", enabled: noSelectedNotes },
- !hasSubtreeHidden && { title: t("tree-context-menu.collapse-subtree"), command: "collapseSubtree", keyboardShortcut: "collapseSubtree", uiIcon: "bx bx-collapse", enabled: noSelectedNotes },
- {
- title: hasSubtreeHidden ? t("tree-context-menu.show-subtree") : t("tree-context-menu.hide-subtree"),
- uiIcon: "bx bx-show",
- enabled: isNotRoot,
- handler: async () => {
- const note = await froca.getNote(this.node.data.noteId);
- if (!note) return;
- attributes.setBooleanWithInheritance(note, "subtreeHidden", !hasSubtreeHidden);
- }
- },
- {
- title: t("tree-context-menu.sort-by"),
- command: "sortChildNotes",
- keyboardShortcut: "sortChildNotes",
- uiIcon: "bx bx-sort-down",
- enabled: noSelectedNotes && notSearch
- },
-
- { kind: "separator" },
-
- { title: t("tree-context-menu.copy-note-path-to-clipboard"), command: "copyNotePathToClipboard", uiIcon: "bx bx-directions", enabled: true },
- { title: t("tree-context-menu.recent-changes-in-subtree"), command: "recentChangesInSubtree", uiIcon: "bx bx-history", enabled: noSelectedNotes && notOptionsOrHelp }
- ].filter(Boolean) as MenuItem<TreeCommandNames>[]
- },
+ { kind: "separator" },
- { kind: "separator" },
+ (notOptionsOrHelp && selectedNotes.length === 1) ? {
+ kind: "custom",
+ componentFn: () => NoteColorPicker({ note })
+ } : null,
- {
- title: t("tree-context-menu.cut"),
- command: "cutNotesToClipboard",
- keyboardShortcut: "cutNotesToClipboard",
- uiIcon: "bx bx-cut",
- enabled: isNotRoot && !isHoisted && parentNotSearch
- },
+ { kind: "separator" },
- { title: t("tree-context-menu.copy-clone"), command: "copyNotesToClipboard", keyboardShortcut: "copyNotesToClipboard", uiIcon: "bx bx-copy", enabled: isNotRoot && !isHoisted },
+ { title: t("tree-context-menu.import-into-note"), command: "importIntoNote", uiIcon: "bx bx-import", enabled: notSearch && noSelectedNotes && notOptionsOrHelp },
- {
- title: t("tree-context-menu.paste-into"),
- command: "pasteNotesFromClipboard",
- keyboardShortcut: "pasteNotesFromClipboard",
- uiIcon: "bx bx-paste",
- enabled: !clipboard.isClipboardEmpty() && notSearch && noSelectedNotes
- },
+ { title: t("tree-context-menu.export"), command: "exportNote", uiIcon: "bx bx-export", enabled: notSearch && noSelectedNotes && notOptionsOrHelp },
- {
- title: t("tree-context-menu.paste-after"),
- command: "pasteNotesAfterFromClipboard",
- uiIcon: "bx bx-paste",
- enabled: !clipboard.isClipboardEmpty() && isNotRoot && !isHoisted && parentNotSearch && noSelectedNotes
- },
+ { kind: "separator" },
- {
- title: t("tree-context-menu.move-to"),
- command: "moveNotesTo",
- keyboardShortcut: "moveNotesTo",
- uiIcon: "bx bx-transfer",
- enabled: isNotRoot && !isHoisted && parentNotSearch
- },
+ {
+ title: t("tree-context-menu.search-in-subtree"),
+ command: "searchInSubtree",
+ keyboardShortcut: "searchInSubtree",
+ uiIcon: "bx bx-search",
+ enabled: notSearch && noSelectedNotes
+ }
+ ];
- { title: t("tree-context-menu.clone-to"), command: "cloneNotesTo", keyboardShortcut: "cloneNotesTo", uiIcon: "bx bx-duplicate", enabled: isNotRoot && !isHoisted },
+ return items.filter((row) => row !== null) as MenuItem<TreeCommandNames>[];
+}
- {
- title: t("tree-context-menu.duplicate"),
- command: "duplicateSubtree",
- keyboardShortcut: "duplicateSubtree",
- uiIcon: "bx bx-outline",
- enabled: parentNotSearch && isNotRoot && !isHoisted && notOptionsOrHelp
- },
+/**
+ * Dispatch a selection from a tree context menu. Most commands are forwarded via
+ * `ctx.component.triggerCommand`; a handful are handled locally because they
+ * need app-level services or tree-agnostic state.
+ */
+export async function handleTreeContextMenuSelect(
+ item: MenuCommandItem<TreeCommandNames>,
+ ctx: TreeContextMenuContext
+) {
+ const { command, type, mime, templateNoteId } = item;
+ const resolved = resolveContext(ctx);
+ const { note, branch, notePath, component, selectedOrActiveBranchIds, selectedOrActiveNoteIds } = resolved;
+
+ resolved.onBeforeCommand?.();
+
+ if (command === "openInTab") {
+ appContext.tabManager.openTabWithNoteWithHoisting(notePath);
+ } else if (command === "insertNoteAfter") {
+ const parentNotePath = parentNotePathOf(notePath);
+ const parentNote = await froca.getNote(branch.parentNoteId);
+ noteCreateService.createNote(parentNotePath, {
+ target: "after",
+ targetBranchId: branch.branchId,
+ type,
+ mime,
+ isProtected: parentNote?.isProtected ?? false,
+ templateNoteId
+ });
+ } else if (command === "insertChildNote") {
+ noteCreateService.createNote(notePath, {
+ type,
+ mime,
+ isProtected: note.isProtected,
+ templateNoteId
+ });
+ } else if (command === "openNoteInSplit") {
+ const subContexts = appContext.tabManager.getActiveContext()?.getSubContexts();
+ const { ntxId } = subContexts?.[subContexts.length - 1] ?? {};
+
+ component.triggerCommand("openNewNoteSplit", { ntxId, notePath });
+ } else if (command === "openNoteInWindow") {
+ appContext.triggerCommand("openInWindow", {
+ notePath,
+ hoistedNoteId: appContext.tabManager.getActiveContext()?.hoistedNoteId
+ });
+ } else if (command === "openNoteInPopup") {
+ appContext.triggerCommand("openInPopup", { noteIdOrPath: notePath });
+ } else if (command === "convertNoteToAttachment") {
+ if (!(await dialogService.confirm(t("tree-context-menu.convert-to-attachment-confirm")))) {
+ return;
+ }
- {
- title: !isArchived ? t("tree-context-menu.archive") : t("tree-context-menu.unarchive"),
- uiIcon: !isArchived ? "bx bx-archive" : "bx bx-archive-out",
- enabled: canToggleArchived,
- handler: () => {
- if (!selectedNotes.length) return;
-
- if (selectedNotes.length == 1) {
- const note = selectedNotes[0];
- if (!isArchived) {
- attributes.addLabel(note.noteId, "archived");
- } else {
- attributes.removeOwnedLabelByName(note, "archived");
- }
- } else {
- const noteIds = selectedNotes.map(note => note.noteId);
- if (!isArchived) {
- executeBulkActions(noteIds, [{
- name: "addLabel", labelName: "archived"
- }]);
- } else {
- executeBulkActions(noteIds, [{
- name: "deleteLabel", labelName: "archived"
- }]);
- }
- }
- }
- },
- {
- title: t("tree-context-menu.delete"),
- command: "deleteNotes",
- keyboardShortcut: "deleteNotes",
- uiIcon: "bx bx-trash destructive-action-icon",
- enabled: isNotRoot && !isHoisted && parentNotSearch && notOptionsOrHelp
- },
+ let converted = 0;
- { kind: "separator"},
+ for (const noteId of selectedOrActiveNoteIds) {
+ const candidate = await froca.getNote(noteId);
- (notOptionsOrHelp && selectedNotes.length === 1) ? {
- kind: "custom",
- componentFn: () => {
- return NoteColorPicker({note});
- }
- } : null,
+ if (candidate?.isEligibleForConversionToAttachment()) {
+ const { attachment } = await server.post<ConvertToAttachmentResponse>(`notes/${candidate.noteId}/convert-to-attachment`);
- { kind: "separator" },
+ if (attachment) {
+ converted++;
+ }
+ }
+ }
- { title: t("tree-context-menu.import-into-note"), command: "importIntoNote", uiIcon: "bx bx-import", enabled: notSearch && noSelectedNotes && notOptionsOrHelp },
+ toastService.showMessage(t("tree-context-menu.converted-to-attachments", { count: converted }));
+ } else if (command === "copyNotePathToClipboard") {
+ navigator.clipboard.writeText(`#${notePath}`);
+ } else if (command) {
+ component.triggerCommand<TreeCommandNames>(command, {
+ node: resolved.node,
+ notePath,
+ noteId: note.noteId,
+ branchId: branch.branchId,
+ selectedOrActiveBranchIds,
+ selectedOrActiveNoteIds
+ });
+ }
+}
- { title: t("tree-context-menu.export"), command: "exportNote", uiIcon: "bx bx-export", enabled: notSearch && noSelectedNotes && notOptionsOrHelp },
+function parentNotePathOf(notePath: string): string {
+ const idx = notePath.lastIndexOf("/");
+ return idx >= 0 ? notePath.slice(0, idx) : "";
+}
- { kind: "separator" },
+export default class TreeContextMenu implements SelectMenuItemEventListener<TreeCommandNames> {
+ private treeWidget: NoteTreeWidget;
+ private node: Fancytree.FancytreeNode;
- {
- title: t("tree-context-menu.search-in-subtree"),
- command: "searchInSubtree",
- keyboardShortcut: "searchInSubtree",
- uiIcon: "bx bx-search",
- enabled: notSearch && noSelectedNotes
- }
- ];
- return items.filter((row) => row !== null) as MenuItem<TreeCommandNames>[];
+ constructor(treeWidget: NoteTreeWidget, node: Fancytree.FancytreeNode) {
+ this.treeWidget = treeWidget;
+ this.node = node;
}
- async selectMenuItemHandler({ command, type, mime, templateNoteId }: MenuCommandItem<TreeCommandNames>) {
- const notePath = treeService.getNotePath(this.node);
-
- if (utils.isMobile()) {
- this.treeWidget.triggerCommand("setActiveScreen", { screen: "detail" });
- }
+ async show(e: PointerEvent | JQuery.TouchStartEvent | JQuery.ContextMenuEvent) {
+ const ctx = await this.#buildContext();
+ if (!ctx) return;
- if (command === "openInTab") {
- appContext.tabManager.openTabWithNoteWithHoisting(notePath);
- } else if (command === "insertNoteAfter") {
- const parentNotePath = treeService.getNotePath(this.node.getParent());
- const isProtected = treeService.getParentProtectedStatus(this.node);
-
- noteCreateService.createNote(parentNotePath, {
- target: "after",
- targetBranchId: this.node.data.branchId,
- type,
- mime,
- isProtected,
- templateNoteId
- });
- } else if (command === "insertChildNote") {
- const parentNotePath = treeService.getNotePath(this.node);
-
- noteCreateService.createNote(parentNotePath, {
- type,
- mime,
- isProtected: this.node.data.isProtected,
- templateNoteId
- });
- } else if (command === "openNoteInSplit") {
- const subContexts = appContext.tabManager.getActiveContext()?.getSubContexts();
- const { ntxId } = subContexts?.[subContexts.length - 1] ?? {};
-
- this.treeWidget.triggerCommand("openNewNoteSplit", { ntxId, notePath });
- } else if (command === "openNoteInWindow") {
- appContext.triggerCommand("openInWindow", {
- notePath,
- hoistedNoteId: appContext.tabManager.getActiveContext()?.hoistedNoteId
- });
- } else if (command === "openNoteInPopup") {
- appContext.triggerCommand("openInPopup", { noteIdOrPath: notePath });
- } else if (command === "convertNoteToAttachment") {
- if (!(await dialogService.confirm(t("tree-context-menu.convert-to-attachment-confirm")))) {
- return;
+ await contextMenu.show({
+ x: e.pageX ?? 0,
+ y: e.pageY ?? 0,
+ items: await buildTreeContextMenuItems(ctx),
+ selectMenuItemHandler: (item) => handleTreeContextMenuSelect(item, ctx),
+ onHide: () => {
+ lastTargetNode?.classList.remove("fancytree-menu-target");
}
+ });
+ // It's placed after show to ensure the old target is cleared before showing the context menu again on repeated right-clicks.
+ lastTargetNode?.classList.remove("fancytree-menu-target");
+ lastTargetNode = this.node.span;
+ lastTargetNode.classList.add("fancytree-menu-target");
+ }
- let converted = 0;
-
- for (const noteId of this.treeWidget.getSelectedOrActiveNoteIds(this.node)) {
- const note = await froca.getNote(noteId);
+ // Kept so callers using `selectMenuItemHandler` on this instance still work
+ // (e.g. via `SelectMenuItemEventListener`).
+ async selectMenuItemHandler(item: MenuCommandItem<TreeCommandNames>) {
+ const ctx = await this.#buildContext();
+ if (!ctx) return;
+ await handleTreeContextMenuSelect(item, ctx);
+ }
- if (note?.isEligibleForConversionToAttachment()) {
- const { attachment } = await server.post<ConvertToAttachmentResponse>(`notes/${note.noteId}/convert-to-attachment`);
+ async #buildContext(): Promise<TreeContextMenuContext | null> {
+ const note = this.node.data.noteId ? await froca.getNote(this.node.data.noteId) : null;
+ const branch = froca.getBranch(this.node.data.branchId);
+ if (!note || !branch) return null;
- if (attachment) {
- converted++;
- }
+ const selNodes = this.treeWidget.getSelectedNodes();
+ const selectedNotes = await froca.getNotes(selNodes.map((n) => n.data.noteId));
+ if (!selectedNotes.includes(note)) selectedNotes.push(note);
+
+ return {
+ note,
+ branch,
+ notePath: treeService.getNotePath(this.node),
+ component: this.treeWidget,
+ selectedOrActiveBranchIds: this.treeWidget.getSelectedOrActiveBranchIds(this.node),
+ selectedOrActiveNoteIds: this.treeWidget.getSelectedOrActiveNoteIds(this.node),
+ selectedNotes,
+ isSpotlighted: this.node.extraClasses.includes("spotlighted-node"),
+ node: this.node,
+ onBeforeCommand: () => {
+ if (utils.isMobile()) {
+ this.treeWidget.triggerCommand("setActiveScreen", { screen: "detail" });
}
}
-
- toastService.showMessage(t("tree-context-menu.converted-to-attachments", { count: converted }));
- } else if (command === "copyNotePathToClipboard") {
- navigator.clipboard.writeText(`#${ notePath}`);
- } else if (command) {
- this.treeWidget.triggerCommand<TreeCommandNames>(command, {
- node: this.node,
- notePath,
- noteId: this.node.data.noteId,
- selectedOrActiveBranchIds: this.treeWidget.getSelectedOrActiveBranchIds(this.node),
- selectedOrActiveNoteIds: this.treeWidget.getSelectedOrActiveNoteIds(this.node)
- });
- }
+ };
}
}
diff --cc apps/edit-docs/src/utils.ts
index 96c6c906bd,ed0a1fad22..1b5aa4c85b
--- a/apps/edit-docs/src/utils.ts
+++ b/apps/edit-docs/src/utils.ts
@@@ -1,5 -1,5 +1,4 @@@
import cls from "@triliumnext/server/src/services/cls.js";
--import TaskContext from "@triliumnext/server/src/services/task_context.js";
import windowService from "@triliumnext/server/src/services/window.js";
import archiver, { type Archiver } from "archiver";
import electron from "electron";
@@@ -62,9 -62,9 +61,8 @@@ export function startElectron(callback
export async function importData(path: string) {
const buffer = await createImportZip(path);
- const { zipImportService } = (await import("@triliumnext/core"));
- const importService = (await import("@triliumnext/server/src/services/import/zip.js")).default;
++ const { zipImportService, TaskContext, becca } = (await import("@triliumnext/core"));
const context = new TaskContext("no-progress-reporting", "importNotes", null);
-- const becca = (await import("@triliumnext/server/src/becca/becca.js")).default;
const rootNote = becca.getRoot();
if (!rootNote) {
diff --cc apps/server/package.json
index 581c2f5995,b5540d340c..3b42991da5
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@@ -31,16 -30,16 +31,16 @@@
"proxy-nginx-subdir": "docker run --name trilium-nginx-subdir --rm --network=host -v ./docker/nginx.conf:/etc/nginx/conf.d/default.conf:ro nginx:latest"
},
"dependencies": {
- "@ai-sdk/anthropic": "3.0.69",
- "@ai-sdk/google": "3.0.63",
+ "@ai-sdk/anthropic": "3.0.71",
+ "@ai-sdk/google": "3.0.64",
"@ai-sdk/openai": "3.0.53",
"@modelcontextprotocol/sdk": "^1.12.1",
- "ai": "6.0.161",
+ "ai": "6.0.168",
"better-sqlite3": "12.9.0",
"html-to-text": "9.0.5",
+ "i18next-fs-backend": "2.6.3",
+ "i18next": "26.0.5",
"js-yaml": "4.1.1",
- "node-html-parser": "7.1.0",
- "sucrase": "3.35.1",
"unpdf": "1.6.0"
},
"devDependencies": {
@@@ -83,8 -88,9 +83,8 @@@
"debounce": "3.0.0",
"debug": "4.4.3",
"ejs": "5.0.2",
- "electron": "41.2.0",
+ "electron": "41.3.0",
"electron-window-state": "5.0.3",
- "escape-html": "1.0.3",
"express": "5.2.1",
"express-http-proxy": "2.1.2",
"express-openid-connect": "2.20.2",
@@@ -97,7 -103,8 +97,7 @@@
"html2plaintext": "2.1.4",
"http-proxy-agent": "9.0.0",
"https-proxy-agent": "9.0.0",
- "i18next-fs-backend": "2.6.3",
- "i18next": "26.0.6",
+ "i18next-fs-backend": "2.6.4",
"image-type": "6.1.0",
"ini": "6.0.0",
"is-animated": "2.0.2",
@@@ -119,7 -129,9 +119,7 @@@
"time2fa": "1.4.2",
"tmp": "0.2.5",
"turnish": "1.8.0",
- "vite": "8.0.8",
- "unescape": "1.0.1",
+ "vite": "8.0.9",
- "ws": "8.20.0",
"xml2js": "0.6.2",
"yauzl": "3.3.0"
}
diff --cc apps/server/src/services/blob.spec.ts
index 0000000000,0b78e0440d..438b9ae58b
mode 000000,100644..100644
--- a/apps/server/src/services/blob.spec.ts
+++ b/apps/server/src/services/blob.spec.ts
@@@ -1,0 -1,53 +1,51 @@@
++import type { BlobRow } from "@triliumnext/commons";
++import { blob as blobService } from "@triliumnext/core";
+ import { describe, expect, it } from "vitest";
+
-import blobService from "./blob.js";
-import type { Blob } from "./blob-interface.js";
-
+ // These tests lock the exact output of calculateContentHash against known inputs.
+ // The hash is written to entity_changes.hash and shipped to sync peers — any
+ // change to the formula (fields, separators, ordering) silently invalidates
+ // hashes on already-synced blobs, so changes must be deliberate. If a code
+ // change breaks these expectations, update the expected values AND ensure a
+ // migration or sync-compatibility plan is in place.
+ describe("calculateContentHash", () => {
- const baseBlob: Blob = {
++ const baseBlob: Pick<BlobRow, "blobId" | "content" | "textRepresentation"> = {
+ blobId: "blob001",
- content: "hello world",
- utcDateModified: "2026-01-01 00:00:00.000Z"
++ content: "hello world"
+ };
+
+ it("hashes a blob without textRepresentation to the locked value (no trailing separator)", () => {
+ // Must match hash("blobId|content") — same formula used before
+ // textRepresentation existed, so pre-OCR blobs don't re-hash on upgrade.
+ expect(blobService.calculateContentHash(baseBlob)).toBe("dyhIZrQHB3Bb1bhcZVPld8Q6ONU=");
+ });
+
+ it("hashes a blob with textRepresentation to the locked value", () => {
+ expect(blobService.calculateContentHash({ ...baseBlob, textRepresentation: "OCR result" }))
+ .toBe("CsMYMZbvYJtrGVGJwxnr5w6KbMg=");
+ });
+
+ it("treats undefined, null, and empty-string textRepresentation identically", () => {
+ const undefinedHash = blobService.calculateContentHash(baseBlob);
+ const nullHash = blobService.calculateContentHash({ ...baseBlob, textRepresentation: null });
+ const emptyHash = blobService.calculateContentHash({ ...baseBlob, textRepresentation: "" });
+ expect(nullHash).toBe(undefinedHash);
+ expect(emptyHash).toBe(undefinedHash);
+ });
+
+ it("produces different hashes for different blobIds, content, and textRepresentation", () => {
+ const base = blobService.calculateContentHash(baseBlob);
+ const diffId = blobService.calculateContentHash({ ...baseBlob, blobId: "blob002" });
+ const diffContent = blobService.calculateContentHash({ ...baseBlob, content: "other" });
+ const diffTextRep = blobService.calculateContentHash({ ...baseBlob, textRepresentation: "x" });
+ expect(diffId).not.toBe(base);
+ expect(diffContent).not.toBe(base);
+ expect(diffTextRep).not.toBe(base);
+ });
+
+ it("hashes string and equivalent Buffer content identically", () => {
+ const stringHash = blobService.calculateContentHash(baseBlob);
+ const bufferHash = blobService.calculateContentHash({ ...baseBlob, content: Buffer.from("hello world") });
+ expect(bufferHash).toBe(stringHash);
+ });
+ });
diff --cc apps/server/src/share/content_renderer.ts
index 0a10eeea93,98c480b466..58d3e43e44
--- a/apps/server/src/share/content_renderer.ts
+++ b/apps/server/src/share/content_renderer.ts
@@@ -1,5 -1,5 +1,5 @@@
- import { renderSpreadsheetToHtml } from "@triliumnext/commons";
-import { sanitizeUrl } from "@braintree/sanitize-url";
+ import { renderSpreadsheetToHtml, renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons";
+import { icon_packs as iconPackService, sanitize, utils } from "@triliumnext/core";
import { highlightAuto } from "@triliumnext/highlightjs";
import ejs from "ejs";
import escapeHtml from "escape-html";
@@@ -450,6 -454,38 +452,38 @@@ function cleanUpReferenceLinks(linkEl:
}
}
+ /**
+ * Renders a markdown code note by converting the markdown source to HTML
+ * using the shared {@link renderMarkdownToHtml} pipeline.
+ */
+ function renderMarkdown(result: Result, note: SNote | BNote) {
+ if (typeof result.content !== "string" || !result.content?.trim()) {
+ result.isEmpty = true;
+ return;
+ }
+
- let html = renderMarkdownToHtml(result.content, note.title, {
- sanitize: htmlSanitizer.sanitize,
++ const html = renderMarkdownToHtml(result.content, note.title, {
++ sanitize: sanitize.sanitizeHtml,
+ wikiLink: { formatHref: (id) => `./${id}` }
+ });
+
+ // Apply syntax highlighting to code blocks, same as renderText.
+ const parseOpts: Partial<Options> = { blockTextElements: {} };
+ const document = parse(html, parseOpts);
+ for (const codeEl of document.querySelectorAll("pre code")) {
+ if (codeEl.classList.contains("language-mermaid")
+ || codeEl.classList.contains("language-text-x-trilium-auto")) {
+ continue;
+ }
+
+ const highlightResult = highlightAuto(codeEl.text);
+ codeEl.innerHTML = highlightResult.value;
+ codeEl.classList.add("hljs");
+ }
+
+ result.content = document.innerHTML;
+ }
+
/**
* Renders a code note.
*/
diff --cc packages/trilium-core/src/services/blob.ts
index caa4952121,9de3758ff5..490e27a9fa
--- a/packages/trilium-core/src/services/blob.ts
+++ b/packages/trilium-core/src/services/blob.ts
@@@ -38,21 -37,22 +38,22 @@@ function processContent(content: Uint8A
}
if (isStringContent) {
- return content === null ? "" : content.toString("utf-8");
- } else {
- // see https://github.com/zadam/trilium/issues/3523
- // IIRC a zero-sized buffer can be returned as null from the database
- if (content === null) {
- // this will force de/encryption
- content = Buffer.alloc(0);
- }
-
- return content;
+ if (content === null) return "";
+ return decodeUtf8(content);
}
+ // see https://github.com/zadam/trilium/issues/3523
+ // IIRC a zero-sized buffer can be returned as null from the database
+ if (content === null) {
+ // this will force de/encryption
+ content = new Uint8Array(0);
+ }
+
+ return content;
}
-function calculateContentHash({ blobId, content, textRepresentation }: Blob) {
+function calculateContentHash({ blobId, content, textRepresentation }: Pick<BlobRow, "blobId" | "content" | "textRepresentation">) {
- return hash(`${blobId}|${content.toString()}|${textRepresentation ?? ""}`);
+ const textRepresentationSegment = textRepresentation ? `|${textRepresentation}` : "";
+ return hash(`${blobId}|${content.toString()}${textRepresentationSegment}`);
}
export default {
diff --cc packages/trilium-core/src/services/handlers.ts
index f5b701825b,0000000000..0ad5d22286
mode 100644,000000..100644
--- a/packages/trilium-core/src/services/handlers.ts
+++ b/packages/trilium-core/src/services/handlers.ts
@@@ -1,251 -1,0 +1,251 @@@
+import eventService from "./events.js";
+import scriptService from "./script.js";
+import treeService from "./tree.js";
+import noteService from "./notes.js";
+import becca from "../becca/becca.js";
+import BAttribute from "../becca/entities/battribute.js";
+import hiddenSubtreeService from "./hidden_subtree.js";
+import oneTimeTimer from "./one_time_timer.js";
+import type BNote from "../becca/entities/bnote.js";
+import type AbstractBeccaEntity from "../becca/entities/abstract_becca_entity.js";
+import { DefinitionObject } from "@triliumnext/commons";
+
+type Handler = (definition: DefinitionObject, note: BNote, targetNote: BNote) => void;
+
+function runAttachedRelations(note: BNote, relationName: string, originEntity: AbstractBeccaEntity<any>) {
+ if (!note) {
+ return;
+ }
+
+ // the same script note can get here with multiple ways, but execute only once
+ const notesToRun = new Set(
+ note
+ .getRelations(relationName)
+ .map((relation) => relation.getTargetNote())
+ .filter((note) => !!note) as BNote[]
+ );
+
+ for (const noteToRun of notesToRun) {
+ scriptService.executeNoteNoException(noteToRun, { originEntity });
+ }
+}
+
+eventService.subscribe(eventService.NOTE_TITLE_CHANGED, (note) => {
+ runAttachedRelations(note, "runOnNoteTitleChange", note);
+
+ if (!note.isRoot()) {
+ const noteFromCache = becca.notes[note.noteId];
+
+ if (!noteFromCache) {
+ return;
+ }
+
+ for (const parentNote of noteFromCache.parents) {
+ if (parentNote.hasLabel("sorted")) {
+ treeService.sortNotesIfNeeded(parentNote.noteId);
+ }
+ }
+ }
+});
+
+eventService.subscribe([eventService.ENTITY_CHANGED, eventService.ENTITY_DELETED], ({ entityName, entity }) => {
+ if (entityName === "attributes") {
+ runAttachedRelations(entity.getNote(), "runOnAttributeChange", entity);
+
+ if (entity.type === "label" && ["sorted", "sortDirection", "sortFoldersFirst", "sortNatural", "sortLocale"].includes(entity.name)) {
+ handleSortedAttribute(entity);
+ } else if (entity.type === "label") {
+ handleMaybeSortingLabel(entity);
+ }
+ } else if (entityName === "notes") {
+ // ENTITY_DELETED won't trigger anything since all branches/attributes are already deleted at this point
+ runAttachedRelations(entity, "runOnNoteChange", entity);
+ }
+});
+
+eventService.subscribe(eventService.ENTITY_CHANGED, ({ entityName, entity }) => {
+ if (entityName === "branches") {
+ const parentNote = becca.getNote(entity.parentNoteId);
+
+ if (parentNote?.hasLabel("sorted")) {
+ treeService.sortNotesIfNeeded(parentNote.noteId);
+ }
+
+ const childNote = becca.getNote(entity.noteId);
+
+ if (childNote) {
+ runAttachedRelations(childNote, "runOnBranchChange", entity);
+ }
+ }
+});
+
+eventService.subscribe(eventService.NOTE_CONTENT_CHANGE, ({ entity }) => {
+ runAttachedRelations(entity, "runOnNoteContentChange", entity);
+});
+
+eventService.subscribe(eventService.ENTITY_CREATED, ({ entityName, entity }) => {
+ if (entityName === "attributes") {
+ runAttachedRelations(entity.getNote(), "runOnAttributeCreation", entity);
+
+ if (entity.type === "relation" && entity.name === "template") {
+ const note = becca.getNote(entity.noteId);
+ if (!note) {
+ return;
+ }
+
+ const templateNote = becca.getNote(entity.value);
+
+ if (!templateNote) {
+ return;
+ }
+
+ const content = note.getContent();
+
+ if (
- ["text", "code", "mermaid", "canvas", "relationMap", "mindMap", "webView"].includes(note.type) &&
++ note.hasStringContent() &&
+ typeof content === "string" &&
+ // if the note has already content we're not going to overwrite it with template's one
+ (!content || content.trim().length === 0) &&
+ templateNote.hasStringContent()
+ ) {
+ const templateNoteContent = templateNote.getContent();
+
+ if (templateNoteContent) {
+ note.setContent(templateNoteContent);
+ }
+
+ note.type = templateNote.type;
+ note.mime = templateNote.mime;
+ note.save();
+ }
+
+ // we'll copy the children notes only if there's none so far
+ // this protects against e.g. multiple assignment of template relation resulting in having multiple copies of the subtree
+ if (note.getChildNotes().length === 0 && !note.isDescendantOfNote(templateNote.noteId)) {
+ noteService.duplicateSubtreeWithoutRoot(templateNote.noteId, note.noteId);
+ }
+ } else if (entity.type === "label" && ["sorted", "sortDirection", "sortFoldersFirst", "sortNatural", "sortLocale"].includes(entity.name)) {
+ handleSortedAttribute(entity);
+ } else if (entity.type === "label") {
+ handleMaybeSortingLabel(entity);
+ }
+ } else if (entityName === "branches") {
+ runAttachedRelations(entity.getNote(), "runOnBranchCreation", entity);
+
+ if (entity.parentNote?.hasLabel("sorted")) {
+ treeService.sortNotesIfNeeded(entity.parentNoteId);
+ }
+ } else if (entityName === "notes") {
+ runAttachedRelations(entity, "runOnNoteCreation", entity);
+ }
+});
+
+eventService.subscribe(eventService.CHILD_NOTE_CREATED, ({ parentNote, childNote }) => {
+ runAttachedRelations(parentNote, "runOnChildNoteCreation", childNote);
+});
+
+function processInverseRelations(entityName: string, entity: BAttribute, handler: Handler) {
+ if (entityName === "attributes" && entity.type === "relation") {
+ const note = entity.getNote();
+ const relDefinitions = note.getLabels(`relation:${entity.name}`);
+
+ for (const relDefinition of relDefinitions) {
+ const definition = relDefinition.getDefinition();
+
+ if (definition.inverseRelation && definition.inverseRelation.trim()) {
+ const targetNote = entity.getTargetNote();
+
+ if (targetNote) {
+ handler(definition, note, targetNote);
+ }
+ }
+ }
+ }
+}
+
+function handleSortedAttribute(entity: BAttribute) {
+ treeService.sortNotesIfNeeded(entity.noteId);
+
+ if (entity.isInheritable) {
+ const note = becca.notes[entity.noteId];
+
+ if (note) {
+ for (const noteId of note.getSubtreeNoteIds()) {
+ treeService.sortNotesIfNeeded(noteId);
+ }
+ }
+ }
+}
+
+function handleMaybeSortingLabel(entity: BAttribute) {
+ // check if this label is used for sorting, if yes force re-sort
+ const note = becca.notes[entity.noteId];
+
+ // this will not work on deleted notes, but in that case we don't really need to re-sort
+ if (note) {
+ for (const parentNote of note.getParentNotes()) {
+ const sorted = parentNote.getLabelValue("sorted");
+ if (sorted === null) {
+ // checking specifically for null since that means the label doesn't exist
+ // empty valued "sorted" is still valid
+ continue;
+ }
+
+ if (
+ sorted.includes(entity.name) || // hacky check if this label is used in the sort
+ entity.name === "top" ||
+ entity.name === "bottom"
+ ) {
+ treeService.sortNotesIfNeeded(parentNote.noteId);
+ }
+ }
+ }
+}
+
+eventService.subscribe(eventService.ENTITY_CHANGED, ({ entityName, entity }) => {
+ processInverseRelations(entityName, entity, (definition, note, targetNote) => {
+ // we need to make sure that also target's inverse attribute exists and if not, then create it
+ // inverse attribute has to target our note as well
+ const hasInverseAttribute = targetNote.getRelations(definition.inverseRelation).some((attr) => attr.value === note.noteId);
+
+ if (!hasInverseAttribute) {
+ new BAttribute({
+ noteId: targetNote.noteId,
+ type: "relation",
+ name: definition.inverseRelation || "",
+ value: note.noteId,
+ isInheritable: entity.isInheritable
+ }).save();
+
+ // becca will not be updated before we'll check from the other side which would create infinite relation creation (#2269)
+ targetNote.invalidateThisCache();
+ }
+ });
+});
+
+eventService.subscribe(eventService.ENTITY_DELETED, ({ entityName, entity }) => {
+ processInverseRelations(entityName, entity, (definition: DefinitionObject, note: BNote, targetNote: BNote) => {
+ // if one inverse attribute is deleted, then the other should be deleted as well
+ const relations = targetNote.getOwnedRelations(definition.inverseRelation);
+
+ for (const relation of relations) {
+ if (relation.value === note.noteId) {
+ relation.markAsDeleted();
+ }
+ }
+ });
+
+ if (entityName === "branches") {
+ runAttachedRelations(entity.getNote(), "runOnBranchDeletion", entity);
+ }
+
+ if (entityName === "notes" && entity.noteId.startsWith("_")) {
+ // "named" note has been deleted, we will probably need to rebuild the hidden subtree
+ // scheduling so that bulk deletes won't trigger so many checks
+ oneTimeTimer.scheduleExecution("hidden-subtree-check", 1000, () => hiddenSubtreeService.checkHiddenSubtree());
+ }
+});
+
+export default {
+ runAttachedRelations
+};
diff --cc packages/trilium-core/src/services/notes.ts
index 2ecd711f5e,0000000000..5a34282615
mode 100644,000000..100644
--- a/packages/trilium-core/src/services/notes.ts
+++ b/packages/trilium-core/src/services/notes.ts
@@@ -1,1185 -1,0 +1,1205 @@@
- import { type AttachmentRow, type AttributeRow, type BranchRow, dayjs, type NoteRow, NoteType } from "@triliumnext/commons";
++import { type AttachmentRow, type AttributeRow, type BranchRow, dayjs, type NoteRow, type NoteType } from "@triliumnext/commons";
+import fs from "fs";
+import html2plaintext from "html2plaintext";
+import { t } from "i18next";
+import url from "url";
+
+import becca from "../becca/becca.js";
+import BAttachment from "../becca/entities/battachment.js";
+import BAttribute from "../becca/entities/battribute.js";
+import BBranch from "../becca/entities/bbranch.js";
+import BNote from "../becca/entities/bnote.js";
- import log, { getLog } from "../services/log.js";
++import { ValidationError } from "../errors.js";
++import { getLog } from "../services/log.js";
+import protectedSessionService from "../services/protected_session.js";
- import { newEntityId, quoteRegex, toMap, unescapeHtml } from "./utils/index.js";
- import date_utils from "./utils/date.js";
++import * as cls from "./context.js";
+import entityChangesService from "./entity_changes.js";
+import eventService from "./events.js";
+import imageService from "./image.js";
+import noteTypesService from "./note_types.js";
+import optionService from "./options.js";
+import request from "./request.js";
+import revisionService from "./revisions.js";
++import { sanitizeHtml } from "./sanitizer.js";
++import { getSql } from "./sql/index.js";
+import type TaskContext from "./task_context.js";
- import ws from "./ws.js";
+import { decodeBase64 } from "./utils/binary.js";
- import { getSql } from "./sql/index.js";
- import { sanitizeHtml } from "./sanitizer.js";
- import { ValidationError } from "../errors.js";
- import * as cls from "./context.js";
++import date_utils from "./utils/date.js";
++import { newEntityId, quoteRegex, toMap, unescapeHtml } from "./utils/index.js";
+import { basename } from "./utils/path.js";
++import ws from "./ws.js";
+
+interface FoundLink {
+ name: "imageLink" | "internalLink" | "includeNoteLink" | "relationMapLink";
+ value: string;
+}
+
+interface Attachment {
+ attachmentId?: string;
+ title: string;
+}
+
+export interface NoteParams {
+ /** optionally can force specific noteId */
+ noteId?: string;
+ branchId?: string;
+ parentNoteId: string;
+ templateNoteId?: string;
+ title: string;
+ content: string | Uint8Array;
+ /** text, code, file, image, search, book, relationMap, canvas, webView */
+ type: NoteType;
+ /** default value is derived from default mimes for type */
+ mime?: string;
+ /** default is false */
+ isProtected?: boolean;
+ /** default is false */
+ isExpanded?: boolean;
+ /** default is empty string */
+ prefix?: string;
+ /** default is the last existing notePosition in a parent + 10 */
+ notePosition?: number;
+ dateCreated?: string;
+ utcDateCreated?: string;
+ ignoreForbiddenParents?: boolean;
+ target?: "into";
+ /** Attributes to be set on the note. These are set atomically on note creation, so entity changes are not sent for attributes defined here. */
+ attributes?: Omit<AttributeRow, "noteId" | "attributeId">[];
+}
+
+function getNewNotePosition(parentNote: BNote) {
+ if (parentNote.isLabelTruthy("newNotesOnTop")) {
+ const minNotePos = parentNote
+ .getChildBranches()
+ .filter((branch) => branch?.noteId !== "_hidden") // has "always last" note position
+ .reduce((min, note) => Math.min(min, note?.notePosition || 0), 0);
+
+ return minNotePos - 10;
+ }
+ const maxNotePos = parentNote
+ .getChildBranches()
+ .filter((branch) => branch?.noteId !== "_hidden") // has "always last" note position
+ .reduce((max, note) => Math.max(max, note?.notePosition || 0), 0);
+
+ return maxNotePos + 10;
+}
+
+function triggerNoteTitleChanged(note: BNote) {
+ eventService.emit(eventService.NOTE_TITLE_CHANGED, note);
+}
+
+function deriveMime(type: string, mime?: string) {
+ if (!type) {
+ throw new Error(`Note type is a required param`);
+ }
+
+ if (mime) {
+ return mime;
+ }
+
+ return noteTypesService.getDefaultMimeForNoteType(type);
+}
+
+function copyChildAttributes(parentNote: BNote, childNote: BNote) {
+ for (const attr of parentNote.getAttributes()) {
+ if (attr.name.startsWith("child:")) {
+ const name = attr.name.substring(6);
+ const hasAlreadyTemplate = childNote.hasRelation("template");
+
+ if (hasAlreadyTemplate && attr.type === "relation" && name === "template") {
+ // if the note already has a template, it means the template was chosen by the user explicitly
+ // in the menu. In that case, we should override the default templates defined in the child: attrs
+ continue;
+ }
+
+ new BAttribute({
+ noteId: childNote.noteId,
+ type: attr.type,
+ name,
+ value: attr.value,
+ position: attr.position,
+ isInheritable: attr.isInheritable
+ }).save();
+ }
+ }
+}
+
+function copyAttachments(origNote: BNote, newNote: BNote) {
+ for (const attachment of origNote.getAttachments()) {
+ if (attachment.role === "image") {
+ // Handled separately, see `checkImageAttachments`.
+ continue;
+ }
+
+ const newAttachment = new BAttachment({
+ ...attachment,
+ attachmentId: undefined,
+ ownerId: newNote.noteId
+ });
+
+ newAttachment.save();
+ }
+}
+
+function getNewNoteTitle(parentNote: BNote) {
+ let title = t("notes.new-note");
+
+ const titleTemplate = parentNote.getLabelValue("titleTemplate");
+
+ if (titleTemplate !== null) {
+ try {
+ const now = dayjs(date_utils.localNowDateTime() || new Date());
+
+ // "officially" injected values:
+ // - now
+ // - parentNote
+
+ title = eval(`\`${titleTemplate}\``);
+ } catch (e: any) {
+ getLog().error(`Title template of note '${parentNote.noteId}' failed with: ${e.message}`);
+ }
+ }
+
+ // this isn't in theory a good place to sanitize title, but this will catch a lot of XSS attempts.
+ // title is supposed to contain text only (not HTML) and be printed text only, but given the number of usages,
+ // it's difficult to guarantee correct handling in all cases
+ title = sanitizeHtml(title);
+
+ return title;
+}
+
+interface GetValidateParams {
+ parentNoteId: string;
+ type: string;
+ ignoreForbiddenParents?: boolean;
+}
+
+function getAndValidateParent(params: GetValidateParams) {
+ const parentNote = becca.notes[params.parentNoteId];
+
+ if (!parentNote) {
+ throw new ValidationError(`Parent note '${params.parentNoteId}' was not found.`);
+ }
+
+ if (parentNote.type === "launcher" && parentNote.noteId !== "_lbBookmarks") {
+ throw new ValidationError(`Creating child notes into launcher notes is not allowed.`);
+ }
+
+ if (["_lbAvailableLaunchers", "_lbVisibleLaunchers"].includes(params.parentNoteId) && params.type !== "launcher") {
+ throw new ValidationError(`Only 'launcher' notes can be created in parent '${params.parentNoteId}'`);
+ }
+
+ if (!params.ignoreForbiddenParents) {
+ if (["_lbRoot", "_hidden"].includes(parentNote.noteId)
+ || parentNote.noteId.startsWith("_lbTpl")
+ || parentNote.noteId.startsWith("_help")
+ || parentNote.isOptions()) {
+ throw new ValidationError(`Creating child notes into '${parentNote.noteId}' is not allowed.`);
+ }
+ }
+
+ return parentNote;
+}
+
+function createNewNote(params: NoteParams): {
+ note: BNote;
+ branch: BBranch;
+} {
+ const parentNote = getAndValidateParent(params);
+
+ if (params.title === null || params.title === undefined) {
+ params.title = getNewNoteTitle(parentNote);
+ }
+
+ if (params.content === null || params.content === undefined) {
+ throw new Error(`Note content must be set`);
+ }
+
+ let error;
+ if ((error = date_utils.validateLocalDateTime(params.dateCreated))) {
+ throw new Error(error);
+ }
+
+ if ((error = date_utils.validateUtcDateTime(params.utcDateCreated))) {
+ throw new Error(error);
+ }
+
++ // When creating from a template, inherit the template's type and mime if not explicitly provided.
++ // This ensures binary types (PDF, images, etc.) get the correct mime from the start.
++ if (params.templateNoteId) {
++ const templateNote = becca.getNote(params.templateNoteId);
++ if (templateNote) {
++ if (!params.mime) {
++ params.mime = templateNote.mime;
++ }
++ }
++ }
++
+ return getSql().transactional(() => {
+ let note, branch, isEntityEventsDisabled;
+
+ try {
+ isEntityEventsDisabled = cls.isEntityEventsDisabled();
+
+ if (!isEntityEventsDisabled) {
+ // it doesn't make sense to run note creation events on a partially constructed note, so
+ // defer them until note creation is completed
+ cls.disableEntityEvents();
+ }
+
+ // TODO: think about what can happen if the note already exists with the forced ID
+ // I guess on DB it's going to be fine, but becca references between entities
+ // might get messed up (two note instances for the same ID existing in the references)
+ note = new BNote({
+ noteId: params.noteId, // optionally can force specific noteId
+ title: params.title,
+ isProtected: !!params.isProtected,
+ type: params.type,
+ mime: deriveMime(params.type, params.mime),
+ dateCreated: params.dateCreated,
+ utcDateCreated: params.utcDateCreated
+ }).save();
+
+ // Create attributes atomically.
+ for (const attribute of params.attributes || []) {
+ new BAttribute({
+ ...attribute,
+ noteId: note.noteId
+ }).save();
+ }
+
+ note.setContent(params.content);
+
+ branch = new BBranch({
+ noteId: note.noteId,
+ parentNoteId: params.parentNoteId,
+ notePosition: params.notePosition !== undefined ? params.notePosition : getNewNotePosition(parentNote),
+ prefix: params.prefix || "",
+ isExpanded: !!params.isExpanded
+ }).save();
+ } finally {
+ if (!isEntityEventsDisabled) {
+ // re-enable entity events only if they were previously enabled
+ // (they can be disabled in case of import)
+ cls.enableEntityEvents();
+ }
+ }
+
+ if (params.templateNoteId) {
+ const templateNote = becca.getNote(params.templateNoteId);
+ if (!templateNote) {
+ throw new Error(`Template note '${params.templateNoteId}' does not exist.`);
+ }
+
++ // for binary content types (PDF, images, etc.), copy the template's content directly
++ // since the event handler in handlers.ts only handles string content
++ if (!templateNote.hasStringContent()) {
++ const templateContent = templateNote.getContent();
++ if (templateContent) {
++ note.setContent(templateContent);
++ }
++ }
++
+ note.addRelation("template", params.templateNoteId);
+ copyAttachments(templateNote, note);
+
+ // no special handling for ~inherit since it doesn't matter if it's assigned with the note creation or later
+ }
+
+ copyChildAttributes(parentNote, note);
+
+ eventService.emit(eventService.ENTITY_CREATED, { entityName: "notes", entity: note });
+ eventService.emit(eventService.ENTITY_CHANGED, { entityName: "notes", entity: note });
+ triggerNoteTitleChanged(note);
+ // blobs entity doesn't use "created" event
+ eventService.emit(eventService.ENTITY_CHANGED, { entityName: "blobs", entity: note });
+ eventService.emit(eventService.ENTITY_CREATED, { entityName: "branches", entity: branch });
+ eventService.emit(eventService.ENTITY_CHANGED, { entityName: "branches", entity: branch });
+ eventService.emit(eventService.CHILD_NOTE_CREATED, { childNote: note, parentNote });
+
+ getLog().info(`Created new note '${note.noteId}', branch '${branch.branchId}' of type '${note.type}', mime '${note.mime}'`);
+
+ return {
+ note,
+ branch
+ };
+ });
+}
+
+function createNewNoteWithTarget(target: "into" | "after" | "before", targetBranchId: string | undefined, params: NoteParams) {
+ if (!params.type) {
+ const parentNote = becca.notes[params.parentNoteId];
+
+ // code note type can be inherited, otherwise "text" is the default
+ params.type = parentNote.type === "code" ? "code" : "text";
+ params.mime = parentNote.type === "code" ? parentNote.mime : "text/html";
+ }
+
+ if (target === "into") {
+ return createNewNote(params);
+ } else if (target === "after" && targetBranchId) {
+ const afterBranch = becca.branches[targetBranchId];
+
+ // not updating utcDateModified to avoid having to sync whole rows
+ getSql().execute("UPDATE branches SET notePosition = notePosition + 10 WHERE parentNoteId = ? AND notePosition > ? AND isDeleted = 0", [params.parentNoteId, afterBranch.notePosition]);
+
+ params.notePosition = afterBranch.notePosition + 10;
+
+ const retObject = createNewNote(params);
+
+ entityChangesService.putNoteReorderingEntityChange(params.parentNoteId);
+
+ return retObject;
+ } else if (target === "before" && targetBranchId) {
+ const beforeBranch = becca.branches[targetBranchId];
+
+ // not updating utcDateModified to avoid having to sync whole rows
+ getSql().execute("UPDATE branches SET notePosition = notePosition - 10 WHERE parentNoteId = ? AND notePosition < ? AND isDeleted = 0", [params.parentNoteId, beforeBranch.notePosition]);
+
+ params.notePosition = beforeBranch.notePosition - 10;
+
+ const retObject = createNewNote(params);
+
+ entityChangesService.putNoteReorderingEntityChange(params.parentNoteId);
+
+ return retObject;
+ }
+ throw new Error(`Unknown target '${target}'`);
+}
+
+function protectNoteRecursively(note: BNote, protect: boolean, includingSubTree: boolean, taskContext: TaskContext<"protectNotes">) {
+ protectNote(note, protect);
+
+ taskContext.increaseProgressCount();
+
+ if (includingSubTree) {
+ for (const child of note.getChildNotes()) {
+ protectNoteRecursively(child, protect, includingSubTree, taskContext);
+ }
+ }
+}
+
+function protectNote(note: BNote, protect: boolean) {
+ if (!protectedSessionService.isProtectedSessionAvailable()) {
+ throw new Error(`Cannot (un)protect note '${note.noteId}' with protect flag '${protect}' without active protected session`);
+ }
+
+ const log = getLog();
+ try {
+ if (protect !== note.isProtected) {
+ const content = note.getContent();
+
+ note.isProtected = protect;
+ note.setContent(content, { forceSave: true });
+ }
+
+ revisionService.protectRevisions(note);
+
+ for (const attachment of note.getAttachments()) {
+ if (protect !== attachment.isProtected) {
+ try {
+ const content = attachment.getContent();
+
+ attachment.isProtected = protect;
+ attachment.setContent(content, { forceSave: true });
+ } catch (e) {
+ log.error(`Could not un/protect attachment '${attachment.attachmentId}'`);
+
+ throw e;
+ }
+ }
+ }
+ } catch (e) {
+ log.error(`Could not un/protect note '${note.noteId}'`);
+
+ throw e;
+ }
+}
+
+function checkImageAttachments(note: BNote, content: string) {
+ const foundAttachmentIds = new Set<string>();
+ let match;
+
+ const imgRegExp = /src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g;
+ while ((match = imgRegExp.exec(content))) {
+ foundAttachmentIds.add(match[1]);
+ }
+
+ const linkRegExp = /href="[^"]+attachmentId=([a-zA-Z0-9_]+)/g;
+ while ((match = linkRegExp.exec(content))) {
+ foundAttachmentIds.add(match[1]);
+ }
+
+ const attachments = note.getAttachments();
+
+ for (const attachment of attachments) {
+ const attachmentInContent = attachment.attachmentId && foundAttachmentIds.has(attachment.attachmentId);
+
+ if (attachment.utcDateScheduledForErasureSince && attachmentInContent) {
+ attachment.utcDateScheduledForErasureSince = null;
+ attachment.save();
+ } else if (!attachment.utcDateScheduledForErasureSince && !attachmentInContent) {
+ attachment.utcDateScheduledForErasureSince = date_utils.utcNowDateTime();
+ attachment.save();
+ }
+ }
+
+ const existingAttachmentIds = new Set<string | undefined>(attachments.map((att) => att.attachmentId));
+ const unknownAttachmentIds = Array.from(foundAttachmentIds).filter((foundAttId) => !existingAttachmentIds.has(foundAttId));
+ const unknownAttachments = becca.getAttachments(unknownAttachmentIds);
+
+ for (const unknownAttachment of unknownAttachments) {
+ // the attachment belongs to a different note (was copy-pasted). Attachments can be linked only from the note
+ // which owns it, so either find an existing attachment having the same content or make a copy.
+ let localAttachment = note.getAttachments().find((att) => att.role === unknownAttachment.role && att.blobId === unknownAttachment.blobId);
+
+ if (localAttachment) {
+ if (localAttachment.utcDateScheduledForErasureSince) {
+ // the attachment is for sure linked now, so reset the scheduled deletion
+ localAttachment.utcDateScheduledForErasureSince = null;
+ localAttachment.save();
+ }
+
+ getLog().info(
+ `Found equivalent attachment '${localAttachment.attachmentId}' of note '${note.noteId}' for the linked foreign attachment '${unknownAttachment.attachmentId}' of note '${unknownAttachment.ownerId}'`
+ );
+ } else {
+ localAttachment = unknownAttachment.copy();
+ localAttachment.ownerId = note.noteId;
+ localAttachment.setContent(unknownAttachment.getContent(), { forceSave: true });
+
+ ws.sendMessageToAllClients({ type: "toast", message: `Attachment '${localAttachment.title}' has been copied to note '${note.title}'.` });
+ getLog().info(`Copied attachment '${unknownAttachment.attachmentId}' of note '${unknownAttachment.ownerId}' to new '${localAttachment.attachmentId}' of note '${note.noteId}'`);
+ }
+
+ // replace image links
+ content = content.replace(`api/attachments/${unknownAttachment.attachmentId}/image`, `api/attachments/${localAttachment.attachmentId}/image`);
+ // replace reference links
+ content = content.replace(
+ new RegExp(`href="[^"]+attachmentId=${unknownAttachment.attachmentId}[^"]*"`, "g"),
+ `href="#root/${localAttachment.ownerId}?viewMode=attachments&amp;attachmentId=${localAttachment.attachmentId}"`
+ );
+ }
+
+ return {
+ forceFrontendReload: unknownAttachments.length > 0,
+ content
+ };
+}
+
+function findImageLinks(content: string, foundLinks: FoundLink[]) {
+ const re = /src="[^"]*api\/images\/([a-zA-Z0-9_]+)\//g;
+ let match;
+
+ while ((match = re.exec(content))) {
+ foundLinks.push({
+ name: "imageLink",
+ value: match[1]
+ });
+ }
+
+ // removing absolute references to server to keep it working between instances,
+ // we also omit / at the beginning to keep the paths relative
+ return content.replace(/src="[^"]*\/api\/images\//g, 'src="api/images/');
+}
+
+function findInternalLinks(content: string, foundLinks: FoundLink[]) {
+ const re = /href="[^"]*#root[a-zA-Z0-9_\/]*\/([a-zA-Z0-9_]+)\/?"/g;
+ let match;
+
+ while ((match = re.exec(content))) {
+ foundLinks.push({
+ name: "internalLink",
+ value: match[1]
+ });
+ }
+
+ // removing absolute references to server to keep it working between instances
+ return content.replace(/href="[^"]*#root/g, 'href="#root');
+}
+
+function findIncludeNoteLinks(content: string, foundLinks: FoundLink[]) {
+ const re = /<section class="include-note[^>]+data-note-id="([a-zA-Z0-9_]+)"[^>]*>/g;
+ let match;
+
+ while ((match = re.exec(content))) {
+ foundLinks.push({
+ name: "includeNoteLink",
+ value: match[1]
+ });
+ }
+
+ return content;
+}
+
+/**
+ * Extracts bookmark IDs from CKEditor bookmark anchors (`<a id="..."></a>` without href).
+ * Bookmarks are stored as labels on the note so they can be looked up without parsing content.
+ * Matches id regardless of attribute order; skips anchors with href (those are regular links).
+ */
+export function findBookmarks(content: string): string[] {
+ const re = /<a\b([^>]*)>(<\/a>)?/g;
+ const bookmarks: string[] = [];
+ let match;
+
+ while ((match = re.exec(content))) {
+ const attrs = match[1];
+
+ // Skip anchors that also have an href (those are regular links, not bookmarks)
+ if (/\bhref\s*=/.test(attrs)) {
+ continue;
+ }
+
+ const idMatch = /\bid\s*=\s*"([^"]+)"/.exec(attrs) ?? /\bid\s*=\s*'([^']+)'/.exec(attrs);
+ if (!idMatch) {
+ continue;
+ }
+
+ const id = idMatch[1];
+ if (!bookmarks.includes(id)) {
+ bookmarks.push(id);
+ }
+ }
+
+ return bookmarks;
+}
+
+function saveBookmarks(note: BNote, content: string) {
+ const foundBookmarks = findBookmarks(content);
+ const existingBookmarks = note.getOwnedLabels("internalBookmark");
+
+ for (const bookmarkId of foundBookmarks) {
+ const existing = existingBookmarks.find((l) => l.value === bookmarkId);
+
+ if (!existing) {
+ new BAttribute({
+ noteId: note.noteId,
+ type: "label",
+ name: "internalBookmark",
+ value: bookmarkId
+ }).save();
+ }
+ }
+
+ // Remove bookmarks that are no longer in the content
+ const unusedBookmarks = existingBookmarks.filter((l) => !foundBookmarks.includes(l.value));
+ for (const unused of unusedBookmarks) {
+ unused.markAsDeleted();
+ }
+}
+
+function findRelationMapLinks(content: string, foundLinks: FoundLink[]) {
+ try {
+ const obj = JSON.parse(content);
+
+ for (const note of obj.notes) {
+ foundLinks.push({
+ name: "relationMapLink",
+ value: note.noteId
+ });
+ }
+ } catch (e: any) {
+ getLog().error(`Could not scan for relation map links: ${e.message}`);
+ }
+}
+
+const imageUrlToAttachmentIdMapping: Record<string, string> = {};
+
+async function downloadImage(noteId: string, imageUrl: string) {
+ const unescapedUrl = unescapeHtml(imageUrl);
+
+ try {
+ let imageBuffer: Uint8Array;
+
+ if (imageUrl.toLowerCase().startsWith("file://")) {
+ imageBuffer = await new Promise((res, rej) => {
+ const localFilePath = imageUrl.substring("file://".length);
+
+ return fs.readFile(localFilePath, (err, data) => {
+ if (err) {
+ rej(err);
+ } else {
+ res(data);
+ }
+ });
+ });
+ } else {
+ imageBuffer = new Uint8Array(await request.getImage(unescapedUrl));
+ }
+
+ const parsedUrl = url.parse(unescapedUrl);
+ const title = basename(parsedUrl.pathname || "");
+
+ const attachment = imageService.saveImageToAttachment(noteId, imageBuffer, title, true, true);
+
+ if (attachment.attachmentId) {
+ imageUrlToAttachmentIdMapping[imageUrl] = attachment.attachmentId;
+ } else {
+ getLog().error(`Download of '${imageUrl}' for note '${noteId}' failed due to no attachment ID.`);
+ }
+
+ getLog().info(`Download of '${imageUrl}' succeeded and was saved as image attachment '${attachment.attachmentId}' of note '${noteId}'`);
+ } catch (e: any) {
+ getLog().error(`Download of '${imageUrl}' for note '${noteId}' failed with error: ${e.message} ${e.stack}`);
+ }
+}
+
+/** url => download promise */
+const downloadImagePromises: Record<string, Promise<void>> = {};
+
+function replaceUrl(content: string, url: string, attachment: Attachment) {
+ const quotedUrl = quoteRegex(url);
+
+ return content.replace(new RegExp(`\\s+src=[\"']${quotedUrl}[\"']`, "ig"), ` src="api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}"`);
+}
+
+function downloadImages(noteId: string, content: string) {
+ const imageRe = /<img[^>]*?\ssrc=['"]([^'">]+)['"]/gi;
+ let imageMatch;
+
+ while ((imageMatch = imageRe.exec(content))) {
+ const url = imageMatch[1];
+ const inlineImageMatch = /^data:image\/[a-z]+;base64,/.exec(url);
+
+ if (inlineImageMatch) {
+ const imageBase64 = url.substring(inlineImageMatch[0].length);
+ const imageBuffer = decodeBase64(imageBase64);
+
+ const attachment = imageService.saveImageToAttachment(noteId, imageBuffer, "inline image", true, true);
+
+ const encodedTitle = encodeURIComponent(attachment.title);
+
+ content = `${content.substring(0, imageMatch.index)}<img src="api/attachments/${attachment.attachmentId}/image/${encodedTitle}"${content.substring(imageMatch.index + imageMatch[0].length)}`;
+ } else if (
+ !url.includes("api/images/") &&
+ !/api\/attachments\/.+\/image\/?.*/.test(url) &&
+ // this is an exception for the web clipper's "imageId"
+ (url.length !== 20 || url.toLowerCase().startsWith("http"))
+ ) {
+ if (!optionService.getOptionBool("downloadImagesAutomatically")) {
+ continue;
+ }
+
+ if (url in imageUrlToAttachmentIdMapping) {
+ const attachment = becca.getAttachment(imageUrlToAttachmentIdMapping[url]);
+
+ if (!attachment) {
+ delete imageUrlToAttachmentIdMapping[url];
+ } else {
+ content = replaceUrl(content, url, attachment);
+ continue;
+ }
+ }
+
+ if (url in downloadImagePromises) {
+ // download is already in progress
+ continue;
+ }
+
+ // this is done asynchronously, it would be too slow to wait for the download
+ // given that save can be triggered very often
+ downloadImagePromises[url] = downloadImage(noteId, url);
+ }
+ }
+
+ Promise.all(Object.values(downloadImagePromises)).then(() => {
+ setTimeout(() => {
+ // the normal expected flow of the offline image saving is that users will paste the image(s)
+ // which will get asynchronously downloaded, during that time they keep editing the note
+ // once the download is finished, the image note representing the downloaded image will be used
+ // to replace the IMG link.
+ // However, there's another flow where the user pastes the image and leaves the note before the images
+ // are downloaded and the IMG references are not updated. For this occasion we have this code
+ // which upon the download of all the images will update the note if the links have not been fixed before
+
+ cls.getContext().init(() => {
+ getSql().transactional(() => {
- const imageNotes = becca.getNotes(Object.values(imageUrlToAttachmentIdMapping), true);
++ const imageNotes = becca.getNotes(Object.values(imageUrlToAttachmentIdMapping), true);
+ const log = getLog();
+
- const origNote = becca.getNote(noteId);
++ const origNote = becca.getNote(noteId);
+
- if (!origNote) {
- log.error(`Cannot find note '${noteId}' to replace image link.`);
- return;
- }
++ if (!origNote) {
++ log.error(`Cannot find note '${noteId}' to replace image link.`);
++ return;
++ }
+
- const origContent = origNote.getContent();
- let updatedContent = origContent;
++ const origContent = origNote.getContent();
++ let updatedContent = origContent;
+
- if (typeof updatedContent !== "string") {
- log.error(`Note '${noteId}' has a non-string content, cannot replace image link.`);
- return;
- }
++ if (typeof updatedContent !== "string") {
++ log.error(`Note '${noteId}' has a non-string content, cannot replace image link.`);
++ return;
++ }
+
- for (const url in imageUrlToAttachmentIdMapping) {
- const imageNote = imageNotes.find((note) => note.noteId === imageUrlToAttachmentIdMapping[url]);
++ for (const url in imageUrlToAttachmentIdMapping) {
++ const imageNote = imageNotes.find((note) => note.noteId === imageUrlToAttachmentIdMapping[url]);
+
- if (imageNote) {
- updatedContent = replaceUrl(updatedContent, url, imageNote);
- }
++ if (imageNote) {
++ updatedContent = replaceUrl(updatedContent, url, imageNote);
+ }
++ }
+
- // update only if the links have not been already fixed.
- if (updatedContent !== origContent) {
- origNote.setContent(updatedContent);
++ // update only if the links have not been already fixed.
++ if (updatedContent !== origContent) {
++ origNote.setContent(updatedContent);
+
- asyncPostProcessContent(origNote, updatedContent);
++ asyncPostProcessContent(origNote, updatedContent);
+
- console.log(`Fixed the image links for note '${noteId}' to the offline saved.`);
- }
++ console.log(`Fixed the image links for note '${noteId}' to the offline saved.`);
++ }
+ });
+ });
+ }, 5000);
+ });
+
+ return content;
+}
+
+function saveAttachments(note: BNote, content: string) {
+ const inlineAttachmentRe = /<a[^>]*?\shref=['"]data:([^;'">]+);base64,([^'">]+)['"][^>]*>(.*?)<\/a>/gim;
+ let attachmentMatch;
+
+ while ((attachmentMatch = inlineAttachmentRe.exec(content))) {
+ const mime = attachmentMatch[1].toLowerCase();
+
+ const base64data = attachmentMatch[2];
+ const buffer = decodeBase64(base64data);
+
+ const title = html2plaintext(attachmentMatch[3]);
+
+ const attachment = note.saveAttachment({
+ role: "file",
+ mime,
+ title,
+ content: buffer
+ });
+
+ content = `${content.substring(0, attachmentMatch.index)}<a class="reference-link" href="#root/${note.noteId}?viewMode=attachments&attachmentId=${attachment.attachmentId}">${title}</a>${content.substring(attachmentMatch.index + attachmentMatch[0].length)}`;
+ }
+
+ // removing absolute references to server to keep it working between instances,
+ // we also omit / at the beginning to keep the paths relative
+ content = content.replace(/src="[^"]*\/api\/attachments\//g, 'src="api/attachments/');
+
+ return content;
+}
+
+function saveLinks(note: BNote, content: string | Uint8Array) {
+ if ((note.type !== "text" && note.type !== "relationMap") || (note.isProtected && !protectedSessionService.isProtectedSessionAvailable())) {
+ return {
+ forceFrontendReload: false,
+ content
+ };
+ }
+
+ const foundLinks: FoundLink[] = [];
+ let forceFrontendReload = false;
+
+ if (note.type === "text" && typeof content === "string") {
+ content = downloadImages(note.noteId, content);
+ content = saveAttachments(note, content);
+
+ content = findImageLinks(content, foundLinks);
+ content = findInternalLinks(content, foundLinks);
+ content = findIncludeNoteLinks(content, foundLinks);
+ saveBookmarks(note, content);
+
+ ({ forceFrontendReload, content } = checkImageAttachments(note, content));
+ } else if (note.type === "relationMap" && typeof content === "string") {
+ findRelationMapLinks(content, foundLinks);
+ } else {
+ throw new Error(`Unrecognized type '${note.type}'`);
+ }
+
+ const existingLinks = note.getRelations().filter((rel) => ["internalLink", "imageLink", "relationMapLink", "includeNoteLink"].includes(rel.name));
+
+ for (const foundLink of foundLinks) {
+ const targetNote = becca.notes[foundLink.value];
+ if (!targetNote) {
+ continue;
+ }
+
+ const existingLink = existingLinks.find((existingLink) => existingLink.value === foundLink.value && existingLink.name === foundLink.name);
+
+ if (!existingLink) {
+ const newLink = new BAttribute({
+ noteId: note.noteId,
+ type: "relation",
+ name: foundLink.name,
+ value: foundLink.value
+ }).save();
+
+ existingLinks.push(newLink);
+ }
+ // else the link exists, so we don't need to do anything
+ }
+
+ // marking links as deleted if they are not present on the page anymore
+ const unusedLinks = existingLinks.filter((existingLink) => !foundLinks.some((foundLink) => existingLink.value === foundLink.value && existingLink.name === foundLink.name));
+
+ for (const unusedLink of unusedLinks) {
+ unusedLink.markAsDeleted();
+ }
+
+ return { forceFrontendReload, content };
+}
+
+function saveRevisionIfNeeded(note: BNote) {
+ // files and images are versioned separately
+ if (note.type === "file" || note.type === "image" || note.isLabelTruthy("disableVersioning")) {
+ return;
+ }
+
+ const now = new Date();
+ const revisionSnapshotTimeInterval = parseInt(optionService.getOption("revisionSnapshotTimeInterval"));
+
+ const revisionCutoff = date_utils.utcDateTimeStr(new Date(now.getTime() - revisionSnapshotTimeInterval * 1000));
+
+ const existingRevisionId = getSql().getValue("SELECT revisionId FROM revisions WHERE noteId = ? AND utcDateCreated >= ?", [note.noteId, revisionCutoff]);
+
+ const msSinceDateCreated = now.getTime() - date_utils.parseDateTime(note.utcDateCreated).getTime();
+
+ if (!existingRevisionId && msSinceDateCreated >= revisionSnapshotTimeInterval * 1000) {
+ note.saveRevision();
+ }
+}
+
+function updateNoteData(noteId: string, content: string, attachments: AttachmentRow[] = []) {
+ const note = becca.getNote(noteId);
+
+ if (!note || !note.isContentAvailable()) {
+ throw new Error(`Note '${noteId}' is not available for change!`);
+ }
+
+ saveRevisionIfNeeded(note);
+
+ const { forceFrontendReload, content: newContent } = saveLinks(note, content);
+
+ note.setContent(newContent, { forceFrontendReload });
+
+ if (attachments?.length > 0) {
+ const existingAttachmentsByTitle = toMap(note.getAttachments(), "title");
+
+ for (const { attachmentId, role, mime, title, position, content, encoding } of attachments) {
+ const decodedContent = encoding === "base64" && typeof content === "string"
+ ? decodeBase64(content) : content;
+
+ const existingAttachment = existingAttachmentsByTitle.get(title);
+ if (attachmentId || !existingAttachment) {
+ note.saveAttachment({ attachmentId, role, mime, title, content: decodedContent, position });
+ } else {
+ existingAttachment.role = role;
+ existingAttachment.mime = mime;
+ existingAttachment.position = position;
+ if (decodedContent) {
+ existingAttachment.setContent(decodedContent, { forceSave: true });
+ }
+ }
+ }
+ }
+}
+
+function undeleteNote(noteId: string, taskContext: TaskContext<"undeleteNotes">) {
+ const noteRow = getSql().getRow<NoteRow>("SELECT * FROM notes WHERE noteId = ?", [noteId]);
+
+ if (!noteRow.isDeleted || !noteRow.deleteId) {
+ getLog().error(`Note '${noteId}' is not deleted and thus cannot be undeleted.`);
+ return;
+ }
+
+ const undeletedParentBranchIds = getUndeletedParentBranchIds(noteId, noteRow.deleteId);
+
+ if (undeletedParentBranchIds.length === 0) {
+ // cannot undelete if there's no undeleted parent
+ return;
+ }
+
+ for (const parentBranchId of undeletedParentBranchIds) {
+ undeleteBranch(parentBranchId, noteRow.deleteId, taskContext);
+ }
+}
+
+function undeleteBranch(branchId: string, deleteId: string, taskContext: TaskContext<"undeleteNotes">) {
+ const sql = getSql();
+ const branchRow = sql.getRow<BranchRow>("SELECT * FROM branches WHERE branchId = ?", [branchId]);
+
+ if (!branchRow.isDeleted) {
+ return;
+ }
+
+ const noteRow = sql.getRow<NoteRow>("SELECT * FROM notes WHERE noteId = ?", [branchRow.noteId]);
+
+ if (noteRow.isDeleted && noteRow.deleteId !== deleteId) {
+ return;
+ }
+
+ new BBranch(branchRow).save();
+
+ taskContext.increaseProgressCount();
+
+ if (noteRow.isDeleted && noteRow.deleteId === deleteId) {
+ // becca entity was already created as skeleton in "new Branch()" above
+ const noteEntity = becca.getNote(noteRow.noteId);
+ if (!noteEntity) {
+ throw new Error("Unable to find the just restored branch.");
+ }
+
+ noteEntity.updateFromRow(noteRow);
+ noteEntity.save();
+
+ const attributeRows = sql.getRows<AttributeRow>(
+ `
+ SELECT * FROM attributes
+ WHERE isDeleted = 1
+ AND deleteId = ?
+ AND (noteId = ?
+ OR (type = 'relation' AND value = ?))`,
+ [deleteId, noteRow.noteId, noteRow.noteId]
+ );
+
+ for (const attributeRow of attributeRows) {
+ // relation might point to a note which hasn't been undeleted yet and would thus throw up
+ new BAttribute(attributeRow).save({ skipValidation: true });
+ }
+
+ const attachmentRows = sql.getRows<AttachmentRow>(
+ `
+ SELECT * FROM attachments
+ WHERE isDeleted = 1
+ AND deleteId = ?
+ AND ownerId = ?`,
+ [deleteId, noteRow.noteId]
+ );
+
+ for (const attachmentRow of attachmentRows) {
+ new BAttachment(attachmentRow).save();
+ }
+
+ const childBranchIds = sql.getColumn<string>(
+ `
+ SELECT branches.branchId
+ FROM branches
+ WHERE branches.isDeleted = 1
+ AND branches.deleteId = ?
+ AND branches.parentNoteId = ?`,
+ [deleteId, noteRow.noteId]
+ );
+
+ for (const childBranchId of childBranchIds) {
+ undeleteBranch(childBranchId, deleteId, taskContext);
+ }
+ }
+}
+
+/**
+ * @returns return deleted branchIds of an undeleted parent note
+ */
+function getUndeletedParentBranchIds(noteId: string, deleteId: string) {
+ return getSql().getColumn<string>(
+ `
+ SELECT branches.branchId
+ FROM branches
+ JOIN notes AS parentNote ON parentNote.noteId = branches.parentNoteId
+ WHERE branches.noteId = ?
+ AND branches.isDeleted = 1
+ AND branches.deleteId = ?
+ AND parentNote.isDeleted = 0`,
+ [noteId, deleteId]
+ );
+}
+
+function scanForLinks(note: BNote, content: string | Uint8Array) {
+ if (!note || !["text", "relationMap"].includes(note.type)) {
+ return;
+ }
+
+ try {
+ getSql().transactional(() => {
+ const { forceFrontendReload, content: newContent } = saveLinks(note, content);
+
+ if (content !== newContent) {
+ note.setContent(newContent, { forceFrontendReload });
+ }
+ });
+ } catch (e: any) {
+ getLog().error(`Could not scan for links note '${note.noteId}': ${e.message} ${e.stack}`);
+ }
+}
+
+/**
+ * Things which have to be executed after updating content, but asynchronously (separate transaction)
+ */
+async function asyncPostProcessContent(note: BNote, content: string | Uint8Array) {
+ if (cls.isMigrationRunning()) {
+ // this is rarely needed for migrations, but can cause trouble by e.g. triggering downloads
+ return;
+ }
+
+ if (note.hasStringContent() && typeof content !== "string") {
+ content = content.toString();
+ }
+
+ scanForLinks(note, content);
+}
+
+// all keys should be replaced by the corresponding values
+function replaceByMap(str: string, mapObj: Record<string, string>) {
+ if (!mapObj) {
+ return str;
+ }
+
+ const re = new RegExp(Object.keys(mapObj).join("|"), "g");
+
+ return str.replace(re, (matched) => mapObj[matched]);
+}
+
+function duplicateSubtree(origNoteId: string, newParentNoteId: string) {
+ if (origNoteId === "root") {
+ throw new Error("Duplicating root is not possible");
+ }
+
+ getLog().info(`Duplicating '${origNoteId}' subtree into '${newParentNoteId}'`);
+
+ const origNote = becca.notes[origNoteId];
+ // might be null if orig note is not in the target newParentNoteId
+ const origBranch = origNote.getParentBranches().find((branch) => branch.parentNoteId === newParentNoteId);
+
+ const noteIdMapping = getNoteIdMapping(origNote);
+
+ const res = duplicateSubtreeInner(origNote, origBranch, newParentNoteId, noteIdMapping);
+
+ const duplicateNoteSuffix = t("notes.duplicate-note-suffix");
+
+ if (!res.note.title.endsWith(duplicateNoteSuffix) && !res.note.title.startsWith(duplicateNoteSuffix)) {
+ res.note.title = t("notes.duplicate-note-title", { noteTitle: res.note.title, duplicateNoteSuffix });
+ }
+
+ res.note.save();
+
+ return res;
+}
+
+function duplicateSubtreeWithoutRoot(origNoteId: string, newNoteId: string) {
+ if (origNoteId === "root") {
+ throw new Error("Duplicating root is not possible");
+ }
+
+ const origNote = becca.getNote(origNoteId);
+ if (origNote == null) {
+ throw new Error("Unable to find note to duplicate.");
+ }
+
+ const noteIdMapping = getNoteIdMapping(origNote);
+ for (const childBranch of origNote.getChildBranches()) {
+ if (childBranch) {
+ duplicateSubtreeInner(childBranch.getNote(), childBranch, newNoteId, noteIdMapping);
+ }
+ }
+}
+
+function duplicateSubtreeInner(origNote: BNote, origBranch: BBranch | null | undefined, newParentNoteId: string, noteIdMapping: Record<string, string>) {
+ if (origNote.isProtected && !protectedSessionService.isProtectedSessionAvailable()) {
+ throw new Error(`Cannot duplicate note '${origNote.noteId}' because it is protected and protected session is not available. Enter protected session and try again.`);
+ }
+
+ const newNoteId = noteIdMapping[origNote.noteId];
+
+ function createDuplicatedBranch() {
+ return new BBranch({
+ noteId: newNoteId,
+ parentNoteId: newParentNoteId,
+ // here increasing just by 1 to make sure it's directly after original
+ notePosition: origBranch ? origBranch.notePosition + 1 : null
+ }).save();
+ }
+
+ function createDuplicatedNote() {
+ const newNote = new BNote({
+ ...origNote,
+ noteId: newNoteId,
+ dateCreated: date_utils.localNowDateTime(),
+ utcDateCreated: date_utils.utcNowDateTime()
+ }).save();
+
+ let content = origNote.getContent();
+
+ if (typeof content === "string" && ["text", "relationMap", "search"].includes(origNote.type)) {
+ // fix links in the content
+ content = replaceByMap(content, noteIdMapping);
+ }
+
+ newNote.setContent(content);
+
+ for (const attribute of origNote.getOwnedAttributes()) {
+ const attr = new BAttribute({
+ ...attribute,
+ attributeId: undefined,
+ noteId: newNote.noteId
+ });
+
+ // if relation points to within the duplicated tree then replace the target to the duplicated note
+ // if it points outside of duplicated tree then keep the original target
+ if (attr.type === "relation" && attr.value in noteIdMapping) {
+ attr.value = noteIdMapping[attr.value];
+ }
+
+ // the relation targets may not be created yet, the mapping is pre-generated
+ attr.save({ skipValidation: true });
+ }
+
+ for (const childBranch of origNote.getChildBranches()) {
+ if (childBranch) {
+ duplicateSubtreeInner(childBranch.getNote(), childBranch, newNote.noteId, noteIdMapping);
+ }
+ }
+
+ asyncPostProcessContent(newNote, content);
+
+ return newNote;
+ }
+
+ const existingNote = becca.notes[newNoteId];
+
+ if (existingNote && existingNote.title !== undefined) {
+ // checking that it's not just note's skeleton created because of Branch above
+ // note has multiple clones and was already created from another placement in the tree,
+ // so a branch is all we need for this clone
+ return {
+ note: existingNote,
+ branch: createDuplicatedBranch()
+ };
+ }
+ return {
+ // order here is important, note needs to be created first to not mess up the becca
+ note: createDuplicatedNote(),
+ branch: createDuplicatedBranch()
+ };
+
+}
+
+function getNoteIdMapping(origNote: BNote) {
+ const noteIdMapping: Record<string, string> = {};
+
+ // pregenerate new noteIds since we'll need to fix relation references even for not yet created notes
+ for (const origNoteId of origNote.getDescendantNoteIds()) {
+ noteIdMapping[origNoteId] = newEntityId();
+ }
+
+ return noteIdMapping;
+}
+
+export default {
+ createNewNote,
+ createNewNoteWithTarget,
+ updateNoteData,
+ undeleteNote,
+ protectNoteRecursively,
+ duplicateSubtree,
+ duplicateSubtreeWithoutRoot,
+ getUndeletedParentBranchIds,
+ triggerNoteTitleChanged,
+ saveRevisionIfNeeded,
+ downloadImages,
+ asyncPostProcessContent
+};
diff --cc packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts
index 23603d80d0,827f8cc173..18a2b45cca
--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts
+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext.ts
@@@ -80,10 -80,10 +80,10 @@@ class NoteContentFulltextExp extends Ex
const resultNoteSet = new NoteSet();
// Search through notes with content
- for (const row of sql.iterateRows<SearchRow>(`
+ for (const row of getSql().iterateRows<SearchRow>(`
SELECT noteId, type, mime, content, isProtected
FROM notes JOIN blobs USING (blobId)
- WHERE type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap')
+ WHERE type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap', 'spreadsheet')
AND isDeleted = 0
AND LENGTH(content) < ${MAX_SEARCH_CONTENT_SIZE}`)) {
this.findInText(row, inputNoteSet, resultNoteSet);
diff --cc packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts
index f53a941be6,927c72e4fb..dd48594700
--- a/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts
+++ b/packages/trilium-core/src/services/search/expressions/note_content_fulltext_preprocessor.ts
@@@ -1,9 -1,10 +1,10 @@@
+ import { extractSpreadsheetText } from "@triliumnext/commons";
import striptags from "striptags";
+import { normalizeSearchText } from "../utils/text_utils";
+import { normalize } from "../../utils/index";
-import { normalize } from "../../utils.js";
-
-export default function preprocessContent(content: string | Buffer, type: string, mime: string, raw?: boolean) {
- content = normalize(content.toString());
+export default function preprocessContent(rawContent: string | Uint8Array, type: string, mime: string, raw?: boolean) {
+ let content = normalize(rawContent.toString());
if (type === "text" && mime === "text/html") {
if (!raw) {
diff --cc pnpm-lock.yaml
index 59a036f715,5491ba645a..ea469b8284
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@@ -172,30 -172,23 +172,30 @@@ importers
specifier: 6.0.3
version: 6.0.3
typescript-eslint:
- specifier: 8.58.2
+ specifier: 8.59.0
vite:
- specifier: 8.0.8
+ specifier: 8.0.9
vite-plugin-dts:
specifier: 4.5.4
vitest:
- specifier: 4.1.4
+ specifier: 4.1.5
apps/build-docs:
+ dependencies:
+ '@triliumnext/core':
+ specifier: workspace:*
+ version: link:../../packages/trilium-core
+ '@triliumnext/server':
+ specifier: workspace:*
+ version: link:../server
devDependencies:
'@redocly/cli':
- specifier: 2.28.0
+ specifier: 2.29.1
archiver:
specifier: 7.0.1
version: 7.0.1
@@@ -425,236 -418,13 +425,239 @@@
script-loader:
specifier: 0.7.2
version: 0.7.2
+ stylelint:
+ specifier: 17.8.0
+ version: 17.8.0([email protected])
vite-plugin-static-copy:
- specifier: 4.0.1
+ specifier: 4.1.0
+ apps/client-standalone:
+ dependencies:
+ '@excalidraw/excalidraw':
+ specifier: 0.18.0
+ '@fullcalendar/core':
+ specifier: 6.1.20
+ version: 6.1.20
+ '@fullcalendar/daygrid':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@fullcalendar/interaction':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@fullcalendar/list':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@fullcalendar/multimonth':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@fullcalendar/timegrid':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@maplibre/maplibre-gl-leaflet':
+ specifier: 0.1.3
+ '@mermaid-js/layout-elk':
+ specifier: 0.2.1
+ version: 0.2.1([email protected])
+ '@mind-elixir/node-menu':
+ specifier: 5.0.1
+ version: 5.0.1([email protected])
+ '@popperjs/core':
+ specifier: 2.11.8
+ version: 2.11.8
+ '@preact/signals':
+ specifier: 2.9.0
+ version: 2.9.0([email protected])
+ '@sqlite.org/sqlite-wasm':
+ specifier: 3.51.1-build2
+ version: 3.51.1-build2
+ '@triliumnext/ckeditor5':
+ specifier: workspace:*
+ version: link:../../packages/ckeditor5
+ '@triliumnext/codemirror':
+ specifier: workspace:*
+ version: link:../../packages/codemirror
+ '@triliumnext/commons':
+ specifier: workspace:*
+ version: link:../../packages/commons
+ '@triliumnext/core':
+ specifier: workspace:*
+ version: link:../../packages/trilium-core
+ '@triliumnext/highlightjs':
+ specifier: workspace:*
+ version: link:../../packages/highlightjs
+ '@triliumnext/share-theme':
+ specifier: workspace:*
+ version: link:../../packages/share-theme
+ '@triliumnext/split.js':
+ specifier: workspace:*
+ version: link:../../packages/splitjs
+ '@zumer/snapdom':
+ specifier: 2.8.0
+ version: 2.8.0
+ aes-js:
+ specifier: 3.1.2
+ version: 3.1.2
+ autocomplete.js:
+ specifier: 0.38.1
+ version: 0.38.1
+ bootstrap:
+ specifier: 5.3.8
+ version: 5.3.8(@popperjs/[email protected])
+ boxicons:
+ specifier: 2.1.4
+ version: 2.1.4
+ clsx:
+ specifier: 2.1.1
+ version: 2.1.1
+ color:
+ specifier: 5.0.3
+ version: 5.0.3
+ debounce:
+ specifier: 3.0.0
+ version: 3.0.0
+ draggabilly:
+ specifier: 3.0.0
+ version: 3.0.0
+ fflate:
+ specifier: 0.8.2
+ version: 0.8.2
+ force-graph:
+ specifier: 1.51.4
+ version: 1.51.4
+ globals:
+ specifier: 17.4.0
+ version: 17.4.0
+ i18next:
+ specifier: 26.0.5
+ version: 26.0.5([email protected])
+ i18next-http-backend:
+ specifier: 3.0.4
+ version: 3.0.4([email protected])
+ jquery:
+ specifier: 4.0.0
+ version: 4.0.0
+ jquery.fancytree:
+ specifier: 2.38.5
+ version: 2.38.5([email protected])
+ js-md5:
+ specifier: 0.8.3
+ version: 0.8.3
+ js-sha1:
+ specifier: 0.7.0
+ version: 0.7.0
+ js-sha256:
+ specifier: 0.11.1
+ version: 0.11.1
+ js-sha512:
+ specifier: 0.9.0
+ version: 0.9.0
+ jsplumb:
+ specifier: 2.15.6
+ version: 2.15.6
+ katex:
+ specifier: 0.16.45
+ version: 0.16.45
+ knockout:
+ specifier: 3.5.1
+ version: 3.5.1
+ leaflet:
+ specifier: 1.9.4
+ version: 1.9.4
+ leaflet-gpx:
+ specifier: 2.2.0
+ version: 2.2.0
+ mark.js:
+ specifier: 8.11.1
+ version: 8.11.1
+ marked:
+ specifier: 18.0.1
+ version: 18.0.1
+ mermaid:
+ specifier: 11.14.0
+ version: 11.14.0
+ mind-elixir:
+ specifier: 5.10.0
+ version: 5.10.0
+ normalize.css:
+ specifier: 8.0.1
+ version: 8.0.1
+ panzoom:
+ specifier: 9.4.4
+ version: 9.4.4
+ preact:
+ specifier: 10.29.1
+ version: 10.29.1
+ react-i18next:
+ specifier: 17.0.4
+ react-window:
+ specifier: 2.2.7
+ reveal.js:
+ specifier: 6.0.1
+ version: 6.0.1
+ scrypt-js:
+ specifier: 3.0.1
+ version: 3.0.1
+ svg-pan-zoom:
+ specifier: 3.6.2
+ version: 3.6.2
+ tabulator-tables:
+ specifier: 6.4.0
+ version: 6.4.0
+ vanilla-js-wheel-zoom:
+ specifier: 9.0.4
+ version: 9.0.4
+ devDependencies:
+ '@ckeditor/ckeditor5-inspector':
+ specifier: 5.0.0
+ version: 5.0.0
+ '@preact/preset-vite':
+ specifier: 2.10.2
+ '@types/aes-js':
+ specifier: 3.1.4
+ version: 3.1.4
+ '@types/bootstrap':
+ specifier: 5.2.10
+ version: 5.2.10
+ '@types/jquery':
+ specifier: 4.0.0
+ version: 4.0.0
+ '@types/leaflet':
+ specifier: 1.9.21
+ version: 1.9.21
+ '@types/leaflet-gpx':
+ specifier: 1.3.8
+ version: 1.3.8
+ '@types/mark.js':
+ specifier: 8.11.12
+ version: 8.11.12
+ '@types/reveal.js':
+ specifier: 5.2.2
+ version: 5.2.2
+ '@types/tabulator-tables':
+ specifier: 6.3.1
+ version: 6.3.1
+ copy-webpack-plugin:
+ specifier: 14.0.0
+ cross-env:
+ specifier: 7.0.3
+ version: 7.0.3
+ happy-dom:
+ specifier: 20.9.0
+ script-loader:
+ specifier: 0.7.2
+ version: 0.7.2
+ vite-plugin-static-copy:
+ specifier: 4.0.1
+
apps/db-compare:
dependencies:
colors:
@@@ -808,22 -572,8 +811,24 @@@
specifier: 2.1.2
version: 2.1.2
+ apps/mobile:
+ dependencies:
+ '@capacitor/android':
+ specifier: 8.3.1
+ version: 8.3.1(@capacitor/[email protected])
+ '@capacitor/core':
+ specifier: 8.3.1
+ version: 8.3.1
+ '@capacitor/splash-screen':
+ specifier: 8.0.1
+ version: 8.0.1(@capacitor/[email protected])
+ devDependencies:
+ '@capacitor/cli':
+ specifier: 8.3.1
+ version: 8.3.1
+
+ apps/script-deployer: {}
+
apps/server:
dependencies:
'@ai-sdk/anthropic':
@@@ -1082,9 -868,15 +1087,9 @@@
turnish:
specifier: 1.8.0
version: 1.8.0
- unescape:
- specifier: 1.0.1
- version: 1.0.1
vite:
- specifier: 8.0.8
+ specifier: 8.0.9
- ws:
- specifier: 8.20.0
xml2js:
specifier: 0.6.2
version: 0.6.2
@@@ -1663,70 -1464,9 +1671,70 @@@
specifier: 20.9.0
vitest:
- specifier: 4.1.4
+ specifier: 4.1.5
+ packages/trilium-core:
+ dependencies:
+ '@braintree/sanitize-url':
+ specifier: 7.1.1
+ version: 7.1.1
+ '@triliumnext/commons':
+ specifier: workspace:*
+ version: link:../commons
+ '@triliumnext/turndown-plugin-gfm':
+ specifier: workspace:*
+ version: link:../turndown-plugin-gfm
+ async-mutex:
+ specifier: 0.5.0
+ version: 0.5.0
+ chardet:
+ specifier: 2.1.1
+ version: 2.1.1
+ escape-html:
+ specifier: 1.0.3
+ version: 1.0.3
+ i18next:
+ specifier: 26.0.5
+ version: 26.0.5([email protected])
+ mime-types:
+ specifier: 3.0.2
+ version: 3.0.2
+ node-html-parser:
+ specifier: 7.1.0
+ version: 7.1.0
+ sanitize-filename:
+ specifier: 1.6.4
+ version: 1.6.4
+ sanitize-html:
+ specifier: 2.17.2
+ version: 2.17.2
+ strip-bom:
+ specifier: 5.0.0
+ version: 5.0.0
+ sucrase:
+ specifier: 3.35.1
+ version: 3.35.1
+ unescape:
+ specifier: 1.0.1
+ version: 1.0.1
+ devDependencies:
+ '@types/escape-html':
+ specifier: 1.0.4
+ version: 1.0.4
+ '@types/mime-types':
+ specifier: 3.0.1
+ version: 3.0.1
+ '@types/sanitize-html':
+ specifier: 2.16.1
+ version: 2.16.1
+
+ packages/trilium-e2e:
+ devDependencies:
+ dotenv:
+ specifier: 17.4.2
+ version: 17.4.2
+
packages/turndown-plugin-gfm:
devDependencies:
happy-dom:
@@@ -3211,21 -2948,21 +3237,30 @@@ packages
resolution: {integrity: sha512-rZAP3aVgB9ds9KOeUSL+zZ21hPmo8dh6fnIFwRQj5EAZl9gzR7wxYbYXYysAM8CTqGmUGyp2S4kUdV17MnGuWQ==}
engines: {node: ^20.19.0 || ^22.13.0 || >=24}
+ '@excalidraw/[email protected]':
+ resolution: {integrity: sha512-QkIiS+5qdy8lmDWTKsuy0sK/fen/LRDtbhm2lc2xcFcqhv2/zdg95bYnl+wnwwXGHo7kEmP65BSiMHE7PJ3Zpw==}
+ peerDependencies:
+ react: ^17.0.2 || ^18.2.0 || ^19.0.0
+ react-dom: ^17.0.2 || ^18.2.0 || ^19.0.0
+
+ '@excalidraw/[email protected]':
+ resolution: {integrity: sha512-6i5Gt7IDTOH//qa0Z315Ly5iVRhjWpu2whrlQFqkuwrkKUWgRsMk0P5qdE7bpyDpai7jeLeWYkyj1eVAfni1lw==}
+ peerDependencies:
+ react: ^17.0.2 || ^18.2.0 || ^19.0.0
+ react-dom: ^17.0.2 || ^18.2.0 || ^19.0.0
+
'@excalidraw/[email protected]':
resolution: {integrity: sha512-psA1z1N2qeAfsORdXc9JmD2y4CmDwmuMRxnNdJHZexIcPwaNEyIpNcelw+QkL9rz9tosaN9krXuKaRqYpRAR6g==}
'@excalidraw/[email protected]':
resolution: {integrity: sha512-1nDXBNAojfi3oSFwJswKREkFm5wrSjqay81QlyRv2pkITG/XYB5v+oChENVBQLcxQwX4IUATWvXM5BcaNhPiIg==}
+ '@excalidraw/[email protected]':
+ resolution: {integrity: sha512-hAFv/TTIsOdoy0dL5v+oBd297SQ+Z88gZ5u99fCIFuEMHfQuPgLhU/ztKhFSTs7fISwVo6fizny/5oQRR3d4tQ==}
+
+ '@excalidraw/[email protected]':
+ resolution: {integrity: sha512-5VKQq5CdRocC82vOIUpQ5ufJOVV9FpBTdHGA+ULqazeIVV+cr299877omQCibsdS3Bpitz2fsnTwnIXEmLVDSg==}
+
'@excalidraw/[email protected]':
resolution: {integrity: sha512-nULYsQxkWHnbmHvcs+efMkJ4/9TtvNyFeLyHdeGxW0zHs6P+jYVqcRff9A6Vq9w9JXeDRnRh2VKvTtS19GW2qA==}
engines: {node: '>=10'}
@@@ -6099,9 -5790,9 +6139,12 @@@
resolution: {integrity: sha512-uh2Lv57xvggst6lCqNdFAmDSvoMG7M/HDtX4iUCquxQ5EGPtaPM5PL5Hmi7LCvOG8db7YaCPNJEeoI8s/WzIQw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-qL05wGXVy0yfWcF8LCE9+9uSeUIpeKdgpm8YmOAPTjLd3FaoZziPOhVxIiLzEhLTFfOvbuwnaWDm4v4i87diRQ==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ox1MLWti8gNnWMNYd0Kob2nRNxttvjB0FwtZkWC3MkDtO9SdOe785dfEN+8Bjmrn9x5RzGR6Lj837Icr0seOeg==}
+
resolution: {integrity: sha512-chhaNf2oKHlRkDGt+tiKE2Z5aJ6qalm7Z9rlLdBwmOiAAf09YQvvoLXjWK4HWPF1xU/fqvMgfNfpVoBscA/tKA==}
@@@ -9849,20 -9458,20 +9828,31 @@@
resolution: {integrity: sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==}
- resolution: {integrity: sha512-lzbUnowXYd5RFO8flpQhd9khYWNgrzwtxHw1kktJCiTRBaAEiLB2t9EPSXRj8qlC7WcEgFDIsmBUixyludcznw==}
+ resolution: {integrity: sha512-/5aW996nbolGh/qVU9urjAJ2QiXpiyGuhG8x/ZvvZQ3bMlrK+ouUdD6whS4e+sU9CCdUIzl7x/heEjsBh/3xtw==}
+
+ resolution: {integrity: sha512-udwrBIE6cNpqn1gRAqRULq3+7MzIIuaiKRWrz++dVz5SqWW2VwXmPJtAgkI0JtMLFaADC9qNmnZAxWAhsxXx2g==}
+ resolution: {integrity: sha512-QaWHnsxieEDcqKe+vo/RFqpiIFRi/KBqlOSPcUlvinBaISCeiTRCbtrazHAjtHtsLC66oDsROAH8frWkQzfMMQ==}
+
+ resolution: {integrity: sha512-9uHb4T27TdV36phJXcbpnRPt5yzAfqHXVrdASvmHZyPuZJtrLythd+GyXhiaHV5LlpuuskbAqhwPjmfTbKbi8w==}
+ peerDependencies:
+ typescript: ^5 || ^6
+ peerDependenciesMeta:
+ typescript:
+ optional: true
+
+ resolution: {integrity: sha512-A4U6eCXodIbrhf8EarRurB9/4ebyaurH4+fu4gig9bqxmpSt+fCAFm/GpRQDcN1Xzu/LdFCx4nYHsnM1edIIbg==}
+ peerDependencies:
+ typescript: ^5 || ^6
+ peerDependenciesMeta:
+ typescript:
+ optional: true
+
resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==}
engines: {node: '>=0.10.0'}
@@@ -10895,11 -10490,11 +10890,16 @@@
engines: {node: '>= 20'}
hasBin: true
+ resolution: {integrity: sha512-IILJE4Aap/KIGu4ZRCzQcYMxkhumblXnbqfQe+HAD4f982wrRAsJEGKGM653yAioS6g3Yq3yOhjrUebcrtOgRA==}
+ engines: {node: '>= 20'}
+ hasBin: true
+
+ resolution: {integrity: sha512-NsmlUYBS/Zg57rgDWMYdnre6OTj4e+qq/JS2ot3KrYLSoHLw+sDu0Nm1ZGpRgYAq6c+b1ekaY5NzVchMCQnzcg==}
+ engines: {node: '>= 20'}
+ hasBin: true
+
resolution: {integrity: sha512-PRsaiG84bK+AMvxziE/lCFss8juXjNaWzVbN5tXAm4XjeaS9NAHhop+PjQxz2A9h8Q4M/xGmzP8vqNwy6JeK0A==}
engines: {node: '>= 12'}
@@@ -11145,9 -10740,9 +11145,12 @@@
resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-AY/tDXz8stMbx0MIutdn63Dz0uwY1VVMKIxCqOOA2hg5WGdCGm2qqEZF498deLDxoZbL+hDf1SwBWzvWADBoPA==}
+
+ resolution: {integrity: sha512-KaTi6/rwFEV1deDSjXF1z7PfvjTXSpul+viGuu6LT4SD6ATLBzkkBmsz5HOmpDj/bAyFP9oGlqzScSXsiOOXUA==}
+
resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}
engines: {node: 18 || 20 || >=22}
@@@ -12035,10 -11609,14 +12028,10 @@@
resolution: {integrity: sha512-OCVPnIObs4N29kxTjzLfUryOkvZEq+pf8jTF0lg8E7uETuWHA+v7j3c/xJmiqpX450191LlmZfUKkXxkTry7nA==}
engines: {node: ^10 || ^12 || >=14}
- resolution: {integrity: sha512-7a70Nsot+EMX9fFU3064K/kdHWZqGVY+BADLyXc8Dfv+mTLLVl6JzJpPaCZ2kQL9gIJvKXSLMHhqdRRjwQeFtw==}
+ resolution: {integrity: sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==}
engines: {node: ^10 || ^12 || >=14}
- resolution: {integrity: sha512-7a70Nsot+EMX9fFU3064K/kdHWZqGVY+BADLyXc8Dfv+mTLLVl6JzJpPaCZ2kQL9gIJvKXSLMHhqdRRjwQeFtw==}
- engines: {node: ^10 || ^12 || >=14}
-
resolution: {integrity: sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==}
engines: {node: '>=14.0.0'}
@@@ -13572,8 -13136,12 +13565,8 @@@
resolution: {integrity: sha512-u9r3uZC0bdpGOXtlxUIdwf9pkmvhqJdrVCH9fapQtgy/OeTTMZ1nqH7agtvEfmGui6e1XxjcdrlxvxJvc3sMqw==}
engines: {node: '>=18'}
-- resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==}
- engines: {node: '>=12.0.0'}
-
+ resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==}
engines: {node: '>=12.0.0'}
@@@ -14124,12 -13677,12 +14110,18 @@@
vite:
optional: true
+ resolution: {integrity: sha512-r3kQUrrimduikhyRm58ayemoxsgB8lZdn/JULLL4wpXHAZlYejtyZx7E/id7dwRtIOSYWu/tWvFjdEOTzso2MA==}
+ engines: {node: ^22.0.0 || >=24.0.0}
+ peerDependencies:
+ vite: '>=7.3.2'
+
+ resolution: {integrity: sha512-9XOarNV7LgP0KBB7AApxdgFikLXx3daZdqjC3AevYsL6MrUH62zphonLUs2a6LZc1HN1GY+vQdheZ8VVJb6dQQ==}
+ engines: {node: ^22.0.0 || >=24.0.0}
+ peerDependencies:
+ vite: '>=7.3.2'
+
resolution: {integrity: sha512-WaiOUlmt1fKw1w/WWJnx9gVk42D1BASKZmGCPpy6iTLE5iIemN2lim3MwI7Rffyt3aQnPrLfLSLnI8ZUJ9s49g==}
peerDependencies:
@@@ -17057,56 -16592,57 +17067,103 @@@ snapshots
'@eslint/core': 1.2.1
levn: 0.4.1
+ dependencies:
+ '@braintree/sanitize-url': 6.0.2
+ '@excalidraw/laser-pointer': 1.3.1
+ '@excalidraw/mermaid-to-excalidraw': 1.1.2
+ '@excalidraw/random-username': 1.1.0
+ '@radix-ui/react-tabs': 1.0.2([email protected]([email protected]))([email protected])
+ browser-fs-access: 0.29.1
+ canvas-roundrect-polyfill: 0.0.1
+ clsx: 1.1.1
+ cross-env: 7.0.3
+ es6-promise-pool: 2.5.0
+ fractional-indexing: 3.2.0
+ fuzzy: 0.1.3
+ image-blob-reduce: 3.0.1
+ jotai: 2.11.0(@types/[email protected])([email protected])
+ lodash.debounce: 4.0.8
+ lodash.throttle: 4.1.1
+ nanoid: 5.1.7
+ open-color: 1.9.1
+ pako: 2.0.3
+ perfect-freehand: 1.2.0
+ pica: 7.1.1
+ png-chunk-text: 1.0.0
+ png-chunks-encode: 1.0.0
+ png-chunks-extract: 1.0.0
+ points-on-curve: 1.0.1
+ pwacompat: 2.0.17
+ react: 19.2.4
+ react-dom: 19.2.4([email protected])
+ roughjs: 4.6.6
+ sass: 1.51.0
+ tunnel-rat: 0.1.2(@types/[email protected])([email protected])
+ transitivePeerDependencies:
+ - '@types/react'
+ - '@types/react-dom'
+ - immer
+
+ dependencies:
+ '@braintree/sanitize-url': 6.0.2
+ '@excalidraw/laser-pointer': 1.3.1
+ '@excalidraw/mermaid-to-excalidraw': 2.2.2
+ '@excalidraw/random-username': 1.1.0
+ '@radix-ui/react-tabs': 1.0.2([email protected]([email protected]))([email protected])
+ browser-fs-access: 0.29.1
+ canvas-roundrect-polyfill: 0.0.1
+ clsx: 1.1.1
+ cross-env: 7.0.3
+ es6-promise-pool: 2.5.0
+ fractional-indexing: 3.2.0
+ fuzzy: 0.1.3
+ image-blob-reduce: 3.0.1
+ jotai: 2.11.0(@types/[email protected])([email protected])
+ lodash.debounce: 4.0.8
+ lodash.throttle: 4.1.1
+ nanoid: 5.1.7
+ open-color: 1.9.1
+ pako: 2.0.3
+ perfect-freehand: 1.2.0
+ pica: 7.1.1
+ png-chunk-text: 1.0.0
+ png-chunks-encode: 1.0.0
+ png-chunks-extract: 1.0.0
+ points-on-curve: 1.0.1
+ pwacompat: 2.0.17
+ react: 19.2.4
+ react-dom: 19.2.4([email protected])
+ roughjs: 4.6.6
+ sass: 1.51.0
+ tunnel-rat: 0.1.2(@types/[email protected])([email protected])
+ transitivePeerDependencies:
+ - '@types/react'
+ - '@types/react-dom'
+ - immer
+
'@excalidraw/[email protected]': {}
'@excalidraw/[email protected]': {}
+ '@excalidraw/[email protected]':
+ dependencies:
+ '@excalidraw/markdown-to-text': 0.1.2
+ mermaid: 11.14.0
+ nanoid: 5.1.7
+
+ '@excalidraw/[email protected]':
+ dependencies:
+ '@excalidraw/markdown-to-text': 0.1.2
+ '@mermaid-js/parser': 0.6.3
+ mermaid: 11.14.0
+ nanoid: 5.1.7
+
'@excalidraw/[email protected]': {}
'@exercism/[email protected]': {}
@@@ -18194,10 -17658,10 +18255,14 @@@
'@microsoft/[email protected]': {}
+ dependencies:
+ mind-elixir: 5.10.0
+
+ dependencies:
+ mind-elixir: 5.11.0
+
'@mixmark-io/[email protected]': {}
'@modelcontextprotocol/[email protected]([email protected])':
@@@ -18530,23 -17983,7 +18584,23 @@@
'@popperjs/[email protected]': {}
+ dependencies:
+ '@babel/core': 7.29.0
+ '@babel/plugin-transform-react-jsx': 7.27.1(@babel/[email protected])
+ '@babel/plugin-transform-react-jsx-development': 7.27.1(@babel/[email protected])
+ '@rollup/pluginutils': 4.2.1
+ babel-plugin-transform-hook-names: 1.0.2(@babel/[email protected])
+ debug: 4.4.3
+ picocolors: 1.1.1
+ transitivePeerDependencies:
+ - preact
+ - supports-color
+
dependencies:
'@babel/core': 7.29.0
'@babel/plugin-transform-react-jsx': 7.27.1(@babel/[email protected])
@@@ -20164,8 -19593,8 +20218,10 @@@
'@types/methods': 1.1.4
'@types/superagent': 8.1.9
+ '@types/[email protected]': {}
+
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
@@@ -23339,7 -22664,7 +23299,7 @@@
normalize-path: 3.0.0
schema-utils: 4.3.3
serialize-javascript: 7.0.5
-- tinyglobby: 0.2.15
++ tinyglobby: 0.2.16
webpack: 5.105.4([email protected])
@@@ -25654,20 -24973,20 +25614,32 @@@
dependencies:
ms: 2.1.3
+
+ dependencies:
+ cross-fetch: 4.1.0([email protected])
+ transitivePeerDependencies:
+ - encoding
+ dependencies:
+ cross-fetch: 4.1.0([email protected])
+ transitivePeerDependencies:
+ - encoding
+
+ dependencies:
+ '@babel/runtime': 7.29.2
+ optionalDependencies:
+ typescript: 6.0.3
+
+ dependencies:
+ '@babel/runtime': 7.29.2
+ optionalDependencies:
+ typescript: 6.0.3
+
dependencies:
safer-buffer: 2.1.2
@@@ -26687,10 -25985,14 +26650,16 @@@
+ dependencies:
+ marked: 18.0.2
+
+
+
@@@ -27117,8 -26419,8 +27086,10 @@@
+
+
dependencies:
brace-expansion: 5.0.5
@@@ -28326,17 -27598,17 +28281,28 @@@
react: 19.2.4
scheduler: 0.27.0
+ dependencies:
+ '@babel/runtime': 7.29.2
+ html-parse-stringify: 3.0.1
+ i18next: 26.0.5([email protected])
+ react: 19.2.4
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ react-dom: 19.2.4([email protected])
+ typescript: 6.0.3
+
+ dependencies:
+ '@babel/runtime': 7.29.2
+ html-parse-stringify: 3.0.1
+ i18next: 26.0.6([email protected])
+ react: 19.2.4
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ react-dom: 19.2.4([email protected])
+ typescript: 6.0.3
+
dependencies:
detect-it: 3.0.7
@@@ -28920,7 -28187,7 +28886,7 @@@
htmlparser2: 10.1.0
is-plain-object: 5.0.0
parse-srcset: 1.0.2
-- postcss: 8.5.9
++ postcss: 8.5.10
dependencies:
@@@ -29714,7 -28976,7 +29679,7 @@@
lines-and-columns: 1.2.4
mz: 2.7.0
pirates: 4.0.7
-- tinyglobby: 0.2.15
++ tinyglobby: 0.2.16
ts-interface-checker: 0.1.13
@@@ -29929,7 -29187,12 +29894,7 @@@
- dependencies:
- fdir: 6.5.0([email protected])
- picomatch: 4.0.4
-
dependencies:
fdir: 6.5.0([email protected])
picomatch: 4.0.4
@@@ -30506,7 -29754,7 +30460,15 @@@
- rollup
- supports-color
++ dependencies:
++ chokidar: 3.6.0
++ p-map: 7.0.4
++ picocolors: 1.1.1
++ tinyglobby: 0.2.16
++
dependencies:
chokidar: 3.6.0
p-map: 7.0.4