Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
chore(prettier): fix all files
Elian Doran4cbb529fd4e9
diff --git a/.github/workflows_old/docker.yaml b/.github/workflows_old/docker.yamlindex c2db4becf4..39adce00a0 100644--- a/.github/workflows_old/docker.yaml+++ b/.github/workflows_old/docker.yaml@@ -1,53 +1,53 @@name: Publish Docker imageon:- push:- tags: [v*]+ push:+ tags: [v*]jobs:- push_to_registries:- name: Push Docker image to multiple registries- runs-on: ubuntu-latest- permissions:- packages: write- contents: read- steps:- - name: Checkout- uses: actions/checkout@v2- - name: Set up QEMU- uses: docker/setup-qemu-action@v1- - name: Docker meta- id: meta- uses: docker/metadata-action@v3- with:- images: |- zadam/trilium- ghcr.io/zadam/trilium- tags: |- type=semver,pattern={{version}}- type=semver,pattern={{major}}.{{minor}}-latest- type=match,pattern=(\d+.\d+).\d+\-beta,enable=${{ endsWith(github.ref, 'beta') }},group=1,suffix=-latest- - name: Set up Docker Buildx- uses: docker/setup-buildx-action@v1- with:- install: true- - name: Log in to Docker Hub- uses: docker/login-action@v1- with:- username: ${{ secrets.DOCKER_USERNAME }}- password: ${{ secrets.DOCKER_PASSWORD }}- - name: Log in to GitHub Docker Registry- uses: docker/login-action@v1- with:- registry: ghcr.io- username: ${{ github.repository_owner }}- password: ${{ secrets.GITHUB_TOKEN }}- - name: Create server-package.json- run: cat package.json | grep -v electron > server-package.json- - name: Build and Push- uses: docker/[email protected]- with:- context: .- platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6- push: true- cache-from: type=registry,ref=zadam/trilium:buildcache- cache-to: type=registry,ref=zadam/trilium:buildcache,mode=max- tags: ${{ steps.meta.outputs.tags }}+ push_to_registries:+ name: Push Docker image to multiple registries+ runs-on: ubuntu-latest+ permissions:+ packages: write+ contents: read+ steps:+ - name: Checkout+ uses: actions/checkout@v2+ - name: Set up QEMU+ uses: docker/setup-qemu-action@v1+ - name: Docker meta+ id: meta+ uses: docker/metadata-action@v3+ with:+ images: |+ zadam/trilium+ ghcr.io/zadam/trilium+ tags: |+ type=semver,pattern={{version}}+ type=semver,pattern={{major}}.{{minor}}-latest+ type=match,pattern=(\d+.\d+).\d+\-beta,enable=${{ endsWith(github.ref, 'beta') }},group=1,suffix=-latest+ - name: Set up Docker Buildx+ uses: docker/setup-buildx-action@v1+ with:+ install: true+ - name: Log in to Docker Hub+ uses: docker/login-action@v1+ with:+ username: ${{ secrets.DOCKER_USERNAME }}+ password: ${{ secrets.DOCKER_PASSWORD }}+ - name: Log in to GitHub Docker Registry+ uses: docker/login-action@v1+ with:+ registry: ghcr.io+ username: ${{ github.repository_owner }}+ password: ${{ secrets.GITHUB_TOKEN }}+ - name: Create server-package.json+ run: cat package.json | grep -v electron > server-package.json+ - name: Build and Push+ uses: docker/[email protected]+ with:+ context: .+ platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6+ push: true+ cache-from: type=registry,ref=zadam/trilium:buildcache+ cache-to: type=registry,ref=zadam/trilium:buildcache,mode=max+ tags: ${{ steps.meta.outputs.tags }}diff --git a/.vscode/extensions.json b/.vscode/extensions.jsonindex cf619af516..7fc3d99753 100644--- a/.vscode/extensions.json+++ b/.vscode/extensions.json@@ -1,6 +1,3 @@{- "recommendations": [- "lokalise.i18n-ally",- "editorconfig.editorconfig"- ]-}\ No newline at end of file+ "recommendations": ["lokalise.i18n-ally", "editorconfig.editorconfig"]+}diff --git a/.vscode/launch.json b/.vscode/launch.jsonindex 07248c0fb3..f8d4780a15 100644--- a/.vscode/launch.json+++ b/.vscode/launch.json@@ -1,24 +1,22 @@{- "version": "0.2.0",- "configurations": [- // nodemon should be installed globally, use npm i -g nodemon- {- "console": "integratedTerminal",- "internalConsoleOptions": "neverOpen",- "name": "nodemon start-server",- "program": "${workspaceFolder}/src/www",- "request": "launch",- "restart": true,- "runtimeExecutable": "nodemon",- "env": {- "TRILIUM_ENV": "dev",- "TRILIUM_DATA_DIR": "./data"- },- "skipFiles": [- "<node_internals>/**"- ],- "type": "node",- "outputCapture": "std",- },- ]-}\ No newline at end of file+ "version": "0.2.0",+ "configurations": [+ // nodemon should be installed globally, use npm i -g nodemon+ {+ "console": "integratedTerminal",+ "internalConsoleOptions": "neverOpen",+ "name": "nodemon start-server",+ "program": "${workspaceFolder}/src/www",+ "request": "launch",+ "restart": true,+ "runtimeExecutable": "nodemon",+ "env": {+ "TRILIUM_ENV": "dev",+ "TRILIUM_DATA_DIR": "./data"+ },+ "skipFiles": ["<node_internals>/**"],+ "type": "node",+ "outputCapture": "std"+ }+ ]+}diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex 1a141254a3..a9c07eb281 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -1,27 +1,22 @@{- "editor.formatOnSave": false,- "editor.defaultFormatter": "esbenp.prettier-vscode",- "files.eol": "\n",- "typescript.tsdk": "node_modules/typescript/lib",- "i18n-ally.sourceLanguage": "en",- "i18n-ally.keystyle": "nested",- "i18n-ally.localesPaths": [- "./src/public/translations",- "./translations"- ],- "[jsonc]": {- "editor.defaultFormatter": "vscode.json-language-features"- },- "[javascript]": {- "editor.defaultFormatter": "vscode.typescript-language-features"- },- "[typescript]": {- "editor.defaultFormatter": "vscode.typescript-language-features"- },- "github-actions.workflows.pinned.workflows": [- ".github/workflows/nightly.yml"- ],- "[css]": {- "editor.defaultFormatter": "vscode.css-language-features"- },+ "editor.formatOnSave": false,+ "editor.defaultFormatter": "esbenp.prettier-vscode",+ "files.eol": "\n",+ "typescript.tsdk": "node_modules/typescript/lib",+ "i18n-ally.sourceLanguage": "en",+ "i18n-ally.keystyle": "nested",+ "i18n-ally.localesPaths": ["./src/public/translations", "./translations"],+ "[jsonc]": {+ "editor.defaultFormatter": "vscode.json-language-features"+ },+ "[javascript]": {+ "editor.defaultFormatter": "vscode.typescript-language-features"+ },+ "[typescript]": {+ "editor.defaultFormatter": "vscode.typescript-language-features"+ },+ "github-actions.workflows.pinned.workflows": [".github/workflows/nightly.yml"],+ "[css]": {+ "editor.defaultFormatter": "vscode.css-language-features"+ }}diff --git a/.vscode/snippets.code-snippets b/.vscode/snippets.code-snippetsindex 792d1501f0..77b251a4ad 100644--- a/.vscode/snippets.code-snippets+++ b/.vscode/snippets.code-snippets@@ -1,26 +1,24 @@{- // Place your Notes workspace snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and- // description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope- // is left empty or omitted, the snippet gets applied to all languages. The prefix is what is- // used to trigger the snippet and the body will be expanded and inserted. Possible variables are:- // $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders.- // Placeholders with the same ids are connected.- // Example:- // "Print to console": {- // "scope": "javascript,typescript",- // "prefix": "log",- // "body": [- // "console.log('$1');",- // "$2"- // ],- // "description": "Log output to console"- // }+ // Place your Notes workspace snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and+ // description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope+ // is left empty or omitted, the snippet gets applied to all languages. The prefix is what is+ // used to trigger the snippet and the body will be expanded and inserted. Possible variables are:+ // $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders.+ // Placeholders with the same ids are connected.+ // Example:+ // "Print to console": {+ // "scope": "javascript,typescript",+ // "prefix": "log",+ // "body": [+ // "console.log('$1');",+ // "$2"+ // ],+ // "description": "Log output to console"+ // }- "JQuery HTMLElement field": {- "scope": "typescript",- "prefix": "jqf",- "body": [- "private $${1:name}!: JQuery<HTMLElement>;"- ]- }-}\ No newline at end of file+ "JQuery HTMLElement field": {+ "scope": "typescript",+ "prefix": "jqf",+ "body": ["private $${1:name}!: JQuery<HTMLElement>;"]+ }+}diff --git a/bin/copy-dist.ts b/bin/copy-dist.tsindex 69ca710b75..d594dcdb9a 100644--- a/bin/copy-dist.ts+++ b/bin/copy-dist.ts@@ -8,108 +8,108 @@ const DEST_DIR_NODE_MODULES = path.join(DEST_DIR, "node_modules");const VERBOSE = process.env.VERBOSE;function log(...args) {- if (VERBOSE) {- console.log(args);- }+ if (VERBOSE) {+ console.log(args);+ }}async function copyNodeModuleFileOrFolder(source: string) {- const adjustedSource = source.substring(13);- const destination = path.join(DEST_DIR_NODE_MODULES, adjustedSource);+ const adjustedSource = source.substring(13);+ const destination = path.join(DEST_DIR_NODE_MODULES, adjustedSource);- log(`Copying ${source} to ${destination}`);- await fs.ensureDir(path.dirname(destination));- await fs.copy(source, destination);+ log(`Copying ${source} to ${destination}`);+ await fs.ensureDir(path.dirname(destination));+ await fs.copy(source, destination);}const copy = async () => {- for (const srcFile of fs.readdirSync("build")) {- const destFile = path.join(DEST_DIR, path.basename(srcFile));- log(`Copying source ${srcFile} -> ${destFile}.`);- fs.copySync(path.join("build", srcFile), destFile, { recursive: true });- }+ for (const srcFile of fs.readdirSync("build")) {+ const destFile = path.join(DEST_DIR, path.basename(srcFile));+ log(`Copying source ${srcFile} -> ${destFile}.`);+ fs.copySync(path.join("build", srcFile), destFile, { recursive: true });+ }- const filesToCopy = ["config-sample.ini", "tsconfig.webpack.json"];- for (const file of filesToCopy) {- log(`Copying ${file}`);- await fs.copy(file, path.join(DEST_DIR, file));- }+ const filesToCopy = ["config-sample.ini", "tsconfig.webpack.json"];+ for (const file of filesToCopy) {+ log(`Copying ${file}`);+ await fs.copy(file, path.join(DEST_DIR, file));+ }- const dirsToCopy = ["images", "libraries", "translations", "db"];- for (const dir of dirsToCopy) {- log(`Copying ${dir}`);- await fs.copy(dir, path.join(DEST_DIR, dir));- }+ const dirsToCopy = ["images", "libraries", "translations", "db"];+ for (const dir of dirsToCopy) {+ log(`Copying ${dir}`);+ await fs.copy(dir, path.join(DEST_DIR, dir));+ }- const srcDirsToCopy = ["./src/public", "./src/views", "./build"];- for (const dir of srcDirsToCopy) {- log(`Copying ${dir}`);- await fs.copy(dir, path.join(DEST_DIR_SRC, path.basename(dir)));- }+ const srcDirsToCopy = ["./src/public", "./src/views", "./build"];+ for (const dir of srcDirsToCopy) {+ log(`Copying ${dir}`);+ await fs.copy(dir, path.join(DEST_DIR_SRC, path.basename(dir)));+ }- /**- * Directories to be copied relative to the project root into <resource_dir>/src/public/app-dist.- */- const publicDirsToCopy = [ "./src/public/app/doc_notes" ];- const PUBLIC_DIR = path.join(DEST_DIR, "src", "public", "app-dist");- for (const dir of publicDirsToCopy) {- await fs.copy(dir, path.join(PUBLIC_DIR, path.basename(dir)));- }+ /**+ * Directories to be copied relative to the project root into <resource_dir>/src/public/app-dist.+ */+ const publicDirsToCopy = ["./src/public/app/doc_notes"];+ const PUBLIC_DIR = path.join(DEST_DIR, "src", "public", "app-dist");+ for (const dir of publicDirsToCopy) {+ await fs.copy(dir, path.join(PUBLIC_DIR, path.basename(dir)));+ }- const nodeModulesFile = [- "node_modules/react/umd/react.production.min.js",- "node_modules/react/umd/react.development.js",- "node_modules/react-dom/umd/react-dom.production.min.js",- "node_modules/react-dom/umd/react-dom.development.js",- "node_modules/katex/dist/katex.min.js",- "node_modules/katex/dist/contrib/mhchem.min.js",- "node_modules/katex/dist/contrib/auto-render.min.js",- "node_modules/@highlightjs/cdn-assets/highlight.min.js",- "node_modules/@mind-elixir/node-menu/dist/node-menu.umd.cjs",- ];+ const nodeModulesFile = [+ "node_modules/react/umd/react.production.min.js",+ "node_modules/react/umd/react.development.js",+ "node_modules/react-dom/umd/react-dom.production.min.js",+ "node_modules/react-dom/umd/react-dom.development.js",+ "node_modules/katex/dist/katex.min.js",+ "node_modules/katex/dist/contrib/mhchem.min.js",+ "node_modules/katex/dist/contrib/auto-render.min.js",+ "node_modules/@highlightjs/cdn-assets/highlight.min.js",+ "node_modules/@mind-elixir/node-menu/dist/node-menu.umd.cjs"+ ];- for (const file of nodeModulesFile) {- await copyNodeModuleFileOrFolder(file);- }+ for (const file of nodeModulesFile) {+ await copyNodeModuleFileOrFolder(file);+ }- const nodeModulesFolder = [- "node_modules/@excalidraw/excalidraw/dist/",- "node_modules/katex/dist/",- "node_modules/dayjs/",- "node_modules/force-graph/dist/",- "node_modules/boxicons/css/",- "node_modules/boxicons/fonts/",- "node_modules/mermaid/dist/",- "node_modules/jquery/dist/",- "node_modules/jquery-hotkeys/",- "node_modules/print-this/",- "node_modules/split.js/dist/",- "node_modules/panzoom/dist/",- "node_modules/i18next/",- "node_modules/i18next-http-backend/",- "node_modules/eslint/bin/",- "node_modules/jsplumb/dist/",- "node_modules/vanilla-js-wheel-zoom/dist/",- "node_modules/mark.js/dist/",- "node_modules/knockout/build/output/",- "node_modules/normalize.css/",- "node_modules/jquery.fancytree/dist/",- "node_modules/bootstrap/dist/",- "node_modules/autocomplete.js/dist/",- "node_modules/codemirror/lib/",- "node_modules/codemirror/addon/",- "node_modules/codemirror/mode/",- "node_modules/codemirror/keymap/",- "node_modules/mind-elixir/dist/",- "node_modules/@highlightjs/cdn-assets/languages",- "node_modules/@highlightjs/cdn-assets/styles"- ];+ const nodeModulesFolder = [+ "node_modules/@excalidraw/excalidraw/dist/",+ "node_modules/katex/dist/",+ "node_modules/dayjs/",+ "node_modules/force-graph/dist/",+ "node_modules/boxicons/css/",+ "node_modules/boxicons/fonts/",+ "node_modules/mermaid/dist/",+ "node_modules/jquery/dist/",+ "node_modules/jquery-hotkeys/",+ "node_modules/print-this/",+ "node_modules/split.js/dist/",+ "node_modules/panzoom/dist/",+ "node_modules/i18next/",+ "node_modules/i18next-http-backend/",+ "node_modules/eslint/bin/",+ "node_modules/jsplumb/dist/",+ "node_modules/vanilla-js-wheel-zoom/dist/",+ "node_modules/mark.js/dist/",+ "node_modules/knockout/build/output/",+ "node_modules/normalize.css/",+ "node_modules/jquery.fancytree/dist/",+ "node_modules/bootstrap/dist/",+ "node_modules/autocomplete.js/dist/",+ "node_modules/codemirror/lib/",+ "node_modules/codemirror/addon/",+ "node_modules/codemirror/mode/",+ "node_modules/codemirror/keymap/",+ "node_modules/mind-elixir/dist/",+ "node_modules/@highlightjs/cdn-assets/languages",+ "node_modules/@highlightjs/cdn-assets/styles"+ ];- for (const folder of nodeModulesFolder) {- await copyNodeModuleFileOrFolder(folder);- }+ for (const folder of nodeModulesFolder) {+ await copyNodeModuleFileOrFolder(folder);+ }};copy()- .then(() => console.log("Copying complete!"))- .catch((err) => console.error("Error during copy:", err));+ .then(() => console.log("Copying complete!"))+ .catch((err) => console.error("Error during copy:", err));diff --git a/bin/create-anonymization-script.ts b/bin/create-anonymization-script.tsindex 5cf991b220..ff462ec5e2 100755--- a/bin/create-anonymization-script.ts+++ b/bin/create-anonymization-script.ts@@ -1,7 +1,7 @@#!/usr/bin/env node-import anonymizationService from '../src/services/anonymization.js';-import fs from 'fs';-import path from 'path';+import anonymizationService from "../src/services/anonymization.js";+import fs from "fs";+import path from "path";-fs.writeFileSync(path.resolve(__dirname, 'tpl', 'anonymize-database.sql'), anonymizationService.getFullAnonymizationScript());+fs.writeFileSync(path.resolve(__dirname, "tpl", "anonymize-database.sql"), anonymizationService.getFullAnonymizationScript());diff --git a/bin/docs/assets/v0.63.6/app-dist/share.js b/bin/docs/assets/v0.63.6/app-dist/share.jsindex 03ad925154..3c3282497a 100644--- a/bin/docs/assets/v0.63.6/app-dist/share.js+++ b/bin/docs/assets/v0.63.6/app-dist/share.js@@ -13,11 +13,15 @@ async function fetchNote(noteId = null) {return await resp.json();}-document.addEventListener('DOMContentLoaded', () => {- const toggleMenuButton = document.getElementById('toggleMenuButton');- const layout = document.getElementById('layout');+document.addEventListener(+ "DOMContentLoaded",+ () => {+ const toggleMenuButton = document.getElementById("toggleMenuButton");+ const layout = document.getElementById("layout");- if (toggleMenuButton && layout) {- toggleMenuButton.addEventListener('click', () => layout.classList.toggle('showMenu'));- }-}, false);+ if (toggleMenuButton && layout) {+ toggleMenuButton.addEventListener("click", () => layout.classList.toggle("showMenu"));+ }+ },+ false+);diff --git a/bin/docs/assets/v0.63.6/libraries/ckeditor/ckeditor-content.css b/bin/docs/assets/v0.63.6/libraries/ckeditor/ckeditor-content.cssindex 47274e5f41..41d0ab466e 100644--- a/bin/docs/assets/v0.63.6/libraries/ckeditor/ckeditor-content.css+++ b/bin/docs/assets/v0.63.6/libraries/ckeditor/ckeditor-content.css@@ -1,6 +1,8 @@/* !!!!!! TRILIUM CUSTOM CHANGES !!!!!! */-.printed-content .ck-widget__selection-handle, .printed-content .ck-widget__type-around { /* gets rid of triangles: https://github.com/zadam/trilium/issues/1129 */+.printed-content .ck-widget__selection-handle,+.printed-content .ck-widget__type-around {+ /* gets rid of triangles: https://github.com/zadam/trilium/issues/1129 */display: none;}@@ -59,7 +61,7 @@.ck-content .table table td,.ck-content .table table th {min-width: 2em;- padding: .4em;+ padding: 0.4em;border: 1px solid hsl(0, 0%, 75%);}/* @ckeditor/ckeditor5-table/theme/table.css */@@ -83,8 +85,8 @@text-align: center;color: var(--ck-color-selector-caption-text);background-color: var(--ck-color-selector-caption-background);- padding: .6em;- font-size: .75em;+ padding: 0.6em;+ font-size: 0.75em;outline-offset: -1px;}/* @ckeditor/ckeditor5-page-break/theme/pagebreak.css */@@ -98,7 +100,7 @@}/* @ckeditor/ckeditor5-page-break/theme/pagebreak.css */.ck-content .page-break::after {- content: '';+ content: "";position: absolute;border-bottom: 2px dashed hsl(0, 0%, 77%);width: 100%;@@ -107,7 +109,7 @@.ck-content .page-break__label {position: relative;z-index: 1;- padding: .3em .6em;+ padding: 0.3em 0.6em;display: block;text-transform: uppercase;border: 1px solid hsl(0, 0%, 77%);@@ -158,7 +160,7 @@margin-left: 0;}/* @ckeditor/ckeditor5-list/theme/todolist.css */-.ck-content[dir=rtl] .todo-list .todo-list__label > input {+.ck-content[dir="rtl"] .todo-list .todo-list__label > input {left: 0;margin-right: 0;right: -25px;@@ -169,7 +171,7 @@display: block;position: absolute;box-sizing: border-box;- content: '';+ content: "";width: 100%;height: 100%;border: 1px solid hsl(0, 0%, 20%);@@ -182,14 +184,14 @@position: absolute;box-sizing: content-box;pointer-events: none;- content: '';- left: calc( var(--ck-todo-list-checkmark-size) / 3 );- top: calc( var(--ck-todo-list-checkmark-size) / 5.3 );- width: calc( var(--ck-todo-list-checkmark-size) / 5.3 );- height: calc( var(--ck-todo-list-checkmark-size) / 2.6 );+ content: "";+ left: calc(var(--ck-todo-list-checkmark-size) / 3);+ top: calc(var(--ck-todo-list-checkmark-size) / 5.3);+ width: calc(var(--ck-todo-list-checkmark-size) / 5.3);+ height: calc(var(--ck-todo-list-checkmark-size) / 2.6);border-style: solid;border-color: transparent;- border-width: 0 calc( var(--ck-todo-list-checkmark-size) / 8 ) calc( var(--ck-todo-list-checkmark-size) / 8 ) 0;+ border-width: 0 calc(var(--ck-todo-list-checkmark-size) / 8) calc(var(--ck-todo-list-checkmark-size) / 8) 0;transform: rotate(45deg);}/* @ckeditor/ckeditor5-list/theme/todolist.css */@@ -206,20 +208,21 @@vertical-align: middle;}/* @ckeditor/ckeditor5-list/theme/todolist.css */-.ck-content .todo-list .todo-list__label.todo-list__label_without-description input[type=checkbox] {+.ck-content .todo-list .todo-list__label.todo-list__label_without-description input[type="checkbox"] {position: absolute;}/* @ckeditor/ckeditor5-list/theme/todolist.css */.ck-editor__editable.ck-content .todo-list .todo-list__label > input,-.ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable=false] > input {+.ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable="false"] > input {cursor: pointer;}/* @ckeditor/ckeditor5-list/theme/todolist.css */-.ck-editor__editable.ck-content .todo-list .todo-list__label > input:hover::before, .ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable=false] > input:hover::before {+.ck-editor__editable.ck-content .todo-list .todo-list__label > input:hover::before,+.ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable="false"] > input:hover::before {box-shadow: 0 0 0 5px hsla(0, 0%, 0%, 0.1);}/* @ckeditor/ckeditor5-list/theme/todolist.css */-.ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable=false] > input {+.ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable="false"] > input {-webkit-appearance: none;display: inline-block;position: relative;@@ -233,18 +236,18 @@margin-left: 0;}/* @ckeditor/ckeditor5-list/theme/todolist.css */-.ck-editor__editable.ck-content[dir=rtl] .todo-list .todo-list__label > span[contenteditable=false] > input {+.ck-editor__editable.ck-content[dir="rtl"] .todo-list .todo-list__label > span[contenteditable="false"] > input {left: 0;margin-right: 0;right: -25px;margin-left: -15px;}/* @ckeditor/ckeditor5-list/theme/todolist.css */-.ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable=false] > input::before {+.ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable="false"] > input::before {display: block;position: absolute;box-sizing: border-box;- content: '';+ content: "";width: 100%;height: 100%;border: 1px solid hsl(0, 0%, 20%);@@ -252,32 +255,32 @@transition: 250ms ease-in-out box-shadow;}/* @ckeditor/ckeditor5-list/theme/todolist.css */-.ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable=false] > input::after {+.ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable="false"] > input::after {display: block;position: absolute;box-sizing: content-box;pointer-events: none;- content: '';- left: calc( var(--ck-todo-list-checkmark-size) / 3 );- top: calc( var(--ck-todo-list-checkmark-size) / 5.3 );- width: calc( var(--ck-todo-list-checkmark-size) / 5.3 );- height: calc( var(--ck-todo-list-checkmark-size) / 2.6 );+ content: "";+ left: calc(var(--ck-todo-list-checkmark-size) / 3);+ top: calc(var(--ck-todo-list-checkmark-size) / 5.3);+ width: calc(var(--ck-todo-list-checkmark-size) / 5.3);+ height: calc(var(--ck-todo-list-checkmark-size) / 2.6);border-style: solid;border-color: transparent;- border-width: 0 calc( var(--ck-todo-list-checkmark-size) / 8 ) calc( var(--ck-todo-list-checkmark-size) / 8 ) 0;+ border-width: 0 calc(var(--ck-todo-list-checkmark-size) / 8) calc(var(--ck-todo-list-checkmark-size) / 8) 0;transform: rotate(45deg);}/* @ckeditor/ckeditor5-list/theme/todolist.css */-.ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable=false] > input[checked]::before {+.ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable="false"] > input[checked]::before {background: hsl(126, 64%, 41%);border-color: hsl(126, 64%, 41%);}/* @ckeditor/ckeditor5-list/theme/todolist.css */-.ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable=false] > input[checked]::after {+.ck-editor__editable.ck-content .todo-list .todo-list__label > span[contenteditable="false"] > input[checked]::after {border-color: hsl(0, 0%, 100%);}/* @ckeditor/ckeditor5-list/theme/todolist.css */-.ck-editor__editable.ck-content .todo-list .todo-list__label.todo-list__label_without-description input[type=checkbox] {+.ck-editor__editable.ck-content .todo-list .todo-list__label.todo-list__label_without-description input[type="checkbox"] {position: absolute;}/* @ckeditor/ckeditor5-list/theme/list.css */@@ -379,8 +382,8 @@word-break: break-word;color: var(--ck-color-image-caption-text);background-color: var(--ck-color-image-caption-background);- padding: .6em;- font-size: .75em;+ padding: 0.6em;+ font-size: 0.75em;outline-offset: -1px;}/* @ckeditor/ckeditor5-image/theme/imagestyle.css */@@ -488,16 +491,16 @@/* @ckeditor/ckeditor5-basic-styles/theme/code.css */.ck-content code {background-color: hsla(0, 0%, 78%, 0.3);- padding: .15em;+ padding: 0.15em;border-radius: 2px;}/* @ckeditor/ckeditor5-font/theme/fontsize.css */.ck-content .text-tiny {- font-size: .7em;+ font-size: 0.7em;}/* @ckeditor/ckeditor5-font/theme/fontsize.css */.ck-content .text-small {- font-size: .85em;+ font-size: 0.85em;}/* @ckeditor/ckeditor5-font/theme/fontsize.css */.ck-content .text-big {diff --git a/bin/docs/assets/v0.63.6/libraries/normalize.min.css b/bin/docs/assets/v0.63.6/libraries/normalize.min.cssindex 87aa24dc54..3d24d023de 100644--- a/bin/docs/assets/v0.63.6/libraries/normalize.min.css+++ b/bin/docs/assets/v0.63.6/libraries/normalize.min.css@@ -1,2 +1,148 @@-/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none}-/*# sourceMappingURL=normalize.min.css.map */\ No newline at end of file+/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */+html {+ line-height: 1.15;+ -webkit-text-size-adjust: 100%;+}+body {+ margin: 0;+}+main {+ display: block;+}+h1 {+ font-size: 2em;+ margin: 0.67em 0;+}+hr {+ box-sizing: content-box;+ height: 0;+ overflow: visible;+}+pre {+ font-family: monospace, monospace;+ font-size: 1em;+}+a {+ background-color: transparent;+}+abbr[title] {+ border-bottom: none;+ text-decoration: underline;+ text-decoration: underline dotted;+}+b,+strong {+ font-weight: bolder;+}+code,+kbd,+samp {+ font-family: monospace, monospace;+ font-size: 1em;+}+small {+ font-size: 80%;+}+sub,+sup {+ font-size: 75%;+ line-height: 0;+ position: relative;+ vertical-align: baseline;+}+sub {+ bottom: -0.25em;+}+sup {+ top: -0.5em;+}+img {+ border-style: none;+}+button,+input,+optgroup,+select,+textarea {+ font-family: inherit;+ font-size: 100%;+ line-height: 1.15;+ margin: 0;+}+button,+input {+ overflow: visible;+}+button,+select {+ text-transform: none;+}+[type="button"],+[type="reset"],+[type="submit"],+button {+ -webkit-appearance: button;+}+[type="button"]::-moz-focus-inner,+[type="reset"]::-moz-focus-inner,+[type="submit"]::-moz-focus-inner,+button::-moz-focus-inner {+ border-style: none;+ padding: 0;+}+[type="button"]:-moz-focusring,+[type="reset"]:-moz-focusring,+[type="submit"]:-moz-focusring,+button:-moz-focusring {+ outline: 1px dotted ButtonText;+}+fieldset {+ padding: 0.35em 0.75em 0.625em;+}+legend {+ box-sizing: border-box;+ color: inherit;+ display: table;+ max-width: 100%;+ padding: 0;+ white-space: normal;+}+progress {+ vertical-align: baseline;+}+textarea {+ overflow: auto;+}+[type="checkbox"],+[type="radio"] {+ box-sizing: border-box;+ padding: 0;+}+[type="number"]::-webkit-inner-spin-button,+[type="number"]::-webkit-outer-spin-button {+ height: auto;+}+[type="search"] {+ -webkit-appearance: textfield;+ outline-offset: -2px;+}+[type="search"]::-webkit-search-decoration {+ -webkit-appearance: none;+}+::-webkit-file-upload-button {+ -webkit-appearance: button;+ font: inherit;+}+details {+ display: block;+}+summary {+ display: list-item;+}+template {+ display: none;+}+[hidden] {+ display: none;+}+/*# sourceMappingURL=normalize.min.css.map */diff --git a/bin/docs/assets/v0.63.6/stylesheets/share.css b/bin/docs/assets/v0.63.6/stylesheets/share.cssindex 718f8594c3..457898d8f6 100644--- a/bin/docs/assets/v0.63.6/stylesheets/share.css+++ b/bin/docs/assets/v0.63.6/stylesheets/share.css@@ -1,5 +1,5 @@body {- font-family: 'Lucida Grande', 'Lucida Sans Unicode', arial, sans-serif;+ font-family: "Lucida Grande", "Lucida Sans Unicode", arial, sans-serif;line-height: 1.5;}diff --git a/bin/update-build-info.ts b/bin/update-build-info.tsindex 25356c4684..4635bb8ea3 100644--- a/bin/update-build-info.ts+++ b/bin/update-build-info.ts@@ -4,15 +4,11 @@ import fs from "fs";function getBuildDate() {const now = new Date();now.setMilliseconds(0);- return now- .toISOString()- .replace(".000", "");+ return now.toISOString().replace(".000", "");}function getGitRevision() {- return child_process.execSync('git log -1 --format="%H"')- .toString("utf-8")- .trimEnd();+ return child_process.execSync('git log -1 --format="%H"').toString("utf-8").trimEnd();}const output = `\diff --git a/bin/update-nightly-version.ts b/bin/update-nightly-version.tsindex c700e3b221..b08231dda9 100644--- a/bin/update-nightly-version.ts+++ b/bin/update-nightly-version.ts@@ -20,11 +20,7 @@ function processVersion(version) {version = version.replace("-beta", "");// Add the nightly suffix, plus the date.- const referenceDate = new Date()- .toISOString()- .substring(2, 19)- .replace(/[-:]*/g, "")- .replace("T", "-");+ const referenceDate = new Date().toISOString().substring(2, 19).replace(/[-:]*/g, "").replace("T", "-");version = `${version}-test-${referenceDate}`;return version;diff --git a/bin/watch-dist.ts b/bin/watch-dist.tsindex 9faa8d7a2e..8c76034af1 100644--- a/bin/watch-dist.ts+++ b/bin/watch-dist.ts@@ -12,7 +12,5 @@ function onFileChanged(sourceFile: string) {const sourceDir = "src/public";-chokidar- .watch(sourceDir)- .on("change", onFileChanged);+chokidar.watch(sourceDir).on("change", onFileChanged);console.log(`Watching for changes to ${sourceDir}...`);diff --git a/db/migrations/0216__move_content_into_blobs.js b/db/migrations/0216__move_content_into_blobs.jsindex eea287b210..53586d0e3d 100644--- a/db/migrations/0216__move_content_into_blobs.js+++ b/db/migrations/0216__move_content_into_blobs.js@@ -1,6 +1,6 @@module.exports = () => {- const sql = require('../../src/services/sql');- const utils = require('../../src/services/utils');+ const sql = require("../../src/services/sql");+ const utils = require("../../src/services/utils");const existingBlobIds = new Set();@@ -11,7 +11,7 @@ module.exports = () => {if (!existingBlobIds.has(blobId)) {existingBlobIds.add(blobId);- sql.insert('blobs', {+ sql.insert("blobs", {blobId,content: row.content,dateModified: row.dateModified,@@ -24,7 +24,7 @@ module.exports = () => {sql.execute("DELETE FROM entity_changes WHERE entityName = 'note_contents' AND entityId = ?", [row.noteId]);}- sql.execute('UPDATE notes SET blobId = ? WHERE noteId = ?', [blobId, row.noteId]);+ sql.execute("UPDATE notes SET blobId = ? WHERE noteId = ?", [blobId, row.noteId]);}for (const noteRevisionId of sql.getColumn(`SELECT noteRevisionId FROM note_revision_contents`)) {@@ -34,7 +34,7 @@ module.exports = () => {if (!existingBlobIds.has(blobId)) {existingBlobIds.add(blobId);- sql.insert('blobs', {+ sql.insert("blobs", {blobId,content: row.content,dateModified: row.utcDateModified,@@ -47,7 +47,7 @@ module.exports = () => {sql.execute("DELETE FROM entity_changes WHERE entityName = 'note_revision_contents' AND entityId = ?", [row.noteId]);}- sql.execute('UPDATE note_revisions SET blobId = ? WHERE noteRevisionId = ?', [blobId, row.noteRevisionId]);+ sql.execute("UPDATE note_revisions SET blobId = ? WHERE noteRevisionId = ?", [blobId, row.noteRevisionId]);}const notesWithoutBlobIds = sql.getColumn("SELECT noteId FROM notes WHERE blobId IS NULL");diff --git a/db/migrations/0220__migrate_images_to_attachments.js b/db/migrations/0220__migrate_images_to_attachments.jsindex f88894820f..a93e2028d7 100644--- a/db/migrations/0220__migrate_images_to_attachments.js+++ b/db/migrations/0220__migrate_images_to_attachments.js@@ -1,9 +1,9 @@module.exports = () => {- const beccaLoader = require('../../src/becca/becca_loader');- const becca = require('../../src/becca/becca');- const cls = require('../../src/services/cls');- const log = require('../../src/services/log');- const sql = require('../../src/services/sql');+ const beccaLoader = require("../../src/becca/becca_loader");+ const becca = require("../../src/becca/becca");+ const cls = require("../../src/services/cls");+ const log = require("../../src/services/log");+ const sql = require("../../src/services/sql");cls.init(() => {// emergency disabling of image compression since it appears to make problems in migration to 0.61@@ -18,8 +18,7 @@ module.exports = () => {if (attachment) {log.info(`Auto-converted note '${note.noteId}' into attachment '${attachment.attachmentId}'.`);}- }- catch (e) {+ } catch (e) {log.error(`Cannot convert note '${note.noteId}' to attachment: ${e.message} ${e.stack}`);}}diff --git a/docker_healthcheck.ts b/docker_healthcheck.tsindex c11c853a4a..2a2635db2e 100755--- a/docker_healthcheck.ts+++ b/docker_healthcheck.ts@@ -1,8 +1,8 @@import http from "http";import ini from "ini";import fs from "fs";-import dataDir from './src/services/data_dir.js';-const config = ini.parse(fs.readFileSync(dataDir.CONFIG_INI_PATH, 'utf-8'));+import dataDir from "./src/services/data_dir.js";+const config = ini.parse(fs.readFileSync(dataDir.CONFIG_INI_PATH, "utf-8"));if (config.Network.https) {// built-in TLS (terminated by trilium) is not supported yet, PRs are welcome@@ -10,12 +10,12 @@ if (config.Network.https) {process.exit(0);}-import port from './src/services/port.js';-import host from './src/services/host.js';+import port from "./src/services/port.js";+import host from "./src/services/host.js";const options: http.RequestOptions = { timeout: 2000 };-const callback: (res: http.IncomingMessage) => void = res => {+const callback: (res: http.IncomingMessage) => void = (res) => {console.log(`STATUS: ${res.statusCode}`);if (res.statusCode === 200) {process.exit(0);@@ -26,16 +26,18 @@ const callback: (res: http.IncomingMessage) => void = res => {let request;-if (port !== 0) { // TCP socket.+if (port !== 0) {+ // TCP socket.const url = `http://${host}:${port}/api/health-check`;request = http.request(url, options, callback);-} else { // Unix socket.+} else {+ // Unix socket.options.socketPath = host;- options.path = '/api/health-check';+ options.path = "/api/health-check";request = http.request(options, callback);}-request.on("error", err => {+request.on("error", (err) => {console.log("ERROR");process.exit(1);});diff --git a/dump-db/dump-db.ts b/dump-db/dump-db.tsindex 44273a7267..e00f1c6152 100755--- a/dump-db/dump-db.ts+++ b/dump-db/dump-db.ts@@ -1,33 +1,37 @@#!/usr/bin/env node-import yargs from 'yargs';-import { hideBin } from 'yargs/helpers';-import dumpService from './inc/dump.js';+import yargs from "yargs";+import { hideBin } from "yargs/helpers";+import dumpService from "./inc/dump.js";yargs(hideBin(process.argv))- .command('$0 <path_to_document> <target_directory>', 'dump the contents of document.db into the target directory', (yargs) => {- return yargs- .option('path_to_document', { alias: 'p', describe: 'path to the document.db', type: 'string', demandOption: true })- .option('target_directory', { alias: 't', describe: 'path of the directory into which the notes should be dumped', type: 'string', demandOption: true });- }, (argv) => {- try {- dumpService.dumpDocument(argv.path_to_document, argv.target_directory, {- includeDeleted: argv.includeDeleted,- password: argv.password- });+ .command(+ "$0 <path_to_document> <target_directory>",+ "dump the contents of document.db into the target directory",+ (yargs) => {+ return yargs+ .option("path_to_document", { alias: "p", describe: "path to the document.db", type: "string", demandOption: true })+ .option("target_directory", { alias: "t", describe: "path of the directory into which the notes should be dumped", type: "string", demandOption: true });+ },+ (argv) => {+ try {+ dumpService.dumpDocument(argv.path_to_document, argv.target_directory, {+ includeDeleted: argv.includeDeleted,+ password: argv.password+ });+ } catch (e) {+ console.error(`Unrecoverable error:`, e);+ process.exit(1);+ }}- catch (e) {- console.error(`Unrecoverable error:`, e);- process.exit(1);- }- })- .option('password', {- type: 'string',- description: 'Set password to be able to decrypt protected notes.'+ )+ .option("password", {+ type: "string",+ description: "Set password to be able to decrypt protected notes."})- .option('include-deleted', {- type: 'boolean',+ .option("include-deleted", {+ type: "boolean",default: false,- description: 'If set to true, dump also deleted notes.'+ description: "If set to true, dump also deleted notes."}).parse();diff --git a/dump-db/inc/data_key.ts b/dump-db/inc/data_key.tsindex a2781c8e14..35594926ae 100644--- a/dump-db/inc/data_key.ts+++ b/dump-db/inc/data_key.ts@@ -1,6 +1,6 @@-import crypto from 'crypto';-import sql from './sql.js';-import decryptService from './decrypt.js';+import crypto from "crypto";+import sql from "./sql.js";+import decryptService from "./decrypt.js";function getDataKey(password: any) {if (!password) {@@ -10,26 +10,24 @@ function getDataKey(password: any) {try {const passwordDerivedKey = getPasswordDerivedKey(password);- const encryptedDataKey = getOption('encryptedDataKey');+ const encryptedDataKey = getOption("encryptedDataKey");const decryptedDataKey = decryptService.decrypt(passwordDerivedKey, encryptedDataKey, 16);return decryptedDataKey;- }- catch (e: any) {+ } catch (e: any) {throw new Error(`Cannot read data key, the entered password might be wrong. The underlying error: '${e.message}', stack:\n${e.stack}`);}}function getPasswordDerivedKey(password: any) {- const salt = getOption('passwordDerivedKeySalt');+ const salt = getOption("passwordDerivedKeySalt");return getScryptHash(password, salt);}function getScryptHash(password: any, salt: any) {- const hashed = crypto.scryptSync(password, salt, 32,- { N: 16384, r: 8, p: 1 });+ const hashed = crypto.scryptSync(password, salt, 32, { N: 16384, r: 8, p: 1 });return hashed;}diff --git a/dump-db/inc/decrypt.ts b/dump-db/inc/decrypt.tsindex e30c362bcb..d7ae92614f 100644--- a/dump-db/inc/decrypt.ts+++ b/dump-db/inc/decrypt.ts@@ -1,4 +1,4 @@-import crypto from 'crypto';+import crypto from "crypto";function decryptString(dataKey: any, cipherText: any) {const buffer = decrypt(dataKey, cipherText);@@ -7,9 +7,9 @@ function decryptString(dataKey: any, cipherText: any) {return null;}- const str = buffer.toString('utf-8');+ const str = buffer.toString("utf-8");- if (str === 'false') {+ if (str === "false") {throw new Error("Could not decrypt string.");}@@ -26,12 +26,12 @@ function decrypt(key: any, cipherText: any, ivLength = 13) {}try {- const cipherTextBufferWithIv = Buffer.from(cipherText.toString(), 'base64');+ const cipherTextBufferWithIv = Buffer.from(cipherText.toString(), "base64");const iv = cipherTextBufferWithIv.slice(0, ivLength);const cipherTextBuffer = cipherTextBufferWithIv.slice(ivLength);- const decipher = crypto.createDecipheriv('aes-128-cbc', pad(key), pad(iv));+ const decipher = crypto.createDecipheriv("aes-128-cbc", pad(key), pad(iv));const decryptedBytes = Buffer.concat([decipher.update(cipherTextBuffer), decipher.final()]);@@ -45,14 +45,12 @@ function decrypt(key: any, cipherText: any, ivLength = 13) {}return payload;- }- catch (e: any) {+ } catch (e: any) {// recovery from https://github.com/zadam/trilium/issues/510if (e.message?.includes("WRONG_FINAL_BLOCK_LENGTH") || e.message?.includes("wrong final block length")) {console.log("Caught WRONG_FINAL_BLOCK_LENGTH, returning cipherText instead");return cipherText;- }- else {+ } else {throw e;}}@@ -61,8 +59,7 @@ function decrypt(key: any, cipherText: any, ivLength = 13) {function pad(data: any) {if (data.length > 16) {data = data.slice(0, 16);- }- else if (data.length < 16) {+ } else if (data.length < 16) {const zeros = Array(16 - data.length).fill(0);data = Buffer.concat([data, Buffer.from(zeros)]);@@ -82,7 +79,7 @@ function arraysIdentical(a: any, b: any) {function shaArray(content: any) {// we use this as simple checksum and don't rely on its security so SHA-1 is good enough- return crypto.createHash('sha1').update(content).digest();+ return crypto.createHash("sha1").update(content).digest();}export default {diff --git a/dump-db/inc/dump.ts b/dump-db/inc/dump.tsindex 4bb51e1815..cb4960f029 100644--- a/dump-db/inc/dump.ts+++ b/dump-db/inc/dump.ts@@ -1,11 +1,11 @@-import fs from 'fs';-import sanitize from 'sanitize-filename';-import sql from './sql.js';-import decryptService from './decrypt.js';-import dataKeyService from './data_key.js';-import extensionService from './extension.js';--function dumpDocument(documentPath: string, targetPath: string, options: { password: any; includeDeleted: any; }) {+import fs from "fs";+import sanitize from "sanitize-filename";+import sql from "./sql.js";+import decryptService from "./decrypt.js";+import dataKeyService from "./data_key.js";+import extensionService from "./extension.js";++function dumpDocument(documentPath: string, targetPath: string, options: { password: any; includeDeleted: any }) {const stats = {succeeded: 0,failed: 0,@@ -22,7 +22,7 @@ function dumpDocument(documentPath: string, targetPath: string, options: { passwconst existingPaths: Record<string, any> = {};const noteIdToPath: Record<string, any> = {};- dumpNote(targetPath, 'root');+ dumpNote(targetPath, "root");printDumpResults(stats, options);@@ -56,10 +56,10 @@ function dumpDocument(documentPath: string, targetPath: string, options: { passwsafeTitle = safeTitle.substring(0, 20);}- childTargetPath = targetPath + '/' + safeTitle;+ childTargetPath = targetPath + "/" + safeTitle;for (let i = 1; i < 100000 && childTargetPath in existingPaths; i++) {- childTargetPath = targetPath + '/' + safeTitle + '_' + i;+ childTargetPath = targetPath + "/" + safeTitle + "_" + i;}existingPaths[childTargetPath] = true;@@ -93,8 +93,7 @@ function dumpDocument(documentPath: string, targetPath: string, options: { passw}noteIdToPath[noteId] = childTargetPath;- }- catch (e: any) {+ } catch (e: any) {console.error(`DUMPERROR: Writing '${noteId}' failed with error '${e.message}':\n${e.stack}`);stats.failed++;@@ -104,13 +103,12 @@ function dumpDocument(documentPath: string, targetPath: string, options: { passwif (childNoteIds.length > 0) {if (childTargetPath === fileNameWithPath) {- childTargetPath += '_dir';+ childTargetPath += "_dir";}try {fs.mkdirSync(childTargetPath as string, { recursive: true });- }- catch (e: any) {+ } catch (e: any) {console.error(`DUMPERROR: Creating directory ${childTargetPath} failed with error '${e.message}'`);}@@ -122,12 +120,12 @@ function dumpDocument(documentPath: string, targetPath: string, options: { passw}function printDumpResults(stats: any, options: any) {- console.log('\n----------------------- STATS -----------------------');- console.log('Successfully dumpted notes: ', stats.succeeded.toString().padStart(5, ' '));- console.log('Protected notes: ', stats.protected.toString().padStart(5, ' '), options.password ? '' : '(skipped)');- console.log('Failed notes: ', stats.failed.toString().padStart(5, ' '));- console.log('Deleted notes: ', stats.deleted.toString().padStart(5, ' '), options.includeDeleted ? "(dumped)" : "(at least, skipped)");- console.log('-----------------------------------------------------');+ console.log("\n----------------------- STATS -----------------------");+ console.log("Successfully dumpted notes: ", stats.succeeded.toString().padStart(5, " "));+ console.log("Protected notes: ", stats.protected.toString().padStart(5, " "), options.password ? "" : "(skipped)");+ console.log("Failed notes: ", stats.failed.toString().padStart(5, " "));+ console.log("Deleted notes: ", stats.deleted.toString().padStart(5, " "), options.includeDeleted ? "(dumped)" : "(at least, skipped)");+ console.log("-----------------------------------------------------");if (!options.password && stats.protected > 0) {console.log("\nWARNING: protected notes are present in the document but no password has been provided. Protected notes have not been dumped.");@@ -140,12 +138,10 @@ function isContentEmpty(content: any) {}if (typeof content === "string") {- return !content.trim() || content.trim() === '<p></p>';- }- else if (Buffer.isBuffer(content)) {+ return !content.trim() || content.trim() === "<p></p>";+ } else if (Buffer.isBuffer(content)) {return content.length === 0;- }- else {+ } else {return false;}}diff --git a/dump-db/inc/extension.ts b/dump-db/inc/extension.tsindex 612e1ce235..73c90a2b7f 100644--- a/dump-db/inc/extension.ts+++ b/dump-db/inc/extension.ts@@ -5,15 +5,17 @@ function getFileName(note: any, childTargetPath: string, safeTitle: string) {let existingExtension = path.extname(safeTitle).toLowerCase();let newExtension;- if (note.type === 'text') {- newExtension = 'html';- } else if (note.mime === 'application/x-javascript' || note.mime === 'text/javascript') {- newExtension = 'js';- } else if (existingExtension.length > 0) { // if the page already has an extension, then we'll just keep it+ if (note.type === "text") {+ newExtension = "html";+ } else if (note.mime === "application/x-javascript" || note.mime === "text/javascript") {+ newExtension = "js";+ } else if (existingExtension.length > 0) {+ // if the page already has an extension, then we'll just keep itnewExtension = null;} else {- if (note.mime?.toLowerCase()?.trim() === "image/jpg") { // image/jpg is invalid but pretty common- newExtension = 'jpg';+ if (note.mime?.toLowerCase()?.trim() === "image/jpg") {+ // image/jpg is invalid but pretty common+ newExtension = "jpg";} else {newExtension = mimeTypes.extension(note.mime) || "dat";}diff --git a/dump-db/inc/sql.ts b/dump-db/inc/sql.tsindex 00d6296a21..c0f6ebc50b 100644--- a/dump-db/inc/sql.ts+++ b/dump-db/inc/sql.ts@@ -2,7 +2,9 @@ import Database, { Database as DatabaseType } from "better-sqlite3";let dbConnection: DatabaseType;-const openDatabase = (documentPath: string) => { dbConnection = new Database(documentPath, { readonly: true }) };+const openDatabase = (documentPath: string) => {+ dbConnection = new Database(documentPath, { readonly: true });+};const getRow = (query: string, params: string[] = []): Record<string, any> => dbConnection.prepare(query).get(params) as Record<string, any>;const getRows = (query: string, params = []) => dbConnection.prepare(query).all(params);diff --git a/dump-db/tsconfig.json b/dump-db/tsconfig.jsonindex eb70c28dbb..1865f5d1bd 100644--- a/dump-db/tsconfig.json+++ b/dump-db/tsconfig.json@@ -1,10 +1,10 @@{- "compilerOptions": {- "module": "ESNext",- "moduleResolution": "node",- "esModuleInterop": true,- "allowSyntheticDefaultImports": true,- "target": "ES6",- "strict": true- }-}\ No newline at end of file+ "compilerOptions": {+ "module": "ESNext",+ "moduleResolution": "node",+ "esModuleInterop": true,+ "allowSyntheticDefaultImports": true,+ "target": "ES6",+ "strict": true+ }+}diff --git a/electron-main.ts b/electron-main.tsindex 58fae2dd94..424209012e 100644--- a/electron-main.ts+++ b/electron-main.ts@@ -1,4 +1,4 @@import { initializeTranslations } from "./src/services/i18n.js";await initializeTranslations();-await import("./electron.js")+await import("./electron.js");diff --git a/electron.ts b/electron.tsindex 188240610d..154ec38d41 100644--- a/electron.ts+++ b/electron.ts@@ -12,8 +12,8 @@ import sourceMapSupport from "source-map-support";sourceMapSupport.install();// Prevent Trilium starting twice on first install and on uninstall for the Windows installer.-if ((await import('electron-squirrel-startup')).default) {- process.exit(0);+if ((await import("electron-squirrel-startup")).default) {+ process.exit(0);}// Adds debug features like hotkeys for triggering dev tools and reload@@ -24,50 +24,48 @@ appIconService.installLocalAppIcon();electronDl({ saveAs: true });// needed for excalidraw export https://github.com/zadam/trilium/issues/4271-electron.app.commandLine.appendSwitch(- "enable-experimental-web-platform-features"-);+electron.app.commandLine.appendSwitch("enable-experimental-web-platform-features");// Quit when all windows are closed, except on macOS. There, it's common// for applications and their menu bar to stay active until the user quits// explicitly with Cmd + Q.electron.app.on("window-all-closed", () => {- if (process.platform !== "darwin") {- electron.app.quit();- }+ if (process.platform !== "darwin") {+ electron.app.quit();+ }});electron.app.on("ready", async () => {- // electron.app.setAppUserModelId('com.github.zadam.trilium');-- // if db is not initialized -> setup process- // if db is initialized, then we need to wait until the migration process is finished- if (sqlInit.isDbInitialized()) {- await sqlInit.dbReady;+ // electron.app.setAppUserModelId('com.github.zadam.trilium');- await windowService.createMainWindow(electron.app);+ // if db is not initialized -> setup process+ // if db is initialized, then we need to wait until the migration process is finished+ if (sqlInit.isDbInitialized()) {+ await sqlInit.dbReady;- if (process.platform === "darwin") {- electron.app.on("activate", async () => {- if (electron.BrowserWindow.getAllWindows().length === 0) {await windowService.createMainWindow(electron.app);++ if (process.platform === "darwin") {+ electron.app.on("activate", async () => {+ if (electron.BrowserWindow.getAllWindows().length === 0) {+ await windowService.createMainWindow(electron.app);+ }+ });}- });- }- tray.createTray();- } else {- await windowService.createSetupWindow();- }+ tray.createTray();+ } else {+ await windowService.createSetupWindow();+ }- await windowService.registerGlobalShortcuts();+ await windowService.registerGlobalShortcuts();});electron.app.on("will-quit", () => {- electron.globalShortcut.unregisterAll();+ electron.globalShortcut.unregisterAll();});// this is to disable electron warning spam in the dev console (local development only)process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";-await import('./src/main.js');+await import("./src/main.js");diff --git a/forge.config.cjs b/forge.config.cjsindex 3d29c84f03..64ef74b165 100644--- a/forge.config.cjs+++ b/forge.config.cjs@@ -1,117 +1,115 @@-const path = require('path');-const fs = require('fs-extra');+const path = require("path");+const fs = require("fs-extra");const APP_NAME = "TriliumNext Notes";module.exports = {- packagerConfig: {- executableName: "trilium",- name: APP_NAME,- overwrite: true,- asar: true,- icon: "./images/app-icons/icon",- extraResource: [- // Moved to root- ...getExtraResourcesForPlatform(),+ packagerConfig: {+ executableName: "trilium",+ name: APP_NAME,+ overwrite: true,+ asar: true,+ icon: "./images/app-icons/icon",+ extraResource: [+ // Moved to root+ ...getExtraResourcesForPlatform(),- // Moved to resources (TriliumNext Notes.app/Contents/Resources on macOS)- "translations/",- "node_modules/@highlightjs/cdn-assets/styles"- ],- afterComplete: [(buildPath, _electronVersion, platform, _arch, callback) => {- const extraResources = getExtraResourcesForPlatform();- for (const resource of extraResources) {- const baseName = path.basename(resource);- let sourcePath;- if (platform === 'darwin') {- sourcePath = path.join(buildPath, `${APP_NAME}.app`, 'Contents', 'Resources', baseName);- } else {- sourcePath = path.join(buildPath, 'resources', baseName);- }- let destPath;-- if (baseName !== "256x256.png") {- destPath = path.join(buildPath, baseName);- } else {- destPath = path.join(buildPath, "icon.png");- }+ // Moved to resources (TriliumNext Notes.app/Contents/Resources on macOS)+ "translations/",+ "node_modules/@highlightjs/cdn-assets/styles"+ ],+ afterComplete: [+ (buildPath, _electronVersion, platform, _arch, callback) => {+ const extraResources = getExtraResourcesForPlatform();+ for (const resource of extraResources) {+ const baseName = path.basename(resource);+ let sourcePath;+ if (platform === "darwin") {+ sourcePath = path.join(buildPath, `${APP_NAME}.app`, "Contents", "Resources", baseName);+ } else {+ sourcePath = path.join(buildPath, "resources", baseName);+ }+ let destPath;- // Copy files from resources folder to root- fs.move(sourcePath, destPath)- .then(() => callback())- .catch(err => callback(err));- }- }]- },- rebuildConfig: {- force: true- },- makers: [- {- name: '@electron-forge/maker-deb',- config: {- options: {- icon: "./images/app-icons/png/128x128.png",- desktopTemplate: path.resolve("./bin/electron-forge/desktop.ejs")- }- }- },- {- name: '@electron-forge/maker-squirrel',- config: {- iconUrl: "https://raw.githubusercontent.com/TriliumNext/Notes/develop/images/app-icons/icon.ico",- setupIcon: "./images/app-icons/icon.ico",- loadingGif: "./images/app-icons/win/setup-banner.gif"- }+ if (baseName !== "256x256.png") {+ destPath = path.join(buildPath, baseName);+ } else {+ destPath = path.join(buildPath, "icon.png");+ }++ // Copy files from resources folder to root+ fs.move(sourcePath, destPath)+ .then(() => callback())+ .catch((err) => callback(err));+ }+ }+ ]},- {- name: '@electron-forge/maker-dmg',- config: {- icon: "./images/app-icons/icon.icns",- }+ rebuildConfig: {+ force: true},- {- name: '@electron-forge/maker-zip',- config: {- options: {- iconUrl: "https://raw.githubusercontent.com/TriliumNext/Notes/develop/images/app-icons/icon.ico",- icon: "./images/app-icons/icon.ico",+ makers: [+ {+ name: "@electron-forge/maker-deb",+ config: {+ options: {+ icon: "./images/app-icons/png/128x128.png",+ desktopTemplate: path.resolve("./bin/electron-forge/desktop.ejs")+ }+ }+ },+ {+ name: "@electron-forge/maker-squirrel",+ config: {+ iconUrl: "https://raw.githubusercontent.com/TriliumNext/Notes/develop/images/app-icons/icon.ico",+ setupIcon: "./images/app-icons/icon.ico",+ loadingGif: "./images/app-icons/win/setup-banner.gif"+ }+ },+ {+ name: "@electron-forge/maker-dmg",+ config: {+ icon: "./images/app-icons/icon.icns"+ }+ },+ {+ name: "@electron-forge/maker-zip",+ config: {+ options: {+ iconUrl: "https://raw.githubusercontent.com/TriliumNext/Notes/develop/images/app-icons/icon.ico",+ icon: "./images/app-icons/icon.ico"+ }+ }}- }- }- ],- plugins: [- {- name: '@electron-forge/plugin-auto-unpack-natives',- config: {},- },- ],+ ],+ plugins: [+ {+ name: "@electron-forge/plugin-auto-unpack-natives",+ config: {}+ }+ ]};-function getExtraResourcesForPlatform() {- let resources = [- 'dump-db/',- './bin/tpl/anonymize-database.sql'- ];- const scripts = ['trilium-portable', 'trilium-safe-mode', 'trilium-no-cert-check']- switch (process.platform) {- case 'win32':- for (const script of scripts) {- resources.push(`./bin/tpl/${script}.bat`)- }- break;- case 'darwin':- break;- case 'linux':- resources.push("images/app-icons/png/256x256.png")- for (const script of scripts) {- resources.push(`./bin/tpl/${script}.sh`)- }- break;- default:- break;- }+ let resources = ["dump-db/", "./bin/tpl/anonymize-database.sql"];+ const scripts = ["trilium-portable", "trilium-safe-mode", "trilium-no-cert-check"];+ switch (process.platform) {+ case "win32":+ for (const script of scripts) {+ resources.push(`./bin/tpl/${script}.bat`);+ }+ break;+ case "darwin":+ break;+ case "linux":+ resources.push("images/app-icons/png/256x256.png");+ for (const script of scripts) {+ resources.push(`./bin/tpl/${script}.sh`);+ }+ break;+ default:+ break;+ }- return resources;-}\ No newline at end of file+ return resources;+}diff --git a/integration-tests/auth.setup.ts b/integration-tests/auth.setup.tsindex 8a1d4e4d10..9b31eec499 100644--- a/integration-tests/auth.setup.ts+++ b/integration-tests/auth.setup.ts@@ -1,6 +1,6 @@-import { test as setup, expect } from '@playwright/test';+import { test as setup, expect } from "@playwright/test";-const authFile = 'playwright/.auth/user.json';+const authFile = "playwright/.auth/user.json";const ROOT_URL = "http://localhost:8082";const LOGIN_PASSWORD = "demo1234";@@ -12,6 +12,6 @@ setup("authenticate", async ({ page }) => {await expect(page).toHaveURL(`${ROOT_URL}/login`);await page.getByRole("textbox", { name: "Password" }).fill(LOGIN_PASSWORD);- await page.getByRole("button", { name: "Login"}).click();+ await page.getByRole("button", { name: "Login" }).click();await page.context().storageState({ path: authFile });});diff --git a/integration-tests/duplicate.spec.ts b/integration-tests/duplicate.spec.tsindex e984c2f98a..fe079952bd 100644--- a/integration-tests/duplicate.spec.ts+++ b/integration-tests/duplicate.spec.ts@@ -1,9 +1,9 @@-import { test, expect } from '@playwright/test';+import { test, expect } from "@playwright/test";test("Can duplicate note with broken links", async ({ page }) => {await page.goto(`http://localhost:8082/#2VammGGdG6Ie`);- await page.locator('.tree-wrapper .fancytree-active').getByText('Note map').click({ button: 'right' });- await page.getByText('Duplicate subtree').click();+ await page.locator(".tree-wrapper .fancytree-active").getByText("Note map").click({ button: "right" });+ await page.getByText("Duplicate subtree").click();await expect(page.locator(".toast-body")).toBeHidden();- await expect(page.locator('.tree-wrapper').getByText('Note map (dup)')).toBeVisible();+ await expect(page.locator(".tree-wrapper").getByText("Note map (dup)")).toBeVisible();});diff --git a/integration-tests/example.disabled.ts b/integration-tests/example.disabled.tsindex 54a906a4e8..a149fe3286 100644--- a/integration-tests/example.disabled.ts+++ b/integration-tests/example.disabled.ts@@ -1,18 +1,18 @@-import { test, expect } from '@playwright/test';+import { test, expect } from "@playwright/test";-test('has title', async ({ page }) => {- await page.goto('https://playwright.dev/');+test("has title", async ({ page }) => {+ await page.goto("https://playwright.dev/");- // Expect a title "to contain" a substring.- await expect(page).toHaveTitle(/Playwright/);+ // Expect a title "to contain" a substring.+ await expect(page).toHaveTitle(/Playwright/);});-test('get started link', async ({ page }) => {- await page.goto('https://playwright.dev/');+test("get started link", async ({ page }) => {+ await page.goto("https://playwright.dev/");- // Click the get started link.- await page.getByRole('link', { name: 'Get started' }).click();+ // Click the get started link.+ await page.getByRole("link", { name: "Get started" }).click();- // Expects page to have a heading with the name of Installation.- await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible();+ // Expects page to have a heading with the name of Installation.+ await expect(page.getByRole("heading", { name: "Installation" })).toBeVisible();});diff --git a/integration-tests/help.spec.ts b/integration-tests/help.spec.tsindex cd7722222b..bf12d99787 100644--- a/integration-tests/help.spec.ts+++ b/integration-tests/help.spec.ts@@ -1,23 +1,23 @@import test, { expect } from "@playwright/test";-test('Help popup', async ({ page }) => {- await page.goto('http://localhost:8082');- await page.getByText('Trilium Integration Test DB').click();+test("Help popup", async ({ page }) => {+ await page.goto("http://localhost:8082");+ await page.getByText("Trilium Integration Test DB").click();- await page.locator('body').press('F1');- await page.getByRole('link', { name: 'online↗' }).click();- expect((await page.waitForEvent('popup')).url()).toBe("https://triliumnext.github.io/Docs/")+ await page.locator("body").press("F1");+ await page.getByRole("link", { name: "online↗" }).click();+ expect((await page.waitForEvent("popup")).url()).toBe("https://triliumnext.github.io/Docs/");});-test('Complete help in search', async ({ page }) => {- await page.goto('http://localhost:8082');+test("Complete help in search", async ({ page }) => {+ await page.goto("http://localhost:8082");// Clear all tabs- await page.locator('.note-tab:first-of-type').locator("div").nth(1).click({ button: 'right' });- await page.getByText('Close all tabs').click();+ await page.locator(".note-tab:first-of-type").locator("div").nth(1).click({ button: "right" });+ await page.getByText("Close all tabs").click();- await page.locator('#launcher-container').getByRole('button', { name: '' }).first().click();- await page.getByRole('cell', { name: ' ' }).locator('span').first().click();- await page.getByRole('button', { name: 'complete help on search syntax' }).click();- expect((await page.waitForEvent('popup')).url()).toBe("https://triliumnext.github.io/Docs/Wiki/search.html");+ await page.locator("#launcher-container").getByRole("button", { name: "" }).first().click();+ await page.getByRole("cell", { name: " " }).locator("span").first().click();+ await page.getByRole("button", { name: "complete help on search syntax" }).click();+ expect((await page.waitForEvent("popup")).url()).toBe("https://triliumnext.github.io/Docs/Wiki/search.html");});diff --git a/integration-tests/i18n.spec.ts b/integration-tests/i18n.spec.tsindex bd935ac689..1c3fc1d36b 100644--- a/integration-tests/i18n.spec.ts+++ b/integration-tests/i18n.spec.ts@@ -1,33 +1,33 @@import test, { expect } from "@playwright/test";test("User can change language from settings", async ({ page }) => {- await page.goto('http://localhost:8082');+ await page.goto("http://localhost:8082");// Clear all tabs- await page.locator('.note-tab:first-of-type').locator("div").nth(1).click({ button: 'right' });- await page.getByText('Close all tabs').click();+ await page.locator(".note-tab:first-of-type").locator("div").nth(1).click({ button: "right" });+ await page.getByText("Close all tabs").click();// Go to options -> Appearance- await page.locator('#launcher-pane div').filter({ hasText: 'Options Open New Window' }).getByRole('button').click();- await page.locator('#launcher-pane').getByText('Options').click();- await page.locator('#center-pane').getByText('Appearance').click();+ await page.locator("#launcher-pane div").filter({ hasText: "Options Open New Window" }).getByRole("button").click();+ await page.locator("#launcher-pane").getByText("Options").click();+ await page.locator("#center-pane").getByText("Appearance").click();// Check that the default value (English) is set.- await expect(page.locator('#center-pane')).toContainText('Theme');- const languageCombobox = await page.getByRole('combobox').first();+ await expect(page.locator("#center-pane")).toContainText("Theme");+ const languageCombobox = await page.getByRole("combobox").first();await expect(languageCombobox).toHaveValue("en");// Select Chinese and ensure the translation is set.languageCombobox.selectOption("cn");- await expect(page.locator('#center-pane')).toContainText('主题');+ await expect(page.locator("#center-pane")).toContainText("主题");// Select English again.languageCombobox.selectOption("en");});test("Restores language on start-up on desktop", async ({ page, context }) => {- await page.goto('http://localhost:8082');- await expect(page.locator('#launcher-pane').first()).toContainText("Open New Window");+ await page.goto("http://localhost:8082");+ await expect(page.locator("#launcher-pane").first()).toContainText("Open New Window");});test("Restores language on start-up on mobile", async ({ page, context }) => {@@ -38,6 +38,6 @@ test("Restores language on start-up on mobile", async ({ page, context }) => {value: "mobile"}]);- await page.goto('http://localhost:8082');- await expect(page.locator('#launcher-pane div').first()).toContainText("Open New Window");+ await page.goto("http://localhost:8082");+ await expect(page.locator("#launcher-pane div").first()).toContainText("Open New Window");});diff --git a/integration-tests/katex.disabled.ts b/integration-tests/katex.disabled.tsindex 0e99a3fbe8..457c53d7c2 100644--- a/integration-tests/katex.disabled.ts+++ b/integration-tests/katex.disabled.ts@@ -1,4 +1,4 @@-import { test, expect } from '@playwright/test';+import { test, expect } from "@playwright/test";const ROOT_URL = "http://localhost:8080";const LOGIN_PASSWORD = "eliandoran";@@ -12,7 +12,6 @@ test("Can insert equations", async ({ page }) => {// .click();const activeNote = page.locator(".component.note-split:visible");- const noteContent = activeNote- .locator(".note-detail-editable-text-editor")+ const noteContent = activeNote.locator(".note-detail-editable-text-editor");await noteContent.press("Ctrl+M");});diff --git a/integration-tests/settings.spec.ts b/integration-tests/settings.spec.tsindex 835e8e341d..b3fe16fda3 100644--- a/integration-tests/settings.spec.ts+++ b/integration-tests/settings.spec.ts@@ -1,21 +1,21 @@import test, { expect } from "@playwright/test";test("Native Title Bar not displayed on web", async ({ page }) => {- await page.goto('http://localhost:8082/#root/_hidden/_options/_optionsAppearance');- await expect(page.getByRole('heading', { name: 'Theme' })).toBeVisible();- await expect(page.getByRole('heading', { name: 'Native Title Bar (requires' })).toBeHidden();+ await page.goto("http://localhost:8082/#root/_hidden/_options/_optionsAppearance");+ await expect(page.getByRole("heading", { name: "Theme" })).toBeVisible();+ await expect(page.getByRole("heading", { name: "Native Title Bar (requires" })).toBeHidden();});test("Tray settings not displayed on web", async ({ page }) => {- await page.goto('http://localhost:8082/#root/_hidden/_options/_optionsOther');- await expect(page.getByRole('heading', { name: 'Note Erasure Timeout' })).toBeVisible();- await expect(page.getByRole('heading', { name: 'Tray' })).toBeHidden();+ await page.goto("http://localhost:8082/#root/_hidden/_options/_optionsOther");+ await expect(page.getByRole("heading", { name: "Note Erasure Timeout" })).toBeVisible();+ await expect(page.getByRole("heading", { name: "Tray" })).toBeHidden();});test("Spellcheck settings not displayed on web", async ({ page }) => {- await page.goto('http://localhost:8082/#root/_hidden/_options/_optionsSpellcheck');- await expect(page.getByRole('heading', { name: 'Spell Check' })).toBeVisible();- await expect(page.getByRole('heading', { name: 'Tray' })).toBeHidden();- await expect(page.getByText('These options apply only for desktop builds')).toBeVisible();- await expect(page.getByText('Enable spellcheck')).toBeHidden();+ await page.goto("http://localhost:8082/#root/_hidden/_options/_optionsSpellcheck");+ await expect(page.getByRole("heading", { name: "Spell Check" })).toBeVisible();+ await expect(page.getByRole("heading", { name: "Tray" })).toBeHidden();+ await expect(page.getByText("These options apply only for desktop builds")).toBeVisible();+ await expect(page.getByText("Enable spellcheck")).toBeHidden();});diff --git a/integration-tests/tree.spec.ts b/integration-tests/tree.spec.tsindex 0bc9caf225..257375fa81 100644--- a/integration-tests/tree.spec.ts+++ b/integration-tests/tree.spec.ts@@ -1,8 +1,8 @@import test, { expect } from "@playwright/test";test("Renders on desktop", async ({ page, context }) => {- await page.goto('http://localhost:8082');- await expect(page.locator('.tree')).toContainText('Trilium Integration Test');+ await page.goto("http://localhost:8082");+ await expect(page.locator(".tree")).toContainText("Trilium Integration Test");});test("Renders on mobile", async ({ page, context }) => {@@ -13,6 +13,6 @@ test("Renders on mobile", async ({ page, context }) => {value: "mobile"}]);- await page.goto('http://localhost:8082');- await expect(page.locator('.tree')).toContainText('Trilium Integration Test');+ await page.goto("http://localhost:8082");+ await expect(page.locator(".tree")).toContainText("Trilium Integration Test");});diff --git a/integration-tests/update_check.spec.ts b/integration-tests/update_check.spec.tsindex 732cd501a3..8cb7f4bf2c 100644--- a/integration-tests/update_check.spec.ts+++ b/integration-tests/update_check.spec.ts@@ -1,12 +1,12 @@-import { test, expect } from '@playwright/test';+import { test, expect } from "@playwright/test";const expectedVersion = "0.90.3";test("Displays update badge when there is a version available", async ({ page }) => {await page.goto("http://localhost:8080");- await page.getByRole('button', { name: '' }).click();+ await page.getByRole("button", { name: "" }).click();await page.getByText(`Version ${expectedVersion} is available,`).click();- const page1 = await page.waitForEvent('popup');+ const page1 = await page.waitForEvent("popup");expect(page1.url()).toBe(`https://github.com/TriliumNext/Notes/releases/tag/v${expectedVersion}`);});diff --git a/jsdoc-conf.json b/jsdoc-conf.jsonindex c0451f5b4f..b61bbacb6c 100644--- a/jsdoc-conf.json+++ b/jsdoc-conf.json@@ -4,4 +4,4 @@"includeDate": false}}-}\ No newline at end of file+}diff --git a/loader-register.js b/loader-register.jsindex b35f8bd593..ff86e6832a 100644--- a/loader-register.js+++ b/loader-register.js@@ -5,6 +5,6 @@// Then probably can change webpack comand to// "webpack": "cross-env NODE_OPTIONS=--import=ts-node/esm webpack -c webpack.config.ts",-import { register } from 'node:module';-import { pathToFileURL } from 'node:url';-register('ts-node/esm', pathToFileURL('./'));+import { register } from "node:module";+import { pathToFileURL } from "node:url";+register("ts-node/esm", pathToFileURL("./"));diff --git a/nodemon.json b/nodemon.jsonindex efaf5f759d..e860ebccca 100644--- a/nodemon.json+++ b/nodemon.json@@ -1,15 +1,12 @@{- "restartable": "rs",- "ignore": [".git", "node_modules/**/node_modules", "src/public/"],- "verbose": false,- "exec": "tsx",- "watch": [- "src/",- "translations/"- ],- "signal": "SIGTERM",- "env": {- "NODE_ENV": "development"- },- "ext": "ts,js,json"+ "restartable": "rs",+ "ignore": [".git", "node_modules/**/node_modules", "src/public/"],+ "verbose": false,+ "exec": "tsx",+ "watch": ["src/", "translations/"],+ "signal": "SIGTERM",+ "env": {+ "NODE_ENV": "development"+ },+ "ext": "ts,js,json"}diff --git a/playwright.config.ts b/playwright.config.tsindex ca8b95889f..93103178b5 100644--- a/playwright.config.ts+++ b/playwright.config.ts@@ -1,4 +1,4 @@-import { defineConfig, devices } from '@playwright/test';+import { defineConfig, devices } from "@playwright/test";/*** Read environment variables from file.@@ -11,75 +11,75 @@ import { defineConfig, devices } from '@playwright/test';* See https://playwright.dev/docs/test-configuration.*/export default defineConfig({- testDir: './integration-tests',- /* Run tests in files in parallel */- fullyParallel: true,- /* Fail the build on CI if you accidentally left test.only in the source code. */- forbidOnly: !!process.env.CI,- /* Retry on CI only */- retries: process.env.CI ? 2 : 0,- /* Opt out of parallel tests on CI. */- workers: process.env.CI ? 1 : undefined,- /* Reporter to use. See https://playwright.dev/docs/test-reporters */- reporter: 'html',- /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */- use: {- /* Base URL to use in actions like `await page.goto('/')`. */- // baseURL: 'http://127.0.0.1:3000',-- /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */- trace: 'on-first-retry',- },-- webServer: {- command: "npm run integration-mem-db",- url: "http://127.0.0.1:8082",- reuseExistingServer: true,- stdout: "ignore",- stderr: "pipe"- },+ testDir: "./integration-tests",+ /* Run tests in files in parallel */+ fullyParallel: true,+ /* Fail the build on CI if you accidentally left test.only in the source code. */+ forbidOnly: !!process.env.CI,+ /* Retry on CI only */+ retries: process.env.CI ? 2 : 0,+ /* Opt out of parallel tests on CI. */+ workers: process.env.CI ? 1 : undefined,+ /* Reporter to use. See https://playwright.dev/docs/test-reporters */+ reporter: "html",+ /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */+ use: {+ /* Base URL to use in actions like `await page.goto('/')`. */+ // baseURL: 'http://127.0.0.1:3000',- /* Configure projects for major browsers */- projects: [- {- name: "setup",- testMatch: /.*\.setup\.ts/+ /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */+ trace: "on-first-retry"},- {- name: "firefox",- use: {- ...devices[ "Desktop Firefox" ],- storageState: "playwright/.auth/user.json"- },- dependencies: [ "setup" ]+ webServer: {+ command: "npm run integration-mem-db",+ url: "http://127.0.0.1:8082",+ reuseExistingServer: true,+ stdout: "ignore",+ stderr: "pipe"},- /* Test against mobile viewports. */- // {- // name: 'Mobile Chrome',- // use: { ...devices['Pixel 5'] },- // },- // {- // name: 'Mobile Safari',- // use: { ...devices['iPhone 12'] },- // },+ /* Configure projects for major browsers */+ projects: [+ {+ name: "setup",+ testMatch: /.*\.setup\.ts/+ },- /* Test against branded browsers. */- // {- // name: 'Microsoft Edge',- // use: { ...devices['Desktop Edge'], channel: 'msedge' },- // },- // {- // name: 'Google Chrome',- // use: { ...devices['Desktop Chrome'], channel: 'chrome' },- // },- ],+ {+ name: "firefox",+ use: {+ ...devices["Desktop Firefox"],+ storageState: "playwright/.auth/user.json"+ },+ dependencies: ["setup"]+ }- /* Run your local dev server before starting the tests */- // webServer: {- // command: 'npm run start',- // url: 'http://127.0.0.1:3000',- // reuseExistingServer: !process.env.CI,- // },+ /* Test against mobile viewports. */+ // {+ // name: 'Mobile Chrome',+ // use: { ...devices['Pixel 5'] },+ // },+ // {+ // name: 'Mobile Safari',+ // use: { ...devices['iPhone 12'] },+ // },++ /* Test against branded browsers. */+ // {+ // name: 'Microsoft Edge',+ // use: { ...devices['Desktop Edge'], channel: 'msedge' },+ // },+ // {+ // name: 'Google Chrome',+ // use: { ...devices['Desktop Chrome'], channel: 'chrome' },+ // },+ ]++ /* Run your local dev server before starting the tests */+ // webServer: {+ // command: 'npm run start',+ // url: 'http://127.0.0.1:3000',+ // reuseExistingServer: !process.env.CI,+ // },});diff --git a/spec-es6/attribute_parser.spec.ts b/spec-es6/attribute_parser.spec.tsindex 60f510d8db..c7932b378b 100644--- a/spec-es6/attribute_parser.spec.ts+++ b/spec-es6/attribute_parser.spec.ts@@ -1,29 +1,24 @@-import * as attributeParser from '../src/public/app/services/attribute_parser.js';+import * as attributeParser from "../src/public/app/services/attribute_parser.js";-import {describe, it, expect, execute} from './mini_test.js';+import { describe, it, expect, execute } from "./mini_test.js";describe("Lexing", () => {it("simple label", () => {- expect(attributeParser.lex("#label").map((t: any) => t.text))- .toEqual(["#label"]);+ expect(attributeParser.lex("#label").map((t: any) => t.text)).toEqual(["#label"]);});it("simple label with trailing spaces", () => {- expect(attributeParser.lex(" #label ").map((t: any) => t.text))- .toEqual(["#label"]);+ expect(attributeParser.lex(" #label ").map((t: any) => t.text)).toEqual(["#label"]);});it("inherited label", () => {- expect(attributeParser.lex("#label(inheritable)").map((t: any) => t.text))- .toEqual(["#label", "(", "inheritable", ")"]);+ expect(attributeParser.lex("#label(inheritable)").map((t: any) => t.text)).toEqual(["#label", "(", "inheritable", ")"]);- expect(attributeParser.lex("#label ( inheritable ) ").map((t: any) => t.text))- .toEqual(["#label", "(", "inheritable", ")"]);+ expect(attributeParser.lex("#label ( inheritable ) ").map((t: any) => t.text)).toEqual(["#label", "(", "inheritable", ")"]);});it("label with value", () => {- expect(attributeParser.lex("#label=Hallo").map((t: any) => t.text))- .toEqual(["#label", "=", "Hallo"]);+ expect(attributeParser.lex("#label=Hallo").map((t: any) => t.text)).toEqual(["#label", "=", "Hallo"]);});it("label with value", () => {@@ -33,79 +28,72 @@ describe("Lexing", () => {});it("relation with value", () => {- expect(attributeParser.lex('~relation=#root/RclIpMauTOKS/NFi2gL4xtPxM').map((t: any) => t.text))- .toEqual(["~relation", "=", "#root/RclIpMauTOKS/NFi2gL4xtPxM"]);+ expect(attributeParser.lex("~relation=#root/RclIpMauTOKS/NFi2gL4xtPxM").map((t: any) => t.text)).toEqual(["~relation", "=", "#root/RclIpMauTOKS/NFi2gL4xtPxM"]);});it("use quotes to define value", () => {- expect(attributeParser.lex("#'label a'='hello\"` world'").map((t: any) => t.text))- .toEqual(["#label a", "=", 'hello"` world']);+ expect(attributeParser.lex("#'label a'='hello\"` world'").map((t: any) => t.text)).toEqual(["#label a", "=", 'hello"` world']);- expect(attributeParser.lex('#"label a" = "hello\'` world"').map((t: any) => t.text))- .toEqual(["#label a", "=", "hello'` world"]);+ expect(attributeParser.lex('#"label a" = "hello\'` world"').map((t: any) => t.text)).toEqual(["#label a", "=", "hello'` world"]);- expect(attributeParser.lex('#`label a` = `hello\'" world`').map((t: any) => t.text))- .toEqual(["#label a", "=", "hello'\" world"]);+ expect(attributeParser.lex("#`label a` = `hello'\" world`").map((t: any) => t.text)).toEqual(["#label a", "=", "hello'\" world"]);});});describe("Parser", () => {it("simple label", () => {- const attrs = attributeParser.parse(["#token"].map((t: any) => ({text: t})));+ const attrs = attributeParser.parse(["#token"].map((t: any) => ({ text: t })));expect(attrs.length).toEqual(1);- expect(attrs[0].type).toEqual('label');- expect(attrs[0].name).toEqual('token');+ expect(attrs[0].type).toEqual("label");+ expect(attrs[0].name).toEqual("token");expect(attrs[0].isInheritable).toBeFalsy();expect(attrs[0].value).toBeFalsy();});it("inherited label", () => {- const attrs = attributeParser.parse(["#token", "(", "inheritable", ")"].map((t: any) => ({text: t})));+ const attrs = attributeParser.parse(["#token", "(", "inheritable", ")"].map((t: any) => ({ text: t })));expect(attrs.length).toEqual(1);- expect(attrs[0].type).toEqual('label');- expect(attrs[0].name).toEqual('token');+ expect(attrs[0].type).toEqual("label");+ expect(attrs[0].name).toEqual("token");expect(attrs[0].isInheritable).toBeTruthy();expect(attrs[0].value).toBeFalsy();});it("label with value", () => {- const attrs = attributeParser.parse(["#token", "=", "val"].map((t: any) => ({text: t})));+ const attrs = attributeParser.parse(["#token", "=", "val"].map((t: any) => ({ text: t })));expect(attrs.length).toEqual(1);- expect(attrs[0].type).toEqual('label');- expect(attrs[0].name).toEqual('token');+ expect(attrs[0].type).toEqual("label");+ expect(attrs[0].name).toEqual("token");expect(attrs[0].value).toEqual("val");});it("relation", () => {- let attrs = attributeParser.parse(["~token", "=", "#root/RclIpMauTOKS/NFi2gL4xtPxM"].map((t: any) => ({text: t})));+ let attrs = attributeParser.parse(["~token", "=", "#root/RclIpMauTOKS/NFi2gL4xtPxM"].map((t: any) => ({ text: t })));expect(attrs.length).toEqual(1);- expect(attrs[0].type).toEqual('relation');+ expect(attrs[0].type).toEqual("relation");expect(attrs[0].name).toEqual("token");- expect(attrs[0].value).toEqual('NFi2gL4xtPxM');+ expect(attrs[0].value).toEqual("NFi2gL4xtPxM");- attrs = attributeParser.parse(["~token", "=", "#NFi2gL4xtPxM"].map((t: any) => ({text: t})));+ attrs = attributeParser.parse(["~token", "=", "#NFi2gL4xtPxM"].map((t: any) => ({ text: t })));expect(attrs.length).toEqual(1);- expect(attrs[0].type).toEqual('relation');+ expect(attrs[0].type).toEqual("relation");expect(attrs[0].name).toEqual("token");- expect(attrs[0].value).toEqual('NFi2gL4xtPxM');+ expect(attrs[0].value).toEqual("NFi2gL4xtPxM");});});describe("error cases", () => {it("error cases", () => {- expect(() => attributeParser.lexAndParse('~token'))- .toThrow('Relation "~token" in "~token" should point to a note.');+ expect(() => attributeParser.lexAndParse("~token")).toThrow('Relation "~token" in "~token" should point to a note.');- expect(() => attributeParser.lexAndParse("#a&b/s"))- .toThrow(`Attribute name "a&b/s" contains disallowed characters, only alphanumeric characters, colon and underscore are allowed.`);+ expect(() => attributeParser.lexAndParse("#a&b/s")).toThrow(`Attribute name "a&b/s" contains disallowed characters, only alphanumeric characters, colon and underscore are allowed.`);- expect(() => attributeParser.lexAndParse("#"))- .toThrow(`Attribute name is empty, please fill the name.`);+ expect(() => attributeParser.lexAndParse("#")).toThrow(`Attribute name is empty, please fill the name.`);});});diff --git a/spec-es6/mini_test.ts b/spec-es6/mini_test.tsindex 1105981c08..0657b8a89e 100644--- a/spec-es6/mini_test.ts+++ b/spec-es6/mini_test.ts@@ -47,8 +47,7 @@ export function expect(val: any) {toThrow: (errorMessage: any) => {try {val();- }- catch (e: any) {+ } catch (e: any) {if (e.message !== errorMessage) {console.trace("toThrow caught exception, but messages differ");console.error(`expected: ${errorMessage}`);@@ -66,7 +65,7 @@ export function expect(val: any) {console.error(`got: [none]`);errorCount++;}- }+ };}export function execute() {@@ -74,8 +73,7 @@ export function execute() {if (errorCount) {console.log(`!!!${errorCount} tests failed!!!`);- }- else {+ } else {console.log("All tests passed!");}}diff --git a/spec-es6/sanitize_attribute_name.spec.ts b/spec-es6/sanitize_attribute_name.spec.tsindex fa01a4690a..9399d1edbd 100644--- a/spec-es6/sanitize_attribute_name.spec.ts+++ b/spec-es6/sanitize_attribute_name.spec.ts@@ -1,43 +1,39 @@-import sanitizeAttributeName from "../src/services/sanitize_attribute_name"+import sanitizeAttributeName from "../src/services/sanitize_attribute_name";import { describe, it, execute, expect } from "./mini_test";// fn value, expected valueconst testCases: [fnValue: string, expectedValue: string][] = [- ["testName", "testName"],- ["test_name", "test_name"],- ["test with space", "test_with_space"],- ["test:with:colon", "test:with:colon"],+ ["testName", "testName"],+ ["test_name", "test_name"],+ ["test with space", "test_with_space"],+ ["test:with:colon", "test:with:colon"],- // numbers- ["123456", "123456"],- ["123:456", "123:456"],- ["123456 abc", "123456_abc"],+ // numbers+ ["123456", "123456"],+ ["123:456", "123:456"],+ ["123456 abc", "123456_abc"],- // non-latin characters- ["ε", "ε"],- ["attribute ε", "attribute_ε"],--- // special characters- ["test/name", "test_name"],- ["test%name", "test_name"],- ["\/", "_"],-- // empty string- ["", "unnamed"],-]+ // non-latin characters+ ["ε", "ε"],+ ["attribute ε", "attribute_ε"],+ // special characters+ ["test/name", "test_name"],+ ["test%name", "test_name"],+ ["\/", "_"],+ // empty string+ ["", "unnamed"]+];describe("sanitizeAttributeName unit tests", () => {-- testCases.forEach(testCase => {- return it(`'${testCase[0]}' should return '${testCase[1]}'`, () => {- const [value, expected] = testCase;- const actual = sanitizeAttributeName(value);- expect(actual).toEqual(expected);- })- })-})--execute()\ No newline at end of file+ testCases.forEach((testCase) => {+ return it(`'${testCase[0]}' should return '${testCase[1]}'`, () => {+ const [value, expected] = testCase;+ const actual = sanitizeAttributeName(value);+ expect(actual).toEqual(expected);+ });+ });+});++execute();diff --git a/spec-es6/utils/formatDownloadTitle.spec.ts b/spec-es6/utils/formatDownloadTitle.spec.tsindex 9237869150..053f79fb76 100644--- a/spec-es6/utils/formatDownloadTitle.spec.ts+++ b/spec-es6/utils/formatDownloadTitle.spec.ts@@ -2,128 +2,62 @@ import { formatDownloadTitle } from "../../src/services/utils.ts";import { describe, it, execute, expect } from "../mini_test.ts";const testCases: [fnValue: Parameters<typeof formatDownloadTitle>, expectedValue: ReturnType<typeof formatDownloadTitle>][] = [- // empty fileName tests- [- ["", "text", ""],- "untitled.html"- ],-- [- ["", "canvas", ""],- "untitled.json"- ],-- [- ["", null, ""],- "untitled"- ],-- // json extension from type tests- [- ["test_file", "canvas", ""],- "test_file.json"- ],-- [- ["test_file", "relationMap", ""],- "test_file.json"- ],-- [- ["test_file", "search", ""],- "test_file.json"- ],-- // extension based on mime type- [- ["test_file", null, "text/csv"],- "test_file.csv"- ],-- [- ["test_file_wo_ext", "image", "image/svg+xml"],- "test_file_wo_ext.svg"- ],-- [- ["test_file_wo_ext", "file", "application/json"],- "test_file_wo_ext.json"- ],-- [- ["test_file_w_fake_ext.ext", "image", "image/svg+xml"],- "test_file_w_fake_ext.ext.svg"- ],-- [- ["test_file_w_correct_ext.svg", "image", "image/svg+xml"],- "test_file_w_correct_ext.svg"- ],-- [- ["test_file_w_correct_ext.svgz", "image", "image/svg+xml"],- "test_file_w_correct_ext.svgz"- ],-- [- ["test_file.zip", "file", "application/zip"],- "test_file.zip"- ],-- [- ["test_file", "file", "application/zip"],- "test_file.zip"- ],-- // application/octet-stream tests- [- ["test_file", "file", "application/octet-stream"],- "test_file"- ],-- [- ["test_file.zip", "file", "application/octet-stream"],- "test_file.zip"- ],-- [- ["test_file.unknown", null, "application/octet-stream"],- "test_file.unknown"- ],-- // sanitized filename tests- [- ["test/file", null, "application/octet-stream"],- "testfile"- ],-- [- ["test:file.zip", "file", "application/zip"],- "testfile.zip"- ],-- [- [":::", "file", "application/zip"],- ".zip"- ],-- [- [":::a", "file", "application/zip"],- "a.zip"- ],-]+ // empty fileName tests+ [["", "text", ""], "untitled.html"],+ [["", "canvas", ""], "untitled.json"],-describe("utils/formatDownloadTitle unit tests", () => {+ [["", null, ""], "untitled"],++ // json extension from type tests+ [["test_file", "canvas", ""], "test_file.json"],++ [["test_file", "relationMap", ""], "test_file.json"],++ [["test_file", "search", ""], "test_file.json"],++ // extension based on mime type+ [["test_file", null, "text/csv"], "test_file.csv"],++ [["test_file_wo_ext", "image", "image/svg+xml"], "test_file_wo_ext.svg"],++ [["test_file_wo_ext", "file", "application/json"], "test_file_wo_ext.json"],++ [["test_file_w_fake_ext.ext", "image", "image/svg+xml"], "test_file_w_fake_ext.ext.svg"],++ [["test_file_w_correct_ext.svg", "image", "image/svg+xml"], "test_file_w_correct_ext.svg"],- testCases.forEach(testCase => {- return it(`With args '${JSON.stringify(testCase[0])}' it should return '${testCase[1]}'`, () => {- const [value, expected] = testCase;- const actual = formatDownloadTitle(...value);- expect(actual).toEqual(expected);- })- })+ [["test_file_w_correct_ext.svgz", "image", "image/svg+xml"], "test_file_w_correct_ext.svgz"],-})+ [["test_file.zip", "file", "application/zip"], "test_file.zip"],-execute()\ No newline at end of file+ [["test_file", "file", "application/zip"], "test_file.zip"],++ // application/octet-stream tests+ [["test_file", "file", "application/octet-stream"], "test_file"],++ [["test_file.zip", "file", "application/octet-stream"], "test_file.zip"],++ [["test_file.unknown", null, "application/octet-stream"], "test_file.unknown"],++ // sanitized filename tests+ [["test/file", null, "application/octet-stream"], "testfile"],++ [["test:file.zip", "file", "application/zip"], "testfile.zip"],++ [[":::", "file", "application/zip"], ".zip"],++ [[":::a", "file", "application/zip"], "a.zip"]+];++describe("utils/formatDownloadTitle unit tests", () => {+ testCases.forEach((testCase) => {+ return it(`With args '${JSON.stringify(testCase[0])}' it should return '${testCase[1]}'`, () => {+ const [value, expected] = testCase;+ const actual = formatDownloadTitle(...value);+ expect(actual).toEqual(expected);+ });+ });+});++execute();diff --git a/spec/etapi/app_info.ts b/spec/etapi/app_info.tsindex 6ba0493578..4bb8c40647 100644--- a/spec/etapi/app_info.ts+++ b/spec/etapi/app_info.ts@@ -1,8 +1,8 @@import etapi from "../support/etapi.js";etapi.describeEtapi("app_info", () => {- it("get", async () => {- const appInfo = await etapi.getEtapi("app-info");- expect(appInfo.clipperProtocolVersion).toEqual("1.0");- });+ it("get", async () => {+ const appInfo = await etapi.getEtapi("app-info");+ expect(appInfo.clipperProtocolVersion).toEqual("1.0");+ });});diff --git a/spec/etapi/backup.ts b/spec/etapi/backup.tsindex 2f9532f71d..78aa01d7fc 100644--- a/spec/etapi/backup.ts+++ b/spec/etapi/backup.ts@@ -1,8 +1,8 @@import etapi from "../support/etapi.js";etapi.describeEtapi("backup", () => {- it("create", async () => {- const response = await etapi.putEtapiContent("backup/etapi_test");- expect(response.status).toEqual(204);- });+ it("create", async () => {+ const response = await etapi.putEtapiContent("backup/etapi_test");+ expect(response.status).toEqual(204);+ });});diff --git a/spec/etapi/import.ts b/spec/etapi/import.tsindex d800075d4b..d36a01c583 100644--- a/spec/etapi/import.ts+++ b/spec/etapi/import.ts@@ -4,28 +4,21 @@ import path from "path";import { fileURLToPath } from "url";etapi.describeEtapi("import", () => {- // temporarily skip this test since test-export.zip is missing- xit("import", async () => {- const scriptDir = path.dirname(fileURLToPath(import.meta.url));+ // temporarily skip this test since test-export.zip is missing+ xit("import", async () => {+ const scriptDir = path.dirname(fileURLToPath(import.meta.url));- const zipFileBuffer = fs.readFileSync(- path.resolve(scriptDir, "test-export.zip")- );+ const zipFileBuffer = fs.readFileSync(path.resolve(scriptDir, "test-export.zip"));- const response = await etapi.postEtapiContent(- "notes/root/import",- zipFileBuffer- );- expect(response.status).toEqual(201);+ const response = await etapi.postEtapiContent("notes/root/import", zipFileBuffer);+ expect(response.status).toEqual(201);- const { note, branch } = await response.json();+ const { note, branch } = await response.json();- expect(note.title).toEqual("test-export");- expect(branch.parentNoteId).toEqual("root");+ expect(note.title).toEqual("test-export");+ expect(branch.parentNoteId).toEqual("root");- const content = await (- await etapi.getEtapiContent(`notes/${note.noteId}/content`)- ).text();- expect(content).toContain("test export content");- });+ const content = await (await etapi.getEtapiContent(`notes/${note.noteId}/content`)).text();+ expect(content).toContain("test export content");+ });});diff --git a/spec/etapi/notes.spec.ts b/spec/etapi/notes.spec.tsindex ce0df713d3..bf7e0a2826 100644--- a/spec/etapi/notes.spec.ts+++ b/spec/etapi/notes.spec.ts@@ -1,5 +1,3 @@describe("Notes", () => {- it("zzz", () => {-- });+ it("zzz", () => {});});diff --git a/spec/etapi/notes.ts b/spec/etapi/notes.tsindex 3db54ab1ba..6efcd88a1f 100644--- a/spec/etapi/notes.ts+++ b/spec/etapi/notes.ts@@ -2,106 +2,100 @@ import crypto from "crypto";import etapi from "../support/etapi.js";etapi.describeEtapi("notes", () => {- it("create", async () => {- const { note, branch } = await etapi.postEtapi("create-note", {- parentNoteId: "root",- type: "text",- title: "Hello World!",- content: "Content",- prefix: "Custom prefix",+ it("create", async () => {+ const { note, branch } = await etapi.postEtapi("create-note", {+ parentNoteId: "root",+ type: "text",+ title: "Hello World!",+ content: "Content",+ prefix: "Custom prefix"+ });++ expect(note.title).toEqual("Hello World!");+ expect(branch.parentNoteId).toEqual("root");+ expect(branch.prefix).toEqual("Custom prefix");++ const rNote = await etapi.getEtapi(`notes/${note.noteId}`);+ expect(rNote.title).toEqual("Hello World!");++ const rContent = await (await etapi.getEtapiContent(`notes/${note.noteId}/content`)).text();+ expect(rContent).toEqual("Content");++ const rBranch = await etapi.getEtapi(`branches/${branch.branchId}`);+ expect(rBranch.parentNoteId).toEqual("root");+ expect(rBranch.prefix).toEqual("Custom prefix");});- expect(note.title).toEqual("Hello World!");- expect(branch.parentNoteId).toEqual("root");- expect(branch.prefix).toEqual("Custom prefix");-- const rNote = await etapi.getEtapi(`notes/${note.noteId}`);- expect(rNote.title).toEqual("Hello World!");-- const rContent = await (- await etapi.getEtapiContent(`notes/${note.noteId}/content`)- ).text();- expect(rContent).toEqual("Content");-- const rBranch = await etapi.getEtapi(`branches/${branch.branchId}`);- expect(rBranch.parentNoteId).toEqual("root");- expect(rBranch.prefix).toEqual("Custom prefix");- });-- it("patch", async () => {- const { note } = await etapi.postEtapi("create-note", {- parentNoteId: "root",- type: "text",- title: "Hello World!",- content: "Content",+ it("patch", async () => {+ const { note } = await etapi.postEtapi("create-note", {+ parentNoteId: "root",+ type: "text",+ title: "Hello World!",+ content: "Content"+ });++ await etapi.patchEtapi(`notes/${note.noteId}`, {+ title: "new title",+ type: "code",+ mime: "text/apl",+ dateCreated: "2000-01-01 12:34:56.999+0200",+ utcDateCreated: "2000-01-01 10:34:56.999Z"+ });++ const rNote = await etapi.getEtapi(`notes/${note.noteId}`);+ expect(rNote.title).toEqual("new title");+ expect(rNote.type).toEqual("code");+ expect(rNote.mime).toEqual("text/apl");+ expect(rNote.dateCreated).toEqual("2000-01-01 12:34:56.999+0200");+ expect(rNote.utcDateCreated).toEqual("2000-01-01 10:34:56.999Z");});- await etapi.patchEtapi(`notes/${note.noteId}`, {- title: "new title",- type: "code",- mime: "text/apl",- dateCreated: "2000-01-01 12:34:56.999+0200",- utcDateCreated: "2000-01-01 10:34:56.999Z",- });-- const rNote = await etapi.getEtapi(`notes/${note.noteId}`);- expect(rNote.title).toEqual("new title");- expect(rNote.type).toEqual("code");- expect(rNote.mime).toEqual("text/apl");- expect(rNote.dateCreated).toEqual("2000-01-01 12:34:56.999+0200");- expect(rNote.utcDateCreated).toEqual("2000-01-01 10:34:56.999Z");- });-- it("update content", async () => {- const { note } = await etapi.postEtapi("create-note", {- parentNoteId: "root",- type: "text",- title: "Hello World!",- content: "Content",- });+ it("update content", async () => {+ const { note } = await etapi.postEtapi("create-note", {+ parentNoteId: "root",+ type: "text",+ title: "Hello World!",+ content: "Content"+ });- await etapi.putEtapiContent(`notes/${note.noteId}/content`, "new content");+ await etapi.putEtapiContent(`notes/${note.noteId}/content`, "new content");- const rContent = await (- await etapi.getEtapiContent(`notes/${note.noteId}/content`)- ).text();- expect(rContent).toEqual("new content");- });-- it("create / update binary content", async () => {- const { note } = await etapi.postEtapi("create-note", {- parentNoteId: "root",- type: "file",- title: "Hello World!",- content: "ZZZ",+ const rContent = await (await etapi.getEtapiContent(`notes/${note.noteId}/content`)).text();+ expect(rContent).toEqual("new content");});- const updatedContent = crypto.randomBytes(16);+ it("create / update binary content", async () => {+ const { note } = await etapi.postEtapi("create-note", {+ parentNoteId: "root",+ type: "file",+ title: "Hello World!",+ content: "ZZZ"+ });- await etapi.putEtapiContent(`notes/${note.noteId}/content`, updatedContent);+ const updatedContent = crypto.randomBytes(16);- const rContent = await (- await etapi.getEtapiContent(`notes/${note.noteId}/content`)- ).arrayBuffer();- expect(Buffer.from(new Uint8Array(rContent))).toEqual(updatedContent);- });+ await etapi.putEtapiContent(`notes/${note.noteId}/content`, updatedContent);- it("delete note", async () => {- const { note } = await etapi.postEtapi("create-note", {- parentNoteId: "root",- type: "text",- title: "Hello World!",- content: "Content",+ const rContent = await (await etapi.getEtapiContent(`notes/${note.noteId}/content`)).arrayBuffer();+ expect(Buffer.from(new Uint8Array(rContent))).toEqual(updatedContent);});- await etapi.deleteEtapi(`notes/${note.noteId}`);+ it("delete note", async () => {+ const { note } = await etapi.postEtapi("create-note", {+ parentNoteId: "root",+ type: "text",+ title: "Hello World!",+ content: "Content"+ });++ await etapi.deleteEtapi(`notes/${note.noteId}`);- const resp = await etapi.getEtapiResponse(`notes/${note.noteId}`);- expect(resp.status).toEqual(404);+ const resp = await etapi.getEtapiResponse(`notes/${note.noteId}`);+ expect(resp.status).toEqual(404);- const error = await resp.json();- expect(error.status).toEqual(404);- expect(error.code).toEqual("NOTE_NOT_FOUND");- expect(error.message).toEqual(`Note '${note.noteId}' not found.`);- });+ const error = await resp.json();+ expect(error.status).toEqual(404);+ expect(error.code).toEqual("NOTE_NOT_FOUND");+ expect(error.message).toEqual(`Note '${note.noteId}' not found.`);+ });});diff --git a/spec/search/becca_mocking.ts b/spec/search/becca_mocking.tsindex 33bbb63bbd..0bc7116cb6 100644--- a/spec/search/becca_mocking.ts+++ b/spec/search/becca_mocking.ts@@ -7,81 +7,76 @@ import SearchResult from "../../src/services/search/search_result.js";import { NoteType } from "../../src/becca/entities/rows.js";randtoken.generator({ source: "crypto" });-function findNoteByTitle(- searchResults: Array<SearchResult>,- title: string-): BNote | undefined {- return searchResults- .map((sr) => becca.notes[sr.noteId])- .find((note) => note.title === title);+function findNoteByTitle(searchResults: Array<SearchResult>, title: string): BNote | undefined {+ return searchResults.map((sr) => becca.notes[sr.noteId]).find((note) => note.title === title);}class NoteBuilder {- note: BNote;- constructor(note: BNote) {- this.note = note;- }+ note: BNote;+ constructor(note: BNote) {+ this.note = note;+ }- label(name: string, value = "", isInheritable = false) {- new BAttribute({- attributeId: id(),- noteId: this.note.noteId,- type: "label",- isInheritable,- name,- value,- });+ label(name: string, value = "", isInheritable = false) {+ new BAttribute({+ attributeId: id(),+ noteId: this.note.noteId,+ type: "label",+ isInheritable,+ name,+ value+ });- return this;- }+ return this;+ }- relation(name: string, targetNote: BNote) {- new BAttribute({- attributeId: id(),- noteId: this.note.noteId,- type: "relation",- name,- value: targetNote.noteId,- });+ relation(name: string, targetNote: BNote) {+ new BAttribute({+ attributeId: id(),+ noteId: this.note.noteId,+ type: "relation",+ name,+ value: targetNote.noteId+ });- return this;- }+ return this;+ }- child(childNoteBuilder: NoteBuilder, prefix = "") {- new BBranch({- branchId: id(),- noteId: childNoteBuilder.note.noteId,- parentNoteId: this.note.noteId,- prefix,- notePosition: 10,- });+ child(childNoteBuilder: NoteBuilder, prefix = "") {+ new BBranch({+ branchId: id(),+ noteId: childNoteBuilder.note.noteId,+ parentNoteId: this.note.noteId,+ prefix,+ notePosition: 10+ });- return this;- }+ return this;+ }}function id() {- return randtoken.generate(10);+ return randtoken.generate(10);}function note(title: string, extraParams = {}) {- const row = Object.assign(- {- noteId: id(),- title: title,- type: "text" as NoteType,- mime: "text/html",- },- extraParams- );+ const row = Object.assign(+ {+ noteId: id(),+ title: title,+ type: "text" as NoteType,+ mime: "text/html"+ },+ extraParams+ );- const note = new BNote(row);+ const note = new BNote(row);- return new NoteBuilder(note);+ return new NoteBuilder(note);}export default {- NoteBuilder,- findNoteByTitle,- note,+ NoteBuilder,+ findNoteByTitle,+ note};diff --git a/spec/search/lexer.spec.ts b/spec/search/lexer.spec.tsindex 2e3179fa3a..c489b03e6f 100644--- a/spec/search/lexer.spec.ts+++ b/spec/search/lexer.spec.ts@@ -1,256 +1,162 @@import lex from "../../src/services/search/services/lex.js";describe("Lexer fulltext", () => {- it("simple lexing", () => {- expect(lex("hello world").fulltextTokens.map((t) => t.token)).toEqual([- "hello",- "world",- ]);-- expect(lex("hello, world").fulltextTokens.map((t) => t.token)).toEqual([- "hello",- "world",- ]);- });-- it("use quotes to keep words together", () => {- expect(- lex("'hello world' my friend").fulltextTokens.map((t) => t.token)- ).toEqual(["hello world", "my", "friend"]);-- expect(- lex('"hello world" my friend').fulltextTokens.map((t) => t.token)- ).toEqual(["hello world", "my", "friend"]);-- expect(- lex("`hello world` my friend").fulltextTokens.map((t) => t.token)- ).toEqual(["hello world", "my", "friend"]);- });-- it("you can use different quotes and other special characters inside quotes", () => {- expect(- lex("'i can use \" or ` or #~=*' without problem").fulltextTokens.map(- (t) => t.token- )- ).toEqual(['i can use " or ` or #~=*', "without", "problem"]);- });-- it("I can use backslash to escape quotes", () => {- expect(lex('hello \\"world\\"').fulltextTokens.map((t) => t.token)).toEqual(- ["hello", '"world"']- );-- expect(lex("hello \\'world\\'").fulltextTokens.map((t) => t.token)).toEqual(- ["hello", "'world'"]- );-- expect(lex("hello \\`world\\`").fulltextTokens.map((t) => t.token)).toEqual(- ["hello", "`world`"]- );-- expect(- lex('"hello \\"world\\"').fulltextTokens.map((t) => t.token)- ).toEqual(['hello "world"']);-- expect(- lex("'hello \\'world\\''").fulltextTokens.map((t) => t.token)- ).toEqual(["hello 'world'"]);-- expect(- lex("`hello \\`world\\``").fulltextTokens.map((t) => t.token)- ).toEqual(["hello `world`"]);-- expect(lex("\\#token").fulltextTokens.map((t) => t.token)).toEqual([- "#token",- ]);- });-- it("quote inside a word does not have a special meaning", () => {- const lexResult = lex("d'Artagnan is dead #hero = d'Artagnan");-- expect(lexResult.fulltextTokens.map((t) => t.token)).toEqual([- "d'artagnan",- "is",- "dead",- ]);-- expect(lexResult.expressionTokens.map((t) => t.token)).toEqual([- "#hero",- "=",- "d'artagnan",- ]);- });-- it("if quote is not ended then it's just one long token", () => {- expect(lex("'unfinished quote").fulltextTokens.map((t) => t.token)).toEqual(- ["unfinished quote"]- );- });-- it("parenthesis and symbols in fulltext section are just normal characters", () => {- expect(- lex("what's u=p <b(r*t)h>").fulltextTokens.map((t) => t.token)- ).toEqual(["what's", "u=p", "<b(r*t)h>"]);- });-- it("operator characters in expressions are separate tokens", () => {- expect(- lex("# abc+=-def**-+d").expressionTokens.map((t) => t.token)- ).toEqual(["#", "abc", "+=-", "def", "**-+", "d"]);- });-- it("escaping special characters", () => {- expect(lex("hello \\#\\~\\'").fulltextTokens.map((t) => t.token)).toEqual([- "hello",- "#~'",- ]);- });+ it("simple lexing", () => {+ expect(lex("hello world").fulltextTokens.map((t) => t.token)).toEqual(["hello", "world"]);++ expect(lex("hello, world").fulltextTokens.map((t) => t.token)).toEqual(["hello", "world"]);+ });++ it("use quotes to keep words together", () => {+ expect(lex("'hello world' my friend").fulltextTokens.map((t) => t.token)).toEqual(["hello world", "my", "friend"]);++ expect(lex('"hello world" my friend').fulltextTokens.map((t) => t.token)).toEqual(["hello world", "my", "friend"]);++ expect(lex("`hello world` my friend").fulltextTokens.map((t) => t.token)).toEqual(["hello world", "my", "friend"]);+ });++ it("you can use different quotes and other special characters inside quotes", () => {+ expect(lex("'i can use \" or ` or #~=*' without problem").fulltextTokens.map((t) => t.token)).toEqual(['i can use " or ` or #~=*', "without", "problem"]);+ });++ it("I can use backslash to escape quotes", () => {+ expect(lex('hello \\"world\\"').fulltextTokens.map((t) => t.token)).toEqual(["hello", '"world"']);++ expect(lex("hello \\'world\\'").fulltextTokens.map((t) => t.token)).toEqual(["hello", "'world'"]);++ expect(lex("hello \\`world\\`").fulltextTokens.map((t) => t.token)).toEqual(["hello", "`world`"]);++ expect(lex('"hello \\"world\\"').fulltextTokens.map((t) => t.token)).toEqual(['hello "world"']);++ expect(lex("'hello \\'world\\''").fulltextTokens.map((t) => t.token)).toEqual(["hello 'world'"]);++ expect(lex("`hello \\`world\\``").fulltextTokens.map((t) => t.token)).toEqual(["hello `world`"]);++ expect(lex("\\#token").fulltextTokens.map((t) => t.token)).toEqual(["#token"]);+ });++ it("quote inside a word does not have a special meaning", () => {+ const lexResult = lex("d'Artagnan is dead #hero = d'Artagnan");++ expect(lexResult.fulltextTokens.map((t) => t.token)).toEqual(["d'artagnan", "is", "dead"]);++ expect(lexResult.expressionTokens.map((t) => t.token)).toEqual(["#hero", "=", "d'artagnan"]);+ });++ it("if quote is not ended then it's just one long token", () => {+ expect(lex("'unfinished quote").fulltextTokens.map((t) => t.token)).toEqual(["unfinished quote"]);+ });++ it("parenthesis and symbols in fulltext section are just normal characters", () => {+ expect(lex("what's u=p <b(r*t)h>").fulltextTokens.map((t) => t.token)).toEqual(["what's", "u=p", "<b(r*t)h>"]);+ });++ it("operator characters in expressions are separate tokens", () => {+ expect(lex("# abc+=-def**-+d").expressionTokens.map((t) => t.token)).toEqual(["#", "abc", "+=-", "def", "**-+", "d"]);+ });++ it("escaping special characters", () => {+ expect(lex("hello \\#\\~\\'").fulltextTokens.map((t) => t.token)).toEqual(["hello", "#~'"]);+ });});describe("Lexer expression", () => {- it("simple attribute existence", () => {- expect(- lex("#label ~relation").expressionTokens.map((t) => t.token)- ).toEqual(["#label", "~relation"]);- });-- it("simple label operators", () => {- expect(lex("#label*=*text").expressionTokens.map((t) => t.token)).toEqual([- "#label",- "*=*",- "text",- ]);- });-- it("simple label operator with in quotes", () => {- expect(lex("#label*=*'text'").expressionTokens).toEqual([- { token: "#label", inQuotes: false, startIndex: 0, endIndex: 5 },- { token: "*=*", inQuotes: false, startIndex: 6, endIndex: 8 },- { token: "text", inQuotes: true, startIndex: 10, endIndex: 13 },- ]);- });-- it("simple label operator with param without quotes", () => {- expect(lex("#label*=*text").expressionTokens).toEqual([- { token: "#label", inQuotes: false, startIndex: 0, endIndex: 5 },- { token: "*=*", inQuotes: false, startIndex: 6, endIndex: 8 },- { token: "text", inQuotes: false, startIndex: 9, endIndex: 12 },- ]);- });-- it("simple label operator with empty string param", () => {- expect(lex("#label = ''").expressionTokens).toEqual([- { token: "#label", inQuotes: false, startIndex: 0, endIndex: 5 },- { token: "=", inQuotes: false, startIndex: 7, endIndex: 7 },- // weird case for empty strings which ends up with endIndex < startIndex :-(- { token: "", inQuotes: true, startIndex: 10, endIndex: 9 },- ]);- });-- it("note. prefix also separates fulltext from expression", () => {- expect(- lex(`hello fulltext note.labels.capital = Prague`).expressionTokens.map(- (t) => t.token- )- ).toEqual(["note", ".", "labels", ".", "capital", "=", "prague"]);- });-- it("note. prefix in quotes will note start expression", () => {- expect(- lex(`hello fulltext "note.txt"`).expressionTokens.map((t) => t.token)- ).toEqual([]);-- expect(- lex(`hello fulltext "note.txt"`).fulltextTokens.map((t) => t.token)- ).toEqual(["hello", "fulltext", "note.txt"]);- });-- it("complex expressions with and, or and parenthesis", () => {- expect(- lex(`# (#label=text OR #second=text) AND ~relation`).expressionTokens.map(- (t) => t.token- )- ).toEqual([- "#",- "(",- "#label",- "=",- "text",- "or",- "#second",- "=",- "text",- ")",- "and",- "~relation",- ]);- });-- it("dot separated properties", () => {- expect(- lex(- `# ~author.title = 'Hugh Howey' AND note.'book title' = 'Silo'`- ).expressionTokens.map((t) => t.token)- ).toEqual([- "#",- "~author",- ".",- "title",- "=",- "hugh howey",- "and",- "note",- ".",- "book title",- "=",- "silo",- ]);- });-- it("negation of label and relation", () => {- expect(- lex(`#!capital ~!neighbor`).expressionTokens.map((t) => t.token)- ).toEqual(["#!capital", "~!neighbor"]);- });-- it("negation of sub-expression", () => {- expect(- lex(`# not(#capital) and note.noteId != "root"`).expressionTokens.map(- (t) => t.token- )- ).toEqual([- "#",- "not",- "(",- "#capital",- ")",- "and",- "note",- ".",- "noteid",- "!=",- "root",- ]);- });-- it("order by multiple labels", () => {- expect(lex(`# orderby #a,#b`).expressionTokens.map((t) => t.token)).toEqual(- ["#", "orderby", "#a", ",", "#b"]- );- });+ it("simple attribute existence", () => {+ expect(lex("#label ~relation").expressionTokens.map((t) => t.token)).toEqual(["#label", "~relation"]);+ });++ it("simple label operators", () => {+ expect(lex("#label*=*text").expressionTokens.map((t) => t.token)).toEqual(["#label", "*=*", "text"]);+ });++ it("simple label operator with in quotes", () => {+ expect(lex("#label*=*'text'").expressionTokens).toEqual([+ { token: "#label", inQuotes: false, startIndex: 0, endIndex: 5 },+ { token: "*=*", inQuotes: false, startIndex: 6, endIndex: 8 },+ { token: "text", inQuotes: true, startIndex: 10, endIndex: 13 }+ ]);+ });++ it("simple label operator with param without quotes", () => {+ expect(lex("#label*=*text").expressionTokens).toEqual([+ { token: "#label", inQuotes: false, startIndex: 0, endIndex: 5 },+ { token: "*=*", inQuotes: false, startIndex: 6, endIndex: 8 },+ { token: "text", inQuotes: false, startIndex: 9, endIndex: 12 }+ ]);+ });++ it("simple label operator with empty string param", () => {+ expect(lex("#label = ''").expressionTokens).toEqual([+ { token: "#label", inQuotes: false, startIndex: 0, endIndex: 5 },+ { token: "=", inQuotes: false, startIndex: 7, endIndex: 7 },+ // weird case for empty strings which ends up with endIndex < startIndex :-(+ { token: "", inQuotes: true, startIndex: 10, endIndex: 9 }+ ]);+ });++ it("note. prefix also separates fulltext from expression", () => {+ expect(lex(`hello fulltext note.labels.capital = Prague`).expressionTokens.map((t) => t.token)).toEqual(["note", ".", "labels", ".", "capital", "=", "prague"]);+ });++ it("note. prefix in quotes will note start expression", () => {+ expect(lex(`hello fulltext "note.txt"`).expressionTokens.map((t) => t.token)).toEqual([]);++ expect(lex(`hello fulltext "note.txt"`).fulltextTokens.map((t) => t.token)).toEqual(["hello", "fulltext", "note.txt"]);+ });++ it("complex expressions with and, or and parenthesis", () => {+ expect(lex(`# (#label=text OR #second=text) AND ~relation`).expressionTokens.map((t) => t.token)).toEqual([+ "#",+ "(",+ "#label",+ "=",+ "text",+ "or",+ "#second",+ "=",+ "text",+ ")",+ "and",+ "~relation"+ ]);+ });++ it("dot separated properties", () => {+ expect(lex(`# ~author.title = 'Hugh Howey' AND note.'book title' = 'Silo'`).expressionTokens.map((t) => t.token)).toEqual([+ "#",+ "~author",+ ".",+ "title",+ "=",+ "hugh howey",+ "and",+ "note",+ ".",+ "book title",+ "=",+ "silo"+ ]);+ });++ it("negation of label and relation", () => {+ expect(lex(`#!capital ~!neighbor`).expressionTokens.map((t) => t.token)).toEqual(["#!capital", "~!neighbor"]);+ });++ it("negation of sub-expression", () => {+ expect(lex(`# not(#capital) and note.noteId != "root"`).expressionTokens.map((t) => t.token)).toEqual(["#", "not", "(", "#capital", ")", "and", "note", ".", "noteid", "!=", "root"]);+ });++ it("order by multiple labels", () => {+ expect(lex(`# orderby #a,#b`).expressionTokens.map((t) => t.token)).toEqual(["#", "orderby", "#a", ",", "#b"]);+ });});describe("Lexer invalid queries and edge cases", () => {- it("concatenated attributes", () => {- expect(lex("#label~relation").expressionTokens.map((t) => t.token)).toEqual(- ["#label", "~relation"]- );- });-- it("trailing escape \\", () => {- expect(lex("abc \\").fulltextTokens.map((t) => t.token)).toEqual([- "abc",- "\\",- ]);- });+ it("concatenated attributes", () => {+ expect(lex("#label~relation").expressionTokens.map((t) => t.token)).toEqual(["#label", "~relation"]);+ });++ it("trailing escape \\", () => {+ expect(lex("abc \\").fulltextTokens.map((t) => t.token)).toEqual(["abc", "\\"]);+ });});diff --git a/spec/search/parens.spec.ts b/spec/search/parens.spec.tsindex 3bc900b8bb..cea7fc5de1 100644--- a/spec/search/parens.spec.ts+++ b/spec/search/parens.spec.ts@@ -3,23 +3,9 @@ import { TokenStructure } from "../../src/services/search/services/types.js";describe("Parens handler", () => {it("handles parens", () => {- const input = ["(", "hello", ")", "and", "(", "(", "pick", "one", ")", "and", "another", ")"]- .map(token => ({token}));+ const input = ["(", "hello", ")", "and", "(", "(", "pick", "one", ")", "and", "another", ")"].map((token) => ({ token }));- const actual: TokenStructure = [- [- {token: "hello"}- ],- {token: "and"},- [- [- {token: "pick"},- {token: "one"}- ],- {token: "and"},- {token: "another"}- ]- ];+ const actual: TokenStructure = [[{ token: "hello" }], { token: "and" }, [[{ token: "pick" }, { token: "one" }], { token: "and" }, { token: "another" }]];expect(handleParens(input)).toEqual(actual);});diff --git a/spec/search/parser.spec.ts b/spec/search/parser.spec.tsindex 0030366643..cf5d3315dc 100644--- a/spec/search/parser.spec.ts+++ b/spec/search/parser.spec.ts@@ -17,301 +17,297 @@ function tokens(toks: Array<string>, cur = 0): Array<any> {token: arg,inQuotes: false,startIndex: cur - arg.length,- endIndex: cur - 1,+ endIndex: cur - 1};}});}function assertIsArchived(exp: Expression) {- expect(exp.constructor.name).toEqual('PropertyComparisonExp');- expect(exp.propertyName).toEqual('isArchived');- expect(exp.operator).toEqual('=');- expect(exp.comparedValue).toEqual('false');+ expect(exp.constructor.name).toEqual("PropertyComparisonExp");+ expect(exp.propertyName).toEqual("isArchived");+ expect(exp.operator).toEqual("=");+ expect(exp.comparedValue).toEqual("false");}-describe('Parser', () => {- it('fulltext parser without content', () => {+describe("Parser", () => {+ it("fulltext parser without content", () => {const rootExp = parse({- fulltextTokens: tokens(['hello', 'hi']),+ fulltextTokens: tokens(["hello", "hi"]),expressionTokens: [],- searchContext: new SearchContext({ excludeArchived: true }),+ searchContext: new SearchContext({ excludeArchived: true })});- expect(rootExp.constructor.name).toEqual('AndExp');- expect(rootExp.subExpressions[0].constructor.name).toEqual('PropertyComparisonExp');- expect(rootExp.subExpressions[2].constructor.name).toEqual('OrExp');- expect(rootExp.subExpressions[2].subExpressions[0].constructor.name).toEqual('NoteFlatTextExp');- expect(rootExp.subExpressions[2].subExpressions[0].tokens).toEqual(['hello', 'hi']);+ expect(rootExp.constructor.name).toEqual("AndExp");+ expect(rootExp.subExpressions[0].constructor.name).toEqual("PropertyComparisonExp");+ expect(rootExp.subExpressions[2].constructor.name).toEqual("OrExp");+ expect(rootExp.subExpressions[2].subExpressions[0].constructor.name).toEqual("NoteFlatTextExp");+ expect(rootExp.subExpressions[2].subExpressions[0].tokens).toEqual(["hello", "hi"]);});- it('fulltext parser with content', () => {+ it("fulltext parser with content", () => {const rootExp = parse({- fulltextTokens: tokens(['hello', 'hi']),+ fulltextTokens: tokens(["hello", "hi"]),expressionTokens: [],- searchContext: new SearchContext(),+ searchContext: new SearchContext()});- expect(rootExp.constructor.name).toEqual('AndExp');+ expect(rootExp.constructor.name).toEqual("AndExp");assertIsArchived(rootExp.subExpressions[0]);- expect(rootExp.subExpressions[2].constructor.name).toEqual('OrExp');+ expect(rootExp.subExpressions[2].constructor.name).toEqual("OrExp");const subs = rootExp.subExpressions[2].subExpressions;- expect(subs[0].constructor.name).toEqual('NoteFlatTextExp');- expect(subs[0].tokens).toEqual(['hello', 'hi']);+ expect(subs[0].constructor.name).toEqual("NoteFlatTextExp");+ expect(subs[0].tokens).toEqual(["hello", "hi"]);- expect(subs[1].constructor.name).toEqual('NoteContentFulltextExp');- expect(subs[1].tokens).toEqual(['hello', 'hi']);+ expect(subs[1].constructor.name).toEqual("NoteContentFulltextExp");+ expect(subs[1].tokens).toEqual(["hello", "hi"]);});- it('simple label comparison', () => {+ it("simple label comparison", () => {const rootExp = parse({fulltextTokens: [],- expressionTokens: tokens(['#mylabel', '=', 'text']),- searchContext: new SearchContext(),+ expressionTokens: tokens(["#mylabel", "=", "text"]),+ searchContext: new SearchContext()});- expect(rootExp.constructor.name).toEqual('AndExp');+ expect(rootExp.constructor.name).toEqual("AndExp");assertIsArchived(rootExp.subExpressions[0]);- expect(rootExp.subExpressions[2].constructor.name).toEqual('LabelComparisonExp');- expect(rootExp.subExpressions[2].attributeType).toEqual('label');- expect(rootExp.subExpressions[2].attributeName).toEqual('mylabel');+ expect(rootExp.subExpressions[2].constructor.name).toEqual("LabelComparisonExp");+ expect(rootExp.subExpressions[2].attributeType).toEqual("label");+ expect(rootExp.subExpressions[2].attributeName).toEqual("mylabel");expect(rootExp.subExpressions[2].comparator).toBeTruthy();});- it('simple attribute negation', () => {+ it("simple attribute negation", () => {let rootExp = parse({fulltextTokens: [],- expressionTokens: tokens(['#!mylabel']),- searchContext: new SearchContext(),+ expressionTokens: tokens(["#!mylabel"]),+ searchContext: new SearchContext()});- expect(rootExp.constructor.name).toEqual('AndExp');+ expect(rootExp.constructor.name).toEqual("AndExp");assertIsArchived(rootExp.subExpressions[0]);- expect(rootExp.subExpressions[2].constructor.name).toEqual('NotExp');- expect(rootExp.subExpressions[2].subExpression.constructor.name).toEqual('AttributeExistsExp');- expect(rootExp.subExpressions[2].subExpression.attributeType).toEqual('label');- expect(rootExp.subExpressions[2].subExpression.attributeName).toEqual('mylabel');+ expect(rootExp.subExpressions[2].constructor.name).toEqual("NotExp");+ expect(rootExp.subExpressions[2].subExpression.constructor.name).toEqual("AttributeExistsExp");+ expect(rootExp.subExpressions[2].subExpression.attributeType).toEqual("label");+ expect(rootExp.subExpressions[2].subExpression.attributeName).toEqual("mylabel");rootExp = parse({fulltextTokens: [],- expressionTokens: tokens(['~!myrelation']),- searchContext: new SearchContext(),+ expressionTokens: tokens(["~!myrelation"]),+ searchContext: new SearchContext()});- expect(rootExp.constructor.name).toEqual('AndExp');+ expect(rootExp.constructor.name).toEqual("AndExp");assertIsArchived(rootExp.subExpressions[0]);- expect(rootExp.subExpressions[2].constructor.name).toEqual('NotExp');- expect(rootExp.subExpressions[2].subExpression.constructor.name).toEqual('AttributeExistsExp');- expect(rootExp.subExpressions[2].subExpression.attributeType).toEqual('relation');- expect(rootExp.subExpressions[2].subExpression.attributeName).toEqual('myrelation');+ expect(rootExp.subExpressions[2].constructor.name).toEqual("NotExp");+ expect(rootExp.subExpressions[2].subExpression.constructor.name).toEqual("AttributeExistsExp");+ expect(rootExp.subExpressions[2].subExpression.attributeType).toEqual("relation");+ expect(rootExp.subExpressions[2].subExpression.attributeName).toEqual("myrelation");});- it('simple label AND', () => {+ it("simple label AND", () => {const rootExp = parse({fulltextTokens: [],- expressionTokens: tokens(['#first', '=', 'text', 'and', '#second', '=', 'text']),- searchContext: new SearchContext(true),+ expressionTokens: tokens(["#first", "=", "text", "and", "#second", "=", "text"]),+ searchContext: new SearchContext(true)});- expect(rootExp.constructor.name).toEqual('AndExp');+ expect(rootExp.constructor.name).toEqual("AndExp");assertIsArchived(rootExp.subExpressions[0]);- expect(rootExp.subExpressions[2].constructor.name).toEqual('AndExp');+ expect(rootExp.subExpressions[2].constructor.name).toEqual("AndExp");const [firstSub, secondSub] = rootExp.subExpressions[2].subExpressions;- expect(firstSub.constructor.name).toEqual('LabelComparisonExp');- expect(firstSub.attributeName).toEqual('first');+ expect(firstSub.constructor.name).toEqual("LabelComparisonExp");+ expect(firstSub.attributeName).toEqual("first");- expect(secondSub.constructor.name).toEqual('LabelComparisonExp');- expect(secondSub.attributeName).toEqual('second');+ expect(secondSub.constructor.name).toEqual("LabelComparisonExp");+ expect(secondSub.attributeName).toEqual("second");});- it('simple label AND without explicit AND', () => {+ it("simple label AND without explicit AND", () => {const rootExp = parse({fulltextTokens: [],- expressionTokens: tokens(['#first', '=', 'text', '#second', '=', 'text']),- searchContext: new SearchContext(),+ expressionTokens: tokens(["#first", "=", "text", "#second", "=", "text"]),+ searchContext: new SearchContext()});- expect(rootExp.constructor.name).toEqual('AndExp');+ expect(rootExp.constructor.name).toEqual("AndExp");assertIsArchived(rootExp.subExpressions[0]);- expect(rootExp.subExpressions[2].constructor.name).toEqual('AndExp');+ expect(rootExp.subExpressions[2].constructor.name).toEqual("AndExp");const [firstSub, secondSub] = rootExp.subExpressions[2].subExpressions;- expect(firstSub.constructor.name).toEqual('LabelComparisonExp');- expect(firstSub.attributeName).toEqual('first');+ expect(firstSub.constructor.name).toEqual("LabelComparisonExp");+ expect(firstSub.attributeName).toEqual("first");- expect(secondSub.constructor.name).toEqual('LabelComparisonExp');- expect(secondSub.attributeName).toEqual('second');+ expect(secondSub.constructor.name).toEqual("LabelComparisonExp");+ expect(secondSub.attributeName).toEqual("second");});- it('simple label OR', () => {+ it("simple label OR", () => {const rootExp = parse({fulltextTokens: [],- expressionTokens: tokens(['#first', '=', 'text', 'or', '#second', '=', 'text']),- searchContext: new SearchContext(),+ expressionTokens: tokens(["#first", "=", "text", "or", "#second", "=", "text"]),+ searchContext: new SearchContext()});- expect(rootExp.constructor.name).toEqual('AndExp');+ expect(rootExp.constructor.name).toEqual("AndExp");assertIsArchived(rootExp.subExpressions[0]);- expect(rootExp.subExpressions[2].constructor.name).toEqual('OrExp');+ expect(rootExp.subExpressions[2].constructor.name).toEqual("OrExp");const [firstSub, secondSub] = rootExp.subExpressions[2].subExpressions;- expect(firstSub.constructor.name).toEqual('LabelComparisonExp');- expect(firstSub.attributeName).toEqual('first');+ expect(firstSub.constructor.name).toEqual("LabelComparisonExp");+ expect(firstSub.attributeName).toEqual("first");- expect(secondSub.constructor.name).toEqual('LabelComparisonExp');- expect(secondSub.attributeName).toEqual('second');+ expect(secondSub.constructor.name).toEqual("LabelComparisonExp");+ expect(secondSub.attributeName).toEqual("second");});- it('fulltext and simple label', () => {+ it("fulltext and simple label", () => {const rootExp = parse({- fulltextTokens: tokens(['hello']),- expressionTokens: tokens(['#mylabel', '=', 'text']),- searchContext: new SearchContext({ excludeArchived: true }),+ fulltextTokens: tokens(["hello"]),+ expressionTokens: tokens(["#mylabel", "=", "text"]),+ searchContext: new SearchContext({ excludeArchived: true })});- expect(rootExp.constructor.name).toEqual('AndExp');+ expect(rootExp.constructor.name).toEqual("AndExp");const [firstSub, secondSub, thirdSub, fourth] = rootExp.subExpressions;- expect(firstSub.constructor.name).toEqual('PropertyComparisonExp');- expect(firstSub.propertyName).toEqual('isArchived');+ expect(firstSub.constructor.name).toEqual("PropertyComparisonExp");+ expect(firstSub.propertyName).toEqual("isArchived");- expect(thirdSub.constructor.name).toEqual('OrExp');- expect(thirdSub.subExpressions[0].constructor.name).toEqual('NoteFlatTextExp');- expect(thirdSub.subExpressions[0].tokens).toEqual(['hello']);+ expect(thirdSub.constructor.name).toEqual("OrExp");+ expect(thirdSub.subExpressions[0].constructor.name).toEqual("NoteFlatTextExp");+ expect(thirdSub.subExpressions[0].tokens).toEqual(["hello"]);- expect(fourth.constructor.name).toEqual('LabelComparisonExp');- expect(fourth.attributeName).toEqual('mylabel');+ expect(fourth.constructor.name).toEqual("LabelComparisonExp");+ expect(fourth.attributeName).toEqual("mylabel");});- it('label sub-expression', () => {+ it("label sub-expression", () => {const rootExp = parse({fulltextTokens: [],- expressionTokens: tokens(['#first', '=', 'text', 'or', ['#second', '=', 'text', 'and', '#third', '=', 'text']]),- searchContext: new SearchContext(),+ expressionTokens: tokens(["#first", "=", "text", "or", ["#second", "=", "text", "and", "#third", "=", "text"]]),+ searchContext: new SearchContext()});- expect(rootExp.constructor.name).toEqual('AndExp');+ expect(rootExp.constructor.name).toEqual("AndExp");assertIsArchived(rootExp.subExpressions[0]);- expect(rootExp.subExpressions[2].constructor.name).toEqual('OrExp');+ expect(rootExp.subExpressions[2].constructor.name).toEqual("OrExp");const [firstSub, secondSub] = rootExp.subExpressions[2].subExpressions;- expect(firstSub.constructor.name).toEqual('LabelComparisonExp');- expect(firstSub.attributeName).toEqual('first');+ expect(firstSub.constructor.name).toEqual("LabelComparisonExp");+ expect(firstSub.attributeName).toEqual("first");- expect(secondSub.constructor.name).toEqual('AndExp');+ expect(secondSub.constructor.name).toEqual("AndExp");const [firstSubSub, secondSubSub] = secondSub.subExpressions;- expect(firstSubSub.constructor.name).toEqual('LabelComparisonExp');- expect(firstSubSub.attributeName).toEqual('second');+ expect(firstSubSub.constructor.name).toEqual("LabelComparisonExp");+ expect(firstSubSub.attributeName).toEqual("second");- expect(secondSubSub.constructor.name).toEqual('LabelComparisonExp');- expect(secondSubSub.attributeName).toEqual('third');+ expect(secondSubSub.constructor.name).toEqual("LabelComparisonExp");+ expect(secondSubSub.attributeName).toEqual("third");});- it('label sub-expression without explicit operator', () => {+ it("label sub-expression without explicit operator", () => {const rootExp = parse({fulltextTokens: [],- expressionTokens: tokens(['#first', ['#second', 'or', '#third'], '#fourth']),- searchContext: new SearchContext(),+ expressionTokens: tokens(["#first", ["#second", "or", "#third"], "#fourth"]),+ searchContext: new SearchContext()});- expect(rootExp.constructor.name).toEqual('AndExp');+ expect(rootExp.constructor.name).toEqual("AndExp");assertIsArchived(rootExp.subExpressions[0]);- expect(rootExp.subExpressions[2].constructor.name).toEqual('AndExp');+ expect(rootExp.subExpressions[2].constructor.name).toEqual("AndExp");const [firstSub, secondSub, thirdSub] = rootExp.subExpressions[2].subExpressions;- expect(firstSub.constructor.name).toEqual('AttributeExistsExp');- expect(firstSub.attributeName).toEqual('first');+ expect(firstSub.constructor.name).toEqual("AttributeExistsExp");+ expect(firstSub.attributeName).toEqual("first");- expect(secondSub.constructor.name).toEqual('OrExp');+ expect(secondSub.constructor.name).toEqual("OrExp");const [firstSubSub, secondSubSub] = secondSub.subExpressions;- expect(firstSubSub.constructor.name).toEqual('AttributeExistsExp');- expect(firstSubSub.attributeName).toEqual('second');+ expect(firstSubSub.constructor.name).toEqual("AttributeExistsExp");+ expect(firstSubSub.attributeName).toEqual("second");- expect(secondSubSub.constructor.name).toEqual('AttributeExistsExp');- expect(secondSubSub.attributeName).toEqual('third');+ expect(secondSubSub.constructor.name).toEqual("AttributeExistsExp");+ expect(secondSubSub.attributeName).toEqual("third");- expect(thirdSub.constructor.name).toEqual('AttributeExistsExp');- expect(thirdSub.attributeName).toEqual('fourth');+ expect(thirdSub.constructor.name).toEqual("AttributeExistsExp");+ expect(thirdSub.attributeName).toEqual("fourth");});});-describe('Invalid expressions', () => {- it('incomplete comparison', () => {+describe("Invalid expressions", () => {+ it("incomplete comparison", () => {const searchContext = new SearchContext();parse({fulltextTokens: [],- expressionTokens: tokens(['#first', '=']),- searchContext,+ expressionTokens: tokens(["#first", "="]),+ searchContext});expect(searchContext.error).toEqual('Misplaced or incomplete expression "="');});- it('comparison between labels is impossible', () => {+ it("comparison between labels is impossible", () => {let searchContext = new SearchContext();- searchContext.originalQuery = '#first = #second';+ searchContext.originalQuery = "#first = #second";parse({fulltextTokens: [],- expressionTokens: tokens(['#first', '=', '#second']),- searchContext,+ expressionTokens: tokens(["#first", "=", "#second"]),+ searchContext});- expect(searchContext.error).toEqual(- `Error near token "#second" in "#first = #second", it's possible to compare with constant only.`- );+ expect(searchContext.error).toEqual(`Error near token "#second" in "#first = #second", it's possible to compare with constant only.`);searchContext = new SearchContext();- searchContext.originalQuery = '#first = note.relations.second';+ searchContext.originalQuery = "#first = note.relations.second";parse({fulltextTokens: [],- expressionTokens: tokens(['#first', '=', 'note', '.', 'relations', 'second']),- searchContext,+ expressionTokens: tokens(["#first", "=", "note", ".", "relations", "second"]),+ searchContext});- expect(searchContext.error).toEqual(- `Error near token "note" in "#first = note.relations.second", it's possible to compare with constant only.`- );+ expect(searchContext.error).toEqual(`Error near token "note" in "#first = note.relations.second", it's possible to compare with constant only.`);const rootExp = parse({fulltextTokens: [],expressionTokens: [- { token: '#first', inQuotes: false },- { token: '=', inQuotes: false },- { token: '#second', inQuotes: true },+ { token: "#first", inQuotes: false },+ { token: "=", inQuotes: false },+ { token: "#second", inQuotes: true }],- searchContext: new SearchContext(),+ searchContext: new SearchContext()});- expect(rootExp.constructor.name).toEqual('AndExp');+ expect(rootExp.constructor.name).toEqual("AndExp");assertIsArchived(rootExp.subExpressions[0]);- expect(rootExp.subExpressions[2].constructor.name).toEqual('LabelComparisonExp');- expect(rootExp.subExpressions[2].attributeType).toEqual('label');- expect(rootExp.subExpressions[2].attributeName).toEqual('first');+ expect(rootExp.subExpressions[2].constructor.name).toEqual("LabelComparisonExp");+ expect(rootExp.subExpressions[2].attributeType).toEqual("label");+ expect(rootExp.subExpressions[2].attributeName).toEqual("first");expect(rootExp.subExpressions[2].comparator).toBeTruthy();});- it('searching by relation without note property', () => {+ it("searching by relation without note property", () => {const searchContext = new SearchContext();parse({fulltextTokens: [],- expressionTokens: tokens(['~first', '=', 'text', '-', 'abc']),- searchContext,+ expressionTokens: tokens(["~first", "=", "text", "-", "abc"]),+ searchContext});expect(searchContext.error).toEqual('Relation can be compared only with property, e.g. ~relation.title=hello in ""');diff --git a/spec/search/search.spec.ts b/spec/search/search.spec.tsindex a058ae8950..0099546ad7 100644--- a/spec/search/search.spec.ts+++ b/spec/search/search.spec.ts@@ -6,195 +6,177 @@ import dateUtils from "../../src/services/date_utils.js";import becca from "../../src/becca/becca.js";import becca_mocking from "./becca_mocking.js";-describe('Search', () => {+describe("Search", () => {let rootNote: any;beforeEach(() => {becca.reset();- rootNote = new becca_mocking.NoteBuilder(new BNote({ noteId: 'root', title: 'root', type: 'text' }));+ rootNote = new becca_mocking.NoteBuilder(new BNote({ noteId: "root", title: "root", type: "text" }));new BBranch({- branchId: 'none_root',- noteId: 'root',- parentNoteId: 'none',- notePosition: 10,+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",+ notePosition: 10});});- xit('simple path match', () => {- rootNote.child(becca_mocking.note('Europe').child(becca_mocking.note('Austria')));+ xit("simple path match", () => {+ rootNote.child(becca_mocking.note("Europe").child(becca_mocking.note("Austria")));const searchContext = new SearchContext();- const searchResults = searchService.findResultsWithQuery('europe austria', searchContext);+ const searchResults = searchService.findResultsWithQuery("europe austria", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Austria')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Austria")).toBeTruthy();});- xit('normal search looks also at attributes', () => {- const austria = becca_mocking.note('Austria');- const vienna = becca_mocking.note('Vienna');+ xit("normal search looks also at attributes", () => {+ const austria = becca_mocking.note("Austria");+ const vienna = becca_mocking.note("Vienna");- rootNote.child(austria.relation('capital', vienna.note)).child(vienna.label('inhabitants', '1888776'));+ rootNote.child(austria.relation("capital", vienna.note)).child(vienna.label("inhabitants", "1888776"));const searchContext = new SearchContext();- let searchResults = searchService.findResultsWithQuery('capital', searchContext);+ let searchResults = searchService.findResultsWithQuery("capital", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Austria')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Austria")).toBeTruthy();- searchResults = searchService.findResultsWithQuery('inhabitants', searchContext);+ searchResults = searchService.findResultsWithQuery("inhabitants", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Vienna')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Vienna")).toBeTruthy();});- xit('normal search looks also at type and mime', () => {- rootNote- .child(becca_mocking.note('Effective Java', { type: 'book', mime: '' }))- .child(becca_mocking.note('Hello World.java', { type: 'code', mime: 'text/x-java' }));+ xit("normal search looks also at type and mime", () => {+ rootNote.child(becca_mocking.note("Effective Java", { type: "book", mime: "" })).child(becca_mocking.note("Hello World.java", { type: "code", mime: "text/x-java" }));const searchContext = new SearchContext();- let searchResults = searchService.findResultsWithQuery('book', searchContext);+ let searchResults = searchService.findResultsWithQuery("book", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Effective Java')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Effective Java")).toBeTruthy();- searchResults = searchService.findResultsWithQuery('text', searchContext); // should match mime+ searchResults = searchService.findResultsWithQuery("text", searchContext); // should match mimeexpect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Hello World.java')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Hello World.java")).toBeTruthy();- searchResults = searchService.findResultsWithQuery('java', searchContext);+ searchResults = searchService.findResultsWithQuery("java", searchContext);expect(searchResults.length).toEqual(2);});- xit('only end leafs are results', () => {- rootNote.child(becca_mocking.note('Europe').child(becca_mocking.note('Austria')));+ xit("only end leafs are results", () => {+ rootNote.child(becca_mocking.note("Europe").child(becca_mocking.note("Austria")));const searchContext = new SearchContext();- const searchResults = searchService.findResultsWithQuery('europe', searchContext);+ const searchResults = searchService.findResultsWithQuery("europe", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Europe')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Europe")).toBeTruthy();});- xit('only end leafs are results', () => {- rootNote.child(becca_mocking.note('Europe').child(becca_mocking.note('Austria').label('capital', 'Vienna')));+ xit("only end leafs are results", () => {+ rootNote.child(becca_mocking.note("Europe").child(becca_mocking.note("Austria").label("capital", "Vienna")));const searchContext = new SearchContext();- const searchResults = searchService.findResultsWithQuery('Vienna', searchContext);+ const searchResults = searchService.findResultsWithQuery("Vienna", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Austria')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Austria")).toBeTruthy();});- it('label comparison with short syntax', () => {- rootNote.child(- becca_mocking- .note('Europe')- .child(becca_mocking.note('Austria').label('capital', 'Vienna'))- .child(becca_mocking.note('Czech Republic').label('capital', 'Prague'))- );+ it("label comparison with short syntax", () => {+ rootNote.child(becca_mocking.note("Europe").child(becca_mocking.note("Austria").label("capital", "Vienna")).child(becca_mocking.note("Czech Republic").label("capital", "Prague")));const searchContext = new SearchContext();- let searchResults = searchService.findResultsWithQuery('#capital=Vienna', searchContext);+ let searchResults = searchService.findResultsWithQuery("#capital=Vienna", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Austria')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Austria")).toBeTruthy();// case sensitivity:- searchResults = searchService.findResultsWithQuery('#CAPITAL=VIENNA', searchContext);+ searchResults = searchService.findResultsWithQuery("#CAPITAL=VIENNA", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Austria')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Austria")).toBeTruthy();- searchResults = searchService.findResultsWithQuery('#caPItal=vienNa', searchContext);+ searchResults = searchService.findResultsWithQuery("#caPItal=vienNa", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Austria')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Austria")).toBeTruthy();});- it('label comparison with full syntax', () => {- rootNote.child(- becca_mocking- .note('Europe')- .child(becca_mocking.note('Austria').label('capital', 'Vienna'))- .child(becca_mocking.note('Czech Republic').label('capital', 'Prague'))- );+ it("label comparison with full syntax", () => {+ rootNote.child(becca_mocking.note("Europe").child(becca_mocking.note("Austria").label("capital", "Vienna")).child(becca_mocking.note("Czech Republic").label("capital", "Prague")));const searchContext = new SearchContext();- let searchResults = searchService.findResultsWithQuery('# note.labels.capital=Prague', searchContext);+ let searchResults = searchService.findResultsWithQuery("# note.labels.capital=Prague", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Czech Republic')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Czech Republic")).toBeTruthy();});- it('numeric label comparison', () => {+ it("numeric label comparison", () => {rootNote.child(becca_mocking- .note('Europe')- .label('country', '', true)- .child(becca_mocking.note('Austria').label('population', '8859000'))- .child(becca_mocking.note('Czech Republic').label('population', '10650000'))+ .note("Europe")+ .label("country", "", true)+ .child(becca_mocking.note("Austria").label("population", "8859000"))+ .child(becca_mocking.note("Czech Republic").label("population", "10650000")));const searchContext = new SearchContext();- const searchResults = searchService.findResultsWithQuery('#country #population >= 10000000', searchContext);+ const searchResults = searchService.findResultsWithQuery("#country #population >= 10000000", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Czech Republic')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Czech Republic")).toBeTruthy();});- xit('inherited label comparison', () => {- rootNote.child(- becca_mocking- .note('Europe')- .label('country', '', true)- .child(becca_mocking.note('Austria'))- .child(becca_mocking.note('Czech Republic'))- );+ xit("inherited label comparison", () => {+ rootNote.child(becca_mocking.note("Europe").label("country", "", true).child(becca_mocking.note("Austria")).child(becca_mocking.note("Czech Republic")));const searchContext = new SearchContext();- const searchResults = searchService.findResultsWithQuery('austria #country', searchContext);+ const searchResults = searchService.findResultsWithQuery("austria #country", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Austria')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Austria")).toBeTruthy();});- it('numeric label comparison fallback to string comparison', () => {+ it("numeric label comparison fallback to string comparison", () => {// dates should not be coerced into numbers which would then give wrong numbersrootNote.child(becca_mocking- .note('Europe')- .label('country', '', true)- .child(becca_mocking.note('Austria').label('established', '1955-07-27'))- .child(becca_mocking.note('Czech Republic').label('established', '1993-01-01'))- .child(becca_mocking.note('Hungary').label('established', '1920-06-04'))+ .note("Europe")+ .label("country", "", true)+ .child(becca_mocking.note("Austria").label("established", "1955-07-27"))+ .child(becca_mocking.note("Czech Republic").label("established", "1993-01-01"))+ .child(becca_mocking.note("Hungary").label("established", "1920-06-04")));const searchContext = new SearchContext();let searchResults = searchService.findResultsWithQuery('#established <= "1955-01-01"', searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Hungary')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Hungary")).toBeTruthy();searchResults = searchService.findResultsWithQuery('#established > "1955-01-01"', searchContext);expect(searchResults.length).toEqual(2);- expect(becca_mocking.findNoteByTitle(searchResults, 'Austria')).toBeTruthy();- expect(becca_mocking.findNoteByTitle(searchResults, 'Czech Republic')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Austria")).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Czech Republic")).toBeTruthy();});- it('smart date comparisons', () => {+ it("smart date comparisons", () => {// dates should not be coerced into numbers which would then give wrong numbersrootNote.child(becca_mocking- .note('My note', { dateCreated: dateUtils.localNowDateTime() })- .label('year', new Date().getFullYear().toString())- .label('month', dateUtils.localNowDate().substr(0, 7))- .label('date', dateUtils.localNowDate())- .label('dateTime', dateUtils.localNowDateTime())+ .note("My note", { dateCreated: dateUtils.localNowDateTime() })+ .label("year", new Date().getFullYear().toString())+ .label("month", dateUtils.localNowDate().substr(0, 7))+ .label("date", dateUtils.localNowDate())+ .label("dateTime", dateUtils.localNowDateTime()));const searchContext = new SearchContext();@@ -206,263 +188,258 @@ describe('Search', () => {.toEqual(expectedResultCount);if (expectedResultCount === 1) {- expect(becca_mocking.findNoteByTitle(searchResults, 'My note')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "My note")).toBeTruthy();}}- test('#year = YEAR', 1);+ test("#year = YEAR", 1);test("#year = 'YEAR'", 0);- test('#year >= YEAR', 1);- test('#year <= YEAR', 1);- test('#year < YEAR+1', 1);- test('#year < YEAR + 1', 1);- test('#year < year + 1', 1);- test('#year > YEAR+1', 0);-- test('#month = MONTH', 1);- test('#month = month', 1);+ test("#year >= YEAR", 1);+ test("#year <= YEAR", 1);+ test("#year < YEAR+1", 1);+ test("#year < YEAR + 1", 1);+ test("#year < year + 1", 1);+ test("#year > YEAR+1", 0);++ test("#month = MONTH", 1);+ test("#month = month", 1);test("#month = 'MONTH'", 0);- test('note.dateCreated =* month', 2);+ test("note.dateCreated =* month", 2);- test('#date = TODAY', 1);- test('#date = today', 1);+ test("#date = TODAY", 1);+ test("#date = today", 1);test("#date = 'today'", 0);- test('#date > TODAY', 0);- test('#date > TODAY-1', 1);- test('#date > TODAY - 1', 1);- test('#date < TODAY+1', 1);- test('#date < TODAY + 1', 1);+ test("#date > TODAY", 0);+ test("#date > TODAY-1", 1);+ test("#date > TODAY - 1", 1);+ test("#date < TODAY+1", 1);+ test("#date < TODAY + 1", 1);test("#date < 'TODAY + 1'", 1);- test('#dateTime <= NOW+10', 1);- test('#dateTime <= NOW + 10', 1);- test('#dateTime < NOW-10', 0);- test('#dateTime >= NOW-10', 1);- test('#dateTime < NOW-10', 0);+ test("#dateTime <= NOW+10", 1);+ test("#dateTime <= NOW + 10", 1);+ test("#dateTime < NOW-10", 0);+ test("#dateTime >= NOW-10", 1);+ test("#dateTime < NOW-10", 0);});- it('logical or', () => {+ it("logical or", () => {rootNote.child(becca_mocking- .note('Europe')- .label('country', '', true)- .child(becca_mocking.note('Austria').label('languageFamily', 'germanic'))- .child(becca_mocking.note('Czech Republic').label('languageFamily', 'slavic'))- .child(becca_mocking.note('Hungary').label('languageFamily', 'finnougric'))+ .note("Europe")+ .label("country", "", true)+ .child(becca_mocking.note("Austria").label("languageFamily", "germanic"))+ .child(becca_mocking.note("Czech Republic").label("languageFamily", "slavic"))+ .child(becca_mocking.note("Hungary").label("languageFamily", "finnougric")));const searchContext = new SearchContext();- const searchResults = searchService.findResultsWithQuery('#languageFamily = slavic OR #languageFamily = germanic', searchContext);+ const searchResults = searchService.findResultsWithQuery("#languageFamily = slavic OR #languageFamily = germanic", searchContext);expect(searchResults.length).toEqual(2);- expect(becca_mocking.findNoteByTitle(searchResults, 'Czech Republic')).toBeTruthy();- expect(becca_mocking.findNoteByTitle(searchResults, 'Austria')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Czech Republic")).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Austria")).toBeTruthy();});- it('fuzzy attribute search', () => {+ it("fuzzy attribute search", () => {rootNote.child(becca_mocking- .note('Europe')- .label('country', '', true)- .child(becca_mocking.note('Austria').label('languageFamily', 'germanic'))- .child(becca_mocking.note('Czech Republic').label('languageFamily', 'slavic'))+ .note("Europe")+ .label("country", "", true)+ .child(becca_mocking.note("Austria").label("languageFamily", "germanic"))+ .child(becca_mocking.note("Czech Republic").label("languageFamily", "slavic")));let searchContext = new SearchContext({ fuzzyAttributeSearch: false });- let searchResults = searchService.findResultsWithQuery('#language', searchContext);+ let searchResults = searchService.findResultsWithQuery("#language", searchContext);expect(searchResults.length).toEqual(0);- searchResults = searchService.findResultsWithQuery('#languageFamily=ger', searchContext);+ searchResults = searchService.findResultsWithQuery("#languageFamily=ger", searchContext);expect(searchResults.length).toEqual(0);searchContext = new SearchContext({ fuzzyAttributeSearch: true });- searchResults = searchService.findResultsWithQuery('#language', searchContext);+ searchResults = searchService.findResultsWithQuery("#language", searchContext);expect(searchResults.length).toEqual(2);- searchResults = searchService.findResultsWithQuery('#languageFamily=ger', searchContext);+ searchResults = searchService.findResultsWithQuery("#languageFamily=ger", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Austria')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Austria")).toBeTruthy();});- it('filter by note property', () => {- rootNote.child(becca_mocking.note('Europe').child(becca_mocking.note('Austria')).child(becca_mocking.note('Czech Republic')));+ it("filter by note property", () => {+ rootNote.child(becca_mocking.note("Europe").child(becca_mocking.note("Austria")).child(becca_mocking.note("Czech Republic")));const searchContext = new SearchContext();- const searchResults = searchService.findResultsWithQuery('# note.title =* czech', searchContext);+ const searchResults = searchService.findResultsWithQuery("# note.title =* czech", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Czech Republic')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Czech Republic")).toBeTruthy();});it("filter by note's parent", () => {rootNote.child(becca_mocking- .note('Europe')- .child(becca_mocking.note('Austria'))- .child(becca_mocking.note('Czech Republic').child(becca_mocking.note('Prague')))+ .note("Europe")+ .child(becca_mocking.note("Austria"))+ .child(becca_mocking.note("Czech Republic").child(becca_mocking.note("Prague"))))- .child(becca_mocking.note('Asia').child(becca_mocking.note('Taiwan')));+ .child(becca_mocking.note("Asia").child(becca_mocking.note("Taiwan")));const searchContext = new SearchContext();- let searchResults = searchService.findResultsWithQuery('# note.parents.title = Europe', searchContext);+ let searchResults = searchService.findResultsWithQuery("# note.parents.title = Europe", searchContext);expect(searchResults.length).toEqual(2);- expect(becca_mocking.findNoteByTitle(searchResults, 'Austria')).toBeTruthy();- expect(becca_mocking.findNoteByTitle(searchResults, 'Czech Republic')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Austria")).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Czech Republic")).toBeTruthy();- searchResults = searchService.findResultsWithQuery('# note.parents.title = Asia', searchContext);+ searchResults = searchService.findResultsWithQuery("# note.parents.title = Asia", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Taiwan')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Taiwan")).toBeTruthy();- searchResults = searchService.findResultsWithQuery('# note.parents.parents.title = Europe', searchContext);+ searchResults = searchService.findResultsWithQuery("# note.parents.parents.title = Europe", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Prague')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Prague")).toBeTruthy();});it("filter by note's ancestor", () => {rootNote.child(becca_mocking- .note('Europe')- .child(becca_mocking.note('Austria'))- .child(becca_mocking.note('Czech Republic').child(becca_mocking.note('Prague').label('city')))+ .note("Europe")+ .child(becca_mocking.note("Austria"))+ .child(becca_mocking.note("Czech Republic").child(becca_mocking.note("Prague").label("city"))))- .child(becca_mocking.note('Asia').child(becca_mocking.note('Taiwan').child(becca_mocking.note('Taipei').label('city'))));+ .child(becca_mocking.note("Asia").child(becca_mocking.note("Taiwan").child(becca_mocking.note("Taipei").label("city"))));const searchContext = new SearchContext();- let searchResults = searchService.findResultsWithQuery('#city AND note.ancestors.title = Europe', searchContext);+ let searchResults = searchService.findResultsWithQuery("#city AND note.ancestors.title = Europe", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Prague')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Prague")).toBeTruthy();- searchResults = searchService.findResultsWithQuery('#city AND note.ancestors.title = Asia', searchContext);+ searchResults = searchService.findResultsWithQuery("#city AND note.ancestors.title = Asia", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Taipei')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Taipei")).toBeTruthy();});it("filter by note's child", () => {rootNote.child(becca_mocking- .note('Europe')- .child(becca_mocking.note('Austria').child(becca_mocking.note('Vienna')))- .child(becca_mocking.note('Czech Republic').child(becca_mocking.note('Prague')))+ .note("Europe")+ .child(becca_mocking.note("Austria").child(becca_mocking.note("Vienna")))+ .child(becca_mocking.note("Czech Republic").child(becca_mocking.note("Prague"))))- .child(becca_mocking.note('Oceania').child(becca_mocking.note('Australia')));+ .child(becca_mocking.note("Oceania").child(becca_mocking.note("Australia")));const searchContext = new SearchContext();- let searchResults = searchService.findResultsWithQuery('# note.children.title =* Aust', searchContext);+ let searchResults = searchService.findResultsWithQuery("# note.children.title =* Aust", searchContext);expect(searchResults.length).toEqual(2);- expect(becca_mocking.findNoteByTitle(searchResults, 'Europe')).toBeTruthy();- expect(becca_mocking.findNoteByTitle(searchResults, 'Oceania')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Europe")).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Oceania")).toBeTruthy();- searchResults = searchService.findResultsWithQuery(- '# note.children.title =* Aust AND note.children.title *= republic',- searchContext- );+ searchResults = searchService.findResultsWithQuery("# note.children.title =* Aust AND note.children.title *= republic", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Europe')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Europe")).toBeTruthy();- searchResults = searchService.findResultsWithQuery('# note.children.children.title = Prague', searchContext);+ searchResults = searchService.findResultsWithQuery("# note.children.children.title = Prague", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Europe')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Europe")).toBeTruthy();});it("filter by relation's note properties using short syntax", () => {- const austria = becca_mocking.note('Austria');- const portugal = becca_mocking.note('Portugal');+ const austria = becca_mocking.note("Austria");+ const portugal = becca_mocking.note("Portugal");rootNote.child(becca_mocking- .note('Europe')+ .note("Europe").child(austria)- .child(becca_mocking.note('Czech Republic').relation('neighbor', austria.note))+ .child(becca_mocking.note("Czech Republic").relation("neighbor", austria.note)).child(portugal)- .child(becca_mocking.note('Spain').relation('neighbor', portugal.note))+ .child(becca_mocking.note("Spain").relation("neighbor", portugal.note)));const searchContext = new SearchContext();- let searchResults = searchService.findResultsWithQuery('# ~neighbor.title = Austria', searchContext);+ let searchResults = searchService.findResultsWithQuery("# ~neighbor.title = Austria", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Czech Republic')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Czech Republic")).toBeTruthy();- searchResults = searchService.findResultsWithQuery('# ~neighbor.title = Portugal', searchContext);+ searchResults = searchService.findResultsWithQuery("# ~neighbor.title = Portugal", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Spain')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Spain")).toBeTruthy();});it("filter by relation's note properties using long syntax", () => {- const austria = becca_mocking.note('Austria');- const portugal = becca_mocking.note('Portugal');+ const austria = becca_mocking.note("Austria");+ const portugal = becca_mocking.note("Portugal");rootNote.child(becca_mocking- .note('Europe')+ .note("Europe").child(austria)- .child(becca_mocking.note('Czech Republic').relation('neighbor', austria.note))+ .child(becca_mocking.note("Czech Republic").relation("neighbor", austria.note)).child(portugal)- .child(becca_mocking.note('Spain').relation('neighbor', portugal.note))+ .child(becca_mocking.note("Spain").relation("neighbor", portugal.note)));const searchContext = new SearchContext();- const searchResults = searchService.findResultsWithQuery('# note.relations.neighbor.title = Austria', searchContext);+ const searchResults = searchService.findResultsWithQuery("# note.relations.neighbor.title = Austria", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Czech Republic')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Czech Republic")).toBeTruthy();});- it('filter by multiple level relation', () => {- const austria = becca_mocking.note('Austria');- const slovakia = becca_mocking.note('Slovakia');- const italy = becca_mocking.note('Italy');- const ukraine = becca_mocking.note('Ukraine');+ it("filter by multiple level relation", () => {+ const austria = becca_mocking.note("Austria");+ const slovakia = becca_mocking.note("Slovakia");+ const italy = becca_mocking.note("Italy");+ const ukraine = becca_mocking.note("Ukraine");rootNote.child(becca_mocking- .note('Europe')- .child(austria.relation('neighbor', italy.note).relation('neighbor', slovakia.note))- .child(becca_mocking.note('Czech Republic').relation('neighbor', austria.note).relation('neighbor', slovakia.note))- .child(slovakia.relation('neighbor', ukraine.note))+ .note("Europe")+ .child(austria.relation("neighbor", italy.note).relation("neighbor", slovakia.note))+ .child(becca_mocking.note("Czech Republic").relation("neighbor", austria.note).relation("neighbor", slovakia.note))+ .child(slovakia.relation("neighbor", ukraine.note)).child(ukraine));const searchContext = new SearchContext();- let searchResults = searchService.findResultsWithQuery('# note.relations.neighbor.relations.neighbor.title = Italy', searchContext);+ let searchResults = searchService.findResultsWithQuery("# note.relations.neighbor.relations.neighbor.title = Italy", searchContext);expect(searchResults.length).toEqual(1);- expect(becca_mocking.findNoteByTitle(searchResults, 'Czech Republic')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Czech Republic")).toBeTruthy();- searchResults = searchService.findResultsWithQuery('# note.relations.neighbor.relations.neighbor.title = Ukraine', searchContext);+ searchResults = searchService.findResultsWithQuery("# note.relations.neighbor.relations.neighbor.title = Ukraine", searchContext);expect(searchResults.length).toEqual(2);- expect(becca_mocking.findNoteByTitle(searchResults, 'Czech Republic')).toBeTruthy();- expect(becca_mocking.findNoteByTitle(searchResults, 'Austria')).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Czech Republic")).toBeTruthy();+ expect(becca_mocking.findNoteByTitle(searchResults, "Austria")).toBeTruthy();});- it('test note properties', () => {- const austria = becca_mocking.note('Austria');+ it("test note properties", () => {+ const austria = becca_mocking.note("Austria");- austria.relation('myself', austria.note);- austria.label('capital', 'Vienna');- austria.label('population', '8859000');+ austria.relation("myself", austria.note);+ austria.label("capital", "Vienna");+ austria.label("population", "8859000");rootNote- .child(becca_mocking.note('Asia'))- .child(- becca_mocking.note('Europe').child(austria.child(becca_mocking.note('Vienna')).child(becca_mocking.note('Sebastian Kurz')))- )- .child(becca_mocking.note('Mozart').child(austria));+ .child(becca_mocking.note("Asia"))+ .child(becca_mocking.note("Europe").child(austria.child(becca_mocking.note("Vienna")).child(becca_mocking.note("Sebastian Kurz"))))+ .child(becca_mocking.note("Mozart").child(austria));austria.note.isProtected = false;- austria.note.dateCreated = '2020-05-14 12:11:42.001+0200';- austria.note.dateModified = '2020-05-14 13:11:42.001+0200';- austria.note.utcDateCreated = '2020-05-14 10:11:42.001Z';- austria.note.utcDateModified = '2020-05-14 11:11:42.001Z';+ austria.note.dateCreated = "2020-05-14 12:11:42.001+0200";+ austria.note.dateModified = "2020-05-14 13:11:42.001+0200";+ austria.note.utcDateCreated = "2020-05-14 10:11:42.001Z";+ austria.note.utcDateModified = "2020-05-14 11:11:42.001Z";// austria.note.contentLength = 1001;const searchContext = new SearchContext();@@ -472,141 +449,130 @@ describe('Search', () => {expect(searchResults.length).toEqual(expectedResultCount);}- test('type', 'text', 7);- test('TYPE', 'TEXT', 7);- test('type', 'code', 0);+ test("type", "text", 7);+ test("TYPE", "TEXT", 7);+ test("type", "code", 0);- test('mime', 'text/html', 6);- test('mime', 'application/json', 0);+ test("mime", "text/html", 6);+ test("mime", "application/json", 0);- test('isProtected', 'false', 7);- test('isProtected', 'FALSE', 7);- test('isProtected', 'true', 0);- test('isProtected', 'TRUE', 0);+ test("isProtected", "false", 7);+ test("isProtected", "FALSE", 7);+ test("isProtected", "true", 0);+ test("isProtected", "TRUE", 0);- test('dateCreated', "'2020-05-14 12:11:42.001+0200'", 1);- test('dateCreated', 'wrong', 0);+ test("dateCreated", "'2020-05-14 12:11:42.001+0200'", 1);+ test("dateCreated", "wrong", 0);- test('dateModified', "'2020-05-14 13:11:42.001+0200'", 1);- test('dateModified', 'wrong', 0);+ test("dateModified", "'2020-05-14 13:11:42.001+0200'", 1);+ test("dateModified", "wrong", 0);- test('utcDateCreated', "'2020-05-14 10:11:42.001Z'", 1);- test('utcDateCreated', 'wrong', 0);+ test("utcDateCreated", "'2020-05-14 10:11:42.001Z'", 1);+ test("utcDateCreated", "wrong", 0);- test('utcDateModified', "'2020-05-14 11:11:42.001Z'", 1);- test('utcDateModified', 'wrong', 0);+ test("utcDateModified", "'2020-05-14 11:11:42.001Z'", 1);+ test("utcDateModified", "wrong", 0);- test('parentCount', '2', 1);- test('parentCount', '3', 0);+ test("parentCount", "2", 1);+ test("parentCount", "3", 0);- test('childrenCount', '2', 1);- test('childrenCount', '10', 0);+ test("childrenCount", "2", 1);+ test("childrenCount", "10", 0);- test('attributeCount', '3', 1);- test('attributeCount', '4', 0);+ test("attributeCount", "3", 1);+ test("attributeCount", "4", 0);- test('labelCount', '2', 1);- test('labelCount', '3', 0);+ test("labelCount", "2", 1);+ test("labelCount", "3", 0);- test('relationCount', '1', 1);- test('relationCount', '2', 0);+ test("relationCount", "1", 1);+ test("relationCount", "2", 0);});- it('test order by', () => {- const italy = becca_mocking.note('Italy').label('capital', 'Rome');- const slovakia = becca_mocking.note('Slovakia').label('capital', 'Bratislava');- const austria = becca_mocking.note('Austria').label('capital', 'Vienna');- const ukraine = becca_mocking.note('Ukraine').label('capital', 'Kiev');+ it("test order by", () => {+ const italy = becca_mocking.note("Italy").label("capital", "Rome");+ const slovakia = becca_mocking.note("Slovakia").label("capital", "Bratislava");+ const austria = becca_mocking.note("Austria").label("capital", "Vienna");+ const ukraine = becca_mocking.note("Ukraine").label("capital", "Kiev");- rootNote.child(becca_mocking.note('Europe').child(ukraine).child(slovakia).child(austria).child(italy));+ rootNote.child(becca_mocking.note("Europe").child(ukraine).child(slovakia).child(austria).child(italy));const searchContext = new SearchContext();- let searchResults = searchService.findResultsWithQuery('# note.parents.title = Europe orderBy note.title', searchContext);+ let searchResults = searchService.findResultsWithQuery("# note.parents.title = Europe orderBy note.title", searchContext);expect(searchResults.length).toEqual(4);- expect(becca.notes[searchResults[0].noteId].title).toEqual('Austria');- expect(becca.notes[searchResults[1].noteId].title).toEqual('Italy');- expect(becca.notes[searchResults[2].noteId].title).toEqual('Slovakia');- expect(becca.notes[searchResults[3].noteId].title).toEqual('Ukraine');+ expect(becca.notes[searchResults[0].noteId].title).toEqual("Austria");+ expect(becca.notes[searchResults[1].noteId].title).toEqual("Italy");+ expect(becca.notes[searchResults[2].noteId].title).toEqual("Slovakia");+ expect(becca.notes[searchResults[3].noteId].title).toEqual("Ukraine");- searchResults = searchService.findResultsWithQuery('# note.parents.title = Europe orderBy note.labels.capital', searchContext);+ searchResults = searchService.findResultsWithQuery("# note.parents.title = Europe orderBy note.labels.capital", searchContext);expect(searchResults.length).toEqual(4);- expect(becca.notes[searchResults[0].noteId].title).toEqual('Slovakia');- expect(becca.notes[searchResults[1].noteId].title).toEqual('Ukraine');- expect(becca.notes[searchResults[2].noteId].title).toEqual('Italy');- expect(becca.notes[searchResults[3].noteId].title).toEqual('Austria');+ expect(becca.notes[searchResults[0].noteId].title).toEqual("Slovakia");+ expect(becca.notes[searchResults[1].noteId].title).toEqual("Ukraine");+ expect(becca.notes[searchResults[2].noteId].title).toEqual("Italy");+ expect(becca.notes[searchResults[3].noteId].title).toEqual("Austria");- searchResults = searchService.findResultsWithQuery('# note.parents.title = Europe orderBy note.labels.capital DESC', searchContext);+ searchResults = searchService.findResultsWithQuery("# note.parents.title = Europe orderBy note.labels.capital DESC", searchContext);expect(searchResults.length).toEqual(4);- expect(becca.notes[searchResults[0].noteId].title).toEqual('Austria');- expect(becca.notes[searchResults[1].noteId].title).toEqual('Italy');- expect(becca.notes[searchResults[2].noteId].title).toEqual('Ukraine');- expect(becca.notes[searchResults[3].noteId].title).toEqual('Slovakia');-- searchResults = searchService.findResultsWithQuery(- '# note.parents.title = Europe orderBy note.labels.capital DESC limit 2',- searchContext- );+ expect(becca.notes[searchResults[0].noteId].title).toEqual("Austria");+ expect(becca.notes[searchResults[1].noteId].title).toEqual("Italy");+ expect(becca.notes[searchResults[2].noteId].title).toEqual("Ukraine");+ expect(becca.notes[searchResults[3].noteId].title).toEqual("Slovakia");++ searchResults = searchService.findResultsWithQuery("# note.parents.title = Europe orderBy note.labels.capital DESC limit 2", searchContext);expect(searchResults.length).toEqual(2);- expect(becca.notes[searchResults[0].noteId].title).toEqual('Austria');- expect(becca.notes[searchResults[1].noteId].title).toEqual('Italy');+ expect(becca.notes[searchResults[0].noteId].title).toEqual("Austria");+ expect(becca.notes[searchResults[1].noteId].title).toEqual("Italy");- searchResults = searchService.findResultsWithQuery('# note.parents.title = Europe orderBy #capital DESC limit 1', searchContext);+ searchResults = searchService.findResultsWithQuery("# note.parents.title = Europe orderBy #capital DESC limit 1", searchContext);expect(searchResults.length).toEqual(1);- searchResults = searchService.findResultsWithQuery('# note.parents.title = Europe orderBy #capital DESC limit 1000', searchContext);+ searchResults = searchService.findResultsWithQuery("# note.parents.title = Europe orderBy #capital DESC limit 1000", searchContext);expect(searchResults.length).toEqual(4);});- it('test not(...)', () => {- const italy = becca_mocking.note('Italy').label('capital', 'Rome');- const slovakia = becca_mocking.note('Slovakia').label('capital', 'Bratislava');+ it("test not(...)", () => {+ const italy = becca_mocking.note("Italy").label("capital", "Rome");+ const slovakia = becca_mocking.note("Slovakia").label("capital", "Bratislava");- rootNote.child(becca_mocking.note('Europe').child(slovakia).child(italy));+ rootNote.child(becca_mocking.note("Europe").child(slovakia).child(italy));const searchContext = new SearchContext();- let searchResults = searchService.findResultsWithQuery('# not(#capital) and note.noteId != root', searchContext);+ let searchResults = searchService.findResultsWithQuery("# not(#capital) and note.noteId != root", searchContext);expect(searchResults.length).toEqual(1);- expect(becca.notes[searchResults[0].noteId].title).toEqual('Europe');+ expect(becca.notes[searchResults[0].noteId].title).toEqual("Europe");- searchResults = searchService.findResultsWithQuery('#!capital and note.noteId != root', searchContext);+ searchResults = searchService.findResultsWithQuery("#!capital and note.noteId != root", searchContext);expect(searchResults.length).toEqual(1);- expect(becca.notes[searchResults[0].noteId].title).toEqual('Europe');+ expect(becca.notes[searchResults[0].noteId].title).toEqual("Europe");});- xit('test note.text *=* something', () => {- const italy = becca_mocking.note('Italy').label('capital', 'Rome');- const slovakia = becca_mocking.note('Slovakia').label('capital', 'Bratislava');+ xit("test note.text *=* something", () => {+ const italy = becca_mocking.note("Italy").label("capital", "Rome");+ const slovakia = becca_mocking.note("Slovakia").label("capital", "Bratislava");- rootNote.child(becca_mocking.note('Europe').child(slovakia).child(italy));+ rootNote.child(becca_mocking.note("Europe").child(slovakia).child(italy));const searchContext = new SearchContext();- let searchResults = searchService.findResultsWithQuery('# note.text *=* vaki and note.noteId != root', searchContext);+ let searchResults = searchService.findResultsWithQuery("# note.text *=* vaki and note.noteId != root", searchContext);expect(searchResults.length).toEqual(1);- expect(becca.notes[searchResults[0].noteId].title).toEqual('Slovakia');+ expect(becca.notes[searchResults[0].noteId].title).toEqual("Slovakia");});- xit('test that fulltext does not match archived notes', () => {- const italy = becca_mocking.note('Italy').label('capital', 'Rome');- const slovakia = becca_mocking.note('Slovakia').label('capital', 'Bratislava');+ xit("test that fulltext does not match archived notes", () => {+ const italy = becca_mocking.note("Italy").label("capital", "Rome");+ const slovakia = becca_mocking.note("Slovakia").label("capital", "Bratislava");- rootNote- .child(- becca_mocking- .note('Reddit')- .label('archived', '', true)- .child(becca_mocking.note('Post X'))- .child(becca_mocking.note('Post Y'))- )- .child(becca_mocking.note('Reddit is bad'));+ rootNote.child(becca_mocking.note("Reddit").label("archived", "", true).child(becca_mocking.note("Post X")).child(becca_mocking.note("Post Y"))).child(becca_mocking.note("Reddit is bad"));const searchContext = new SearchContext({ includeArchivedNotes: false });- let searchResults = searchService.findResultsWithQuery('reddit', searchContext);+ let searchResults = searchService.findResultsWithQuery("reddit", searchContext);expect(searchResults.length).toEqual(1);- expect(becca.notes[searchResults[0].noteId].title).toEqual('Reddit is bad');+ expect(becca.notes[searchResults[0].noteId].title).toEqual("Reddit is bad");});// FIXME: test what happens when we order without any filter criteriadiff --git a/spec/search/value_extractor.spec.ts b/spec/search/value_extractor.spec.tsindex 1672ddbb63..4155a7e51b 100644--- a/spec/search/value_extractor.spec.ts+++ b/spec/search/value_extractor.spec.ts@@ -5,77 +5,74 @@ import SearchContext from "../../src/services/search/search_context.js";const dsc = new SearchContext();-describe('Value extractor', () => {+describe("Value extractor", () => {beforeEach(() => {becca.reset();});- it('simple title extraction', async () => {- const europe = becca_mocking.note('Europe').note;+ it("simple title extraction", async () => {+ const europe = becca_mocking.note("Europe").note;- const valueExtractor = new ValueExtractor(dsc, ['note', 'title']);+ const valueExtractor = new ValueExtractor(dsc, ["note", "title"]);expect(valueExtractor.validate()).toBeFalsy();- expect(valueExtractor.extract(europe)).toEqual('Europe');+ expect(valueExtractor.extract(europe)).toEqual("Europe");});- it('label extraction', async () => {- const austria = becca_mocking.note('Austria').label('Capital', 'Vienna').note;+ it("label extraction", async () => {+ const austria = becca_mocking.note("Austria").label("Capital", "Vienna").note;- let valueExtractor = new ValueExtractor(dsc, ['note', 'labels', 'capital']);+ let valueExtractor = new ValueExtractor(dsc, ["note", "labels", "capital"]);expect(valueExtractor.validate()).toBeFalsy();- expect(valueExtractor.extract(austria)).toEqual('Vienna');+ expect(valueExtractor.extract(austria)).toEqual("Vienna");- valueExtractor = new ValueExtractor(dsc, ['#capital']);+ valueExtractor = new ValueExtractor(dsc, ["#capital"]);expect(valueExtractor.validate()).toBeFalsy();- expect(valueExtractor.extract(austria)).toEqual('Vienna');+ expect(valueExtractor.extract(austria)).toEqual("Vienna");});- it('parent/child property extraction', async () => {- const vienna = becca_mocking.note('Vienna');- const europe = becca_mocking.note('Europe').child(becca_mocking.note('Austria').child(vienna));+ it("parent/child property extraction", async () => {+ const vienna = becca_mocking.note("Vienna");+ const europe = becca_mocking.note("Europe").child(becca_mocking.note("Austria").child(vienna));- let valueExtractor = new ValueExtractor(dsc, ['note', 'children', 'children', 'title']);+ let valueExtractor = new ValueExtractor(dsc, ["note", "children", "children", "title"]);expect(valueExtractor.validate()).toBeFalsy();- expect(valueExtractor.extract(europe.note)).toEqual('Vienna');+ expect(valueExtractor.extract(europe.note)).toEqual("Vienna");- valueExtractor = new ValueExtractor(dsc, ['note', 'parents', 'parents', 'title']);+ valueExtractor = new ValueExtractor(dsc, ["note", "parents", "parents", "title"]);expect(valueExtractor.validate()).toBeFalsy();- expect(valueExtractor.extract(vienna.note)).toEqual('Europe');+ expect(valueExtractor.extract(vienna.note)).toEqual("Europe");});- it('extract through relation', async () => {- const czechRepublic = becca_mocking.note('Czech Republic').label('capital', 'Prague');- const slovakia = becca_mocking.note('Slovakia').label('capital', 'Bratislava');- const austria = becca_mocking.note('Austria').relation('neighbor', czechRepublic.note).relation('neighbor', slovakia.note);+ it("extract through relation", async () => {+ const czechRepublic = becca_mocking.note("Czech Republic").label("capital", "Prague");+ const slovakia = becca_mocking.note("Slovakia").label("capital", "Bratislava");+ const austria = becca_mocking.note("Austria").relation("neighbor", czechRepublic.note).relation("neighbor", slovakia.note);- let valueExtractor = new ValueExtractor(dsc, ['note', 'relations', 'neighbor', 'labels', 'capital']);+ let valueExtractor = new ValueExtractor(dsc, ["note", "relations", "neighbor", "labels", "capital"]);expect(valueExtractor.validate()).toBeFalsy();- expect(valueExtractor.extract(austria.note)).toEqual('Prague');+ expect(valueExtractor.extract(austria.note)).toEqual("Prague");- valueExtractor = new ValueExtractor(dsc, ['~neighbor', 'labels', 'capital']);+ valueExtractor = new ValueExtractor(dsc, ["~neighbor", "labels", "capital"]);expect(valueExtractor.validate()).toBeFalsy();- expect(valueExtractor.extract(austria.note)).toEqual('Prague');+ expect(valueExtractor.extract(austria.note)).toEqual("Prague");});});-describe('Invalid value extractor property path', () => {- it('each path must start with "note" (or label/relation)', () => expect(new ValueExtractor(dsc, ['neighbor']).validate()).toBeTruthy());+describe("Invalid value extractor property path", () => {+ it('each path must start with "note" (or label/relation)', () => expect(new ValueExtractor(dsc, ["neighbor"]).validate()).toBeTruthy());- it('extra path element after terminal label', () =>- expect(new ValueExtractor(dsc, ['~neighbor', 'labels', 'capital', 'noteId']).validate()).toBeTruthy());+ it("extra path element after terminal label", () => expect(new ValueExtractor(dsc, ["~neighbor", "labels", "capital", "noteId"]).validate()).toBeTruthy());- it('extra path element after terminal title', () =>- expect(new ValueExtractor(dsc, ['note', 'title', 'isProtected']).validate()).toBeTruthy());+ it("extra path element after terminal title", () => expect(new ValueExtractor(dsc, ["note", "title", "isProtected"]).validate()).toBeTruthy());- it('relation name and note property is missing', () => expect(new ValueExtractor(dsc, ['note', 'relations']).validate()).toBeTruthy());+ it("relation name and note property is missing", () => expect(new ValueExtractor(dsc, ["note", "relations"]).validate()).toBeTruthy());- it('relation is specified but target note property is not specified', () =>- expect(new ValueExtractor(dsc, ['note', 'relations', 'myrel']).validate()).toBeTruthy());+ it("relation is specified but target note property is not specified", () => expect(new ValueExtractor(dsc, ["note", "relations", "myrel"]).validate()).toBeTruthy());});diff --git a/spec/support/etapi.ts b/spec/support/etapi.tsindex 2738a34a23..3e6e1ac988 100644--- a/spec/support/etapi.ts+++ b/spec/support/etapi.ts@@ -2,176 +2,153 @@ import child_process from "child_process";let etapiAuthToken: string | undefined;-const getEtapiAuthorizationHeader = (): string =>- "Basic " + Buffer.from(`etapi:${etapiAuthToken}`).toString("base64");+const getEtapiAuthorizationHeader = (): string => "Basic " + Buffer.from(`etapi:${etapiAuthToken}`).toString("base64");const PORT: string = "9999";const HOST: string = "http://localhost:" + PORT;type SpecDefinitionsFunc = () => void;-function describeEtapi(- description: string,- specDefinitions: SpecDefinitionsFunc-): void {- describe(description, () => {- let appProcess: ReturnType<typeof child_process.spawn>;+function describeEtapi(description: string, specDefinitions: SpecDefinitionsFunc): void {+ describe(description, () => {+ let appProcess: ReturnType<typeof child_process.spawn>;- beforeAll(async () => {+ beforeAll(async () => {});- });-- afterAll(() => {+ afterAll(() => {});+ specDefinitions();});-- specDefinitions();- });}async function getEtapiResponse(url: string): Promise<Response> {- return await fetch(`${HOST}/etapi/${url}`, {- method: "GET",- headers: {- Authorization: getEtapiAuthorizationHeader(),- },- });+ return await fetch(`${HOST}/etapi/${url}`, {+ method: "GET",+ headers: {+ Authorization: getEtapiAuthorizationHeader()+ }+ });}async function getEtapi(url: string): Promise<any> {- const response = await getEtapiResponse(url);- return await processEtapiResponse(response);+ const response = await getEtapiResponse(url);+ return await processEtapiResponse(response);}async function getEtapiContent(url: string): Promise<Response> {- const response = await fetch(`${HOST}/etapi/${url}`, {- method: "GET",- headers: {- Authorization: getEtapiAuthorizationHeader(),- },- });+ const response = await fetch(`${HOST}/etapi/${url}`, {+ method: "GET",+ headers: {+ Authorization: getEtapiAuthorizationHeader()+ }+ });- checkStatus(response);+ checkStatus(response);- return response;+ return response;}-async function postEtapi(- url: string,- data: Record<string, unknown> = {}-): Promise<any> {- const response = await fetch(`${HOST}/etapi/${url}`, {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: getEtapiAuthorizationHeader(),- },- body: JSON.stringify(data),- });- return await processEtapiResponse(response);+async function postEtapi(url: string, data: Record<string, unknown> = {}): Promise<any> {+ const response = await fetch(`${HOST}/etapi/${url}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: getEtapiAuthorizationHeader()+ },+ body: JSON.stringify(data)+ });+ return await processEtapiResponse(response);}-async function postEtapiContent(- url: string,- data: BodyInit-): Promise<Response> {- const response = await fetch(`${HOST}/etapi/${url}`, {- method: "POST",- headers: {- "Content-Type": "application/octet-stream",- Authorization: getEtapiAuthorizationHeader(),- },- body: data,- });-- checkStatus(response);-- return response;+async function postEtapiContent(url: string, data: BodyInit): Promise<Response> {+ const response = await fetch(`${HOST}/etapi/${url}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/octet-stream",+ Authorization: getEtapiAuthorizationHeader()+ },+ body: data+ });++ checkStatus(response);++ return response;}-async function putEtapi(- url: string,- data: Record<string, unknown> = {}-): Promise<any> {- const response = await fetch(`${HOST}/etapi/${url}`, {- method: "PUT",- headers: {- "Content-Type": "application/json",- Authorization: getEtapiAuthorizationHeader(),- },- body: JSON.stringify(data),- });- return await processEtapiResponse(response);+async function putEtapi(url: string, data: Record<string, unknown> = {}): Promise<any> {+ const response = await fetch(`${HOST}/etapi/${url}`, {+ method: "PUT",+ headers: {+ "Content-Type": "application/json",+ Authorization: getEtapiAuthorizationHeader()+ },+ body: JSON.stringify(data)+ });+ return await processEtapiResponse(response);}-async function putEtapiContent(- url: string,- data?: BodyInit-): Promise<Response> {- const response = await fetch(`${HOST}/etapi/${url}`, {- method: "PUT",- headers: {- "Content-Type": "application/octet-stream",- Authorization: getEtapiAuthorizationHeader(),- },- body: data,- });-- checkStatus(response);-- return response;+async function putEtapiContent(url: string, data?: BodyInit): Promise<Response> {+ const response = await fetch(`${HOST}/etapi/${url}`, {+ method: "PUT",+ headers: {+ "Content-Type": "application/octet-stream",+ Authorization: getEtapiAuthorizationHeader()+ },+ body: data+ });++ checkStatus(response);++ return response;}-async function patchEtapi(- url: string,- data: Record<string, unknown> = {}-): Promise<any> {- const response = await fetch(`${HOST}/etapi/${url}`, {- method: "PATCH",- headers: {- "Content-Type": "application/json",- Authorization: getEtapiAuthorizationHeader(),- },- body: JSON.stringify(data),- });- return await processEtapiResponse(response);+async function patchEtapi(url: string, data: Record<string, unknown> = {}): Promise<any> {+ const response = await fetch(`${HOST}/etapi/${url}`, {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ Authorization: getEtapiAuthorizationHeader()+ },+ body: JSON.stringify(data)+ });+ return await processEtapiResponse(response);}async function deleteEtapi(url: string): Promise<any> {- const response = await fetch(`${HOST}/etapi/${url}`, {- method: "DELETE",- headers: {- Authorization: getEtapiAuthorizationHeader(),- },- });- return await processEtapiResponse(response);+ const response = await fetch(`${HOST}/etapi/${url}`, {+ method: "DELETE",+ headers: {+ Authorization: getEtapiAuthorizationHeader()+ }+ });+ return await processEtapiResponse(response);}async function processEtapiResponse(response: Response): Promise<any> {- const text = await response.text();+ const text = await response.text();- if (response.status < 200 || response.status >= 300) {- throw new Error(`ETAPI error ${response.status}: ${text}`);- }+ if (response.status < 200 || response.status >= 300) {+ throw new Error(`ETAPI error ${response.status}: ${text}`);+ }- return text?.trim() ? JSON.parse(text) : null;+ return text?.trim() ? JSON.parse(text) : null;}function checkStatus(response: Response): void {- if (response.status < 200 || response.status >= 300) {- throw new Error(`ETAPI error ${response.status}`);- }+ if (response.status < 200 || response.status >= 300) {+ throw new Error(`ETAPI error ${response.status}`);+ }}export default {- describeEtapi,- getEtapi,- getEtapiResponse,- getEtapiContent,- postEtapi,- postEtapiContent,- putEtapi,- putEtapiContent,- patchEtapi,- deleteEtapi,+ describeEtapi,+ getEtapi,+ getEtapiResponse,+ getEtapiContent,+ postEtapi,+ postEtapiContent,+ putEtapi,+ putEtapiContent,+ patchEtapi,+ deleteEtapi};diff --git a/spec/support/jasmine.json b/spec/support/jasmine.jsonindex 1a1e6b68e8..5043a9a037 100644--- a/spec/support/jasmine.json+++ b/spec/support/jasmine.json@@ -1,7 +1,7 @@{- "spec_dir": "spec",- "spec_files": ["./**/*.spec.ts"],- "helpers": ["helpers/**/*.js"],- "stopSpecOnExpectationFailure": false,- "random": true+ "spec_dir": "spec",+ "spec_files": ["./**/*.spec.ts"],+ "helpers": ["helpers/**/*.js"],+ "stopSpecOnExpectationFailure": false,+ "random": true}diff --git a/spec/support/utils.spec.ts b/spec/support/utils.spec.tsindex c385d0729a..566e225d80 100644--- a/spec/support/utils.spec.ts+++ b/spec/support/utils.spec.ts@@ -5,8 +5,7 @@ describe("Utils", () => {expect(trimIndentation`\Helloworld- 123`- ).toBe(`\+ 123`).toBe(`\Helloworld123`);diff --git a/spec/support/utils.ts b/spec/support/utils.tsindex 1e38fbe84e..8735c96517 100644--- a/spec/support/utils.ts+++ b/spec/support/utils.ts@@ -3,16 +3,16 @@ export function trimIndentation(strings: TemplateStringsArray) {// Count the number of spaces on the first line.let numSpaces = 0;- while (str.charAt(numSpaces) == ' ' && numSpaces < str.length) {+ while (str.charAt(numSpaces) == " " && numSpaces < str.length) {numSpaces++;}// Trim the indentation of the first line in all the lines.const lines = str.split("\n");const output = [];- for (let i=0; i<lines.length; i++) {+ for (let i = 0; i < lines.length; i++) {let numSpacesLine = 0;- while (str.charAt(numSpacesLine) == ' ' && numSpacesLine < str.length) {+ while (str.charAt(numSpacesLine) == " " && numSpacesLine < str.length) {numSpacesLine++;}output.push(lines[i].substring(numSpacesLine));diff --git a/src/anonymize.ts b/src/anonymize.tsindex 8ad803c63e..e78fe00179 100644--- a/src/anonymize.ts+++ b/src/anonymize.ts@@ -6,7 +6,7 @@ sqlInit.dbReady.then(async () => {try {console.log("Starting anonymization...");- const resp = await anonymizationService.createAnonymizedCopy('full');+ const resp = await anonymizationService.createAnonymizedCopy("full");if (resp.success) {console.log(`Anonymized file has been saved to: ${resp.anonymizedFilePath}`);@@ -15,8 +15,7 @@ sqlInit.dbReady.then(async () => {} else {console.log("Anonymization failed.");}- }- catch (e: any) {+ } catch (e: any) {console.error(e.message, e.stack);}diff --git a/src/app.ts b/src/app.tsindex a3943b7131..3977daf2e7 100644--- a/src/app.ts+++ b/src/app.ts@@ -16,8 +16,8 @@ import { startScheduledCleanup } from "./services/erase.js";import sql_init from "./services/sql_init.js";import { t } from "i18next";-await import('./services/handlers.js');-await import('./becca/becca_loader.js');+await import("./services/handlers.js");+await import("./becca/becca_loader.js");const app = express();@@ -27,8 +27,8 @@ const scriptDir = dirname(fileURLToPath(import.meta.url));sql_init.initializeDb();// view engine setup-app.set('views', path.join(scriptDir, 'views'));-app.set('view engine', 'ejs');+app.set("views", path.join(scriptDir, "views"));+app.set("view engine", "ejs");app.use((req, res, next) => {res.locals.t = t;@@ -39,21 +39,23 @@ if (!utils.isElectron()) {app.use(compression()); // HTTP compression}-app.use(helmet({- hidePoweredBy: false, // errors out in electron- contentSecurityPolicy: false,- crossOriginEmbedderPolicy: false-}));--app.use(express.text({ limit: '500mb' }));-app.use(express.json({ limit: '500mb' }));-app.use(express.raw({ limit: '500mb' }));+app.use(+ helmet({+ hidePoweredBy: false, // errors out in electron+ contentSecurityPolicy: false,+ crossOriginEmbedderPolicy: false+ })+);++app.use(express.text({ limit: "500mb" }));+app.use(express.json({ limit: "500mb" }));+app.use(express.raw({ limit: "500mb" }));app.use(express.urlencoded({ extended: false }));app.use(cookieParser());-app.use(express.static(path.join(scriptDir, 'public/root')));-app.use(`/manifest.webmanifest`, express.static(path.join(scriptDir, 'public/manifest.webmanifest')));-app.use(`/robots.txt`, express.static(path.join(scriptDir, 'public/robots.txt')));-app.use(`/icon.png`, express.static(path.join(scriptDir, 'public/icon.png')));+app.use(express.static(path.join(scriptDir, "public/root")));+app.use(`/manifest.webmanifest`, express.static(path.join(scriptDir, "public/manifest.webmanifest")));+app.use(`/robots.txt`, express.static(path.join(scriptDir, "public/robots.txt")));+app.use(`/icon.png`, express.static(path.join(scriptDir, "public/icon.png")));app.use(sessionParser);app.use(favicon(`${scriptDir}/../images/app-icons/icon.ico`));@@ -66,17 +68,17 @@ error_handlers.register(app);await import("./services/sync.js");// triggers backup timer-await import('./services/backup.js');+await import("./services/backup.js");// trigger consistency checks timer-await import('./services/consistency_checks.js');+await import("./services/consistency_checks.js");-await import('./services/scheduler.js');+await import("./services/scheduler.js");startScheduledCleanup();if (utils.isElectron()) {- (await import('@electron/remote/main/index.js')).initialize();+ (await import("@electron/remote/main/index.js")).initialize();}export default app;diff --git a/src/becca/becca-interface.ts b/src/becca/becca-interface.tsindex d4c0bf1b79..0a89899b01 100644--- a/src/becca/becca-interface.ts+++ b/src/becca/becca-interface.ts@@ -8,7 +8,7 @@ import BAttribute from "./entities/battribute.js";import BBranch from "./entities/bbranch.js";import BRevision from "./entities/brevision.js";import BAttachment from "./entities/battachment.js";-import { AttachmentRow, BlobRow, RevisionRow } from './entities/rows.js';+import { AttachmentRow, BlobRow, RevisionRow } from "./entities/rows.js";import BBlob from "./entities/bblob.js";import BRecentNote from "./entities/brecent_note.js";import AbstractBeccaEntity from "./entities/abstract_becca_entity.js";@@ -55,13 +55,13 @@ export default class Becca {}getRoot() {- return this.getNote('root');+ return this.getNote("root");}findAttributes(type: string, name: string): BAttribute[] {name = name.trim().toLowerCase();- if (name.startsWith('#') || name.startsWith('~')) {+ if (name.startsWith("#") || name.startsWith("~")) {name = name.substr(1);}@@ -177,8 +177,7 @@ export default class Becca {WHERE attachmentId = ? AND isDeleted = 0`: `SELECT * FROM attachments WHERE attachmentId = ? AND isDeleted = 0`;- return sql.getRows<AttachmentRow>(query, [attachmentId])- .map(row => new BAttachment(row))[0];+ return sql.getRows<AttachmentRow>(query, [attachmentId]).map((row) => new BAttachment(row))[0];}getAttachmentOrThrow(attachmentId: string, opts: AttachmentOpts = {}): BAttachment {@@ -190,8 +189,7 @@ export default class Becca {}getAttachments(attachmentIds: string[]): BAttachment[] {- return sql.getManyRows<AttachmentRow>("SELECT * FROM attachments WHERE attachmentId IN (???) AND isDeleted = 0", attachmentIds)- .map(row => new BAttachment(row));+ return sql.getManyRows<AttachmentRow>("SELECT * FROM attachments WHERE attachmentId IN (???) AND isDeleted = 0", attachmentIds).map((row) => new BAttachment(row));}getBlob(entity: { blobId?: string }): BBlob | null {@@ -220,18 +218,13 @@ export default class Becca {return null;}- if (entityName === 'revisions') {+ if (entityName === "revisions") {return this.getRevision(entityId);- } else if (entityName === 'attachments') {+ } else if (entityName === "attachments") {return this.getAttachment(entityId);}- const camelCaseEntityName = entityName.toLowerCase().replace(/(_[a-z])/g,- group =>- group- .toUpperCase()- .replace('_', '')- );+ const camelCaseEntityName = entityName.toLowerCase().replace(/(_[a-z])/g, (group) => group.toUpperCase().replace("_", ""));if (!(camelCaseEntityName in this)) {throw new Error(`Unknown entity name '${camelCaseEntityName}' (original argument '${entityName}')`);@@ -242,12 +235,12 @@ export default class Becca {getRecentNotesFromQuery(query: string, params: string[] = []): BRecentNote[] {const rows = sql.getRows<BRecentNote>(query, params);- return rows.map(row => new BRecentNote(row));+ return rows.map((row) => new BRecentNote(row));}getRevisionsFromQuery(query: string, params: string[] = []): BRevision[] {const rows = sql.getRows<RevisionRow>(query, params);- return rows.map(row => new BRevision(row));+ return rows.map((row) => new BRevision(row));}/** Should be called when the set of all non-skeleton notes changes (added/removed) */diff --git a/src/becca/becca_loader.ts b/src/becca/becca_loader.tsindex 8bdfd475e7..e48c4ed7b1 100644--- a/src/becca/becca_loader.ts+++ b/src/becca/becca_loader.ts@@ -11,7 +11,7 @@ import BOption from "./entities/boption.js";import BEtapiToken from "./entities/betapi_token.js";import cls from "../services/cls.js";import entityConstructor from "../becca/entity_constructor.js";-import { AttributeRow, BranchRow, EtapiTokenRow, NoteRow, OptionRow } from './entities/rows.js';+import { AttributeRow, BranchRow, EtapiTokenRow, NoteRow, OptionRow } from "./entities/rows.js";import AbstractBeccaEntity from "./entities/abstract_becca_entity.js";import ws from "../services/ws.js";@@ -119,13 +119,13 @@ eventService.subscribeBeccaLoader(eventService.ENTITY_CHANGED, ({ entityName, en* It should be therefore treated as a row.*/function postProcessEntityUpdate(entityName: string, entityRow: any) {- if (entityName === 'notes') {+ if (entityName === "notes") {noteUpdated(entityRow);- } else if (entityName === 'branches') {+ } else if (entityName === "branches") {branchUpdated(entityRow);- } else if (entityName === 'attributes') {+ } else if (entityName === "attributes") {attributeUpdated(entityRow);- } else if (entityName === 'note_reordering') {+ } else if (entityName === "note_reordering") {noteReorderingUpdated(entityRow);}}@@ -135,13 +135,13 @@ eventService.subscribeBeccaLoader([eventService.ENTITY_DELETED, eventService.ENTreturn;}- if (entityName === 'notes') {+ if (entityName === "notes") {noteDeleted(entityId);- } else if (entityName === 'branches') {+ } else if (entityName === "branches") {branchDeleted(entityId);- } else if (entityName === 'attributes') {+ } else if (entityName === "attributes") {attributeDeleted(entityId);- } else if (entityName === 'etapi_tokens') {+ } else if (entityName === "etapi_tokens") {etapiTokenDeleted(entityId);}});@@ -162,9 +162,8 @@ function branchDeleted(branchId: string) {const childNote = becca.notes[branch.noteId];if (childNote) {- childNote.parents = childNote.parents.filter(parent => parent.noteId !== branch.parentNoteId);- childNote.parentBranches = childNote.parentBranches- .filter(parentBranch => parentBranch.branchId !== branch.branchId);+ childNote.parents = childNote.parents.filter((parent) => parent.noteId !== branch.parentNoteId);+ childNote.parentBranches = childNote.parentBranches.filter((parentBranch) => parentBranch.branchId !== branch.branchId);if (childNote.parents.length > 0) {// subtree notes might lose some inherited attributes@@ -175,7 +174,7 @@ function branchDeleted(branchId: string) {const parentNote = becca.notes[branch.parentNoteId];if (parentNote) {- parentNote.children = parentNote.children.filter(child => child.noteId !== branch.noteId);+ parentNote.children = parentNote.children.filter((child) => child.noteId !== branch.noteId);}delete becca.childParentToBranch[`${branch.noteId}-${branch.parentNoteId}`];@@ -230,12 +229,12 @@ function attributeDeleted(attributeId: string) {note.invalidateThisCache();}- note.ownedAttributes = note.ownedAttributes.filter(attr => attr.attributeId !== attribute.attributeId);+ note.ownedAttributes = note.ownedAttributes.filter((attr) => attr.attributeId !== attribute.attributeId);const targetNote = attribute.targetNote;if (targetNote) {- targetNote.targetRelations = targetNote.targetRelations.filter(rel => rel.attributeId !== attribute.attributeId);+ targetNote.targetRelations = targetNote.targetRelations.filter((rel) => rel.attributeId !== attribute.attributeId);}}@@ -244,7 +243,7 @@ function attributeDeleted(attributeId: string) {const key = `${attribute.type}-${attribute.name.toLowerCase()}`;if (key in becca.attributeIndex) {- becca.attributeIndex[key] = becca.attributeIndex[key].filter(attr => attr.attributeId !== attribute.attributeId);+ becca.attributeIndex[key] = becca.attributeIndex[key].filter((attr) => attr.attributeId !== attribute.attributeId);}}@@ -282,8 +281,7 @@ function etapiTokenDeleted(etapiTokenId: string) {eventService.subscribeBeccaLoader(eventService.ENTER_PROTECTED_SESSION, () => {try {becca.decryptProtectedNotes();- }- catch (e: any) {+ } catch (e: any) {log.error(`Could not decrypt protected notes: ${e.message} ${e.stack}`);}});diff --git a/src/becca/becca_service.ts b/src/becca/becca_service.tsindex 46d41fdbf2..ab6838a780 100644--- a/src/becca/becca_service.ts+++ b/src/becca/becca_service.ts@@ -37,7 +37,7 @@ function getNoteTitle(childNoteId: string, parentNoteId?: string) {const branch = parentNote ? becca.getBranchFromChildAndParent(childNote.noteId, parentNote.noteId) : null;- return `${(branch && branch.prefix) ? `${branch.prefix} - ` : ''}${title}`;+ return `${branch && branch.prefix ? `${branch.prefix} - ` : ""}${title}`;}function getNoteTitleArrayForPath(notePathArray: string[]) {@@ -51,7 +51,7 @@ function getNoteTitleArrayForPath(notePathArray: string[]) {const titles = [];- let parentNoteId = 'root';+ let parentNoteId = "root";let hoistedNotePassed = false;// this is a notePath from outside of hoisted subtree, so the full title path needs to be returned@@ -79,7 +79,7 @@ function getNoteTitleArrayForPath(notePathArray: string[]) {function getNoteTitleForPath(notePathArray: string[]) {const titles = getNoteTitleArrayForPath(notePathArray);- return titles.join(' / ');+ return titles.join(" / ");}export default {diff --git a/src/becca/entities/abstract_becca_entity.ts b/src/becca/entities/abstract_becca_entity.tsindex f86eced670..f0e7b6edc6 100644--- a/src/becca/entities/abstract_becca_entity.ts+++ b/src/becca/entities/abstract_becca_entity.ts@@ -9,7 +9,7 @@ import cls from "../../services/cls.js";import log from "../../services/log.js";import protectedSessionService from "../../services/protected_session.js";import blobService from "../../services/blob.js";-import Becca, { ConstructorData } from '../becca-interface.js';+import Becca, { ConstructorData } from "../becca-interface.js";import becca from "../becca.js";interface ContentOpts {@@ -23,7 +23,6 @@ interface ContentOpts {* @type T the same entity type needed for self-reference in {@link ConstructorData}.*/abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {-utcDateModified?: string;dateCreated?: string;dateModified?: string;@@ -35,7 +34,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {blobId?: string;protected beforeSaving(opts?: {}) {- const constructorData = (this.constructor as unknown as ConstructorData<T>);+ const constructorData = this.constructor as unknown as ConstructorData<T>;if (!(this as any)[constructorData.primaryKeyName]) {(this as any)[constructorData.primaryKeyName] = utils.newEntityId();}@@ -50,19 +49,19 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {}protected putEntityChange(isDeleted: boolean) {- const constructorData = (this.constructor as unknown as ConstructorData<T>);+ const constructorData = this.constructor as unknown as ConstructorData<T>;entityChangesService.putEntityChange({entityName: constructorData.entityName,entityId: (this as any)[constructorData.primaryKeyName],hash: this.generateHash(isDeleted),isErased: false,utcDateChanged: this.getUtcDateChanged(),- isSynced: constructorData.entityName !== 'options' || !!this.isSynced+ isSynced: constructorData.entityName !== "options" || !!this.isSynced});}generateHash(isDeleted?: boolean): string {- const constructorData = (this.constructor as unknown as ConstructorData<T>);+ const constructorData = this.constructor as unknown as ConstructorData<T>;let contentToHash = "";for (const propertyName of constructorData.hashedProperties) {@@ -99,10 +98,10 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {}/**- * Saves entity - executes SQL, but doesn't commit the transaction on its own- */+ * Saves entity - executes SQL, but doesn't commit the transaction on its own+ */save(opts?: {}): this {- const constructorData = (this.constructor as unknown as ConstructorData<T>);+ const constructorData = this.constructor as unknown as ConstructorData<T>;const entityName = constructorData.entityName;const primaryKeyName = constructorData.primaryKeyName;@@ -115,7 +114,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {sql.transactional(() => {sql.upsert(entityName, primaryKeyName, pojo);- if (entityName === 'recent_notes') {+ if (entityName === "recent_notes") {return;}@@ -144,7 +143,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {opts.forceFrontendReload = !!opts.forceFrontendReload;if (content === null || content === undefined) {- const constructorData = (this.constructor as unknown as ConstructorData<T>);+ const constructorData = this.constructor as unknown as ConstructorData<T>;throw new Error(`Cannot set null content to ${constructorData.primaryKeyName} '${(this as any)[constructorData.primaryKeyName]}'`);}@@ -206,9 +205,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {if (this.isProtected) {// a "random" prefix makes sure that the calculated hash/blobId is different for a decrypted/encrypted contentconst encryptedPrefixSuffix = "t$[nvQg7q)&_ENCRYPTED_?M:Bf&j3jr_";- return Buffer.isBuffer(unencryptedContent)- ? Buffer.concat([Buffer.from(encryptedPrefixSuffix), unencryptedContent])- : `${encryptedPrefixSuffix}${unencryptedContent}`;+ return Buffer.isBuffer(unencryptedContent) ? Buffer.concat([Buffer.from(encryptedPrefixSuffix), unencryptedContent]) : `${encryptedPrefixSuffix}${unencryptedContent}`;} else {return unencryptedContent;}@@ -216,13 +213,13 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {private saveBlob(content: string | Buffer, unencryptedContentForHashCalculation: string | Buffer, opts: ContentOpts = {}) {/*- * We're using the unencrypted blob for the hash calculation, because otherwise the random IV would- * cause every content blob to be unique which would balloon the database size (esp. with revisioning).- * This has minor security implications (it's easy to infer that given content is shared between different- * notes/attachments), but the trade-off comes out clearly positive.- */+ * We're using the unencrypted blob for the hash calculation, because otherwise the random IV would+ * cause every content blob to be unique which would balloon the database size (esp. with revisioning).+ * This has minor security implications (it's easy to infer that given content is shared between different+ * notes/attachments), but the trade-off comes out clearly positive.+ */const newBlobId = utils.hashedBlobId(unencryptedContentForHashCalculation);- const blobNeedsInsert = !sql.getValue('SELECT 1 FROM blobs WHERE blobId = ?', [newBlobId]);+ const blobNeedsInsert = !sql.getValue("SELECT 1 FROM blobs WHERE blobId = ?", [newBlobId]);if (!blobNeedsInsert) {return newBlobId;@@ -242,7 +239,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {const hash = blobService.calculateContentHash(pojo);entityChangesService.putEntityChange({- entityName: 'blobs',+ entityName: "blobs",entityId: newBlobId,hash: hash,isErased: false,@@ -254,7 +251,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {});eventService.emit(eventService.ENTITY_CHANGED, {- entityName: 'blobs',+ entityName: "blobs",entity: this});@@ -265,7 +262,7 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {const row = sql.getRow<{ content: string | Buffer }>(`SELECT content FROM blobs WHERE blobId = ?`, [this.blobId]);if (!row) {- const constructorData = (this.constructor as unknown as ConstructorData<T>);+ const constructorData = this.constructor as unknown as ConstructorData<T>;throw new Error(`Cannot find content for ${constructorData.primaryKeyName} '${(this as any)[constructorData.primaryKeyName]}', blobId '${this.blobId}'`);}@@ -273,26 +270,27 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {}/**- * Mark the entity as (soft) deleted. It will be completely erased later.- *- * This is a low-level method, for notes and branches use `note.deleteNote()` and 'branch.deleteBranch()` instead.- */+ * Mark the entity as (soft) deleted. It will be completely erased later.+ *+ * This is a low-level method, for notes and branches use `note.deleteNote()` and 'branch.deleteBranch()` instead.+ */markAsDeleted(deleteId: string | null = null) {- const constructorData = (this.constructor as unknown as ConstructorData<T>);+ const constructorData = this.constructor as unknown as ConstructorData<T>;const entityId = (this as any)[constructorData.primaryKeyName];const entityName = constructorData.entityName;this.utcDateModified = dateUtils.utcNowDateTime();- sql.execute(`UPDATE ${entityName} SET isDeleted = 1, deleteId = ?, utcDateModified = ?+ sql.execute(+ `UPDATE ${entityName} SET isDeleted = 1, deleteId = ?, utcDateModified = ?WHERE ${constructorData.primaryKeyName} = ?`,- [deleteId, this.utcDateModified, entityId]);+ [deleteId, this.utcDateModified, entityId]+ );if (this.dateModified) {this.dateModified = dateUtils.localNowDateTime();- sql.execute(`UPDATE ${entityName} SET dateModified = ? WHERE ${constructorData.primaryKeyName} = ?`,- [this.dateModified, entityId]);+ sql.execute(`UPDATE ${entityName} SET dateModified = ? WHERE ${constructorData.primaryKeyName} = ?`, [this.dateModified, entityId]);}log.info(`Marking ${entityName} ${entityId} as deleted`);@@ -303,15 +301,17 @@ abstract class AbstractBeccaEntity<T extends AbstractBeccaEntity<T>> {}markAsDeletedSimple() {- const constructorData = (this.constructor as unknown as ConstructorData<T>);+ const constructorData = this.constructor as unknown as ConstructorData<T>;const entityId = (this as any)[constructorData.primaryKeyName];const entityName = constructorData.entityName;this.utcDateModified = dateUtils.utcNowDateTime();- sql.execute(`UPDATE ${entityName} SET isDeleted = 1, utcDateModified = ?+ sql.execute(+ `UPDATE ${entityName} SET isDeleted = 1, utcDateModified = ?WHERE ${constructorData.primaryKeyName} = ?`,- [this.utcDateModified, entityId]);+ [this.utcDateModified, entityId]+ );log.info(`Marking ${entityName} ${entityId} as deleted`);diff --git a/src/becca/entities/battachment.ts b/src/becca/entities/battachment.tsindex b265995989..b88b1df2cb 100644--- a/src/becca/entities/battachment.ts+++ b/src/becca/entities/battachment.ts@@ -6,14 +6,14 @@ import AbstractBeccaEntity from "./abstract_becca_entity.js";import sql from "../../services/sql.js";import protectedSessionService from "../../services/protected_session.js";import log from "../../services/log.js";-import { AttachmentRow } from './rows.js';+import { AttachmentRow } from "./rows.js";import BNote from "./bnote.js";import BBranch from "./bbranch.js";import noteService from "../../services/notes.js";const attachmentRoleToNoteTypeMapping = {- 'image': 'image',- 'file': 'file'+ image: "image",+ file: "file"};interface ContentOpts {@@ -31,9 +31,15 @@ interface ContentOpts {* larger amounts of data and generally not accessible to the user.*/class BAttachment extends AbstractBeccaEntity<BAttachment> {- static get entityName() { return "attachments"; }- static get primaryKeyName() { return "attachmentId"; }- static get hashedProperties() { return ["attachmentId", "ownerId", "role", "mime", "title", "blobId", "utcDateScheduledForErasureSince"]; }+ static get entityName() {+ return "attachments";+ }+ static get primaryKeyName() {+ return "attachmentId";+ }+ static get hashedProperties() {+ return ["attachmentId", "ownerId", "role", "mime", "title", "blobId", "utcDateScheduledForErasureSince"];+ }noteId?: number;attachmentId?: string;@@ -102,13 +108,15 @@ class BAttachment extends AbstractBeccaEntity<BAttachment> {}isContentAvailable() {- return !this.attachmentId // new attachment which was not encrypted yet- || !this.isProtected- || protectedSessionService.isProtectedSessionAvailable()+ return (+ !this.attachmentId || // new attachment which was not encrypted yet+ !this.isProtected ||+ protectedSessionService.isProtectedSessionAvailable()+ );}getTitleOrProtected() {- return this.isContentAvailable() ? this.title : '[protected]';+ return this.isContentAvailable() ? this.title : "[protected]";}decrypt() {@@ -121,8 +129,7 @@ class BAttachment extends AbstractBeccaEntity<BAttachment> {try {this.title = protectedSessionService.decryptString(this.title) || "";this.isDecrypted = true;- }- catch (e: any) {+ } catch (e: any) {log.error(`Could not decrypt attachment ${this.attachmentId}: ${e.message} ${e.stack}`);}}@@ -136,22 +143,22 @@ class BAttachment extends AbstractBeccaEntity<BAttachment> {this._setContent(content, opts);}- convertToNote(): { note: BNote, branch: BBranch } {+ convertToNote(): { note: BNote; branch: BBranch } {// TODO: can this ever be "search"?- if (this.type as string === 'search') {+ if ((this.type as string) === "search") {throw new Error(`Note of type search cannot have child notes`);}if (!this.getNote()) {- throw new Error("Cannot find note of this attachment. It is possible that this is note revision's attachment. " +- "Converting note revision's attachments to note is not (yet) supported.");+ throw new Error("Cannot find note of this attachment. It is possible that this is note revision's attachment. " + "Converting note revision's attachments to note is not (yet) supported.");}if (!(this.role in attachmentRoleToNoteTypeMapping)) {throw new Error(`Mapping from attachment role '${this.role}' to note's type is not defined`);}- if (!this.isContentAvailable()) { // isProtected is the same for attachment+ if (!this.isContentAvailable()) {+ // isProtected is the same for attachmentthrow new Error(`Cannot convert protected attachment outside of protected session`);}@@ -168,7 +175,7 @@ class BAttachment extends AbstractBeccaEntity<BAttachment> {const parentNote = this.getNote();- if (this.role === 'image' && parentNote.type === 'text') {+ if (this.role === "image" && parentNote.type === "text") {const origContent = parentNote.getContent();if (typeof origContent !== "string") {@@ -191,7 +198,7 @@ class BAttachment extends AbstractBeccaEntity<BAttachment> {}getFileName() {- const type = this.role === 'image' ? 'image' : 'file';+ const type = this.role === "image" ? "image" : "file";return utils.formatDownloadTitle(this.title, type, this.mime);}@@ -200,9 +207,14 @@ class BAttachment extends AbstractBeccaEntity<BAttachment> {super.beforeSaving();if (this.position === undefined || this.position === null) {- this.position = 10 + sql.getValue<number>(`SELECT COALESCE(MAX(position), 0)+ this.position =+ 10 ++ sql.getValue<number>(+ `SELECT COALESCE(MAX(position), 0)FROM attachments- WHERE ownerId = ?`, [this.noteId]);+ WHERE ownerId = ?`,+ [this.noteId]+ );}this.dateModified = dateUtils.localNowDateTime();@@ -234,8 +246,7 @@ class BAttachment extends AbstractBeccaEntity<BAttachment> {if (pojo.isProtected) {if (this.isDecrypted) {pojo.title = protectedSessionService.encrypt(pojo.title || "") || undefined;- }- else {+ } else {// updating protected note outside of protected session means we will keep original ciphertextsdelete pojo.title;}diff --git a/src/becca/entities/battribute.ts b/src/becca/entities/battribute.tsindex 66ef83ca85..746f493a1e 100644--- a/src/becca/entities/battribute.ts+++ b/src/becca/entities/battribute.ts@@ -5,7 +5,7 @@ import AbstractBeccaEntity from "./abstract_becca_entity.js";import dateUtils from "../../services/date_utils.js";import promotedAttributeDefinitionParser from "../../services/promoted_attribute_definition_parser.js";import sanitizeAttributeName from "../../services/sanitize_attribute_name.js";-import { AttributeRow, AttributeType } from './rows.js';+import { AttributeRow, AttributeType } from "./rows.js";interface SavingOpts {skipValidation?: boolean;@@ -16,9 +16,15 @@ interface SavingOpts {* and relation (representing named relationship between source and target note)*/class BAttribute extends AbstractBeccaEntity<BAttribute> {- static get entityName() { return "attributes"; }- static get primaryKeyName() { return "attributeId"; }- static get hashedProperties() { return ["attributeId", "noteId", "type", "name", "value", "isInheritable"]; }+ static get entityName() {+ return "attributes";+ }+ static get primaryKeyName() {+ return "attributeId";+ }+ static get hashedProperties() {+ return ["attributeId", "noteId", "type", "name", "value", "isInheritable"];+ }attributeId!: string;noteId!: string;@@ -40,16 +46,7 @@ class BAttribute extends AbstractBeccaEntity<BAttribute> {}updateFromRow(row: AttributeRow) {- this.update([- row.attributeId,- row.noteId,- row.type,- row.name,- row.value,- row.isInheritable,- row.position,- row.utcDateModified- ]);+ this.update([row.attributeId, row.noteId, row.type, row.name, row.value, row.isInheritable, row.position, row.utcDateModified]);}update([attributeId, noteId, type, name, value, isInheritable, position, utcDateModified]: any) {@@ -72,7 +69,7 @@ class BAttribute extends AbstractBeccaEntity<BAttribute> {if (!(this.noteId in this.becca.notes)) {// entities can come out of order in sync, create skeleton which will be filled later- this.becca.addNote(this.noteId, new BNote({noteId: this.noteId}));+ this.becca.addNote(this.noteId, new BNote({ noteId: this.noteId }));}this.becca.notes[this.noteId].ownedAttributes.push(this);@@ -97,22 +94,22 @@ class BAttribute extends AbstractBeccaEntity<BAttribute> {throw new Error(`Invalid empty name in attribute '${this.attributeId}' of note '${this.noteId}'`);}- if (this.type === 'relation' && !(this.value in this.becca.notes)) {+ if (this.type === "relation" && !(this.value in this.becca.notes)) {throw new Error(`Cannot save relation '${this.name}' of note '${this.noteId}' since it targets not existing note '${this.value}'.`);}}get isAffectingSubtree() {- return this.isInheritable- || (this.type === 'relation' && ['template', 'inherit'].includes(this.name));+ return this.isInheritable || (this.type === "relation" && ["template", "inherit"].includes(this.name));}- get targetNoteId() { // alias- return this.type === 'relation' ? this.value : undefined;+ get targetNoteId() {+ // alias+ return this.type === "relation" ? this.value : undefined;}isAutoLink() {- return this.type === 'relation' && ['internalLink', 'imageLink', 'relationMapLink', 'includeNoteLink'].includes(this.name);+ return this.type === "relation" && ["internalLink", "imageLink", "relationMapLink", "includeNoteLink"].includes(this.name);}get note() {@@ -120,7 +117,7 @@ class BAttribute extends AbstractBeccaEntity<BAttribute> {}get targetNote() {- if (this.type === 'relation') {+ if (this.type === "relation") {return this.becca.notes[this.value];}}@@ -136,7 +133,7 @@ class BAttribute extends AbstractBeccaEntity<BAttribute> {}getTargetNote() {- if (this.type !== 'relation') {+ if (this.type !== "relation") {throw new Error(`Attribute '${this.attributeId}' is not a relation.`);}@@ -148,7 +145,7 @@ class BAttribute extends AbstractBeccaEntity<BAttribute> {}isDefinition() {- return this.type === 'label' && (this.name.startsWith('label:') || this.name.startsWith('relation:'));+ return this.type === "label" && (this.name.startsWith("label:") || this.name.startsWith("relation:"));}getDefinition() {@@ -156,9 +153,9 @@ class BAttribute extends AbstractBeccaEntity<BAttribute> {}getDefinedName() {- if (this.type === 'label' && this.name.startsWith('label:')) {+ if (this.type === "label" && this.name.startsWith("label:")) {return this.name.substr(6);- } else if (this.type === 'label' && this.name.startsWith('relation:')) {+ } else if (this.type === "label" && this.name.startsWith("relation:")) {return this.name.substr(9);} else {return this.name;@@ -182,7 +179,8 @@ class BAttribute extends AbstractBeccaEntity<BAttribute> {}if (this.position === undefined || this.position === null) {- const maxExistingPosition = this.getNote().getAttributes()+ const maxExistingPosition = this.getNote()+ .getAttributes().reduce((maxPosition, attr) => Math.max(maxPosition, attr.position || 0), 0);this.position = maxExistingPosition + 10;diff --git a/src/becca/entities/bblob.ts b/src/becca/entities/bblob.tsindex 7ce94eb2e0..f724535789 100644--- a/src/becca/entities/bblob.ts+++ b/src/becca/entities/bblob.ts@@ -3,9 +3,15 @@ import { BlobRow } from "./rows.js";// TODO: Why this does not extend the abstract becca?class BBlob extends AbstractBeccaEntity<BBlob> {- static get entityName() { return "blobs"; }- static get primaryKeyName() { return "blobId"; }- static get hashedProperties() { return ["blobId", "content"]; }+ static get entityName() {+ return "blobs";+ }+ static get primaryKeyName() {+ return "blobId";+ }+ static get hashedProperties() {+ return ["blobId", "content"];+ }content!: string | Buffer;contentLength!: number;diff --git a/src/becca/entities/bbranch.ts b/src/becca/entities/bbranch.tsindex 674136c735..443cbfd15f 100644--- a/src/becca/entities/bbranch.ts+++ b/src/becca/entities/bbranch.ts@@ -7,7 +7,7 @@ import utils from "../../services/utils.js";import TaskContext from "../../services/task_context.js";import cls from "../../services/cls.js";import log from "../../services/log.js";-import { BranchRow } from './rows.js';+import { BranchRow } from "./rows.js";import handlers from "../../services/handlers.js";/**@@ -18,10 +18,16 @@ import handlers from "../../services/handlers.js";* Always check noteId instead.*/class BBranch extends AbstractBeccaEntity<BBranch> {- static get entityName() { return "branches"; }- static get primaryKeyName() { return "branchId"; }+ static get entityName() {+ return "branches";+ }+ static get primaryKeyName() {+ return "branchId";+ }// notePosition is not part of hash because it would produce a lot of updates in case of reordering- static get hashedProperties() { return ["branchId", "noteId", "parentNoteId", "prefix"]; }+ static get hashedProperties() {+ return ["branchId", "noteId", "parentNoteId", "prefix"];+ }branchId?: string;noteId!: string;@@ -42,15 +48,7 @@ class BBranch extends AbstractBeccaEntity<BBranch> {}updateFromRow(row: BranchRow) {- this.update([- row.branchId,- row.noteId,- row.parentNoteId,- row.prefix,- row.notePosition,- row.isExpanded,- row.utcDateModified- ]);+ this.update([row.branchId, row.noteId, row.parentNoteId, row.prefix, row.notePosition, row.isExpanded, row.utcDateModified]);}update([branchId, noteId, parentNoteId, prefix, notePosition, isExpanded, utcDateModified]: any) {@@ -78,7 +76,7 @@ class BBranch extends AbstractBeccaEntity<BBranch> {childNote.parentBranches.push(this);}- if (this.noteId === 'root') {+ if (this.noteId === "root") {return;}@@ -97,7 +95,7 @@ class BBranch extends AbstractBeccaEntity<BBranch> {get childNote(): BNote {if (!(this.noteId in this.becca.notes)) {// entities can come out of order in sync/import, create skeleton which will be filled later- this.becca.addNote(this.noteId, new BNote({noteId: this.noteId}));+ this.becca.addNote(this.noteId, new BNote({ noteId: this.noteId }));}return this.becca.notes[this.noteId];@@ -109,43 +107,43 @@ class BBranch extends AbstractBeccaEntity<BBranch> {/** @returns root branch will have undefined parent, all other branches have to have a parent note */get parentNote(): BNote | undefined {- if (!(this.parentNoteId in this.becca.notes) && this.parentNoteId !== 'none') {+ if (!(this.parentNoteId in this.becca.notes) && this.parentNoteId !== "none") {// entities can come out of order in sync/import, create skeleton which will be filled later- this.becca.addNote(this.parentNoteId, new BNote({noteId: this.parentNoteId}));+ this.becca.addNote(this.parentNoteId, new BNote({ noteId: this.parentNoteId }));}return this.becca.notes[this.parentNoteId];}get isDeleted() {- return (this.branchId == undefined || !(this.branchId in this.becca.branches));+ return this.branchId == undefined || !(this.branchId in this.becca.branches);}/**- * Branch is weak when its existence should not hinder deletion of its note.- * As a result, note with only weak branches should be immediately deleted.- * An example is shared or bookmarked clones - they are created automatically and exist for technical reasons,- * not as user-intended actions. From user perspective, they don't count as real clones and for the purpose- * of deletion should not act as a clone.- */+ * Branch is weak when its existence should not hinder deletion of its note.+ * As a result, note with only weak branches should be immediately deleted.+ * An example is shared or bookmarked clones - they are created automatically and exist for technical reasons,+ * not as user-intended actions. From user perspective, they don't count as real clones and for the purpose+ * of deletion should not act as a clone.+ */get isWeak() {- return ['_share', '_lbBookmarks'].includes(this.parentNoteId);+ return ["_share", "_lbBookmarks"].includes(this.parentNoteId);}/**- * Delete a branch. If this is a last note's branch, delete the note as well.- *- * @param deleteId - optional delete identified- *- * @returns true if note has been deleted, false otherwise- */+ * Delete a branch. If this is a last note's branch, delete the note as well.+ *+ * @param deleteId - optional delete identified+ *+ * @returns true if note has been deleted, false otherwise+ */deleteBranch(deleteId?: string, taskContext?: TaskContext): boolean {if (!deleteId) {deleteId = utils.randomString(10);}if (!taskContext) {- taskContext = new TaskContext('no-progress-reporting');+ taskContext = new TaskContext("no-progress-reporting");}taskContext.increaseProgressCount();@@ -157,13 +155,11 @@ class BBranch extends AbstractBeccaEntity<BBranch> {if (parentBranches.length === 1 && parentBranches[0] === this) {// needs to be run before branches and attributes are deleted and thus attached relations disappear- handlers.runAttachedRelations(note, 'runOnNoteDeletion', note);+ handlers.runAttachedRelations(note, "runOnNoteDeletion", note);}}- if (this.noteId === 'root'- || this.noteId === cls.getHoistedNoteId()) {-+ if (this.noteId === "root" || this.noteId === cls.getHoistedNoteId()) {throw new Error("Can't delete root or hoisted branch/note");}@@ -203,8 +199,7 @@ class BBranch extends AbstractBeccaEntity<BBranch> {note.markAsDeleted(deleteId);return true;- }- else {+ } else {return false;}}@@ -225,8 +220,9 @@ class BBranch extends AbstractBeccaEntity<BBranch> {continue;}- if (maxNotePos < childBranch.notePosition- && childBranch.noteId !== '_hidden' // hidden has a very large notePosition to always stay last+ if (+ maxNotePos < childBranch.notePosition &&+ childBranch.noteId !== "_hidden" // hidden has a very large notePosition to always stay last) {maxNotePos = childBranch.notePosition;}diff --git a/src/becca/entities/betapi_token.ts b/src/becca/entities/betapi_token.tsindex bfd4383e3e..d315029a2a 100644--- a/src/becca/entities/betapi_token.ts+++ b/src/becca/entities/betapi_token.ts@@ -15,9 +15,15 @@ import AbstractBeccaEntity from "./abstract_becca_entity.js";* from tokenHash and token.*/class BEtapiToken extends AbstractBeccaEntity<BEtapiToken> {- static get entityName() { return "etapi_tokens"; }- static get primaryKeyName() { return "etapiTokenId"; }- static get hashedProperties() { return ["etapiTokenId", "name", "tokenHash", "utcDateCreated", "utcDateModified", "isDeleted"]; }+ static get entityName() {+ return "etapi_tokens";+ }+ static get primaryKeyName() {+ return "etapiTokenId";+ }+ static get hashedProperties() {+ return ["etapiTokenId", "name", "tokenHash", "utcDateCreated", "utcDateModified", "isDeleted"];+ }etapiTokenId?: string;name!: string;@@ -66,7 +72,7 @@ class BEtapiToken extends AbstractBeccaEntity<BEtapiToken> {utcDateCreated: this.utcDateCreated,utcDateModified: this.utcDateModified,isDeleted: this.isDeleted- }+ };}beforeSaving() {diff --git a/src/becca/entities/bnote.ts b/src/becca/entities/bnote.tsindex 44d0686a65..b8aa696144 100644--- a/src/becca/entities/bnote.ts+++ b/src/becca/entities/bnote.ts@@ -14,18 +14,18 @@ import TaskContext from "../../services/task_context.js";import dayjs from "dayjs";import utc from "dayjs/plugin/utc.js";import eventService from "../../services/events.js";-import { AttachmentRow, AttributeType, NoteRow, NoteType, RevisionRow } from './rows.js';+import { AttachmentRow, AttributeType, NoteRow, NoteType, RevisionRow } from "./rows.js";import BBranch from "./bbranch.js";import BAttribute from "./battribute.js";-import { NotePojo } from '../becca-interface.js';+import { NotePojo } from "../becca-interface.js";import searchService from "../../services/search/services/search.js";import cloningService, { CloneResponse } from "../../services/cloning.js";import noteService from "../../services/notes.js";import handlers from "../../services/handlers.js";dayjs.extend(utc);-const LABEL = 'label';-const RELATION = 'relation';+const LABEL = "label";+const RELATION = "relation";interface NotePathRecord {isArchived: boolean;@@ -47,7 +47,7 @@ interface AttachmentOpts {interface Relationship {parentNoteId: string;- childNoteId: string+ childNoteId: string;}interface ConvertOpts {@@ -59,9 +59,15 @@ interface ConvertOpts {* Trilium's main entity, which can represent text note, image, code note, file attachment etc.*/class BNote extends AbstractBeccaEntity<BNote> {- static get entityName() { return "notes"; }- static get primaryKeyName() { return "noteId"; }- static get hashedProperties() { return ["noteId", "title", "isProtected", "type", "mime", "blobId"]; }+ static get entityName() {+ return "notes";+ }+ static get primaryKeyName() {+ return "noteId";+ }+ static get hashedProperties() {+ return ["noteId", "title", "isProtected", "type", "mime", "blobId"];+ }noteId!: string;title!: string;@@ -105,18 +111,7 @@ class BNote extends AbstractBeccaEntity<BNote> {}updateFromRow(row: Partial<NoteRow>) {- this.update([- row.noteId,- row.title,- row.type,- row.mime,- row.isProtected,- row.blobId,- row.dateCreated,- row.dateModified,- row.utcDateCreated,- row.utcDateModified- ]);+ this.update([row.noteId, row.title, row.type, row.mime, row.isProtected, row.blobId, row.dateCreated, row.dateModified, row.utcDateCreated, row.utcDateModified]);}update([noteId, title, type, mime, isProtected, blobId, dateCreated, dateModified, utcDateCreated, utcDateModified]: any) {@@ -164,13 +159,15 @@ class BNote extends AbstractBeccaEntity<BNote> {}isContentAvailable() {- return !this.noteId // new note which was not encrypted yet- || !this.isProtected- || protectedSessionService.isProtectedSessionAvailable()+ return (+ !this.noteId || // new note which was not encrypted yet+ !this.isProtected ||+ protectedSessionService.isProtectedSessionAvailable()+ );}getTitleOrProtected() {- return this.isContentAvailable() ? this.title : '[protected]';+ return this.isContentAvailable() ? this.title : "[protected]";}getParentBranches() {@@ -178,15 +175,15 @@ class BNote extends AbstractBeccaEntity<BNote> {}/**- * Returns <i>strong</i> (as opposed to <i>weak</i>) parent branches. See isWeak for details.- */+ * Returns <i>strong</i> (as opposed to <i>weak</i>) parent branches. See isWeak for details.+ */getStrongParentBranches() {- return this.getParentBranches().filter(branch => !branch.isWeak);+ return this.getParentBranches().filter((branch) => !branch.isWeak);}/**- * @deprecated use getParentBranches() instead- */+ * @deprecated use getParentBranches() instead+ */getBranches() {return this.parentBranches;}@@ -204,25 +201,24 @@ class BNote extends AbstractBeccaEntity<BNote> {}getChildBranches(): BBranch[] {- return this.children- .map(childNote => this.becca.getBranchFromChildAndParent(childNote.noteId, this.noteId)) as BBranch[];+ return this.children.map((childNote) => this.becca.getBranchFromChildAndParent(childNote.noteId, this.noteId)) as BBranch[];}/**- * Note content has quite special handling - it's not a separate entity, but a lazily loaded- * part of Note entity with its own sync. Reasons behind this hybrid design has been:- *- * - content can be quite large, and it's not necessary to load it / fill memory for any note access even if we don't need a content, especially for bulk operations like search- * - changes in the note metadata or title should not trigger note content sync (so we keep separate utcDateModified and entity changes records)- * - but to the user note content and title changes are one and the same - single dateModified (so all changes must go through Note and content is not a separate entity)- */+ * Note content has quite special handling - it's not a separate entity, but a lazily loaded+ * part of Note entity with its own sync. Reasons behind this hybrid design has been:+ *+ * - content can be quite large, and it's not necessary to load it / fill memory for any note access even if we don't need a content, especially for bulk operations like search+ * - changes in the note metadata or title should not trigger note content sync (so we keep separate utcDateModified and entity changes records)+ * - but to the user note content and title changes are one and the same - single dateModified (so all changes must go through Note and content is not a separate entity)+ */getContent() {return this._getContent();}/**- * @throws Error in case of invalid JSON- */+ * @throws Error in case of invalid JSON+ */getJsonContent(): any | null {const content = this.getContent();@@ -237,8 +233,7 @@ class BNote extends AbstractBeccaEntity<BNote> {getJsonContentSafely() {try {return this.getJsonContent();- }- catch (e) {+ } catch (e) {return null;}}@@ -250,7 +245,7 @@ class BNote extends AbstractBeccaEntity<BNote> {}setJsonContent(content: {}) {- this.setContent(JSON.stringify(content, null, '\t'));+ this.setContent(JSON.stringify(content, null, "\t"));}get dateCreatedObj() {@@ -271,7 +266,7 @@ class BNote extends AbstractBeccaEntity<BNote> {/** @returns true if this note is the root of the note tree. Root note has "root" noteId */isRoot() {- return this.noteId === 'root';+ return this.noteId === "root";}/** @returns true if this note is of application/json content type */@@ -281,22 +276,20 @@ class BNote extends AbstractBeccaEntity<BNote> {/** @returns true if this note is JavaScript (code or attachment) */isJavaScript() {- return (this.type === "code" || this.type === "file" || this.type === 'launcher')- && (this.mime.startsWith("application/javascript")- || this.mime === "application/x-javascript"- || this.mime === "text/javascript");+ return (+ (this.type === "code" || this.type === "file" || this.type === "launcher") &&+ (this.mime.startsWith("application/javascript") || this.mime === "application/x-javascript" || this.mime === "text/javascript")+ );}/** @returns true if this note is HTML */isHtml() {- return ["code", "file", "render"].includes(this.type)- && this.mime === "text/html";+ return ["code", "file", "render"].includes(this.type) && this.mime === "text/html";}/** @returns true if this note is an image */isImage() {- return this.type === 'image'- || (this.type === 'file' && this.mime?.startsWith('image/'));+ return this.type === "image" || (this.type === "file" && this.mime?.startsWith("image/"));}/** @deprecated use hasStringContent() instead */@@ -311,15 +304,15 @@ class BNote extends AbstractBeccaEntity<BNote> {/** @returns JS script environment - either "frontend" or "backend" */getScriptEnv() {- if (this.isHtml() || (this.isJavaScript() && this.mime.endsWith('env=frontend'))) {+ if (this.isHtml() || (this.isJavaScript() && this.mime.endsWith("env=frontend"))) {return "frontend";}- if (this.type === 'render') {+ if (this.type === "render") {return "frontend";}- if (this.isJavaScript() && this.mime.endsWith('env=backend')) {+ if (this.isJavaScript() && this.mime.endsWith("env=backend")) {return "backend";}@@ -327,13 +320,13 @@ class BNote extends AbstractBeccaEntity<BNote> {}/**- * Beware that the method must not create a copy of the array, but actually returns its internal array- * (for performance reasons)- *- * @param type - (optional) attribute type to filter- * @param name - (optional) attribute name to filter- * @returns all note's attributes, including inherited ones- */+ * Beware that the method must not create a copy of the array, but actually returns its internal array+ * (for performance reasons)+ *+ * @param type - (optional) attribute type to filter+ * @param name - (optional) attribute name to filter+ * @returns all note's attributes, including inherited ones+ */getAttributes(type?: string, name?: string): BAttribute[] {this.__validateTypeName(type, name);this.__ensureAttributeCacheIsAvailable();@@ -343,15 +336,12 @@ class BNote extends AbstractBeccaEntity<BNote> {}if (type && name) {- return this.__attributeCache.filter(attr => attr.name === name && attr.type === type);- }- else if (type) {- return this.__attributeCache.filter(attr => attr.type === type);- }- else if (name) {- return this.__attributeCache.filter(attr => attr.name === name);- }- else {+ return this.__attributeCache.filter((attr) => attr.name === name && attr.type === type);+ } else if (type) {+ return this.__attributeCache.filter((attr) => attr.type === type);+ } else if (name) {+ return this.__attributeCache.filter((attr) => attr.name === name);+ } else {return this.__attributeCache;}}@@ -372,7 +362,7 @@ class BNote extends AbstractBeccaEntity<BNote> {const newPath = [...path, this.noteId];// inheritable attrs on root are typically not intended to be applied to hidden subtree #3537- if (this.noteId !== 'root' && this.noteId !== '_hidden') {+ if (this.noteId !== "root" && this.noteId !== "_hidden") {for (const parentNote of this.parents) {parentAttributes.push(...parentNote.__getInheritableAttributes(newPath));}@@ -380,15 +370,17 @@ class BNote extends AbstractBeccaEntity<BNote> {const templateAttributes = [];- for (const ownedAttr of parentAttributes) { // parentAttributes so we process also inherited templates- if (ownedAttr.type === 'relation' && ['template', 'inherit'].includes(ownedAttr.name)) {+ for (const ownedAttr of parentAttributes) {+ // parentAttributes so we process also inherited templates+ if (ownedAttr.type === "relation" && ["template", "inherit"].includes(ownedAttr.name)) {const templateNote = this.becca.notes[ownedAttr.value];if (templateNote) {templateAttributes.push(- ...templateNote.__getAttributes(newPath)+ ...templateNote+ .__getAttributes(newPath)// template attr is used as a marker for templates, but it's not meant to be inherited- .filter(attr => !(attr.type === 'label' && (attr.name === 'template' || attr.name === 'workspacetemplate')))+ .filter((attr) => !(attr.type === "label" && (attr.name === "template" || attr.name === "workspacetemplate"))));}}@@ -431,55 +423,48 @@ class BNote extends AbstractBeccaEntity<BNote> {}__validateTypeName(type?: string | null, name?: string | null) {- if (type && type !== 'label' && type !== 'relation') {+ if (type && type !== "label" && type !== "relation") {throw new Error(`Unrecognized attribute type '${type}'. Only 'label' and 'relation' are possible values.`);}if (name) {const firstLetter = name.charAt(0);- if (firstLetter === '#' || firstLetter === '~') {+ if (firstLetter === "#" || firstLetter === "~") {throw new Error(`Detect '#' or '~' in the attribute's name. In the API, attribute names should be set without these characters.`);}}}hasAttribute(type: string, name: string, value: string | null = null): boolean {- return !!this.getAttributes().find(attr =>- attr.name === name- && (value === undefined || value === null || attr.value === value)- && attr.type === type- );+ return !!this.getAttributes().find((attr) => attr.name === name && (value === undefined || value === null || attr.value === value) && attr.type === type);}getAttributeCaseInsensitive(type: string, name: string, value?: string | null) {name = name.toLowerCase();value = value ? value.toLowerCase() : null;- return this.getAttributes().find(- attr => attr.name.toLowerCase() === name- && (!value || attr.value.toLowerCase() === value)- && attr.type === type);+ return this.getAttributes().find((attr) => attr.name.toLowerCase() === name && (!value || attr.value.toLowerCase() === value) && attr.type === type);}getRelationTarget(name: string) {- const relation = this.getAttributes().find(attr => attr.name === name && attr.type === 'relation');+ const relation = this.getAttributes().find((attr) => attr.name === name && attr.type === "relation");return relation ? relation.targetNote : null;}/**- * @param name - label name- * @param value - label value- * @returns true if label exists (including inherited)- */+ * @param name - label name+ * @param value - label value+ * @returns true if label exists (including inherited)+ */hasLabel(name: string, value?: string): boolean {return this.hasAttribute(LABEL, name, value);}/**- * @param name - label name- * @returns true if label exists (including inherited) and does not have "false" value.- */+ * @param name - label name+ * @returns true if label exists (including inherited) and does not have "false" value.+ */isLabelTruthy(name: string): boolean {const label = this.getLabel(name);@@ -487,127 +472,127 @@ class BNote extends AbstractBeccaEntity<BNote> {return false;}- return label && label.value !== 'false';+ return label && label.value !== "false";}/**- * @param name - label name- * @param value - label value- * @returns true if label exists (excluding inherited)- */+ * @param name - label name+ * @param value - label value+ * @returns true if label exists (excluding inherited)+ */hasOwnedLabel(name: string, value?: string): boolean {return this.hasOwnedAttribute(LABEL, name, value);}/**- * @param name - relation name- * @param value - relation value- * @returns true if relation exists (including inherited)- */+ * @param name - relation name+ * @param value - relation value+ * @returns true if relation exists (including inherited)+ */hasRelation(name: string, value?: string): boolean {return this.hasAttribute(RELATION, name, value);}/**- * @param name - relation name- * @param value - relation value- * @returns true if relation exists (excluding inherited)- */+ * @param name - relation name+ * @param value - relation value+ * @returns true if relation exists (excluding inherited)+ */hasOwnedRelation(name: string, value?: string): boolean {return this.hasOwnedAttribute(RELATION, name, value);}/**- * @param name - label name- * @returns label if it exists, null otherwise- */+ * @param name - label name+ * @returns label if it exists, null otherwise+ */getLabel(name: string): BAttribute | null {return this.getAttribute(LABEL, name);}/**- * @param name - label name- * @returns label if it exists, null otherwise- */+ * @param name - label name+ * @returns label if it exists, null otherwise+ */getOwnedLabel(name: string): BAttribute | null {return this.getOwnedAttribute(LABEL, name);}/**- * @param name - relation name- * @returns relation if it exists, null otherwise- */+ * @param name - relation name+ * @returns relation if it exists, null otherwise+ */getRelation(name: string): BAttribute | null {return this.getAttribute(RELATION, name);}/**- * @param name - relation name- * @returns relation if it exists, null otherwise- */+ * @param name - relation name+ * @returns relation if it exists, null otherwise+ */getOwnedRelation(name: string): BAttribute | null {return this.getOwnedAttribute(RELATION, name);}/**- * @param name - label name- * @returns label value if label exists, null otherwise- */+ * @param name - label name+ * @returns label value if label exists, null otherwise+ */getLabelValue(name: string): string | null {return this.getAttributeValue(LABEL, name);}/**- * @param name - label name- * @returns label value if label exists, null otherwise- */+ * @param name - label name+ * @returns label value if label exists, null otherwise+ */getOwnedLabelValue(name: string): string | null {return this.getOwnedAttributeValue(LABEL, name);}/**- * @param name - relation name- * @returns relation value if relation exists, null otherwise- */+ * @param name - relation name+ * @returns relation value if relation exists, null otherwise+ */getRelationValue(name: string): string | null {return this.getAttributeValue(RELATION, name);}/**- * @param name - relation name- * @returns relation value if relation exists, null otherwise- */+ * @param name - relation name+ * @returns relation value if relation exists, null otherwise+ */getOwnedRelationValue(name: string): string | null {return this.getOwnedAttributeValue(RELATION, name);}/**- * @param attribute type (label, relation, etc.)- * @param name - attribute name- * @param value - attribute value- * @returns true if note has an attribute with given type and name (excluding inherited)- */+ * @param attribute type (label, relation, etc.)+ * @param name - attribute name+ * @param value - attribute value+ * @returns true if note has an attribute with given type and name (excluding inherited)+ */hasOwnedAttribute(type: string, name: string, value?: string): boolean {return !!this.getOwnedAttribute(type, name, value);}/**- * @param type - attribute type (label, relation, etc.)- * @param name - attribute name- * @returns attribute of the given type and name. If there are more such attributes, first is returned.- * Returns null if there's no such attribute belonging to this note.- */+ * @param type - attribute type (label, relation, etc.)+ * @param name - attribute name+ * @returns attribute of the given type and name. If there are more such attributes, first is returned.+ * Returns null if there's no such attribute belonging to this note.+ */getAttribute(type: string, name: string): BAttribute | null {const attributes = this.getAttributes();- return attributes.find(attr => attr.name === name && attr.type === type) || null;+ return attributes.find((attr) => attr.name === name && attr.type === type) || null;}/**- * @param type - attribute type (label, relation, etc.)- * @param name - attribute name- * @returns attribute value of given type and name or null if no such attribute exists.- */+ * @param type - attribute type (label, relation, etc.)+ * @param name - attribute name+ * @returns attribute value of given type and name or null if no such attribute exists.+ */getAttributeValue(type: string, name: string): string | null {const attr = this.getAttribute(type, name);@@ -615,10 +600,10 @@ class BNote extends AbstractBeccaEntity<BNote> {}/**- * @param type - attribute type (label, relation, etc.)- * @param name - attribute name- * @returns attribute value of given type and name or null if no such attribute exists.- */+ * @param type - attribute type (label, relation, etc.)+ * @param name - attribute name+ * @returns attribute value of given type and name or null if no such attribute exists.+ */getOwnedAttributeValue(type: string, name: string): string | null {const attr = this.getOwnedAttribute(type, name);@@ -626,87 +611,83 @@ class BNote extends AbstractBeccaEntity<BNote> {}/**- * @param name - label name to filter- * @returns all note's labels (attributes with type label), including inherited ones- */+ * @param name - label name to filter+ * @returns all note's labels (attributes with type label), including inherited ones+ */getLabels(name?: string): BAttribute[] {return this.getAttributes(LABEL, name);}/**- * @param name - label name to filter- * @returns all note's label values, including inherited ones- */+ * @param name - label name to filter+ * @returns all note's label values, including inherited ones+ */getLabelValues(name: string): string[] {- return this.getLabels(name).map(l => l.value);+ return this.getLabels(name).map((l) => l.value);}/**- * @param name - label name to filter- * @returns all note's labels (attributes with type label), excluding inherited ones- */+ * @param name - label name to filter+ * @returns all note's labels (attributes with type label), excluding inherited ones+ */getOwnedLabels(name: string): BAttribute[] {return this.getOwnedAttributes(LABEL, name);}/**- * @param name - label name to filter- * @returns all note's label values, excluding inherited ones- */+ * @param name - label name to filter+ * @returns all note's label values, excluding inherited ones+ */getOwnedLabelValues(name: string): string[] {- return this.getOwnedAttributes(LABEL, name).map(l => l.value);+ return this.getOwnedAttributes(LABEL, name).map((l) => l.value);}/**- * @param name - relation name to filter- * @returns all note's relations (attributes with type relation), including inherited ones- */+ * @param name - relation name to filter+ * @returns all note's relations (attributes with type relation), including inherited ones+ */getRelations(name?: string): BAttribute[] {return this.getAttributes(RELATION, name);}/**- * @param name - relation name to filter- * @returns all note's relations (attributes with type relation), excluding inherited ones- */+ * @param name - relation name to filter+ * @returns all note's relations (attributes with type relation), excluding inherited ones+ */getOwnedRelations(name?: string | null): BAttribute[] {return this.getOwnedAttributes(RELATION, name);}/**- * Beware that the method must not create a copy of the array, but actually returns its internal array- * (for performance reasons)- *- * @param type - (optional) attribute type to filter- * @param name - (optional) attribute name to filter- * @param value - (optional) attribute value to filter- * @returns note's "owned" attributes - excluding inherited ones- */+ * Beware that the method must not create a copy of the array, but actually returns its internal array+ * (for performance reasons)+ *+ * @param type - (optional) attribute type to filter+ * @param name - (optional) attribute name to filter+ * @param value - (optional) attribute value to filter+ * @returns note's "owned" attributes - excluding inherited ones+ */getOwnedAttributes(type: string | null = null, name: string | null = null, value: string | null = null) {this.__validateTypeName(type, name);if (type && name && value !== undefined && value !== null) {- return this.ownedAttributes.filter(attr => attr.name === name && attr.value === value && attr.type === type);- }- else if (type && name) {- return this.ownedAttributes.filter(attr => attr.name === name && attr.type === type);- }- else if (type) {- return this.ownedAttributes.filter(attr => attr.type === type);- }- else if (name) {- return this.ownedAttributes.filter(attr => attr.name === name);- }- else {+ return this.ownedAttributes.filter((attr) => attr.name === name && attr.value === value && attr.type === type);+ } else if (type && name) {+ return this.ownedAttributes.filter((attr) => attr.name === name && attr.type === type);+ } else if (type) {+ return this.ownedAttributes.filter((attr) => attr.type === type);+ } else if (name) {+ return this.ownedAttributes.filter((attr) => attr.name === name);+ } else {return this.ownedAttributes;}}/**- * @returns attribute belonging to this specific note (excludes inherited attributes)- *- * This method can be significantly faster than the getAttribute()- */+ * @returns attribute belonging to this specific note (excludes inherited attributes)+ *+ * This method can be significantly faster than the getAttribute()+ */getOwnedAttribute(type: string, name: string, value: string | null = null) {const attrs = this.getOwnedAttributes(type, name, value);@@ -714,7 +695,7 @@ class BNote extends AbstractBeccaEntity<BNote> {}get isArchived() {- return this.hasAttribute('label', 'archived');+ return this.hasAttribute("label", "archived");}areAllNotePathsArchived() {@@ -734,7 +715,7 @@ class BNote extends AbstractBeccaEntity<BNote> {hasInheritableArchivedLabel() {for (const attr of this.getAttributes()) {- if (attr.name === 'archived' && attr.type === LABEL && attr.isInheritable) {+ if (attr.name === "archived" && attr.type === LABEL && attr.isInheritable) {return true;}}@@ -755,9 +736,7 @@ class BNote extends AbstractBeccaEntity<BNote> {}});- this.parents = this.parentBranches- .map(branch => branch.parentNote)- .filter(note => !!note) as BNote[];+ this.parents = this.parentBranches.map((branch) => branch.parentNote).filter((note) => !!note) as BNote[];}sortChildren() {@@ -771,17 +750,17 @@ class BNote extends AbstractBeccaEntity<BNote> {const aBranch = becca.getBranchFromChildAndParent(a.noteId, this.noteId);const bBranch = becca.getBranchFromChildAndParent(b.noteId, this.noteId);- return ((aBranch?.notePosition || 0) - (bBranch?.notePosition || 0)) || 0;+ return (aBranch?.notePosition || 0) - (bBranch?.notePosition || 0) || 0;});}/**- * This is used for:- * - fast searching- * - note similarity evaluation- *- * @returns - returns flattened textual representation of note, prefixes and attributes- */+ * This is used for:+ * - fast searching+ * - note similarity evaluation+ *+ * @returns - returns flattened textual representation of note, prefixes and attributes+ */getFlatText() {if (!this.__flatTextCache) {this.__flatTextCache = `${this.noteId} ${this.type} ${this.mime} `;@@ -796,13 +775,13 @@ class BNote extends AbstractBeccaEntity<BNote> {for (const attr of this.getAttributes()) {// it's best to use space as separator since spaces are filtered from the search string by the tokenization into words- this.__flatTextCache += `${attr.type === 'label' ? '#' : '~'}${attr.name}`;+ this.__flatTextCache += `${attr.type === "label" ? "#" : "~"}${attr.name}`;if (attr.value) {this.__flatTextCache += `=${attr.value}`;}- this.__flatTextCache += ' ';+ this.__flatTextCache += " ";}this.__flatTextCache = utils.normalize(this.__flatTextCache);@@ -835,7 +814,7 @@ class BNote extends AbstractBeccaEntity<BNote> {}for (const targetRelation of this.targetRelations) {- if (targetRelation.name === 'template' || targetRelation.name === 'inherit') {+ if (targetRelation.name === "template" || targetRelation.name === "inherit") {const note = targetRelation.note;if (note) {@@ -846,17 +825,15 @@ class BNote extends AbstractBeccaEntity<BNote> {}getRelationDefinitions() {- return this.getLabels()- .filter(l => l.name.startsWith("relation:"));+ return this.getLabels().filter((l) => l.name.startsWith("relation:"));}getLabelDefinitions() {- return this.getLabels()- .filter(l => l.name.startsWith("relation:"));+ return this.getLabels().filter((l) => l.name.startsWith("relation:"));}isInherited() {- return !!this.targetRelations.find(rel => rel.name === 'template' || rel.name === 'inherit');+ return !!this.targetRelations.find((rel) => rel.name === "template" || rel.name === "inherit");}getSubtreeNotesIncludingTemplated(): BNote[] {@@ -864,7 +841,7 @@ class BNote extends AbstractBeccaEntity<BNote> {function inner(note: BNote) {// _hidden is not counted as subtree for the purpose of inheritance- if (set.has(note) || note.noteId === '_hidden') {+ if (set.has(note) || note.noteId === "_hidden") {return;}@@ -875,7 +852,7 @@ class BNote extends AbstractBeccaEntity<BNote> {}for (const targetRelation of note.targetRelations) {- if (targetRelation.name === 'template' || targetRelation.name === 'inherit') {+ if (targetRelation.name === "template" || targetRelation.name === "inherit") {const targetNote = targetRelation.note;if (targetNote) {@@ -891,26 +868,23 @@ class BNote extends AbstractBeccaEntity<BNote> {}getSearchResultNotes(): BNote[] {- if (this.type !== 'search') {+ if (this.type !== "search") {return [];}try {const result = searchService.searchFromNote(this);const becca = this.becca;- return (result.searchResultNoteIds)- .map(resultNoteId => becca.notes[resultNoteId])- .filter(note => !!note);- }- catch (e: any) {+ return result.searchResultNoteIds.map((resultNoteId) => becca.notes[resultNoteId]).filter((note) => !!note);+ } catch (e: any) {log.error(`Could not resolve search note ${this.noteId}: ${e.message}`);return [];}}- getSubtree({includeArchived = true, includeHidden = false, resolveSearch = false} = {}): {- notes: BNote[],- relationships: Relationship[]+ getSubtree({ includeArchived = true, includeHidden = false, resolveSearch = false } = {}): {+ notes: BNote[];+ relationships: Relationship[];} {const noteSet = new Set<BNote>();const relationships: Relationship[] = []; // list of tuples parentNoteId -> childNoteId@@ -920,14 +894,13 @@ class BNote extends AbstractBeccaEntity<BNote> {for (const resultNote of searchNote.getSearchResultNotes()) {addSubtreeNotesInner(resultNote, searchNote);}- }- catch (e: any) {+ } catch (e: any) {log.error(`Could not resolve search note ${searchNote?.noteId}: ${e.message}`);}}function addSubtreeNotesInner(note: BNote, parentNote: BNote | null = null) {- if (note.noteId === '_hidden' && !includeHidden) {+ if (note.noteId === "_hidden" && !includeHidden) {return;}@@ -949,12 +922,11 @@ class BNote extends AbstractBeccaEntity<BNote> {noteSet.add(note);- if (note.type === 'search') {+ if (note.type === "search") {if (resolveSearch) {resolveSearchNote(note);}- }- else {+ } else {for (const childNote of note.children) {addSubtreeNotesInner(childNote, note);}@@ -970,10 +942,8 @@ class BNote extends AbstractBeccaEntity<BNote> {}/** @returns includes the subtree root note as well */- getSubtreeNoteIds({includeArchived = true, includeHidden = false, resolveSearch = false} = {}) {- return this.getSubtree({includeArchived, includeHidden, resolveSearch})- .notes- .map(note => note.noteId);+ getSubtreeNoteIds({ includeArchived = true, includeHidden = false, resolveSearch = false } = {}) {+ return this.getSubtree({ includeArchived, includeHidden, resolveSearch }).notes.map((note) => note.noteId);}/** @deprecated use getSubtreeNoteIds() instead */@@ -990,31 +960,31 @@ class BNote extends AbstractBeccaEntity<BNote> {}get labelCount() {- return this.getAttributes().filter(attr => attr.type === 'label').length;+ return this.getAttributes().filter((attr) => attr.type === "label").length;}get ownedLabelCount() {- return this.ownedAttributes.filter(attr => attr.type === 'label').length;+ return this.ownedAttributes.filter((attr) => attr.type === "label").length;}get relationCount() {- return this.getAttributes().filter(attr => attr.type === 'relation' && !attr.isAutoLink()).length;+ return this.getAttributes().filter((attr) => attr.type === "relation" && !attr.isAutoLink()).length;}get relationCountIncludingLinks() {- return this.getAttributes().filter(attr => attr.type === 'relation').length;+ return this.getAttributes().filter((attr) => attr.type === "relation").length;}get ownedRelationCount() {- return this.ownedAttributes.filter(attr => attr.type === 'relation' && !attr.isAutoLink()).length;+ return this.ownedAttributes.filter((attr) => attr.type === "relation" && !attr.isAutoLink()).length;}get ownedRelationCountIncludingLinks() {- return this.ownedAttributes.filter(attr => attr.type === 'relation').length;+ return this.ownedAttributes.filter((attr) => attr.type === "relation").length;}get targetRelationCount() {- return this.targetRelations.filter(attr => !attr.isAutoLink()).length;+ return this.targetRelations.filter((attr) => !attr.isAutoLink()).length;}get targetRelationCountIncludingLinks() {@@ -1055,7 +1025,7 @@ class BNote extends AbstractBeccaEntity<BNote> {}getAncestorNoteIds(): string[] {- return this.getAncestors().map(note => note.noteId);+ return this.getAncestors().map((note) => note.noteId);}hasAncestor(ancestorNoteId: string): boolean {@@ -1069,7 +1039,7 @@ class BNote extends AbstractBeccaEntity<BNote> {}isInHiddenSubtree() {- return this.noteId === '_hidden' || this.hasAncestor('_hidden');+ return this.noteId === "_hidden" || this.hasAncestor("_hidden");}getTargetRelations() {@@ -1077,12 +1047,12 @@ class BNote extends AbstractBeccaEntity<BNote> {}/** @returns returns only notes which are templated, does not include their subtrees- * in effect returns notes which are influenced by note's non-inheritable attributes */+ * in effect returns notes which are influenced by note's non-inheritable attributes */getInheritingNotes(): BNote[] {const arr: BNote[] = [this];for (const targetRelation of this.targetRelations) {- if (targetRelation.name === 'template' || targetRelation.name === 'inherit') {+ if (targetRelation.name === "template" || targetRelation.name === "inherit") {const note = targetRelation.note;if (note) {@@ -1109,8 +1079,7 @@ class BNote extends AbstractBeccaEntity<BNote> {}getRevisions(): BRevision[] {- return sql.getRows<RevisionRow>("SELECT * FROM revisions WHERE noteId = ? ORDER BY revisions.utcDateCreated ASC", [this.noteId])- .map(row => new BRevision(row));+ return sql.getRows<RevisionRow>("SELECT * FROM revisions WHERE noteId = ? ORDER BY revisions.utcDateCreated ASC", [this.noteId]).map((row) => new BRevision(row));}getAttachments(opts: AttachmentOpts = {}) {@@ -1126,8 +1095,7 @@ class BNote extends AbstractBeccaEntity<BNote> {ORDER BY position`: `SELECT * FROM attachments WHERE ownerId = ? AND isDeleted = 0 ORDER BY position`;- return sql.getRows<AttachmentRow>(query, [this.noteId])- .map(row => new BAttachment(row));+ return sql.getRows<AttachmentRow>(query, [this.noteId]).map((row) => new BAttachment(row));}getAttachmentById(attachmentId: string, opts: AttachmentOpts = {}) {@@ -1140,41 +1108,45 @@ class BNote extends AbstractBeccaEntity<BNote> {WHERE ownerId = ? AND attachmentId = ? AND isDeleted = 0`: `SELECT * FROM attachments WHERE ownerId = ? AND attachmentId = ? AND isDeleted = 0`;- return sql.getRows<AttachmentRow>(query, [this.noteId, attachmentId])- .map(row => new BAttachment(row))[0];+ return sql.getRows<AttachmentRow>(query, [this.noteId, attachmentId]).map((row) => new BAttachment(row))[0];}getAttachmentsByRole(role: string): BAttachment[] {- return sql.getRows<AttachmentRow>(`+ return sql+ .getRows<AttachmentRow>(+ `SELECT attachments.*FROM attachmentsWHERE ownerId = ?AND role = ?AND isDeleted = 0- ORDER BY position`, [this.noteId, role])- .map(row => new BAttachment(row));+ ORDER BY position`,+ [this.noteId, role]+ )+ .map((row) => new BAttachment(row));}getAttachmentByTitle(title: string): BAttachment | undefined {// cannot use SQL to filter by title since it can be encrypted- return this.getAttachments().filter(attachment => attachment.title === title)[0];+ return this.getAttachments().filter((attachment) => attachment.title === title)[0];}/**- * Gives all possible note paths leading to this note. Paths containing search note are ignored (could form cycles)- *- * @returns array of notePaths (each represented by array of noteIds constituting the particular note path)- */+ * Gives all possible note paths leading to this note. Paths containing search note are ignored (could form cycles)+ *+ * @returns array of notePaths (each represented by array of noteIds constituting the particular note path)+ */getAllNotePaths(): string[][] {- if (this.noteId === 'root') {- return [['root']];+ if (this.noteId === "root") {+ return [["root"]];}const parentNotes = this.getParentNotes();- const notePaths = parentNotes.length === 1- ? parentNotes[0].getAllNotePaths() // optimization for the most common case- : parentNotes.flatMap(parentNote => parentNote.getAllNotePaths());+ const notePaths =+ parentNotes.length === 1+ ? parentNotes[0].getAllNotePaths() // optimization for the most common case+ : parentNotes.flatMap((parentNote) => parentNote.getAllNotePaths());for (const notePath of notePaths) {notePath.push(this.noteId);@@ -1183,14 +1155,14 @@ class BNote extends AbstractBeccaEntity<BNote> {return notePaths;}- getSortedNotePathRecords(hoistedNoteId: string = 'root'): NotePathRecord[] {- const isHoistedRoot = hoistedNoteId === 'root';+ getSortedNotePathRecords(hoistedNoteId: string = "root"): NotePathRecord[] {+ const isHoistedRoot = hoistedNoteId === "root";- const notePaths = this.getAllNotePaths().map(path => ({+ const notePaths = this.getAllNotePaths().map((path) => ({notePath: path,isInHoistedSubTree: isHoistedRoot || path.includes(hoistedNoteId),- isArchived: path.some(noteId => this.becca.notes[noteId].isArchived),- isHidden: path.includes('_hidden')+ isArchived: path.some((noteId) => this.becca.notes[noteId].isArchived),+ isHidden: path.includes("_hidden")}));notePaths.sort((a, b) => {@@ -1209,37 +1181,37 @@ class BNote extends AbstractBeccaEntity<BNote> {}/**- * Returns a note path considered to be the "best"- *- * @return array of noteIds constituting the particular note path- */- getBestNotePath(hoistedNoteId: string = 'root'): string[] {+ * Returns a note path considered to be the "best"+ *+ * @return array of noteIds constituting the particular note path+ */+ getBestNotePath(hoistedNoteId: string = "root"): string[] {return this.getSortedNotePathRecords(hoistedNoteId)[0]?.notePath;}/**- * Returns a note path considered to be the "best"- *- * @return serialized note path (e.g. 'root/a1h315/js725h')- */- getBestNotePathString(hoistedNoteId: string = 'root'): string {+ * Returns a note path considered to be the "best"+ *+ * @return serialized note path (e.g. 'root/a1h315/js725h')+ */+ getBestNotePathString(hoistedNoteId: string = "root"): string {const notePath = this.getBestNotePath(hoistedNoteId);return notePath?.join("/");}/**- * @return boolean - true if there's no non-hidden path, note is not cloned to the visible tree- */+ * @return boolean - true if there's no non-hidden path, note is not cloned to the visible tree+ */isHiddenCompletely() {- if (this.noteId === 'root') {+ if (this.noteId === "root") {return false;}for (const parentNote of this.parents) {- if (parentNote.noteId === 'root') {+ if (parentNote.noteId === "root") {return false;- } else if (parentNote.noteId === '_hidden') {+ } else if (parentNote.noteId === "_hidden") {continue;} else if (!parentNote.isHiddenCompletely()) {return false;@@ -1250,24 +1222,24 @@ class BNote extends AbstractBeccaEntity<BNote> {}/**- * @returns true if ancestorNoteId occurs in at least one of the note's paths- */+ * @returns true if ancestorNoteId occurs in at least one of the note's paths+ */isDescendantOfNote(ancestorNoteId: string): boolean {const notePaths = this.getAllNotePaths();- return notePaths.some(path => path.includes(ancestorNoteId));+ return notePaths.some((path) => path.includes(ancestorNoteId));}/**- * Update's given attribute's value or creates it if it doesn't exist- *- * @param type - attribute type (label, relation, etc.)- * @param name - attribute name- * @param value - attribute value (optional)- */+ * Update's given attribute's value or creates it if it doesn't exist+ *+ * @param type - attribute type (label, relation, etc.)+ * @param name - attribute name+ * @param value - attribute value (optional)+ */setAttribute(type: AttributeType, name: string, value?: string) {const attributes = this.getOwnedAttributes();- const attr = attributes.find(attr => attr.type === type && attr.name === name);+ const attr = attributes.find((attr) => attr.type === type && attr.name === name);value = value?.toString() || "";@@ -1276,8 +1248,7 @@ class BNote extends AbstractBeccaEntity<BNote> {attr.value = value;attr.save();}- }- else {+ } else {new BAttribute({noteId: this.noteId,type: type,@@ -1288,12 +1259,12 @@ class BNote extends AbstractBeccaEntity<BNote> {}/**- * Removes given attribute name-value pair if it exists.- *- * @param type - attribute type (label, relation, etc.)- * @param name - attribute name- * @param value - attribute value (optional)- */+ * Removes given attribute name-value pair if it exists.+ *+ * @param type - attribute type (label, relation, etc.)+ * @param name - attribute name+ * @param value - attribute value (optional)+ */removeAttribute(type: string, name: string, value?: string) {const attributes = this.getOwnedAttributes();@@ -1305,13 +1276,13 @@ class BNote extends AbstractBeccaEntity<BNote> {}/**- * Adds a new attribute to this note. The attribute is saved and returned.- * See addLabel, addRelation for more specific methods.- *- * @param type - attribute type (label / relation)- * @param name - name of the attribute, not including the leading ~/#- * @param value - value of the attribute - text for labels, target note ID for relations; optional.- */+ * Adds a new attribute to this note. The attribute is saved and returned.+ * See addLabel, addRelation for more specific methods.+ *+ * @param type - attribute type (label / relation)+ * @param name - name of the attribute, not including the leading ~/#+ * @param value - value of the attribute - text for labels, target note ID for relations; optional.+ */addAttribute(type: AttributeType, name: string, value: string = "", isInheritable: boolean = false, position: number | null = null): BAttribute {return new BAttribute({noteId: this.noteId,@@ -1324,100 +1295,99 @@ class BNote extends AbstractBeccaEntity<BNote> {}/**- * Adds a new label to this note. The label attribute is saved and returned.- *- * @param name - name of the label, not including the leading #- * @param value - text value of the label; optional- */+ * Adds a new label to this note. The label attribute is saved and returned.+ *+ * @param name - name of the label, not including the leading #+ * @param value - text value of the label; optional+ */addLabel(name: string, value: string = "", isInheritable: boolean = false): BAttribute {return this.addAttribute(LABEL, name, value, isInheritable);}/**- * Adds a new relation to this note. The relation attribute is saved and- * returned.- *- * @param name - name of the relation, not including the leading ~- */+ * Adds a new relation to this note. The relation attribute is saved and+ * returned.+ *+ * @param name - name of the relation, not including the leading ~+ */addRelation(name: string, targetNoteId: string, isInheritable: boolean = false): BAttribute {return this.addAttribute(RELATION, name, targetNoteId, isInheritable);}/**- * Based on enabled, the attribute is either set or removed.- *- * @param type - attribute type ('relation', 'label' etc.)- * @param enabled - toggle On or Off- * @param name - attribute name- * @param value - attribute value (optional)- */+ * Based on enabled, the attribute is either set or removed.+ *+ * @param type - attribute type ('relation', 'label' etc.)+ * @param enabled - toggle On or Off+ * @param name - attribute name+ * @param value - attribute value (optional)+ */toggleAttribute(type: AttributeType, enabled: boolean, name: string, value?: string) {if (enabled) {this.setAttribute(type, name, value);- }- else {+ } else {this.removeAttribute(type, name, value);}}/**- * Based on enabled, label is either set or removed.- *- * @param enabled - toggle On or Off- * @param name - label name- * @param value - label value (optional)- */+ * Based on enabled, label is either set or removed.+ *+ * @param enabled - toggle On or Off+ * @param name - label name+ * @param value - label value (optional)+ */toggleLabel(enabled: boolean, name: string, value?: string) {return this.toggleAttribute(LABEL, enabled, name, value);}/**- * Based on enabled, relation is either set or removed.- *- * @param enabled - toggle On or Off- * @param name - relation name- * @param value - relation value (noteId)- */+ * Based on enabled, relation is either set or removed.+ *+ * @param enabled - toggle On or Off+ * @param name - relation name+ * @param value - relation value (noteId)+ */toggleRelation(enabled: boolean, name: string, value?: string) {return this.toggleAttribute(RELATION, enabled, name, value);}/**- * Update's given label's value or creates it if it doesn't exist- *- * @param name - label name- * @param value label value- */+ * Update's given label's value or creates it if it doesn't exist+ *+ * @param name - label name+ * @param value label value+ */setLabel(name: string, value?: string) {return this.setAttribute(LABEL, name, value);}/**- * Update's given relation's value or creates it if it doesn't exist- *- * @param name - relation name- * @param value - relation value (noteId)- */+ * Update's given relation's value or creates it if it doesn't exist+ *+ * @param name - relation name+ * @param value - relation value (noteId)+ */setRelation(name: string, value?: string) {return this.setAttribute(RELATION, name, value);}/**- * Remove label name-value pair, if it exists.- *- * @param name - label name- * @param value - label value- */+ * Remove label name-value pair, if it exists.+ *+ * @param name - label name+ * @param value - label value+ */removeLabel(name: string, value?: string) {return this.removeAttribute(LABEL, name, value);}/**- * Remove the relation name-value pair, if it exists.- *- * @param name - relation name- * @param value - relation value (noteId)- */+ * Remove the relation name-value pair, if it exists.+ *+ * @param name - relation name+ * @param value - relation value (noteId)+ */removeRelation(name: string, value?: string) {return this.removeAttribute(RELATION, name, value);}@@ -1443,11 +1413,11 @@ class BNote extends AbstractBeccaEntity<BNote> {}isEligibleForConversionToAttachment(opts: ConvertOpts = { autoConversion: false }) {- if (this.type !== 'image' || !this.isContentAvailable() || this.hasChildren() || this.getParentBranches().length !== 1) {+ if (this.type !== "image" || !this.isContentAvailable() || this.hasChildren() || this.getParentBranches().length !== 1) {return false;}- const targetRelations = this.getTargetRelations().filter(relation => relation.name === 'imageLink');+ const targetRelations = this.getTargetRelations().filter((relation) => relation.name === "imageLink");if (opts.autoConversion && targetRelations.length === 0) {return false;@@ -1460,7 +1430,7 @@ class BNote extends AbstractBeccaEntity<BNote> {if (referencingNote && parentNote !== referencingNote) {return false;- } else if (parentNote.type !== 'text' || !parentNote.isContentAvailable()) {+ } else if (parentNote.type !== "text" || !parentNote.isContentAvailable()) {return false;}@@ -1468,20 +1438,20 @@ class BNote extends AbstractBeccaEntity<BNote> {}/**- * Some notes are eligible for conversion into an attachment of its parent, note must have these properties:- * - it has exactly one target relation- * - it has a relation from its parent note- * - it has no children- * - it has no clones- * - the parent is of type text- * - both notes are either unprotected or user is in protected session- *- * Currently, works only for image notes.- *- * In the future, this functionality might get more generic and some of the requirements relaxed.- *- * @returns null if note is not eligible for conversion- */+ * Some notes are eligible for conversion into an attachment of its parent, note must have these properties:+ * - it has exactly one target relation+ * - it has a relation from its parent note+ * - it has no children+ * - it has no clones+ * - the parent is of type text+ * - both notes are either unprotected or user is in protected session+ *+ * Currently, works only for image notes.+ *+ * In the future, this functionality might get more generic and some of the requirements relaxed.+ *+ * @returns null if note is not eligible for conversion+ */convertToParentAttachment(opts: ConvertOpts = { autoConversion: false }): BAttachment | null {if (!this.isEligibleForConversionToAttachment(opts)) {return null;@@ -1491,7 +1461,7 @@ class BNote extends AbstractBeccaEntity<BNote> {const parentNote = this.getParentNotes()[0];const attachment = parentNote.saveAttachment({- role: 'image',+ role: "image",mime: this.mime,title: this.title,content: content@@ -1518,10 +1488,10 @@ class BNote extends AbstractBeccaEntity<BNote> {}/**- * (Soft) delete a note and all its descendants.- *- * @param deleteId - optional delete identified- */+ * (Soft) delete a note and all its descendants.+ *+ * @param deleteId - optional delete identified+ */deleteNote(deleteId: string | null = null, taskContext: TaskContext | null = null) {if (this.isDeleted) {return;@@ -1532,11 +1502,11 @@ class BNote extends AbstractBeccaEntity<BNote> {}if (!taskContext) {- taskContext = new TaskContext('no-progress-reporting');+ taskContext = new TaskContext("no-progress-reporting");}// needs to be run before branches and attributes are deleted and thus attached relations disappear- handlers.runAttachedRelations(this, 'runOnNoteDeletion', this);+ handlers.runAttachedRelations(this, "runOnNoteDeletion", this);taskContext.noteDeletionHandlerTriggered = true;for (const branch of this.getParentBranches()) {@@ -1551,15 +1521,14 @@ class BNote extends AbstractBeccaEntity<BNote> {this.__flatTextCache = null;this.isDecrypted = true;- }- catch (e: any) {+ } catch (e: any) {log.error(`Could not decrypt note ${this.noteId}: ${e.message} ${e.stack}`);}}}isLaunchBarConfig() {- return this.type === 'launcher' || ['_lbRoot', '_lbAvailableLaunchers', '_lbVisibleLaunchers'].includes(this.noteId);+ return this.type === "launcher" || ["_lbRoot", "_lbAvailableLaunchers", "_lbVisibleLaunchers"].includes(this.noteId);}isOptions() {@@ -1576,19 +1545,22 @@ class BNote extends AbstractBeccaEntity<BNote> {return sql.transactional(() => {let noteContent = this.getContent();- const revision = new BRevision({- noteId: this.noteId,- // title and text should be decrypted now- title: this.title,- type: this.type,- mime: this.mime,- isProtected: this.isProtected,- utcDateLastEdited: this.utcDateModified,- utcDateCreated: dateUtils.utcNowDateTime(),- utcDateModified: dateUtils.utcNowDateTime(),- dateLastEdited: this.dateModified,- dateCreated: dateUtils.localNowDateTime()- }, true);+ const revision = new BRevision(+ {+ noteId: this.noteId,+ // title and text should be decrypted now+ title: this.title,+ type: this.type,+ mime: this.mime,+ isProtected: this.isProtected,+ utcDateLastEdited: this.utcDateModified,+ utcDateCreated: dateUtils.utcNowDateTime(),+ utcDateModified: dateUtils.utcNowDateTime(),+ dateLastEdited: this.dateModified,+ dateCreated: dateUtils.localNowDateTime()+ },+ true+ );revision.save(); // to generate revisionId, which is then used to save attachments@@ -1602,19 +1574,20 @@ class BNote extends AbstractBeccaEntity<BNote> {revisionAttachment.ownerId = revision.revisionId;revisionAttachment.setContent(noteAttachment.getContent(), { forceSave: true });- if (this.type === 'text' && typeof noteContent === "string") {+ if (this.type === "text" && typeof noteContent === "string") {// content is rewritten to point to the revision attachments- noteContent = noteContent.replaceAll(`attachments/${noteAttachment.attachmentId}`,- `attachments/${revisionAttachment.attachmentId}`);+ noteContent = noteContent.replaceAll(`attachments/${noteAttachment.attachmentId}`, `attachments/${revisionAttachment.attachmentId}`);- noteContent = noteContent.replaceAll(new RegExp(`href="[^"]*attachmentId=${noteAttachment.attachmentId}[^"]*"`, 'gi'),- `href="api/attachments/${revisionAttachment.attachmentId}/download"`);+ noteContent = noteContent.replaceAll(+ new RegExp(`href="[^"]*attachmentId=${noteAttachment.attachmentId}[^"]*"`, "gi"),+ `href="api/attachments/${revisionAttachment.attachmentId}/download"`+ );}}revision.setContent(noteContent);- this.eraseExcessRevisionSnapshots()+ this.eraseExcessRevisionSnapshots();return revision;});}@@ -1625,14 +1598,14 @@ class BNote extends AbstractBeccaEntity<BNote> {// lable has a higher prioritylet revisionSnapshotNumberLimit = parseInt(this.getLabelValue("versioningLimit") ?? "");if (!Number.isInteger(revisionSnapshotNumberLimit)) {- revisionSnapshotNumberLimit = parseInt(optionService.getOption('revisionSnapshotNumberLimit'));+ revisionSnapshotNumberLimit = parseInt(optionService.getOption("revisionSnapshotNumberLimit"));}if (revisionSnapshotNumberLimit >= 0) {const revisions = this.getRevisions();if (revisions.length - revisionSnapshotNumberLimit > 0) {const revisionIds = revisions.slice(0, revisions.length - revisionSnapshotNumberLimit)- .map(revision => revision.revisionId)+ .map((revision) => revision.revisionId).filter((id): id is string => id !== undefined);eraseService.eraseRevisions(revisionIds);}@@ -1640,33 +1613,35 @@ class BNote extends AbstractBeccaEntity<BNote> {}/**- * @param matchBy - choose by which property we detect if to update an existing attachment.- * Supported values are either 'attachmentId' (default) or 'title'- */- saveAttachment({attachmentId, role, mime, title, content, position}: AttachmentRow, matchBy = 'attachmentId') {- if (!['attachmentId', 'title'].includes(matchBy)) {+ * @param matchBy - choose by which property we detect if to update an existing attachment.+ * Supported values are either 'attachmentId' (default) or 'title'+ */+ saveAttachment({ attachmentId, role, mime, title, content, position }: AttachmentRow, matchBy = "attachmentId") {+ if (!["attachmentId", "title"].includes(matchBy)) {throw new Error(`Unsupported value '${matchBy}' for matchBy param, has to be either 'attachmentId' or 'title'.`);}let attachment;- if (matchBy === 'title' && title) {+ if (matchBy === "title" && title) {attachment = this.getAttachmentByTitle(title);- } else if (matchBy === 'attachmentId' && attachmentId) {+ } else if (matchBy === "attachmentId" && attachmentId) {attachment = this.becca.getAttachmentOrThrow(attachmentId);}- attachment = attachment || new BAttachment({- ownerId: this.noteId,- title,- role,- mime,- isProtected: this.isProtected,- position- });+ attachment =+ attachment ||+ new BAttachment({+ ownerId: this.noteId,+ title,+ role,+ mime,+ isProtected: this.isProtected,+ position+ });content = content || "";- attachment.setContent(content, {forceSave: true});+ attachment.setContent(content, { forceSave: true });return attachment;}@@ -1706,8 +1681,7 @@ class BNote extends AbstractBeccaEntity<BNote> {if (pojo.isProtected) {if (this.isDecrypted && pojo.title) {pojo.title = protectedSessionService.encrypt(pojo.title) || undefined;- }- else {+ } else {// updating protected note outside of protected session means we will keep original ciphertextsdelete pojo.title;}diff --git a/src/becca/entities/boption.ts b/src/becca/entities/boption.tsindex 4ae5ba7a98..f18be29860 100644--- a/src/becca/entities/boption.ts+++ b/src/becca/entities/boption.ts@@ -2,15 +2,21 @@import dateUtils from "../../services/date_utils.js";import AbstractBeccaEntity from "./abstract_becca_entity.js";-import { OptionRow } from './rows.js';+import { OptionRow } from "./rows.js";/*** Option represents a name-value pair, either directly configurable by the user or some system property.*/class BOption extends AbstractBeccaEntity<BOption> {- static get entityName() { return "options"; }- static get primaryKeyName() { return "name"; }- static get hashedProperties() { return ["name", "value"]; }+ static get entityName() {+ return "options";+ }+ static get primaryKeyName() {+ return "name";+ }+ static get hashedProperties() {+ return ["name", "value"];+ }name!: string;value!: string;@@ -43,7 +49,7 @@ class BOption extends AbstractBeccaEntity<BOption> {value: this.value,isSynced: this.isSynced,utcDateModified: this.utcDateModified- }+ };}}diff --git a/src/becca/entities/brecent_note.ts b/src/becca/entities/brecent_note.tsindex f9f31a98fd..d4c54ba2e0 100644--- a/src/becca/entities/brecent_note.ts+++ b/src/becca/entities/brecent_note.ts@@ -9,9 +9,15 @@ import AbstractBeccaEntity from "./abstract_becca_entity.js";* RecentNote represents recently visited note.*/class BRecentNote extends AbstractBeccaEntity<BRecentNote> {- static get entityName() { return "recent_notes"; }- static get primaryKeyName() { return "noteId"; }- static get hashedProperties() { return ["noteId", "notePath"]; }+ static get entityName() {+ return "recent_notes";+ }+ static get primaryKeyName() {+ return "noteId";+ }+ static get hashedProperties() {+ return ["noteId", "notePath"];+ }noteId!: string;notePath!: string;@@ -33,7 +39,7 @@ class BRecentNote extends AbstractBeccaEntity<BRecentNote> {noteId: this.noteId,notePath: this.notePath,utcDateCreated: this.utcDateCreated- }+ };}}diff --git a/src/becca/entities/brevision.ts b/src/becca/entities/brevision.tsindex 8ba6fbeadd..352302318f 100644--- a/src/becca/entities/brevision.ts+++ b/src/becca/entities/brevision.ts@@ -7,7 +7,7 @@ import becca from "../becca.js";import AbstractBeccaEntity from "./abstract_becca_entity.js";import sql from "../../services/sql.js";import BAttachment from "./battachment.js";-import { AttachmentRow, RevisionRow } from './rows.js';+import { AttachmentRow, RevisionRow } from "./rows.js";import eraseService from "../../services/erase.js";interface ContentOpts {@@ -24,10 +24,15 @@ interface GetByIdOpts {* It's used for seamless note versioning.*/class BRevision extends AbstractBeccaEntity<BRevision> {- static get entityName() { return "revisions"; }- static get primaryKeyName() { return "revisionId"; }- static get hashedProperties() { return ["revisionId", "noteId", "title", "isProtected", "dateLastEdited", "dateCreated",- "utcDateLastEdited", "utcDateCreated", "utcDateModified", "blobId"]; }+ static get entityName() {+ return "revisions";+ }+ static get primaryKeyName() {+ return "revisionId";+ }+ static get hashedProperties() {+ return ["revisionId", "noteId", "title", "isProtected", "dateLastEdited", "dateCreated", "utcDateLastEdited", "utcDateCreated", "utcDateModified", "blobId"];+ }revisionId?: string;noteId!: string;@@ -75,25 +80,27 @@ class BRevision extends AbstractBeccaEntity<BRevision> {}isContentAvailable() {- return !this.revisionId // new note which was not encrypted yet- || !this.isProtected- || protectedSessionService.isProtectedSessionAvailable()+ return (+ !this.revisionId || // new note which was not encrypted yet+ !this.isProtected ||+ protectedSessionService.isProtectedSessionAvailable()+ );}/*- * Note revision content has quite special handling - it's not a separate entity, but a lazily loaded- * part of Revision entity with its own sync. The reason behind this hybrid design is that- * content can be quite large, and it's not necessary to load it / fill memory for any note access even- * if we don't need a content, especially for bulk operations like search.- *- * This is the same approach as is used for Note's content.- */+ * Note revision content has quite special handling - it's not a separate entity, but a lazily loaded+ * part of Revision entity with its own sync. The reason behind this hybrid design is that+ * content can be quite large, and it's not necessary to load it / fill memory for any note access even+ * if we don't need a content, especially for bulk operations like search.+ *+ * This is the same approach as is used for Note's content.+ */getContent(): string | Buffer {return this._getContent();}/**- * @throws Error in case of invalid JSON */+ * @throws Error in case of invalid JSON */getJsonContent(): {} | null {const content = this.getContent();@@ -108,8 +115,7 @@ class BRevision extends AbstractBeccaEntity<BRevision> {getJsonContentSafely(): {} | null {try {return this.getJsonContent();- }- catch (e) {+ } catch (e) {return null;}}@@ -119,12 +125,16 @@ class BRevision extends AbstractBeccaEntity<BRevision> {}getAttachments(): BAttachment[] {- return sql.getRows<AttachmentRow>(`+ return sql+ .getRows<AttachmentRow>(+ `SELECT attachments.*FROM attachmentsWHERE ownerId = ?- AND isDeleted = 0`, [this.revisionId])- .map(row => new BAttachment(row));+ AND isDeleted = 0`,+ [this.revisionId]+ )+ .map((row) => new BAttachment(row));}getAttachmentById(attachmentId: String, opts: GetByIdOpts = {}): BAttachment | null {@@ -137,29 +147,32 @@ class BRevision extends AbstractBeccaEntity<BRevision> {WHERE ownerId = ? AND attachmentId = ? AND isDeleted = 0`: `SELECT * FROM attachments WHERE ownerId = ? AND attachmentId = ? AND isDeleted = 0`;- return sql.getRows<AttachmentRow>(query, [this.revisionId, attachmentId])- .map(row => new BAttachment(row))[0];+ return sql.getRows<AttachmentRow>(query, [this.revisionId, attachmentId]).map((row) => new BAttachment(row))[0];}getAttachmentsByRole(role: string): BAttachment[] {- return sql.getRows<AttachmentRow>(`+ return sql+ .getRows<AttachmentRow>(+ `SELECT attachments.*FROM attachmentsWHERE ownerId = ?AND role = ?AND isDeleted = 0- ORDER BY position`, [this.revisionId, role])- .map(row => new BAttachment(row));+ ORDER BY position`,+ [this.revisionId, role]+ )+ .map((row) => new BAttachment(row));}getAttachmentByTitle(title: string): BAttachment {// cannot use SQL to filter by title since it can be encrypted- return this.getAttachments().filter(attachment => attachment.title === title)[0];+ return this.getAttachments().filter((attachment) => attachment.title === title)[0];}/**- * Revisions are not soft-deletable, they are immediately hard-deleted (erased).- */+ * Revisions are not soft-deletable, they are immediately hard-deleted (erased).+ */eraseRevision() {if (this.revisionId) {eraseService.eraseRevisions([this.revisionId]);@@ -199,8 +212,7 @@ class BRevision extends AbstractBeccaEntity<BRevision> {if (pojo.isProtected) {if (protectedSessionService.isProtectedSessionAvailable()) {pojo.title = protectedSessionService.encrypt(this.title) || undefined;- }- else {+ } else {// updating protected note outside of protected session means we will keep original ciphertextsdelete pojo.title;}diff --git a/src/becca/entities/rows.ts b/src/becca/entities/rows.tsindex bced96c781..d2d327541a 100644--- a/src/becca/entities/rows.ts+++ b/src/becca/entities/rows.ts@@ -100,8 +100,25 @@ export interface BranchRow {* end user. Those types should be used only for checking against, they are* not for direct use.*/-export const ALLOWED_NOTE_TYPES = [ "file", "image", "search", "noteMap", "launcher", "doc", "contentWidget", "text", "relationMap", "render", "canvas", "mermaid", "book", "webView", "code", "mindMap" ] as const;-export type NoteType = typeof ALLOWED_NOTE_TYPES[number];+export const ALLOWED_NOTE_TYPES = [+ "file",+ "image",+ "search",+ "noteMap",+ "launcher",+ "doc",+ "contentWidget",+ "text",+ "relationMap",+ "render",+ "canvas",+ "mermaid",+ "book",+ "webView",+ "code",+ "mindMap"+] as const;+export type NoteType = (typeof ALLOWED_NOTE_TYPES)[number];export interface NoteRow {noteId: string;diff --git a/src/becca/entity_constructor.ts b/src/becca/entity_constructor.tsindex 49476961c3..b6dd4c52b8 100644--- a/src/becca/entity_constructor.ts+++ b/src/becca/entity_constructor.ts@@ -1,4 +1,4 @@-import { ConstructorData } from './becca-interface.js';+import { ConstructorData } from "./becca-interface.js";import AbstractBeccaEntity from "./entities/abstract_becca_entity.js";import BAttachment from "./entities/battachment.js";import BAttribute from "./entities/battribute.js";@@ -13,15 +13,15 @@ import BRevision from "./entities/brevision.js";type EntityClass = new (row?: any) => AbstractBeccaEntity<any>;const ENTITY_NAME_TO_ENTITY: Record<string, ConstructorData<any> & EntityClass> = {- "attachments": BAttachment,- "attributes": BAttribute,- "blobs": BBlob,- "branches": BBranch,- "etapi_tokens": BEtapiToken,- "notes": BNote,- "options": BOption,- "recent_notes": BRecentNote,- "revisions": BRevision+ attachments: BAttachment,+ attributes: BAttribute,+ blobs: BBlob,+ branches: BBranch,+ etapi_tokens: BEtapiToken,+ notes: BNote,+ options: BOption,+ recent_notes: BRecentNote,+ revisions: BRevision};function getEntityFromEntityName(entityName: keyof typeof ENTITY_NAME_TO_ENTITY) {diff --git a/src/becca/similarity.ts b/src/becca/similarity.tsindex 3c9b071b44..5313419d6c 100644--- a/src/becca/similarity.ts+++ b/src/becca/similarity.ts@@ -7,11 +7,7 @@ import BNote from "./entities/bnote.js";const DEBUG = false;-const IGNORED_ATTRS = [- "datenote",- "monthnote",- "yearnote"-];+const IGNORED_ATTRS = ["datenote", "monthnote", "yearnote"];const IGNORED_ATTR_NAMES = ["includenotelink",@@ -30,7 +26,7 @@ const IGNORED_ATTR_NAMES = ["similarnoteswidgetdisabled","disableinclusion","rendernote",- "pageurl",+ "pageurl"];interface DateLimits {@@ -42,9 +38,9 @@ interface DateLimits {function filterUrlValue(value: string) {return value- .replace(/https?:\/\//ig, "")- .replace(/www.js\./ig, "")- .replace(/(\.net|\.com|\.org|\.info|\.edu)/ig, "");+ .replace(/https?:\/\//gi, "")+ .replace(/www.js\./gi, "")+ .replace(/(\.net|\.com|\.org|\.info|\.edu)/gi, "");}function buildRewardMap(note: BNote) {@@ -61,8 +57,7 @@ function buildRewardMap(note: BNote) {const currentReward = map.get(word) || 0;// reward grows with the length of matched string- const length = word.length- - 0.9; // to penalize specifically very short words - 1 and 2 characters+ const length = word.length - 0.9; // to penalize specifically very short words - 1 and 2 charactersmap.set(word, currentReward + rewardFactor * Math.pow(length, 0.7));}@@ -70,7 +65,7 @@ function buildRewardMap(note: BNote) {}for (const ancestorNote of note.getAncestors()) {- if (ancestorNote.noteId === 'root') {+ if (ancestorNote.noteId === "root") {continue;}@@ -94,9 +89,7 @@ function buildRewardMap(note: BNote) {}for (const attr of note.getAttributes()) {- if (attr.name.startsWith('child:')- || attr.name.startsWith('relation:')- || attr.name.startsWith('label:')) {+ if (attr.name.startsWith("child:") || attr.name.startsWith("relation:") || attr.name.startsWith("label:")) {continue;}@@ -111,13 +104,13 @@ function buildRewardMap(note: BNote) {addToRewardMap(attr.name, reward);}- if (attr.name === 'cliptype') {+ if (attr.name === "cliptype") {reward /= 2;}let value = attr.value;- if (value.startsWith('http')) {+ if (value.startsWith("http")) {value = filterUrlValue(value);// words in URLs are not that valuable@@ -127,7 +120,7 @@ function buildRewardMap(note: BNote) {addToRewardMap(value, reward);}- if (note.type === 'text' && note.isDecrypted) {+ if (note.type === "text" && note.isDecrypted) {const content = note.getContent();const dom = new JSDOM(content);@@ -135,7 +128,7 @@ function buildRewardMap(note: BNote) {for (const el of dom.window.document.querySelectorAll(elName)) {addToRewardMap(el.textContent, rewardFactor);}- }+ };// the title is the top with weight 1 so smaller headings will have lower weight@@ -154,12 +147,12 @@ function buildRewardMap(note: BNote) {const mimeCache: Record<string, string> = {};function trimMime(mime: string) {- if (!mime || mime === 'text/html') {+ if (!mime || mime === "text/html") {return;}if (!(mime in mimeCache)) {- const chunks = mime.split('/');+ const chunks = mime.split("/");let str = "";@@ -167,7 +160,7 @@ function trimMime(mime: string) {// we're not interested in 'text/' or 'application/' prefixstr = chunks[1];- if (str.startsWith('-x')) {+ if (str.startsWith("-x")) {str = str.substr(2);}}@@ -185,7 +178,7 @@ function buildDateLimits(baseNote: BNote): DateLimits {minDate: dateUtils.utcDateTimeStr(new Date(dateCreatedTs - 3600 * 1000)),minExcludedDate: dateUtils.utcDateTimeStr(new Date(dateCreatedTs - 5 * 1000)),maxExcludedDate: dateUtils.utcDateTimeStr(new Date(dateCreatedTs + 5 * 1000)),- maxDate: dateUtils.utcDateTimeStr(new Date(dateCreatedTs + 3600 * 1000)),+ maxDate: dateUtils.utcDateTimeStr(new Date(dateCreatedTs + 3600 * 1000))};}@@ -193,9 +186,34 @@ function buildDateLimits(baseNote: BNote): DateLimits {const wordCache = new Map();const WORD_BLACKLIST = [- "a", "the", "in", "for", "from", "but", "s", "so", "if", "while", "until",- "whether", "after", "before", "because", "since", "when", "where", "how",- "than", "then", "and", "either", "or", "neither", "nor", "both", "also"+ "a",+ "the",+ "in",+ "for",+ "from",+ "but",+ "s",+ "so",+ "if",+ "while",+ "until",+ "whether",+ "after",+ "before",+ "because",+ "since",+ "when",+ "where",+ "how",+ "than",+ "then",+ "and",+ "either",+ "or",+ "neither",+ "nor",+ "both",+ "also"];function splitToWords(text: string) {@@ -212,8 +230,7 @@ function splitToWords(text: string) {// special case for english pluralselse if (words[idx].length > 2 && words[idx].endsWith("es")) {words[idx] = words[idx].substr(0, words[idx] - 2);- }- else if (words[idx].length > 1 && words[idx].endsWith("s")) {+ } else if (words[idx].length > 1 && words[idx].endsWith("s")) {words[idx] = words[idx].substr(0, words[idx] - 1);}}@@ -227,9 +244,7 @@ function splitToWords(text: string) {* that it doesn't actually need to be shown to the user.*/function hasConnectingRelation(sourceNote: BNote, targetNote: BNote) {- return sourceNote.getAttributes().find(attr => attr.type === 'relation'- && ['includenotelink', 'imagelink'].includes(attr.name)- && attr.value === targetNote.noteId);+ return sourceNote.getAttributes().find((attr) => attr.type === "relation" && ["includenotelink", "imagelink"].includes(attr.name) && attr.value === targetNote.noteId);}async function findSimilarNotes(noteId: string) {@@ -246,14 +261,13 @@ async function findSimilarNotes(noteId: string) {try {dateLimits = buildDateLimits(baseNote);- }- catch (e: any) {+ } catch (e: any) {throw new Error(`Date limits failed with ${e.message}, entity: ${JSON.stringify(baseNote.getPojo())}`);}const rewardMap = buildRewardMap(baseNote);let ancestorRewardCache: Record<string, number> = {};- const ancestorNoteIds = new Set(baseNote.getAncestors().map(note => note.noteId));+ const ancestorNoteIds = new Set(baseNote.getAncestors().map((note) => note.noteId));ancestorNoteIds.add(baseNote.noteId);let displayRewards = false;@@ -270,7 +284,7 @@ async function findSimilarNotes(noteId: string) {const lengthPenalization = 1 / Math.pow(text.length, 0.3);for (const word of splitToWords(text)) {- const reward = (rewardMap.get(word) * factor * lengthPenalization) || 0;+ const reward = rewardMap.get(word) * factor * lengthPenalization || 0;if (displayRewards && reward > 0) {console.log(`Reward ${Math.round(reward * 10) / 10} for word: ${word}`);@@ -294,7 +308,6 @@ async function findSimilarNotes(noteId: string) {for (const parentNote of note.parents) {if (!ancestorNoteIds.has(parentNote.noteId)) {-if (displayRewards) {console.log("Considering", parentNote.title);}@@ -304,8 +317,7 @@ async function findSimilarNotes(noteId: string) {}for (const branch of parentNote.getParentBranches()) {- score += gatherRewards(branch.prefix, 0.3)- + gatherAncestorRewards(branch.parentNote);+ score += gatherRewards(branch.prefix, 0.3) + gatherAncestorRewards(branch.parentNote);}}}@@ -317,8 +329,7 @@ async function findSimilarNotes(noteId: string) {}function computeScore(candidateNote: BNote) {- let score = gatherRewards(trimMime(candidateNote.mime))- + gatherAncestorRewards(candidateNote);+ let score = gatherRewards(trimMime(candidateNote.mime)) + gatherAncestorRewards(candidateNote);if (candidateNote.isDecrypted) {score += gatherRewards(candidateNote.title);@@ -329,9 +340,7 @@ async function findSimilarNotes(noteId: string) {}for (const attr of candidateNote.getAttributes()) {- if (attr.name.startsWith('child:')- || attr.name.startsWith('relation:')- || attr.name.startsWith('label:')) {+ if (attr.name.startsWith("child:") || attr.name.startsWith("relation:") || attr.name.startsWith("label:")) {continue;}@@ -349,8 +358,7 @@ async function findSimilarNotes(noteId: string) {if (!value.startsWith) {log.info(`Unexpected falsy value for attribute ${JSON.stringify(attr.getPojo())}`);continue;- }- else if (value.startsWith('http')) {+ } else if (value.startsWith("http")) {value = filterUrlValue(value);// words in URLs are not that valuable@@ -369,13 +377,13 @@ async function findSimilarNotes(noteId: string) {}/**- * We want to improve the standing of notes which have been created in similar time to each other since- * there's a good chance they are related.- *- * But there's an exception - if they were created really close to each other (within few seconds) then- * they are probably part of the import and not created by hand - these OTOH should not benefit.- */- const {utcDateCreated} = candidateNote;+ * We want to improve the standing of notes which have been created in similar time to each other since+ * there's a good chance they are related.+ *+ * But there's an exception - if they were created really close to each other (within few seconds) then+ * they are probably part of the import and not created by hand - these OTOH should not benefit.+ */+ const { utcDateCreated } = candidateNote;if (utcDateCreated < dateLimits.minExcludedDate || utcDateCreated > dateLimits.maxExcludedDate) {if (utcDateCreated >= dateLimits.minDate && utcDateCreated <= dateLimits.maxDate) {@@ -384,9 +392,7 @@ async function findSimilarNotes(noteId: string) {}score += 1;- }- else if (utcDateCreated.substr(0, 10) === dateLimits.minDate.substr(0, 10)- || utcDateCreated.substr(0, 10) === dateLimits.maxDate.substr(0, 10)) {+ } else if (utcDateCreated.substr(0, 10) === dateLimits.minDate.substr(0, 10) || utcDateCreated.substr(0, 10) === dateLimits.maxDate.substr(0, 10)) {if (displayRewards) {console.log("Adding reward for same day of creation");}@@ -400,9 +406,7 @@ async function findSimilarNotes(noteId: string) {}for (const candidateNote of Object.values(becca.notes)) {- if (candidateNote.noteId === baseNote.noteId- || hasConnectingRelation(candidateNote, baseNote)- || hasConnectingRelation(baseNote, candidateNote)) {+ if (candidateNote.noteId === baseNote.noteId || hasConnectingRelation(candidateNote, baseNote) || hasConnectingRelation(baseNote, candidateNote)) {continue;}@@ -420,7 +424,7 @@ async function findSimilarNotes(noteId: string) {score -= 0.5; // archived penalization}- results.push({score, notePath, noteId: candidateNote.noteId});+ results.push({ score, notePath, noteId: candidateNote.noteId });}i++;@@ -430,13 +434,13 @@ async function findSimilarNotes(noteId: string) {}}- results.sort((a, b) => a.score > b.score ? -1 : 1);+ results.sort((a, b) => (a.score > b.score ? -1 : 1));if (DEBUG) {console.log("REWARD MAP", rewardMap);if (results.length >= 1) {- for (const {noteId} of results) {+ for (const { noteId } of results) {const note = becca.notes[noteId];displayRewards = true;diff --git a/src/etapi/app_info.ts b/src/etapi/app_info.tsindex 53cb50ee4b..ec5b781c2e 100644--- a/src/etapi/app_info.ts+++ b/src/etapi/app_info.ts@@ -1,9 +1,9 @@-import { Router } from 'express';+import { Router } from "express";import appInfo from "../services/app_info.js";import eu from "./etapi_utils.js";function register(router: Router) {- eu.route(router, 'get', '/etapi/app-info', (req, res, next) => {+ eu.route(router, "get", "/etapi/app-info", (req, res, next) => {res.status(200).json(appInfo);});}diff --git a/src/etapi/attachments.ts b/src/etapi/attachments.tsindex 949a6984d9..38b7d9603b 100644--- a/src/etapi/attachments.ts+++ b/src/etapi/attachments.ts@@ -3,21 +3,21 @@ import eu from "./etapi_utils.js";import mappers from "./mappers.js";import v from "./validators.js";import utils from "../services/utils.js";-import { Router } from 'express';-import { AttachmentRow } from '../becca/entities/rows.js';-import { ValidatorMap } from './etapi-interface.js';+import { Router } from "express";+import { AttachmentRow } from "../becca/entities/rows.js";+import { ValidatorMap } from "./etapi-interface.js";function register(router: Router) {const ALLOWED_PROPERTIES_FOR_CREATE_ATTACHMENT: ValidatorMap = {- 'ownerId': [v.notNull, v.isNoteId],- 'role': [v.notNull, v.isString],- 'mime': [v.notNull, v.isString],- 'title': [v.notNull, v.isString],- 'position': [v.notNull, v.isInteger],- 'content': [v.isString],+ ownerId: [v.notNull, v.isNoteId],+ role: [v.notNull, v.isString],+ mime: [v.notNull, v.isString],+ title: [v.notNull, v.isString],+ position: [v.notNull, v.isInteger],+ content: [v.isString]};- eu.route(router, 'post', '/etapi/attachments', (req, res, next) => {+ eu.route(router, "post", "/etapi/attachments", (req, res, next) => {const _params: Partial<AttachmentRow> = {};eu.validateAndPatch(_params, req.body, ALLOWED_PROPERTIES_FOR_CREATE_ATTACHMENT);const params = _params as AttachmentRow;@@ -30,26 +30,25 @@ function register(router: Router) {const attachment = note.saveAttachment(params);res.status(201).json(mappers.mapAttachmentToPojo(attachment));- }- catch (e: any) {+ } catch (e: any) {throw new eu.EtapiError(500, eu.GENERIC_CODE, e.message);}});- eu.route(router, 'get', '/etapi/attachments/:attachmentId', (req, res, next) => {+ eu.route(router, "get", "/etapi/attachments/:attachmentId", (req, res, next) => {const attachment = eu.getAndCheckAttachment(req.params.attachmentId);res.json(mappers.mapAttachmentToPojo(attachment));});const ALLOWED_PROPERTIES_FOR_PATCH = {- 'role': [v.notNull, v.isString],- 'mime': [v.notNull, v.isString],- 'title': [v.notNull, v.isString],- 'position': [v.notNull, v.isInteger],+ role: [v.notNull, v.isString],+ mime: [v.notNull, v.isString],+ title: [v.notNull, v.isString],+ position: [v.notNull, v.isInteger]};- eu.route(router, 'patch', '/etapi/attachments/:attachmentId', (req, res, next) => {+ eu.route(router, "patch", "/etapi/attachments/:attachmentId", (req, res, next) => {const attachment = eu.getAndCheckAttachment(req.params.attachmentId);if (attachment.isProtected) {@@ -62,7 +61,7 @@ function register(router: Router) {res.json(mappers.mapAttachmentToPojo(attachment));});- eu.route(router, 'get', '/etapi/attachments/:attachmentId/content', (req, res, next) => {+ eu.route(router, "get", "/etapi/attachments/:attachmentId/content", (req, res, next) => {const attachment = eu.getAndCheckAttachment(req.params.attachmentId);if (attachment.isProtected) {@@ -71,15 +70,15 @@ function register(router: Router) {const filename = utils.formatDownloadTitle(attachment.title, attachment.role, attachment.mime);- res.setHeader('Content-Disposition', utils.getContentDisposition(filename));+ res.setHeader("Content-Disposition", utils.getContentDisposition(filename));res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");- res.setHeader('Content-Type', attachment.mime);+ res.setHeader("Content-Type", attachment.mime);res.send(attachment.getContent());});- eu.route(router, 'put', '/etapi/attachments/:attachmentId/content', (req, res, next) => {+ eu.route(router, "put", "/etapi/attachments/:attachmentId/content", (req, res, next) => {const attachment = eu.getAndCheckAttachment(req.params.attachmentId);if (attachment.isProtected) {@@ -91,7 +90,7 @@ function register(router: Router) {return res.sendStatus(204);});- eu.route(router, 'delete', '/etapi/attachments/:attachmentId', (req, res, next) => {+ eu.route(router, "delete", "/etapi/attachments/:attachmentId", (req, res, next) => {const attachment = becca.getAttachment(req.params.attachmentId);if (!attachment) {diff --git a/src/etapi/attributes.ts b/src/etapi/attributes.tsindex 4d749744ba..94e2e23ec7 100644--- a/src/etapi/attributes.ts+++ b/src/etapi/attributes.ts@@ -3,29 +3,29 @@ import eu from "./etapi_utils.js";import mappers from "./mappers.js";import attributeService from "../services/attributes.js";import v from "./validators.js";-import { Router } from 'express';-import { AttributeRow } from '../becca/entities/rows.js';-import { ValidatorMap } from './etapi-interface.js';+import { Router } from "express";+import { AttributeRow } from "../becca/entities/rows.js";+import { ValidatorMap } from "./etapi-interface.js";function register(router: Router) {- eu.route(router, 'get', '/etapi/attributes/:attributeId', (req, res, next) => {+ eu.route(router, "get", "/etapi/attributes/:attributeId", (req, res, next) => {const attribute = eu.getAndCheckAttribute(req.params.attributeId);res.json(mappers.mapAttributeToPojo(attribute));});const ALLOWED_PROPERTIES_FOR_CREATE_ATTRIBUTE: ValidatorMap = {- 'attributeId': [v.mandatory, v.notNull, v.isValidEntityId],- 'noteId': [v.mandatory, v.notNull, v.isNoteId],- 'type': [v.mandatory, v.notNull, v.isAttributeType],- 'name': [v.mandatory, v.notNull, v.isString],- 'value': [v.notNull, v.isString],- 'isInheritable': [v.notNull, v.isBoolean],- 'position': [v.notNull, v.isInteger]+ attributeId: [v.mandatory, v.notNull, v.isValidEntityId],+ noteId: [v.mandatory, v.notNull, v.isNoteId],+ type: [v.mandatory, v.notNull, v.isAttributeType],+ name: [v.mandatory, v.notNull, v.isString],+ value: [v.notNull, v.isString],+ isInheritable: [v.notNull, v.isBoolean],+ position: [v.notNull, v.isInteger]};- eu.route(router, 'post', '/etapi/attributes', (req, res, next) => {- if (req.body.type === 'relation') {+ eu.route(router, "post", "/etapi/attributes", (req, res, next) => {+ if (req.body.type === "relation") {eu.getAndCheckNote(req.body.value);}@@ -37,27 +37,26 @@ function register(router: Router) {const attr = attributeService.createAttribute(params);res.status(201).json(mappers.mapAttributeToPojo(attr));- }- catch (e: any) {+ } catch (e: any) {throw new eu.EtapiError(500, eu.GENERIC_CODE, e.message);}});const ALLOWED_PROPERTIES_FOR_PATCH_LABEL = {- 'value': [v.notNull, v.isString],- 'position': [v.notNull, v.isInteger]+ value: [v.notNull, v.isString],+ position: [v.notNull, v.isInteger]};const ALLOWED_PROPERTIES_FOR_PATCH_RELATION = {- 'position': [v.notNull, v.isInteger]+ position: [v.notNull, v.isInteger]};- eu.route(router, 'patch', '/etapi/attributes/:attributeId', (req, res, next) => {+ eu.route(router, "patch", "/etapi/attributes/:attributeId", (req, res, next) => {const attribute = eu.getAndCheckAttribute(req.params.attributeId);- if (attribute.type === 'label') {+ if (attribute.type === "label") {eu.validateAndPatch(attribute, req.body, ALLOWED_PROPERTIES_FOR_PATCH_LABEL);- } else if (attribute.type === 'relation') {+ } else if (attribute.type === "relation") {eu.getAndCheckNote(req.body.value);eu.validateAndPatch(attribute, req.body, ALLOWED_PROPERTIES_FOR_PATCH_RELATION);@@ -68,7 +67,7 @@ function register(router: Router) {res.json(mappers.mapAttributeToPojo(attribute));});- eu.route(router, 'delete', '/etapi/attributes/:attributeId', (req, res, next) => {+ eu.route(router, "delete", "/etapi/attributes/:attributeId", (req, res, next) => {const attribute = becca.getAttribute(req.params.attributeId);if (!attribute) {diff --git a/src/etapi/auth.ts b/src/etapi/auth.tsindex 4ca2fb45bf..ce44eaab10 100644--- a/src/etapi/auth.ts+++ b/src/etapi/auth.ts@@ -2,24 +2,24 @@ import becca from "../becca/becca.js";import eu from "./etapi_utils.js";import passwordEncryptionService from "../services/encryption/password_encryption.js";import etapiTokenService from "../services/etapi_tokens.js";-import { RequestHandler, Router } from 'express';+import { RequestHandler, Router } from "express";function register(router: Router, loginMiddleware: RequestHandler[]) {- eu.NOT_AUTHENTICATED_ROUTE(router, 'post', '/etapi/auth/login', loginMiddleware, (req, res, next) => {- const {password, tokenName} = req.body;+ eu.NOT_AUTHENTICATED_ROUTE(router, "post", "/etapi/auth/login", loginMiddleware, (req, res, next) => {+ const { password, tokenName } = req.body;if (!passwordEncryptionService.verifyPassword(password)) {throw new eu.EtapiError(401, "WRONG_PASSWORD", "Wrong password.");}- const {authToken} = etapiTokenService.createToken(tokenName || "ETAPI login");+ const { authToken } = etapiTokenService.createToken(tokenName || "ETAPI login");res.status(201).json({authToken});});- eu.route(router, 'post', '/etapi/auth/logout', (req, res, next) => {+ eu.route(router, "post", "/etapi/auth/logout", (req, res, next) => {const parsed = etapiTokenService.parseAuthToken(req.headers.authorization);if (!parsed || !parsed.etapiTokenId) {@@ -41,4 +41,4 @@ function register(router: Router, loginMiddleware: RequestHandler[]) {export default {register-}+};diff --git a/src/etapi/backup.ts b/src/etapi/backup.tsindex f1b80630de..3b9f3f8746 100644--- a/src/etapi/backup.ts+++ b/src/etapi/backup.ts@@ -4,7 +4,7 @@ import eu from "./etapi_utils.js";import backupService from "../services/backup.js";function register(router: Router) {- eu.route(router, 'put', '/etapi/backup/:backupName', async (req, res, next) => {+ eu.route(router, "put", "/etapi/backup/:backupName", async (req, res, next) => {await backupService.backupNow(req.params.backupName);res.sendStatus(204);diff --git a/src/etapi/branches.ts b/src/etapi/branches.tsindex 8a6b61e2f4..ab1425947e 100644--- a/src/etapi/branches.ts+++ b/src/etapi/branches.ts@@ -9,21 +9,21 @@ import v from "./validators.js";import { BranchRow } from "../becca/entities/rows.js";function register(router: Router) {- eu.route(router, 'get', '/etapi/branches/:branchId', (req, res, next) => {+ eu.route(router, "get", "/etapi/branches/:branchId", (req, res, next) => {const branch = eu.getAndCheckBranch(req.params.branchId);res.json(mappers.mapBranchToPojo(branch));});const ALLOWED_PROPERTIES_FOR_CREATE_BRANCH = {- 'noteId': [v.mandatory, v.notNull, v.isNoteId],- 'parentNoteId': [v.mandatory, v.notNull, v.isNoteId],- 'notePosition': [v.notNull, v.isInteger],- 'prefix': [v.isString],- 'isExpanded': [v.notNull, v.isBoolean]+ noteId: [v.mandatory, v.notNull, v.isNoteId],+ parentNoteId: [v.mandatory, v.notNull, v.isNoteId],+ notePosition: [v.notNull, v.isInteger],+ prefix: [v.isString],+ isExpanded: [v.notNull, v.isBoolean]};- eu.route(router, 'post', '/etapi/branches', (req, res, next) => {+ eu.route(router, "post", "/etapi/branches", (req, res, next) => {const _params = {};eu.validateAndPatch(_params, req.body, ALLOWED_PROPERTIES_FOR_CREATE_BRANCH);const params: BranchRow = _params as BranchRow;@@ -49,12 +49,12 @@ function register(router: Router) {});const ALLOWED_PROPERTIES_FOR_PATCH = {- 'notePosition': [v.notNull, v.isInteger],- 'prefix': [v.isString],- 'isExpanded': [v.notNull, v.isBoolean]+ notePosition: [v.notNull, v.isInteger],+ prefix: [v.isString],+ isExpanded: [v.notNull, v.isBoolean]};- eu.route(router, 'patch', '/etapi/branches/:branchId', (req, res, next) => {+ eu.route(router, "patch", "/etapi/branches/:branchId", (req, res, next) => {const branch = eu.getAndCheckBranch(req.params.branchId);eu.validateAndPatch(branch, req.body, ALLOWED_PROPERTIES_FOR_PATCH);@@ -63,7 +63,7 @@ function register(router: Router) {res.json(mappers.mapBranchToPojo(branch));});- eu.route(router, 'delete', '/etapi/branches/:branchId', (req, res, next) => {+ eu.route(router, "delete", "/etapi/branches/:branchId", (req, res, next) => {const branch = becca.getBranch(req.params.branchId);if (!branch) {@@ -75,7 +75,7 @@ function register(router: Router) {res.sendStatus(204);});- eu.route(router, 'post', '/etapi/refresh-note-ordering/:parentNoteId', (req, res, next) => {+ eu.route(router, "post", "/etapi/refresh-note-ordering/:parentNoteId", (req, res, next) => {eu.getAndCheckNote(req.params.parentNoteId);entityChangesService.putNoteReorderingEntityChange(req.params.parentNoteId, "etapi");diff --git a/src/etapi/etapi-interface.ts b/src/etapi/etapi-interface.tsindex b4e8169915..0d866690ae 100644--- a/src/etapi/etapi-interface.ts+++ b/src/etapi/etapi-interface.ts@@ -1,3 +1,3 @@-export type ValidatorFunc = (obj: unknown) => (string | undefined);+export type ValidatorFunc = (obj: unknown) => string | undefined;export type ValidatorMap = Record<string, ValidatorFunc[]>;diff --git a/src/etapi/etapi.openapi.yaml b/src/etapi/etapi.openapi.yamlindex 97a8977dea..eed39fd809 100644--- a/src/etapi/etapi.openapi.yaml+++ b/src/etapi/etapi.openapi.yaml@@ -1,1168 +1,1168 @@openapi: "3.0.3"info:- version: 1.0.0- title: ETAPI- description: External Trilium API- contact:- name: zadam- email: [email protected]- url: https://github.com/zadam/trilium- license:- name: Apache 2.0- url: https://www.apache.org/licenses/LICENSE-2.0.html+ version: 1.0.0+ title: ETAPI+ description: External Trilium API+ contact:+ name: zadam+ email: [email protected]+ url: https://github.com/zadam/trilium+ license:+ name: Apache 2.0+ url: https://www.apache.org/licenses/LICENSE-2.0.htmlservers:- - url: http://localhost:37740/etapi- - url: http://localhost:8080/etapi+ - url: http://localhost:37740/etapi+ - url: http://localhost:8080/etapisecurity:- - EtapiTokenAuth: []- - EtapiBasicAuth: []+ - EtapiTokenAuth: []+ - EtapiBasicAuth: []paths:- /create-note:- post:- description: Create a note and place it into the note tree- operationId: createNote- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/CreateNoteDef'- responses:- '201':- description: note created- content:- application/json; charset=utf-8:+ /create-note:+ post:+ description: Create a note and place it into the note tree+ operationId: createNote+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/CreateNoteDef"+ responses:+ "201":+ description: note created+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/NoteWithBranch"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /notes:+ get:+ description: Search notes+ operationId: searchNotes+ parameters:+ - name: search+ in: query+ required: true+ description: search query string as described in https://triliumnext.github.io/Docs/Wiki/search.html+ schema:+ type: string+ examples:+ fulltext:+ summary: Fulltext search for keywords (not exact match)+ value: "towers tolkien"+ fulltextExactMatch:+ summary: Fulltext search for exact match (notice the double quotes)+ value: '"Two Towers"'+ fulltextWithLabel:+ summary: Fulltext search for keyword AND matching label+ value: "towers #book"+ - name: fastSearch+ in: query+ required: false+ description: enable fast search (fulltext doesn't look into content)+ schema:+ type: boolean+ default: false+ - name: includeArchivedNotes+ in: query+ required: false+ description: search by default ignores archived notes. Set to 'true' to includes archived notes into search results.+ schema:+ type: boolean+ default: false+ - name: ancestorNoteId+ in: query+ required: false+ description: search only in a subtree identified by the subtree noteId. By default whole tree is searched.+ schema:+ $ref: "#/components/schemas/EntityId"+ - name: ancestorDepth+ in: query+ required: false+ description: define how deep in the tree should the notes be searched+ schema:+ type: string+ examples:+ directChildren:+ summary: depth of exactly 1 (direct children) to the ancestor (root if not set)+ value: eq1+ grandGrandChildren:+ summary: depth of exactly 3 to the ancestor (root if not set)+ value: eq3+ lessThan4:+ summary: depth less than 4 (so 1, 2, 3) to the ancestor (root if not set)+ value: lt4+ greaterThan2:+ summary: depth greater than 2 (so 3, 4, 5, 6...) to the ancestor (root if not set)+ value: gt4+ - name: orderBy+ in: query+ required: false+ description: name of the property/label to order search results by+ schema:+ type: string+ example:+ - title+ - "#publicationDate"+ - isProtected+ - isArchived+ - dateCreated+ - dateModified+ - utcDateCreated+ - utcDateModified+ - parentCount+ - childrenCount+ - attributeCount+ - labelCount+ - ownedLabelCount+ - relationCount+ - ownedRelationCount+ - relationCountIncludingLinks+ - ownedRelationCountIncludingLinks+ - targetRelationCount+ - targetRelationCountIncludingLinks+ - contentSize+ - contentAndAttachmentsSize+ - contentAndAttachmentsAndRevisionsSize+ - revisionCount+ - name: orderDirection+ in: query+ required: false+ description: order direction, ascending or descending+ schema:+ type: string+ default: asc+ enum:+ - asc+ - desc+ - name: limit+ in: query+ required: false+ description: limit the number of results you want to receive+ schema:+ type: integer+ example: 10+ - name: debug+ in: query+ required: false+ description: set to true to get debug information in the response (search query parsing)+ schema:+ type: boolean+ default: false+ responses:+ "200":+ description: search response+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/SearchResponse"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /notes/{noteId}:+ parameters:+ - name: noteId+ in: path+ required: trueschema:- $ref: '#/components/schemas/NoteWithBranch'- default:- description: unexpected error- content:- application/json; charset=utf-8:+ $ref: "#/components/schemas/EntityId"+ get:+ description: Returns a note identified by its ID+ operationId: getNoteById+ responses:+ "200":+ description: note response+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Note"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ patch:+ description: patch a note identified by the noteId with changes in the body+ operationId: patchNoteById+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/Note"+ responses:+ "200":+ description: note updated+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Note"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ delete:+ description: deletes a single note based on the noteId supplied+ operationId: deleteNoteById+ responses:+ "204":+ description: note deleted+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /notes/{noteId}/content:+ parameters:+ - name: noteId+ in: path+ required: trueschema:- $ref: '#/components/schemas/Error'- /notes:- get:- description: Search notes- operationId: searchNotes- parameters:- - name: search- in: query- required: true- description: search query string as described in https://triliumnext.github.io/Docs/Wiki/search.html- schema:- type: string- examples:- fulltext:- summary: Fulltext search for keywords (not exact match)- value: 'towers tolkien'- fulltextExactMatch:- summary: Fulltext search for exact match (notice the double quotes)- value: '"Two Towers"'- fulltextWithLabel:- summary: Fulltext search for keyword AND matching label- value: 'towers #book'- - name: fastSearch- in: query- required: false- description: enable fast search (fulltext doesn't look into content)- schema:- type: boolean- default: false- - name: includeArchivedNotes- in: query- required: false- description: search by default ignores archived notes. Set to 'true' to includes archived notes into search results.- schema:- type: boolean- default: false- - name: ancestorNoteId- in: query- required: false- description: search only in a subtree identified by the subtree noteId. By default whole tree is searched.- schema:- $ref: '#/components/schemas/EntityId'- - name: ancestorDepth- in: query- required: false- description: define how deep in the tree should the notes be searched- schema:- type: string- examples:- directChildren:- summary: depth of exactly 1 (direct children) to the ancestor (root if not set)- value: eq1- grandGrandChildren:- summary: depth of exactly 3 to the ancestor (root if not set)- value: eq3- lessThan4:- summary: depth less than 4 (so 1, 2, 3) to the ancestor (root if not set)- value: lt4- greaterThan2:- summary: depth greater than 2 (so 3, 4, 5, 6...) to the ancestor (root if not set)- value: gt4- - name: orderBy- in: query- required: false- description: name of the property/label to order search results by- schema:- type: string- example:- - title- - '#publicationDate'- - isProtected- - isArchived- - dateCreated- - dateModified- - utcDateCreated- - utcDateModified- - parentCount- - childrenCount- - attributeCount- - labelCount- - ownedLabelCount- - relationCount- - ownedRelationCount- - relationCountIncludingLinks- - ownedRelationCountIncludingLinks- - targetRelationCount- - targetRelationCountIncludingLinks- - contentSize- - contentAndAttachmentsSize- - contentAndAttachmentsAndRevisionsSize- - revisionCount- - name: orderDirection- in: query- required: false- description: order direction, ascending or descending- schema:- type: string- default: asc- enum:- - asc- - desc- - name: limit- in: query- required: false- description: limit the number of results you want to receive- schema:- type: integer- example: 10- - name: debug- in: query- required: false- description: set to true to get debug information in the response (search query parsing)- schema:- type: boolean- default: false- responses:- '200':- description: search response- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/SearchResponse'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /notes/{noteId}:- parameters:- - name: noteId- in: path- required: true- schema:- $ref: '#/components/schemas/EntityId'- get:- description: Returns a note identified by its ID- operationId: getNoteById- responses:- '200':- description: note response- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Note'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- patch:- description: patch a note identified by the noteId with changes in the body- operationId: patchNoteById- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/Note'- responses:- '200':- description: note updated- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Note'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- delete:- description: deletes a single note based on the noteId supplied- operationId: deleteNoteById- responses:- '204':- description: note deleted- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /notes/{noteId}/content:- parameters:- - name: noteId- in: path- required: true- schema:- $ref: '#/components/schemas/EntityId'- get:- description: Returns note content identified by its ID- operationId: getNoteContent- responses:- '200':- description: note content response- content:- text/html:- schema:- type: string- put:- description: Updates note content identified by its ID- operationId: putNoteContentById- requestBody:- description: html content of note- required: true- content:- text/plain:- schema:- type: string- responses:- '204':- description: note content updated- /notes/{noteId}/export:- parameters:- - name: noteId- in: path- required: true- schema:- $ref: '#/components/schemas/EntityId'- - name: format- in: query- required: false- schema:- enum:- - html- - markdown- default: html- get:- description: Exports ZIP file export of a given note subtree. To export whole document, use "root" for noteId- operationId: exportNoteSubtree- responses:- '200':- description: export ZIP file- content:- application/zip:- schema:- type: string- format: binary- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /notes/{noteId}/import:- parameters:- - name: noteId- in: path- required: true- schema:- $ref: '#/components/schemas/EntityId'- post:- description: Imports ZIP file into a given note.- operationId: importZip- responses:- '201':- description: note created- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/NoteWithBranch'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /notes/{noteId}/revision:- parameters:- - name: noteId- in: path- required: true- schema:- $ref: '#/components/schemas/EntityId'- - name: format- in: query- required: false- schema:- enum:- - html- - markdown- default: html- post:- description: Create a note revision for the given note- operationId: createRevision- responses:- '204':- description: revision has been created- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /branches:- post:- description: >- Create a branch (clone a note to a different location in the tree).- In case there is a branch between parent note and child note already,- then this will update the existing branch with prefix, notePosition and isExpanded.- operationId: postBranch- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/Branch'- responses:- '200':- description: branch updated (branch between parent note and child note already existed)- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Branch'- '201':- description: branch created- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Branch'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /branches/{branchId}:- parameters:- - name: branchId- in: path- required: true- schema:- $ref: '#/components/schemas/EntityId'- get:- description: Returns a branch identified by its ID- operationId: getBranchById- responses:- '200':- description: branch response- content:- application/json; charset=utf-8:+ $ref: "#/components/schemas/EntityId"+ get:+ description: Returns note content identified by its ID+ operationId: getNoteContent+ responses:+ "200":+ description: note content response+ content:+ text/html:+ schema:+ type: string+ put:+ description: Updates note content identified by its ID+ operationId: putNoteContentById+ requestBody:+ description: html content of note+ required: true+ content:+ text/plain:+ schema:+ type: string+ responses:+ "204":+ description: note content updated+ /notes/{noteId}/export:+ parameters:+ - name: noteId+ in: path+ required: trueschema:- $ref: '#/components/schemas/Branch'- default:- description: unexpected error- content:- application/json; charset=utf-8:+ $ref: "#/components/schemas/EntityId"+ - name: format+ in: query+ required: falseschema:- $ref: '#/components/schemas/Error'- patch:- description: patch a branch identified by the branchId with changes in the body. Only prefix and notePosition can be updated. If you want to update other properties, you need to delete the old branch and create a new one.- operationId: patchBranchById- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/Branch'- responses:- '200':- description: branch updated- content:- application/json; charset=utf-8:+ enum:+ - html+ - markdown+ default: html+ get:+ description: Exports ZIP file export of a given note subtree. To export whole document, use "root" for noteId+ operationId: exportNoteSubtree+ responses:+ "200":+ description: export ZIP file+ content:+ application/zip:+ schema:+ type: string+ format: binary+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /notes/{noteId}/import:+ parameters:+ - name: noteId+ in: path+ required: trueschema:- $ref: '#/components/schemas/Branch'- default:- description: unexpected error- content:- application/json; charset=utf-8:+ $ref: "#/components/schemas/EntityId"+ post:+ description: Imports ZIP file into a given note.+ operationId: importZip+ responses:+ "201":+ description: note created+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/NoteWithBranch"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /notes/{noteId}/revision:+ parameters:+ - name: noteId+ in: path+ required: trueschema:- $ref: '#/components/schemas/Error'- delete:- description: >- deletes a branch based on the branchId supplied. If this is the last branch of the (child) note,- then the note is deleted as well.- operationId: deleteBranchById- responses:- '204':- description: branch deleted- default:- description: unexpected error- content:- application/json; charset=utf-8:+ $ref: "#/components/schemas/EntityId"+ - name: format+ in: query+ required: falseschema:- $ref: '#/components/schemas/Error'- /attachments:- post:- description: create an attachment- operationId: postAttachment- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/CreateAttachment'- responses:- '201':- description: attachment created- content:- application/json; charset=utf-8:+ enum:+ - html+ - markdown+ default: html+ post:+ description: Create a note revision for the given note+ operationId: createRevision+ responses:+ "204":+ description: revision has been created+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /branches:+ post:+ description: >+ Create a branch (clone a note to a different location in the tree).+ In case there is a branch between parent note and child note already,+ then this will update the existing branch with prefix, notePosition and isExpanded.+ operationId: postBranch+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/Branch"+ responses:+ "200":+ description: branch updated (branch between parent note and child note already existed)+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Branch"+ "201":+ description: branch created+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Branch"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /branches/{branchId}:+ parameters:+ - name: branchId+ in: path+ required: trueschema:- $ref: '#/components/schemas/Attachment'- default:- description: unexpected error- content:- application/json; charset=utf-8:+ $ref: "#/components/schemas/EntityId"+ get:+ description: Returns a branch identified by its ID+ operationId: getBranchById+ responses:+ "200":+ description: branch response+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Branch"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ patch:+ description: patch a branch identified by the branchId with changes in the body. Only prefix and notePosition can be updated. If you want to update other properties, you need to delete the old branch and create a new one.+ operationId: patchBranchById+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/Branch"+ responses:+ "200":+ description: branch updated+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Branch"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ delete:+ description: >+ deletes a branch based on the branchId supplied. If this is the last branch of the (child) note,+ then the note is deleted as well.+ operationId: deleteBranchById+ responses:+ "204":+ description: branch deleted+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /attachments:+ post:+ description: create an attachment+ operationId: postAttachment+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/CreateAttachment"+ responses:+ "201":+ description: attachment created+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Attachment"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /attachments/{attachmentId}:+ parameters:+ - name: attachmentId+ in: path+ required: trueschema:- $ref: '#/components/schemas/Error'- /attachments/{attachmentId}:- parameters:- - name: attachmentId- in: path- required: true- schema:- $ref: '#/components/schemas/EntityId'- get:- description: Returns an attachment identified by its ID- operationId: getAttachmentById- responses:- '200':- description: attachment response- content:- application/json; charset=utf-8:+ $ref: "#/components/schemas/EntityId"+ get:+ description: Returns an attachment identified by its ID+ operationId: getAttachmentById+ responses:+ "200":+ description: attachment response+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Attachment"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ patch:+ description: patch an attachment identified by the attachmentId with changes in the body. Only role, mime, title, and position are patchable.+ operationId: patchAttachmentById+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/Attachment"+ responses:+ "200":+ description: attribute updated+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Attachment"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ delete:+ description: deletes an attachment based on the attachmentId supplied.+ operationId: deleteAttachmentById+ responses:+ "204":+ description: attachment deleted+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /attachments/{attachmentId}/content:+ parameters:+ - name: attachmentId+ in: path+ required: trueschema:- $ref: '#/components/schemas/Attachment'- default:- description: unexpected error- content:- application/json; charset=utf-8:+ $ref: "#/components/schemas/EntityId"+ get:+ description: Returns attachment content identified by its ID+ operationId: getAttachmentContent+ responses:+ "200":+ description: attachment content response+ content:+ text/html:+ schema:+ type: string+ put:+ description: Updates attachment content identified by its ID+ operationId: putAttachmentContentById+ requestBody:+ description: html content of attachment+ required: true+ content:+ text/plain:+ schema:+ type: string+ responses:+ "204":+ description: attachment content updated+ /attributes:+ post:+ description: create an attribute for a given note+ operationId: postAttribute+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/Attribute"+ responses:+ "201":+ description: attribute created+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Attribute"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /attributes/{attributeId}:+ parameters:+ - name: attributeId+ in: path+ required: trueschema:- $ref: '#/components/schemas/Error'- patch:- description: patch an attachment identified by the attachmentId with changes in the body. Only role, mime, title, and position are patchable.- operationId: patchAttachmentById- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/Attachment'- responses:- '200':- description: attribute updated- content:- application/json; charset=utf-8:+ $ref: "#/components/schemas/EntityId"+ get:+ description: Returns an attribute identified by its ID+ operationId: getAttributeById+ responses:+ "200":+ description: attribute response+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Attribute"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ patch:+ description: patch an attribute identified by the attributeId with changes in the body. For labels, only value and position can be updated. For relations, only position can be updated. If you want to modify other properties, you need to delete the old attribute and create a new one.+ operationId: patchAttributeById+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/Attribute"+ responses:+ "200":+ description: attribute updated+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Attribute"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ delete:+ description: deletes an attribute based on the attributeId supplied.+ operationId: deleteAttributeById+ responses:+ "204":+ description: attribute deleted+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /refresh-note-ordering/{parentNoteId}:+ parameters:+ - name: parentNoteId+ in: path+ required: trueschema:- $ref: '#/components/schemas/Attachment'- default:- description: unexpected error- content:- application/json; charset=utf-8:+ $ref: "#/components/schemas/EntityId"+ post:+ description: >+ notePositions in branches are not automatically pushed to connected clients and need a specific instruction.+ If you want your changes to be in effect immediately, call this service after setting branches' notePosition.+ Note that you need to supply "parentNoteId" of branch(es) with changed positions.+ operationId: postRefreshNoteOrdering+ responses:+ "204":+ description: note ordering will be asynchronously updated in all connected clients+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /inbox/{date}:+ get:+ description: >+ returns an "inbox" note, into which note can be created. Date will be used depending on whether the inbox+ is a fixed note (identified with #inbox label) or a day note in a journal.+ operationId: getInboxNote+ parameters:+ - name: date+ in: path+ required: true+ schema:+ type: string+ format: date+ example: 2022-02-22+ responses:+ "200":+ description: inbox note+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Note"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /calendar/days/{date}:+ get:+ description: returns a day note for a given date. Gets created if doesn't exist.+ operationId: getDayNote+ parameters:+ - name: date+ in: path+ required: true+ schema:+ type: string+ format: date+ example: 2022-02-22+ responses:+ "200":+ description: day note+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Note"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /calendar/weeks/{date}:+ get:+ description: returns a week note for a given date. Gets created if doesn't exist.+ operationId: getWeekNote+ parameters:+ - name: date+ in: path+ required: true+ schema:+ type: string+ format: date+ example: 2022-02-22+ responses:+ "200":+ description: week note+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Note"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /calendar/months/{month}:+ get:+ description: returns a week note for a given date. Gets created if doesn't exist.+ operationId: getMonthNote+ parameters:+ - name: month+ in: path+ required: true+ schema:+ type: string+ pattern: "[0-9]{4}-[0-9]{2}"+ example: 2022-02+ responses:+ "200":+ description: month note+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Note"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /calendar/years/{year}:+ get:+ description: returns a week note for a given date. Gets created if doesn't exist.+ operationId: getYearNote+ parameters:+ - name: year+ in: path+ required: true+ schema:+ type: string+ pattern: "[0-9]{4}-[0-9]{2}"+ example: 2022-02+ responses:+ "200":+ description: year note+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Note"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /auth/login:+ post:+ description: get an ETAPI token based on password for further use with ETAPI+ operationId: login+ security: [] # no token based auth for login endpoint+ requestBody:+ required: true+ content:+ application/json:+ schema:+ properties:+ password:+ type: string+ description: user's password used to e.g. login to Trilium server and/or protect notes+ responses:+ "201":+ description: auth token+ content:+ application/json; charset=utf-8:+ schema:+ properties:+ authToken:+ type: string+ example: Bc4bFn0Ffiok_4NpbVCDnFz7B2WU+pdhW8B5Ne3DiR5wXrEyqdjgRIsk=+ "429":+ description: Client IP has been blacklisted because too many requests (possibly failed authentications) were made within a short time frame, try again later+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /auth/logout:+ post:+ description: logout (delete/deactivate) an ETAPI token+ operationId: logout+ responses:+ "204":+ description: logout successful+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /app-info:+ get:+ description: returns information about the running Trilium instance+ operationId: getAppInfo+ responses:+ "200":+ description: app info+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/AppInfo"+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+ /backup/{backupName}:+ parameters:+ - name: backupName+ in: path+ required: true+ description: If the backupName is e.g. "now", then the backup will be written to "backup-now.db" fileschema:- $ref: '#/components/schemas/Error'- delete:- description: deletes an attachment based on the attachmentId supplied.- operationId: deleteAttachmentById- responses:- '204':- description: attachment deleted- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /attachments/{attachmentId}/content:- parameters:- - name: attachmentId- in: path- required: true- schema:- $ref: '#/components/schemas/EntityId'- get:- description: Returns attachment content identified by its ID- operationId: getAttachmentContent- responses:- '200':- description: attachment content response- content:- text/html:- schema:- type: string- put:- description: Updates attachment content identified by its ID- operationId: putAttachmentContentById- requestBody:- description: html content of attachment- required: true- content:- text/plain:- schema:- type: string- responses:- '204':- description: attachment content updated- /attributes:- post:- description: create an attribute for a given note- operationId: postAttribute- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/Attribute'- responses:- '201':- description: attribute created- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Attribute'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /attributes/{attributeId}:- parameters:- - name: attributeId- in: path- required: true- schema:- $ref: '#/components/schemas/EntityId'- get:- description: Returns an attribute identified by its ID- operationId: getAttributeById- responses:- '200':- description: attribute response- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Attribute'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- patch:- description: patch an attribute identified by the attributeId with changes in the body. For labels, only value and position can be updated. For relations, only position can be updated. If you want to modify other properties, you need to delete the old attribute and create a new one.- operationId: patchAttributeById- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/Attribute'- responses:- '200':- description: attribute updated- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Attribute'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- delete:- description: deletes an attribute based on the attributeId supplied.- operationId: deleteAttributeById- responses:- '204':- description: attribute deleted- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /refresh-note-ordering/{parentNoteId}:- parameters:- - name: parentNoteId- in: path- required: true- schema:- $ref: '#/components/schemas/EntityId'- post:- description: >- notePositions in branches are not automatically pushed to connected clients and need a specific instruction.- If you want your changes to be in effect immediately, call this service after setting branches' notePosition.- Note that you need to supply "parentNoteId" of branch(es) with changed positions.- operationId: postRefreshNoteOrdering- responses:- '204':- description: note ordering will be asynchronously updated in all connected clients- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /inbox/{date}:- get:- description: >- returns an "inbox" note, into which note can be created. Date will be used depending on whether the inbox- is a fixed note (identified with #inbox label) or a day note in a journal.- operationId: getInboxNote- parameters:- - name: date- in: path- required: true- schema:- type: string- format: date- example: 2022-02-22- responses:- '200':- description: inbox note- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Note'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /calendar/days/{date}:- get:- description: returns a day note for a given date. Gets created if doesn't exist.- operationId: getDayNote- parameters:- - name: date- in: path- required: true- schema:+ $ref: "#/components/schemas/StringId"+ put:+ description: Create a database backup under a given name+ operationId: createBackup+ responses:+ "204":+ description: backup has been created+ default:+ description: unexpected error+ content:+ application/json; charset=utf-8:+ schema:+ $ref: "#/components/schemas/Error"+components:+ securitySchemes:+ EtapiTokenAuth:+ type: apiKey+ in: header+ name: Authorization+ EtapiBasicAuth:+ type: http+ scheme: basic+ description: >+ Basic Auth where username is arbitrary string (e.g. "trilium", not checked),+ username is the ETAPI token.+ To emphasize, do not use Trilium password here (won't work), only the generated+ ETAPI token (from Options -> ETAPI)+ schemas:+ CreateNoteDef:+ type: object+ required:+ - parentNoteId+ - title+ - type+ - content+ properties:+ parentNoteId:+ $ref: "#/components/schemas/EntityId"+ description: Note ID of the parent note in the tree+ title:+ type: string+ type:+ type: string+ enum:+ - text+ - code+ - file+ - image+ - search+ - book+ - relationMap+ - render+ mime:+ type: string+ description: this needs to be specified only for note types 'code', 'file', 'image'.+ example: application/json+ content:+ type: string+ notePosition:+ type: integer+ description: >+ Position of the note in the parent. Normal ordering is 10, 20, 30 ...+ So if you want to create a note on the first position, use e.g. 5, for second position 15, for last e.g. 1000000+ prefix:+ type: string+ description: >+ Prefix is branch (placement) specific title prefix for the note.+ Let's say you have your note placed into two different places in the tree,+ but you want to change the title a bit in one of the placements. For this you can use prefix.+ isExpanded:+ type: boolean+ description: true if this note (as a folder) should appear expanded+ noteId:+ $ref: "#/components/schemas/EntityId"+ description: DON'T specify unless you want to force a specific noteId+ branchId:+ $ref: "#/components/schemas/EntityId"+ description: DON'T specify unless you want to force a specific branchId+ dateCreated:+ $ref: "#/components/schemas/LocalDateTime"+ description: Local timestap of the note creation. Specify only if you want to override the default (current datetime in the current timezone/offset).+ utcDateCreated:+ $ref: "#/components/schemas/UtcDateTime"+ description: UTC timestap of the note creation. Specify only if you want to override the default (current datetime).+ Note:+ type: object+ properties:+ noteId:+ $ref: "#/components/schemas/EntityId"+ readOnly: true+ title:+ type: string+ type:+ type: string+ enum: [text, code, render, file, image, search, relationMap, book, noteMap, mermaid, webView, shortcut, doc, contentWidget, launcher]+ mime:+ type: string+ isProtected:+ type: boolean+ readOnly: true+ blobId:+ type: string+ description: ID of the blob object which effectively serves as a content hash+ attributes:+ $ref: "#/components/schemas/AttributeList"+ readOnly: true+ parentNoteIds:+ $ref: "#/components/schemas/EntityIdList"+ readOnly: true+ childNoteIds:+ $ref: "#/components/schemas/EntityIdList"+ readOnly: true+ parentBranchIds:+ $ref: "#/components/schemas/EntityIdList"+ readOnly: true+ childBranchIds:+ $ref: "#/components/schemas/EntityIdList"+ readOnly: true+ dateCreated:+ $ref: "#/components/schemas/LocalDateTime"+ dateModified:+ $ref: "#/components/schemas/LocalDateTime"+ readOnly: true+ utcDateCreated:+ $ref: "#/components/schemas/UtcDateTime"+ utcDateModified:+ $ref: "#/components/schemas/UtcDateTime"+ readOnly: true+ Branch:+ type: object+ description: Branch places the note into the tree, it represents the relationship between a parent note and child note+ properties:+ branchId:+ $ref: "#/components/schemas/EntityId"+ noteId:+ $ref: "#/components/schemas/EntityId"+ readOnly: true+ description: identifies the child note+ parentNoteId:+ $ref: "#/components/schemas/EntityId"+ readOnly: true+ description: identifies the parent note+ prefix:+ type: string+ notePosition:+ type: integer+ format: int32+ isExpanded:+ type: boolean+ utcDateModified:+ $ref: "#/components/schemas/UtcDateTime"+ readOnly: true+ NoteWithBranch:+ type: object+ properties:+ note:+ $ref: "#/components/schemas/Note"+ branch:+ $ref: "#/components/schemas/Branch"+ Attachment:+ type: object+ description: Attachment is owned by a note, has title and content+ properties:+ attachmentId:+ $ref: "#/components/schemas/EntityId"+ readOnly: true+ ownerId:+ $ref: "#/components/schemas/EntityId"+ description: identifies the owner of the attachment, is either noteId or revisionId+ role:+ type: string+ mime:+ type: string+ title:+ type: string+ position:+ type: integer+ format: int32+ blobId:+ type: string+ description: ID of the blob object which effectively serves as a content hash+ dateModified:+ $ref: "#/components/schemas/LocalDateTime"+ readOnly: true+ utcDateModified:+ $ref: "#/components/schemas/UtcDateTime"+ readOnly: true+ utcDateScheduledForErasureSince:+ $ref: "#/components/schemas/UtcDateTime"+ readOnly: true+ contentLength:+ type: integer+ format: int32+ CreateAttachment:+ type: object+ properties:+ ownerId:+ $ref: "#/components/schemas/EntityId"+ description: identifies the owner of the attachment, is either noteId or revisionId+ role:+ type: string+ mime:+ type: string+ title:+ type: string+ content:+ type: string+ position:+ type: integer+ format: int32+ Attribute:+ type: object+ description: Attribute (Label, Relation) is a key-value record attached to a note.+ properties:+ attributeId:+ $ref: "#/components/schemas/EntityId"+ noteId:+ $ref: "#/components/schemas/EntityId"+ readOnly: true+ description: identifies the child note+ type:+ type: string+ enum: [label, relation]+ name:+ type: string+ pattern: '^[^\s]+'+ example: shareCss+ value:+ type: string+ position:+ type: integer+ format: int32+ isInheritable:+ type: boolean+ utcDateModified:+ $ref: "#/components/schemas/UtcDateTime"+ readOnly: true+ AttributeList:+ type: array+ items:+ $ref: "#/components/schemas/Attribute"+ SearchResponse:+ type: object+ required:+ - results+ properties:+ results:+ type: array+ items:+ $ref: "#/components/schemas/Note"+ debugInfo:+ type: object+ description: debugging info on parsing the search query enabled with &debug=true parameter+ EntityId:type: string- format: date- example: 2022-02-22- responses:- '200':- description: day note- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Note'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /calendar/weeks/{date}:- get:- description: returns a week note for a given date. Gets created if doesn't exist.- operationId: getWeekNote- parameters:- - name: date- in: path- required: true- schema:+ pattern: "[a-zA-Z0-9_]{4,32}"+ example: evnnmvHTCgIn+ StringId:type: string- format: date- example: 2022-02-22- responses:- '200':- description: week note- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Note'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /calendar/months/{month}:- get:- description: returns a week note for a given date. Gets created if doesn't exist.- operationId: getMonthNote- parameters:- - name: month- in: path- required: true- schema:+ pattern: "[a-zA-Z0-9_]{1,32}"+ example: my_ID+ EntityIdList:+ type: array+ items:+ $ref: "#/components/schemas/EntityId"+ LocalDateTime:type: string- pattern: '[0-9]{4}-[0-9]{2}'- example: 2022-02- responses:- '200':- description: month note- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Note'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /calendar/years/{year}:- get:- description: returns a week note for a given date. Gets created if doesn't exist.- operationId: getYearNote- parameters:- - name: year- in: path- required: true- schema:+ pattern: '[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}[\+\-][0-9]{4}'+ example: 2021-12-31 20:18:11.930+0100+ UtcDateTime:type: string- pattern: '[0-9]{4}-[0-9]{2}'- example: 2022-02- responses:- '200':- description: year note- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Note'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /auth/login:- post:- description: get an ETAPI token based on password for further use with ETAPI- operationId: login- security: [] # no token based auth for login endpoint- requestBody:- required: true- content:- application/json:- schema:- properties:- password:- type: string- description: user's password used to e.g. login to Trilium server and/or protect notes- responses:- '201':- description: auth token- content:- application/json; charset=utf-8:- schema:- properties:- authToken:+ pattern: '[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z'+ example: 2021-12-31 19:18:11.930Z+ AppInfo:+ type: object+ properties:+ appVersion:type: string- example: Bc4bFn0Ffiok_4NpbVCDnFz7B2WU+pdhW8B5Ne3DiR5wXrEyqdjgRIsk=- '429':- description: Client IP has been blacklisted because too many requests (possibly failed authentications) were made within a short time frame, try again later- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /auth/logout:- post:- description: logout (delete/deactivate) an ETAPI token- operationId: logout- responses:- '204':- description: logout successful- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /app-info:- get:- description: returns information about the running Trilium instance- operationId: getAppInfo- responses:- '200':- description: app info- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/AppInfo'- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'- /backup/{backupName}:- parameters:- - name: backupName- in: path- required: true- description: If the backupName is e.g. "now", then the backup will be written to "backup-now.db" file- schema:- $ref: '#/components/schemas/StringId'- put:- description: Create a database backup under a given name- operationId: createBackup- responses:- '204':- description: backup has been created- default:- description: unexpected error- content:- application/json; charset=utf-8:- schema:- $ref: '#/components/schemas/Error'-components:- securitySchemes:- EtapiTokenAuth:- type: apiKey- in: header- name: Authorization- EtapiBasicAuth:- type: http- scheme: basic- description: >- Basic Auth where username is arbitrary string (e.g. "trilium", not checked),- username is the ETAPI token.- To emphasize, do not use Trilium password here (won't work), only the generated- ETAPI token (from Options -> ETAPI)- schemas:- CreateNoteDef:- type: object- required:- - parentNoteId- - title- - type- - content- properties:- parentNoteId:- $ref: '#/components/schemas/EntityId'- description: Note ID of the parent note in the tree- title:- type: string- type:- type: string- enum:- - text- - code- - file- - image- - search- - book- - relationMap- - render- mime:- type: string- description: this needs to be specified only for note types 'code', 'file', 'image'.- example: application/json- content:- type: string- notePosition:- type: integer- description: >- Position of the note in the parent. Normal ordering is 10, 20, 30 ...- So if you want to create a note on the first position, use e.g. 5, for second position 15, for last e.g. 1000000- prefix:- type: string- description: >- Prefix is branch (placement) specific title prefix for the note.- Let's say you have your note placed into two different places in the tree,- but you want to change the title a bit in one of the placements. For this you can use prefix.- isExpanded:- type: boolean- description: true if this note (as a folder) should appear expanded- noteId:- $ref: '#/components/schemas/EntityId'- description: DON'T specify unless you want to force a specific noteId- branchId:- $ref: '#/components/schemas/EntityId'- description: DON'T specify unless you want to force a specific branchId- dateCreated:- $ref: '#/components/schemas/LocalDateTime'- description: Local timestap of the note creation. Specify only if you want to override the default (current datetime in the current timezone/offset).- utcDateCreated:- $ref: '#/components/schemas/UtcDateTime'- description: UTC timestap of the note creation. Specify only if you want to override the default (current datetime).- Note:- type: object- properties:- noteId:- $ref: '#/components/schemas/EntityId'- readOnly: true- title:- type: string- type:- type: string- enum: [text, code, render, file, image, search, relationMap, book, noteMap, mermaid, webView, shortcut, doc, contentWidget, launcher]- mime:- type: string- isProtected:- type: boolean- readOnly: true- blobId:- type: string- description: ID of the blob object which effectively serves as a content hash- attributes:- $ref: '#/components/schemas/AttributeList'- readOnly: true- parentNoteIds:- $ref: '#/components/schemas/EntityIdList'- readOnly: true- childNoteIds:- $ref: '#/components/schemas/EntityIdList'- readOnly: true- parentBranchIds:- $ref: '#/components/schemas/EntityIdList'- readOnly: true- childBranchIds:- $ref: '#/components/schemas/EntityIdList'- readOnly: true- dateCreated:- $ref: '#/components/schemas/LocalDateTime'- dateModified:- $ref: '#/components/schemas/LocalDateTime'- readOnly: true- utcDateCreated:- $ref: '#/components/schemas/UtcDateTime'- utcDateModified:- $ref: '#/components/schemas/UtcDateTime'- readOnly: true- Branch:- type: object- description: Branch places the note into the tree, it represents the relationship between a parent note and child note- properties:- branchId:- $ref: '#/components/schemas/EntityId'- noteId:- $ref: '#/components/schemas/EntityId'- readOnly: true- description: identifies the child note- parentNoteId:- $ref: '#/components/schemas/EntityId'- readOnly: true- description: identifies the parent note- prefix:- type: string- notePosition:- type: integer- format: int32- isExpanded:- type: boolean- utcDateModified:- $ref: '#/components/schemas/UtcDateTime'- readOnly: true- NoteWithBranch:- type: object- properties:- note:- $ref: '#/components/schemas/Note'- branch:- $ref: '#/components/schemas/Branch'- Attachment:- type: object- description: Attachment is owned by a note, has title and content- properties:- attachmentId:- $ref: '#/components/schemas/EntityId'- readOnly: true- ownerId:- $ref: '#/components/schemas/EntityId'- description: identifies the owner of the attachment, is either noteId or revisionId- role:- type: string- mime:- type: string- title:- type: string- position:- type: integer- format: int32- blobId:- type: string- description: ID of the blob object which effectively serves as a content hash- dateModified:- $ref: '#/components/schemas/LocalDateTime'- readOnly: true- utcDateModified:- $ref: '#/components/schemas/UtcDateTime'- readOnly: true- utcDateScheduledForErasureSince:- $ref: '#/components/schemas/UtcDateTime'- readOnly: true- contentLength:- type: integer- format: int32- CreateAttachment:- type: object- properties:- ownerId:- $ref: '#/components/schemas/EntityId'- description: identifies the owner of the attachment, is either noteId or revisionId- role:- type: string- mime:- type: string- title:- type: string- content:- type: string- position:- type: integer- format: int32- Attribute:- type: object- description: Attribute (Label, Relation) is a key-value record attached to a note.- properties:- attributeId:- $ref: '#/components/schemas/EntityId'- noteId:- $ref: '#/components/schemas/EntityId'- readOnly: true- description: identifies the child note- type:- type: string- enum: [label, relation]- name:- type: string- pattern: '^[^\s]+'- example: shareCss- value:- type: string- position:- type: integer- format: int32- isInheritable:- type: boolean- utcDateModified:- $ref: '#/components/schemas/UtcDateTime'- readOnly: true- AttributeList:- type: array- items:- $ref: '#/components/schemas/Attribute'- SearchResponse:- type: object- required:- - results- properties:- results:- type: array- items:- $ref: '#/components/schemas/Note'- debugInfo:- type: object- description: debugging info on parsing the search query enabled with &debug=true parameter- EntityId:- type: string- pattern: '[a-zA-Z0-9_]{4,32}'- example: evnnmvHTCgIn- StringId:- type: string- pattern: '[a-zA-Z0-9_]{1,32}'- example: my_ID- EntityIdList:- type: array- items:- $ref: '#/components/schemas/EntityId'- LocalDateTime:- type: string- pattern: '[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}[\+\-][0-9]{4}'- example: 2021-12-31 20:18:11.930+0100- UtcDateTime:- type: string- pattern: '[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z'- example: 2021-12-31 19:18:11.930Z- AppInfo:- type: object- properties:- appVersion:- type: string- description: Trilium version- example: 0.50.2- dbVersion:- type: integer- format: int32- description: DB version- example: 194- syncVersion:- type: integer- format: int32- description: Sync protocol version- example: 25- buildDate:- type: string- format: date-time- description: build date- example: 2022-02-09T22:52:36+01:00- buildRevision:- type: string- description: git build revision- example: 23daaa2387a0655685377f0a541d154aeec2aae8- dataDirectory:- type: string- description: data directory where Trilium stores files- example: /home/user/data- clipperProtocolVersion:- type: string- description: version of the supported Trilium Web Clipper protocol- example: 1.0- utcDateTime:- type: string- description: current UTC date time- example: 2022-03-07T21:54:25.277Z- Error:- type: object- required:- - status- - code- - message- properties:- status:- type: integer- format: int32- description: HTTP status, identical to the one given in HTTP response- example: 400- code:- type: string- description: stable string constant- example: NOTE_IS_PROTECTED- message:- type: string- description: Human readable error, potentially with more details,- example: Note 'evnnmvHTCgIn' is protected and cannot be modified through ETAPI+ description: Trilium version+ example: 0.50.2+ dbVersion:+ type: integer+ format: int32+ description: DB version+ example: 194+ syncVersion:+ type: integer+ format: int32+ description: Sync protocol version+ example: 25+ buildDate:+ type: string+ format: date-time+ description: build date+ example: 2022-02-09T22:52:36+01:00+ buildRevision:+ type: string+ description: git build revision+ example: 23daaa2387a0655685377f0a541d154aeec2aae8+ dataDirectory:+ type: string+ description: data directory where Trilium stores files+ example: /home/user/data+ clipperProtocolVersion:+ type: string+ description: version of the supported Trilium Web Clipper protocol+ example: 1.0+ utcDateTime:+ type: string+ description: current UTC date time+ example: 2022-03-07T21:54:25.277Z+ Error:+ type: object+ required:+ - status+ - code+ - message+ properties:+ status:+ type: integer+ format: int32+ description: HTTP status, identical to the one given in HTTP response+ example: 400+ code:+ type: string+ description: stable string constant+ example: NOTE_IS_PROTECTED+ message:+ type: string+ description: Human readable error, potentially with more details,+ example: Note 'evnnmvHTCgIn' is protected and cannot be modified through ETAPIdiff --git a/src/etapi/etapi_utils.ts b/src/etapi/etapi_utils.tsindex 435de51d2b..ae6e310d78 100644--- a/src/etapi/etapi_utils.ts+++ b/src/etapi/etapi_utils.ts@@ -4,8 +4,8 @@ import log from "../services/log.js";import becca from "../becca/becca.js";import etapiTokenService from "../services/etapi_tokens.js";import config from "../services/config.js";-import { NextFunction, Request, RequestHandler, Response, Router } from 'express';-import { ValidatorMap } from './etapi-interface.js';+import { NextFunction, Request, RequestHandler, Response, Router } from "express";+import { ValidatorMap } from "./etapi-interface.js";import { ApiRequestHandler } from "../routes/routes.js";const GENERIC_CODE = "GENERIC";@@ -30,20 +30,21 @@ class EtapiError extends Error {function sendError(res: Response, statusCode: number, code: string, message: string) {return res- .set('Content-Type', 'application/json')+ .set("Content-Type", "application/json").status(statusCode)- .send(JSON.stringify({- "status": statusCode,- "code": code,- "message": message- }));+ .send(+ JSON.stringify({+ status: statusCode,+ code: code,+ message: message+ })+ );}function checkEtapiAuth(req: Request, res: Response, next: NextFunction) {if (noAuthentication || etapiTokenService.isValidAuthHeader(req.headers.authorization)) {next();- }- else {+ } else {sendError(res, 401, "NOT_AUTHENTICATED", "Not authenticated");}}@@ -54,8 +55,8 @@ function processRequest(req: Request, res: Response, routeHandler: ApiRequestHancls.namespace.bindEmitter(res);cls.init(() => {- cls.set('componentId', "etapi");- cls.set('localNowDateTime', req.headers['trilium-local-now-datetime']);+ cls.set("componentId", "etapi");+ cls.set("localNowDateTime", req.headers["trilium-local-now-datetime"]);const cb = () => routeHandler(req, res, next);@@ -85,19 +86,17 @@ function getAndCheckNote(noteId: string) {if (note) {return note;- }- else {+ } else {throw new EtapiError(404, "NOTE_NOT_FOUND", `Note '${noteId}' not found.`);}}function getAndCheckAttachment(attachmentId: string) {- const attachment = becca.getAttachment(attachmentId, {includeContentLength: true});+ const attachment = becca.getAttachment(attachmentId, { includeContentLength: true });if (attachment) {return attachment;- }- else {+ } else {throw new EtapiError(404, "ATTACHMENT_NOT_FOUND", `Attachment '${attachmentId}' not found.`);}}@@ -107,8 +106,7 @@ function getAndCheckBranch(branchId: string) {if (branch) {return branch;- }- else {+ } else {throw new EtapiError(404, "BRANCH_NOT_FOUND", `Branch '${branchId}' not found.`);}}@@ -118,8 +116,7 @@ function getAndCheckAttribute(attributeId: string) {if (attribute) {return attribute;- }- else {+ } else {throw new EtapiError(404, "ATTRIBUTE_NOT_FOUND", `Attribute '${attributeId}' not found.`);}}@@ -128,8 +125,7 @@ function validateAndPatch(target: any, source: any, allowedProperties: Validatorfor (const key of Object.keys(source)) {if (!(key in allowedProperties)) {throw new EtapiError(400, "PROPERTY_NOT_ALLOWED", `Property '${key}' is not allowed for this method.`);- }- else {+ } else {for (const validator of allowedProperties[key]) {const validationResult = validator(source[key]);@@ -157,4 +153,4 @@ export default {getAndCheckBranch,getAndCheckAttribute,getAndCheckAttachment-}+};diff --git a/src/etapi/mappers.ts b/src/etapi/mappers.tsindex 1caf21cf49..33cd2c29f2 100644--- a/src/etapi/mappers.ts+++ b/src/etapi/mappers.ts@@ -15,11 +15,11 @@ function mapNoteToPojo(note: BNote) {dateModified: note.dateModified,utcDateCreated: note.utcDateCreated,utcDateModified: note.utcDateModified,- parentNoteIds: note.getParentNotes().map(p => p.noteId),- childNoteIds: note.getChildNotes().map(ch => ch.noteId),- parentBranchIds: note.getParentBranches().map(p => p.branchId),- childBranchIds: note.getChildBranches().map(ch => ch.branchId),- attributes: note.getAttributes().map(attr => mapAttributeToPojo(attr))+ parentNoteIds: note.getParentNotes().map((p) => p.noteId),+ childNoteIds: note.getChildNotes().map((ch) => ch.noteId),+ parentBranchIds: note.getParentBranches().map((p) => p.branchId),+ childBranchIds: note.getChildBranches().map((ch) => ch.branchId),+ attributes: note.getAttributes().map((attr) => mapAttributeToPojo(attr))};}diff --git a/src/etapi/notes.ts b/src/etapi/notes.tsindex 173dd0ec80..855cb0c951 100644--- a/src/etapi/notes.ts+++ b/src/etapi/notes.ts@@ -9,28 +9,28 @@ import searchService from "../services/search/services/search.js";import SearchContext from "../services/search/search_context.js";import zipExportService from "../services/export/zip.js";import zipImportService from "../services/import/zip.js";-import { Request, Router } from 'express';-import { ParsedQs } from 'qs';-import { NoteParams } from '../services/note-interface.js';-import { SearchParams } from '../services/search/services/types.js';-import { ValidatorMap } from './etapi-interface.js';+import { Request, Router } from "express";+import { ParsedQs } from "qs";+import { NoteParams } from "../services/note-interface.js";+import { SearchParams } from "../services/search/services/types.js";+import { ValidatorMap } from "./etapi-interface.js";function register(router: Router) {- eu.route(router, 'get', '/etapi/notes', (req, res, next) => {+ eu.route(router, "get", "/etapi/notes", (req, res, next) => {const { search } = req.query;if (typeof search !== "string" || !search?.trim()) {- throw new eu.EtapiError(400, 'SEARCH_QUERY_PARAM_MANDATORY', "'search' query parameter is mandatory.");+ throw new eu.EtapiError(400, "SEARCH_QUERY_PARAM_MANDATORY", "'search' query parameter is mandatory.");}const searchParams = parseSearchParams(req);const searchContext = new SearchContext(searchParams);const searchResults = searchService.findResultsWithQuery(search, searchContext);- const foundNotes = searchResults.map(sr => becca.notes[sr.noteId]);+ const foundNotes = searchResults.map((sr) => becca.notes[sr.noteId]);const resp: any = {- results: foundNotes.map(note => mappers.mapNoteToPojo(note)),+ results: foundNotes.map((note) => mappers.mapNoteToPojo(note))};if (searchContext.debugInfo) {@@ -40,27 +40,27 @@ function register(router: Router) {res.json(resp);});- eu.route(router, 'get', '/etapi/notes/:noteId', (req, res, next) => {+ eu.route(router, "get", "/etapi/notes/:noteId", (req, res, next) => {const note = eu.getAndCheckNote(req.params.noteId);res.json(mappers.mapNoteToPojo(note));});const ALLOWED_PROPERTIES_FOR_CREATE_NOTE: ValidatorMap = {- 'parentNoteId': [v.mandatory, v.notNull, v.isNoteId],- 'title': [v.mandatory, v.notNull, v.isString],- 'type': [v.mandatory, v.notNull, v.isNoteType],- 'mime': [v.notNull, v.isString],- 'content': [v.notNull, v.isString],- 'notePosition': [v.notNull, v.isInteger],- 'prefix': [v.notNull, v.isString],- 'isExpanded': [v.notNull, v.isBoolean],- 'noteId': [v.notNull, v.isValidEntityId],- 'dateCreated': [v.notNull, v.isString, v.isLocalDateTime],- 'utcDateCreated': [v.notNull, v.isString, v.isUtcDateTime]+ parentNoteId: [v.mandatory, v.notNull, v.isNoteId],+ title: [v.mandatory, v.notNull, v.isString],+ type: [v.mandatory, v.notNull, v.isNoteType],+ mime: [v.notNull, v.isString],+ content: [v.notNull, v.isString],+ notePosition: [v.notNull, v.isInteger],+ prefix: [v.notNull, v.isString],+ isExpanded: [v.notNull, v.isBoolean],+ noteId: [v.notNull, v.isValidEntityId],+ dateCreated: [v.notNull, v.isString, v.isLocalDateTime],+ utcDateCreated: [v.notNull, v.isString, v.isUtcDateTime]};- eu.route(router, 'post', '/etapi/create-note', (req, res, next) => {+ eu.route(router, "post", "/etapi/create-note", (req, res, next) => {const _params = {};eu.validateAndPatch(_params, req.body, ALLOWED_PROPERTIES_FOR_CREATE_NOTE);const params = _params as NoteParams;@@ -72,21 +72,20 @@ function register(router: Router) {note: mappers.mapNoteToPojo(resp.note),branch: mappers.mapBranchToPojo(resp.branch)});- }- catch (e: any) {+ } catch (e: any) {return eu.sendError(res, 500, eu.GENERIC_CODE, e.message);}});const ALLOWED_PROPERTIES_FOR_PATCH = {- 'title': [v.notNull, v.isString],- 'type': [v.notNull, v.isString],- 'mime': [v.notNull, v.isString],- 'dateCreated': [v.notNull, v.isString, v.isLocalDateTime],- 'utcDateCreated': [v.notNull, v.isString, v.isUtcDateTime]+ title: [v.notNull, v.isString],+ type: [v.notNull, v.isString],+ mime: [v.notNull, v.isString],+ dateCreated: [v.notNull, v.isString, v.isLocalDateTime],+ utcDateCreated: [v.notNull, v.isString, v.isUtcDateTime]};- eu.route(router, 'patch', '/etapi/notes/:noteId', (req, res, next) => {+ eu.route(router, "patch", "/etapi/notes/:noteId", (req, res, next) => {const note = eu.getAndCheckNote(req.params.noteId);if (note.isProtected) {@@ -99,7 +98,7 @@ function register(router: Router) {res.json(mappers.mapNoteToPojo(note));});- eu.route(router, 'delete', '/etapi/notes/:noteId', (req, res, next) => {+ eu.route(router, "delete", "/etapi/notes/:noteId", (req, res, next) => {const { noteId } = req.params;const note = becca.getNote(noteId);@@ -108,12 +107,12 @@ function register(router: Router) {return res.sendStatus(204);}- note.deleteNote(null, new TaskContext('no-progress-reporting'));+ note.deleteNote(null, new TaskContext("no-progress-reporting"));res.sendStatus(204);});- eu.route(router, 'get', '/etapi/notes/:noteId/content', (req, res, next) => {+ eu.route(router, "get", "/etapi/notes/:noteId/content", (req, res, next) => {const note = eu.getAndCheckNote(req.params.noteId);if (note.isProtected) {@@ -122,15 +121,15 @@ function register(router: Router) {const filename = utils.formatDownloadTitle(note.title, note.type, note.mime);- res.setHeader('Content-Disposition', utils.getContentDisposition(filename));+ res.setHeader("Content-Disposition", utils.getContentDisposition(filename));res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");- res.setHeader('Content-Type', note.mime);+ res.setHeader("Content-Type", note.mime);res.send(note.getContent());});- eu.route(router, 'put', '/etapi/notes/:noteId/content', (req, res, next) => {+ eu.route(router, "put", "/etapi/notes/:noteId/content", (req, res, next) => {const note = eu.getAndCheckNote(req.params.noteId);if (note.isProtected) {@@ -144,7 +143,7 @@ function register(router: Router) {return res.sendStatus(204);});- eu.route(router, 'get', '/etapi/notes/:noteId/export', (req, res, next) => {+ eu.route(router, "get", "/etapi/notes/:noteId/export", (req, res, next) => {const note = eu.getAndCheckNote(req.params.noteId);const format = req.query.format || "html";@@ -152,7 +151,7 @@ function register(router: Router) {throw new eu.EtapiError(400, "UNRECOGNIZED_EXPORT_FORMAT", `Unrecognized export format '${format}', supported values are 'html' (default) or 'markdown'.`);}- const taskContext = new TaskContext('no-progress-reporting');+ const taskContext = new TaskContext("no-progress-reporting");// technically a branch is being exported (includes prefix), but it's such a minor difference yet usability pain// (e.g. branchIds are not seen in UI), that we export "note export" instead.@@ -161,19 +160,19 @@ function register(router: Router) {zipExportService.exportToZip(taskContext, branch, format as "html" | "markdown", res);});- eu.route(router, 'post', '/etapi/notes/:noteId/import', (req, res, next) => {+ eu.route(router, "post", "/etapi/notes/:noteId/import", (req, res, next) => {const note = eu.getAndCheckNote(req.params.noteId);- const taskContext = new TaskContext('no-progress-reporting');+ const taskContext = new TaskContext("no-progress-reporting");- zipImportService.importZip(taskContext, req.body, note).then(importedNote => {+ zipImportService.importZip(taskContext, req.body, note).then((importedNote) => {res.status(201).json({note: mappers.mapNoteToPojo(importedNote),- branch: mappers.mapBranchToPojo(importedNote.getParentBranches()[0]),+ branch: mappers.mapBranchToPojo(importedNote.getParentBranches()[0])});}); // we need better error handling here, async errors won't be properly processed.});- eu.route(router, 'post', '/etapi/notes/:noteId/revision', (req, res, next) => {+ eu.route(router, "post", "/etapi/notes/:noteId/revision", (req, res, next) => {const note = eu.getAndCheckNote(req.params.noteId);note.saveRevision();@@ -181,27 +180,25 @@ function register(router: Router) {return res.sendStatus(204);});- eu.route(router, 'get', '/etapi/notes/:noteId/attachments', (req, res, next) => {+ eu.route(router, "get", "/etapi/notes/:noteId/attachments", (req, res, next) => {const note = eu.getAndCheckNote(req.params.noteId);- const attachments = note.getAttachments({ includeContentLength: true })+ const attachments = note.getAttachments({ includeContentLength: true });- res.json(- attachments.map(attachment => mappers.mapAttachmentToPojo(attachment))- );+ res.json(attachments.map((attachment) => mappers.mapAttachmentToPojo(attachment)));});}function parseSearchParams(req: Request) {const rawSearchParams: SearchParams = {- fastSearch: parseBoolean(req.query, 'fastSearch'),- includeArchivedNotes: parseBoolean(req.query, 'includeArchivedNotes'),- ancestorNoteId: parseString(req.query['ancestorNoteId']),- ancestorDepth: parseString(req.query['ancestorDepth']), // e.g. "eq5"- orderBy: parseString(req.query['orderBy']),+ fastSearch: parseBoolean(req.query, "fastSearch"),+ includeArchivedNotes: parseBoolean(req.query, "includeArchivedNotes"),+ ancestorNoteId: parseString(req.query["ancestorNoteId"]),+ ancestorDepth: parseString(req.query["ancestorDepth"]), // e.g. "eq5"+ orderBy: parseString(req.query["orderBy"]),// TODO: Check why the order direction was provided as a number, but it's a string everywhere else.- orderDirection: parseOrderDirection(req.query, 'orderDirection') as unknown as string,- limit: parseInteger(req.query, 'limit'),- debug: parseBoolean(req.query, 'debug')+ orderDirection: parseOrderDirection(req.query, "orderDirection") as unknown as string,+ limit: parseInteger(req.query, "limit"),+ debug: parseBoolean(req.query, "debug")};const searchParams: SearchParams = {};@@ -230,11 +227,11 @@ function parseBoolean(obj: any, name: string) {return undefined;}- if (!['true', 'false'].includes(obj[name])) {+ if (!["true", "false"].includes(obj[name])) {throw new eu.EtapiError(400, SEARCH_PARAM_ERROR, `Cannot parse boolean '${name}' value '${obj[name]}, allowed values are 'true' and 'false'.`);}- return obj[name] === 'true';+ return obj[name] === "true";}function parseOrderDirection(obj: any, name: string) {@@ -244,7 +241,7 @@ function parseOrderDirection(obj: any, name: string) {const integer = parseInt(obj[name]);- if (!['asc', 'desc'].includes(obj[name])) {+ if (!["asc", "desc"].includes(obj[name])) {throw new eu.EtapiError(400, SEARCH_PARAM_ERROR, `Cannot parse order direction value '${obj[name]}, allowed values are 'asc' and 'desc'.`);}diff --git a/src/etapi/spec.ts b/src/etapi/spec.tsindex 9c183e9c13..5e27be9492 100644--- a/src/etapi/spec.ts+++ b/src/etapi/spec.ts@@ -4,16 +4,16 @@ import fs from "fs";import path from "path";import { fileURLToPath } from "url";-const specPath = path.join(path.dirname(fileURLToPath(import.meta.url)), 'etapi.openapi.yaml');+const specPath = path.join(path.dirname(fileURLToPath(import.meta.url)), "etapi.openapi.yaml");let spec: string | null = null;function register(router: Router) {- router.get('/etapi/etapi.openapi.yaml', (req, res, next) => {+ router.get("/etapi/etapi.openapi.yaml", (req, res, next) => {if (!spec) {- spec = fs.readFileSync(specPath, 'utf8');+ spec = fs.readFileSync(specPath, "utf8");}- res.header('Content-Type', 'text/plain'); // so that it displays in browser+ res.header("Content-Type", "text/plain"); // so that it displays in browserres.status(200).send(spec);});}diff --git a/src/etapi/special_notes.ts b/src/etapi/special_notes.tsindex 1df65c638a..14626710d8 100644--- a/src/etapi/special_notes.ts+++ b/src/etapi/special_notes.ts@@ -2,10 +2,10 @@ import specialNotesService from "../services/special_notes.js";import dateNotesService from "../services/date_notes.js";import eu from "./etapi_utils.js";import mappers from "./mappers.js";-import { Router } from 'express';+import { Router } from "express";const getDateInvalidError = (date: string) => new eu.EtapiError(400, "DATE_INVALID", `Date "${date}" is not valid.`);-const getMonthInvalidError = (month: string)=> new eu.EtapiError(400, "MONTH_INVALID", `Month "${month}" is not valid.`);+const getMonthInvalidError = (month: string) => new eu.EtapiError(400, "MONTH_INVALID", `Month "${month}" is not valid.`);const getYearInvalidError = (year: string) => new eu.EtapiError(400, "YEAR_INVALID", `Year "${year}" is not valid.`);function isValidDate(date: string) {@@ -17,7 +17,7 @@ function isValidDate(date: string) {}function register(router: Router) {- eu.route(router, 'get', '/etapi/inbox/:date', (req, res, next) => {+ eu.route(router, "get", "/etapi/inbox/:date", (req, res, next) => {const { date } = req.params;if (!isValidDate(date)) {@@ -28,7 +28,7 @@ function register(router: Router) {res.json(mappers.mapNoteToPojo(note));});- eu.route(router, 'get', '/etapi/calendar/days/:date', (req, res, next) => {+ eu.route(router, "get", "/etapi/calendar/days/:date", (req, res, next) => {const { date } = req.params;if (!isValidDate(date)) {@@ -39,7 +39,7 @@ function register(router: Router) {res.json(mappers.mapNoteToPojo(note));});- eu.route(router, 'get', '/etapi/calendar/weeks/:date', (req, res, next) => {+ eu.route(router, "get", "/etapi/calendar/weeks/:date", (req, res, next) => {const { date } = req.params;if (!isValidDate(date)) {@@ -50,7 +50,7 @@ function register(router: Router) {res.json(mappers.mapNoteToPojo(note));});- eu.route(router, 'get', '/etapi/calendar/months/:month', (req, res, next) => {+ eu.route(router, "get", "/etapi/calendar/months/:month", (req, res, next) => {const { month } = req.params;if (!/[0-9]{4}-[0-9]{2}/.test(month)) {@@ -61,7 +61,7 @@ function register(router: Router) {res.json(mappers.mapNoteToPojo(note));});- eu.route(router, 'get', '/etapi/calendar/years/:year', (req, res, next) => {+ eu.route(router, "get", "/etapi/calendar/years/:year", (req, res, next) => {const { year } = req.params;if (!/[0-9]{4}/.test(year)) {diff --git a/src/etapi/validators.ts b/src/etapi/validators.tsindex 37aafecefb..52b24ddc49 100644--- a/src/etapi/validators.ts+++ b/src/etapi/validators.ts@@ -19,7 +19,7 @@ function isString(obj: unknown) {return;}- if (typeof obj !== 'string') {+ if (typeof obj !== "string") {return `'${obj}' is not a string`;}}@@ -45,7 +45,7 @@ function isBoolean(obj: unknown) {return;}- if (typeof obj !== 'boolean') {+ if (typeof obj !== "boolean") {return `'${obj}' is not a boolean`;}}@@ -65,7 +65,7 @@ function isNoteId(obj: unknown) {return;}- if (typeof obj !== 'string') {+ if (typeof obj !== "string") {return `'${obj}' is not a valid noteId`;}@@ -91,7 +91,7 @@ function isAttributeType(obj: unknown) {return;}- if (typeof obj !== "string" || !['label', 'relation'].includes(obj)) {+ if (typeof obj !== "string" || !["label", "relation"].includes(obj)) {return `'${obj}' is not a valid attribute type, allowed types are: label, relation`;}}@@ -101,7 +101,7 @@ function isValidEntityId(obj: unknown) {return;}- if (typeof obj !== 'string' || !/^[A-Za-z0-9_]{4,128}$/.test(obj)) {+ if (typeof obj !== "string" || !/^[A-Za-z0-9_]{4,128}$/.test(obj)) {return `'${obj}' is not a valid entityId. Only alphanumeric characters are allowed of length 4 to 32.`;}}diff --git a/src/express.d.ts b/src/express.d.tsindex e7b6393f19..eb523dff2a 100644--- a/src/express.d.ts+++ b/src/express.d.ts@@ -4,18 +4,18 @@ export declare module "express-serve-static-core" {interface Request {session: Session & {loggedIn: boolean;- },+ };headers: {"x-local-date"?: string;"x-labels"?: string;- "authorization"?: string;+ authorization?: string;"trilium-cred"?: string;"x-csrf-token"?: string;"trilium-component-id"?: string;"trilium-local-now-datetime"?: string;"trilium-hoisted-note-id"?: string;- }+ };}}diff --git a/src/public/app/components/app_context.ts b/src/public/app/components/app_context.tsindex ceaef38822..035eeb0f83 100644--- a/src/public/app/components/app_context.ts+++ b/src/public/app/components/app_context.ts@@ -98,7 +98,7 @@ export type CommandMappings = {showInfoDialog: ConfirmWithMessageOptions;showConfirmDialog: ConfirmWithMessageOptions;openNewNoteSplit: NoteCommandData;- openInWindow: NoteCommandData,+ openInWindow: NoteCommandData;openNoteInNewTab: CommandData;openNoteInNewSplit: CommandData;openNoteInNewWindow: CommandData;@@ -139,11 +139,12 @@ export type CommandMappings = {resetLauncher: ContextMenuCommandData;executeInActiveNoteDetailWidget: CommandData & {- callback: (value: NoteDetailWidget | PromiseLike<NoteDetailWidget>) => void- };- executeWithTextEditor: CommandData & ExecuteCommandData & {- callback?: GetTextEditorCallback;+ callback: (value: NoteDetailWidget | PromiseLike<NoteDetailWidget>) => void;};+ executeWithTextEditor: CommandData &+ ExecuteCommandData & {+ callback?: GetTextEditorCallback;+ };executeWithCodeEditor: CommandData & ExecuteCommandData;executeWithContentElement: CommandData & ExecuteCommandData;executeWithTypeWidget: CommandData & ExecuteCommandData;@@ -177,8 +178,8 @@ export type CommandMappings = {/** Sets the active {@link Screen} (e.g. to toggle the tree sidebar). It triggers the {@link EventMappings.activeScreenChanged} event, but only if the provided <em>screen</em> is different than the current one. */setActiveScreen: CommandData & {screen: Screen;- }-}+ };+};type EventMappings = {initialRenderComplete: {};@@ -195,57 +196,57 @@ type EventMappings = {messages: string[];};entitiesReloaded: {- loadResults: LoadResults+ loadResults: LoadResults;};addNewLabel: CommandData;addNewRelation: CommandData;sqlQueryResults: CommandData & {results: SqlExecuteResults;- },+ };readOnlyTemporarilyDisabled: {- noteContext: NoteContext- },+ noteContext: NoteContext;+ };/** Triggered when the {@link CommandMappings.setActiveScreen} command is invoked. */activeScreenChanged: {activeScreen: Screen;- },+ };activeContextChanged: {noteContext: NoteContext;- },+ };noteSwitched: {noteContext: NoteContext;notePath: string;- },+ };noteSwitchedAndActivatedEvent: {noteContext: NoteContext;notePath: string;- },+ };setNoteContext: {noteContext: NoteContext;- },+ };noteTypeMimeChangedEvent: {noteId: string;- },+ };reEvaluateHighlightsListWidgetVisibility: {noteId: string | undefined;- },+ };showHighlightsListWidget: {noteId: string;- }-}+ };+};export type EventListener<T extends EventNames> = {- [key in T as `${key}Event`]: (data: EventData<T>) => void-}+ [key in T as `${key}Event`]: (data: EventData<T>) => void;+};export type CommandListener<T extends CommandNames> = {- [key in T as `${key}Command`]: (data: CommandListenerData<T>) => void-}+ [key in T as `${key}Command`]: (data: CommandListenerData<T>) => void;+};export type CommandListenerData<T extends CommandNames> = CommandMappings[T];export type EventData<T extends EventNames> = EventMappings[T];-type CommandAndEventMappings = (CommandMappings & EventMappings);+type CommandAndEventMappings = CommandMappings & EventMappings;/*** This type is a discriminated union which contains all the possible commands that can be triggered via {@link AppContext.triggerCommand}.@@ -253,7 +254,7 @@ type CommandAndEventMappings = (CommandMappings & EventMappings);export type CommandNames = keyof CommandMappings;type EventNames = keyof EventMappings;-type FilterByValueType<T, ValueType> = { [K in keyof T]: T[K] extends ValueType ? K : never; }[keyof T];+type FilterByValueType<T, ValueType> = { [K in keyof T]: T[K] extends ValueType ? K : never }[keyof T];/*** Generic which filters {@link CommandNames} to provide only those commands that take in as data the desired implementation of {@link CommandData}. Mostly useful for contextual menu, to enforce consistency in the commands.@@ -261,7 +262,6 @@ type FilterByValueType<T, ValueType> = { [K in keyof T]: T[K] extends ValueTypeexport type FilteredCommandNames<T extends CommandData> = keyof Pick<CommandMappings, FilterByValueType<CommandMappings, T>>;class AppContext extends Component {-isMainWindow: boolean;components: Component[];beforeUnloadListeners: WeakRef<BeforeUploadListener>[];@@ -304,13 +304,7 @@ class AppContext extends Component {initComponents() {this.tabManager = new TabManager();- this.components = [- this.tabManager,- new RootCommandExecutor(),- new Entrypoints(),- new MainTreeExecutors(),- new ShortcutComponent()- ];+ this.components = [this.tabManager, new RootCommandExecutor(), new Entrypoints(), new MainTreeExecutors(), new ShortcutComponent()];if (utils.isMobile()) {this.components.push(new MobileScreenSwitcherExecutor());@@ -337,21 +331,21 @@ class AppContext extends Component {$("body").append($renderedWidget);- $renderedWidget.on('click', "[data-trigger-command]", function() {+ $renderedWidget.on("click", "[data-trigger-command]", function () {if ($(this).hasClass("disabled")) {return;}- const commandName = $(this).attr('data-trigger-command');+ const commandName = $(this).attr("data-trigger-command");const $component = $(this).closest(".component");const component = $component.prop("component");- component.triggerCommand(commandName, {$el: $(this)});+ component.triggerCommand(commandName, { $el: $(this) });});this.child(rootWidget);- this.triggerEvent('initialRenderComplete');+ this.triggerEvent("initialRenderComplete");}// TODO: Remove ignore once all commands are mapped out.@@ -378,7 +372,7 @@ class AppContext extends Component {}getComponentByEl(el: HTMLElement) {- return $(el).closest(".component").prop('component');+ return $(el).closest(".component").prop("component");}addBeforeUnloadListener(obj: BeforeUploadListener) {@@ -394,10 +388,10 @@ class AppContext extends Component {const appContext = new AppContext(window.glob.isMainWindow);// we should save all outstanding changes before the page/app is closed-$(window).on('beforeunload', () => {+$(window).on("beforeunload", () => {let allSaved = true;- appContext.beforeUnloadListeners = appContext.beforeUnloadListeners.filter(wr => !!wr.deref());+ appContext.beforeUnloadListeners = appContext.beforeUnloadListeners.filter((wr) => !!wr.deref());for (const weakRef of appContext.beforeUnloadListeners) {const component = weakRef.deref();@@ -420,8 +414,8 @@ $(window).on('beforeunload', () => {}});-$(window).on('hashchange', function() {- const {notePath, ntxId, viewScope} = linkService.parseNavigationStateFromUrl(window.location.href);+$(window).on("hashchange", function () {+ const { notePath, ntxId, viewScope } = linkService.parseNavigationStateFromUrl(window.location.href);if (notePath || ntxId) {appContext.tabManager.switchToNoteContext(ntxId, notePath, viewScope);diff --git a/src/public/app/components/component.ts b/src/public/app/components/component.tsindex 9300b1f861..cb8f0d9bf1 100644--- a/src/public/app/components/component.ts+++ b/src/public/app/components/component.ts@@ -1,5 +1,5 @@-import utils from '../services/utils.js';-import { CommandMappings, CommandNames } from './app_context.js';+import utils from "../services/utils.js";+import { CommandMappings, CommandNames } from "./app_context.js";/*** Abstract class for all components in the Trilium's frontend.@@ -28,7 +28,7 @@ export class TypedComponent<ChildT extends TypedComponent<ChildT>> {get sanitizedClassName() {// webpack mangles names and sometimes uses unsafe characters- return this.constructor.name.replace(/[^A-Z0-9]/ig, "_");+ return this.constructor.name.replace(/[^A-Z0-9]/gi, "_");}setParent(parent: TypedComponent<any>) {@@ -48,18 +48,13 @@ export class TypedComponent<ChildT extends TypedComponent<ChildT>> {handleEvent(name: string, data: unknown): Promise<unknown> | null {try {- const callMethodPromise = this.initialized- ? this.initialized.then(() => this.callMethod((this as any)[`${name}Event`], data))- : this.callMethod((this as any)[`${name}Event`], data);+ const callMethodPromise = this.initialized ? this.initialized.then(() => this.callMethod((this as any)[`${name}Event`], data)) : this.callMethod((this as any)[`${name}Event`], data);const childrenPromise = this.handleEventInChildren(name, data);// don't create promises if not needed (optimization)- return callMethodPromise && childrenPromise- ? Promise.all([callMethodPromise, childrenPromise])- : (callMethodPromise || childrenPromise);- }- catch (e: any) {+ return callMethodPromise && childrenPromise ? Promise.all([callMethodPromise, childrenPromise]) : callMethodPromise || childrenPromise;+ } catch (e: any) {console.error(`Handling of event '${name}' failed in ${this.constructor.name} with error ${e.message} ${e.stack}`);return null;@@ -101,7 +96,7 @@ export class TypedComponent<ChildT extends TypedComponent<ChildT>> {}callMethod(fun: (arg: unknown) => Promise<unknown>, data: unknown) {- if (typeof fun !== 'function') {+ if (typeof fun !== "function") {return;}@@ -111,7 +106,8 @@ export class TypedComponent<ChildT extends TypedComponent<ChildT>> {const took = Date.now() - startTime;- if (glob.isDev && took > 20) { // measuring only sync handlers+ if (glob.isDev && took > 20) {+ // measuring only sync handlersconsole.log(`Call to ${fun.name} in ${this.componentId} took ${took}ms`);}diff --git a/src/public/app/components/entrypoints.ts b/src/public/app/components/entrypoints.tsindex 1aae586a30..571d554b23 100644--- a/src/public/app/components/entrypoints.ts+++ b/src/public/app/components/entrypoints.ts@@ -1,6 +1,6 @@import utils from "../services/utils.js";import dateNoteService from "../services/date_notes.js";-import protectedSessionHolder from '../services/protected_session_holder.js';+import protectedSessionHolder from "../services/protected_session_holder.js";import server from "../services/server.js";import appContext, { NoteCommandData } from "./app_context.js";import Component from "./component.js";@@ -41,7 +41,7 @@ export default class Entrypoints extends Component {openDevToolsCommand() {if (utils.isElectron()) {- utils.dynamicRequire('@electron/remote').getCurrentWindow().toggleDevTools();+ utils.dynamicRequire("@electron/remote").getCurrentWindow().toggleDevTools();}}@@ -52,20 +52,20 @@ export default class Entrypoints extends Component {return;}- const {note} = await server.post<CreateChildrenResponse>(`notes/${inboxNote.noteId}/children?target=into`, {- content: '',- type: 'text',+ const { note } = await server.post<CreateChildrenResponse>(`notes/${inboxNote.noteId}/children?target=into`, {+ content: "",+ type: "text",isProtected: inboxNote.isProtected && protectedSessionHolder.isProtectedSessionAvailable()});await ws.waitForMaxKnownEntityChangeId();- await appContext.tabManager.openTabWithNoteWithHoisting(note.noteId, {activate: true});+ await appContext.tabManager.openTabWithNoteWithHoisting(note.noteId, { activate: true });- appContext.triggerEvent('focusAndSelectTitle', {isNewNote: true});+ appContext.triggerEvent("focusAndSelectTitle", { isNewNote: true });}- async toggleNoteHoistingCommand({noteId = appContext.tabManager.getActiveContextNoteId()}) {+ async toggleNoteHoistingCommand({ noteId = appContext.tabManager.getActiveContextNoteId() }) {if (!noteId) {return;}@@ -75,12 +75,12 @@ export default class Entrypoints extends Component {if (noteToHoist?.noteId === activeNoteContext.hoistedNoteId) {await activeNoteContext.unhoist();- } else if (noteToHoist?.type !== 'search') {+ } else if (noteToHoist?.type !== "search") {await activeNoteContext.setHoistedNoteId(noteId);}}- async hoistNoteCommand({noteId}: { noteId: string }) {+ async hoistNoteCommand({ noteId }: { noteId: string }) {const noteContext = appContext.tabManager.getActiveContext();if (noteContext.hoistedNoteId !== noteId) {@@ -102,7 +102,7 @@ export default class Entrypoints extends Component {toggleFullscreenCommand() {if (utils.isElectron()) {- const win = utils.dynamicRequire('@electron/remote').getCurrentWindow();+ const win = utils.dynamicRequire("@electron/remote").getCurrentWindow();if (win.isFullScreenable()) {win.setFullScreen(!win.isFullScreen());@@ -115,22 +115,20 @@ export default class Entrypoints extends Component {}logoutCommand() {- const $logoutForm = $('<form action="logout" method="POST">')- .append($(`<input type='_hidden' name="_csrf" value="${glob.csrfToken}"/>`));+ const $logoutForm = $('<form action="logout" method="POST">').append($(`<input type='_hidden' name="_csrf" value="${glob.csrfToken}"/>`));$("body").append($logoutForm);- $logoutForm.trigger('submit');+ $logoutForm.trigger("submit");}backInNoteHistoryCommand() {if (utils.isElectron()) {// standard JS version does not work completely correctly in electron- const webContents = utils.dynamicRequire('@electron/remote').getCurrentWebContents();+ const webContents = utils.dynamicRequire("@electron/remote").getCurrentWebContents();const activeIndex = parseInt(webContents.navigationHistory.getActiveIndex());webContents.goToIndex(activeIndex - 1);- }- else {+ } else {window.history.back();}}@@ -138,52 +136,50 @@ export default class Entrypoints extends Component {forwardInNoteHistoryCommand() {if (utils.isElectron()) {// standard JS version does not work completely correctly in electron- const webContents = utils.dynamicRequire('@electron/remote').getCurrentWebContents();+ const webContents = utils.dynamicRequire("@electron/remote").getCurrentWebContents();const activeIndex = parseInt(webContents.navigationHistory.getActiveIndex());webContents.goToIndex(activeIndex + 1);- }- else {+ } else {window.history.forward();}}async switchToDesktopVersionCommand() {- utils.setCookie('trilium-device', 'desktop');+ utils.setCookie("trilium-device", "desktop");utils.reloadFrontendApp("Switching to desktop version");}async switchToMobileVersionCommand() {- utils.setCookie('trilium-device', 'mobile');+ utils.setCookie("trilium-device", "mobile");utils.reloadFrontendApp("Switching to mobile version");}- async openInWindowCommand({notePath, hoistedNoteId, viewScope}: NoteCommandData) {- const extraWindowHash = linkService.calculateHash({notePath, hoistedNoteId, viewScope});+ async openInWindowCommand({ notePath, hoistedNoteId, viewScope }: NoteCommandData) {+ const extraWindowHash = linkService.calculateHash({ notePath, hoistedNoteId, viewScope });if (utils.isElectron()) {- const {ipcRenderer} = utils.dynamicRequire('electron');+ const { ipcRenderer } = utils.dynamicRequire("electron");- ipcRenderer.send('create-extra-window', { extraWindowHash });- }- else {+ ipcRenderer.send("create-extra-window", { extraWindowHash });+ } else {const url = `${window.location.protocol}//${window.location.host}${window.location.pathname}?extraWindow=1${extraWindowHash}`;- window.open(url, '', 'width=1000,height=800');+ window.open(url, "", "width=1000,height=800");}}async openNewWindowCommand() {- this.openInWindowCommand({notePath: '', hoistedNoteId: 'root'});+ this.openInWindowCommand({ notePath: "", hoistedNoteId: "root" });}async runActiveNoteCommand() {- const {ntxId, note} = appContext.tabManager.getActiveContext();+ const { ntxId, note } = appContext.tabManager.getActiveContext();// ctrl+enter is also used elsewhere, so make sure we're running only when appropriate- if (!note || note.type !== 'code') {+ if (!note || note.type !== "code") {return;}@@ -192,14 +188,14 @@ export default class Entrypoints extends Component {await bundleService.getAndExecuteBundle(note.noteId);} else if (note.mime.endsWith("env=backend")) {await server.post(`script/run/${note.noteId}`);- } else if (note.mime === 'text/x-sqlite;schema=trilium') {+ } else if (note.mime === "text/x-sqlite;schema=trilium") {const resp = await server.post<SqlExecuteResponse>(`sql/execute/${note.noteId}`);if (!resp.success) {toastService.showError(t("entrypoints.sql-error", { message: resp.error }));}- await appContext.triggerEvent('sqlQueryResults', {ntxId: ntxId, results: resp.results});+ await appContext.triggerEvent("sqlQueryResults", { ntxId: ntxId, results: resp.results });}toastService.showMessage(t("entrypoints.note-executed"));diff --git a/src/public/app/components/main_tree_executors.ts b/src/public/app/components/main_tree_executors.tsindex add809a08c..78251d67c3 100644--- a/src/public/app/components/main_tree_executors.ts+++ b/src/public/app/components/main_tree_executors.ts@@ -19,9 +19,9 @@ export default class MainTreeExecutors extends Component {return;}- const selectedOrActiveNoteIds = this.tree.getSelectedOrActiveNodes().map(node => node.data.noteId);+ const selectedOrActiveNoteIds = this.tree.getSelectedOrActiveNodes().map((node) => node.data.noteId);- this.triggerCommand('cloneNoteIdsTo', {noteIds: selectedOrActiveNoteIds});+ this.triggerCommand("cloneNoteIdsTo", { noteIds: selectedOrActiveNoteIds });}async moveNotesToCommand() {@@ -29,9 +29,9 @@ export default class MainTreeExecutors extends Component {return;}- const selectedOrActiveBranchIds = this.tree.getSelectedOrActiveNodes().map(node => node.data.branchId);+ const selectedOrActiveBranchIds = this.tree.getSelectedOrActiveNodes().map((node) => node.data.branchId);- this.triggerCommand('moveBranchIdsTo', {branchIds: selectedOrActiveBranchIds});+ this.triggerCommand("moveBranchIdsTo", { branchIds: selectedOrActiveBranchIds });}async createNoteIntoCommand() {@@ -61,12 +61,12 @@ export default class MainTreeExecutors extends Component {const parentNotePath = treeService.getNotePath(node.getParent());const isProtected = treeService.getParentProtectedStatus(node);- if (node.data.noteId === 'root' || node.data.noteId === hoistedNoteService.getHoistedNoteId()) {+ if (node.data.noteId === "root" || node.data.noteId === hoistedNoteService.getHoistedNoteId()) {return;}await noteCreateService.createNote(parentNotePath, {- target: 'after',+ target: "after",targetBranchId: node.data.branchId,isProtected: isProtected,saveSelection: falsediff --git a/src/public/app/components/mobile_screen_switcher.ts b/src/public/app/components/mobile_screen_switcher.tsindex 217bbc3fe6..a11ed1ffca 100644--- a/src/public/app/components/mobile_screen_switcher.ts+++ b/src/public/app/components/mobile_screen_switcher.ts@@ -3,15 +3,13 @@ import type { CommandListener, CommandListenerData } from "./app_context.js";export type Screen = "detail" | "tree";-export default class MobileScreenSwitcherExecutor extends Component- implements CommandListener<"setActiveScreen">-{+export default class MobileScreenSwitcherExecutor extends Component implements CommandListener<"setActiveScreen"> {private activeScreen?: Screen;- setActiveScreenCommand({screen}: CommandListenerData<"setActiveScreen">) {+ setActiveScreenCommand({ screen }: CommandListenerData<"setActiveScreen">) {if (screen !== this.activeScreen) {this.activeScreen = screen;- this.triggerEvent('activeScreenChanged', {activeScreen: screen});+ this.triggerEvent("activeScreenChanged", { activeScreen: screen });}}}diff --git a/src/public/app/components/note_context.ts b/src/public/app/components/note_context.tsindex b18ec7e7a5..7af3f94afb 100644--- a/src/public/app/components/note_context.ts+++ b/src/public/app/components/note_context.ts@@ -17,10 +17,7 @@ interface SetNoteOpts {export type GetTextEditorCallback = () => void;-class NoteContext extends Component- implements EventListener<"entitiesReloaded">-{-+class NoteContext extends Component implements EventListener<"entitiesReloaded"> {ntxId: string | null;hoistedNoteId: string;private mainNtxId: string | null;@@ -30,7 +27,7 @@ class NoteContext extends Componentprivate parentNoteId?: string | null;viewScope?: ViewScope;- constructor(ntxId: string | null = null, hoistedNoteId: string = 'root', mainNtxId: string | null = null) {+ constructor(ntxId: string | null = null, hoistedNoteId: string = "root", mainNtxId: string | null = null) {super();this.ntxId = ntxId || NoteContext.generateNtxId();@@ -50,7 +47,7 @@ class NoteContext extends Componentthis.parentNoteId = null;// hoisted note is kept intentionally- this.triggerEvent('noteSwitched', {+ this.triggerEvent("noteSwitched", {noteContext: this,notePath: this.notePath});@@ -81,20 +78,20 @@ class NoteContext extends Componentreturn;}- await this.triggerEvent('beforeNoteSwitch', {noteContext: this});+ await this.triggerEvent("beforeNoteSwitch", { noteContext: this });utils.closeActiveDialog();this.notePath = resolvedNotePath;this.viewScope = opts.viewScope;- ({noteId: this.noteId, parentNoteId: this.parentNoteId} = treeService.getNoteIdAndParentIdFromUrl(resolvedNotePath));+ ({ noteId: this.noteId, parentNoteId: this.parentNoteId } = treeService.getNoteIdAndParentIdFromUrl(resolvedNotePath));this.saveToRecentNotes(resolvedNotePath);protectedSessionHolder.touchProtectedSessionIfNecessary(this.note);if (opts.triggerSwitchEvent) {- await this.triggerEvent('noteSwitched', {+ await this.triggerEvent("noteSwitched", {noteContext: this,notePath: this.notePath});@@ -103,23 +100,20 @@ class NoteContext extends Componentawait this.setHoistedNoteIfNeeded();if (utils.isMobile()) {- this.triggerCommand('setActiveScreen', {screen: 'detail'});+ this.triggerCommand("setActiveScreen", { screen: "detail" });}}async setHoistedNoteIfNeeded() {- if (this.hoistedNoteId === 'root'- && this.notePath?.startsWith("root/_hidden")- && !this.note?.isLabelTruthy("keepCurrentHoisting")- ) {+ if (this.hoistedNoteId === "root" && this.notePath?.startsWith("root/_hidden") && !this.note?.isLabelTruthy("keepCurrentHoisting")) {// hidden subtree displays only when hoisted, so it doesn't make sense to keep root as hoisted note- let hoistedNoteId = '_hidden';+ let hoistedNoteId = "_hidden";if (this.note?.isLaunchBarConfig()) {- hoistedNoteId = '_lbRoot';+ hoistedNoteId = "_lbRoot";} else if (this.note?.isOptions()) {- hoistedNoteId = '_options';+ hoistedNoteId = "_options";}await this.setHoistedNoteId(hoistedNoteId);@@ -127,7 +121,7 @@ class NoteContext extends Component}getSubContexts() {- return appContext.tabManager.noteContexts.filter(nc => nc.ntxId === this.ntxId || nc.mainNtxId === this.ntxId);+ return appContext.tabManager.noteContexts.filter((nc) => nc.ntxId === this.ntxId || nc.mainNtxId === this.ntxId);}/**@@ -152,13 +146,11 @@ class NoteContext extends Componentif (this.mainNtxId) {try {return appContext.tabManager.getNoteContextById(this.mainNtxId);- }- catch (e) {+ } catch (e) {this.mainNtxId = null;return this;}- }- else {+ } else {return this;}}@@ -167,7 +159,7 @@ class NoteContext extends ComponentsetTimeout(async () => {// we include the note in the recent list only if the user stayed on the note at least 5 secondsif (resolvedNotePath && resolvedNotePath === this.notePath) {- await server.post('recent-notes', {+ await server.post("recent-notes", {noteId: this.note?.noteId,notePath: this.notePath});@@ -183,7 +175,7 @@ class NoteContext extends Componentreturn;}- if (await hoistedNoteService.checkNoteAccess(resolvedNotePath, this) === false) {+ if ((await hoistedNoteService.checkNoteAccess(resolvedNotePath, this)) === false) {return; // note is outside of hoisted subtree and user chose not to unhoist}@@ -200,7 +192,7 @@ class NoteContext extends Component/** @returns {string[]} */get notePathArray() {- return this.notePath ? this.notePath.split('/') : [];+ return this.notePath ? this.notePath.split("/") : [];}isActive() {@@ -208,7 +200,7 @@ class NoteContext extends Component}getPojoState() {- if (this.hoistedNoteId !== 'root') {+ if (this.hoistedNoteId !== "root") {// keeping empty hoisted tab is esp. important for mobile (e.g. opened launcher config)if (!this.notePath && this.getSubContexts().length === 0) {@@ -223,11 +215,11 @@ class NoteContext extends ComponenthoistedNoteId: this.hoistedNoteId,active: this.isActive(),viewScope: this.viewScope- }+ };}async unhoist() {- await this.setHoistedNoteId('root');+ await this.setHoistedNoteId("root");}async setHoistedNoteId(noteIdToHoist: string) {@@ -241,7 +233,7 @@ class NoteContext extends Componentawait this.setNote(noteIdToHoist);}- await this.triggerEvent('hoistedNoteChanged', {+ await this.triggerEvent("hoistedNoteChanged", {noteId: noteIdToHoist,ntxId: this.ntxId});@@ -254,15 +246,15 @@ class NoteContext extends Component}// "readOnly" is a state valid only for text/code notes- if (!this.note || (this.note.type !== 'text' && this.note.type !== 'code')) {+ if (!this.note || (this.note.type !== "text" && this.note.type !== "code")) {return false;}- if (this.note.isLabelTruthy('readOnly')) {+ if (this.note.isLabelTruthy("readOnly")) {return true;}- if (this.viewScope?.viewMode === 'source') {+ if (this.viewScope?.viewMode === "source") {return true;}@@ -271,24 +263,20 @@ class NoteContext extends Componentreturn false;}- const sizeLimit = this.note.type === 'text'- ? options.getInt('autoReadonlySizeText')- : options.getInt('autoReadonlySizeCode');+ const sizeLimit = this.note.type === "text" ? options.getInt("autoReadonlySizeText") : options.getInt("autoReadonlySizeCode");- return sizeLimit- && blob.contentLength > sizeLimit- && !this.note.isLabelTruthy('autoReadOnlyDisabled');+ return sizeLimit && blob.contentLength > sizeLimit && !this.note.isLabelTruthy("autoReadOnlyDisabled");}- async entitiesReloadedEvent({loadResults}: EventData<"entitiesReloaded">) {+ async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {if (this.noteId && loadResults.isNoteReloaded(this.noteId)) {- const noteRow = loadResults.getEntityRow('notes', this.noteId);+ const noteRow = loadResults.getEntityRow("notes", this.noteId);if (noteRow.isDeleted) {this.noteId = null;this.notePath = null;- this.triggerEvent('noteSwitched', {+ this.triggerEvent("noteSwitched", {noteContext: this,notePath: this.notePath});@@ -297,48 +285,63 @@ class NoteContext extends Component}hasNoteList() {- return this.note- && this.viewScope?.viewMode === 'default'- && this.note.hasChildren()- && ['book', 'text', 'code'].includes(this.note.type)- && this.note.mime !== 'text/x-sqlite;schema=trilium'- && !this.note.isLabelTruthy('hideChildrenOverview');+ return (+ this.note &&+ this.viewScope?.viewMode === "default" &&+ this.note.hasChildren() &&+ ["book", "text", "code"].includes(this.note.type) &&+ this.note.mime !== "text/x-sqlite;schema=trilium" &&+ !this.note.isLabelTruthy("hideChildrenOverview")+ );}async getTextEditor(callback?: GetTextEditorCallback) {- return this.timeout<TextEditor>(new Promise(resolve => appContext.triggerCommand('executeWithTextEditor', {- callback,- resolve,- ntxId: this.ntxId- })));+ return this.timeout<TextEditor>(+ new Promise((resolve) =>+ appContext.triggerCommand("executeWithTextEditor", {+ callback,+ resolve,+ ntxId: this.ntxId+ })+ )+ );}async getCodeEditor() {- return this.timeout(new Promise(resolve => appContext.triggerCommand('executeWithCodeEditor', {- resolve,- ntxId: this.ntxId- })));+ return this.timeout(+ new Promise((resolve) =>+ appContext.triggerCommand("executeWithCodeEditor", {+ resolve,+ ntxId: this.ntxId+ })+ )+ );}async getContentElement() {- return this.timeout<JQuery<HTMLElement>>(new Promise(resolve => appContext.triggerCommand('executeWithContentElement', {- resolve,- ntxId: this.ntxId- })));+ return this.timeout<JQuery<HTMLElement>>(+ new Promise((resolve) =>+ appContext.triggerCommand("executeWithContentElement", {+ resolve,+ ntxId: this.ntxId+ })+ )+ );}async getTypeWidget() {- return this.timeout(new Promise(resolve => appContext.triggerCommand('executeWithTypeWidget', {- resolve,- ntxId: this.ntxId- })));+ return this.timeout(+ new Promise((resolve) =>+ appContext.triggerCommand("executeWithTypeWidget", {+ resolve,+ ntxId: this.ntxId+ })+ )+ );}timeout<T>(promise: Promise<T | null>) {- return Promise.race([- promise,- new Promise(res => setTimeout(() => res(null), 200))- ]) as Promise<T>;+ return Promise.race([promise, new Promise((res) => setTimeout(() => res(null), 200))]) as Promise<T>;}resetViewScope() {@@ -355,9 +358,7 @@ class NoteContext extends Componentconst { note, viewScope } = this;- let title = viewScope?.viewMode === 'default'- ? note.title- : `${note.title}: ${viewScope?.viewMode}`;+ let title = viewScope?.viewMode === "default" ? note.title : `${note.title}: ${viewScope?.viewMode}`;if (viewScope?.attachmentId) {// assuming the attachment has been already loadeddiff --git a/src/public/app/components/root_command_executor.ts b/src/public/app/components/root_command_executor.tsindex afc3ec8fda..643f02c7be 100644--- a/src/public/app/components/root_command_executor.ts+++ b/src/public/app/components/root_command_executor.ts@@ -25,11 +25,11 @@ export default class RootCommandExecutor extends Component {const noteContext = await appContext.tabManager.openTabWithNoteWithHoisting(sqlConsoleNote.noteId, { activate: true });- appContext.triggerEvent('focusOnDetail', {ntxId: noteContext.ntxId});+ appContext.triggerEvent("focusOnDetail", { ntxId: noteContext.ntxId });}- async searchNotesCommand({searchString, ancestorNoteId}: CommandListenerData<"searchNotes">) {- const searchNote = await dateNoteService.createSearchNote({searchString, ancestorNoteId});+ async searchNotesCommand({ searchString, ancestorNoteId }: CommandListenerData<"searchNotes">) {+ const searchNote = await dateNoteService.createSearchNote({ searchString, ancestorNoteId });if (!searchNote) {return;}@@ -41,13 +41,13 @@ export default class RootCommandExecutor extends Component {activate: true});- appContext.triggerCommand('focusOnSearchDefinition', {ntxId: noteContext.ntxId});+ appContext.triggerCommand("focusOnSearchDefinition", { ntxId: noteContext.ntxId });}- async searchInSubtreeCommand({notePath}: CommandListenerData<"searchInSubtree">) {+ async searchInSubtreeCommand({ notePath }: CommandListenerData<"searchInSubtree">) {const noteId = treeService.getNoteIdFromUrl(notePath);- this.searchNotesCommand({ancestorNoteId: noteId});+ this.searchNotesCommand({ ancestorNoteId: noteId });}openNoteExternallyCommand() {@@ -83,11 +83,11 @@ export default class RootCommandExecutor extends Component {}toggleLeftPaneCommand() {- options.toggle('leftPaneVisible');+ options.toggle("leftPaneVisible");}async showBackendLogCommand() {- await appContext.tabManager.openTabWithNoteWithHoisting('_backendLog', { activate: true });+ await appContext.tabManager.openTabWithNoteWithHoisting("_backendLog", { activate: true });}async showLaunchBarSubtreeCommand() {@@ -97,26 +97,26 @@ export default class RootCommandExecutor extends Component {}async showShareSubtreeCommand() {- await this.showAndHoistSubtree('_share');+ await this.showAndHoistSubtree("_share");}async showHiddenSubtreeCommand() {- await this.showAndHoistSubtree('_hidden');+ await this.showAndHoistSubtree("_hidden");}- async showOptionsCommand({section}: CommandListenerData<"showOptions">) {- await appContext.tabManager.openContextWithNote(section || '_options', {+ async showOptionsCommand({ section }: CommandListenerData<"showOptions">) {+ await appContext.tabManager.openContextWithNote(section || "_options", {activate: true,- hoistedNoteId: '_options'+ hoistedNoteId: "_options"});}async showSQLConsoleHistoryCommand() {- await this.showAndHoistSubtree('_sqlConsole');+ await this.showAndHoistSubtree("_sqlConsole");}async showSearchHistoryCommand() {- await this.showAndHoistSubtree('_search');+ await this.showAndHoistSubtree("_search");}async showAndHoistSubtree(subtreeNoteId: string) {@@ -133,7 +133,7 @@ export default class RootCommandExecutor extends Component {await appContext.tabManager.openTabWithNoteWithHoisting(notePath, {activate: true,viewScope: {- viewMode: 'source'+ viewMode: "source"}});}@@ -146,7 +146,7 @@ export default class RootCommandExecutor extends Component {await appContext.tabManager.openTabWithNoteWithHoisting(notePath, {activate: true,viewScope: {- viewMode: 'attachments'+ viewMode: "attachments"}});}@@ -159,7 +159,7 @@ export default class RootCommandExecutor extends Component {await appContext.tabManager.openTabWithNoteWithHoisting(notePath, {activate: true,viewScope: {- viewMode: 'attachments'+ viewMode: "attachments"}});}@@ -167,23 +167,43 @@ export default class RootCommandExecutor extends Component {toggleTrayCommand() {if (!utils.isElectron()) return;- const {BrowserWindow} = utils.dynamicRequire('@electron/remote');- const windows = (BrowserWindow.getAllWindows()) as Electron.BaseWindow[];- const isVisible = windows.every(w => w.isVisible());- const action = isVisible ? "hide" : "show"+ const { BrowserWindow } = utils.dynamicRequire("@electron/remote");+ const windows = BrowserWindow.getAllWindows() as Electron.BaseWindow[];+ const isVisible = windows.every((w) => w.isVisible());+ const action = isVisible ? "hide" : "show";for (const window of windows) window[action]();}- firstTabCommand() { this.#goToTab(1); }- secondTabCommand() { this.#goToTab(2); }- thirdTabCommand() { this.#goToTab(3); }- fourthTabCommand() { this.#goToTab(4); }- fifthTabCommand() { this.#goToTab(5); }- sixthTabCommand() { this.#goToTab(6); }- seventhTabCommand() { this.#goToTab(7); }- eigthTabCommand() { this.#goToTab(8); }- ninthTabCommand() { this.#goToTab(9); }- lastTabCommand() { this.#goToTab(Number.POSITIVE_INFINITY); }+ firstTabCommand() {+ this.#goToTab(1);+ }+ secondTabCommand() {+ this.#goToTab(2);+ }+ thirdTabCommand() {+ this.#goToTab(3);+ }+ fourthTabCommand() {+ this.#goToTab(4);+ }+ fifthTabCommand() {+ this.#goToTab(5);+ }+ sixthTabCommand() {+ this.#goToTab(6);+ }+ seventhTabCommand() {+ this.#goToTab(7);+ }+ eigthTabCommand() {+ this.#goToTab(8);+ }+ ninthTabCommand() {+ this.#goToTab(9);+ }+ lastTabCommand() {+ this.#goToTab(Number.POSITIVE_INFINITY);+ }#goToTab(tabNumber: number) {const mainNoteContexts = appContext.tabManager.getMainNoteContexts();diff --git a/src/public/app/components/shortcut_component.ts b/src/public/app/components/shortcut_component.tsindex 4d01a05889..d2b1ee8b07 100644--- a/src/public/app/components/shortcut_component.ts+++ b/src/public/app/components/shortcut_component.ts@@ -5,13 +5,11 @@ import Component from "./component.js";import froca from "../services/froca.js";import { AttributeRow } from "../services/load_results.js";-export default class ShortcutComponent extends Component- implements EventListener<"entitiesReloaded">-{+export default class ShortcutComponent extends Component implements EventListener<"entitiesReloaded"> {constructor() {super();- server.get<AttributeRow[]>('keyboard-shortcuts-for-notes').then(shortcutAttributes => {+ server.get<AttributeRow[]>("keyboard-shortcuts-for-notes").then((shortcutAttributes) => {for (const attr of shortcutAttributes) {this.bindNoteShortcutHandler(attr);}@@ -22,7 +20,8 @@ export default class ShortcutComponent extends Componentconst handler = () => appContext.tabManager.getActiveContext().setNote(labelOrRow.noteId);const namespace = labelOrRow.attributeId;- if (labelOrRow.isDeleted) { // only applicable if row+ if (labelOrRow.isDeleted) {+ // only applicable if rowif (namespace) {shortcutService.removeGlobalShortcut(namespace);}@@ -31,12 +30,12 @@ export default class ShortcutComponent extends Component}}- async entitiesReloadedEvent({loadResults}: EventData<"entitiesReloaded">) {+ async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {for (const attr of loadResults.getAttributeRows()) {- if (attr.type === 'label' && attr.name === 'keyboardShortcut' && attr.noteId) {+ if (attr.type === "label" && attr.name === "keyboardShortcut" && attr.noteId) {const note = await froca.getNote(attr.noteId);// launcher shortcuts are handled specifically- if (note && attr && note.type !== 'launcher') {+ if (note && attr && note.type !== "launcher") {this.bindNoteShortcutHandler(attr);}}diff --git a/src/public/app/components/tab_manager.js b/src/public/app/components/tab_manager.jsindex ccff6f89e6..7a7b2f2cfb 100644--- a/src/public/app/components/tab_manager.js+++ b/src/public/app/components/tab_manager.js@@ -28,11 +28,9 @@ export default class TabManager extends Component {return;}- const openNoteContexts = this.noteContexts- .map(nc => nc.getPojoState())- .filter(t => !!t);+ const openNoteContexts = this.noteContexts.map((nc) => nc.getPojoState()).filter((t) => !!t);- await server.put('options', {+ await server.put("options", {openNoteContexts: JSON.stringify(openNoteContexts)});});@@ -47,21 +45,17 @@ export default class TabManager extends Component {/** @type {NoteContext[]} */get mainNoteContexts() {- return this.noteContexts.filter(nc => !nc.mainNtxId)+ return this.noteContexts.filter((nc) => !nc.mainNtxId);}async loadTabs() {try {- const noteContextsToOpen = (appContext.isMainWindow && options.getJson('openNoteContexts')) || [];+ const noteContextsToOpen = (appContext.isMainWindow && options.getJson("openNoteContexts")) || [];// preload all notes at once- await froca.getNotes([- ...noteContextsToOpen.flatMap(tab =>- [ treeService.getNoteIdFromUrl(tab.notePath), tab.hoistedNoteId]- ),- ], true);+ await froca.getNotes([...noteContextsToOpen.flatMap((tab) => [treeService.getNoteIdFromUrl(tab.notePath), tab.hoistedNoteId])], true);- const filteredNoteContexts = noteContextsToOpen.filter(openTab => {+ const filteredNoteContexts = noteContextsToOpen.filter((openTab) => {const noteId = treeService.getNoteIdFromUrl(openTab.notePath);if (!(noteId in froca.notes)) {// note doesn't exist so don't try to open tab for it@@ -69,7 +63,7 @@ export default class TabManager extends Component {}if (!(openTab.hoistedNoteId in froca.notes)) {- openTab.hoistedNoteId = 'root';+ openTab.hoistedNoteId = "root";}return true;@@ -82,13 +76,13 @@ export default class TabManager extends Component {parsedFromUrl.ntxId = parsedFromUrl.ntxId || NoteContext.generateNtxId(); // generate already here, so that we later know which one to activatefilteredNoteContexts.push({- notePath: parsedFromUrl.notePath || 'root',+ notePath: parsedFromUrl.notePath || "root",ntxId: parsedFromUrl.ntxId,active: true,- hoistedNoteId: parsedFromUrl.hoistedNoteId || 'root',+ hoistedNoteId: parsedFromUrl.hoistedNoteId || "root",viewScope: parsedFromUrl.viewScope || {}});- } else if (!filteredNoteContexts.find(tab => tab.active)) {+ } else if (!filteredNoteContexts.find((tab) => tab.active)) {filteredNoteContexts[0].active = true;}@@ -107,27 +101,21 @@ export default class TabManager extends Component {// if there's a notePath in the URL, make sure it's open and active// (useful, for e.g., opening clipped notes from clipper or opening link in an extra window)if (parsedFromUrl.notePath) {- await appContext.tabManager.switchToNoteContext(- parsedFromUrl.ntxId,- parsedFromUrl.notePath,- parsedFromUrl.viewScope,- parsedFromUrl.hoistedNoteId- );+ await appContext.tabManager.switchToNoteContext(parsedFromUrl.ntxId, parsedFromUrl.notePath, parsedFromUrl.viewScope, parsedFromUrl.hoistedNoteId);} else if (parsedFromUrl.searchString) {- await appContext.triggerCommand('searchNotes', {+ await appContext.triggerCommand("searchNotes", {searchString: parsedFromUrl.searchString});}- }- catch (e) {- logError(`Loading note contexts '${options.get('openNoteContexts')}' failed: ${e.message} ${e.stack}`);+ } catch (e) {+ logError(`Loading note contexts '${options.get("openNoteContexts")}' failed: ${e.message} ${e.stack}`);// try to recoverawait this.openEmptyTab();}}- noteSwitchedEvent({noteContext}) {+ noteSwitchedEvent({ noteContext }) {if (noteContext.isActive()) {this.setCurrentNavigationStateToHash();}@@ -147,7 +135,7 @@ export default class TabManager extends Component {const activeNoteContext = this.getActiveContext();this.updateDocumentTitle(activeNoteContext);- this.triggerEvent('activeNoteChanged'); // trigger this even in on popstate event+ this.triggerEvent("activeNoteChanged"); // trigger this even in on popstate event}calculateHash() {@@ -174,12 +162,12 @@ export default class TabManager extends Component {* @returns {NoteContext[]}*/getMainNoteContexts() {- return this.noteContexts.filter(nc => nc.isMainContext());+ return this.noteContexts.filter((nc) => nc.isMainContext());}/** @returns {NoteContext} */getNoteContextById(ntxId) {- const noteContext = this.noteContexts.find(nc => nc.ntxId === ntxId);+ const noteContext = this.noteContexts.find((nc) => nc.ntxId === ntxId);if (!noteContext) {throw new Error(`Cannot find noteContext id='${ntxId}'`);@@ -194,9 +182,7 @@ export default class TabManager extends Component {* @returns {NoteContext}*/getActiveContext() {- return this.activeNtxId- ? this.getNoteContextById(this.activeNtxId)- : null;+ return this.activeNtxId ? this.getNoteContextById(this.activeNtxId) : null;}/**@@ -205,9 +191,7 @@ export default class TabManager extends Component {* @returns {NoteContext}*/getActiveMainContext() {- return this.activeNtxId- ? this.getNoteContextById(this.activeNtxId).getMainContext()- : null;+ return this.activeNtxId ? this.getNoteContextById(this.activeNtxId).getMainContext() : null;}/** @returns {string|null} */@@ -243,8 +227,7 @@ export default class TabManager extends Component {}async switchToNoteContext(ntxId, notePath, viewScope = {}, hoistedNoteId = null) {- const noteContext = this.noteContexts.find(nc => nc.ntxId === ntxId)- || await this.openEmptyTab();+ const noteContext = this.noteContexts.find((nc) => nc.ntxId === ntxId) || (await this.openEmptyTab());await this.activateNoteContext(noteContext.ntxId);@@ -265,10 +248,10 @@ export default class TabManager extends Component {await noteContext.setEmpty();}- async openEmptyTab(ntxId = null, hoistedNoteId = 'root', mainNtxId = null) {+ async openEmptyTab(ntxId = null, hoistedNoteId = "root", mainNtxId = null) {const noteContext = new NoteContext(ntxId, hoistedNoteId, mainNtxId);- const existingNoteContext = this.children.find(nc => nc.ntxId === noteContext.ntxId);+ const existingNoteContext = this.children.find((nc) => nc.ntxId === noteContext.ntxId);if (existingNoteContext) {await existingNoteContext.setHoistedNoteId(hoistedNoteId);@@ -278,7 +261,7 @@ export default class TabManager extends Component {this.child(noteContext);- await this.triggerEvent('newNoteContextCreated', {noteContext});+ await this.triggerEvent("newNoteContextCreated", { noteContext });return noteContext;}@@ -300,12 +283,12 @@ export default class TabManager extends Component {*/async openTabWithNoteWithHoisting(notePath, opts = {}) {const noteContext = this.getActiveContext();- let hoistedNoteId = 'root';+ let hoistedNoteId = "root";if (noteContext) {const resolvedNotePath = await treeService.resolveNotePath(notePath, noteContext.hoistedNoteId);- if (resolvedNotePath.includes(noteContext.hoistedNoteId) || resolvedNotePath.includes('_hidden')) {+ if (resolvedNotePath.includes(noteContext.hoistedNoteId) || resolvedNotePath.includes("_hidden")) {hoistedNoteId = noteContext.hoistedNoteId;}}@@ -319,7 +302,7 @@ export default class TabManager extends Component {const activate = !!opts.activate;const ntxId = opts.ntxId || null;const mainNtxId = opts.mainNtxId || null;- const hoistedNoteId = opts.hoistedNoteId || 'root';+ const hoistedNoteId = opts.hoistedNoteId || "root";const viewScope = opts.viewScope || { viewMode: "default" };const noteContext = await this.openEmptyTab(ntxId, hoistedNoteId, mainNtxId);@@ -335,7 +318,7 @@ export default class TabManager extends Component {if (activate) {this.activateNoteContext(noteContext.ntxId, false);- await this.triggerEvent('noteSwitchedAndActivated', {+ await this.triggerEvent("noteSwitchedAndActivated", {noteContext,notePath: noteContext.notePath // resolved note path});@@ -366,7 +349,7 @@ export default class TabManager extends Component {this.activeNtxId = ntxId;if (triggerEvent) {- await this.triggerEvent('activeContextChanged', {+ await this.triggerEvent("activeContextChanged", {noteContext: this.getNoteContextById(ntxId)});}@@ -388,14 +371,13 @@ export default class TabManager extends Component {try {noteContextToRemove = this.getNoteContextById(ntxId);- }- catch {+ } catch {// note context not foundreturn false;}if (noteContextToRemove.isMainContext()) {- const mainNoteContexts = this.getNoteContexts().filter(nc => nc.isMainContext());+ const mainNoteContexts = this.getNoteContexts().filter((nc) => nc.isMainContext());if (mainNoteContexts.length === 1) {if (noteContextToRemove.isEmpty()) {@@ -415,28 +397,25 @@ export default class TabManager extends Component {}const noteContextsToRemove = noteContextToRemove.getSubContexts();- const ntxIdsToRemove = noteContextsToRemove.map(nc => nc.ntxId);+ const ntxIdsToRemove = noteContextsToRemove.map((nc) => nc.ntxId);- await this.triggerEvent('beforeNoteContextRemove', { ntxIds: ntxIdsToRemove });+ await this.triggerEvent("beforeNoteContextRemove", { ntxIds: ntxIdsToRemove });if (!noteContextToRemove.isMainContext()) {const siblings = noteContextToRemove.getMainContext().getSubContexts();- const idx = siblings.findIndex(nc => nc.ntxId === noteContextToRemove.ntxId);+ const idx = siblings.findIndex((nc) => nc.ntxId === noteContextToRemove.ntxId);const contextToActivateIdx = idx === siblings.length - 1 ? idx - 1 : idx + 1;const contextToActivate = siblings[contextToActivateIdx];await this.activateNoteContext(contextToActivate.ntxId);- }- else if (this.mainNoteContexts.length <= 1) {+ } else if (this.mainNoteContexts.length <= 1) {await this.openAndActivateEmptyTab();- }- else if (ntxIdsToRemove.includes(this.activeNtxId)) {- const idx = this.mainNoteContexts.findIndex(nc => nc.ntxId === noteContextToRemove.ntxId);+ } else if (ntxIdsToRemove.includes(this.activeNtxId)) {+ const idx = this.mainNoteContexts.findIndex((nc) => nc.ntxId === noteContextToRemove.ntxId);if (idx === this.mainNoteContexts.length - 1) {await this.activatePreviousTabCommand();- }- else {+ } else {await this.activateNextTabCommand();}}@@ -448,15 +427,15 @@ export default class TabManager extends Component {}removeNoteContexts(noteContextsToRemove) {- const ntxIdsToRemove = noteContextsToRemove.map(nc => nc.ntxId);+ const ntxIdsToRemove = noteContextsToRemove.map((nc) => nc.ntxId);- const position = this.noteContexts.findIndex(nc => ntxIdsToRemove.includes(nc.ntxId));+ const position = this.noteContexts.findIndex((nc) => ntxIdsToRemove.includes(nc.ntxId));- this.children = this.children.filter(nc => !ntxIdsToRemove.includes(nc.ntxId));+ this.children = this.children.filter((nc) => !ntxIdsToRemove.includes(nc.ntxId));this.addToRecentlyClosedTabs(noteContextsToRemove, position);- this.triggerEvent('noteContextRemoved', {ntxIds: ntxIdsToRemove});+ this.triggerEvent("noteContextRemoved", { ntxIds: ntxIdsToRemove });this.tabsUpdate.scheduleUpdate();}@@ -466,10 +445,10 @@ export default class TabManager extends Component {return;}- this.recentlyClosedTabs.push({contexts: noteContexts, position: position});+ this.recentlyClosedTabs.push({ contexts: noteContexts, position: position });}- tabReorderEvent({ntxIdsInOrder}) {+ tabReorderEvent({ ntxIdsInOrder }) {const order = {};let i = 0;@@ -480,18 +459,18 @@ export default class TabManager extends Component {}}- this.children.sort((a, b) => order[a.ntxId] < order[b.ntxId] ? -1 : 1);+ this.children.sort((a, b) => (order[a.ntxId] < order[b.ntxId] ? -1 : 1));this.tabsUpdate.scheduleUpdate();}- noteContextReorderEvent({ntxIdsInOrder, oldMainNtxId, newMainNtxId}) {+ noteContextReorderEvent({ ntxIdsInOrder, oldMainNtxId, newMainNtxId }) {const order = Object.fromEntries(ntxIdsInOrder.map((v, i) => [v, i]));- this.children.sort((a, b) => order[a.ntxId] < order[b.ntxId] ? -1 : 1);+ this.children.sort((a, b) => (order[a.ntxId] < order[b.ntxId] ? -1 : 1));if (oldMainNtxId && newMainNtxId) {- this.children.forEach(c => {+ this.children.forEach((c) => {if (c.ntxId === newMainNtxId) {// new main context has null mainNtxIdc.mainNtxId = null;@@ -508,7 +487,7 @@ export default class TabManager extends Component {async activateNextTabCommand() {const activeMainNtxId = this.getActiveMainContext().ntxId;- const oldIdx = this.mainNoteContexts.findIndex(nc => nc.ntxId === activeMainNtxId);+ const oldIdx = this.mainNoteContexts.findIndex((nc) => nc.ntxId === activeMainNtxId);const newActiveNtxId = this.mainNoteContexts[oldIdx === this.mainNoteContexts.length - 1 ? 0 : oldIdx + 1].ntxId;await this.activateNoteContext(newActiveNtxId);@@ -517,7 +496,7 @@ export default class TabManager extends Component {async activatePreviousTabCommand() {const activeMainNtxId = this.getActiveMainContext().ntxId;- const oldIdx = this.mainNoteContexts.findIndex(nc => nc.ntxId === activeMainNtxId);+ const oldIdx = this.mainNoteContexts.findIndex((nc) => nc.ntxId === activeMainNtxId);const newActiveNtxId = this.mainNoteContexts[oldIdx === 0 ? this.mainNoteContexts.length - 1 : oldIdx - 1].ntxId;await this.activateNoteContext(newActiveNtxId);@@ -538,21 +517,21 @@ export default class TabManager extends Component {}async closeAllTabsCommand() {- for (const ntxIdToRemove of this.mainNoteContexts.map(nc => nc.ntxId)) {+ for (const ntxIdToRemove of this.mainNoteContexts.map((nc) => nc.ntxId)) {await this.removeNoteContext(ntxIdToRemove);}}- async closeOtherTabsCommand({ntxId}) {- for (const ntxIdToRemove of this.mainNoteContexts.map(nc => nc.ntxId)) {+ async closeOtherTabsCommand({ ntxId }) {+ for (const ntxIdToRemove of this.mainNoteContexts.map((nc) => nc.ntxId)) {if (ntxIdToRemove !== ntxId) {await this.removeNoteContext(ntxIdToRemove);}}}- async closeRightTabsCommand({ntxId}) {- const ntxIds = this.mainNoteContexts.map(nc => nc.ntxId);+ async closeRightTabsCommand({ ntxId }) {+ const ntxIds = this.mainNoteContexts.map((nc) => nc.ntxId);const index = ntxIds.indexOf(ntxId);if (index !== -1) {@@ -563,23 +542,23 @@ export default class TabManager extends Component {}}- async closeTabCommand({ntxId}) {+ async closeTabCommand({ ntxId }) {await this.removeNoteContext(ntxId);}- async moveTabToNewWindowCommand({ntxId}) {- const {notePath, hoistedNoteId} = this.getNoteContextById(ntxId);+ async moveTabToNewWindowCommand({ ntxId }) {+ const { notePath, hoistedNoteId } = this.getNoteContextById(ntxId);const removed = await this.removeNoteContext(ntxId);if (removed) {- this.triggerCommand('openInWindow', {notePath, hoistedNoteId});+ this.triggerCommand("openInWindow", { notePath, hoistedNoteId });}}- async copyTabToNewWindowCommand({ntxId}) {- const {notePath, hoistedNoteId} = this.getNoteContextById(ntxId);- this.triggerCommand('openInWindow', {notePath, hoistedNoteId});+ async copyTabToNewWindowCommand({ ntxId }) {+ const { notePath, hoistedNoteId } = this.getNoteContextById(ntxId);+ this.triggerCommand("openInWindow", { notePath, hoistedNoteId });}async reopenLastTabCommand() {@@ -601,40 +580,38 @@ export default class TabManager extends Component {for (const noteContext of noteContexts) {this.child(noteContext);- await this.triggerEvent('newNoteContextCreated', {noteContext});+ await this.triggerEvent("newNoteContextCreated", { noteContext });}// restore last position of contexts stored in tab managerconst ntxsInOrder = [...this.noteContexts.slice(0, lastClosedTab.position),...this.noteContexts.slice(-noteContexts.length),- ...this.noteContexts.slice(lastClosedTab.position, -noteContexts.length),- ]- await this.noteContextReorderEvent({ntxIdsInOrder: ntxsInOrder.map(nc => nc.ntxId)});+ ...this.noteContexts.slice(lastClosedTab.position, -noteContexts.length)+ ];+ await this.noteContextReorderEvent({ ntxIdsInOrder: ntxsInOrder.map((nc) => nc.ntxId) });- let mainNtx = noteContexts.find(nc => nc.isMainContext());+ let mainNtx = noteContexts.find((nc) => nc.isMainContext());if (mainNtx) {// reopened a tab, need to reorder new tab widget in tab row- await this.triggerEvent('contextsReopened', {+ await this.triggerEvent("contextsReopened", {mainNtxId: mainNtx.ntxId,- tabPosition: ntxsInOrder.filter(nc => nc.isMainContext()).findIndex(nc => nc.ntxId === mainNtx.ntxId)+ tabPosition: ntxsInOrder.filter((nc) => nc.isMainContext()).findIndex((nc) => nc.ntxId === mainNtx.ntxId)});} else {// reopened a single split, need to reorder the pane widget in split note container- await this.triggerEvent('contextsReopened', {+ await this.triggerEvent("contextsReopened", {ntxId: ntxsInOrder[lastClosedTab.position].ntxId,// this is safe since lastClosedTab.position can never be 0 in this caseafterNtxId: ntxsInOrder[lastClosedTab.position - 1].ntxId});}- const noteContextToActivate = noteContexts.length === 1- ? noteContexts[0]- : noteContexts.find(nc => nc.isMainContext());+ const noteContextToActivate = noteContexts.length === 1 ? noteContexts[0] : noteContexts.find((nc) => nc.isMainContext());await this.activateNoteContext(noteContextToActivate.ntxId);- await this.triggerEvent('noteSwitched', {+ await this.triggerEvent("noteSwitched", {noteContext: noteContextToActivate,notePath: noteContextToActivate.notePath});@@ -659,7 +636,7 @@ export default class TabManager extends Component {document.title = titleFragments.join(" - ");}- async entitiesReloadedEvent({loadResults}) {+ async entitiesReloadedEvent({ loadResults }) {const activeContext = this.getActiveContext();if (activeContext && loadResults.isNoteReloaded(activeContext.noteId)) {diff --git a/src/public/app/components/zoom.ts b/src/public/app/components/zoom.tsindex 8a39e3db1f..938700ba0b 100644--- a/src/public/app/components/zoom.ts+++ b/src/public/app/components/zoom.ts@@ -11,13 +11,13 @@ class ZoomComponent extends Component {if (utils.isElectron()) {options.initializedPromise.then(() => {- const zoomFactor = options.getFloat('zoomFactor');+ const zoomFactor = options.getFloat("zoomFactor");if (zoomFactor) {this.setZoomFactor(zoomFactor);}});- window.addEventListener("wheel", event => {+ window.addEventListener("wheel", (event) => {if (event.ctrlKey) {this.setZoomFactorAndSave(this.getCurrentZoom() - event.deltaY * 0.001);}@@ -26,8 +26,8 @@ class ZoomComponent extends Component {}setZoomFactor(zoomFactor: string | number) {- const parsedZoomFactor = (typeof zoomFactor !== "number" ? parseFloat(zoomFactor) : zoomFactor);- const webFrame = utils.dynamicRequire('electron').webFrame;+ const parsedZoomFactor = typeof zoomFactor !== "number" ? parseFloat(zoomFactor) : zoomFactor;+ const webFrame = utils.dynamicRequire("electron").webFrame;webFrame.setZoomFactor(parsedZoomFactor);}@@ -37,15 +37,14 @@ class ZoomComponent extends Component {this.setZoomFactor(zoomFactor);- await options.save('zoomFactor', zoomFactor);- }- else {+ await options.save("zoomFactor", zoomFactor);+ } else {console.log(`Zoom factor ${zoomFactor} outside of the range, ignored.`);}}getCurrentZoom() {- return utils.dynamicRequire('electron').webFrame.getZoomFactor();+ return utils.dynamicRequire("electron").webFrame.getZoomFactor();}zoomOutEvent() {@@ -58,7 +57,7 @@ class ZoomComponent extends Component {zoomResetEvent() {this.setZoomFactorAndSave(1);}-+setZoomFactorAndSaveEvent({ zoomFactor }: { zoomFactor: number }) {this.setZoomFactorAndSave(zoomFactor);}diff --git a/src/public/app/desktop.js b/src/public/app/desktop.jsindex 8dc5ebdff1..60dd8fe5d9 100644--- a/src/public/app/desktop.js+++ b/src/public/app/desktop.js@@ -1,10 +1,10 @@import appContext from "./components/app_context.js";-import utils from './services/utils.js';-import noteTooltipService from './services/note_tooltip.js';+import utils from "./services/utils.js";+import noteTooltipService from "./services/note_tooltip.js";import bundleService from "./services/bundle.js";import toastService from "./services/toast.js";-import noteAutocompleteService from './services/note_autocomplete.js';-import macInit from './services/mac_init.js';+import noteAutocompleteService from "./services/note_autocomplete.js";+import macInit from "./services/mac_init.js";import electronContextMenu from "./menus/electron_context_menu.js";import glob from "./services/glob.js";import { t } from "./services/i18n.js";@@ -12,20 +12,19 @@ import options from "./services/options.js";await appContext.earlyInit();-bundleService.getWidgetBundlesByParent().then(async widgetBundles => {+bundleService.getWidgetBundlesByParent().then(async (widgetBundles) => {// A dynamic import is required for layouts since they initialize components which require translations.const DesktopLayout = (await import("./layouts/desktop_layout.js")).default;appContext.setLayout(new DesktopLayout(widgetBundles));- appContext.start()- .catch((e) => {- toastService.showPersistent({- title: t("toast.critical-error.title"),- icon: "alert",- message: t("toast.critical-error.message", { message: e.message }),- });- console.error("Critical error occured", e);+ appContext.start().catch((e) => {+ toastService.showPersistent({+ title: t("toast.critical-error.title"),+ icon: "alert",+ message: t("toast.critical-error.message", { message: e.message })});+ console.error("Critical error occured", e);+ });});glob.setupGlobs();@@ -45,8 +44,8 @@ if (utils.isElectron()) {}function initOnElectron() {- const electron = utils.dynamicRequire('electron');- electron.ipcRenderer.on('globalShortcut', async (event, actionName) => appContext.triggerCommand(actionName));+ const electron = utils.dynamicRequire("electron");+ electron.ipcRenderer.on("globalShortcut", async (event, actionName) => appContext.triggerCommand(actionName));const electronRemote = utils.dynamicRequire("@electron/remote");const currentWindow = electronRemote.getCurrentWindow();@@ -72,8 +71,7 @@ function initTitleBarButtons(style, currentWindow) {applyWindowsOverlay();// Register for changes to the native title bar colors.- window.matchMedia("(prefers-color-scheme: dark)")- .addEventListener("change", applyWindowsOverlay);+ window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", applyWindowsOverlay);}if (window.glob.platform === "darwin") {diff --git a/src/public/app/entities/fattachment.ts b/src/public/app/entities/fattachment.tsindex 20ba79c944..67215b33fc 100644--- a/src/public/app/entities/fattachment.ts+++ b/src/public/app/entities/fattachment.ts@@ -23,12 +23,12 @@ class FAttachment {role!: string;mime!: string;title!: string;- isProtected!: boolean; // TODO: Is this used?+ isProtected!: boolean; // TODO: Is this used?private dateModified!: string;utcDateModified!: string;private utcDateScheduledForErasureSince!: string;/**- * optionally added to the entity+ * optionally added to the entity*/private contentLength!: number;@@ -58,7 +58,7 @@ class FAttachment {}async getBlob() {- return await this.froca.getBlob('attachments', this.attachmentId);+ return await this.froca.getBlob("attachments", this.attachmentId);}}diff --git a/src/public/app/entities/fattribute.ts b/src/public/app/entities/fattribute.tsindex 379f0588ab..5ad29db6b1 100644--- a/src/public/app/entities/fattribute.ts+++ b/src/public/app/entities/fattribute.ts@@ -1,5 +1,5 @@-import { Froca } from '../services/froca-interface.js';-import promotedAttributeDefinitionParser from '../services/promoted_attribute_definition_parser.js';+import { Froca } from "../services/froca-interface.js";+import promotedAttributeDefinitionParser from "../services/promoted_attribute_definition_parser.js";/*** There are currently only two types of attributes, labels or relations.@@ -16,7 +16,6 @@ export interface FAttributeRow {isInheritable: boolean;}-/*** Attribute is an abstract concept which has two real uses - label (key - value pair)* and relation (representing named relationship between source and target note)@@ -57,8 +56,9 @@ class FAttribute {return await this.froca.getNote(targetNoteId, true);}- get targetNoteId() { // alias- if (this.type !== 'relation') {+ get targetNoteId() {+ // alias+ if (this.type !== "relation") {throw new Error(`Attribute ${this.attributeId} is not a relation`);}@@ -66,7 +66,7 @@ class FAttribute {}get isAutoLink() {- return this.type === 'relation' && ['internalLink', 'imageLink', 'relationMapLink', 'includeNoteLink'].includes(this.name);+ return this.type === "relation" && ["internalLink", "imageLink", "relationMapLink", "includeNoteLink"].includes(this.name);}get toString() {@@ -74,7 +74,7 @@ class FAttribute {}isDefinition() {- return this.type === 'label' && (this.name.startsWith('label:') || this.name.startsWith('relation:'));+ return this.type === "label" && (this.name.startsWith("label:") || this.name.startsWith("relation:"));}getDefinition() {@@ -82,7 +82,7 @@ class FAttribute {}isDefinitionFor(attr: FAttribute) {- return this.type === 'label' && this.name === `${attr.type}:${attr.name}`;+ return this.type === "label" && this.name === `${attr.type}:${attr.name}`;}get dto(): Omit<FAttribute, "froca"> {diff --git a/src/public/app/entities/fblob.ts b/src/public/app/entities/fblob.tsindex d260f7da64..fc00e1d1f1 100644--- a/src/public/app/entities/fblob.ts+++ b/src/public/app/entities/fblob.ts@@ -1,4 +1,3 @@-export interface FBlobRow {blobId: string;content: string;@@ -8,7 +7,6 @@ export interface FBlobRow {}export default class FBlob {-blobId: string;/*** can either contain the whole content (in e.g. string notes), only part (large text notes) or nothing at all (binary notes, images)@@ -40,8 +38,7 @@ export default class FBlob {getJsonContentSafely(): unknown | null {try {return this.getJsonContent();- }- catch (e) {+ } catch (e) {return null;}}diff --git a/src/public/app/entities/fbranch.ts b/src/public/app/entities/fbranch.tsindex d497c70af9..fb1879b382 100644--- a/src/public/app/entities/fbranch.ts+++ b/src/public/app/entities/fbranch.ts@@ -61,7 +61,7 @@ class FBranch {/** @returns true if it's top level, meaning its parent is the root note */isTopLevel() {- return this.parentNoteId === 'root';+ return this.parentNoteId === "root";}get toString() {@@ -69,7 +69,7 @@ class FBranch {}get pojo(): Omit<FBranch, "froca"> {- const pojo = {...this} as any;+ const pojo = { ...this } as any;delete pojo.froca;return pojo;}diff --git a/src/public/app/entities/fnote.ts b/src/public/app/entities/fnote.tsindex 0fd19fff5b..27ede68ce4 100644--- a/src/public/app/entities/fnote.ts+++ b/src/public/app/entities/fnote.ts@@ -1,33 +1,33 @@-import server from '../services/server.js';+import server from "../services/server.js";import noteAttributeCache from "../services/note_attribute_cache.js";import ws from "../services/ws.js";import froca from "../services/froca.js";import protectedSessionHolder from "../services/protected_session_holder.js";import cssClassManager from "../services/css_class_manager.js";-import { Froca } from '../services/froca-interface.js';-import FAttachment from './fattachment.js';-import FAttribute, { AttributeType } from './fattribute.js';-import utils from '../services/utils.js';+import { Froca } from "../services/froca-interface.js";+import FAttachment from "./fattachment.js";+import FAttribute, { AttributeType } from "./fattribute.js";+import utils from "../services/utils.js";-const LABEL = 'label';-const RELATION = 'relation';+const LABEL = "label";+const RELATION = "relation";const NOTE_TYPE_ICONS = {- "file": "bx bx-file",- "image": "bx bx-image",- "code": "bx bx-code",- "render": "bx bx-extension",- "search": "bx bx-file-find",- "relationMap": "bx bxs-network-chart",- "book": "bx bx-book",- "noteMap": "bx bxs-network-chart",- "mermaid": "bx bx-selection",- "canvas": "bx bx-pen",- "webView": "bx bx-globe-alt",- "launcher": "bx bx-link",- "doc": "bx bxs-file-doc",- "contentWidget": "bx bxs-widget",- "mindMap": "bx bx-sitemap"+ file: "bx bx-file",+ image: "bx bx-image",+ code: "bx bx-code",+ render: "bx bx-extension",+ search: "bx bx-file-find",+ relationMap: "bx bxs-network-chart",+ book: "bx bx-book",+ noteMap: "bx bxs-network-chart",+ mermaid: "bx bx-selection",+ canvas: "bx bx-pen",+ webView: "bx bx-globe-alt",+ launcher: "bx bx-link",+ doc: "bx bxs-file-doc",+ contentWidget: "bx bxs-widget",+ mindMap: "bx bx-sitemap"};/**@@ -65,7 +65,6 @@ export interface NoteMetaData {* Note is the main node and concept in Trilium.*/class FNote {-private froca: Froca;noteId!: string;@@ -119,7 +118,7 @@ class FNote {}addParent(parentNoteId: string, branchId: string, sort = true) {- if (parentNoteId === 'none') {+ if (parentNoteId === "none") {return;}@@ -179,8 +178,7 @@ class FNote {try {return JSON.parse(content);- }- catch (e: any) {+ } catch (e: any) {console.log(`Cannot parse content of note '${this.noteId}': `, e.message);return null;@@ -217,7 +215,7 @@ class FNote {getChildBranches() {// don't use Object.values() to guarantee order- const branchIds = this.children.map(childNoteId => this.childToBranch[childNoteId]);+ const branchIds = this.children.map((childNoteId) => this.childToBranch[childNoteId]);return this.froca.getBranches(branchIds);}@@ -236,7 +234,7 @@ class FNote {this.parents.sort((aNoteId, bNoteId) => {const aBranchId = this.parentToBranch[aNoteId];- if (aBranchId && aBranchId.startsWith('virt-')) {+ if (aBranchId && aBranchId.startsWith("virt-")) {return 1;}@@ -251,7 +249,7 @@ class FNote {}get isArchived() {- return this.hasAttribute('label', 'archived');+ return this.hasAttribute("label", "archived");}getChildNoteIds() {@@ -271,22 +269,21 @@ class FNote {}async getAttachmentsByRole(role: string) {- return (await this.getAttachments())- .filter(attachment => attachment.role === role);+ return (await this.getAttachments()).filter((attachment) => attachment.role === role);}async getAttachmentById(attachmentId: string) {const attachments = await this.getAttachments();- return attachments.find(att => att.attachmentId === attachmentId);+ return attachments.find((att) => att.attachmentId === attachmentId);}isEligibleForConversionToAttachment() {- if (this.type !== 'image' || !this.isContentAvailable() || this.hasChildren() || this.getParentBranches().length !== 1) {+ if (this.type !== "image" || !this.isContentAvailable() || this.hasChildren() || this.getParentBranches().length !== 1) {return false;}- const targetRelations = this.getTargetRelations().filter(relation => relation.name === 'imageLink');+ const targetRelations = this.getTargetRelations().filter((relation) => relation.name === "imageLink");if (targetRelations.length > 1) {return false;@@ -297,7 +294,7 @@ class FNote {if (referencingNote && referencingNote !== parentNote) {return false;- } else if (parentNote.type !== 'text' || !parentNote.isContentAvailable()) {+ } else if (parentNote.type !== "text" || !parentNote.isContentAvailable()) {return false;}@@ -310,9 +307,7 @@ class FNote {* @returns all note's attributes, including inherited ones*/getOwnedAttributes(type?: AttributeType, name?: string) {- const attrs = this.attributes- .map(attributeId => this.froca.attributes[attributeId])- .filter(Boolean); // filter out nulls;+ const attrs = this.attributes.map((attributeId) => this.froca.attributes[attributeId]).filter(Boolean); // filter out nulls;return this.__filterAttrs(attrs, type, name);}@@ -338,26 +333,27 @@ class FNote {if (!(this.noteId in noteAttributeCache.attributes)) {const newPath = [...path, this.noteId];- const attrArrs = [ this.getOwnedAttributes() ];+ const attrArrs = [this.getOwnedAttributes()];// inheritable attrs on root are typically not intended to be applied to hidden subtree #3537- if (this.noteId !== 'root' && this.noteId !== '_hidden') {+ if (this.noteId !== "root" && this.noteId !== "_hidden") {for (const parentNote of this.getParentNotes()) {// these virtual parent-child relationships are also loaded into froca- if (parentNote.type !== 'search') {+ if (parentNote.type !== "search") {attrArrs.push(parentNote.__getInheritableAttributes(newPath));}}}- for (const templateAttr of attrArrs.flat().filter(attr => attr.type === 'relation' && ['template', 'inherit'].includes(attr.name))) {+ for (const templateAttr of attrArrs.flat().filter((attr) => attr.type === "relation" && ["template", "inherit"].includes(attr.name))) {const templateNote = this.froca.notes[templateAttr.value];if (templateNote && templateNote.noteId !== this.noteId) {attrArrs.push(- templateNote.__getCachedAttributes(newPath)+ templateNote+ .__getCachedAttributes(newPath)// template attr is used as a marker for templates, but it's not meant to be inherited- .filter(attr => !(attr.type === 'label' && (attr.name === 'template' || attr.name === 'workspacetemplate')))+ .filter((attr) => !(attr.type === "label" && (attr.name === "template" || attr.name === "workspacetemplate"))));}}@@ -378,7 +374,7 @@ class FNote {}isRoot() {- return this.noteId === 'root';+ return this.noteId === "root";}/**@@ -387,15 +383,16 @@ class FNote {* @returns array of notePaths (each represented by array of noteIds constituting the particular note path)*/getAllNotePaths(): string[][] {- if (this.noteId === 'root') {- return [['root']];+ if (this.noteId === "root") {+ return [["root"]];}- const parentNotes = this.getParentNotes().filter(note => note.type !== 'search');+ const parentNotes = this.getParentNotes().filter((note) => note.type !== "search");- const notePaths = parentNotes.length === 1- ? parentNotes[0].getAllNotePaths() // optimization for the most common case- : parentNotes.flatMap(parentNote => parentNote.getAllNotePaths());+ const notePaths =+ parentNotes.length === 1+ ? parentNotes[0].getAllNotePaths() // optimization for the most common case+ : parentNotes.flatMap((parentNote) => parentNote.getAllNotePaths());for (const notePath of notePaths) {notePath.push(this.noteId);@@ -404,15 +401,15 @@ class FNote {return notePaths;}- getSortedNotePathRecords(hoistedNoteId = 'root') {- const isHoistedRoot = hoistedNoteId === 'root';+ getSortedNotePathRecords(hoistedNoteId = "root") {+ const isHoistedRoot = hoistedNoteId === "root";- const notePaths = this.getAllNotePaths().map(path => ({+ const notePaths = this.getAllNotePaths().map((path) => ({notePath: path,isInHoistedSubTree: isHoistedRoot || path.includes(hoistedNoteId),- isArchived: path.some(noteId => froca.notes[noteId].isArchived),- isSearch: path.find(noteId => froca.notes[noteId].type === 'search'),- isHidden: path.includes('_hidden')+ isArchived: path.some((noteId) => froca.notes[noteId].isArchived),+ isSearch: path.find((noteId) => froca.notes[noteId].type === "search"),+ isHidden: path.includes("_hidden")}));notePaths.sort((a, b) => {@@ -438,7 +435,7 @@ class FNote {* @param {string} [hoistedNoteId='root']* @return {string[]} array of noteIds constituting the particular note path*/- getBestNotePath(hoistedNoteId = 'root') {+ getBestNotePath(hoistedNoteId = "root") {return this.getSortedNotePathRecords(hoistedNoteId)[0]?.notePath;}@@ -448,7 +445,7 @@ class FNote {* @param {string} [hoistedNoteId='root']* @return {string} serialized note path (e.g. 'root/a1h315/js725h')*/- getBestNotePathString(hoistedNoteId = 'root') {+ getBestNotePathString(hoistedNoteId = "root") {const notePath = this.getBestNotePath(hoistedNoteId);return notePath?.join("/");@@ -458,16 +455,16 @@ class FNote {* @return boolean - true if there's no non-hidden path, note is not cloned to the visible tree*/isHiddenCompletely() {- if (this.noteId === '_hidden') {+ if (this.noteId === "_hidden") {return true;- } else if (this.noteId === 'root') {+ } else if (this.noteId === "root") {return false;}for (const parentNote of this.getParentNotes()) {- if (parentNote.noteId === 'root') {+ if (parentNote.noteId === "root") {return false;- } else if (parentNote.noteId === '_hidden' || parentNote.type === 'search') {+ } else if (parentNote.noteId === "_hidden" || parentNote.type === "search") {continue;}@@ -488,11 +485,11 @@ class FNote {if (!type && !name) {return attributes;} else if (type && name) {- return attributes.filter(attr => attr.name === name && attr.type === type);+ return attributes.filter((attr) => attr.name === name && attr.type === type);} else if (type) {- return attributes.filter(attr => attr.type === type);+ return attributes.filter((attr) => attr.type === type);} else if (name) {- return attributes.filter(attr => attr.name === name);+ return attributes.filter((attr) => attr.name === name);}return [];@@ -501,17 +498,17 @@ class FNote {__getInheritableAttributes(path: string[]) {const attrs = this.__getCachedAttributes(path);- return attrs.filter(attr => attr.isInheritable);+ return attrs.filter((attr) => attr.isInheritable);}__validateTypeName(type?: string, name?: string) {- if (type && type !== 'label' && type !== 'relation') {+ if (type && type !== "label" && type !== "relation") {throw new Error(`Unrecognized attribute type '${type}'. Only 'label' and 'relation' are possible values.`);}if (name) {const firstLetter = name.charAt(0);- if (firstLetter === '#' || firstLetter === '~') {+ if (firstLetter === "#" || firstLetter === "~") {throw new Error(`Detect '#' or '~' in the attribute's name. In the API, attribute names should be set without these characters.`);}}@@ -534,33 +531,27 @@ class FNote {}getIcon() {- const iconClassLabels = this.getLabels('iconClass');+ const iconClassLabels = this.getLabels("iconClass");const workspaceIconClass = this.getWorkspaceIconClass();if (iconClassLabels && iconClassLabels.length > 0) {return iconClassLabels[0].value;- }- else if (workspaceIconClass) {+ } else if (workspaceIconClass) {return workspaceIconClass;- }- else if (this.noteId === 'root') {+ } else if (this.noteId === "root") {return "bx bx-home-alt-2";}- if (this.noteId === '_share') {+ if (this.noteId === "_share") {return "bx bx-share-alt";- }- else if (this.type === 'text') {+ } else if (this.type === "text") {if (this.isFolder()) {return "bx bx-folder";- }- else {+ } else {return "bx bx-note";}- }- else if (this.type === 'code' && this.mime.startsWith('text/x-sql')) {+ } else if (this.type === "code" && this.mime.startsWith("text/x-sql")) {return "bx bx-data";- }- else {+ } else {return NOTE_TYPE_ICONS[this.type];}}@@ -571,8 +562,7 @@ class FNote {}isFolder() {- return this.type === 'search'- || this.getFilteredChildBranches().length > 0;+ return this.type === "search" || this.getFilteredChildBranches().length > 0;}getFilteredChildBranches() {@@ -615,7 +605,7 @@ class FNote {hasAttribute(type: AttributeType, name: string) {const attributes = this.getAttributes();- return attributes.some(attr => attr.name === name && attr.type === type);+ return attributes.some((attr) => attr.name === name && attr.type === type);}/**@@ -635,7 +625,7 @@ class FNote {getOwnedAttribute(type: AttributeType, name: string) {const attributes = this.getOwnedAttributes();- return attributes.find(attr => attr.name === name && attr.type === type);+ return attributes.find((attr) => attr.name === name && attr.type === type);}/**@@ -646,7 +636,7 @@ class FNote {getAttribute(type: AttributeType, name: string) {const attributes = this.getAttributes();- return attributes.find(attr => attr.name === name && attr.type === type);+ return attributes.find((attr) => attr.name === name && attr.type === type);}/**@@ -683,7 +673,9 @@ class FNote {* @param name - label name* @returns true if label exists (including inherited)*/- hasLabel(name: string) { return this.hasAttribute(LABEL, name); }+ hasLabel(name: string) {+ return this.hasAttribute(LABEL, name);+ }/*** @param name - label name@@ -696,68 +688,88 @@ class FNote {return false;}- return label && label.value !== 'false';+ return label && label.value !== "false";}/*** @param name - relation name* @returns true if relation exists (excluding inherited)*/- hasOwnedRelation(name: string) { return this.hasOwnedAttribute(RELATION, name); }+ hasOwnedRelation(name: string) {+ return this.hasOwnedAttribute(RELATION, name);+ }/*** @param name - relation name* @returns true if relation exists (including inherited)*/- hasRelation(name: string) { return this.hasAttribute(RELATION, name); }+ hasRelation(name: string) {+ return this.hasAttribute(RELATION, name);+ }/*** @param name - label name* @returns label if it exists, null otherwise*/- getOwnedLabel(name: string) { return this.getOwnedAttribute(LABEL, name); }+ getOwnedLabel(name: string) {+ return this.getOwnedAttribute(LABEL, name);+ }/*** @param name - label name* @returns label if it exists, null otherwise*/- getLabel(name: string) { return this.getAttribute(LABEL, name); }+ getLabel(name: string) {+ return this.getAttribute(LABEL, name);+ }/*** @param name - relation name* @returns relation if it exists, null otherwise*/- getOwnedRelation(name: string) { return this.getOwnedAttribute(RELATION, name); }+ getOwnedRelation(name: string) {+ return this.getOwnedAttribute(RELATION, name);+ }/*** @param name - relation name* @returns relation if it exists, null otherwise*/- getRelation(name: string) { return this.getAttribute(RELATION, name); }+ getRelation(name: string) {+ return this.getAttribute(RELATION, name);+ }/*** @param name - label name* @returns label value if label exists, null otherwise*/- getOwnedLabelValue(name: string) { return this.getOwnedAttributeValue(LABEL, name); }+ getOwnedLabelValue(name: string) {+ return this.getOwnedAttributeValue(LABEL, name);+ }/*** @param name - label name* @returns label value if label exists, null otherwise*/- getLabelValue(name: string) { return this.getAttributeValue(LABEL, name); }+ getLabelValue(name: string) {+ return this.getAttributeValue(LABEL, name);+ }/*** @param name - relation name* @returns relation value if relation exists, null otherwise*/- getOwnedRelationValue(name: string) { return this.getOwnedAttributeValue(RELATION, name); }+ getOwnedRelationValue(name: string) {+ return this.getOwnedAttributeValue(RELATION, name);+ }/*** @param name - relation name* @returns relation value if relation exists, null otherwise*/- getRelationValue(name: string) { return this.getAttributeValue(RELATION, name); }+ getRelationValue(name: string) {+ return this.getAttributeValue(RELATION, name);+ }/*** @param name@@ -784,22 +796,19 @@ class FNote {}getNotesToInheritAttributesFrom() {- const relations = [- ...this.getRelations('template'),- ...this.getRelations('inherit')- ];+ const relations = [...this.getRelations("template"), ...this.getRelations("inherit")];- return relations.map(rel => this.froca.notes[rel.value]);+ return relations.map((rel) => this.froca.notes[rel.value]);}getPromotedDefinitionAttributes() {- if (this.isLabelTruthy('hidePromotedAttributes')) {+ if (this.isLabelTruthy("hidePromotedAttributes")) {return [];}const promotedAttrs = this.getAttributes()- .filter(attr => attr.isDefinition())- .filter(attr => {+ .filter((attr) => attr.isDefinition())+ .filter((attr) => {const def = attr.getDefinition();return def && def.isPromoted;@@ -850,7 +859,7 @@ class FNote {}isInHiddenSubtree() {- return this.noteId === '_hidden' || this.hasAncestor('_hidden');+ return this.noteId === "_hidden" || this.hasAncestor("_hidden");}/**@@ -862,8 +871,7 @@ class FNote {* Get relations which target this note*/getTargetRelations() {- return this.targetRelations- .map(attributeId => this.froca.attributes[attributeId]);+ return this.targetRelations.map((attributeId) => this.froca.attributes[attributeId]);}/**@@ -872,7 +880,7 @@ class FNote {async getTargetRelationSourceNotes() {const targetRelations = this.getTargetRelations();- return await this.froca.getNotes(targetRelations.map(tr => tr.noteId));+ return await this.froca.getNotes(targetRelations.map((tr) => tr.noteId));}/**@@ -883,7 +891,7 @@ class FNote {}async getBlob() {- return await this.froca.getBlob('notes', this.noteId);+ return await this.froca.getBlob("notes", this.noteId);}toString() {@@ -898,26 +906,26 @@ class FNote {}getCssClass() {- const labels = this.getLabels('cssClass');- return labels.map(l => l.value).join(' ');+ const labels = this.getLabels("cssClass");+ return labels.map((l) => l.value).join(" ");}getWorkspaceIconClass() {- const labels = this.getLabels('workspaceIconClass');+ const labels = this.getLabels("workspaceIconClass");return labels.length > 0 ? labels[0].value : "";}getWorkspaceTabBackgroundColor() {- const labels = this.getLabels('workspaceTabBackgroundColor');+ const labels = this.getLabels("workspaceTabBackgroundColor");return labels.length > 0 ? labels[0].value : "";}/** @returns true if this note is JavaScript (code or file) */isJavaScript() {- return (this.type === "code" || this.type === "file" || this.type === 'launcher')- && (this.mime.startsWith("application/javascript")- || this.mime === "application/x-javascript"- || this.mime === "text/javascript");+ return (+ (this.type === "code" || this.type === "file" || this.type === "launcher") &&+ (this.mime.startsWith("application/javascript") || this.mime === "application/x-javascript" || this.mime === "text/javascript")+ );}/** @returns true if this note is HTML */@@ -927,15 +935,15 @@ class FNote {/** @returns JS script environment - either "frontend" or "backend" */getScriptEnv() {- if (this.isHtml() || (this.isJavaScript() && this.mime.endsWith('env=frontend'))) {+ if (this.isHtml() || (this.isJavaScript() && this.mime.endsWith("env=frontend"))) {return "frontend";}- if (this.type === 'render') {+ if (this.type === "render") {return "frontend";}- if (this.isJavaScript() && this.mime.endsWith('env=backend')) {+ if (this.isJavaScript() && this.mime.endsWith("env=backend")) {return "backend";}@@ -961,17 +969,17 @@ class FNote {isShared() {for (const parentNoteId of this.parents) {- if (parentNoteId === 'root' || parentNoteId === 'none') {+ if (parentNoteId === "root" || parentNoteId === "none") {continue;}const parentNote = froca.notes[parentNoteId];- if (!parentNote || parentNote.type === 'search') {+ if (!parentNote || parentNote.type === "search") {continue;}- if (parentNote.noteId === '_share' || parentNote.isShared()) {+ if (parentNote.noteId === "_share" || parentNote.isShared()) {return true;}}@@ -980,11 +988,11 @@ class FNote {}isContentAvailable() {- return !this.isProtected || protectedSessionHolder.isProtectedSessionAvailable()+ return !this.isProtected || protectedSessionHolder.isProtectedSessionAvailable();}isLaunchBarConfig() {- return this.type === 'launcher' || utils.isLaunchBarConfig(this.noteId);+ return this.type === "launcher" || utils.isLaunchBarConfig(this.noteId);}isOptions() {diff --git a/src/public/app/layouts/desktop_layout.js b/src/public/app/layouts/desktop_layout.jsindex 1a0dbdc843..a50dace76d 100644--- a/src/public/app/layouts/desktop_layout.js+++ b/src/public/app/layouts/desktop_layout.js@@ -94,139 +94,147 @@ export default class DesktopLayout {getRootWidget(appContext) {appContext.noteTreeWidget = new NoteTreeWidget();- const launcherPaneIsHorizontal = (options.get("layoutOrientation") === "horizontal");+ const launcherPaneIsHorizontal = options.get("layoutOrientation") === "horizontal";const launcherPane = this.#buildLauncherPane(launcherPaneIsHorizontal);- const isElectron = (utils.isElectron());- const isMac = (window.glob.platform === "darwin");- const isWindows = (window.glob.platform === "win32");- const hasNativeTitleBar = (window.glob.hasNativeTitleBar);+ const isElectron = utils.isElectron();+ const isMac = window.glob.platform === "darwin";+ const isWindows = window.glob.platform === "win32";+ const hasNativeTitleBar = window.glob.hasNativeTitleBar;/*** If true, the tab bar is displayed above the launcher pane with full width; if false (default), the tab bar is displayed in the rest pane.* On macOS we need to force the full-width tab bar on Electron in order to allow the semaphore (window controls) enough space.*/- const fullWidthTabBar = (launcherPaneIsHorizontal || (isElectron && !hasNativeTitleBar && isMac));- const customTitleBarButtons = (!hasNativeTitleBar && !isMac && !isWindows);+ const fullWidthTabBar = launcherPaneIsHorizontal || (isElectron && !hasNativeTitleBar && isMac);+ const customTitleBarButtons = !hasNativeTitleBar && !isMac && !isWindows;return new RootContainer(true).setParent(appContext).class((launcherPaneIsHorizontal ? "horizontal" : "vertical") + "-layout")- .optChild(fullWidthTabBar, new FlexContainer('row')- .class("tab-row-container")- .child(new FlexContainer( "row").id("tab-row-left-spacer"))- .optChild(launcherPaneIsHorizontal, new LeftPaneToggleWidget(true))- .child(new TabRowWidget().class("full-width"))- .optChild(customTitleBarButtons, new TitleBarButtonsWidget())- .css('height', '40px')- .css('background-color', 'var(--launcher-pane-background-color)')- .setParent(appContext)+ .optChild(+ fullWidthTabBar,+ new FlexContainer("row")+ .class("tab-row-container")+ .child(new FlexContainer("row").id("tab-row-left-spacer"))+ .optChild(launcherPaneIsHorizontal, new LeftPaneToggleWidget(true))+ .child(new TabRowWidget().class("full-width"))+ .optChild(customTitleBarButtons, new TitleBarButtonsWidget())+ .css("height", "40px")+ .css("background-color", "var(--launcher-pane-background-color)")+ .setParent(appContext)).optChild(launcherPaneIsHorizontal, launcherPane)- .child(new FlexContainer('row')- .css("flex-grow", "1")- .id("horizontal-main-container")- .optChild(!launcherPaneIsHorizontal, launcherPane)- .child(new LeftPaneContainer()- .optChild(!launcherPaneIsHorizontal, new QuickSearchWidget())- .child(appContext.noteTreeWidget)- .child(...this.customWidgets.get('left-pane'))- )- .child(new FlexContainer('column')- .id('rest-pane')+ .child(+ new FlexContainer("row").css("flex-grow", "1")- .optChild(!fullWidthTabBar, new FlexContainer('row')- .child(new TabRowWidget())- .optChild(customTitleBarButtons, new TitleBarButtonsWidget())- .css('height', '40px')+ .id("horizontal-main-container")+ .optChild(!launcherPaneIsHorizontal, launcherPane)+ .child(+ new LeftPaneContainer()+ .optChild(!launcherPaneIsHorizontal, new QuickSearchWidget())+ .child(appContext.noteTreeWidget)+ .child(...this.customWidgets.get("left-pane")))- .child(new FlexContainer('row')- .filling()- .collapsible()- .id("vertical-main-container")- .child(new FlexContainer('column')- .filling()- .collapsible()- .id('center-pane')- .child(new SplitNoteContainer(() =>- new NoteWrapperWidget()- .child(new FlexContainer('row').class('title-row')- .css("height", "50px")- .css("min-height", "50px")- .css('align-items', "center")- .cssBlock('.title-row > * { margin: 5px; }')- .child(new NoteIconWidget())- .child(new NoteTitleWidget())- .child(new SpacerWidget(0, 1))- .child(new MovePaneButton(true))- .child(new MovePaneButton(false))- .child(new ClosePaneButton())- .child(new CreatePaneButton())- )- .child(- new RibbonContainer()- // the order of the widgets matter. Some of these want to "activate" themselves- // when visible. When this happens to multiple of them, the first one "wins".- // promoted attributes should always win.- .ribbon(new ClassicEditorToolbar())- .ribbon(new ScriptExecutorWidget())- .ribbon(new SearchDefinitionWidget())- .ribbon(new EditedNotesWidget())- .ribbon(new BookPropertiesWidget())- .ribbon(new NotePropertiesWidget())- .ribbon(new FilePropertiesWidget())- .ribbon(new ImagePropertiesWidget())- .ribbon(new BasicPropertiesWidget())- .ribbon(new OwnedAttributeListWidget())- .ribbon(new InheritedAttributesWidget())- .ribbon(new NotePathsWidget())- .ribbon(new NoteMapRibbonWidget())- .ribbon(new SimilarNotesWidget())- .ribbon(new NoteInfoWidget())- .button(new RevisionsButton())- .button(new NoteActionsWidget())- )- .child(new SharedInfoWidget())- .child(new WatchedFileUpdateStatusWidget())- .child(new FloatingButtons()- .child(new EditButton())- .child(new ShowTocWidgetButton())- .child(new ShowHighlightsListWidgetButton())- .child(new CodeButtonsWidget())- .child(new RelationMapButtons())- .child(new CopyImageReferenceButton())- .child(new SvgExportButton())- .child(new BacklinksWidget())- .child(new HideFloatingButtonsButton())- )- .child(new MermaidWidget())- .child(- new ScrollingContainer()- .filling()- .child(new PromotedAttributesWidget())- .child(new SqlTableSchemasWidget())- .child(new NoteDetailWidget())- .child(new NoteListWidget())- .child(new SearchResultWidget())- .child(new SqlResultWidget())- .child(new ScrollPaddingWidget())- )- .child(new ApiLogWidget())- .child(new FindWidget())- .child(- ...this.customWidgets.get('node-detail-pane'), // typo, let's keep it for a while as BC- ...this.customWidgets.get('note-detail-pane')- )- )+ .child(+ new FlexContainer("column")+ .id("rest-pane")+ .css("flex-grow", "1")+ .optChild(!fullWidthTabBar, new FlexContainer("row").child(new TabRowWidget()).optChild(customTitleBarButtons, new TitleBarButtonsWidget()).css("height", "40px"))+ .child(+ new FlexContainer("row")+ .filling()+ .collapsible()+ .id("vertical-main-container")+ .child(+ new FlexContainer("column")+ .filling()+ .collapsible()+ .id("center-pane")+ .child(+ new SplitNoteContainer(() =>+ new NoteWrapperWidget()+ .child(+ new FlexContainer("row")+ .class("title-row")+ .css("height", "50px")+ .css("min-height", "50px")+ .css("align-items", "center")+ .cssBlock(".title-row > * { margin: 5px; }")+ .child(new NoteIconWidget())+ .child(new NoteTitleWidget())+ .child(new SpacerWidget(0, 1))+ .child(new MovePaneButton(true))+ .child(new MovePaneButton(false))+ .child(new ClosePaneButton())+ .child(new CreatePaneButton())+ )+ .child(+ new RibbonContainer()+ // the order of the widgets matter. Some of these want to "activate" themselves+ // when visible. When this happens to multiple of them, the first one "wins".+ // promoted attributes should always win.+ .ribbon(new ClassicEditorToolbar())+ .ribbon(new ScriptExecutorWidget())+ .ribbon(new SearchDefinitionWidget())+ .ribbon(new EditedNotesWidget())+ .ribbon(new BookPropertiesWidget())+ .ribbon(new NotePropertiesWidget())+ .ribbon(new FilePropertiesWidget())+ .ribbon(new ImagePropertiesWidget())+ .ribbon(new BasicPropertiesWidget())+ .ribbon(new OwnedAttributeListWidget())+ .ribbon(new InheritedAttributesWidget())+ .ribbon(new NotePathsWidget())+ .ribbon(new NoteMapRibbonWidget())+ .ribbon(new SimilarNotesWidget())+ .ribbon(new NoteInfoWidget())+ .button(new RevisionsButton())+ .button(new NoteActionsWidget())+ )+ .child(new SharedInfoWidget())+ .child(new WatchedFileUpdateStatusWidget())+ .child(+ new FloatingButtons()+ .child(new EditButton())+ .child(new ShowTocWidgetButton())+ .child(new ShowHighlightsListWidgetButton())+ .child(new CodeButtonsWidget())+ .child(new RelationMapButtons())+ .child(new CopyImageReferenceButton())+ .child(new SvgExportButton())+ .child(new BacklinksWidget())+ .child(new HideFloatingButtonsButton())+ )+ .child(new MermaidWidget())+ .child(+ new ScrollingContainer()+ .filling()+ .child(new PromotedAttributesWidget())+ .child(new SqlTableSchemasWidget())+ .child(new NoteDetailWidget())+ .child(new NoteListWidget())+ .child(new SearchResultWidget())+ .child(new SqlResultWidget())+ .child(new ScrollPaddingWidget())+ )+ .child(new ApiLogWidget())+ .child(new FindWidget())+ .child(+ ...this.customWidgets.get("node-detail-pane"), // typo, let's keep it for a while as BC+ ...this.customWidgets.get("note-detail-pane")+ )+ )+ )+ .child(...this.customWidgets.get("center-pane"))+ )+ .child(+ new RightPaneContainer()+ .child(new TocWidget())+ .child(new HighlightsListWidget())+ .child(...this.customWidgets.get("right-pane"))+ ))- .child(...this.customWidgets.get('center-pane'))- )- .child(new RightPaneContainer()- .child(new TocWidget())- .child(new HighlightsListWidget())- .child(...this.customWidgets.get('right-pane'))- ))- )).child(new BulkActionsDialog()).child(new AboutDialog())@@ -254,14 +262,10 @@ export default class DesktopLayout {}#buildLauncherPane(isHorizontal) {- let launcherPane;+ let launcherPane;if (isHorizontal) {- launcherPane = new FlexContainer("row")- .css("height", "53px")- .class("horizontal")- .child(new LauncherContainer(true))- .child(new GlobalMenuWidget(true))+ launcherPane = new FlexContainer("row").css("height", "53px").class("horizontal").child(new LauncherContainer(true)).child(new GlobalMenuWidget(true));} else {launcherPane = new FlexContainer("column").css("width", "53px")diff --git a/src/public/app/layouts/mobile_layout.ts b/src/public/app/layouts/mobile_layout.tsindex af1e8120ba..0f31199fd5 100644--- a/src/public/app/layouts/mobile_layout.ts+++ b/src/public/app/layouts/mobile_layout.ts@@ -122,81 +122,71 @@ export default class MobileLayout {.setParent(appContext).class("horizontal-layout").cssBlock(MOBILE_CSS)- .child(new FlexContainer("column")- .id("mobile-sidebar-container")- )- .child(new FlexContainer("row")- .filling()- .id("mobile-rest-container")- .child(new SidebarContainer("tree", 'column')- .class("d-sm-flex d-md-flex d-lg-flex d-xl-flex col-12 col-sm-5 col-md-4 col-lg-3 col-xl-3")- .id("mobile-sidebar-wrapper")- .css("max-height", "100%")- .css('padding-left', "0")- .css('padding-right', "0")- .css('contain', 'content')- .child(new FlexContainer("column")- .filling()- .id("mobile-sidebar-wrapper")- .child(new QuickSearchWidget())- .child(new NoteTreeWidget()- .cssBlock(FANCYTREE_CSS))))- .child(new ScreenContainer("detail", "column")- .id("detail-container")- .class("d-sm-flex d-md-flex d-lg-flex d-xl-flex col-12 col-sm-7 col-md-8 col-lg-9")- .css("padding-left", "0")- .css("padding-right", "0")- .css('max-height', '100%')- .css("position", "relative")- .child(new FlexContainer('row').contentSized()- .css('font-size', 'larger')- .css('align-items', 'center')- .child(new ToggleSidebarButtonWidget().contentSized())- .child(new NoteTitleWidget()- .contentSized()- .css("position", "relative")- .css("top", "5px")- .css("padding-left", "0.5em"))- .child(new MobileDetailMenuWidget(true).contentSized())- )- .child(new SharedInfoWidget())- .child(new FloatingButtons()- .child(new EditButton())- .child(new RelationMapButtons())- .child(new SvgExportButton())- .child(new BacklinksWidget())- .child(new HideFloatingButtonsButton())+ .child(new FlexContainer("column").id("mobile-sidebar-container"))+ .child(+ new FlexContainer("row")+ .filling()+ .id("mobile-rest-container")+ .child(+ new SidebarContainer("tree", "column")+ .class("d-sm-flex d-md-flex d-lg-flex d-xl-flex col-12 col-sm-5 col-md-4 col-lg-3 col-xl-3")+ .id("mobile-sidebar-wrapper")+ .css("max-height", "100%")+ .css("padding-left", "0")+ .css("padding-right", "0")+ .css("contain", "content")+ .child(new FlexContainer("column").filling().id("mobile-sidebar-wrapper").child(new QuickSearchWidget()).child(new NoteTreeWidget().cssBlock(FANCYTREE_CSS))))- .child(new MermaidWidget())- .child(new PromotedAttributesWidget()).child(- new ScrollingContainer()- .filling()- .contentSized()+ new ScreenContainer("detail", "column")+ .id("detail-container")+ .class("d-sm-flex d-md-flex d-lg-flex d-xl-flex col-12 col-sm-7 col-md-8 col-lg-9")+ .css("padding-left", "0")+ .css("padding-right", "0")+ .css("max-height", "100%")+ .css("position", "relative").child(- new NoteDetailWidget()- .css('padding', '5px 0 10px 0')+ new FlexContainer("row")+ .contentSized()+ .css("font-size", "larger")+ .css("align-items", "center")+ .child(new ToggleSidebarButtonWidget().contentSized())+ .child(new NoteTitleWidget().contentSized().css("position", "relative").css("top", "5px").css("padding-left", "0.5em"))+ .child(new MobileDetailMenuWidget(true).contentSized())+ )+ .child(new SharedInfoWidget())+ .child(+ new FloatingButtons()+ .child(new EditButton())+ .child(new RelationMapButtons())+ .child(new SvgExportButton())+ .child(new BacklinksWidget())+ .child(new HideFloatingButtonsButton())+ )+ .child(new MermaidWidget())+ .child(new PromotedAttributesWidget())+ .child(+ new ScrollingContainer()+ .filling()+ .contentSized()+ .child(new NoteDetailWidget().css("padding", "5px 0 10px 0"))+ .child(new NoteListWidget())+ .child(new FilePropertiesWidget().css("font-size", "smaller")))- .child(new NoteListWidget())- .child(new FilePropertiesWidget().css('font-size','smaller')))- )- .child(new ProtectedSessionPasswordDialog())- .child(new ConfirmDialog())+ .child(new ProtectedSessionPasswordDialog())+ .child(new ConfirmDialog())+ )+ .child(+ new FlexContainer("column")+ .contentSized()+ .id("mobile-bottom-bar")+ .child(new TabRowWidget().css("height", "40px"))+ .child(new FlexContainer("row").class("horizontal").css("height", "53px").child(new LauncherContainer(true)).child(new GlobalMenuWidget(true)).id("launcher-pane")))- .child(new FlexContainer("column")- .contentSized()- .id("mobile-bottom-bar")- .child(new TabRowWidget().css('height', '40px'))- .child(new FlexContainer("row")- .class("horizontal")- .css("height", "53px")- .child(new LauncherContainer(true))- .child(new GlobalMenuWidget(true))- .id("launcher-pane"))).child(new ClassicEditorToolbar()).child(new AboutDialog()).child(new HelpDialog())- .child(new JumpToNoteDialog())+ .child(new JumpToNoteDialog());}}diff --git a/src/public/app/menus/context_menu.ts b/src/public/app/menus/context_menu.tsindex 3663c56486..25e45e38a6 100644--- a/src/public/app/menus/context_menu.ts+++ b/src/public/app/menus/context_menu.ts@@ -1,6 +1,6 @@-import { CommandNames } from '../components/app_context.js';-import keyboardActionService from '../services/keyboard_actions.js';-import utils from '../services/utils.js';+import { CommandNames } from "../components/app_context.js";+import keyboardActionService from "../services/keyboard_actions.js";+import utils from "../services/utils.js";interface ContextMenuOptions<T extends CommandNames> {x: number;@@ -11,7 +11,7 @@ interface ContextMenuOptions<T extends CommandNames> {}interface MenuSeparatorItem {- title: "----"+ title: "----";}export interface MenuCommandItem<T extends CommandNames> {@@ -31,7 +31,6 @@ export type MenuItem<T extends CommandNames> = MenuCommandItem<T> | MenuSeparatoexport type MenuHandler<T extends CommandNames> = (item: MenuCommandItem<T>, e: JQuery.MouseDownEvent<HTMLElement, undefined, HTMLElement, HTMLElement>) => void;class ContextMenu {-private $widget: JQuery<HTMLElement>;private $cover: JQuery<HTMLElement>;private dateContextMenuOpenedMs: number;@@ -48,7 +47,7 @@ class ContextMenu {if (this.isMobile) {this.$cover.on("click", () => this.hide());} else {- $(document).on('click', (e) => this.hide());+ $(document).on("click", (e) => this.hide());}}@@ -102,7 +101,7 @@ class ContextMenu {top = this.options.y - CONTEXT_MENU_OFFSET;}- if (this.options.orientation === 'left' && contextMenuWidth) {+ if (this.options.orientation === "left" && contextMenuWidth) {if (this.options.x + CONTEXT_MENU_OFFSET > clientWidth - CONTEXT_MENU_PADDING) {// Overflow: rightleft = clientWidth - contextMenuWidth - CONTEXT_MENU_OFFSET;@@ -124,11 +123,13 @@ class ContextMenu {}}- this.$widget.css({- display: "block",- top: top,- left: left- }).addClass("show");+ this.$widget+ .css({+ display: "block",+ top: top,+ left: left+ })+ .addClass("show");}addItems($parent: JQuery<HTMLElement>, items: MenuItem<any>[]) {@@ -137,7 +138,7 @@ class ContextMenu {continue;}- if (item.title === '----') {+ if (item.title === "----") {$parent.append($("<div>").addClass("dropdown-divider"));} else {const $icon = $("<span>");@@ -160,23 +161,22 @@ class ContextMenu {const $item = $("<li>").addClass("dropdown-item").append($link)- .on('contextmenu', e => false)+ .on("contextmenu", (e) => false)// important to use mousedown instead of click since the former does not change focus// (especially important for focused text for spell check)- .on('mousedown', e => {+ .on("mousedown", (e) => {e.stopPropagation();- if (e.which !== 1) { // only left click triggers menu items+ if (e.which !== 1) {+ // only left click triggers menu itemsreturn false;}if (this.isMobile && "items" in item && item.items) {- const $item = $(e.target)- .closest(".dropdown-item");+ const $item = $(e.target).closest(".dropdown-item");$item.toggleClass("submenu-open");- $item.find("ul.dropdown-menu")- .toggleClass("show");+ $item.find("ul.dropdown-menu").toggleClass("show");return false;}diff --git a/src/public/app/menus/electron_context_menu.ts b/src/public/app/menus/electron_context_menu.tsindex c8bbb0a413..43a504d6d2 100644--- a/src/public/app/menus/electron_context_menu.ts+++ b/src/public/app/menus/electron_context_menu.ts@@ -7,17 +7,17 @@ import type { BrowserWindow } from "electron";import { CommandNames } from "../components/app_context.js";function setupContextMenu() {- const electron = utils.dynamicRequire('electron');+ const electron = utils.dynamicRequire("electron");- const remote = utils.dynamicRequire('@electron/remote');+ const remote = utils.dynamicRequire("@electron/remote");// FIXME: Remove typecast once Electron is properly integrated.- const {webContents} = remote.getCurrentWindow() as BrowserWindow;+ const { webContents } = remote.getCurrentWindow() as BrowserWindow;- webContents.on('context-menu', (event, params) => {- const {editFlags} = params;+ webContents.on("context-menu", (event, params) => {+ const { editFlags } = params;const hasText = params.selectionText.trim().length > 0;const isMac = process.platform === "darwin";- const platformModifier = isMac ? 'Meta' : 'Ctrl';+ const platformModifier = isMac ? "Meta" : "Ctrl";const items: MenuItem<CommandNames>[] = [];@@ -60,7 +60,7 @@ function setupContextMenu() {});}- if (!["", "javascript:", "about:blank#blocked"].includes(params.linkURL) && params.mediaType === 'none') {+ if (!["", "javascript:", "about:blank#blocked"].includes(params.linkURL) && params.mediaType === "none") {items.push({title: t("electron_context_menu.copy-link"),uiIcon: "bx bx-copy",@@ -94,9 +94,7 @@ function setupContextMenu() {}if (hasText) {- const shortenedSelection = params.selectionText.length > 15- ? (`${params.selectionText.substr(0, 13)}…`)- : params.selectionText;+ const shortenedSelection = params.selectionText.length > 15 ? `${params.selectionText.substr(0, 13)}…` : params.selectionText;// Read the search engine from the options and fallback to DuckDuckGo if the option is not set.const customSearchEngineName = options.get("customSearchEngineName");@@ -114,7 +112,7 @@ function setupContextMenu() {// Replace the placeholder with the real search keyword.let searchUrl = searchEngineUrl.replace("{keyword}", encodeURIComponent(params.selectionText));- items.push({title: "----"});+ items.push({ title: "----" });items.push({enabled: editFlags.canPaste,@@ -134,8 +132,8 @@ function setupContextMenu() {x: params.x / zoomLevel,y: params.y / zoomLevel,items,- selectMenuItemHandler: ({command, spellingSuggestion}) => {- if (command === 'replaceMisspelling' && spellingSuggestion) {+ selectMenuItemHandler: ({ command, spellingSuggestion }) => {+ if (command === "replaceMisspelling" && spellingSuggestion) {webContents.insertText(spellingSuggestion);}}diff --git a/src/public/app/menus/image_context_menu.ts b/src/public/app/menus/image_context_menu.tsindex b0666ea84b..54d7abcf60 100644--- a/src/public/app/menus/image_context_menu.ts+++ b/src/public/app/menus/image_context_menu.ts@@ -1,4 +1,4 @@-import { t } from '../services/i18n.js';+import { t } from "../services/i18n.js";import utils from "../services/utils.js";import contextMenu from "./context_menu.js";import imageService from "../services/image.js";@@ -11,7 +11,7 @@ function setupContextMenu($image: JQuery<HTMLElement>) {}$image.prop(PROP_NAME, true);- $image.on('contextmenu', e => {+ $image.on("contextmenu", (e) => {e.preventDefault();contextMenu.show({@@ -27,17 +27,17 @@ function setupContextMenu($image: JQuery<HTMLElement>) {title: t("image_context_menu.copy_image_to_clipboard"),command: "copyImageToClipboard",uiIcon: "bx bx-copy"- },+ }],selectMenuItemHandler: async ({ command }) => {- if (command === 'copyImageReferenceToClipboard') {+ if (command === "copyImageReferenceToClipboard") {imageService.copyImageReferenceToClipboard($image);- } else if (command === 'copyImageToClipboard') {+ } else if (command === "copyImageToClipboard") {try {- const nativeImage = utils.dynamicRequire('electron').nativeImage;- const clipboard = utils.dynamicRequire('electron').clipboard;+ const nativeImage = utils.dynamicRequire("electron").nativeImage;+ const clipboard = utils.dynamicRequire("electron").clipboard;- const src = $image.attr('src');+ const src = $image.attr("src");if (!src) {console.error("Missing src");return;@@ -46,15 +46,9 @@ function setupContextMenu($image: JQuery<HTMLElement>) {const response = await fetch(src);const blob = await response.blob();- clipboard.writeImage(- nativeImage.createFromBuffer(- Buffer.from(- await blob.arrayBuffer()- )- )- );+ clipboard.writeImage(nativeImage.createFromBuffer(Buffer.from(await blob.arrayBuffer())));} catch (error) {- console.error('Failed to copy image to clipboard:', error);+ console.error("Failed to copy image to clipboard:", error);}} else {throw new Error(`Unrecognized command '${command}'`);diff --git a/src/public/app/menus/launcher_context_menu.ts b/src/public/app/menus/launcher_context_menu.tsindex 0c4aaca6c4..da69cb3a98 100644--- a/src/public/app/menus/launcher_context_menu.ts+++ b/src/public/app/menus/launcher_context_menu.ts@@ -1,17 +1,16 @@-import treeService, { Node } from '../services/tree.js';+import treeService, { Node } from "../services/tree.js";import froca from "../services/froca.js";import contextMenu, { MenuCommandItem, MenuItem } from "./context_menu.js";import dialogService from "../services/dialog.js";import server from "../services/server.js";-import { t } from '../services/i18n.js';-import type { SelectMenuItemEventListener } from '../components/events.js';-import NoteTreeWidget from '../widgets/note_tree.js';-import { FilteredCommandNames, ContextMenuCommandData } from '../components/app_context.js';+import { t } from "../services/i18n.js";+import type { SelectMenuItemEventListener } from "../components/events.js";+import NoteTreeWidget from "../widgets/note_tree.js";+import { FilteredCommandNames, ContextMenuCommandData } from "../components/app_context.js";type LauncherCommandNames = FilteredCommandNames<ContextMenuCommandData>;export default class LauncherContextMenu implements SelectMenuItemEventListener<LauncherCommandNames> {-private treeWidget: NoteTreeWidget;private node: Node;@@ -26,48 +25,48 @@ export default class LauncherContextMenu implements SelectMenuItemEventListener<y: e.pageY,items: await this.getMenuItems(),selectMenuItemHandler: (item, e) => this.selectMenuItemHandler(item)- })+ });}async getMenuItems(): Promise<MenuItem<LauncherCommandNames>[]> {const note = this.node.data.noteId ? await froca.getNote(this.node.data.noteId) : null;const parentNoteId = this.node.getParent().data.noteId;- const isVisibleRoot = note?.noteId === '_lbVisibleLaunchers';- const isAvailableRoot = note?.noteId === '_lbAvailableLaunchers';- const isVisibleItem = parentNoteId === '_lbVisibleLaunchers';- const isAvailableItem = parentNoteId === '_lbAvailableLaunchers';+ const isVisibleRoot = note?.noteId === "_lbVisibleLaunchers";+ const isAvailableRoot = note?.noteId === "_lbAvailableLaunchers";+ const isVisibleItem = parentNoteId === "_lbVisibleLaunchers";+ const isAvailableItem = parentNoteId === "_lbAvailableLaunchers";const isItem = isVisibleItem || isAvailableItem;const canBeDeleted = !note?.noteId.startsWith("_"); // fixed notes can't be deletedconst canBeReset = !canBeDeleted && note?.isLaunchBarConfig();const items: (MenuItem<LauncherCommandNames> | null)[] = [- (isVisibleRoot || isAvailableRoot) ? { title: t("launcher_context_menu.add-note-launcher"), command: 'addNoteLauncher', uiIcon: "bx bx-note" } : null,- (isVisibleRoot || isAvailableRoot) ? { title: t("launcher_context_menu.add-script-launcher"), command: 'addScriptLauncher', uiIcon: "bx bx-code-curly" } : null,- (isVisibleRoot || isAvailableRoot) ? { title: t("launcher_context_menu.add-custom-widget"), command: 'addWidgetLauncher', uiIcon: "bx bx-customize" } : null,- (isVisibleRoot || isAvailableRoot) ? { title: t("launcher_context_menu.add-spacer"), command: 'addSpacerLauncher', uiIcon: "bx bx-dots-horizontal" } : null,- (isVisibleRoot || isAvailableRoot) ? { title: "----" } : null,+ isVisibleRoot || isAvailableRoot ? { title: t("launcher_context_menu.add-note-launcher"), command: "addNoteLauncher", uiIcon: "bx bx-note" } : null,+ isVisibleRoot || isAvailableRoot ? { title: t("launcher_context_menu.add-script-launcher"), command: "addScriptLauncher", uiIcon: "bx bx-code-curly" } : null,+ isVisibleRoot || isAvailableRoot ? { title: t("launcher_context_menu.add-custom-widget"), command: "addWidgetLauncher", uiIcon: "bx bx-customize" } : null,+ isVisibleRoot || isAvailableRoot ? { title: t("launcher_context_menu.add-spacer"), command: "addSpacerLauncher", uiIcon: "bx bx-dots-horizontal" } : null,+ isVisibleRoot || isAvailableRoot ? { title: "----" } : null,isAvailableItem ? { title: t("launcher_context_menu.move-to-visible-launchers"), command: "moveLauncherToVisible", uiIcon: "bx bx-show", enabled: true } : null,isVisibleItem ? { title: t("launcher_context_menu.move-to-available-launchers"), command: "moveLauncherToAvailable", uiIcon: "bx bx-hide", enabled: true } : null,- (isVisibleItem || isAvailableItem) ? { title: "----" } : null,+ isVisibleItem || isAvailableItem ? { title: "----" } : null,{ title: `${t("launcher_context_menu.duplicate-launcher")}`, command: "duplicateSubtree", uiIcon: "bx bx-outline", enabled: isItem },{ title: `${t("launcher_context_menu.delete")}`, command: "deleteNotes", uiIcon: "bx bx-trash destructive-action-icon", enabled: canBeDeleted },{ title: "----" },- { title: t("launcher_context_menu.reset"), command: "resetLauncher", uiIcon: "bx bx-reset destructive-action-icon", enabled: canBeReset}+ { title: t("launcher_context_menu.reset"), command: "resetLauncher", uiIcon: "bx bx-reset destructive-action-icon", enabled: canBeReset }];- return items.filter(row => row !== null);+ return items.filter((row) => row !== null);}- async selectMenuItemHandler({command}: MenuCommandItem<LauncherCommandNames>) {+ async selectMenuItemHandler({ command }: MenuCommandItem<LauncherCommandNames>) {if (!command) {return;}- if (command === 'resetLauncher') {+ if (command === "resetLauncher") {const confirmed = await dialogService.confirm(t("launcher_context_menu.reset_launcher_confirm", { title: this.node.title }));if (confirmed) {diff --git a/src/public/app/menus/link_context_menu.ts b/src/public/app/menus/link_context_menu.tsindex 1c0993f76c..e1ecef06d7 100644--- a/src/public/app/menus/link_context_menu.ts+++ b/src/public/app/menus/link_context_menu.ts@@ -8,26 +8,24 @@ function openContextMenu(notePath: string, e: PointerEvent, viewScope: ViewScopex: e.pageX,y: e.pageY,items: [- {title: t("link_context_menu.open_note_in_new_tab"), command: "openNoteInNewTab", uiIcon: "bx bx-link-external"},- {title: t("link_context_menu.open_note_in_new_split"), command: "openNoteInNewSplit", uiIcon: "bx bx-dock-right"},- {title: t("link_context_menu.open_note_in_new_window"), command: "openNoteInNewWindow", uiIcon: "bx bx-window-open"}+ { title: t("link_context_menu.open_note_in_new_tab"), command: "openNoteInNewTab", uiIcon: "bx bx-link-external" },+ { title: t("link_context_menu.open_note_in_new_split"), command: "openNoteInNewSplit", uiIcon: "bx bx-dock-right" },+ { title: t("link_context_menu.open_note_in_new_window"), command: "openNoteInNewWindow", uiIcon: "bx bx-window-open" }],- selectMenuItemHandler: ({command}) => {+ selectMenuItemHandler: ({ command }) => {if (!hoistedNoteId) {hoistedNoteId = appContext.tabManager.getActiveContext().hoistedNoteId;}- if (command === 'openNoteInNewTab') {+ if (command === "openNoteInNewTab") {appContext.tabManager.openContextWithNote(notePath, { hoistedNoteId, viewScope });- }- else if (command === 'openNoteInNewSplit') {+ } else if (command === "openNoteInNewSplit") {const subContexts = appContext.tabManager.getActiveContext().getSubContexts();- const {ntxId} = subContexts[subContexts.length - 1];+ const { ntxId } = subContexts[subContexts.length - 1];- appContext.triggerCommand("openNewNoteSplit", {ntxId, notePath, hoistedNoteId, viewScope});- }- else if (command === 'openNoteInNewWindow') {- appContext.triggerCommand('openInWindow', {notePath, hoistedNoteId, viewScope});+ appContext.triggerCommand("openNewNoteSplit", { ntxId, notePath, hoistedNoteId, viewScope });+ } else if (command === "openNoteInNewWindow") {+ appContext.triggerCommand("openInWindow", { notePath, hoistedNoteId, viewScope });}}});@@ -35,4 +33,4 @@ function openContextMenu(notePath: string, e: PointerEvent, viewScope: ViewScopeexport default {openContextMenu-}+};diff --git a/src/public/app/menus/tree_context_menu.ts b/src/public/app/menus/tree_context_menu.tsindex ada4bec217..15e125ffe1 100644--- a/src/public/app/menus/tree_context_menu.ts+++ b/src/public/app/menus/tree_context_menu.ts@@ -1,6 +1,6 @@-import treeService, { Node } from '../services/tree.js';+import treeService, { Node } from "../services/tree.js";import froca from "../services/froca.js";-import clipboard from '../services/clipboard.js';+import clipboard from "../services/clipboard.js";import noteCreateService from "../services/note_create.js";import contextMenu, { MenuCommandItem, MenuItem } from "./context_menu.js";import appContext, { ContextMenuCommandData, FilteredCommandNames } from "../components/app_context.js";@@ -9,9 +9,9 @@ import server from "../services/server.js";import toastService from "../services/toast.js";import dialogService from "../services/dialog.js";import { t } from "../services/i18n.js";-import NoteTreeWidget from '../widgets/note_tree.js';-import FAttachment from '../entities/fattachment.js';-import { SelectMenuItemEventListener } from '../components/events.js';+import NoteTreeWidget from "../widgets/note_tree.js";+import FAttachment from "../entities/fattachment.js";+import { SelectMenuItemEventListener } from "../components/events.js";// TODO: Deduplicate once client/server is well split.interface ConvertToAttachmentResponse {@@ -21,7 +21,6 @@ interface ConvertToAttachmentResponse {type TreeCommandNames = FilteredCommandNames<ContextMenuCommandData>;export default class TreeContextMenu implements SelectMenuItemEventListener<TreeCommandNames> {-private treeWidget: NoteTreeWidget;private node: Node;@@ -36,13 +35,13 @@ export default class TreeContextMenu implements SelectMenuItemEventListener<Treey: e.pageY,items: await this.getMenuItems(),selectMenuItemHandler: (item, e) => this.selectMenuItemHandler(item)- })+ });}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 isNotRoot = note?.noteId !== "root";const isHoisted = note?.noteId === appContext.tabManager.getActiveContext().hoistedNoteId;const parentNote = isNotRoot && branch ? await froca.getNote(branch.parentNoteId) : null;@@ -50,12 +49,11 @@ export default class TreeContextMenu implements SelectMenuItemEventListener<Tree// 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 noSelectedNotes = selNodes.length === 0- || (selNodes.length === 1 && selNodes[0] === this.node);+ const noSelectedNotes = selNodes.length === 0 || (selNodes.length === 1 && selNodes[0] === this.node);- const notSearch = note?.type !== 'search';+ const notSearch = note?.type !== "search";const notOptions = !note?.noteId.startsWith("_options");- const parentNotSearch = !parentNote || parentNote.type !== 'search';+ const parentNotSearch = !parentNote || parentNote.type !== "search";const insertNoteAfterEnabled = isNotRoot && !isHoisted && parentNotSearch;const items: (MenuItem<TreeCommandNames> | null)[] = [@@ -63,117 +61,161 @@ export default class TreeContextMenu implements SelectMenuItemEventListener<Tree{ title: t("tree-context-menu.open-in-a-new-split"), command: "openNoteInSplit", uiIcon: "bx bx-dock-right", enabled: noSelectedNotes },- isHoisted ? null : { title: `${t("tree-context-menu.hoist-note")} <kbd data-command="toggleNoteHoisting"></kbd>`, command: "toggleNoteHoisting", uiIcon: "bx bxs-chevrons-up", enabled: noSelectedNotes && notSearch },- !isHoisted || !isNotRoot ? null : { title: `${t("tree-context-menu.unhoist-note")} <kbd data-command="toggleNoteHoisting"></kbd>`, command: "toggleNoteHoisting", uiIcon: "bx bx-door-open" },-+ isHoisted+ ? null+ : {+ title: `${t("tree-context-menu.hoist-note")} <kbd data-command="toggleNoteHoisting"></kbd>`,+ command: "toggleNoteHoisting",+ uiIcon: "bx bxs-chevrons-up",+ enabled: noSelectedNotes && notSearch+ },+ !isHoisted || !isNotRoot+ ? null+ : { title: `${t("tree-context-menu.unhoist-note")} <kbd data-command="toggleNoteHoisting"></kbd>`, command: "toggleNoteHoisting", uiIcon: "bx bx-door-open" },{ title: "----" },-- { title: `${t("tree-context-menu.insert-note-after")}<kbd data-command="createNoteAfter"></kbd>`, command: "insertNoteAfter", uiIcon: "bx bx-plus",+ {+ title: `${t("tree-context-menu.insert-note-after")}<kbd data-command="createNoteAfter"></kbd>`,+ command: "insertNoteAfter",+ uiIcon: "bx bx-plus",items: insertNoteAfterEnabled ? await noteTypesService.getNoteTypeItems("insertNoteAfter") : null,- enabled: insertNoteAfterEnabled && noSelectedNotes && notOptions },+ enabled: insertNoteAfterEnabled && noSelectedNotes && notOptions+ },- { title: `${t("tree-context-menu.insert-child-note")}<kbd data-command="createNoteInto"></kbd>`, command: "insertChildNote", uiIcon: "bx bx-plus",+ {+ title: `${t("tree-context-menu.insert-child-note")}<kbd data-command="createNoteInto"></kbd>`,+ command: "insertChildNote",+ uiIcon: "bx bx-plus",items: notSearch ? await noteTypesService.getNoteTypeItems("insertChildNote") : null,- enabled: notSearch && noSelectedNotes && notOptions },-+ enabled: notSearch && noSelectedNotes && notOptions+ },{ title: "----" },-{ 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 },-{ title: "----" },-- { 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 },-- { title: "----" },-- { title: `${t("tree-context-menu.edit-branch-prefix")} <kbd data-command="editBranchPrefix"></kbd>`, command: "editBranchPrefix", uiIcon: "bx bx-rename", enabled: isNotRoot && parentNotSearch && noSelectedNotes && notOptions },- { title: t("tree-context-menu.convert-to-attachment"), command: "convertNoteToAttachment", uiIcon: "bx bx-paperclip", enabled: isNotRoot && !isHoisted && notOptions },- { title: `${t("tree-context-menu.duplicate-subtree")} <kbd data-command="duplicateSubtree">`, command: "duplicateSubtree", uiIcon: "bx bx-outline", enabled: parentNotSearch && isNotRoot && !isHoisted && notOptions },-- { title: "----" },-- { title: `${t("tree-context-menu.expand-subtree")} <kbd data-command="expandSubtree"></kbd>`, command: "expandSubtree", uiIcon: "bx bx-expand", enabled: noSelectedNotes },- { title: `${t("tree-context-menu.collapse-subtree")} <kbd data-command="collapseSubtree"></kbd>`, command: "collapseSubtree", uiIcon: "bx bx-collapse", enabled: noSelectedNotes },- { title: `${t("tree-context-menu.sort-by")} <kbd data-command="sortChildNotes"></kbd>`, command: "sortChildNotes", uiIcon: "bx bx-sort-down", enabled: noSelectedNotes && notSearch },-- { title: "----" },-- { 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 && notOptions },- ] },-+ {+ 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 },++ { title: "----" },++ {+ title: `${t("tree-context-menu.edit-branch-prefix")} <kbd data-command="editBranchPrefix"></kbd>`,+ command: "editBranchPrefix",+ uiIcon: "bx bx-rename",+ enabled: isNotRoot && parentNotSearch && noSelectedNotes && notOptions+ },+ { title: t("tree-context-menu.convert-to-attachment"), command: "convertNoteToAttachment", uiIcon: "bx bx-paperclip", enabled: isNotRoot && !isHoisted && notOptions },+ {+ title: `${t("tree-context-menu.duplicate-subtree")} <kbd data-command="duplicateSubtree">`,+ command: "duplicateSubtree",+ uiIcon: "bx bx-outline",+ enabled: parentNotSearch && isNotRoot && !isHoisted && notOptions+ },++ { title: "----" },++ { title: `${t("tree-context-menu.expand-subtree")} <kbd data-command="expandSubtree"></kbd>`, command: "expandSubtree", uiIcon: "bx bx-expand", enabled: noSelectedNotes },+ { title: `${t("tree-context-menu.collapse-subtree")} <kbd data-command="collapseSubtree"></kbd>`, command: "collapseSubtree", uiIcon: "bx bx-collapse", enabled: noSelectedNotes },+ {+ title: `${t("tree-context-menu.sort-by")} <kbd data-command="sortChildNotes"></kbd>`,+ command: "sortChildNotes",+ uiIcon: "bx bx-sort-down",+ enabled: noSelectedNotes && notSearch+ },++ { title: "----" },++ { 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 && notOptions }+ ]+ },{ title: "----" },-- { title: `${t("tree-context-menu.cut")} <kbd data-command="cutNotesToClipboard"></kbd>`, command: "cutNotesToClipboard", uiIcon: "bx bx-cut",- enabled: isNotRoot && !isHoisted && parentNotSearch },-- { title: `${t("tree-context-menu.copy-clone")} <kbd data-command="copyNotesToClipboard"></kbd>`, command: "copyNotesToClipboard", uiIcon: "bx bx-copy",- enabled: isNotRoot && !isHoisted },-- { title: `${t("tree-context-menu.paste-into")} <kbd data-command="pasteNotesFromClipboard"></kbd>`, command: "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")} <kbd data-command="moveNotesTo"></kbd>`, command: "moveNotesTo", uiIcon: "bx bx-transfer",- enabled: isNotRoot && !isHoisted && parentNotSearch },-- { title: `${t("tree-context-menu.clone-to")} <kbd data-command="cloneNotesTo"></kbd>`, command: "cloneNotesTo", uiIcon: "bx bx-duplicate",- enabled: isNotRoot && !isHoisted },-- { title: `${t("tree-context-menu.delete")} <kbd data-command="deleteNotes"></kbd>`, command: "deleteNotes", uiIcon: "bx bx-trash destructive-action-icon",- enabled: isNotRoot && !isHoisted && parentNotSearch && notOptions },+ {+ title: `${t("tree-context-menu.cut")} <kbd data-command="cutNotesToClipboard"></kbd>`,+ command: "cutNotesToClipboard",+ uiIcon: "bx bx-cut",+ enabled: isNotRoot && !isHoisted && parentNotSearch+ },++ { title: `${t("tree-context-menu.copy-clone")} <kbd data-command="copyNotesToClipboard"></kbd>`, command: "copyNotesToClipboard", uiIcon: "bx bx-copy", enabled: isNotRoot && !isHoisted },++ {+ title: `${t("tree-context-menu.paste-into")} <kbd data-command="pasteNotesFromClipboard"></kbd>`,+ command: "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")} <kbd data-command="moveNotesTo"></kbd>`,+ command: "moveNotesTo",+ uiIcon: "bx bx-transfer",+ enabled: isNotRoot && !isHoisted && parentNotSearch+ },++ { title: `${t("tree-context-menu.clone-to")} <kbd data-command="cloneNotesTo"></kbd>`, command: "cloneNotesTo", uiIcon: "bx bx-duplicate", enabled: isNotRoot && !isHoisted },++ {+ title: `${t("tree-context-menu.delete")} <kbd data-command="deleteNotes"></kbd>`,+ command: "deleteNotes",+ uiIcon: "bx bx-trash destructive-action-icon",+ enabled: isNotRoot && !isHoisted && parentNotSearch && notOptions+ },{ title: "----" },- { title: t("tree-context-menu.import-into-note"), command: "importIntoNote", uiIcon: "bx bx-import",- enabled: notSearch && noSelectedNotes && notOptions },-- { title: t("tree-context-menu.export"), command: "exportNote", uiIcon: "bx bx-export",- enabled: notSearch && noSelectedNotes && notOptions },+ { title: t("tree-context-menu.import-into-note"), command: "importIntoNote", uiIcon: "bx bx-import", enabled: notSearch && noSelectedNotes && notOptions },+ { title: t("tree-context-menu.export"), command: "exportNote", uiIcon: "bx bx-export", enabled: notSearch && noSelectedNotes && notOptions },{ title: "----" },-- { title: `${t("tree-context-menu.search-in-subtree")} <kbd data-command="searchInSubtree"></kbd>`, command: "searchInSubtree", uiIcon: "bx bx-search",- enabled: notSearch && noSelectedNotes },-+ {+ title: `${t("tree-context-menu.search-in-subtree")} <kbd data-command="searchInSubtree"></kbd>`,+ command: "searchInSubtree",+ uiIcon: "bx bx-search",+ enabled: notSearch && noSelectedNotes+ }];- return items.filter(row => row !== null);+ return items.filter((row) => row !== null);}- async selectMenuItemHandler({command, type, templateNoteId}: MenuCommandItem<TreeCommandNames>) {+ async selectMenuItemHandler({ command, type, templateNoteId }: MenuCommandItem<TreeCommandNames>) {const notePath = treeService.getNotePath(this.node);- if (command === 'openInTab') {+ if (command === "openInTab") {appContext.tabManager.openTabWithNoteWithHoisting(notePath);- }- else if (command === "insertNoteAfter") {+ } else if (command === "insertNoteAfter") {const parentNotePath = treeService.getNotePath(this.node.getParent());const isProtected = treeService.getParentProtectedStatus(this.node);noteCreateService.createNote(parentNotePath, {- target: 'after',+ target: "after",targetBranchId: this.node.data.branchId,type: type,isProtected: isProtected,templateNoteId: templateNoteId});- }- else if (command === "insertChildNote") {+ } else if (command === "insertChildNote") {const parentNotePath = treeService.getNotePath(this.node);noteCreateService.createNote(parentNotePath, {@@ -181,15 +223,13 @@ export default class TreeContextMenu implements SelectMenuItemEventListener<TreeisProtected: this.node.data.isProtected,templateNoteId: templateNoteId});- }- else if (command === 'openNoteInSplit') {+ } else if (command === "openNoteInSplit") {const subContexts = appContext.tabManager.getActiveContext().getSubContexts();- const {ntxId} = subContexts[subContexts.length - 1];+ const { ntxId } = subContexts[subContexts.length - 1];- this.treeWidget.triggerCommand("openNewNoteSplit", {ntxId, notePath});- }- else if (command === 'convertNoteToAttachment') {- if (!await dialogService.confirm(t("tree-context-menu.convert-to-attachment-confirm"))) {+ this.treeWidget.triggerCommand("openNewNoteSplit", { ntxId, notePath });+ } else if (command === "convertNoteToAttachment") {+ if (!(await dialogService.confirm(t("tree-context-menu.convert-to-attachment-confirm")))) {return;}@@ -199,7 +239,7 @@ export default class TreeContextMenu implements SelectMenuItemEventListener<Treeconst note = await froca.getNote(noteId);if (note?.isEligibleForConversionToAttachment()) {- const {attachment} = await server.post<ConvertToAttachmentResponse>(`notes/${note.noteId}/convert-to-attachment`);+ const { attachment } = await server.post<ConvertToAttachmentResponse>(`notes/${note.noteId}/convert-to-attachment`);if (attachment) {converted++;@@ -208,11 +248,9 @@ export default class TreeContextMenu implements SelectMenuItemEventListener<Tree}toastService.showMessage(t("tree-context-menu.converted-to-attachments", { count: converted }));- }- else if (command === 'copyNotePathToClipboard') {- navigator.clipboard.writeText('#' + notePath);- }- else if (command) {+ } else if (command === "copyNotePathToClipboard") {+ navigator.clipboard.writeText("#" + notePath);+ } else if (command) {this.treeWidget.triggerCommand<TreeCommandNames>(command, {node: this.node,notePath: notePath,diff --git a/src/public/app/mobile.js b/src/public/app/mobile.jsindex 2319d7f9e1..6690566d4b 100644--- a/src/public/app/mobile.js+++ b/src/public/app/mobile.js@@ -1,8 +1,8 @@import appContext from "./components/app_context.js";-import noteAutocompleteService from './services/note_autocomplete.js';+import noteAutocompleteService from "./services/note_autocomplete.js";import glob from "./services/glob.js";-glob.setupGlobs()+glob.setupGlobs();await appContext.earlyInit();diff --git a/src/public/app/services/attribute_autocomplete.ts b/src/public/app/services/attribute_autocomplete.tsindex 88ac35ead7..2721c13d8e 100644--- a/src/public/app/services/attribute_autocomplete.ts+++ b/src/public/app/services/attribute_autocomplete.ts@@ -15,29 +15,34 @@ interface InitOptions {*/function initAttributeNameAutocomplete({ $el, attributeType, open }: InitOptions) {if (!$el.hasClass("aa-input")) {- $el.autocomplete({- appendTo: document.querySelector('body'),- hint: false,- openOnFocus: true,- minLength: 0,- tabAutocomplete: false- }, [{- displayKey: 'name',- // disabling cache is important here because otherwise cache can stay intact when switching between attribute type which will lead to autocomplete displaying attribute names for incorrect attribute type- cache: false,- source: async (term, cb) => {- const type = typeof attributeType === "function" ? attributeType() : attributeType;-- const names = await server.get<string[]>(`attribute-names/?type=${type}&query=${encodeURIComponent(term)}`);- const result = names.map(name => ({name}));-- cb(result);- }- }]);-- $el.on('autocomplete:opened', () => {+ $el.autocomplete(+ {+ appendTo: document.querySelector("body"),+ hint: false,+ openOnFocus: true,+ minLength: 0,+ tabAutocomplete: false+ },+ [+ {+ displayKey: "name",+ // disabling cache is important here because otherwise cache can stay intact when switching between attribute type which will lead to autocomplete displaying attribute names for incorrect attribute type+ cache: false,+ source: async (term, cb) => {+ const type = typeof attributeType === "function" ? attributeType() : attributeType;++ const names = await server.get<string[]>(`attribute-names/?type=${type}&query=${encodeURIComponent(term)}`);+ const result = names.map((name) => ({ name }));++ cb(result);+ }+ }+ ]+ );++ $el.on("autocomplete:opened", () => {if ($el.attr("readonly")) {- $el.autocomplete('close');+ $el.autocomplete("close");}});}@@ -51,7 +56,7 @@ async function initLabelValueAutocomplete({ $el, open, nameCallback }: InitOptioif ($el.hasClass("aa-input")) {// we reinit every time because autocomplete seems to have a bug where it retains state from last// open even though the value was reset- $el.autocomplete('destroy');+ $el.autocomplete("destroy");}let attributeName = "";@@ -63,34 +68,38 @@ async function initLabelValueAutocomplete({ $el, open, nameCallback }: InitOptioreturn;}- const attributeValues = (await server.get<string[]>(`attribute-values/${encodeURIComponent(attributeName)}`))- .map(attribute => ({ value: attribute }));+ const attributeValues = (await server.get<string[]>(`attribute-values/${encodeURIComponent(attributeName)}`)).map((attribute) => ({ value: attribute }));if (attributeValues.length === 0) {return;}- $el.autocomplete({- appendTo: document.querySelector('body'),- hint: false,- openOnFocus: false, // handled manually- minLength: 0,- tabAutocomplete: false- }, [{- displayKey: 'value',- cache: false,- source: async function (term, cb) {- term = term.toLowerCase();-- const filtered = attributeValues.filter(attr => attr.value.toLowerCase().includes(term));-- cb(filtered);- }- }]);+ $el.autocomplete(+ {+ appendTo: document.querySelector("body"),+ hint: false,+ openOnFocus: false, // handled manually+ minLength: 0,+ tabAutocomplete: false+ },+ [+ {+ displayKey: "value",+ cache: false,+ source: async function (term, cb) {+ term = term.toLowerCase();++ const filtered = attributeValues.filter((attr) => attr.value.toLowerCase().includes(term));++ cb(filtered);+ }+ }+ ]+ );- $el.on('autocomplete:opened', () => {+ $el.on("autocomplete:opened", () => {if ($el.attr("readonly")) {- $el.autocomplete('close');+ $el.autocomplete("close");}});@@ -102,4 +111,4 @@ async function initLabelValueAutocomplete({ $el, open, nameCallback }: InitOptioexport default {initAttributeNameAutocomplete,initLabelValueAutocomplete-}+};diff --git a/src/public/app/services/attribute_parser.ts b/src/public/app/services/attribute_parser.tsindex c2a10d471a..d97f6a9c06 100644--- a/src/public/app/services/attribute_parser.ts+++ b/src/public/app/services/attribute_parser.ts@@ -23,17 +23,16 @@ function lex(str: string) {const tokens: Token[] = [];let quotes: boolean | string = false;- let currentWord = '';+ let currentWord = "";function isOperatorSymbol(chr: string) {- return ['=', '*', '>', '<', '!'].includes(chr);+ return ["=", "*", ">", "<", "!"].includes(chr);}function previousOperatorSymbol() {if (currentWord.length === 0) {return false;- }- else {+ } else {return isOperatorSymbol(currentWord[currentWord.length - 1]);}}@@ -42,7 +41,7 @@ function lex(str: string) {* @param endIndex - index of the last character of the token*/function finishWord(endIndex: number) {- if (currentWord === '') {+ if (currentWord === "") {return;}@@ -52,54 +51,47 @@ function lex(str: string) {endIndex: endIndex});- currentWord = '';+ currentWord = "";}for (let i = 0; i < str.length; i++) {const chr = str[i];- if (chr === '\\') {- if ((i + 1) < str.length) {+ if (chr === "\\") {+ if (i + 1 < str.length) {i++;currentWord += str[i];- }- else {+ } else {currentWord += chr;}continue;- }- else if (['"', "'", '`'].includes(chr)) {+ } else if (['"', "'", "`"].includes(chr)) {if (!quotes) {if (previousOperatorSymbol()) {finishWord(i - 1);}quotes = chr;- }- else if (quotes === chr) {+ } else if (quotes === chr) {quotes = false;finishWord(i - 1);- }- else {+ } else {// it's a quote, but within other kind of quotes, so it's valid as a literal charactercurrentWord += chr;}continue;- }- else if (!quotes) {- if (currentWord.length === 0 && (chr === '#' || chr === '~')) {+ } else if (!quotes) {+ if (currentWord.length === 0 && (chr === "#" || chr === "~")) {currentWord = chr;continue;- }- else if (chr === ' ') {+ } else if (chr === " ") {finishWord(i - 1);continue;- }- else if (['(', ')'].includes(chr)) {+ } else if (["(", ")"].includes(chr)) {finishWord(i - 1);currentWord = chr;@@ -107,8 +99,7 @@ function lex(str: string) {finishWord(i);continue;- }- else if (previousOperatorSymbol() !== isOperatorSymbol(chr)) {+ } else if (previousOperatorSymbol() !== isOperatorSymbol(chr)) {finishWord(i - 1);currentWord += chr;@@ -149,27 +140,22 @@ function parse(tokens: Token[], str: string, allowEmptyRelations = false) {const { text, startIndex } = tokens[i];function isInheritable() {- if (tokens.length > i + 3- && tokens[i + 1].text === '('- && tokens[i + 2].text === 'inheritable'- && tokens[i + 3].text === ')') {-+ if (tokens.length > i + 3 && tokens[i + 1].text === "(" && tokens[i + 2].text === "inheritable" && tokens[i + 3].text === ")") {i += 3;return true;- }- else {+ } else {return false;}}- if (text.startsWith('#')) {+ if (text.startsWith("#")) {const labelName = text.substr(1);checkAttributeName(labelName);const attr: Attribute = {- type: 'label',+ type: "label",name: labelName,isInheritable: isInheritable(),startIndex: startIndex,@@ -188,14 +174,13 @@ function parse(tokens: Token[], str: string, allowEmptyRelations = false) {}attrs.push(attr);- }- else if (text.startsWith('~')) {+ } else if (text.startsWith("~")) {const relationName = text.substr(1);checkAttributeName(relationName);const attr: Attribute = {- type: 'relation',+ type: "relation",name: relationName,isInheritable: isInheritable(),startIndex: startIndex,@@ -204,11 +189,10 @@ function parse(tokens: Token[], str: string, allowEmptyRelations = false) {attrs.push(attr);- if (i + 2 >= tokens.length || tokens[i + 1].text !== '=') {+ if (i + 2 >= tokens.length || tokens[i + 1].text !== "=") {if (allowEmptyRelations) {break;- }- else {+ } else {throw new Error(`Relation "${text}" in ${context(i)} should point to a note.`);}}@@ -220,12 +204,11 @@ function parse(tokens: Token[], str: string, allowEmptyRelations = false) {notePath = notePath.substr(1);}- const noteId = notePath.split('/').pop();+ const noteId = notePath.split("/").pop();attr.value = noteId;attr.endIndex = tokens[i].endIndex;- }- else {+ } else {throw new Error(`Invalid attribute "${text}" in ${context(i)}`);}}@@ -243,4 +226,4 @@ export default {lex,parse,lexAndParse-}+};diff --git a/src/public/app/services/attribute_renderer.ts b/src/public/app/services/attribute_renderer.tsindex b5f8477ecb..a686b7098e 100644--- a/src/public/app/services/attribute_renderer.ts+++ b/src/public/app/services/attribute_renderer.ts@@ -4,17 +4,17 @@ import FAttribute from "../entities/fattribute.js";import FNote from "../entities/fnote.js";async function renderAttribute(attribute: FAttribute, renderIsInheritable: boolean) {- const isInheritable = renderIsInheritable && attribute.isInheritable ? `(inheritable)` : '';+ const isInheritable = renderIsInheritable && attribute.isInheritable ? `(inheritable)` : "";const $attr = $("<span>");- if (attribute.type === 'label') {+ if (attribute.type === "label") {$attr.append(document.createTextNode(`#${attribute.name}${isInheritable}`));if (attribute.value) {- $attr.append('=');+ $attr.append("=");$attr.append(document.createTextNode(formatValue(attribute.value)));}- } else if (attribute.type === 'relation') {+ } else if (attribute.type === "relation") {if (attribute.isAutoLink) {return $attr;}@@ -38,17 +38,13 @@ async function renderAttribute(attribute: FAttribute, renderIsInheritable: boolefunction formatValue(val: string) {if (/^[\p{L}\p{N}\-_,.]+$/u.test(val)) {return val;- }- else if (!val.includes('"')) {+ } else if (!val.includes('"')) {return `"${val}"`;- }- else if (!val.includes("'")) {+ } else if (!val.includes("'")) {return `'${val}'`;- }- else if (!val.includes("`")) {+ } else if (!val.includes("`")) {return `\`${val}\``;- }- else {+ } else {return `"${val.replace(/"/g, '\\"')}"`;}}@@ -62,9 +58,8 @@ async function createLink(noteId: string) {return $("<a>", {href: `#root/${noteId}`,- class: 'reference-link'- })- .text(note.title);+ class: "reference-link"+ }).text(note.title);}async function renderAttributes(attributes: FAttribute[], renderIsInheritable: boolean) {@@ -84,31 +79,16 @@ async function renderAttributes(attributes: FAttribute[], renderIsInheritable: breturn $container;}-const HIDDEN_ATTRIBUTES = [- 'originalFileName',- 'fileSize',- 'template',- 'inherit',- 'cssClass',- 'iconClass',- 'pageSize',- 'viewType'-];+const HIDDEN_ATTRIBUTES = ["originalFileName", "fileSize", "template", "inherit", "cssClass", "iconClass", "pageSize", "viewType"];async function renderNormalAttributes(note: FNote) {const promotedDefinitionAttributes = note.getPromotedDefinitionAttributes();let attrs = note.getAttributes();if (promotedDefinitionAttributes.length > 0) {- attrs = attrs.filter(attr => !!promotedDefinitionAttributes.find(promAttr => promAttr.isDefinitionFor(attr)));- }- else {- attrs = attrs.filter(- attr => !attr.isDefinition()- && !attr.isAutoLink- && !HIDDEN_ATTRIBUTES.includes(attr.name)- && attr.noteId === note.noteId- );+ attrs = attrs.filter((attr) => !!promotedDefinitionAttributes.find((promAttr) => promAttr.isDefinitionFor(attr)));+ } else {+ attrs = attrs.filter((attr) => !attr.isDefinition() && !attr.isAutoLink && !HIDDEN_ATTRIBUTES.includes(attr.name) && attr.noteId === note.noteId);}const $renderedAttributes = await renderAttributes(attrs, false);@@ -116,11 +96,11 @@ async function renderNormalAttributes(note: FNote) {return {count: attrs.length,$renderedAttributes- }+ };}export default {renderAttribute,renderAttributes,renderNormalAttributes-}+};diff --git a/src/public/app/services/attributes.ts b/src/public/app/services/attributes.tsindex 4e3eb1fe2b..48ec1c3366 100644--- a/src/public/app/services/attributes.ts+++ b/src/public/app/services/attributes.ts@@ -1,11 +1,11 @@-import server from './server.js';-import froca from './froca.js';-import FNote from '../entities/fnote.js';-import { AttributeRow } from './load_results.js';+import server from "./server.js";+import froca from "./froca.js";+import FNote from "../entities/fnote.js";+import { AttributeRow } from "./load_results.js";async function addLabel(noteId: string, name: string, value: string = "") {await server.put(`notes/${noteId}/attribute`, {- type: 'label',+ type: "label",name: name,value: value});@@ -13,7 +13,7 @@ async function addLabel(noteId: string, name: string, value: string = "") {async function setLabel(noteId: string, name: string, value: string = "") {await server.put(`notes/${noteId}/set-attribute`, {- type: 'label',+ type: "label",name: name,value: value});@@ -68,4 +68,4 @@ export default {setLabel,removeAttributeById,isAffecting-}+};diff --git a/src/public/app/services/branches.ts b/src/public/app/services/branches.tsindex 27884e77e9..401ee7b306 100644--- a/src/public/app/services/branches.ts+++ b/src/public/app/services/branches.ts@@ -1,13 +1,13 @@-import utils from './utils.js';-import server from './server.js';+import utils from "./utils.js";+import server from "./server.js";import toastService, { ToastOptions } from "./toast.js";import froca from "./froca.js";import hoistedNoteService from "./hoisted_note.js";import ws from "./ws.js";import appContext from "../components/app_context.js";-import { t } from './i18n.js';-import { Node } from './tree.js';-import { ResolveOptions } from '../widgets/dialogs/delete_notes.js';+import { t } from "./i18n.js";+import { Node } from "./tree.js";+import { ResolveOptions } from "../widgets/dialogs/delete_notes.js";// TODO: Deduplicate type with serverinterface Response {@@ -48,13 +48,7 @@ async function moveAfterBranch(branchIdsToMove: string[], afterBranchId: string)return;}- const forbiddenNoteIds = [- 'root',- hoistedNoteService.getHoistedNoteId(),- '_lbRoot',- '_lbAvailableLaunchers',- '_lbVisibleLaunchers'- ];+ const forbiddenNoteIds = ["root", hoistedNoteService.getHoistedNoteId(), "_lbRoot", "_lbAvailableLaunchers", "_lbVisibleLaunchers"];if (forbiddenNoteIds.includes(afterNote.noteId)) {toastService.showError(t("branches.cannot-move-notes-here"));@@ -79,7 +73,7 @@ async function moveToParentNote(branchIdsToMove: string[], newParentBranchId: streturn;}- if (newParentBranch.noteId === '_lbRoot') {+ if (newParentBranch.noteId === "_lbRoot") {toastService.showError(t("branches.cannot-move-notes-here"));return;}@@ -89,9 +83,7 @@ async function moveToParentNote(branchIdsToMove: string[], newParentBranchId: stfor (const branchIdToMove of branchIdsToMove) {const branchToMove = froca.getBranch(branchIdToMove);- if (!branchToMove- || branchToMove.noteId === hoistedNoteService.getHoistedNoteId()- || (await branchToMove.getParentNote())?.type === 'search') {+ if (!branchToMove || branchToMove.noteId === hoistedNoteService.getHoistedNoteId() || (await branchToMove.getParentNote())?.type === "search") {continue;}@@ -116,10 +108,10 @@ async function deleteNotes(branchIdsToDelete: string[], forceDeleteAllClones = fif (utils.isMobile()) {proceed = true;deleteAllClones = false;- }- else {- ({proceed, deleteAllClones, eraseNotes} = await new Promise<ResolveOptions>(res =>- appContext.triggerCommand('showDeleteNotesDialog', {branchIdsToDelete, callback: res, forceDeleteAllClones})));+ } else {+ ({ proceed, deleteAllClones, eraseNotes } = await new Promise<ResolveOptions>((res) =>+ appContext.triggerCommand("showDeleteNotesDialog", { branchIdsToDelete, callback: res, forceDeleteAllClones })+ ));}if (!proceed) {@@ -128,8 +120,7 @@ async function deleteNotes(branchIdsToDelete: string[], forceDeleteAllClones = ftry {await activateParentNotePath();- }- catch (e) {+ } catch (e) {console.error(e);}@@ -141,7 +132,7 @@ async function deleteNotes(branchIdsToDelete: string[], forceDeleteAllClones = fcounter++;const last = counter === branchIdsToDelete.length;- const query = `?taskId=${taskId}&eraseNotes=${eraseNotes ? 'true' : 'false'}&last=${last ? 'true' : 'false'}`;+ const query = `?taskId=${taskId}&eraseNotes=${eraseNotes ? "true" : "false"}&last=${last ? "true" : "false"}`;const branch = froca.getBranch(branchIdToDelete);@@ -170,9 +161,7 @@ async function activateParentNotePath() {}async function moveNodeUpInHierarchy(node: Node) {- if (hoistedNoteService.isHoistedNode(node)- || hoistedNoteService.isTopLevelNode(node)- || node.getParent().data.noteType === 'search') {+ if (hoistedNoteService.isHoistedNode(node) || hoistedNoteService.isTopLevelNode(node) || node.getParent().data.noteType === "search") {return;}@@ -193,20 +182,19 @@ async function moveNodeUpInHierarchy(node: Node) {}function filterSearchBranches(branchIds: string[]) {- return branchIds.filter(branchId => !branchId.startsWith('virt-'));+ return branchIds.filter((branchId) => !branchId.startsWith("virt-"));}function filterRootNote(branchIds: string[]) {const hoistedNoteId = hoistedNoteService.getHoistedNoteId();- return branchIds.filter(branchId => {+ return branchIds.filter((branchId) => {const branch = froca.getBranch(branchId);if (!branch) {return false;}- return branch.noteId !== 'root'- && branch.noteId !== hoistedNoteId;+ return branch.noteId !== "root" && branch.noteId !== hoistedNoteId;});}@@ -219,17 +207,17 @@ function makeToast(id: string, message: string): ToastOptions {};}-ws.subscribeToMessages(async message => {- if (message.taskType !== 'deleteNotes') {+ws.subscribeToMessages(async (message) => {+ if (message.taskType !== "deleteNotes") {return;}- if (message.type === 'taskError') {+ if (message.type === "taskError") {toastService.closePersistent(message.taskId);toastService.showError(message.message);- } else if (message.type === 'taskProgressCount') {+ } else if (message.type === "taskProgressCount") {toastService.showPersistent(makeToast(message.taskId, t("branches.delete-notes-in-progress", { count: message.progressCount })));- } else if (message.type === 'taskSucceeded') {+ } else if (message.type === "taskSucceeded") {const toast = makeToast(message.taskId, t("branches.delete-finished-successfully"));toast.closeAfter = 5000;@@ -237,17 +225,17 @@ ws.subscribeToMessages(async message => {}});-ws.subscribeToMessages(async message => {- if (message.taskType !== 'undeleteNotes') {+ws.subscribeToMessages(async (message) => {+ if (message.taskType !== "undeleteNotes") {return;}- if (message.type === 'taskError') {+ if (message.type === "taskError") {toastService.closePersistent(message.taskId);toastService.showError(message.message);- } else if (message.type === 'taskProgressCount') {+ } else if (message.type === "taskProgressCount") {toastService.showPersistent(makeToast(message.taskId, t("branches.undeleting-notes-in-progress", { count: message.progressCount })));- } else if (message.type === 'taskSucceeded') {+ } else if (message.type === "taskSucceeded") {const toast = makeToast(message.taskId, t("branches.undeleting-notes-finished-successfully"));toast.closeAfter = 5000;@@ -292,5 +280,5 @@ export default {moveNodeUpInHierarchy,cloneNoteAfter,cloneNoteToBranch,- cloneNoteToParentNote,+ cloneNoteToParentNote};diff --git a/src/public/app/services/bulk_action.ts b/src/public/app/services/bulk_action.tsindex 5a039ea4fb..615e1c6eb1 100644--- a/src/public/app/services/bulk_action.ts+++ b/src/public/app/services/bulk_action.ts@@ -27,7 +27,7 @@ const ACTION_GROUPS = [},{title: t("bulk_actions.notes"),- actions: [RenameNoteBulkAction, MoveNoteBulkAction, DeleteNoteBulkAction, DeleteRevisionsBulkAction],+ actions: [RenameNoteBulkAction, MoveNoteBulkAction, DeleteNoteBulkAction, DeleteRevisionsBulkAction]},{title: t("bulk_actions.other"),@@ -53,8 +53,8 @@ const ACTION_CLASSES = [async function addAction(noteId: string, actionName: string) {await server.post(`notes/${noteId}/attributes`, {- type: 'label',- name: 'action',+ type: "label",+ name: "action",value: JSON.stringify({name: actionName})@@ -64,28 +64,29 @@ async function addAction(noteId: string, actionName: string) {}function parseActions(note: FNote) {- const actionLabels = note.getLabels('action');+ const actionLabels = note.getLabels("action");- return actionLabels.map(actionAttr => {- let actionDef;+ return actionLabels+ .map((actionAttr) => {+ let actionDef;- try {- actionDef = JSON.parse(actionAttr.value);- } catch (e: any) {- logError(`Parsing of attribute: '${actionAttr.value}' failed with error: ${e.message}`);- return null;- }+ try {+ actionDef = JSON.parse(actionAttr.value);+ } catch (e: any) {+ logError(`Parsing of attribute: '${actionAttr.value}' failed with error: ${e.message}`);+ return null;+ }- const ActionClass = ACTION_CLASSES.find(actionClass => actionClass.actionName === actionDef.name);+ const ActionClass = ACTION_CLASSES.find((actionClass) => actionClass.actionName === actionDef.name);- if (!ActionClass) {- logError(`No action class for '${actionDef.name}' found.`);- return null;- }+ if (!ActionClass) {+ logError(`No action class for '${actionDef.name}' found.`);+ return null;+ }- return new ActionClass(actionAttr, actionDef);- })- .filter(action => !!action);+ return new ActionClass(actionAttr, actionDef);+ })+ .filter((action) => !!action);}export default {diff --git a/src/public/app/services/bundle.ts b/src/public/app/services/bundle.tsindex 071d89458e..a5498348e9 100644--- a/src/public/app/services/bundle.ts+++ b/src/public/app/services/bundle.ts@@ -31,9 +31,9 @@ async function executeBundle(bundle: Bundle, originEntity?: Entity | null, $contconst apiContext = await ScriptContext(bundle.noteId, bundle.allNoteIds, originEntity, $container);try {- return await (function () {+ return await function () {return eval(`const apiContext = this; (async function() { ${bundle.script}\r\n})()`);- }.call(apiContext));+ }.call(apiContext);} catch (e: any) {const note = await froca.getNote(bundle.noteId);@@ -51,7 +51,6 @@ async function executeStartupBundles() {}class WidgetsByParent {-private byParent: Record<string, Widget[]>;constructor() {@@ -73,11 +72,13 @@ class WidgetsByParent {return [];}- return this.byParent[parentName]- // previously, custom widgets were provided as a single instance, but that has the disadvantage- // for splits where we actually need multiple instaces and thus having a class to instantiate is better- // https://github.com/zadam/trilium/issues/4274- .map((w: any) => w.prototype ? new w() : w);+ return (+ this.byParent[parentName]+ // previously, custom widgets were provided as a single instance, but that has the disadvantage+ // for splits where we actually need multiple instaces and thus having a class to instantiate is better+ // https://github.com/zadam/trilium/issues/4274+ .map((w: any) => (w.prototype ? new w() : w))+ );}}@@ -121,4 +122,4 @@ export default {getAndExecuteBundle,executeStartupBundles,getWidgetBundlesByParent-}+};diff --git a/src/public/app/services/clipboard.ts b/src/public/app/services/clipboard.tsindex d1cb708e39..feffee065d 100644--- a/src/public/app/services/clipboard.ts+++ b/src/public/app/services/clipboard.ts@@ -13,14 +13,13 @@ async function pasteAfter(afterBranchId: string) {return;}- if (clipboardMode === 'cut') {+ if (clipboardMode === "cut") {await branchService.moveAfterBranch(clipboardBranchIds, afterBranchId);clipboardBranchIds = [];clipboardMode = null;- }- else if (clipboardMode === 'copy') {- const clipboardBranches = clipboardBranchIds.map(branchId => froca.getBranch(branchId));+ } else if (clipboardMode === "copy") {+ const clipboardBranches = clipboardBranchIds.map((branchId) => froca.getBranch(branchId));for (const clipboardBranch of clipboardBranches) {if (!clipboardBranch) {@@ -36,8 +35,7 @@ async function pasteAfter(afterBranchId: string) {}// copy will keep clipboardBranchIds and clipboardMode, so it's possible to paste into multiple places- }- else {+ } else {toastService.throwError(`Unrecognized clipboard mode=${clipboardMode}`);}}@@ -47,14 +45,13 @@ async function pasteInto(parentBranchId: string) {return;}- if (clipboardMode === 'cut') {+ if (clipboardMode === "cut") {await branchService.moveToParentNote(clipboardBranchIds, parentBranchId);clipboardBranchIds = [];clipboardMode = null;- }- else if (clipboardMode === 'copy') {- const clipboardBranches = clipboardBranchIds.map(branchId => froca.getBranch(branchId));+ } else if (clipboardMode === "copy") {+ const clipboardBranches = clipboardBranchIds.map((branchId) => froca.getBranch(branchId));for (const clipboardBranch of clipboardBranches) {if (!clipboardBranch) {@@ -70,19 +67,18 @@ async function pasteInto(parentBranchId: string) {}// copy will keep clipboardBranchIds and clipboardMode, so it's possible to paste into multiple places- }- else {+ } else {toastService.throwError(`Unrecognized clipboard mode=${clipboardMode}`);}}async function copy(branchIds: string[]) {clipboardBranchIds = branchIds;- clipboardMode = 'copy';+ clipboardMode = "copy";if (utils.isElectron()) {// https://github.com/zadam/trilium/issues/2401- const {clipboard} = require('electron');+ const { clipboard } = require("electron");const links = [];for (const branch of froca.getBranches(clipboardBranchIds)) {@@ -90,7 +86,7 @@ async function copy(branchIds: string[]) {links.push($link[0].outerHTML);}- clipboard.writeHTML(links.join(', '));+ clipboard.writeHTML(links.join(", "));}toastService.showMessage(t("clipboard.copied"));@@ -100,14 +96,14 @@ function cut(branchIds: string[]) {clipboardBranchIds = branchIds;if (clipboardBranchIds.length > 0) {- clipboardMode = 'cut';+ clipboardMode = "cut";toastService.showMessage(t("clipboard.cut"));}}function isClipboardEmpty() {- clipboardBranchIds = clipboardBranchIds.filter(branchId => !!froca.getBranch(branchId));+ clipboardBranchIds = clipboardBranchIds.filter((branchId) => !!froca.getBranch(branchId));return clipboardBranchIds.length === 0;}@@ -118,4 +114,4 @@ export default {cut,copy,isClipboardEmpty-}+};diff --git a/src/public/app/services/content_renderer.ts b/src/public/app/services/content_renderer.tsindex 5fe3f4fad7..a18dece1cf 100644--- a/src/public/app/services/content_renderer.ts+++ b/src/public/app/services/content_renderer.ts@@ -22,54 +22,42 @@ interface Options {imageHasZoom?: boolean;}-const CODE_MIME_TYPES = new Set([- "application/json"-]);+const CODE_MIME_TYPES = new Set(["application/json"]);async function getRenderedContent(this: {} | { ctx: string }, entity: FNote, options: Options = {}) {- options = Object.assign({- tooltip: false- }, options);+ options = Object.assign(+ {+ tooltip: false+ },+ options+ );const type = getRenderingType(entity);// attachment supports only image and file/pdf/audio/videoconst $renderedContent = $('<div class="rendered-content">');- if (type === 'text') {+ if (type === "text") {await renderText(entity, $renderedContent);- }- else if (type === 'code') {+ } else if (type === "code") {await renderCode(entity, $renderedContent);- }- else if (['image', 'canvas', 'mindMap'].includes(type)) {+ } else if (["image", "canvas", "mindMap"].includes(type)) {renderImage(entity, $renderedContent, options);- }- else if (!options.tooltip && ['file', 'pdf', 'audio', 'video'].includes(type)) {+ } else if (!options.tooltip && ["file", "pdf", "audio", "video"].includes(type)) {renderFile(entity, type, $renderedContent);- }- else if (type === 'mermaid') {+ } else if (type === "mermaid") {await renderMermaid(entity, $renderedContent);- }- else if (type === 'render') {- const $content = $('<div>');+ } else if (type === "render") {+ const $content = $("<div>");await renderService.render(entity, $content);$renderedContent.append($content);- }- else if (!options.tooltip && type === 'protectedSession') {- const $button = $(`<button class="btn btn-sm"><span class="bx bx-log-in"></span> Enter protected session</button>`)- .on('click', protectedSessionService.enterProtectedSession);+ } else if (!options.tooltip && type === "protectedSession") {+ const $button = $(`<button class="btn btn-sm"><span class="bx bx-log-in"></span> Enter protected session</button>`).on("click", protectedSessionService.enterProtectedSession);- $renderedContent.append(- $("<div>")- .append("<div>This note is protected and to access it you need to enter password.</div>")- .append("<br/>")- .append($button)- );- }- else if (entity instanceof FNote) {+ $renderedContent.append($("<div>").append("<div>This note is protected and to access it you need to enter password.</div>").append("<br/>").append($button));+ } else if (entity instanceof FNote) {$renderedContent.append($("<div>").css("display", "flex")@@ -98,13 +86,13 @@ async function renderText(note: FNote, $renderedContent: JQuery<HTMLElement>) {if (blob && !utils.isHtmlEmpty(blob.content)) {$renderedContent.append($('<div class="ck-content">').html(blob.content));- if ($renderedContent.find('span.math-tex').length > 0) {+ if ($renderedContent.find("span.math-tex").length > 0) {await libraryLoader.requireLibrary(libraryLoader.KATEX);- renderMathInElement($renderedContent[0], {trust: true});+ renderMathInElement($renderedContent[0], { trust: true });}- const getNoteIdFromLink = (el: HTMLElement) => treeService.getNoteIdFromUrl($(el).attr('href') || "");+ const getNoteIdFromLink = (el: HTMLElement) => treeService.getNoteIdFromUrl($(el).attr("href") || "");const referenceLinks = $renderedContent.find("a.reference-link");const noteIdsToPrefetch = referenceLinks.map((i, el) => getNoteIdFromLink(el));await froca.getNotes(noteIdsToPrefetch);@@ -143,9 +131,9 @@ function renderImage(entity: FNote | FAttachment, $renderedContent: JQuery<HTMLE}$renderedContent // styles needed for the zoom to work well- .css('display', 'flex')- .css('align-items', 'center')- .css('justify-content', 'center');+ .css("display", "flex")+ .css("align-items", "center")+ .css("justify-content", "center");const $img = $("<img>").attr("src", url || "")@@ -171,10 +159,10 @@ function renderFile(entity: FNote | FAttachment, type: string, $renderedContent:let entityType, entityId;if (entity instanceof FNote) {- entityType = 'notes';+ entityType = "notes";entityId = entity.noteId;} else if (entity instanceof FAttachment) {- entityType = 'attachments';+ entityType = "attachments";entityId = entity.attachmentId;} else {throw new Error(`Can't recognize entity type of '${entity}'`);@@ -182,20 +170,20 @@ function renderFile(entity: FNote | FAttachment, type: string, $renderedContent:const $content = $('<div style="display: flex; flex-direction: column; height: 100%;">');- if (type === 'pdf') {+ if (type === "pdf") {const $pdfPreview = $('<iframe class="pdf-preview" style="width: 100%; flex-grow: 100;"></iframe>');$pdfPreview.attr("src", openService.getUrlForDownload(`api/${entityType}/${entityId}/open`));$content.append($pdfPreview);- } else if (type === 'audio') {- const $audioPreview = $('<audio controls></audio>')+ } else if (type === "audio") {+ const $audioPreview = $("<audio controls></audio>").attr("src", openService.getUrlForDownload(`api/${entityType}/${entityId}/open-partial`)).attr("type", entity.mime).css("width", "100%");$content.append($audioPreview);- } else if (type === 'video') {- const $videoPreview = $('<video controls></video>')+ } else if (type === "video") {+ const $videoPreview = $("<video controls></video>").attr("src", openService.getUrlForDownload(`api/${entityType}/${entityId}/open-partial`)).attr("type", entity.mime).css("width", "100%");@@ -203,22 +191,18 @@ function renderFile(entity: FNote | FAttachment, type: string, $renderedContent:$content.append($videoPreview);}- if (entityType === 'notes' && "noteId" in entity) {+ if (entityType === "notes" && "noteId" in entity) {// TODO: we should make this available also for attachments, but there's a problem with "Open externally" support// in attachment listconst $downloadButton = $('<button class="file-download btn btn-primary" type="button">Download</button>');const $openButton = $('<button class="file-open btn btn-primary" type="button">Open</button>');- $downloadButton.on('click', () => openService.downloadFileNote(entity.noteId));- $openButton.on('click', () => openService.openNoteExternally(entity.noteId, entity.mime));+ $downloadButton.on("click", () => openService.downloadFileNote(entity.noteId));+ $openButton.on("click", () => openService.openNoteExternally(entity.noteId, entity.mime));// open doesn't work for protected notes since it works through a browser which isn't in protected session$openButton.toggle(!entity.isProtected);- $content.append(- $('<div style="display: flex; justify-content: space-evenly; margin-top: 5px;">')- .append($downloadButton)- .append($openButton)- );+ $content.append($('<div style="display: flex; justify-content: space-evenly; margin-top: 5px;">').append($downloadButton).append($openButton));}$renderedContent.append($content);@@ -230,18 +214,16 @@ async function renderMermaid(note: FNote, $renderedContent: JQuery<HTMLElement>)const blob = await note.getBlob();const content = blob?.content || "";- $renderedContent- .css("display", "flex")- .css("justify-content", "space-around");+ $renderedContent.css("display", "flex").css("justify-content", "space-around");const documentStyle = window.getComputedStyle(document.documentElement);- const mermaidTheme = documentStyle.getPropertyValue('--mermaid-theme');+ const mermaidTheme = documentStyle.getPropertyValue("--mermaid-theme");- mermaid.mermaidAPI.initialize({startOnLoad: false, theme: mermaidTheme.trim(), securityLevel: 'antiscript'});+ mermaid.mermaidAPI.initialize({ startOnLoad: false, theme: mermaidTheme.trim(), securityLevel: "antiscript" });try {await loadElkIfNeeded(content);- const {svg} = await mermaid.mermaidAPI.render("in-mermaid-graph-" + idCounter++, content);+ const { svg } = await mermaid.mermaidAPI.render("in-mermaid-graph-" + idCounter++, content);$renderedContent.append($(svg));} catch (e) {@@ -270,10 +252,12 @@ async function renderChildrenList($renderedContent: JQuery<HTMLElement>, note: Fconst childNotes = await froca.getNotes(childNoteIds);for (const childNote of childNotes) {- $renderedContent.append(await linkService.createLink(`${note.noteId}/${childNote.noteId}`, {- showTooltip: false,- showNoteIcon: true- }));+ $renderedContent.append(+ await linkService.createLink(`${note.noteId}/${childNote.noteId}`, {+ showTooltip: false,+ showNoteIcon: true+ })+ );$renderedContent.append("<br>");}@@ -287,24 +271,23 @@ function getRenderingType(entity: FNote | FAttachment) {type = entity.role;}- const mime = ("mime" in entity && entity.mime);+ const mime = "mime" in entity && entity.mime;- if (type === 'file' && mime === 'application/pdf') {- type = 'pdf';- } else if (type === "file" && mime && CODE_MIME_TYPES.has(mime) ) {+ if (type === "file" && mime === "application/pdf") {+ type = "pdf";+ } else if (type === "file" && mime && CODE_MIME_TYPES.has(mime)) {type = "code";- } else if (type === 'file' && mime && mime.startsWith('audio/')) {- type = 'audio';- } else if (type === 'file' && mime && mime.startsWith('video/')) {- type = 'video';+ } else if (type === "file" && mime && mime.startsWith("audio/")) {+ type = "audio";+ } else if (type === "file" && mime && mime.startsWith("video/")) {+ type = "video";}if (entity.isProtected) {if (protectedSessionHolder.isProtectedSessionAvailable()) {protectedSessionHolder.touchProtectedSession();- }- else {- type = 'protectedSession';+ } else {+ type = "protectedSession";}}diff --git a/src/public/app/services/date_notes.ts b/src/public/app/services/date_notes.tsindex bab4deb05e..0d604cfa83 100644--- a/src/public/app/services/date_notes.ts+++ b/src/public/app/services/date_notes.ts@@ -47,7 +47,7 @@ async function getYearNote(year: string) {}async function createSqlConsole() {- const note = await server.post<FNoteRow>('special-notes/sql-console');+ const note = await server.post<FNoteRow>("special-notes/sql-console");await ws.waitForMaxKnownEntityChangeId();@@ -55,7 +55,7 @@ async function createSqlConsole() {}async function createSearchNote(opts = {}) {- const note = await server.post<FNoteRow>('special-notes/search-note', opts);+ const note = await server.post<FNoteRow>("special-notes/search-note", opts);await ws.waitForMaxKnownEntityChangeId();@@ -71,4 +71,4 @@ export default {getYearNote,createSqlConsole,createSearchNote-}+};diff --git a/src/public/app/services/debounce.ts b/src/public/app/services/debounce.tsindex 4f9972a7ba..3ccfcd6e5a 100644--- a/src/public/app/services/debounce.ts+++ b/src/public/app/services/debounce.ts@@ -48,14 +48,14 @@ function debounce<T>(func: (...args: unknown[]) => T, waitMs: number, immediate:return result;};- debounced.clear = function() {+ debounced.clear = function () {if (timeout) {clearTimeout(timeout);timeout = null;}};- debounced.flush = function() {+ debounced.flush = function () {if (timeout) {result = func.apply(context, args || []);context = args = null;diff --git a/src/public/app/services/dialog.ts b/src/public/app/services/dialog.tsindex 18db1df409..c83edde19c 100644--- a/src/public/app/services/dialog.ts+++ b/src/public/app/services/dialog.ts@@ -3,26 +3,24 @@ import { ConfirmDialogOptions, ConfirmWithMessageOptions } from "../widgets/dialimport { PromptDialogOptions } from "../widgets/dialogs/prompt.js";async function info(message: string) {- return new Promise(res =>- appContext.triggerCommand("showInfoDialog", {message, callback: res}));+ return new Promise((res) => appContext.triggerCommand("showInfoDialog", { message, callback: res }));}async function confirm(message: string) {- return new Promise(res =>+ return new Promise((res) =>appContext.triggerCommand("showConfirmDialog", <ConfirmWithMessageOptions>{message,callback: (x: false | ConfirmDialogOptions) => res(x && x.confirmed)- }));+ })+ );}async function confirmDeleteNoteBoxWithNote(title: string) {- return new Promise(res =>- appContext.triggerCommand("showConfirmDeleteNoteBoxWithNoteDialog", {title, callback: res}));+ return new Promise((res) => appContext.triggerCommand("showConfirmDeleteNoteBoxWithNoteDialog", { title, callback: res }));}async function prompt(props: PromptDialogOptions) {- return new Promise(res =>- appContext.triggerCommand("showPromptDialog", {...props, callback: res}));+ return new Promise((res) => appContext.triggerCommand("showPromptDialog", { ...props, callback: res }));}export default {diff --git a/src/public/app/services/file_watcher.ts b/src/public/app/services/file_watcher.tsindex 0f9ec3bb53..cda3c2852c 100644--- a/src/public/app/services/file_watcher.ts+++ b/src/public/app/services/file_watcher.ts@@ -16,7 +16,7 @@ const fileModificationStatus: Record<string, Record<string, Message>> = {};function checkType(type: string) {- if (type !== 'notes' && type !== 'attachments') {+ if (type !== "notes" && type !== "attachments") {throw new Error(`Unrecognized type '${type}', should be 'notes' or 'attachments'`);}}@@ -40,7 +40,7 @@ function ignoreModification(entityType: string, entityId: string) {}ws.subscribeToMessages(async (message: Message) => {- if (message.type !== 'openedFileUpdated') {+ if (message.type !== "openedFileUpdated") {return;}@@ -48,7 +48,7 @@ ws.subscribeToMessages(async (message: Message) => {fileModificationStatus[message.entityType][message.entityId] = message;- appContext.triggerEvent('openedFileUpdated', {+ appContext.triggerEvent("openedFileUpdated", {entityType: message.entityType,entityId: message.entityId,lastModifiedMs: message.lastModifiedMs,@@ -60,4 +60,4 @@ export default {getFileModificationStatus,fileModificationUploaded,ignoreModification-}+};diff --git a/src/public/app/services/froca-interface.ts b/src/public/app/services/froca-interface.tsindex 01dd83bc7d..c678e220b7 100644--- a/src/public/app/services/froca-interface.ts+++ b/src/public/app/services/froca-interface.ts@@ -21,4 +21,4 @@ export interface Froca {getBranches(branchIds: string[], silentNotFoundError?: boolean): FBranch[];getAttachmentsForNote(noteId: string): Promise<FAttachment[]>;-}\ No newline at end of file+}diff --git a/src/public/app/services/froca.ts b/src/public/app/services/froca.tsindex f84dc37ea7..265cefda89 100644--- a/src/public/app/services/froca.ts+++ b/src/public/app/services/froca.ts@@ -7,7 +7,6 @@ import FBlob, { FBlobRow } from "../entities/fblob.js";import FAttachment, { FAttachmentRow } from "../entities/fattachment.js";import { Froca } from "./froca-interface.js";-interface SubtreeResponse {notes: FNoteRow[];branches: FBranchRow[];@@ -44,7 +43,7 @@ class FrocaImpl implements Froca {}async loadInitialTree() {- const resp = await server.get<SubtreeResponse>('tree');+ const resp = await server.get<SubtreeResponse>("tree");// clear the cache only directly before adding new content which is important for e.g., switching to protected session@@ -73,7 +72,7 @@ class FrocaImpl implements Froca {const noteIdsToSort = new Set<string>();for (const noteRow of noteRows) {- const {noteId} = noteRow;+ const { noteId } = noteRow;let note = this.notes[noteId];@@ -81,12 +80,12 @@ class FrocaImpl implements Froca {note.update(noteRow);// search note doesn't have child branches in the database and all the children are virtual branches- if (note.type !== 'search') {+ if (note.type !== "search") {for (const childNoteId of note.children) {const childNote = this.notes[childNoteId];if (childNote) {- childNote.parents = childNote.parents.filter(p => p !== noteId);+ childNote.parents = childNote.parents.filter((p) => p !== noteId);delete this.branches[childNote.parentToBranch[noteId]];delete childNote.parentToBranch[noteId];@@ -99,7 +98,7 @@ class FrocaImpl implements Froca {// we want to remove all "real" branches (represented in the database) since those will be created// from branches argument but want to preserve all virtual ones from saved search- note.parents = note.parents.filter(parentNoteId => {+ note.parents = note.parents.filter((parentNoteId) => {const parentNote = this.notes[parentNoteId];const branch = this.branches[parentNote.childToBranch[noteId]];@@ -111,15 +110,14 @@ class FrocaImpl implements Froca {return true;}- parentNote.children = parentNote.children.filter(p => p !== noteId);+ parentNote.children = parentNote.children.filter((p) => p !== noteId);delete this.branches[parentNote.childToBranch[noteId]];delete parentNote.childToBranch[noteId];return false;});- }- else {+ } else {this.notes[noteId] = new FNote(this, noteRow);}}@@ -145,7 +143,7 @@ class FrocaImpl implements Froca {}for (const attributeRow of attributeRows) {- const {attributeId} = attributeRow;+ const { attributeId } = attributeRow;this.attributes[attributeId] = new FAttribute(this, attributeRow);@@ -155,7 +153,7 @@ class FrocaImpl implements Froca {note.attributes.push(attributeId);}- if (attributeRow.type === 'relation') {+ if (attributeRow.type === "relation") {const targetNote = this.notes[attributeRow.value];if (targetNote) {@@ -180,21 +178,21 @@ class FrocaImpl implements Froca {noteIds = Array.from(new Set(noteIds)); // make noteIds unique- const resp = await server.post<SubtreeResponse>('tree/load', { noteIds });+ const resp = await server.post<SubtreeResponse>("tree/load", { noteIds });this.addResp(resp);- appContext.triggerEvent('notesReloaded', {noteIds});+ appContext.triggerEvent("notesReloaded", { noteIds });}async loadSearchNote(noteId: string) {const note = await this.getNote(noteId);- if (!note || note.type !== 'search') {+ if (!note || note.type !== "search") {return;}- const {searchResultNoteIds, highlightedTokens, error} = await server.get<SearchNoteResponse>(`search-note/${note.noteId}`);+ const { searchResultNoteIds, highlightedTokens, error } = await server.get<SearchNoteResponse>(`search-note/${note.noteId}`);if (!Array.isArray(searchResultNoteIds)) {throw new Error(`Search note '${note.noteId}' failed: ${searchResultNoteIds}`);@@ -208,14 +206,16 @@ class FrocaImpl implements Froca {const branches: FBranchRow[] = [...note.getParentBranches(), ...note.getChildBranches()];- searchResultNoteIds.forEach((resultNoteId, index) => branches.push({- // branchId should be repeatable since sometimes we reload some notes without rerendering the tree- branchId: `virt-${note.noteId}-${resultNoteId}`,- noteId: resultNoteId,- parentNoteId: note.noteId,- notePosition: (index + 1) * 10,- fromSearchNote: true- }));+ searchResultNoteIds.forEach((resultNoteId, index) =>+ branches.push({+ // branchId should be repeatable since sometimes we reload some notes without rerendering the tree+ branchId: `virt-${note.noteId}-${resultNoteId}`,+ noteId: resultNoteId,+ parentNoteId: note.noteId,+ notePosition: (index + 1) * 10,+ fromSearchNote: true+ })+ );// update this note with standard (parent) branches + virtual (children) branchesthis.addResp({@@ -227,37 +227,40 @@ class FrocaImpl implements Froca {froca.notes[note.noteId].searchResultsLoaded = true;froca.notes[note.noteId].highlightedTokens = highlightedTokens;- return {error};+ return { error };}getNotesFromCache(noteIds: string[], silentNotFoundError = false): FNote[] {- return noteIds.map(noteId => {- if (!this.notes[noteId] && !silentNotFoundError) {- console.trace(`Can't find note '${noteId}'`);-- return null;- }- else {- return this.notes[noteId];- }- }).filter(note => !!note) as FNote[];+ return noteIds+ .map((noteId) => {+ if (!this.notes[noteId] && !silentNotFoundError) {+ console.trace(`Can't find note '${noteId}'`);++ return null;+ } else {+ return this.notes[noteId];+ }+ })+ .filter((note) => !!note) as FNote[];}async getNotes(noteIds: string[] | JQuery<string>, silentNotFoundError = false): Promise<FNote[]> {noteIds = Array.from(new Set(noteIds)); // make unique- const missingNoteIds = noteIds.filter(noteId => !this.notes[noteId]);+ const missingNoteIds = noteIds.filter((noteId) => !this.notes[noteId]);await this.reloadNotes(missingNoteIds);- return noteIds.map(noteId => {- if (!this.notes[noteId] && !silentNotFoundError) {- console.trace(`Can't find note '${noteId}'`);+ return noteIds+ .map((noteId) => {+ if (!this.notes[noteId] && !silentNotFoundError) {+ console.trace(`Can't find note '${noteId}'`);- return null;- } else {- return this.notes[noteId];- }- }).filter(note => !!note) as FNote[];+ return null;+ } else {+ return this.notes[noteId];+ }+ })+ .filter((note) => !!note) as FNote[];}async noteExists(noteId: string): Promise<boolean> {@@ -267,11 +270,10 @@ class FrocaImpl implements Froca {}async getNote(noteId: string, silentNotFoundError = false): Promise<FNote | null> {- if (noteId === 'none') {+ if (noteId === "none") {console.trace(`No 'none' note.`);return null;- }- else if (!noteId) {+ } else if (!noteId) {console.trace(`Falsy noteId '${noteId}', returning null.`);return null;}@@ -288,9 +290,7 @@ class FrocaImpl implements Froca {}getBranches(branchIds: string[], silentNotFoundError = false): FBranch[] {- return branchIds- .map(branchId => this.getBranch(branchId, silentNotFoundError))- .filter(b => !!b) as FBranch[];+ return branchIds.map((branchId) => this.getBranch(branchId, silentNotFoundError)).filter((b) => !!b) as FBranch[];}getBranch(branchId: string, silentNotFoundError = false) {@@ -298,15 +298,14 @@ class FrocaImpl implements Froca {if (!silentNotFoundError) {logError(`Not existing branch '${branchId}'`);}- }- else {+ } else {return this.branches[branchId];}}async getBranchId(parentNoteId: string, childNoteId: string) {- if (childNoteId === 'root') {- return 'none_root';+ if (childNoteId === "root") {+ return "none_root";}const child = await this.getNote(childNoteId);@@ -354,7 +353,7 @@ class FrocaImpl implements Froca {}processAttachmentRows(attachmentRows: FAttachmentRow[]): FAttachment[] {- return attachmentRows.map(attachmentRow => {+ return attachmentRows.map((attachmentRow) => {let attachment;if (attachmentRow.attachmentId in this.attachments) {@@ -376,16 +375,15 @@ class FrocaImpl implements Froca {const key = `${entityType}-${entityId}`;if (!this.blobPromises[key]) {- this.blobPromises[key] = server.get<FBlobRow>(`${entityType}/${entityId}/blob`)- .then(row => new FBlob(row))- .catch(e => console.error(`Cannot get blob for ${entityType} '${entityId}'`, e));+ this.blobPromises[key] = server+ .get<FBlobRow>(`${entityType}/${entityId}/blob`)+ .then((row) => new FBlob(row))+ .catch((e) => console.error(`Cannot get blob for ${entityType} '${entityId}'`, e));// we don't want to keep large payloads forever in memory, so we clean that up quite quickly// this cache is more meant to share the data between different components within one business transaction (e.g. loading of the note into the tab context and all the components)// if the blob is updated within the cache lifetime, it should be invalidated by froca_updater- this.blobPromises[key]?.then(- () => setTimeout(() => this.blobPromises[key] = null, 1000)- );+ this.blobPromises[key]?.then(() => setTimeout(() => (this.blobPromises[key] = null), 1000));}return await this.blobPromises[key];diff --git a/src/public/app/services/froca_updater.ts b/src/public/app/services/froca_updater.tsindex d936a5495e..6842133362 100644--- a/src/public/app/services/froca_updater.ts+++ b/src/public/app/services/froca_updater.ts@@ -7,42 +7,40 @@ import FBranch, { FBranchRow } from "../entities/fbranch.js";import FAttribute, { FAttributeRow } from "../entities/fattribute.js";import FAttachment, { FAttachmentRow } from "../entities/fattachment.js";import FNote, { FNoteRow } from "../entities/fnote.js";-import type { EntityChange } from "../server_types.js"+import type { EntityChange } from "../server_types.js";async function processEntityChanges(entityChanges: EntityChange[]) {const loadResults = new LoadResults(entityChanges);for (const ec of entityChanges) {try {- if (ec.entityName === 'notes') {+ if (ec.entityName === "notes") {processNoteChange(loadResults, ec);- } else if (ec.entityName === 'branches') {+ } else if (ec.entityName === "branches") {await processBranchChange(loadResults, ec);- } else if (ec.entityName === 'attributes') {+ } else if (ec.entityName === "attributes") {processAttributeChange(loadResults, ec);- } else if (ec.entityName === 'note_reordering') {+ } else if (ec.entityName === "note_reordering") {processNoteReordering(loadResults, ec);- } else if (ec.entityName === 'revisions') {+ } else if (ec.entityName === "revisions") {loadResults.addRevision(ec.entityId, ec.noteId, ec.componentId);- } else if (ec.entityName === 'options') {+ } else if (ec.entityName === "options") {const attributeEntity = ec.entity as FAttributeRow;- if (attributeEntity.name === 'openNoteContexts') {+ if (attributeEntity.name === "openNoteContexts") {continue; // only noise}options.set(attributeEntity.name, attributeEntity.value);loadResults.addOption(attributeEntity.name);- } else if (ec.entityName === 'attachments') {+ } else if (ec.entityName === "attachments") {processAttachment(loadResults, ec);- } else if (ec.entityName === 'blobs' || ec.entityName === 'etapi_tokens') {+ } else if (ec.entityName === "blobs" || ec.entityName === "etapi_tokens") {// NOOP- }- else {+ } else {throw new Error(`Unknown entityName '${ec.entityName}'`);}- }- catch (e: any) {+ } catch (e: any) {throw new Error(`Can't process entity ${JSON.stringify(ec)} with error ${e.message} ${e.stack}`);}}@@ -54,19 +52,17 @@ async function processEntityChanges(entityChanges: EntityChange[]) {// mean we need to load the target of the relation (and then perhaps transitively the whole note path of this target).const missingNoteIds = [];- for (const {entityName, entity} of entityChanges) {- if (!entity) { // if erased+ for (const { entityName, entity } of entityChanges) {+ if (!entity) {+ // if erasedcontinue;}- if (entityName === 'branches' && !((entity as FBranchRow).parentNoteId in froca.notes)) {+ if (entityName === "branches" && !((entity as FBranchRow).parentNoteId in froca.notes)) {missingNoteIds.push((entity as FBranchRow).parentNoteId);- }- else if (entityName === 'attributes') {+ } else if (entityName === "attributes") {let attributeEntity = entity as FAttributeRow;- if (attributeEntity.type === 'relation'- && (attributeEntity.name === 'template' || attributeEntity.name === 'inherit')- && !(attributeEntity.value in froca.notes)) {+ if (attributeEntity.type === "relation" && (attributeEntity.name === "template" || attributeEntity.name === "inherit") && !(attributeEntity.value in froca.notes)) {missingNoteIds.push(attributeEntity.value);}}@@ -84,7 +80,7 @@ async function processEntityChanges(entityChanges: EntityChange[]) {// TODO: Remove after porting the file// @ts-ignoreconst appContext = (await import("../components/app_context.js")).default as any;- await appContext.triggerEvent('entitiesReloaded', {loadResults});+ await appContext.triggerEvent("entitiesReloaded", { loadResults });}}@@ -106,8 +102,7 @@ function processNoteChange(loadResults: LoadResults, ec: EntityChange) {if (ec.isErased || ec.entity?.isDeleted) {delete froca.notes[ec.entityId];- }- else {+ } else {if (note.blobId !== (ec.entity as FNoteRow).blobId) {for (const key of Object.keys(froca.blobPromises)) {if (key.includes(note.noteId)) {@@ -138,12 +133,12 @@ async function processBranchChange(loadResults: LoadResults, ec: EntityChange) {const parentNote = froca.notes[branch.parentNoteId];if (childNote) {- childNote.parents = childNote.parents.filter(parentNoteId => parentNoteId !== branch.parentNoteId);+ childNote.parents = childNote.parents.filter((parentNoteId) => parentNoteId !== branch.parentNoteId);delete childNote.parentToBranch[branch.parentNoteId];}if (parentNote) {- parentNote.children = parentNote.children.filter(childNoteId => childNoteId !== branch.noteId);+ parentNote.children = parentNote.children.filter((childNoteId) => childNoteId !== branch.noteId);delete parentNote.childToBranch[branch.noteId];}@@ -175,8 +170,7 @@ async function processBranchChange(loadResults: LoadResults, ec: EntityChange) {if (branch) {branch.update(ec.entity as FBranch);- }- else if (childNote || parentNote) {+ } else if (childNote || parentNote) {froca.branches[ec.entityId] = branch = new FBranch(froca, branchEntity);}@@ -226,14 +220,14 @@ function processAttributeChange(loadResults: LoadResults, ec: EntityChange) {if (ec.isErased || ec.entity?.isDeleted) {if (attribute) {const sourceNote = froca.notes[attribute.noteId];- const targetNote = attribute.type === 'relation' && froca.notes[attribute.value];+ const targetNote = attribute.type === "relation" && froca.notes[attribute.value];if (sourceNote) {- sourceNote.attributes = sourceNote.attributes.filter(attributeId => attributeId !== attribute.attributeId);+ sourceNote.attributes = sourceNote.attributes.filter((attributeId) => attributeId !== attribute.attributeId);}if (targetNote) {- targetNote.targetRelations = targetNote.targetRelations.filter(attributeId => attributeId !== attribute.attributeId);+ targetNote.targetRelations = targetNote.targetRelations.filter((attributeId) => attributeId !== attribute.attributeId);}if (ec.componentId) {@@ -252,7 +246,7 @@ function processAttributeChange(loadResults: LoadResults, ec: EntityChange) {const attributeEntity = ec.entity as FAttributeRow;const sourceNote = froca.notes[attributeEntity.noteId];- const targetNote = attributeEntity.type === 'relation' && froca.notes[attributeEntity.value];+ const targetNote = attributeEntity.type === "relation" && froca.notes[attributeEntity.value];if (attribute) {attribute.update(ec.entity as FAttributeRow);@@ -285,7 +279,7 @@ function processAttachment(loadResults: LoadResults, ec: EntityChange) {const note = attachment.getNote();if (note && note.attachments) {- note.attachments = note.attachments.filter(att => att.attachmentId !== attachment.attachmentId);+ note.attachments = note.attachments.filter((att) => att.attachmentId !== attachment.attachmentId);}loadResults.addAttachmentRow(attachmentEntity);@@ -312,4 +306,4 @@ function processAttachment(loadResults: LoadResults, ec: EntityChange) {export default {processEntityChanges-}+};diff --git a/src/public/app/services/frontend_script_api.ts b/src/public/app/services/frontend_script_api.tsindex 1cbab4a0fa..acdff7444a 100644--- a/src/public/app/services/frontend_script_api.ts+++ b/src/public/app/services/frontend_script_api.ts@@ -1,13 +1,13 @@-import server from './server.js';-import utils from './utils.js';-import toastService from './toast.js';-import linkService from './link.js';-import froca from './froca.js';-import noteTooltipService from './note_tooltip.js';-import protectedSessionService from './protected_session.js';-import dateNotesService from './date_notes.js';-import searchService from './search.js';-import RightPanelWidget from '../widgets/right_panel_widget.js';+import server from "./server.js";+import utils from "./utils.js";+import toastService from "./toast.js";+import linkService from "./link.js";+import froca from "./froca.js";+import noteTooltipService from "./note_tooltip.js";+import protectedSessionService from "./protected_session.js";+import dateNotesService from "./date_notes.js";+import searchService from "./search.js";+import RightPanelWidget from "../widgets/right_panel_widget.js";import ws from "./ws.js";import appContext from "../components/app_context.js";import NoteContextAwareWidget from "../widgets/note_context_aware_widget.js";@@ -15,12 +15,11 @@ import BasicWidget from "../widgets/basic_widget.js";import SpacedUpdate from "./spaced_update.js";import shortcutService from "./shortcuts.js";import dialogService from "./dialog.js";-import FNote from '../entities/fnote.js';-import { t } from './i18n.js';-import NoteContext from '../components/note_context.js';-import NoteDetailWidget from '../widgets/note_detail.js';-import Component from '../components/component.js';-+import FNote from "../entities/fnote.js";+import { t } from "./i18n.js";+import NoteContext from "../components/note_context.js";+import NoteDetailWidget from "../widgets/note_detail.js";+import Component from "../components/component.js";/*** A whole number@@ -39,7 +38,7 @@ interface AddToToolbarOpts {action: () => void;/** id of the button, used to identify the old instances of this button to be replaced* ID is optional because of BC, but not specifying it is deprecated. ID can be alphanumeric only. */- id: string;+ id: string;/** name of the boxicon to be used (e.g. "time" for "bx-time" icon) */icon: string;/** keyboard shortcut for the button, e.g. "alt+t" */@@ -105,7 +104,7 @@ interface Api {*/activateNewNote(notePath: string): Promise<void>;- /**+ /*** Open a note in a new tab.** @method@@ -131,7 +130,7 @@ interface Api {*/addButtonToToolbar(opts: AddToToolbarOpts): void;- /**+ /*** @private*/__runOnBackendInner(func: unknown, params: unknown[], transactional: boolean): unknown;@@ -248,7 +247,7 @@ interface Api {*/triggerEvent: typeof appContext.triggerEvent;- /**+ /*** Create a note link (jQuery object) for given note.** @param {string} notePath (or noteId)@@ -388,7 +387,7 @@ interface Api {*/setHoistedNoteId(noteId: string): void;- /**+ /*** @param keyboardShortcut - e.g. "ctrl+shift+a"* @param [namespace] specify namespace of the handler for the cases where call for bind may be repeated.* If a handler with this ID exists, it's replaced by the new handler.@@ -447,57 +446,55 @@ interface Api {* available in the JS frontend notes. You can use e.g. <code>api.showMessage(api.startNote.title);</code></p>*/function FrontendScriptApi(this: Api, startNote: FNote, currentNote: FNote, originEntity: Entity | null = null, $container: JQuery<HTMLElement> | null = null) {-this.$container = $container;this.startNote = startNote;- this.currentNote = currentNote;+ this.currentNote = currentNote;this.originEntity = originEntity;this.dayjs = dayjs;this.RightPanelWidget = RightPanelWidget;this.NoteContextAwareWidget = NoteContextAwareWidget;this.BasicWidget = BasicWidget;-- this.activateNote = async notePath => {++ this.activateNote = async (notePath) => {await appContext.tabManager.getActiveContext().setNote(notePath);};- this.activateNewNote = async notePath => {+ this.activateNewNote = async (notePath) => {await ws.waitForMaxKnownEntityChangeId();await appContext.tabManager.getActiveContext().setNote(notePath);- await appContext.triggerEvent('focusAndSelectTitle');+ await appContext.triggerEvent("focusAndSelectTitle");};-this.openTabWithNote = async (notePath, activate) => {await ws.waitForMaxKnownEntityChangeId();await appContext.tabManager.openTabWithNoteWithHoisting(notePath, { activate });if (activate) {- await appContext.triggerEvent('focusAndSelectTitle');+ await appContext.triggerEvent("focusAndSelectTitle");}};-+this.openSplitWithNote = async (notePath, activate) => {await ws.waitForMaxKnownEntityChangeId();const subContexts = appContext.tabManager.getActiveContext().getSubContexts();- const {ntxId} = subContexts[subContexts.length - 1];+ const { ntxId } = subContexts[subContexts.length - 1];- await appContext.triggerCommand("openNewNoteSplit", {ntxId, notePath});+ await appContext.triggerCommand("openNewNoteSplit", { ntxId, notePath });if (activate) {- await appContext.triggerEvent('focusAndSelectTitle');+ await appContext.triggerEvent("focusAndSelectTitle");}};-- this.addButtonToToolbar = async opts => {++ this.addButtonToToolbar = async (opts) => {console.warn("api.addButtonToToolbar() has been deprecated since v0.58 and may be removed in the future. Use Menu -> Configure Launchbar to create/update launchers instead.");- const {action, ...reqBody} = opts;-- await server.put('special-notes/api-script-launcher', {+ const { action, ...reqBody } = opts;++ await server.put("special-notes/api-script-launcher", {action: action.toString(),...reqBody});@@ -508,31 +505,33 @@ function FrontendScriptApi(this: Api, startNote: FNote, currentNote: FNote, origreturn params;}- return params.map(p => {+ return params.map((p) => {if (typeof p === "function") {return `!@#Function: ${p.toString()}`;- }- else {+ } else {return p;}});}-this.__runOnBackendInner = async (func, params, transactional) => {if (typeof func === "function") {func = func.toString();}- const ret = await server.post<ExecResult>('script/exec', {- script: func,- params: prepareParams(params),- startNoteId: startNote.noteId,- currentNoteId: currentNote.noteId,- originEntityName: "notes", // currently there's no other entity on the frontend which can trigger event- originEntityId: originEntity ? originEntity.noteId : null,- transactional- }, "script");+ const ret = await server.post<ExecResult>(+ "script/exec",+ {+ script: func,+ params: prepareParams(params),+ startNoteId: startNote.noteId,+ currentNoteId: currentNote.noteId,+ originEntityName: "notes", // currently there's no other entity on the frontend which can trigger event+ originEntityId: originEntity ? originEntity.noteId : null,+ transactional+ },+ "script"+ );if (ret.success) {await ws.waitForMaxKnownEntityChangeId();@@ -541,7 +540,7 @@ function FrontendScriptApi(this: Api, startNote: FNote, currentNote: FNote, orig} else {throw new Error(`server error: ${ret.error}`);}- }+ };this.runOnBackend = async (func, params = []) => {if (func?.constructor.name === "AsyncFunction" || (typeof func === "string" && func?.startsWith?.("async "))) {@@ -551,7 +550,6 @@ function FrontendScriptApi(this: Api, startNote: FNote, currentNote: FNote, origreturn await this.__runOnBackendInner(func, params, true);};-this.runAsyncOnBackendWithManualTransactionHandling = async (func, params = []) => {if (func?.constructor.name === "Function" || (typeof func === "string" && func?.startsWith?.("function"))) {toastService.showError(t("frontend_script_api.sync_warning"));@@ -559,72 +557,67 @@ function FrontendScriptApi(this: Api, startNote: FNote, currentNote: FNote, origreturn await this.__runOnBackendInner(func, params, false);};-- this.searchForNotes = async searchString => {++ this.searchForNotes = async (searchString) => {return await searchService.searchForNotes(searchString);};-- this.searchForNote = async searchString => {+ this.searchForNote = async (searchString) => {const notes = await this.searchForNotes(searchString);return notes.length > 0 ? notes[0] : null;};-- this.getNote = async noteId => await froca.getNote(noteId);- this.getNotes = async (noteIds, silentNotFoundError = false) => await froca.getNotes(noteIds, silentNotFoundError);- this.reloadNotes = async noteIds => await froca.reloadNotes(noteIds);- this.getInstanceName = () => window.glob.instanceName;+ this.getNote = async (noteId) => await froca.getNote(noteId);+ this.getNotes = async (noteIds, silentNotFoundError = false) => await froca.getNotes(noteIds, silentNotFoundError);+ this.reloadNotes = async (noteIds) => await froca.reloadNotes(noteIds);+ this.getInstanceName = () => window.glob.instanceName;this.formatDateISO = utils.formatDateISO;this.parseDate = utils.parseDate;this.showMessage = toastService.showMessage;this.showError = toastService.showError;- this.showInfoDialog = dialogService.info;+ this.showInfoDialog = dialogService.info;this.showConfirmDialog = dialogService.confirm;-this.showPromptDialog = dialogService.prompt;-- this.triggerCommand = (name, data) => appContext.triggerCommand(name, data);++ this.triggerCommand = (name, data) => appContext.triggerCommand(name, data);this.triggerEvent = (name, data) => appContext.triggerEvent(name, data);-this.createLink = linkService.createLink;this.createNoteLink = linkService.createLink;-- this.addTextToActiveContextEditor = text => appContext.triggerCommand('addTextToActiveEditor', {text});++ this.addTextToActiveContextEditor = (text) => appContext.triggerCommand("addTextToActiveEditor", { text });this.getActiveContextNote = () => appContext.tabManager.getActiveContextNote();this.getActiveContext = () => appContext.tabManager.getActiveContext();this.getActiveMainContext = () => appContext.tabManager.getActiveMainContext();-- this.getNoteContexts = () => appContext.tabManager.getNoteContexts();++ this.getNoteContexts = () => appContext.tabManager.getNoteContexts();this.getMainNoteContexts = () => appContext.tabManager.getMainNoteContexts();-- this.getActiveContextTextEditor = () => appContext.tabManager.getActiveContext()?.getTextEditor();+ this.getActiveContextTextEditor = () => appContext.tabManager.getActiveContext()?.getTextEditor();this.getActiveContextCodeEditor = () => appContext.tabManager.getActiveContext()?.getCodeEditor();-- this.getActiveNoteDetailWidget = () => new Promise(resolve => appContext.triggerCommand('executeInActiveNoteDetailWidget', {callback: resolve}));++ this.getActiveNoteDetailWidget = () => new Promise((resolve) => appContext.triggerCommand("executeInActiveNoteDetailWidget", { callback: resolve }));this.getActiveContextNotePath = () => appContext.tabManager.getActiveContextNotePath();-- this.getComponentByEl = el => appContext.getComponentByEl(el);-++ this.getComponentByEl = (el) => appContext.getComponentByEl(el);+this.setupElementTooltip = noteTooltipService.setupElementTooltip;-+this.protectNote = async (noteId, protect) => {await protectedSessionService.protectNote(noteId, protect, false);};-+this.protectSubTree = async (noteId, protect) => {await protectedSessionService.protectNote(noteId, protect, true);};-- this.getTodayNote = dateNotesService.getTodayNote;++ this.getTodayNote = dateNotesService.getTodayNote;this.getDayNote = dateNotesService.getDayNote;- this.getWeekNote = dateNotesService.getWeekNote;+ this.getWeekNote = dateNotesService.getWeekNote;this.getMonthNote = dateNotesService.getMonthNote;this.getYearNote = dateNotesService.getYearNote;@@ -637,32 +630,33 @@ function FrontendScriptApi(this: Api, startNote: FNote, currentNote: FNote, orig};this.bindGlobalShortcut = shortcutService.bindGlobalShortcut;-+this.waitUntilSynced = ws.waitForMaxKnownEntityChangeId;-- this.refreshIncludedNote = includedNoteId => appContext.triggerEvent('refreshIncludedNote', {noteId: includedNoteId});-+ this.refreshIncludedNote = (includedNoteId) => appContext.triggerEvent("refreshIncludedNote", { noteId: includedNoteId });+this.randomString = utils.randomString;this.formatSize = utils.formatSize;this.formatNoteSize = utils.formatSize;this.logMessages = {};- this.logSpacedUpdates = {};- this.log = message => {- const {noteId} = this.startNote;+ this.logSpacedUpdates = {};+ this.log = (message) => {+ const { noteId } = this.startNote;message = `${utils.now()}: ${message}`;console.log(`Script ${noteId}: ${message}`);this.logMessages[noteId] = this.logMessages[noteId] || [];- this.logSpacedUpdates[noteId] = this.logSpacedUpdates[noteId] || new SpacedUpdate(() => {- const messages = this.logMessages[noteId];- this.logMessages[noteId] = [];+ this.logSpacedUpdates[noteId] =+ this.logSpacedUpdates[noteId] ||+ new SpacedUpdate(() => {+ const messages = this.logMessages[noteId];+ this.logMessages[noteId] = [];- appContext.triggerEvent("apiLogMessages", {noteId, messages});- }, 100);+ appContext.triggerEvent("apiLogMessages", { noteId, messages });+ }, 100);this.logMessages[noteId].push(message);this.logSpacedUpdates[noteId].scheduleUpdate();@@ -670,5 +664,5 @@ function FrontendScriptApi(this: Api, startNote: FNote, currentNote: FNote, orig}export default FrontendScriptApi as any as {- new (startNote: FNote, currentNote: FNote, originEntity: Entity | null, $container: JQuery<HTMLElement> | null): Api+ new (startNote: FNote, currentNote: FNote, originEntity: Entity | null, $container: JQuery<HTMLElement> | null): Api;};diff --git a/src/public/app/services/glob.ts b/src/public/app/services/glob.tsindex e5f9e744d4..69c33e4c75 100644--- a/src/public/app/services/glob.ts+++ b/src/public/app/services/glob.ts@@ -10,10 +10,10 @@ function setupGlobs() {window.glob.isDesktop = utils.isDesktop;window.glob.isMobile = utils.isMobile;- window.glob.getComponentByEl = el => appContext.getComponentByEl(el);+ window.glob.getComponentByEl = (el) => appContext.getComponentByEl(el);window.glob.getHeaders = server.getHeaders;- window.glob.getReferenceLinkTitle = href => linkService.getReferenceLinkTitle(href);- window.glob.getReferenceLinkTitleSync = href => linkService.getReferenceLinkTitleSync(href);+ window.glob.getReferenceLinkTitle = (href) => linkService.getReferenceLinkTitle(href);+ window.glob.getReferenceLinkTitleSync = (href) => linkService.getReferenceLinkTitleSync(href);// required for ESLint plugin and CKEditorwindow.glob.getActiveContextNote = () => appContext.tabManager.getActiveContextNote();@@ -32,16 +32,9 @@ function setupGlobs() {let message = "Uncaught error: ";if (string.includes("script error")) {- message += 'No details available';+ message += "No details available";} else {- message += [- `Message: ${msg}`,- `URL: ${url}`,- `Line: ${lineNo}`,- `Column: ${columnNo}`,- `Error object: ${JSON.stringify(error)}`,- `Stack: ${error && error.stack}`- ].join(', ');+ message += [`Message: ${msg}`, `URL: ${url}`, `Line: ${lineNo}`, `Column: ${columnNo}`, `Error object: ${JSON.stringify(error)}`, `Stack: ${error && error.stack}`].join(", ");}ws.logError(message);@@ -55,7 +48,7 @@ function setupGlobs() {let message = "Uncaught error: ";if (string?.includes("script error")) {- message += 'No details available';+ message += "No details available";} else {message += [`Message: ${e.reason.message}`,@@ -63,7 +56,7 @@ function setupGlobs() {`Column: ${e.reason.columnNumber}`,`Error object: ${JSON.stringify(e.reason)}`,`Stack: ${e.reason && e.reason.stack}`- ].join(', ');+ ].join(", ");}ws.logError(message);@@ -78,7 +71,7 @@ function setupGlobs() {utils.initHelpButtons($(window));$("body").on("click", "a.external", function () {- window.open($(this).attr("href"), '_blank');+ window.open($(this).attr("href"), "_blank");return false;});@@ -86,4 +79,4 @@ function setupGlobs() {export default {setupGlobs-}+};diff --git a/src/public/app/services/hoisted_note.ts b/src/public/app/services/hoisted_note.tsindex 86097da785..d05a2c3c8e 100644--- a/src/public/app/services/hoisted_note.ts+++ b/src/public/app/services/hoisted_note.ts@@ -8,7 +8,7 @@ import { t } from "./i18n.js";function getHoistedNoteId() {const activeNoteContext = appContext.tabManager.getActiveContext();- return activeNoteContext ? activeNoteContext.hoistedNoteId : 'root';+ return activeNoteContext ? activeNoteContext.hoistedNoteId : "root";}async function unhoist() {@@ -25,14 +25,13 @@ function isTopLevelNode(node: Node) {function isHoistedNode(node: Node) {// even though check for 'root' should not be necessary, we keep it just in case- return node.data.noteId === "root"- || node.data.noteId === getHoistedNoteId();+ return node.data.noteId === "root" || node.data.noteId === getHoistedNoteId();}async function isHoistedInHiddenSubtree() {const hoistedNoteId = getHoistedNoteId();- if (hoistedNoteId === 'root') {+ if (hoistedNoteId === "root") {return false;}@@ -50,7 +49,7 @@ async function checkNoteAccess(notePath: string, noteContext: NoteContext) {const hoistedNoteId = noteContext.hoistedNoteId;- if (!resolvedNotePath.includes(hoistedNoteId) && (!resolvedNotePath.includes('_hidden') || resolvedNotePath.includes('_lbBookmarks'))) {+ if (!resolvedNotePath.includes(hoistedNoteId) && (!resolvedNotePath.includes("_hidden") || resolvedNotePath.includes("_lbBookmarks"))) {const noteId = treeService.getNoteIdFromUrl(resolvedNotePath);if (!noteId) {return false;@@ -58,8 +57,10 @@ async function checkNoteAccess(notePath: string, noteContext: NoteContext) {const requestedNote = await froca.getNote(noteId);const hoistedNote = await froca.getNote(hoistedNoteId);- if ((!hoistedNote?.hasAncestor('_hidden') || resolvedNotePath.includes('_lbBookmarks'))- && !await dialogService.confirm(t("hoisted_note.confirm_unhoisting", { requestedNote: requestedNote?.title, hoistedNote: hoistedNote?.title }))) {+ if (+ (!hoistedNote?.hasAncestor("_hidden") || resolvedNotePath.includes("_lbBookmarks")) &&+ !(await dialogService.confirm(t("hoisted_note.confirm_unhoisting", { requestedNote: requestedNote?.title, hoistedNote: hoistedNote?.title })))+ ) {return false;}@@ -77,4 +78,4 @@ export default {isHoistedNode,checkNoteAccess,isHoistedInHiddenSubtree-}+};diff --git a/src/public/app/services/i18n.ts b/src/public/app/services/i18n.tsindex 3d82c0e1da..48b3be72e9 100644--- a/src/public/app/services/i18n.ts+++ b/src/public/app/services/i18n.ts@@ -6,16 +6,14 @@ await library_loader.requireLibrary(library_loader.I18NEXT);export async function initLocale() {const locale = (options.get("locale") as string) || "en";- await i18next- .use(i18nextHttpBackend)- .init({- lng: locale,- fallbackLng: "en",- backend: {- loadPath: `${window.glob.assetPath}/translations/{{lng}}/{{ns}}.json`- },- returnEmptyString: false- });+ await i18next.use(i18nextHttpBackend).init({+ lng: locale,+ fallbackLng: "en",+ backend: {+ loadPath: `${window.glob.assetPath}/translations/{{lng}}/{{ns}}.json`+ },+ returnEmptyString: false+ });}export const t = i18next.t;diff --git a/src/public/app/services/image.ts b/src/public/app/services/image.tsindex deedc7c0e7..3cf1424d50 100644--- a/src/public/app/services/image.ts+++ b/src/public/app/services/image.ts@@ -3,20 +3,19 @@ import toastService from "./toast.js";function copyImageReferenceToClipboard($imageWrapper: JQuery<HTMLElement>) {try {- $imageWrapper.attr('contenteditable', 'true');+ $imageWrapper.attr("contenteditable", "true");selectImage($imageWrapper.get(0));- const success = document.execCommand('copy');+ const success = document.execCommand("copy");if (success) {toastService.showMessage(t("image.copied-to-clipboard"));} else {toastService.showAndLogError(t("image.cannot-copy"));}- }- finally {+ } finally {window.getSelection()?.removeAllRanges();- $imageWrapper.removeAttr('contenteditable');+ $imageWrapper.removeAttr("contenteditable");}}@@ -24,7 +23,7 @@ function selectImage(element: HTMLElement | undefined) {if (!element) {return;}-+const selection = window.getSelection();const range = document.createRange();range.selectNodeContents(element);diff --git a/src/public/app/services/import.ts b/src/public/app/services/import.tsindex b63fde8de3..77b6d489e6 100644--- a/src/public/app/services/import.ts+++ b/src/public/app/services/import.ts@@ -6,7 +6,7 @@ import appContext from "../components/app_context.js";import { t } from "./i18n.js";export async function uploadFiles(entityType: string, parentNoteId: string, files: string[], options: Record<string, string | Blob>) {- if (!['notes', 'attachments'].includes(entityType)) {+ if (!["notes", "attachments"].includes(entityType)) {throw new Error(`Unrecognized import entity type '${entityType}'.`);}@@ -21,9 +21,9 @@ export async function uploadFiles(entityType: string, parentNoteId: string, filecounter++;const formData = new FormData();- formData.append('upload', file);- formData.append('taskId', taskId);- formData.append('last', counter === files.length ? "true" : "false");+ formData.append("upload", file);+ formData.append("taskId", taskId);+ formData.append("last", counter === files.length ? "true" : "false");for (const key in options) {formData.append(key, options[key]);@@ -33,14 +33,14 @@ export async function uploadFiles(entityType: string, parentNoteId: string, fileurl: `${window.glob.baseApiUrl}notes/${parentNoteId}/${entityType}-import`,headers: await server.getHeaders(),data: formData,- dataType: 'json',- type: 'POST',+ dataType: "json",+ type: "POST",timeout: 60 * 60 * 1000,error: function (xhr) {toastService.showError(t("import.failed", { message: xhr.responseText }));},contentType: false, // NEEDED, DON'T REMOVE THIS- processData: false, // NEEDED, DON'T REMOVE THIS+ processData: false // NEEDED, DON'T REMOVE THIS});}}@@ -54,17 +54,17 @@ function makeToast(id: string, message: string): ToastOptions {};}-ws.subscribeToMessages(async message => {- if (message.taskType !== 'importNotes') {+ws.subscribeToMessages(async (message) => {+ if (message.taskType !== "importNotes") {return;}- if (message.type === 'taskError') {+ if (message.type === "taskError") {toastService.closePersistent(message.taskId);toastService.showError(message.message);- } else if (message.type === 'taskProgressCount') {+ } else if (message.type === "taskProgressCount") {toastService.showPersistent(makeToast(message.taskId, t("import.in-progress", { progress: message.progressCount })));- } else if (message.type === 'taskSucceeded') {+ } else if (message.type === "taskSucceeded") {const toast = makeToast(message.taskId, t("import.successful"));toast.closeAfter = 5000;@@ -76,17 +76,17 @@ ws.subscribeToMessages(async message => {}});-ws.subscribeToMessages(async message => {- if (message.taskType !== 'importAttachments') {+ws.subscribeToMessages(async (message) => {+ if (message.taskType !== "importAttachments") {return;}- if (message.type === 'taskError') {+ if (message.type === "taskError") {toastService.closePersistent(message.taskId);toastService.showError(message.message);- } else if (message.type === 'taskProgressCount') {+ } else if (message.type === "taskProgressCount") {toastService.showPersistent(makeToast(message.taskId, t("import.in-progress", { progress: message.progressCount })));- } else if (message.type === 'taskSucceeded') {+ } else if (message.type === "taskSucceeded") {const toast = makeToast(message.taskId, t("import.successful"));toast.closeAfter = 5000;@@ -95,7 +95,7 @@ ws.subscribeToMessages(async message => {if (message.result.parentNoteId) {await appContext.tabManager.getActiveContext().setNote(message.result.importedNoteId, {viewScope: {- viewMode: 'attachments'+ viewMode: "attachments"}});}diff --git a/src/public/app/services/keyboard_actions.ts b/src/public/app/services/keyboard_actions.tsindex bf5403706f..5cadd2219e 100644--- a/src/public/app/services/keyboard_actions.ts+++ b/src/public/app/services/keyboard_actions.ts@@ -7,115 +7,114 @@ const keyboardActionRepo: Record<string, Action> = {};// TODO: Deduplicate with server.export interface Action {- actionName: CommandNames;- effectiveShortcuts: string[];- scope: string;+ actionName: CommandNames;+ effectiveShortcuts: string[];+ scope: string;}-const keyboardActionsLoaded = server.get<Action[]>('keyboard-actions').then(actions => {- actions = actions.filter(a => !!a.actionName); // filter out separators+const keyboardActionsLoaded = server.get<Action[]>("keyboard-actions").then((actions) => {+ actions = actions.filter((a) => !!a.actionName); // filter out separators- for (const action of actions) {- action.effectiveShortcuts = action.effectiveShortcuts.filter(shortcut => !shortcut.startsWith("global:"));+ for (const action of actions) {+ action.effectiveShortcuts = action.effectiveShortcuts.filter((shortcut) => !shortcut.startsWith("global:"));- keyboardActionRepo[action.actionName] = action;- }+ keyboardActionRepo[action.actionName] = action;+ }- return actions;+ return actions;});async function getActions() {- return await keyboardActionsLoaded;+ return await keyboardActionsLoaded;}async function getActionsForScope(scope: string) {- const actions = await keyboardActionsLoaded;+ const actions = await keyboardActionsLoaded;- return actions.filter(action => action.scope === scope);+ return actions.filter((action) => action.scope === scope);}async function setupActionsForElement(scope: string, $el: JQuery<HTMLElement>, component: Component) {- const actions = await getActionsForScope(scope);+ const actions = await getActionsForScope(scope);- for (const action of actions) {- for (const shortcut of action.effectiveShortcuts) {- shortcutService.bindElShortcut($el, shortcut, () => component.triggerCommand(action.actionName, {ntxId: appContext.tabManager.activeNtxId}));- }- }+ for (const action of actions) {+ for (const shortcut of action.effectiveShortcuts) {+ shortcutService.bindElShortcut($el, shortcut, () => component.triggerCommand(action.actionName, { ntxId: appContext.tabManager.activeNtxId }));+ }+ }}-getActionsForScope("window").then(actions => {- for (const action of actions) {- for (const shortcut of action.effectiveShortcuts) {- shortcutService.bindGlobalShortcut(shortcut, () => appContext.triggerCommand(action.actionName, {ntxId: appContext.tabManager.activeNtxId}));- }- }+getActionsForScope("window").then((actions) => {+ for (const action of actions) {+ for (const shortcut of action.effectiveShortcuts) {+ shortcutService.bindGlobalShortcut(shortcut, () => appContext.triggerCommand(action.actionName, { ntxId: appContext.tabManager.activeNtxId }));+ }+ }});async function getAction(actionName: string, silent = false) {- await keyboardActionsLoaded;+ await keyboardActionsLoaded;- const action = keyboardActionRepo[actionName];+ const action = keyboardActionRepo[actionName];- if (!action) {- if (silent) {- console.debug(`Cannot find action '${actionName}'`);- }- else {- throw new Error(`Cannot find action '${actionName}'`);- }- }+ if (!action) {+ if (silent) {+ console.debug(`Cannot find action '${actionName}'`);+ } else {+ throw new Error(`Cannot find action '${actionName}'`);+ }+ }- return action;+ return action;}function updateDisplayedShortcuts($container: JQuery<HTMLElement>) {- //@ts-ignore- //TODO: each() does not support async callbacks.- $container.find('kbd[data-command]').each(async (i, el) => {- const actionName = $(el).attr('data-command');- if (!actionName) {- return;- }-- const action = await getAction(actionName, true);-- if (action) {- const keyboardActions = action.effectiveShortcuts.join(', ');-- if (keyboardActions || $(el).text() !== "not set") {- $(el).text(keyboardActions);- }- }- });-- //@ts-ignore- //TODO: each() does not support async callbacks.- $container.find('[data-trigger-command]').each(async (i, el) => {- const actionName = $(el).attr('data-trigger-command');- if (!actionName) {- return;- }- const action = await getAction(actionName, true);-- if (action) {- const title = $(el).attr('title');- const shortcuts = action.effectiveShortcuts.join(', ');-- if (title?.includes(shortcuts)) {- return;- }-- const newTitle = !title?.trim() ? shortcuts : `${title} (${shortcuts})`;-- $(el).attr('title', newTitle);- }- });+ //@ts-ignore+ //TODO: each() does not support async callbacks.+ $container.find("kbd[data-command]").each(async (i, el) => {+ const actionName = $(el).attr("data-command");+ if (!actionName) {+ return;+ }++ const action = await getAction(actionName, true);++ if (action) {+ const keyboardActions = action.effectiveShortcuts.join(", ");++ if (keyboardActions || $(el).text() !== "not set") {+ $(el).text(keyboardActions);+ }+ }+ });++ //@ts-ignore+ //TODO: each() does not support async callbacks.+ $container.find("[data-trigger-command]").each(async (i, el) => {+ const actionName = $(el).attr("data-trigger-command");+ if (!actionName) {+ return;+ }+ const action = await getAction(actionName, true);++ if (action) {+ const title = $(el).attr("title");+ const shortcuts = action.effectiveShortcuts.join(", ");++ if (title?.includes(shortcuts)) {+ return;+ }++ const newTitle = !title?.trim() ? shortcuts : `${title} (${shortcuts})`;++ $(el).attr("title", newTitle);+ }+ });}export default {- updateDisplayedShortcuts,- setupActionsForElement,- getActions,- getActionsForScope+ updateDisplayedShortcuts,+ setupActionsForElement,+ getActions,+ getActionsForScope};diff --git a/src/public/app/services/library_loader.ts b/src/public/app/services/library_loader.tsindex e7d448820d..133a0e6451 100644--- a/src/public/app/services/library_loader.ts+++ b/src/public/app/services/library_loader.ts@@ -38,26 +38,16 @@ const CODE_MIRROR: Library = {return scriptsToLoad;},- css: [- "node_modules/codemirror/lib/codemirror.css",- "node_modules/codemirror/addon/lint/lint.css"- ]+ css: ["node_modules/codemirror/lib/codemirror.css", "node_modules/codemirror/addon/lint/lint.css"]};const ESLINT: Library = {- js: [- "node_modules/eslint/bin/eslint.js"- ]+ js: ["node_modules/eslint/bin/eslint.js"]};const RELATION_MAP: Library = {- js: [- "node_modules/jsplumb/dist/js/jsplumb.min.js",- "node_modules/panzoom/dist/panzoom.min.js"- ],- css: [- "stylesheets/relation_map.css"- ]+ js: ["node_modules/jsplumb/dist/js/jsplumb.min.js", "node_modules/panzoom/dist/panzoom.min.js"],+ css: ["stylesheets/relation_map.css"]};const PRINT_THIS: Library = {@@ -69,62 +59,44 @@ const CALENDAR_WIDGET: Library = {};const KATEX: Library = {- js: [ "node_modules/katex/dist/katex.min.js",- "node_modules/katex/dist/contrib/mhchem.min.js",- "node_modules/katex/dist/contrib/auto-render.min.js" ],- css: [ "node_modules/katex/dist/katex.min.css" ]+ js: ["node_modules/katex/dist/katex.min.js", "node_modules/katex/dist/contrib/mhchem.min.js", "node_modules/katex/dist/contrib/auto-render.min.js"],+ css: ["node_modules/katex/dist/katex.min.css"]};const WHEEL_ZOOM: Library = {- js: [ "node_modules/vanilla-js-wheel-zoom/dist/wheel-zoom.min.js"]+ js: ["node_modules/vanilla-js-wheel-zoom/dist/wheel-zoom.min.js"]};const FORCE_GRAPH: Library = {- js: [ "node_modules/force-graph/dist/force-graph.min.js"]+ js: ["node_modules/force-graph/dist/force-graph.min.js"]};const MERMAID: Library = {- js: [- "node_modules/mermaid/dist/mermaid.min.js"- ]-}+ js: ["node_modules/mermaid/dist/mermaid.min.js"]+};/*** The ELK extension of Mermaid.js, which supports more advanced layouts.* See https://www.npmjs.com/package/@mermaid-js/layout-elk for more information.*/const MERMAID_ELK: Library = {- js: [- "libraries/mermaid-elk/elk.min.js"- ]-}+ js: ["libraries/mermaid-elk/elk.min.js"]+};const EXCALIDRAW: Library = {- js: [- "node_modules/react/umd/react.production.min.js",- "node_modules/react-dom/umd/react-dom.production.min.js",- "node_modules/@excalidraw/excalidraw/dist/excalidraw.production.min.js",- ]+ js: ["node_modules/react/umd/react.production.min.js", "node_modules/react-dom/umd/react-dom.production.min.js", "node_modules/@excalidraw/excalidraw/dist/excalidraw.production.min.js"]};const MARKJS: Library = {- js: [- "node_modules/mark.js/dist/jquery.mark.es6.min.js"- ]+ js: ["node_modules/mark.js/dist/jquery.mark.es6.min.js"]};const I18NEXT: Library = {- js: [- "node_modules/i18next/i18next.min.js",- "node_modules/i18next-http-backend/i18nextHttpBackend.min.js"- ]+ js: ["node_modules/i18next/i18next.min.js", "node_modules/i18next-http-backend/i18nextHttpBackend.min.js"]};const MIND_ELIXIR: Library = {- js: [- "node_modules/mind-elixir/dist/MindElixir.iife.js",- "node_modules/@mind-elixir/node-menu/dist/node-menu.umd.cjs"- ]+ js: ["node_modules/mind-elixir/dist/MindElixir.iife.js", "node_modules/@mind-elixir/node-menu/dist/node-menu.umd.cjs"]};const HIGHLIGHT_JS: Library = {@@ -155,7 +127,7 @@ const HIGHLIGHT_JS: Library = {async function requireLibrary(library: Library) {if (library.css) {- library.css.map(cssUrl => requireCss(cssUrl));+ library.css.map((cssUrl) => requireCss(cssUrl));}if (library.js) {@@ -191,16 +163,14 @@ async function requireScript(url: string) {}async function requireCss(url: string, prependAssetPath = true) {- const cssLinks = Array- .from(document.querySelectorAll('link'))- .map(el => el.href);+ const cssLinks = Array.from(document.querySelectorAll("link")).map((el) => el.href);- if (!cssLinks.some(l => l.endsWith(url))) {+ if (!cssLinks.some((l) => l.endsWith(url))) {if (prependAssetPath) {url = `${window.glob.assetPath}/${url}`;}- $('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', url));+ $("head").append($('<link rel="stylesheet" type="text/css" />').attr("href", url));}}@@ -250,4 +220,4 @@ export default {I18NEXT,MIND_ELIXIR,HIGHLIGHT_JS-}+};diff --git a/src/public/app/services/link.ts b/src/public/app/services/link.tsindex 3cd5b1a702..b24107f5e6 100644--- a/src/public/app/services/link.ts+++ b/src/public/app/services/link.ts@@ -1,4 +1,4 @@-import treeService from './tree.js';+import treeService from "./tree.js";import linkContextMenuService from "../menus/link_context_menu.js";import appContext, { NoteCommandData } from "../components/app_context.js";import froca from "./froca.js";@@ -13,14 +13,14 @@ function getNotePathFromUrl(url: string) {async function getLinkIcon(noteId: string, viewMode: ViewMode | undefined) {let icon;- if (!viewMode || viewMode === 'default') {+ if (!viewMode || viewMode === "default") {const note = await froca.getNote(noteId);icon = note?.getIcon();- } else if (viewMode === 'source') {- icon = 'bx bx-code-curly';- } else if (viewMode === 'attachments') {- icon = 'bx bx-file';+ } else if (viewMode === "source") {+ icon = "bx bx-code-curly";+ } else if (viewMode === "attachments") {+ icon = "bx bx-file";}return icon;}@@ -72,14 +72,14 @@ async function createLink(notePath: string, options: CreateLinkOptions = {}) {}const viewScope = options.viewScope || {};- const viewMode = viewScope.viewMode || 'default';+ const viewMode = viewScope.viewMode || "default";let linkTitle = options.title;if (!linkTitle) {- if (viewMode === 'attachments' && viewScope.attachmentId) {+ if (viewMode === "attachments" && viewScope.attachmentId) {const attachment = await froca.getAttachment(viewScope.attachmentId);- linkTitle = attachment ? attachment.title : '[missing attachment]';+ linkTitle = attachment ? attachment.title : "[missing attachment]";} else if (noteId) {linkTitle = await treeService.getNoteTitle(noteId, parentNoteId);}@@ -87,7 +87,7 @@ async function createLink(notePath: string, options: CreateLinkOptions = {}) {const note = await froca.getNote(noteId);- if (autoConvertToImage && (note?.type && ['image', 'canvas', 'mermaid'].includes(note.type)) && viewMode === 'default') {+ if (autoConvertToImage && note?.type && ["image", "canvas", "mermaid"].includes(note.type) && viewMode === "default") {const encodedTitle = encodeURIComponent(linkTitle || "");return $("<img>")@@ -101,9 +101,7 @@ async function createLink(notePath: string, options: CreateLinkOptions = {}) {let icon = await getLinkIcon(noteId, viewMode);if (icon) {- $container- .append($("<span>").addClass(`bx ${icon}`))- .append(" ");+ $container.append($("<span>").addClass(`bx ${icon}`)).append(" ");}}@@ -128,7 +126,7 @@ async function createLink(notePath: string, options: CreateLinkOptions = {}) {$container.append($noteLink);if (showNotePath) {- const resolvedPathSegments = await treeService.resolveNotePathToSegments(notePath) || [];+ const resolvedPathSegments = (await treeService.resolveNotePathToSegments(notePath)) || [];resolvedPathSegments.pop(); // Remove last elementconst resolvedPath = resolvedPathSegments.join("/");@@ -144,21 +142,23 @@ async function createLink(notePath: string, options: CreateLinkOptions = {}) {return $container;}-function calculateHash({notePath, ntxId, hoistedNoteId, viewScope = {}}: NoteCommandData) {+function calculateHash({ notePath, ntxId, hoistedNoteId, viewScope = {} }: NoteCommandData) {notePath = notePath || "";const params = [ntxId ? { ntxId: ntxId } : null,- (hoistedNoteId && hoistedNoteId !== 'root') ? { hoistedNoteId: hoistedNoteId } : null,- viewScope.viewMode && viewScope.viewMode !== 'default' ? { viewMode: viewScope.viewMode } : null,+ hoistedNoteId && hoistedNoteId !== "root" ? { hoistedNoteId: hoistedNoteId } : null,+ viewScope.viewMode && viewScope.viewMode !== "default" ? { viewMode: viewScope.viewMode } : null,viewScope.attachmentId ? { attachmentId: viewScope.attachmentId } : null- ].filter(p => !!p);+ ].filter((p) => !!p);- const paramStr = params.map(pair => {- const name = Object.keys(pair)[0];- const value = (pair as Record<string, string | undefined>)[name];+ const paramStr = params+ .map((pair) => {+ const name = Object.keys(pair)[0];+ const value = (pair as Record<string, string | undefined>)[name];- return `${encodeURIComponent(name)}=${encodeURIComponent(value || "")}`;- }).join("&");+ return `${encodeURIComponent(name)}=${encodeURIComponent(value || "")}`;+ })+ .join("&");if (!notePath && !paramStr) {return "";@@ -178,7 +178,7 @@ function parseNavigationStateFromUrl(url: string | undefined) {return {};}- const hashIdx = url.indexOf('#');+ const hashIdx = url.indexOf("#");if (hashIdx === -1) {return {};}@@ -191,7 +191,7 @@ function parseNavigationStateFromUrl(url: string | undefined) {}const viewScope: ViewScope = {- viewMode: 'default'+ viewMode: "default"};let ntxId = null;let hoistedNoteId = null;@@ -203,13 +203,13 @@ function parseNavigationStateFromUrl(url: string | undefined) {name = decodeURIComponent(name);value = decodeURIComponent(value);- if (name === 'ntxId') {+ if (name === "ntxId") {ntxId = value;- } else if (name === 'hoistedNoteId') {+ } else if (name === "hoistedNoteId") {hoistedNoteId = value;- } else if (name === 'searchString') {+ } else if (name === "searchString") {searchString = value; // supports triggering search from URL, e.g. #?searchString=blabla- } else if (['viewMode', 'attachmentId'].includes(name)) {+ } else if (["viewMode", "attachmentId"].includes(name)) {(viewScope as any)[name] = value;} else {console.warn(`Unrecognized hash parameter '${name}'.`);@@ -229,7 +229,7 @@ function parseNavigationStateFromUrl(url: string | undefined) {function goToLink(evt: MouseEvent | JQuery.ClickEvent) {const $link = $(evt.target as any).closest("a,.block-link");- const hrefLink = $link.attr('href') || $link.attr('data-href');+ const hrefLink = $link.attr("href") || $link.attr("data-href");return goToLinkExt(evt, hrefLink, $link);}@@ -246,7 +246,7 @@ function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent, hrefLink: string | undreturn handleFootnote(hrefLink, $link);}- const {notePath, viewScope} = parseNavigationStateFromUrl(hrefLink);+ const { notePath, viewScope } = parseNavigationStateFromUrl(hrefLink);const ctrlKey = utils.isCtrlKey(evt);const isLeftClick = evt.which === 1;@@ -258,15 +258,15 @@ function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent, hrefLink: string | undif (notePath) {if (openInNewTab) {- appContext.tabManager.openTabWithNoteWithHoisting(notePath, {viewScope});+ appContext.tabManager.openTabWithNoteWithHoisting(notePath, { viewScope });} else if (isLeftClick) {- const ntxId = $(evt.target as any).closest("[data-ntx-id]").attr("data-ntx-id");+ const ntxId = $(evt.target as any)+ .closest("[data-ntx-id]")+ .attr("data-ntx-id");- const noteContext = ntxId- ? appContext.tabManager.getNoteContextById(ntxId)- : appContext.tabManager.getActiveContext();+ const noteContext = ntxId ? appContext.tabManager.getNoteContextById(ntxId) : appContext.tabManager.getActiveContext();- noteContext.setNote(notePath, {viewScope}).then(() => {+ noteContext.setNote(notePath, { viewScope }).then(() => {if (noteContext !== appContext.tabManager.getActiveContext()) {appContext.tabManager.activateNoteContext(noteContext.ntxId);}@@ -276,27 +276,67 @@ function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent, hrefLink: string | undconst withinEditLink = $link?.hasClass("ck-link-actions__preview");const outsideOfCKEditor = !$link || $link.closest("[contenteditable]").length === 0;- if (openInNewTab- || (withinEditLink && (leftClick || middleClick))- || (outsideOfCKEditor && (leftClick || middleClick))- ) {- if (hrefLink.toLowerCase().startsWith('http') || hrefLink.startsWith("api/")) {- window.open(hrefLink, '_blank');- } else if ((hrefLink.toLowerCase().startsWith('file:') || hrefLink.toLowerCase().startsWith('geo:')) && utils.isElectron()) {- const electron = utils.dynamicRequire('electron');+ if (openInNewTab || (withinEditLink && (leftClick || middleClick)) || (outsideOfCKEditor && (leftClick || middleClick))) {+ if (hrefLink.toLowerCase().startsWith("http") || hrefLink.startsWith("api/")) {+ window.open(hrefLink, "_blank");+ } else if ((hrefLink.toLowerCase().startsWith("file:") || hrefLink.toLowerCase().startsWith("geo:")) && utils.isElectron()) {+ const electron = utils.dynamicRequire("electron");electron.shell.openPath(hrefLink);} else {// Enable protocols supported by CKEditor 5 to be clickable.// Refer to `allowedProtocols` in https://github.com/TriliumNext/trilium-ckeditor5/blob/main/packages/ckeditor5-build-balloon-block/src/ckeditor.ts.// And be consistent with `allowedSchemes` in `src\services\html_sanitizer.ts`const allowedSchemes = [- 'http', 'https', 'ftp', 'ftps', 'mailto', 'data', 'evernote', 'file', 'facetime', 'gemini', 'git',- 'gopher', 'imap', 'irc', 'irc6', 'jabber', 'jar', 'lastfm', 'ldap', 'ldaps', 'magnet', 'message',- 'mumble', 'nfs', 'onenote', 'pop', 'rmi', 's3', 'sftp', 'skype', 'sms', 'spotify', 'steam', 'svn', 'udp',- 'view-source', 'vlc', 'vnc', 'ws', 'wss', 'xmpp', 'jdbc', 'slack', 'tel', 'smb', 'zotero', 'geo'+ "http",+ "https",+ "ftp",+ "ftps",+ "mailto",+ "data",+ "evernote",+ "file",+ "facetime",+ "gemini",+ "git",+ "gopher",+ "imap",+ "irc",+ "irc6",+ "jabber",+ "jar",+ "lastfm",+ "ldap",+ "ldaps",+ "magnet",+ "message",+ "mumble",+ "nfs",+ "onenote",+ "pop",+ "rmi",+ "s3",+ "sftp",+ "skype",+ "sms",+ "spotify",+ "steam",+ "svn",+ "udp",+ "view-source",+ "vlc",+ "vnc",+ "ws",+ "wss",+ "xmpp",+ "jdbc",+ "slack",+ "tel",+ "smb",+ "zotero",+ "geo"];- if (allowedSchemes.some(protocol => hrefLink.toLowerCase().startsWith(protocol+':'))){- window.open(hrefLink, '_blank');+ if (allowedSchemes.some((protocol) => hrefLink.toLowerCase().startsWith(protocol + ":"))) {+ window.open(hrefLink, "_blank");}}}@@ -313,10 +353,9 @@ function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent, hrefLink: string | und* @returns whether the event should be consumed or not.*/function handleFootnote(hrefLink: string, $link: JQuery<HTMLElement>) {- const el = $link.closest(".ck-content")- .find(hrefLink)[0];+ const el = $link.closest(".ck-content").find(hrefLink)[0];if (el) {- el.scrollIntoView({ behavior: "smooth", block: "center" })+ el.scrollIntoView({ behavior: "smooth", block: "center" });}return true;}@@ -337,7 +376,7 @@ function linkContextMenu(e: PointerEvent) {}async function loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string | null | undefined = null) {- const $link = $el[0].tagName === 'A' ? $el : $el.find("a");+ const $link = $el[0].tagName === "A" ? $el : $el.find("a");href = href || $link.attr("href");if (!href) {@@ -345,7 +384,7 @@ async function loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string | nreturn;}- const {noteId, viewScope} = parseNavigationStateFromUrl(href);+ const { noteId, viewScope } = parseNavigationStateFromUrl(href);if (!noteId) {console.warn("Missing note ID.");return;@@ -370,7 +409,7 @@ async function loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string | n}async function getReferenceLinkTitle(href: string) {- const {noteId, viewScope} = parseNavigationStateFromUrl(href);+ const { noteId, viewScope } = parseNavigationStateFromUrl(href);if (!noteId) {return "[missing note]";}@@ -380,7 +419,7 @@ async function getReferenceLinkTitle(href: string) {return "[missing note]";}- if (viewScope?.viewMode === 'attachments' && viewScope?.attachmentId) {+ if (viewScope?.viewMode === "attachments" && viewScope?.attachmentId) {const attachment = await note.getAttachmentById(viewScope.attachmentId);return attachment ? attachment.title : "[missing attachment]";@@ -390,7 +429,7 @@ async function getReferenceLinkTitle(href: string) {}function getReferenceLinkTitleSync(href: string) {- const {noteId, viewScope} = parseNavigationStateFromUrl(href);+ const { noteId, viewScope } = parseNavigationStateFromUrl(href);if (!noteId) {return "[missing note]";}@@ -400,12 +439,12 @@ function getReferenceLinkTitleSync(href: string) {return "[missing note]";}- if (viewScope?.viewMode === 'attachments' && viewScope?.attachmentId) {+ if (viewScope?.viewMode === "attachments" && viewScope?.attachmentId) {if (!note.attachments) {return "[loading title...]";}- const attachment = note.attachments.find(att => att.attachmentId === viewScope.attachmentId);+ const attachment = note.attachments.find((att) => att.attachmentId === viewScope.attachmentId);return attachment ? attachment.title : "[missing attachment]";} else {@@ -415,27 +454,27 @@ function getReferenceLinkTitleSync(href: string) {// TODO: Check why the event is not supported.//@ts-ignore-$(document).on('click', "a", goToLink);+$(document).on("click", "a", goToLink);// TODO: Check why the event is not supported.//@ts-ignore-$(document).on('auxclick', "a", goToLink); // to handle the middle button+$(document).on("auxclick", "a", goToLink); // to handle the middle button// TODO: Check why the event is not supported.//@ts-ignore-$(document).on('contextmenu', 'a', linkContextMenu);-$(document).on('dblclick', "a", e => {+$(document).on("contextmenu", "a", linkContextMenu);+$(document).on("dblclick", "a", (e) => {e.preventDefault();e.stopPropagation();const $link = $(e.target).closest("a");- const address = $link.attr('href');+ const address = $link.attr("href");- if (address && address.startsWith('http')) {- window.open(address, '_blank');+ if (address && address.startsWith("http")) {+ window.open(address, "_blank");}});-$(document).on('mousedown', 'a', e => {+$(document).on("mousedown", "a", (e) => {if (e.which === 2) {// prevent paste on middle click// https://github.com/zadam/trilium/issues/2995diff --git a/src/public/app/services/load_results.ts b/src/public/app/services/load_results.tsindex 12fa2dbd43..b0a5b2eeb7 100644--- a/src/public/app/services/load_results.ts+++ b/src/public/app/services/load_results.ts@@ -47,13 +47,13 @@ interface ContentNoteIdToComponentIdRow {}type EntityRowMappings = {- "notes": NoteRow,- "branches": BranchRow,- "attributes": AttributeRow,- "options": OptionRow,- "revisions": RevisionRow,- "note_reordering": NoteReorderingRow-}+ notes: NoteRow;+ branches: BranchRow;+ attributes: AttributeRow;+ options: OptionRow;+ revisions: RevisionRow;+ note_reordering: NoteReorderingRow;+};export type EntityRowNames = keyof EntityRowMappings;@@ -72,7 +72,7 @@ export default class LoadResults {constructor(entityChanges: EntityChange[]) {const entities: Record<string, Record<string, any>> = {};- for (const {entityId, entityName, entity} of entityChanges) {+ for (const { entityId, entityName, entity } of entityChanges) {if (entity) {entities[entityName] = entities[entityName] || [];entities[entityName][entityId] = entity;@@ -99,7 +99,7 @@ export default class LoadResults {}getEntityRow<T extends EntityRowNames>(entityName: T, entityId: string): EntityRowMappings[T] {- return (this.entities[entityName]?.[entityId]);+ return this.entities[entityName]?.[entityId];}addNote(noteId: string, componentId?: string | null) {@@ -119,13 +119,11 @@ export default class LoadResults {}addBranch(branchId: string, componentId: string) {- this.branchRows.push({branchId, componentId});+ this.branchRows.push({ branchId, componentId });}getBranchRows() {- return this.branchRows- .map(row => this.getEntityRow("branches", row.branchId))- .filter(branch => !!branch);+ return this.branchRows.map((row) => this.getEntityRow("branches", row.branchId)).filter((branch) => !!branch);}addNoteReordering(parentNoteId: string, componentId: string) {@@ -137,22 +135,22 @@ export default class LoadResults {}addAttribute(attributeId: string, componentId: string) {- this.attributeRows.push({attributeId, componentId});+ this.attributeRows.push({ attributeId, componentId });}- getAttributeRows(componentId = 'none'): AttributeRow[] {+ getAttributeRows(componentId = "none"): AttributeRow[] {return this.attributeRows- .filter(row => row.componentId !== componentId)- .map(row => this.getEntityRow("attributes", row.attributeId))- .filter(attr => !!attr) as AttributeRow[];+ .filter((row) => row.componentId !== componentId)+ .map((row) => this.getEntityRow("attributes", row.attributeId))+ .filter((attr) => !!attr) as AttributeRow[];}addRevision(revisionId: string, noteId?: string, componentId?: string | null) {- this.revisionRows.push({revisionId, noteId, componentId});+ this.revisionRows.push({ revisionId, noteId, componentId });}hasRevisionForNote(noteId: string) {- return !!this.revisionRows.find(row => row.noteId === noteId);+ return !!this.revisionRows.find((row) => row.noteId === noteId);}getNoteIds() {@@ -165,11 +163,11 @@ export default class LoadResults {}const componentIds = this.noteIdToComponentId[noteId];- return componentIds && componentIds.find(sId => sId !== componentId) !== undefined;+ return componentIds && componentIds.find((sId) => sId !== componentId) !== undefined;}addNoteContent(noteId: string, componentId: string) {- this.contentNoteIdToComponentId.push({noteId, componentId});+ this.contentNoteIdToComponentId.push({ noteId, componentId });}isNoteContentReloaded(noteId: string, componentId?: string) {@@ -177,7 +175,7 @@ export default class LoadResults {return false;}- return this.contentNoteIdToComponentId.find(l => l.noteId === noteId && l.componentId !== componentId);+ return this.contentNoteIdToComponentId.find((l) => l.noteId === noteId && l.componentId !== componentId);}addOption(name: string) {@@ -205,25 +203,23 @@ export default class LoadResults {* notably changes in note itself should not have any effect on attributes*/hasAttributeRelatedChanges() {- return this.branchRows.length > 0- || this.attributeRows.length > 0;+ return this.branchRows.length > 0 || this.attributeRows.length > 0;}isEmpty() {- return Object.keys(this.noteIdToComponentId).length === 0- && this.branchRows.length === 0- && this.attributeRows.length === 0- && this.noteReorderings.length === 0- && this.revisionRows.length === 0- && this.contentNoteIdToComponentId.length === 0- && this.optionNames.length === 0- && this.attachmentRows.length === 0;+ return (+ Object.keys(this.noteIdToComponentId).length === 0 &&+ this.branchRows.length === 0 &&+ this.attributeRows.length === 0 &&+ this.noteReorderings.length === 0 &&+ this.revisionRows.length === 0 &&+ this.contentNoteIdToComponentId.length === 0 &&+ this.optionNames.length === 0 &&+ this.attachmentRows.length === 0+ );}isEmptyForTree() {- return Object.keys(this.noteIdToComponentId).length === 0- && this.branchRows.length === 0- && this.attributeRows.length === 0- && this.noteReorderings.length === 0;+ return Object.keys(this.noteIdToComponentId).length === 0 && this.branchRows.length === 0 && this.attributeRows.length === 0 && this.noteReorderings.length === 0;}}diff --git a/src/public/app/services/mac_init.ts b/src/public/app/services/mac_init.tsindex 259b412f10..c864b3cadb 100644--- a/src/public/app/services/mac_init.ts+++ b/src/public/app/services/mac_init.ts@@ -6,12 +6,12 @@ import shortcutService from "./shortcuts.js";function init() {if (utils.isElectron() && utils.isMac()) {- shortcutService.bindGlobalShortcut('meta+c', () => exec("copy"));- shortcutService.bindGlobalShortcut('meta+v', () => exec('paste'));- shortcutService.bindGlobalShortcut('meta+x', () => exec('cut'));- shortcutService.bindGlobalShortcut('meta+a', () => exec('selectAll'));- shortcutService.bindGlobalShortcut('meta+z', () => exec('undo'));- shortcutService.bindGlobalShortcut('meta+y', () => exec('redo'));+ shortcutService.bindGlobalShortcut("meta+c", () => exec("copy"));+ shortcutService.bindGlobalShortcut("meta+v", () => exec("paste"));+ shortcutService.bindGlobalShortcut("meta+x", () => exec("cut"));+ shortcutService.bindGlobalShortcut("meta+a", () => exec("selectAll"));+ shortcutService.bindGlobalShortcut("meta+z", () => exec("undo"));+ shortcutService.bindGlobalShortcut("meta+y", () => exec("redo"));}}@@ -23,4 +23,4 @@ function exec(cmd: string) {export default {init-}+};diff --git a/src/public/app/services/mermaid.ts b/src/public/app/services/mermaid.tsindex e553e89e22..16761bbb52 100644--- a/src/public/app/services/mermaid.ts+++ b/src/public/app/services/mermaid.ts@@ -5,10 +5,10 @@ let elkLoaded = false;/*** Determines whether the ELK extension of Mermaid.js needs to be loaded (which is a relatively large library), based on the* front-matter of the diagram and loads the library if needed.- *+ ** <p>* If the library has already been loaded or the diagram does not require it, the method will exit immediately.- *+ ** @param mermaidContent the plain text of the mermaid diagram, potentially including a frontmatter.*/export async function loadElkIfNeeded(mermaidContent: string) {@@ -18,11 +18,11 @@ export async function loadElkIfNeeded(mermaidContent: string) {}const parsedContent = await mermaid.parse(mermaidContent, {- suppressErrors: true+ suppressErrors: true});if (parsedContent?.config?.layout === "elk") {elkLoaded = true;await library_loader.requireLibrary(library_loader.MERMAID_ELK);mermaid.registerLayoutLoaders(MERMAID_ELK);- }-}\ No newline at end of file+ }+}diff --git a/src/public/app/services/mime_types.ts b/src/public/app/services/mime_types.tsindex 8f8a0e5f49..09e3a0f207 100644--- a/src/public/app/services/mime_types.ts+++ b/src/public/app/services/mime_types.ts@@ -22,7 +22,7 @@ interface MimeTypeDefinition {}interface MimeType extends MimeTypeDefinition {- enabled: boolean+ enabled: boolean;}const MIME_TYPES_DICT: MimeTypeDefinition[] = [@@ -192,11 +192,10 @@ let mimeTypes: MimeType[] | null = null;function loadMimeTypes() {mimeTypes = JSON.parse(JSON.stringify(MIME_TYPES_DICT)) as MimeType[]; // clone- const enabledMimeTypes = options.getJson('codeNotesMimeTypes')- || MIME_TYPES_DICT.filter(mt => mt.default).map(mt => mt.mime);+ const enabledMimeTypes = options.getJson("codeNotesMimeTypes") || MIME_TYPES_DICT.filter((mt) => mt.default).map((mt) => mt.mime);for (const mt of mimeTypes) {- mt.enabled = enabledMimeTypes.includes(mt.mime) || mt.mime === 'text/plain'; // text/plain is always enabled+ mt.enabled = enabledMimeTypes.includes(mt.mime) || mt.mime === "text/plain"; // text/plain is always enabled}}@@ -242,8 +241,7 @@ function getHighlightJsNameForMime(mimeType: string) {* @returns the normalized MIME type (e.g. `text-c-src`).*/function normalizeMimeTypeForCKEditor(mimeType: string) {- return mimeType.toLowerCase()- .replace(/[\W_]+/g,"-");+ return mimeType.toLowerCase().replace(/[\W_]+/g, "-");}export default {@@ -252,4 +250,4 @@ export default {loadMimeTypes,getHighlightJsNameForMime,normalizeMimeTypeForCKEditor-}+};diff --git a/src/public/app/services/note_attribute_cache.ts b/src/public/app/services/note_attribute_cache.tsindex 955744d71b..ae3993cfb2 100644--- a/src/public/app/services/note_attribute_cache.ts+++ b/src/public/app/services/note_attribute_cache.ts@@ -9,7 +9,7 @@ import FAttribute from "../entities/fattribute.js";*/class NoteAttributeCache {attributes: Record<string, FAttribute[]>;-+constructor() {this.attributes = {};}diff --git a/src/public/app/services/note_autocomplete.ts b/src/public/app/services/note_autocomplete.tsindex 67a01969f9..7b3defdb25 100644--- a/src/public/app/services/note_autocomplete.ts+++ b/src/public/app/services/note_autocomplete.ts@@ -1,7 +1,7 @@import server from "./server.js";import appContext from "../components/app_context.js";-import utils from './utils.js';-import noteCreateService from './note_create.js';+import utils from "./utils.js";+import noteCreateService from "./note_create.js";import froca from "./froca.js";import { t } from "./i18n.js";@@ -31,36 +31,42 @@ interface Options {async function autocompleteSourceForCKEditor(queryText: string) {return await new Promise<MentionItem[]>((res, rej) => {- autocompleteSource(queryText, rows => {- res(rows.map(row => {- return {- action: row.action,- noteTitle: row.noteTitle,- id: `@${row.notePathTitle}`,- name: row.notePathTitle || "",- link: `#${row.notePath}`,- notePath: row.notePath,- highlightedNotePathTitle: row.highlightedNotePathTitle- }- }));- }, {- allowCreatingNotes: true- });+ autocompleteSource(+ queryText,+ (rows) => {+ res(+ rows.map((row) => {+ return {+ action: row.action,+ noteTitle: row.noteTitle,+ id: `@${row.notePathTitle}`,+ name: row.notePathTitle || "",+ link: `#${row.notePath}`,+ notePath: row.notePath,+ highlightedNotePathTitle: row.highlightedNotePathTitle+ };+ })+ );+ },+ {+ allowCreatingNotes: true+ }+ );});}async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => void, options: Options = {}) {const fastSearch = options.fastSearch === false ? false : true;if (fastSearch === false) {- if (term.trim().length === 0){+ if (term.trim().length === 0) {return;}- cb(- [{+ cb([+ {noteTitle: term,highlightedNotePathTitle: t("quick-search.searching")- }]- );+ }+ ]);}const activeNoteId = appContext.tabManager.getActiveContextNoteId();@@ -69,9 +75,9 @@ async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => voidif (term.trim().length >= 1 && options.allowCreatingNotes) {results = [{- action: 'create-note',+ action: "create-note",noteTitle: term,- parentNoteId: activeNoteId || 'root',+ parentNoteId: activeNoteId || "root",highlightedNotePathTitle: t("note_autocomplete.create-note", { term })} as Suggestion].concat(results);@@ -80,7 +86,7 @@ async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => voidif (term.trim().length >= 1 && options.allowJumpToSearchNotes) {results = results.concat([{- action: 'search-notes',+ action: "search-notes",noteTitle: term,highlightedNotePathTitle: `${t("note_autocomplete.search-for", { term })} <kbd style='color: var(--muted-text-color); background-color: transparent; float: right;'>Ctrl+Enter</kbd>`}@@ -90,7 +96,7 @@ async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => voidif (term.match(/^[a-z]+:\/\/.+/i) && options.allowExternalLinks) {results = [{- action: 'external-link',+ action: "external-link",externalLink: term,highlightedNotePathTitle: t("note_autocomplete.insert-external-link", { term })} as Suggestion@@ -102,42 +108,42 @@ async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => voidfunction clearText($el: JQuery<HTMLElement>) {$el.setSelectedNotePath("");- $el.autocomplete("val", "").trigger('change');+ $el.autocomplete("val", "").trigger("change");}function setText($el: JQuery<HTMLElement>, text: string) {$el.setSelectedNotePath("");- $el- .autocomplete("val", text.trim())- .autocomplete("open");+ $el.autocomplete("val", text.trim()).autocomplete("open");}-function showRecentNotes($el:JQuery<HTMLElement>) {+function showRecentNotes($el: JQuery<HTMLElement>) {$el.setSelectedNotePath("");$el.autocomplete("val", "");- $el.autocomplete('open');- $el.trigger('focus');+ $el.autocomplete("open");+ $el.trigger("focus");}-function fullTextSearch($el: JQuery<HTMLElement>, options: Options){- const searchString = $el.autocomplete('val') as unknown as string;+function fullTextSearch($el: JQuery<HTMLElement>, options: Options) {+ const searchString = $el.autocomplete("val") as unknown as string;if (options.fastSearch === false || searchString?.trim().length === 0) {return;}- $el.trigger('focus');+ $el.trigger("focus");options.fastSearch = false;- $el.autocomplete('val', '');- $el.autocomplete()+ $el.autocomplete("val", "");+ $el.autocomplete();$el.setSelectedNotePath("");- $el.autocomplete('val', searchString);+ $el.autocomplete("val", searchString);// Set a delay to avoid resetting to true before full text search (await server.get) is called.- setTimeout(() => { options.fastSearch = true; }, 100);+ setTimeout(() => {+ options.fastSearch = true;+ }, 100);}function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {if ($el.hasClass("note-autocomplete-input")) {// clear any event listener added in previous invocation of this function- $el.off('autocomplete:noteselected');+ $el.off("autocomplete:noteselected");return $el;}@@ -146,20 +152,15 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {$el.addClass("note-autocomplete-input");- const $clearTextButton = $("<button>")- .addClass("input-group-text input-clearer-button bx bxs-tag-x")- .prop("title", t("note_autocomplete.clear-text-field"));+ const $clearTextButton = $("<button>").addClass("input-group-text input-clearer-button bx bxs-tag-x").prop("title", t("note_autocomplete.clear-text-field"));- const $showRecentNotesButton = $("<button>")- .addClass("input-group-text show-recent-notes-button bx bx-time")- .prop("title", t("note_autocomplete.show-recent-notes"));+ const $showRecentNotesButton = $("<button>").addClass("input-group-text show-recent-notes-button bx bx-time").prop("title", t("note_autocomplete.show-recent-notes"));const $fullTextSearchButton = $("<button>").addClass("input-group-text full-text-search-button bx bx-search").prop("title", `${t("note_autocomplete.full-text-search")} (Shift+Enter)`);- const $goToSelectedNoteButton = $("<a>")- .addClass("input-group-text go-to-selected-note-button bx bx-arrow-to-right");+ const $goToSelectedNoteButton = $("<a>").addClass("input-group-text go-to-selected-note-button bx bx-arrow-to-right");$el.after($clearTextButton).after($showRecentNotesButton).after($fullTextSearchButton);@@ -167,9 +168,9 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {$el.after($goToSelectedNoteButton);}- $clearTextButton.on('click', () => clearText($el));+ $clearTextButton.on("click", () => clearText($el));- $showRecentNotesButton.on('click', e => {+ $showRecentNotesButton.on("click", (e) => {showRecentNotes($el);// this will cause the click not give focus to the "show recent notes" button@@ -177,7 +178,7 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {return false;});- $fullTextSearchButton.on('click', e => {+ $fullTextSearchButton.on("click", (e) => {fullTextSearch($el, options);return false;});@@ -185,53 +186,56 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {let autocompleteOptions: AutoCompleteConfig = {};if (options.container) {autocompleteOptions.dropdownMenuContainer = options.container;- autocompleteOptions.debug = true; // don't close on blur+ autocompleteOptions.debug = true; // don't close on blur}if (options.allowJumpToSearchNotes) {- $el.on('keydown', (event) => {- if (event.ctrlKey && event.key === 'Enter') {+ $el.on("keydown", (event) => {+ if (event.ctrlKey && event.key === "Enter") {// Prevent Ctrl + Enter from triggering autoComplete.event.stopImmediatePropagation();event.preventDefault();- $el.trigger('autocomplete:selected', { action: 'search-notes', noteTitle: $el.autocomplete("val")});+ $el.trigger("autocomplete:selected", { action: "search-notes", noteTitle: $el.autocomplete("val") });}});}- $el.on('keydown', async (event) => {- if (event.shiftKey && event.key === 'Enter') {+ $el.on("keydown", async (event) => {+ if (event.shiftKey && event.key === "Enter") {// Prevent Enter from triggering autoComplete.event.stopImmediatePropagation();event.preventDefault();- fullTextSearch($el,options)+ fullTextSearch($el, options);}});- $el.autocomplete({- ...autocompleteOptions,- appendTo: document.querySelector('body'),- hint: false,- autoselect: true,- // openOnFocus has to be false, otherwise re-focus (after return from note type chooser dialog) forces- // re-querying of the autocomplete source which then changes the currently selected suggestion- openOnFocus: false,- minLength: 0,- tabAutocomplete: false- }, [+ $el.autocomplete({- source: (term, cb) => autocompleteSource(term, cb, options),- displayKey: 'notePathTitle',- templates: {- suggestion: suggestion => suggestion.highlightedNotePathTitle- },- // we can't cache identical searches because notes can be created / renamed, new recent notes can be added- cache: false- }- ]);+ ...autocompleteOptions,+ appendTo: document.querySelector("body"),+ hint: false,+ autoselect: true,+ // openOnFocus has to be false, otherwise re-focus (after return from note type chooser dialog) forces+ // re-querying of the autocomplete source which then changes the currently selected suggestion+ openOnFocus: false,+ minLength: 0,+ tabAutocomplete: false+ },+ [+ {+ source: (term, cb) => autocompleteSource(term, cb, options),+ displayKey: "notePathTitle",+ templates: {+ suggestion: (suggestion) => suggestion.highlightedNotePathTitle+ },+ // we can't cache identical searches because notes can be created / renamed, new recent notes can be added+ cache: false+ }+ ]+ );// TODO: Types fail due to "autocomplete:selected" not being registered in type definitions.- ($el as any).on('autocomplete:selected', async (event: Event, suggestion: Suggestion) => {- if (suggestion.action === 'external-link') {+ ($el as any).on("autocomplete:selected", async (event: Event, suggestion: Suggestion) => {+ if (suggestion.action === "external-link") {$el.setSelectedNotePath(null);$el.setSelectedExternalLink(suggestion.externalLink);@@ -239,12 +243,12 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {$el.autocomplete("close");- $el.trigger('autocomplete:externallinkselected', [suggestion]);+ $el.trigger("autocomplete:externallinkselected", [suggestion]);return;}- if (suggestion.action === 'create-note') {+ if (suggestion.action === "create-note") {const { success, noteType, templateNoteId } = await noteCreateService.chooseNoteType();if (!success) {@@ -262,9 +266,9 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {suggestion.notePath = note?.getBestNotePathString(hoistedNoteId);}- if (suggestion.action === 'search-notes') {+ if (suggestion.action === "search-notes") {const searchString = suggestion.noteTitle;- appContext.triggerCommand('searchNotes', { searchString });+ appContext.triggerCommand("searchNotes", { searchString });return;}@@ -275,23 +279,23 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {$el.autocomplete("close");- $el.trigger('autocomplete:noteselected', [suggestion]);+ $el.trigger("autocomplete:noteselected", [suggestion]);});- $el.on('autocomplete:closed', () => {+ $el.on("autocomplete:closed", () => {if (!String($el.val())?.trim()) {clearText($el);}});- $el.on('autocomplete:opened', () => {+ $el.on("autocomplete:opened", () => {if ($el.attr("readonly")) {- $el.autocomplete('close');+ $el.autocomplete("close");}});// clear any event listener added in previous invocation of this function- $el.off('autocomplete:noteselected');+ $el.off("autocomplete:noteselected");return $el;}@@ -312,21 +316,17 @@ function init() {return null;}- const chunks = notePath.split('/');+ const chunks = notePath.split("/");return chunks.length >= 1 ? chunks[chunks.length - 1] : null;- }+ };$.fn.setSelectedNotePath = function (notePath) {notePath = notePath || "";$(this).attr(SELECTED_NOTE_PATH_KEY, notePath);- $(this)- .closest(".input-group")- .find(".go-to-selected-note-button")- .toggleClass("disabled", !notePath.trim())- .attr("href", `#${notePath}`); // we also set href here so tooltip can be displayed+ $(this).closest(".input-group").find(".go-to-selected-note-button").toggleClass("disabled", !notePath.trim()).attr("href", `#${notePath}`); // we also set href here so tooltip can be displayed};$.fn.getSelectedExternalLink = function () {@@ -340,12 +340,9 @@ function init() {$.fn.setSelectedExternalLink = function (externalLink) {if (externalLink) {// TODO: This doesn't seem to do anything with the external link, is it normal?- $(this)- .closest(".input-group")- .find(".go-to-selected-note-button")- .toggleClass("disabled", true);+ $(this).closest(".input-group").find(".go-to-selected-note-button").toggleClass("disabled", true);}- }+ };$.fn.setNote = async function (noteId) {const note = noteId ? await froca.getNote(noteId, true) : null;@@ -353,7 +350,7 @@ function init() {$(this).val(note ? note.title : "").setSelectedNotePath(noteId);- }+ };}export default {@@ -362,4 +359,4 @@ export default {showRecentNotes,setText,init-}+};diff --git a/src/public/app/services/note_create.ts b/src/public/app/services/note_create.tsindex b44bbcabb5..50c4e62d58 100644--- a/src/public/app/services/note_create.ts+++ b/src/public/app/services/note_create.ts@@ -26,7 +26,7 @@ interface CreateNoteOpts {// TODO: Replace with interface once note_context.js is converted.getSelectedHtml(): string;removeSelection(): void;- }+ };}interface Response {@@ -41,11 +41,14 @@ interface DuplicateResponse {}async function createNote(parentNotePath: string | undefined, options: CreateNoteOpts = {}) {- options = Object.assign({- activate: true,- focus: 'title',- target: 'into'- }, options);+ options = Object.assign(+ {+ activate: true,+ focus: "title",+ target: "into"+ },+ options+ );// if isProtected isn't available (user didn't enter password yet), then note is created as unencrypted,// but this is quite weird since the user doesn't see WHERE the note is being created, so it shouldn't occur often@@ -53,25 +56,25 @@ async function createNote(parentNotePath: string | undefined, options: CreateNotoptions.isProtected = false;}- if (appContext.tabManager.getActiveContextNoteType() !== 'text') {+ if (appContext.tabManager.getActiveContextNoteType() !== "text") {options.saveSelection = false;}- if (options.saveSelection && options.textEditor) {+ if (options.saveSelection && options.textEditor) {[options.title, options.content] = parseSelectedHtml(options.textEditor.getSelectedHtml());}const parentNoteId = treeService.getNoteIdFromUrl(parentNotePath);- if (options.type === 'mermaid' && !options.content) {+ if (options.type === "mermaid" && !options.content) {options.content = `graph TD;A-->B;A-->C;B-->D;- C-->D;`+ C-->D;`;}- const {note, branch} = await server.post<Response>(`notes/${parentNoteId}/children?target=${options.target}&targetBranchId=${options.targetBranchId || ""}`, {+ const { note, branch } = await server.post<Response>(`notes/${parentNoteId}/children?target=${options.target}&targetBranchId=${options.targetBranchId || ""}`, {title: options.title,content: options.content || "",isProtected: options.isProtected,@@ -91,11 +94,10 @@ async function createNote(parentNotePath: string | undefined, options: CreateNotconst activeNoteContext = appContext.tabManager.getActiveContext();await activeNoteContext.setNote(`${parentNotePath}/${note.noteId}`);- if (options.focus === 'title') {- appContext.triggerEvent('focusAndSelectTitle', {isNewNote: true});- }- else if (options.focus === 'content') {- appContext.triggerEvent('focusOnDetail', {ntxId: activeNoteContext.ntxId});+ if (options.focus === "title") {+ appContext.triggerEvent("focusAndSelectTitle", { isNewNote: true });+ } else if (options.focus === "content") {+ appContext.triggerEvent("focusOnDetail", { ntxId: activeNoteContext.ntxId });}}@@ -109,15 +111,15 @@ async function createNote(parentNotePath: string | undefined, options: CreateNot}async function chooseNoteType() {- return new Promise<ChooseNoteTypeResponse>(res => {+ return new Promise<ChooseNoteTypeResponse>((res) => {// TODO: Remove ignore after callback for chooseNoteType is defined in app_context.ts//@ts-ignore- appContext.triggerCommand("chooseNoteType", {callback: res});+ appContext.triggerCommand("chooseNoteType", { callback: res });});}async function createNoteWithTypePrompt(parentNotePath: string, options: CreateNoteOpts = {}) {- const {success, noteType, templateNoteId} = await chooseNoteType();+ const { success, noteType, templateNoteId } = await chooseNoteType();if (!success) {return;@@ -143,15 +145,14 @@ function parseSelectedHtml(selectedHtml: string) {const content = selectedHtml.replace(dom[0].outerHTML, "");return [title, content];- }- else {+ } else {return [null, selectedHtml];}}async function duplicateSubtree(noteId: string, parentNotePath: string) {const parentNoteId = treeService.getNoteIdFromUrl(parentNotePath);- const {note} = await server.post<DuplicateResponse>(`notes/${noteId}/duplicate/${parentNoteId}`);+ const { note } = await server.post<DuplicateResponse>(`notes/${noteId}/duplicate/${parentNoteId}`);await ws.waitForMaxKnownEntityChangeId();diff --git a/src/public/app/services/note_list_renderer.ts b/src/public/app/services/note_list_renderer.tsindex 8da8d6de8e..e6e3056898 100644--- a/src/public/app/services/note_list_renderer.ts+++ b/src/public/app/services/note_list_renderer.ts@@ -158,7 +158,6 @@ const TPL = `</div>`;class NoteListRenderer {-private $noteList: JQuery<HTMLElement>;private parentNote: FNote;@@ -181,7 +180,7 @@ class NoteListRenderer {this.parentNote = parentNote;const includedNoteIds = this.getIncludedNoteIds();- this.noteIds = noteIds.filter(noteId => !includedNoteIds.has(noteId) && noteId !== '_hidden');+ this.noteIds = noteIds.filter((noteId) => !includedNoteIds.has(noteId) && noteId !== "_hidden");if (this.noteIds.length === 0) {return;@@ -190,17 +189,17 @@ class NoteListRenderer {$parent.append(this.$noteList);this.page = 1;- this.pageSize = parseInt(parentNote.getLabelValue('pageSize') || "");+ this.pageSize = parseInt(parentNote.getLabelValue("pageSize") || "");if (!this.pageSize || this.pageSize < 1) {this.pageSize = 20;}- this.viewType = parentNote.getLabelValue('viewType');+ this.viewType = parentNote.getLabelValue("viewType");- if (!['list', 'grid'].includes(this.viewType || "")) {+ if (!["list", "grid"].includes(this.viewType || "")) {// when not explicitly set, decide based on the note type- this.viewType = parentNote.type === 'search' ? 'list' : 'grid';+ this.viewType = parentNote.type === "search" ? "list" : "grid";}this.$noteList.addClass(`${this.viewType}-view`);@@ -211,11 +210,9 @@ class NoteListRenderer {/** @returns {Set<string>} list of noteIds included (images, included notes) in the parent note and which* don't have to be shown in the note list. */getIncludedNoteIds() {- const includedLinks = this.parentNote- ? this.parentNote.getRelations().filter(rel => rel.name === 'imageLink' || rel.name === 'includeNoteLink')- : [];+ const includedLinks = this.parentNote ? this.parentNote.getRelations().filter((rel) => rel.name === "imageLink" || rel.name === "includeNoteLink") : [];- return new Set(includedLinks.map(rel => rel.value));+ return new Set(includedLinks.map((rel) => rel.value));}async renderList() {@@ -228,18 +225,16 @@ class NoteListRenderer {if (highlightedTokens.length > 0) {await libraryLoader.requireLibrary(libraryLoader.MARKJS);- const regex = highlightedTokens- .map(token => utils.escapeRegExp(token))- .join("|");+ const regex = highlightedTokens.map((token) => utils.escapeRegExp(token)).join("|");- this.highlightRegex = new RegExp(regex, 'gi');+ this.highlightRegex = new RegExp(regex, "gi");} else {this.highlightRegex = null;}this.$noteList.show();- const $container = this.$noteList.find('.note-list-container').empty();+ const $container = this.$noteList.find(".note-list-container").empty();const startIdx = (this.page - 1) * this.pageSize;const endIdx = startIdx + this.pageSize;@@ -248,7 +243,7 @@ class NoteListRenderer {const pageNotes = await froca.getNotes(pageNoteIds);for (const note of pageNotes) {- const $card = await this.renderNote(note, this.parentNote.isLabelTruthy('expanded'));+ const $card = await this.renderNote(note, this.parentNote.isLabelTruthy("expanded"));$container.append($card);}@@ -259,7 +254,7 @@ class NoteListRenderer {}renderPager() {- const $pager = this.$noteList.find('.note-list-pager').empty();+ const $pager = this.$noteList.find(".note-list-pager").empty();if (!this.page || !this.pageSize) {return;}@@ -279,18 +274,17 @@ class NoteListRenderer {$pager.append(i === this.page- ? $('<span>').text(i).css('text-decoration', 'underline').css('font-weight', "bold")+ ? $("<span>").text(i).css("text-decoration", "underline").css("font-weight", "bold"): $('<a href="javascript:">')- .text(i)- .attr("title", `Page of ${startIndex} - ${endIndex}`)- .on('click', () => {- this.page = i;- this.renderList();- }),+ .text(i)+ .attr("title", `Page of ${startIndex} - ${endIndex}`)+ .on("click", () => {+ this.page = i;+ this.renderList();+ })," ");- }- else if (lastPrinted) {+ } else if (lastPrinted) {$pager.append("... ");lastPrinted = false;@@ -304,33 +298,34 @@ class NoteListRenderer {async renderNote(note: FNote, expand: boolean = false) {const $expander = $('<span class="note-expander bx bx-chevron-right"></span>');- const {$renderedAttributes} = await attributeRenderer.renderNormalAttributes(note);- const notePath = this.parentNote.type === 'search'- ? note.noteId // for search note parent, we want to display a non-search path- : `${this.parentNote.noteId}/${note.noteId}`;+ const { $renderedAttributes } = await attributeRenderer.renderNormalAttributes(note);+ const notePath =+ this.parentNote.type === "search"+ ? note.noteId // for search note parent, we want to display a non-search path+ : `${this.parentNote.noteId}/${note.noteId}`;const $card = $('<div class="note-book-card">')- .attr('data-note-id', note.noteId)+ .attr("data-note-id", note.noteId).append($('<h5 class="note-book-header">').append($expander).append($('<span class="note-icon">').addClass(note.getIcon()))- .append(this.viewType === 'grid'- ? $('<span class="note-book-title">').text(await treeService.getNoteTitle(note.noteId, this.parentNote.noteId))- : (await linkService.createLink(notePath, {showTooltip: false, showNotePath: this.showNotePath}))- .addClass("note-book-title")+ .append(+ this.viewType === "grid"+ ? $('<span class="note-book-title">').text(await treeService.getNoteTitle(note.noteId, this.parentNote.noteId))+ : (await linkService.createLink(notePath, { showTooltip: false, showNotePath: this.showNotePath })).addClass("note-book-title")).append($renderedAttributes));- if (this.viewType === 'grid') {+ if (this.viewType === "grid") {$card.addClass("block-link").attr("data-href", `#${notePath}`)- .on('click', e => linkService.goToLink(e));+ .on("click", (e) => linkService.goToLink(e));}- $expander.on('click', () => this.toggleContent($card, note, !$card.hasClass("expanded")));+ $expander.on("click", () => this.toggleContent($card, note, !$card.hasClass("expanded")));if (this.highlightRegex) {$card.find(".note-book-title").markRegExp(this.highlightRegex, {@@ -347,22 +342,21 @@ class NoteListRenderer {}async toggleContent($card: JQuery<HTMLElement>, note: FNote, expand: boolean) {- if (this.viewType === 'list' && ((expand && $card.hasClass("expanded")) || (!expand && !$card.hasClass("expanded")))) {+ if (this.viewType === "list" && ((expand && $card.hasClass("expanded")) || (!expand && !$card.hasClass("expanded")))) {return;}- const $expander = $card.find('> .note-book-header .note-expander');+ const $expander = $card.find("> .note-book-header .note-expander");- if (expand || this.viewType === 'grid') {+ if (expand || this.viewType === "grid") {$card.addClass("expanded");$expander.addClass("bx-chevron-down").removeClass("bx-chevron-right");- }- else {+ } else {$card.removeClass("expanded");$expander.addClass("bx-chevron-right").removeClass("bx-chevron-down");}- if ((expand || this.viewType === 'grid') && $card.find('.note-book-content').length === 0) {+ if ((expand || this.viewType === "grid") && $card.find(".note-book-content").length === 0) {$card.append(await this.renderNoteContent(note));}}@@ -371,8 +365,8 @@ class NoteListRenderer {const $content = $('<div class="note-book-content">');try {- const {$renderedContent, type} = await contentRenderer.getRenderedContent(note, {- trim: this.viewType === 'grid' // for grid only short content is needed+ const { $renderedContent, type } = await contentRenderer.getRenderedContent(note, {+ trim: this.viewType === "grid" // for grid only short content is needed});if (this.highlightRegex) {@@ -393,11 +387,10 @@ class NoteListRenderer {$content.append("rendering error");}- if (this.viewType === 'list') {- const imageLinks = note.getRelations('imageLink');+ if (this.viewType === "list") {+ const imageLinks = note.getRelations("imageLink");- const childNotes = (await note.getChildNotes())- .filter(childNote => !imageLinks.find(rel => rel.value === childNote.noteId));+ const childNotes = (await note.getChildNotes()).filter((childNote) => !imageLinks.find((rel) => rel.value === childNote.noteId));for (const childNote of childNotes) {$content.append(await this.renderNote(childNote));diff --git a/src/public/app/services/note_tooltip.ts b/src/public/app/services/note_tooltip.tsindex 2ae0f47b78..f456d7a639 100644--- a/src/public/app/services/note_tooltip.ts+++ b/src/public/app/services/note_tooltip.ts@@ -12,7 +12,7 @@ function setupGlobalTooltip() {$(document).on("mouseenter", "a", mouseEnterHandler);// close any note tooltip after click, this fixes the problem that sometimes tooltips remained on the screen- $(document).on("click", e => {+ $(document).on("click", (e) => {if ($(e.target).closest(".note-tooltip").length) {// click within the tooltip shouldn't close itreturn;@@ -23,11 +23,11 @@ function setupGlobalTooltip() {}function cleanUpTooltips() {- $('.note-tooltip').remove();+ $(".note-tooltip").remove();}function setupElementTooltip($el: JQuery<HTMLElement>) {- $el.on('mouseenter', mouseEnterHandler);+ $el.on("mouseenter", mouseEnterHandler);}async function mouseEnterHandler(this: HTMLElement) {@@ -51,7 +51,7 @@ async function mouseEnterHandler(this: HTMLElement) {return;}- if (!notePath || !noteId || viewScope?.viewMode !== 'default') {+ if (!notePath || !noteId || viewScope?.viewMode !== "default") {return;}@@ -67,13 +67,13 @@ async function mouseEnterHandler(this: HTMLElement) {if (url?.startsWith("#fn")) {renderPromise = renderFootnote($link, url);} else {- renderPromise = renderTooltip(await froca.getNote(noteId))+ renderPromise = renderTooltip(await froca.getNote(noteId));}const [content] = await Promise.all([renderPromise,// to reduce flicker due to accidental mouseover, cursor must stay for a bit over the link for tooltip to appear- new Promise(res => setTimeout(res, 500))+ new Promise((res) => setTimeout(res, 500))]);if (!content || utils.isHtmlEmpty(content)) {@@ -81,18 +81,18 @@ async function mouseEnterHandler(this: HTMLElement) {}const html = `<div class="note-tooltip-content">${content}</div>`;- const tooltipClass = 'tooltip-' + Math.floor(Math.random() * 999_999_999);+ const tooltipClass = "tooltip-" + Math.floor(Math.random() * 999_999_999);// we need to check if we're still hovering over the element// since the operation to get tooltip content was async, it is possible that// we now create tooltip which won't close because it won't receive mouseleave eventif ($(this).filter(":hover").length > 0) {$(this).tooltip({- container: 'body',+ container: "body",// https://github.com/zadam/trilium/issues/2794 https://github.com/zadam/trilium/issues/2988// with bottom this flickering happens a bit less- placement: 'bottom',- trigger: 'manual',+ placement: "bottom",+ trigger: "manual",//TODO: boundary No longer applicable?//boundary: 'window',title: html,@@ -103,7 +103,7 @@ async function mouseEnterHandler(this: HTMLElement) {});cleanUpTooltips();- $(this).tooltip('show');+ $(this).tooltip("show");// Dismiss the tooltip immediately if a link was clicked inside the tooltip.$(`.${tooltipClass} a`).on("click", (e) => {@@ -121,7 +121,7 @@ async function mouseEnterHandler(this: HTMLElement) {} else {setTimeout(checkTooltip, 1000);}- }+ };setTimeout(checkTooltip, 1000);}@@ -142,12 +142,12 @@ async function renderTooltip(note: FNote | null) {const noteTitleWithPathAsSuffix = await treeService.getNoteTitleWithPathAsSuffix(bestNotePath);let content = "";if (noteTitleWithPathAsSuffix) {- content = `<h5 class="note-tooltip-title">${noteTitleWithPathAsSuffix.prop('outerHTML')}</h5>`;+ content = `<h5 class="note-tooltip-title">${noteTitleWithPathAsSuffix.prop("outerHTML")}</h5>`;}- const {$renderedAttributes} = await attributeRenderer.renderNormalAttributes(note);+ const { $renderedAttributes } = await attributeRenderer.renderNormalAttributes(note);- const {$renderedContent} = await contentRenderer.getRenderedContent(note, {+ const { $renderedContent } = await contentRenderer.getRenderedContent(note, {tooltip: true,trim: true});@@ -161,11 +161,11 @@ function renderFootnote($link: JQuery<HTMLElement>, url: string) {// A footnote text referenceconst footnoteRef = url.substring(3);const $footnoteContent = $link- .closest(".ck-content") // find the parent CK content- .find("> .footnote-section") // find the footnote section- .find(`a[href="#fnref${footnoteRef}"]`) // find the footnote link- .closest(".footnote-item") // find the parent container of the footnote- .find(".footnote-content"); // find the actual text content of the footnote+ .closest(".ck-content") // find the parent CK content+ .find("> .footnote-section") // find the footnote section+ .find(`a[href="#fnref${footnoteRef}"]`) // find the footnote link+ .closest(".footnote-item") // find the parent container of the footnote+ .find(".footnote-content"); // find the actual text content of the footnotereturn $footnoteContent.html() || "";}@@ -173,4 +173,4 @@ function renderFootnote($link: JQuery<HTMLElement>, url: string) {export default {setupGlobalTooltip,setupElementTooltip-}+};diff --git a/src/public/app/services/note_types.ts b/src/public/app/services/note_types.tsindex 0174c78a09..61b71775bb 100644--- a/src/public/app/services/note_types.ts+++ b/src/public/app/services/note_types.ts@@ -43,4 +43,4 @@ async function getNoteTypeItems(command?: NoteTypeCommandNames) {export default {getNoteTypeItems-}+};diff --git a/src/public/app/services/open.ts b/src/public/app/services/open.tsindex da41da3b19..7dab08a1af 100644--- a/src/public/app/services/open.ts+++ b/src/public/app/services/open.ts@@ -1,14 +1,14 @@import utils from "./utils.js";import server from "./server.js";-type ExecFunction = (command: string, cb: ((err: string, stdout: string, stderror: string) => void)) => void;+type ExecFunction = (command: string, cb: (err: string, stdout: string, stderror: string) => void) => void;interface TmpResponse {tmpFilePath: string;}function checkType(type: string) {- if (type !== 'notes' && type !== 'attachments') {+ if (type !== "notes" && type !== "attachments") {throw new Error(`Unrecognized type '${type}', should be 'notes' or 'attachments'`);}}@@ -27,7 +27,7 @@ function getOpenFileUrl(type: string, noteId: string) {function download(url: string) {if (utils.isElectron()) {- const remote = utils.dynamicRequire('@electron/remote');+ const remote = utils.dynamicRequire("@electron/remote");remote.getCurrentWebContents().downloadURL(url);} else {@@ -36,13 +36,13 @@ function download(url: string) {}function downloadFileNote(noteId: string) {- const url = `${getFileUrl('notes', noteId)}?${Date.now()}`; // don't use cache+ const url = `${getFileUrl("notes", noteId)}?${Date.now()}`; // don't use cachedownload(url);}function downloadAttachment(attachmentId: string) {- const url = `${getFileUrl('attachments', attachmentId)}?${Date.now()}`; // don't use cache+ const url = `${getFileUrl("attachments", attachmentId)}?${Date.now()}`; // don't use cachedownload(url);}@@ -55,12 +55,12 @@ async function openCustom(type: string, entityId: string, mime: string) {const resp = await server.post<TmpResponse>(`${type}/${entityId}/save-to-tmp-dir`);let filePath = resp.tmpFilePath;- const exec = utils.dynamicRequire('child_process').exec as ExecFunction;+ const exec = utils.dynamicRequire("child_process").exec as ExecFunction;const platform = process.platform;- if (platform === 'linux') {+ if (platform === "linux") {// we don't know which terminal is available, try in succession- const terminals = ['x-terminal-emulator', 'gnome-terminal', 'konsole', 'xterm', 'xfce4-terminal', 'mate-terminal', 'rxvt', 'terminator', 'terminology'];+ const terminals = ["x-terminal-emulator", "gnome-terminal", "konsole", "xterm", "xfce4-terminal", "mate-terminal", "rxvt", "terminator", "terminology"];const openFileWithTerminal = (terminal: string) => {const command = `${terminal} -e 'mimeopen -d "${filePath}"'`;console.log(`Open Note custom: ${command} `);@@ -77,9 +77,9 @@ async function openCustom(type: string, entityId: string, mime: string) {const searchTerminal = (index: number) => {const terminal = terminals[index];if (!terminal) {- console.error('Open Note custom: No terminal found!');+ console.error("Open Note custom: No terminal found!");// TODO: Remove {url: true} if not needed.- (open as any)(getFileUrl(type, entityId), {url: true});+ (open as any)(getFileUrl(type, entityId), { url: true });return;}exec(`which ${terminal}`, (error, stdout, stderr) => {@@ -91,7 +91,7 @@ async function openCustom(type: string, entityId: string, mime: string) {});};searchTerminal(0);- } else if (platform === 'win32') {+ } else if (platform === "win32") {if (filePath.indexOf("/") !== -1) {// Note that the path separator must be \ instead of /filePath = filePath.replace(/\//g, "\\");@@ -102,7 +102,7 @@ async function openCustom(type: string, entityId: string, mime: string) {console.error("Open Note custom: ", err);// TODO: This appears to be broken, since getFileUrl expects two arguments, with the first one being the type.// Also don't know why {url: true} is passed.- (open as any)(getFileUrl(entityId), {url: true});+ (open as any)(getFileUrl(entityId), { url: true });return;}});@@ -110,15 +110,12 @@ async function openCustom(type: string, entityId: string, mime: string) {console.log('Currently "Open Note custom" only supports linux and windows systems');// TODO: This appears to be broken, since getFileUrl expects two arguments, with the first one being the type.// Also don't know why {url: true} is passed.- (open as any)(getFileUrl(entityId), {url: true});+ (open as any)(getFileUrl(entityId), { url: true });}}-const openNoteCustom =- async (noteId: string, mime: string) => await openCustom('notes', noteId, mime);-const openAttachmentCustom =- async (attachmentId: string, mime: string) => await openCustom('attachments', attachmentId, mime);-+const openNoteCustom = async (noteId: string, mime: string) => await openCustom("notes", noteId, mime);+const openAttachmentCustom = async (attachmentId: string, mime: string) => await openCustom("attachments", attachmentId, mime);function downloadRevision(noteId: string, revisionId: string) {const url = getUrlForDownload(`api/revisions/${revisionId}/download`);@@ -133,18 +130,14 @@ function getUrlForDownload(url: string) {if (utils.isElectron()) {// electron needs absolute URL, so we extract current host, port, protocolreturn `${getHost()}/${url}`;- }- else {+ } else {// web server can be deployed on subdomain, so we need to use a relative pathreturn url;}}function canOpenInBrowser(mime: string) {- return mime === "application/pdf"- || mime.startsWith("image")- || mime.startsWith("audio")- || mime.startsWith("video");+ return mime === "application/pdf" || mime.startsWith("image") || mime.startsWith("audio") || mime.startsWith("video");}async function openExternally(type: string, entityId: string, mime: string) {@@ -153,15 +146,14 @@ async function openExternally(type: string, entityId: string, mime: string) {if (utils.isElectron()) {const resp = await server.post<TmpResponse>(`${type}/${entityId}/save-to-tmp-dir`);- const electron = utils.dynamicRequire('electron');+ const electron = utils.dynamicRequire("electron");const res = await electron.shell.openPath(resp.tmpFilePath);if (res) {// fallback in case there's no default application for this filewindow.open(getFileUrl(type, entityId));}- }- else {+ } else {// allow browser to handle opening common fileif (canOpenInBrowser(mime)) {window.open(getOpenFileUrl(type, entityId));@@ -171,10 +163,8 @@ async function openExternally(type: string, entityId: string, mime: string) {}}-const openNoteExternally =- async (noteId: string, mime: string) => await openExternally('notes', noteId, mime);-const openAttachmentExternally =- async (attachmentId: string, mime: string) => await openExternally('attachments', attachmentId, mime);+const openNoteExternally = async (noteId: string, mime: string) => await openExternally("notes", noteId, mime);+const openAttachmentExternally = async (attachmentId: string, mime: string) => await openExternally("attachments", attachmentId, mime);function getHost() {const url = new URL(window.location.href);@@ -184,17 +174,17 @@ function getHost() {async function openDirectory(directory: string) {try {if (utils.isElectron()) {- const electron = utils.dynamicRequire('electron');+ const electron = utils.dynamicRequire("electron");const res = await electron.shell.openPath(directory);if (res) {- console.error('Failed to open directory:', res);+ console.error("Failed to open directory:", res);}} else {- console.error('Not running in an Electron environment.');+ console.error("Not running in an Electron environment.");}} catch (err: any) {// Handle file system errors (e.g. path does not exist or is inaccessible)- console.error('Error:', err.message);+ console.error("Error:", err.message);}}@@ -209,4 +199,4 @@ export default {openNoteCustom,openAttachmentCustom,openDirectory-}+};diff --git a/src/public/app/services/options.ts b/src/public/app/services/options.tsindex b6162ea1d7..660861d179 100644--- a/src/public/app/services/options.ts+++ b/src/public/app/services/options.ts@@ -1,4 +1,3 @@-import server from "./server.js";type OptionValue = number | string;@@ -8,7 +7,7 @@ class Options {private arr!: Record<string, OptionValue>;constructor() {- this.initializedPromise = server.get<Record<string, OptionValue>>('options').then(data => this.load(data));+ this.initializedPromise = server.get<Record<string, OptionValue>>("options").then((data) => this.load(data));}load(arr: Record<string, OptionValue>) {@@ -30,8 +29,7 @@ class Options {}try {return JSON.parse(value);- }- catch (e) {+ } catch (e) {return null;}}@@ -53,7 +51,7 @@ class Options {}is(key: string) {- return this.arr[key] === 'true';+ return this.arr[key] === "true";}set(key: string, value: OptionValue) {diff --git a/src/public/app/services/promoted_attribute_definition_parser.ts b/src/public/app/services/promoted_attribute_definition_parser.tsindex 35d0f5ad03..ca0095f601 100644--- a/src/public/app/services/promoted_attribute_definition_parser.ts+++ b/src/public/app/services/promoted_attribute_definition_parser.ts@@ -11,35 +11,29 @@ interface DefinitionObject {}function parse(value: string) {- const tokens = value.split(',').map(t => t.trim());+ const tokens = value.split(",").map((t) => t.trim());const defObj: DefinitionObject = {};for (const token of tokens) {- if (token === 'promoted') {+ if (token === "promoted") {defObj.isPromoted = true;- }- else if (['text', 'number', 'boolean', 'date', 'datetime', 'time', 'url'].includes(token)) {+ } else if (["text", "number", "boolean", "date", "datetime", "time", "url"].includes(token)) {defObj.labelType = token as LabelType;- }- else if (['single', 'multi'].includes(token)) {+ } else if (["single", "multi"].includes(token)) {defObj.multiplicity = token as Multiplicity;- }- else if (token.startsWith('precision')) {- const chunks = token.split('=');+ } else if (token.startsWith("precision")) {+ const chunks = token.split("=");defObj.numberPrecision = parseInt(chunks[1]);- }- else if (token.startsWith('alias')) {- const chunks = token.split('=');+ } else if (token.startsWith("alias")) {+ const chunks = token.split("=");defObj.promotedAlias = chunks[1];- }- else if (token.startsWith('inverse')) {- const chunks = token.split('=');+ } else if (token.startsWith("inverse")) {+ const chunks = token.split("=");defObj.inverseRelation = chunks[1];- }- else {+ } else {console.log("Unrecognized attribute definition token:", token);}}diff --git a/src/public/app/services/protected_session.ts b/src/public/app/services/protected_session.tsindex 0b6b03c9d3..1bf995d935 100644--- a/src/public/app/services/protected_session.ts+++ b/src/public/app/services/protected_session.ts@@ -1,5 +1,5 @@-import server from './server.js';-import protectedSessionHolder from './protected_session_holder.js';+import server from "./server.js";+import protectedSessionHolder from "./protected_session_holder.js";import toastService from "./toast.js";import type { ToastOptions } from "./toast.js";import ws from "./ws.js";@@ -7,7 +7,7 @@ import appContext from "../components/app_context.js";import froca from "./froca.js";import utils from "./utils.js";import options from "./options.js";-import { t } from './i18n.js';+import { t } from "./i18n.js";let protectedSessionDeferred: JQuery.Deferred<any, any, any> | null = null;@@ -19,8 +19,8 @@ interface Response {interface Message {taskId: string;data: {- protect: boolean- }+ protect: boolean;+ };}async function leaveProtectedSession() {@@ -40,8 +40,7 @@ function enterProtectedSession() {if (protectedSessionHolder.isProtectedSessionAvailable()) {dfd.resolve(false);- }- else {+ } else {// using deferred instead of promise because it allows resolving from the outsideprotectedSessionDeferred = dfd;@@ -61,7 +60,7 @@ async function reloadData() {}async function setupProtectedSession(password: string) {- const response = await server.post<Response>('login/protected', { password: password });+ const response = await server.post<Response>("login/protected", { password: password });if (!response.success) {toastService.showError(t("protected_session.wrong_password"), 3000);@@ -71,13 +70,13 @@ async function setupProtectedSession(password: string) {protectedSessionHolder.enableProtectedSession();}-ws.subscribeToMessages(async message => {- if (message.type === 'protectedSessionLogin') {+ws.subscribeToMessages(async (message) => {+ if (message.type === "protectedSessionLogin") {await reloadData();- await appContext.triggerEvent('frocaReloaded');+ await appContext.triggerEvent("frocaReloaded");- appContext.triggerEvent('protectedSessionStarted');+ appContext.triggerEvent("protectedSessionStarted");appContext.triggerCommand("closeProtectedSessionPasswordDialog");@@ -87,8 +86,7 @@ ws.subscribeToMessages(async message => {}toastService.showMessage(t("protected_session.started"));- }- else if (message.type === 'protectedSessionLogout') {+ } else if (message.type === "protectedSessionLogout") {utils.reloadFrontendApp(`Protected session logout`);}});@@ -108,23 +106,23 @@ function makeToast(message: Message, title: string, text: string): ToastOptions};}-ws.subscribeToMessages(async message => {- if (message.taskType !== 'protectNotes') {+ws.subscribeToMessages(async (message) => {+ if (message.taskType !== "protectNotes") {return;}const isProtecting = message.data.protect;const title = isProtecting ? t("protected_session.protecting-title") : t("protected_session.unprotecting-title");-- if (message.type === 'taskError') {++ if (message.type === "taskError") {toastService.closePersistent(message.taskId);toastService.showError(message.message);- } else if (message.type === 'taskProgressCount') {+ } else if (message.type === "taskProgressCount") {const count = message.progressCount;- const text = ( isProtecting ? t("protected_session.protecting-in-progress", { count }) : t("protected_session.unprotecting-in-progress-count", { count }));+ const text = isProtecting ? t("protected_session.protecting-in-progress", { count }) : t("protected_session.unprotecting-in-progress-count", { count });toastService.showPersistent(makeToast(message, title, text));- } else if (message.type === 'taskSucceeded') {- const text = (isProtecting ? t("protected_session.protecting-finished-successfully") : t("protected_session.unprotecting-finished-successfully"))+ } else if (message.type === "taskSucceeded") {+ const text = isProtecting ? t("protected_session.protecting-finished-successfully") : t("protected_session.unprotecting-finished-successfully");const toast = makeToast(message, title, text);toast.closeAfter = 3000;diff --git a/src/public/app/services/render.ts b/src/public/app/services/render.tsindex 9a998b573e..5c48fd3f05 100644--- a/src/public/app/services/render.ts+++ b/src/public/app/services/render.ts@@ -3,17 +3,15 @@ import bundleService, { Bundle } from "./bundle.js";import FNote from "../entities/fnote.js";async function render(note: FNote, $el: JQuery<HTMLElement>) {- const relations = note.getRelations('renderNote');- const renderNoteIds = relations- .map(rel => rel.value)- .filter(noteId => noteId);+ const relations = note.getRelations("renderNote");+ const renderNoteIds = relations.map((rel) => rel.value).filter((noteId) => noteId);$el.empty().toggle(renderNoteIds.length > 0);for (const renderNoteId of renderNoteIds) {const bundle = await server.post<Bundle>(`script/bundle/${renderNoteId}`);- const $scriptContainer = $('<div>');+ const $scriptContainer = $("<div>");$el.append($scriptContainer);$scriptContainer.append(bundle.html);@@ -27,4 +25,4 @@ async function render(note: FNote, $el: JQuery<HTMLElement>) {export default {render-}+};diff --git a/src/public/app/services/resizer.ts b/src/public/app/services/resizer.tsindex 6acea693a1..d6e828047e 100644--- a/src/public/app/services/resizer.ts+++ b/src/public/app/services/resizer.ts@@ -12,21 +12,21 @@ function setupLeftPaneResizer(leftPaneVisible: boolean) {$("#left-pane").toggle(leftPaneVisible);if (!leftPaneVisible) {- $("#rest-pane").css('width', '100%');+ $("#rest-pane").css("width", "100%");return;}- let leftPaneWidth = options.getInt('leftPaneWidth');+ let leftPaneWidth = options.getInt("leftPaneWidth");if (!leftPaneWidth || leftPaneWidth < 5) {leftPaneWidth = 5;}if (leftPaneVisible) {- leftInstance = Split(['#left-pane', '#rest-pane'], {+ leftInstance = Split(["#left-pane", "#rest-pane"], {sizes: [leftPaneWidth, 100 - leftPaneWidth],gutterSize: 5,- onDragEnd: sizes => options.save('leftPaneWidth', Math.round(sizes[0]))+ onDragEnd: (sizes) => options.save("leftPaneWidth", Math.round(sizes[0]))});}}@@ -40,26 +40,26 @@ function setupRightPaneResizer() {const rightPaneVisible = $("#right-pane").is(":visible");if (!rightPaneVisible) {- $("#center-pane").css('width', '100%');+ $("#center-pane").css("width", "100%");return;}- let rightPaneWidth = options.getInt('rightPaneWidth');+ let rightPaneWidth = options.getInt("rightPaneWidth");if (!rightPaneWidth || rightPaneWidth < 5) {rightPaneWidth = 5;}if (rightPaneVisible) {- rightInstance = Split(['#center-pane', '#right-pane'], {+ rightInstance = Split(["#center-pane", "#right-pane"], {sizes: [100 - rightPaneWidth, rightPaneWidth],gutterSize: 5,- onDragEnd: sizes => options.save('rightPaneWidth', Math.round(sizes[1]))+ onDragEnd: (sizes) => options.save("rightPaneWidth", Math.round(sizes[1]))});}}export default {setupLeftPaneResizer,- setupRightPaneResizer,+ setupRightPaneResizer};diff --git a/src/public/app/services/script_context.ts b/src/public/app/services/script_context.tsindex 7d76c12a77..a654fa3d9d 100644--- a/src/public/app/services/script_context.ts+++ b/src/public/app/services/script_context.ts@@ -1,6 +1,6 @@-import FrontendScriptApi, { Entity } from './frontend_script_api.js';-import utils from './utils.js';-import froca from './froca.js';+import FrontendScriptApi, { Entity } from "./frontend_script_api.js";+import utils from "./utils.js";+import froca from "./froca.js";async function ScriptContext(startNoteId: string, allNoteIds: string[], originEntity: Entity | null = null, $container: JQuery<HTMLElement> | null = null) {const modules: Record<string, { exports: unknown }> = {};@@ -16,21 +16,21 @@ async function ScriptContext(startNoteId: string, allNoteIds: string[], originEnreturn {modules: modules,- notes: utils.toObject(allNotes, note => [note.noteId, note]),- apis: utils.toObject(allNotes, note => [note.noteId, new FrontendScriptApi(startNote, note, originEntity, $container)]),+ notes: utils.toObject(allNotes, (note) => [note.noteId, note]),+ apis: utils.toObject(allNotes, (note) => [note.noteId, new FrontendScriptApi(startNote, note, originEntity, $container)]),require: (moduleNoteIds: string) => {return (moduleName: string) => {- const candidates = allNotes.filter(note => moduleNoteIds.includes(note.noteId));- const note = candidates.find(c => c.title === moduleName);+ const candidates = allNotes.filter((note) => moduleNoteIds.includes(note.noteId));+ const note = candidates.find((c) => c.title === moduleName);if (!note) {throw new Error(`Could not find module note ${moduleName}`);}return modules[note.noteId].exports;- }+ };}};}-export default ScriptContext;\ No newline at end of file+export default ScriptContext;diff --git a/src/public/app/services/search.ts b/src/public/app/services/search.tsindex f3ca50d754..bc516ecb47 100644--- a/src/public/app/services/search.ts+++ b/src/public/app/services/search.ts@@ -14,4 +14,4 @@ async function searchForNotes(searchString: string) {export default {searchForNoteIds,searchForNotes-}+};diff --git a/src/public/app/services/server.ts b/src/public/app/services/server.tsindex f1499c660e..e15e3ba88f 100644--- a/src/public/app/services/server.ts+++ b/src/public/app/services/server.ts@@ -1,4 +1,4 @@-import utils from './utils.js';+import utils from "./utils.js";import ValidationError from "./validation_error.js";type Headers = Record<string, string | null | undefined>;@@ -28,16 +28,16 @@ export interface StandardResponse {}async function getHeaders(headers?: Headers) {- const appContext = (await import('../components/app_context.js')).default;+ const appContext = (await import("../components/app_context.js")).default;const activeNoteContext = appContext.tabManager ? appContext.tabManager.getActiveContext() : null;// headers need to be lowercase because node.js automatically converts them to lower case// also avoiding using underscores instead of dashes since nginx filters them out by defaultconst allHeaders: Headers = {- 'trilium-component-id': glob.componentId,- 'trilium-local-now-datetime': utils.localNowDateTime(),- 'trilium-hoisted-note-id': activeNoteContext ? activeNoteContext.hoistedNoteId : null,- 'x-csrf-token': glob.csrfToken+ "trilium-component-id": glob.componentId,+ "trilium-local-now-datetime": utils.localNowDateTime(),+ "trilium-hoisted-note-id": activeNoteContext ? activeNoteContext.hoistedNoteId : null,+ "x-csrf-token": glob.csrfToken};for (const headerName in headers) {@@ -55,41 +55,41 @@ async function getHeaders(headers?: Headers) {}async function getWithSilentNotFound<T>(url: string, componentId?: string) {- return await call<T>('GET', url, componentId, { silentNotFound: true });+ return await call<T>("GET", url, componentId, { silentNotFound: true });}async function get<T>(url: string, componentId?: string) {- return await call<T>('GET', url, componentId);+ return await call<T>("GET", url, componentId);}async function post<T>(url: string, data?: unknown, componentId?: string) {- return await call<T>('POST', url, componentId, { data });+ return await call<T>("POST", url, componentId, { data });}async function put<T>(url: string, data?: unknown, componentId?: string) {- return await call<T>('PUT', url, componentId, { data });+ return await call<T>("PUT", url, componentId, { data });}async function patch<T>(url: string, data: unknown, componentId?: string) {- return await call<T>('PATCH', url, componentId, { data });+ return await call<T>("PATCH", url, componentId, { data });}async function remove<T>(url: string, componentId?: string) {- return await call<T>('DELETE', url, componentId);+ return await call<T>("DELETE", url, componentId);}async function upload(url: string, fileToUpload: File) {const formData = new FormData();- formData.append('upload', fileToUpload);+ formData.append("upload", fileToUpload);return await $.ajax({url: window.glob.baseApiUrl + url,headers: await getHeaders(),data: formData,- type: 'PUT',+ type: "PUT",timeout: 60 * 60 * 1000,contentType: false, // NEEDED, DON'T REMOVE THIS- processData: false, // NEEDED, DON'T REMOVE THIS+ processData: false // NEEDED, DON'T REMOVE THIS});}@@ -108,35 +108,34 @@ async function call<T>(method: string, url: string, componentId?: string, optionlet resp;const headers = await getHeaders({- 'trilium-component-id': componentId+ "trilium-component-id": componentId});- const {data} = options;+ const { data } = options;if (utils.isElectron()) {- const ipc = utils.dynamicRequire('electron').ipcRenderer;+ const ipc = utils.dynamicRequire("electron").ipcRenderer;const requestId = idCounter++;- resp = await new Promise((resolve, reject) => {+ resp = (await new Promise((resolve, reject) => {idToRequestMap[requestId] = {resolve,reject,silentNotFound: !!options.silentNotFound};- ipc.send('server-request', {+ ipc.send("server-request", {requestId: requestId,headers: headers,method: method,url: `/${window.glob.baseApiUrl}${url}`,data: data});- }) as any;- }- else {+ })) as any;+ } else {resp = await ajax(url, method, data, headers, !!options.silentNotFound);}- const maxEntityChangeIdStr = resp.headers['trilium-max-entity-change-id'];+ const maxEntityChangeIdStr = resp.headers["trilium-max-entity-change-id"];if (maxEntityChangeIdStr && maxEntityChangeIdStr.trim()) {maxKnownEntityChangeId = Math.max(maxKnownEntityChangeId, parseInt(maxEntityChangeIdStr));@@ -155,20 +154,24 @@ function ajax(url: string, method: string, data: unknown, headers: Headers, silesuccess: (body, textStatus, jqXhr) => {const respHeaders: Headers = {};- jqXhr.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(line => {- const parts = line.split(': ');- const header = parts.shift();- if (header) {- respHeaders[header] = parts.join(': ');- }- });+ jqXhr+ .getAllResponseHeaders()+ .trim()+ .split(/[\r\n]+/)+ .forEach((line) => {+ const parts = line.split(": ");+ const header = parts.shift();+ if (header) {+ respHeaders[header] = parts.join(": ");+ }+ });res({body,headers: respHeaders});},- error: async jqXhr => {+ error: async (jqXhr) => {if (jqXhr.status === 0) {// don't report requests that are rejected by the browser, usually when the user is refreshing or going to a different page.rej("rejected by browser");@@ -187,7 +190,7 @@ function ajax(url: string, method: string, data: unknown, headers: Headers, siletry {options.data = JSON.stringify(data);} catch (e) {- console.log("Can't stringify data: ", data, " because of error: ", e)+ console.log("Can't stringify data: ", data, " because of error: ", e);}options.contentType = "application/json";}@@ -197,13 +200,12 @@ function ajax(url: string, method: string, data: unknown, headers: Headers, sile}if (utils.isElectron()) {- const ipc = utils.dynamicRequire('electron').ipcRenderer;+ const ipc = utils.dynamicRequire("electron").ipcRenderer;- ipc.on('server-response', async (event: string, arg: Arg) => {+ ipc.on("server-response", async (event: string, arg: Arg) => {if (arg.statusCode >= 200 && arg.statusCode < 300) {handleSuccessfulResponse(arg);- }- else {+ } else {if (arg.statusCode === 404 && idToRequestMap[arg.requestId]?.silentNotFound) {// report nothing} else {@@ -217,7 +219,7 @@ if (utils.isElectron()) {});function handleSuccessfulResponse(arg: Arg) {- if (arg.headers['Content-Type'] === 'application/json' && typeof arg.body === "string") {+ if (arg.headers["Content-Type"] === "application/json" && typeof arg.body === "string") {arg.body = JSON.parse(arg.body);}@@ -236,19 +238,18 @@ if (utils.isElectron()) {async function reportError(method: string, url: string, statusCode: number, response: unknown) {let message = response;- if (typeof response === 'string') {+ if (typeof response === "string") {try {response = JSON.parse(response);message = (response as any).message;- }- catch (e) {}+ } catch (e) {}}const toastService = (await import("./toast.js")).default;- const messageStr = (typeof message === "string" ? message : JSON.stringify(message));+ const messageStr = typeof message === "string" ? message : JSON.stringify(message);- if ([400, 404].includes(statusCode) && response && typeof response === 'object') {+ if ([400, 404].includes(statusCode) && response && typeof response === "object") {toastService.showError(messageStr);throw new ValidationError({requestUrl: url,diff --git a/src/public/app/services/shortcuts.ts b/src/public/app/services/shortcuts.tsindex 05886bac26..65da81a0d2 100644--- a/src/public/app/services/shortcuts.ts+++ b/src/public/app/services/shortcuts.ts@@ -4,7 +4,7 @@ type ElementType = HTMLElement | Document;type Handler = (e: JQuery.TriggeredEvent<ElementType, string, ElementType, ElementType>) => void;function removeGlobalShortcut(namespace: string) {- bindGlobalShortcut('', null, namespace);+ bindGlobalShortcut("", null, namespace);}function bindGlobalShortcut(keyboardShortcut: string, handler: Handler | null, namespace: string | null = null) {@@ -15,7 +15,7 @@ function bindElShortcut($el: JQuery<ElementType>, keyboardShortcut: string, handif (utils.isDesktop()) {keyboardShortcut = normalizeShortcut(keyboardShortcut);- let eventName = 'keydown';+ let eventName = "keydown";if (namespace) {eventName += `.${namespace}`;@@ -26,7 +26,7 @@ function bindElShortcut($el: JQuery<ElementType>, keyboardShortcut: string, hand// method can be called to remove the shortcut (e.g. when keyboardShortcut label is deleted)if (keyboardShortcut) {- $el.bind(eventName, keyboardShortcut, e => {+ $el.bind(eventName, keyboardShortcut, (e) => {if (handler) {handler(e);}@@ -46,12 +46,7 @@ function normalizeShortcut(shortcut: string): string {return shortcut;}- return shortcut- .toLowerCase()- .replace("enter", "return")- .replace("delete", "del")- .replace("ctrl+alt", "alt+ctrl")- .replace("meta+alt", "alt+meta"); // alt needs to be first;+ return shortcut.toLowerCase().replace("enter", "return").replace("delete", "del").replace("ctrl+alt", "alt+ctrl").replace("meta+alt", "alt+meta"); // alt needs to be first;}export default {@@ -59,4 +54,4 @@ export default {bindElShortcut,removeGlobalShortcut,normalizeShortcut-}+};diff --git a/src/public/app/services/spaced_update.ts b/src/public/app/services/spaced_update.tsindex 9913204231..e56d6ffa29 100644--- a/src/public/app/services/spaced_update.ts+++ b/src/public/app/services/spaced_update.ts@@ -27,8 +27,7 @@ export default class SpacedUpdate {try {await this.updater();- }- catch (e) {+ } catch (e) {this.changed = true;throw e;@@ -53,8 +52,7 @@ export default class SpacedUpdate {this.updater();this.lastUpdated = Date.now();this.changed = false;- }- else {+ } else {// update isn't triggered but changes are still pending, so we need to schedule another checkthis.scheduleUpdate();}@@ -65,8 +63,7 @@ export default class SpacedUpdate {try {await callback();- }- finally {+ } finally {this.changeForbidden = false;}}diff --git a/src/public/app/services/sync.ts b/src/public/app/services/sync.tsindex 7c953fb84e..c06a2077d7 100644--- a/src/public/app/services/sync.ts+++ b/src/public/app/services/sync.ts@@ -1,5 +1,5 @@-import { t } from './i18n.js';-import server from './server.js';+import { t } from "./i18n.js";+import server from "./server.js";import toastService from "./toast.js";// TODO: De-duplicate with server once we have a commons.@@ -10,17 +10,16 @@ interface SyncResult {}async function syncNow(ignoreNotConfigured = false) {- const result = await server.post<SyncResult>('sync/now');+ const result = await server.post<SyncResult>("sync/now");if (result.success) {toastService.showMessage(t("sync.finished-successfully"));- }- else {+ } else {if (result.message.length > 200) {result.message = `${result.message.substr(0, 200)}...`;}- if (!ignoreNotConfigured || result.errorCode !== 'NOT_CONFIGURED') {+ if (!ignoreNotConfigured || result.errorCode !== "NOT_CONFIGURED") {toastService.showError(t("sync.failed", { message: result.message }));}}diff --git a/src/public/app/services/syntax_highlight.ts b/src/public/app/services/syntax_highlight.tsindex 68ca07ced3..ae2fbde722 100644--- a/src/public/app/services/syntax_highlight.ts+++ b/src/public/app/services/syntax_highlight.ts@@ -8,7 +8,7 @@ export function getStylesheetUrl(theme: string) {}const defaultPrefix = "default:";- if (theme.startsWith(defaultPrefix)) {+ if (theme.startsWith(defaultPrefix)) {return `${window.glob.assetPath}/node_modules/@highlightjs/cdn-assets/styles/${theme.substr(defaultPrefix.length)}.min.css`;}@@ -17,13 +17,13 @@ export function getStylesheetUrl(theme: string) {/*** Identifies all the code blocks (as `pre code`) under the specified hierarchy and uses the highlight.js library to obtain the highlighted text which is then applied on to the code blocks.- *+ ** @param $container the container under which to look for code blocks and to apply syntax highlighting to them.*/export async function applySyntaxHighlight($container: JQuery<HTMLElement>) {if (!isSyntaxHighlightEnabled()) {return;- }+ }const codeBlocks = $container.find("pre code");for (const codeBlock of codeBlocks) {@@ -31,7 +31,7 @@ export async function applySyntaxHighlight($container: JQuery<HTMLElement>) {if (!normalizedMimeType) {continue;}-+applySingleBlockSyntaxHighlight($(codeBlock), normalizedMimeType);}}@@ -58,8 +58,8 @@ export async function applySingleBlockSyntaxHighlight($codeBlock: JQuery<HTMLEleconsole.warn(`Unknown mime type: ${normalizedMimeType}.`);}}-- if (highlightedText) {++ if (highlightedText) {$codeBlock.html(highlightedText.value);}}@@ -75,7 +75,7 @@ export function isSyntaxHighlightEnabled() {/*** Given a HTML element, tries to extract the `language-` class name out of it.- *+ ** @param el the HTML element from which to extract the language tag.* @returns the normalized MIME type (e.g. `text-css` instead of `language-text-css`).*/@@ -88,4 +88,4 @@ function extractLanguageFromClassList(el: HTMLElement) {}return null;-}\ No newline at end of file+}diff --git a/src/public/app/services/toast.ts b/src/public/app/services/toast.tsindex 9b6e4f64ce..18cc876a9b 100644--- a/src/public/app/services/toast.ts+++ b/src/public/app/services/toast.ts@@ -25,8 +25,8 @@ function toast(options: ToastOptions) {</div>`);- $toast.find('.toast-title').text(options.title);- $toast.find('.toast-body').html(options.message);+ $toast.find(".toast-title").text(options.title);+ $toast.find(".toast-body").html(options.message);if (options.id) {$toast.attr("id", `toast-${options.id}`);@@ -39,7 +39,7 @@ function toast(options: ToastOptions) {autohide: !!options.autohide});- $toast.on('hidden.bs.toast', e => e.target.remove());+ $toast.on("hidden.bs.toast", (e) => e.target.remove());$toast.toast("show");@@ -50,9 +50,8 @@ function showPersistent(options: ToastOptions) {let $toast = $(`#toast-${options.id}`);if ($toast.length > 0) {- $toast.find('.toast-body').html(options.message);- }- else {+ $toast.find(".toast-body").html(options.message);+ } else {options.autohide = false;$toast = toast(options);@@ -90,7 +89,7 @@ function showError(message: string, delay = 10000) {toast({title: "Error",- icon: 'alert',+ icon: "alert",message: message,autohide: true,delay@@ -102,7 +101,7 @@ function showErrorTitleAndMessage(title: string, message: string, delay = 10000)toast({title: title,- icon: 'alert',+ icon: "alert",message: message,autohide: true,delay@@ -123,4 +122,4 @@ export default {throwError,showPersistent,closePersistent-}+};diff --git a/src/public/app/services/tree.ts b/src/public/app/services/tree.tsindex 090b1b362c..0a56771a4f 100644--- a/src/public/app/services/tree.ts+++ b/src/public/app/services/tree.ts@@ -1,7 +1,7 @@-import ws from './ws.js';-import utils from './utils.js';-import froca from './froca.js';-import hoistedNoteService from '../services/hoisted_note.js';+import ws from "./ws.js";+import utils from "./utils.js";+import froca from "./froca.js";+import hoistedNoteService from "../services/hoisted_note.js";import appContext from "../components/app_context.js";export interface Node {@@ -9,19 +9,19 @@ export interface Node {getParent(): Node;getChildren(): Node[];folder: boolean;- renderTitle(): void,+ renderTitle(): void;data: {noteId?: string;isProtected?: boolean;branchId: string;noteType: string;- }+ };}/*** @returns {string|null}*/-async function resolveNotePath(notePath: string, hoistedNoteId = 'root') {+async function resolveNotePath(notePath: string, hoistedNoteId = "root") {const runPath = await resolveNotePathToSegments(notePath, hoistedNoteId);return runPath ? runPath.join("/") : null;@@ -32,7 +32,7 @@ async function resolveNotePath(notePath: string, hoistedNoteId = 'root') {* notePath as possible. Part of the path might not be valid because of note moving (which causes* path change) or other corruption, in that case, this will try to get some other valid path to the correct note.*/-async function resolveNotePathToSegments(notePath: string, hoistedNoteId = 'root', logErrors = true) {+async function resolveNotePathToSegments(notePath: string, hoistedNoteId = "root", logErrors = true) {utils.assertArguments(notePath);// we might get notePath with the params suffix, remove it if present@@ -45,7 +45,7 @@ async function resolveNotePathToSegments(notePath: string, hoistedNoteId = 'rootconst path = notePath.split("/").reverse();if (!path.includes("root")) {- path.push('root');+ path.push("root");}const effectivePathSegments = [];@@ -82,13 +82,16 @@ async function resolveNotePathToSegments(notePath: string, hoistedNoteId = 'rootreturn null;}- if (!parents.some(p => p.noteId === parentNoteId)) {+ if (!parents.some((p) => p.noteId === parentNoteId)) {if (logErrors) {const parent = froca.getNoteFromCache(parentNoteId);- console.debug(utils.now(), `Did not find parent ${parentNoteId} (${parent ? parent.title : 'n/a'})- for child ${childNoteId} (${child.title}), available parents: ${parents.map(p => `${p.noteId} (${p.title})`)}.- You can ignore this message as it is mostly harmless.`);+ console.debug(+ utils.now(),+ `Did not find parent ${parentNoteId} (${parent ? parent.title : "n/a"})+ for child ${childNoteId} (${child.title}), available parents: ${parents.map((p) => `${p.noteId} (${p.title})`)}.+ You can ignore this message as it is mostly harmless.`+ );}const bestNotePath = child.getBestNotePath(hoistedNoteId);@@ -113,8 +116,7 @@ async function resolveNotePathToSegments(notePath: string, hoistedNoteId = 'rootif (effectivePathSegments.includes(hoistedNoteId)) {return effectivePathSegments;- }- else {+ } else {const noteId = getNoteIdFromUrl(notePath);if (!noteId) {throw new Error(`Unable to find note with ID: ${noteId}.`);@@ -134,16 +136,16 @@ async function resolveNotePathToSegments(notePath: string, hoistedNoteId = 'root}}-ws.subscribeToMessages(message => {- if (message.type === 'openNote') {- appContext.tabManager.activateOrOpenNote(message.noteId);+ws.subscribeToMessages((message) => {+ if (message.type === "openNote") {+ appContext.tabManager.activateOrOpenNote(message.noteId);- if (utils.isElectron()) {- const currentWindow = utils.dynamicRequire('@electron/remote').getCurrentWindow();+ if (utils.isElectron()) {+ const currentWindow = utils.dynamicRequire("@electron/remote").getCurrentWindow();- currentWindow.show();- }- }+ currentWindow.show();+ }+ }});function getParentProtectedStatus(node: Node) {@@ -162,7 +164,7 @@ function getNoteIdFromUrl(urlOrNotePath: string | undefined) {}async function getBranchIdFromUrl(urlOrNotePath: string) {- const {noteId, parentNoteId} = getNoteIdAndParentIdFromUrl(urlOrNotePath);+ const { noteId, parentNoteId } = getNoteIdAndParentIdFromUrl(urlOrNotePath);if (!parentNoteId) {return null;}@@ -177,15 +179,15 @@ function getNoteIdAndParentIdFromUrl(urlOrNotePath: string) {const [notePath] = urlOrNotePath.split("?");- if (notePath === 'root') {+ if (notePath === "root") {return {- noteId: 'root',- parentNoteId: 'none'+ noteId: "root",+ parentNoteId: "none"};}- let parentNoteId = 'root';- let noteId = '';+ let parentNoteId = "root";+ let noteId = "";if (notePath) {const segments = notePath.split("/");@@ -230,7 +232,7 @@ async function getNoteTitle(noteId: string, parentNoteId: string | null = null)return "[not found]";}- let {title} = note;+ let { title } = note;if (parentNoteId !== null) {const branchId = note.parentToBranch[parentNoteId];@@ -250,17 +252,17 @@ async function getNoteTitle(noteId: string, parentNoteId: string | null = null)async function getNotePathTitleComponents(notePath: string) {const titleComponents = [];- if (notePath.startsWith('root/')) {+ if (notePath.startsWith("root/")) {notePath = notePath.substr(5);}// special case when we want just root's title- if (notePath === 'root') {+ if (notePath === "root") {titleComponents.push(await getNoteTitle(notePath));} else {- let parentNoteId = 'root';+ let parentNoteId = "root";- for (const noteId of notePath.split('/')) {+ for (const noteId of notePath.split("/")) {titleComponents.push(await getNoteTitle(noteId, parentNoteId));parentNoteId = noteId;@@ -275,7 +277,7 @@ async function getNotePathTitle(notePath: string) {const titlePath = await getNotePathTitleComponents(notePath);- return titlePath.join(' / ');+ return titlePath.join(" / ");}async function getNoteTitleWithPathAsSuffix(notePath: string) {@@ -290,9 +292,7 @@ async function getNoteTitleWithPathAsSuffix(notePath: string) {const title = titleComponents[titleComponents.length - 1];const path = titleComponents.slice(0, titleComponents.length - 1);- const $titleWithPath = $('<span class="note-title-with-path">')- .append($('<span class="note-title">').text(title));-+ const $titleWithPath = $('<span class="note-title-with-path">').append($('<span class="note-title">').text(title));$titleWithPath.append(formatNotePath(path));@@ -303,7 +303,6 @@ function formatNotePath(path: string[]) {const $notePath = $('<span class="note-path">');if (path.length > 0) {-$notePath.append($(`<span class="path-bracket"> (</span>)`));for (let segmentIndex = 0; segmentIndex < path.length; segmentIndex++) {@@ -324,8 +323,6 @@ function isNotePathInHiddenSubtree(notePath: string) {return notePath?.includes("root/_hidden");}--export default {resolveNotePath,resolveNotePathToSegments,diff --git a/src/public/app/services/utils.ts b/src/public/app/services/utils.tsindex fa93e47dd9..3d1d72969c 100644--- a/src/public/app/services/utils.ts+++ b/src/public/app/services/utils.ts@@ -11,8 +11,7 @@ function reloadFrontendApp(reason?: string) {function parseDate(str: string) {try {return new Date(Date.parse(str));- }- catch (e: any) {+ } catch (e: any) {throw new Error(`Can't parse date from '${str}': ${e.message} ${e.stack}`);}}@@ -34,26 +33,26 @@ function formatTimeInterval(ms: number) {const minutes = Math.floor(seconds / 60);const hours = Math.floor(minutes / 60);const days = Math.floor(hours / 24);- const plural = (count: number, name: string) => `${count} ${name}${count > 1 ? 's' : ''}`;+ const plural = (count: number, name: string) => `${count} ${name}${count > 1 ? "s" : ""}`;const segments = [];if (days > 0) {- segments.push(plural(days, 'day'));+ segments.push(plural(days, "day"));}if (days < 2) {if (hours % 24 > 0) {- segments.push(plural(hours % 24, 'hour'));+ segments.push(plural(hours % 24, "hour"));}if (hours < 4) {if (minutes % 60 > 0) {- segments.push(plural(minutes % 60, 'minute'));+ segments.push(plural(minutes % 60, "minute"));}if (minutes < 5) {if (seconds % 60 > 0) {- segments.push(plural(seconds % 60, 'second'));+ segments.push(plural(seconds % 60, "second"));}}}@@ -80,7 +79,7 @@ function formatDateTime(date: Date) {}function localNowDateTime() {- return dayjs().format('YYYY-MM-DD HH:mm:ss.SSSZZ');+ return dayjs().format("YYYY-MM-DD HH:mm:ss.SSSZZ");}function now() {@@ -95,12 +94,11 @@ function isElectron() {}function isMac() {- return navigator.platform.indexOf('Mac') > -1;+ return navigator.platform.indexOf("Mac") > -1;}function isCtrlKey(evt: KeyboardEvent | MouseEvent | JQuery.ClickEvent) {- return (!isMac() && evt.ctrlKey)- || (isMac() && evt.metaKey);+ return (!isMac() && evt.ctrlKey) || (isMac() && evt.metaKey);}function assertArguments(...args: string[]) {@@ -112,18 +110,18 @@ function assertArguments(...args: string[]) {}const entityMap: Record<string, string> = {- '&': '&',- '<': '<',- '>': '>',- '"': '"',- "'": ''',- '/': '/',- '`': '`',- '=': '='+ "&": "&",+ "<": "<",+ ">": ">",+ '"': """,+ "'": "'",+ "/": "/",+ "`": "`",+ "=": "="};function escapeHtml(str: string) {- return str.replace(/[&<>"'`=\/]/g, s => entityMap[s]);+ return str.replace(/[&<>"'`=\/]/g, (s) => entityMap[s]);}function formatSize(size: number) {@@ -131,8 +129,7 @@ function formatSize(size: number) {if (size < 1024) {return `${size} KiB`;- }- else {+ } else {return `${Math.round(size / 102.4) / 10} MiB`;}}@@ -161,15 +158,19 @@ function randomString(len: number) {}function isMobile() {- return window.glob?.device === "mobile"+ return (+ window.glob?.device === "mobile" ||// window.glob.device is not available in setup- || (!window.glob?.device && /Mobi/.test(navigator.userAgent));+ (!window.glob?.device && /Mobi/.test(navigator.userAgent))+ );}function isDesktop() {- return window.glob?.device === "desktop"+ return (+ window.glob?.device === "desktop" ||// window.glob.device is not available in setup- || (!window.glob?.device && !/Mobi/.test(navigator.userAgent));+ (!window.glob?.device && !/Mobi/.test(navigator.userAgent))+ );}/**@@ -192,7 +193,7 @@ function getMimeTypeClass(mime: string) {return "";}- const semicolonIdx = mime.indexOf(';');+ const semicolonIdx = mime.indexOf(";");if (semicolonIdx !== -1) {// stripping everything following the semicolon@@ -227,9 +228,7 @@ function focusSavedElement() {// must handle CKEditor separately because of this bug: https://github.com/ckeditor/ckeditor5/issues/607// the bug manifests itself in resetting the cursor position to the first character - jumping above- const editor = $lastFocusedElement- .closest('.ck-editor__editable')- .prop('ckeditorInstance');+ const editor = $lastFocusedElement.closest(".ck-editor__editable").prop("ckeditorInstance");if (editor) {editor.editing.view.focus();@@ -254,7 +253,7 @@ async function openDialog($dialog: JQuery<HTMLElement>, closeActDialog = true) {//@ts-ignorebootstrap.Modal.getOrCreateInstance($dialog[0]).show();- $dialog.on('hidden.bs.modal', () => {+ $dialog.on("hidden.bs.modal", () => {const $autocompleteEl = $(".aa-input");if ("autocomplete" in $autocompleteEl) {$autocompleteEl.autocomplete("close");@@ -276,22 +275,24 @@ async function openDialog($dialog: JQuery<HTMLElement>, closeActDialog = true) {function isHtmlEmpty(html: string) {if (!html) {return true;- } else if (typeof html !== 'string') {+ } else if (typeof html !== "string") {logError(`Got object of type '${typeof html}' where string was expected.`);return false;}html = html.toLowerCase();- return !html.includes('<img')- && !html.includes('<section')+ return (+ !html.includes("<img") &&+ !html.includes("<section") &&// the line below will actually attempt to load images so better to check for images first- && $("<div>").html(html).text().trim().length === 0;+ $("<div>").html(html).text().trim().length === 0+ );}async function clearBrowserCache() {if (isElectron()) {- const win = dynamicRequire('@electron/remote').getCurrentWindow();+ const win = dynamicRequire("@electron/remote").getCurrentWindow();await win.webContents.session.clearCache();}}@@ -304,16 +305,16 @@ function copySelectionToClipboard() {}function dynamicRequire(moduleName: string) {- if (typeof __non_webpack_require__ !== 'undefined') {+ if (typeof __non_webpack_require__ !== "undefined") {return __non_webpack_require__(moduleName);- }- else {+ } else {return require(moduleName);}}function timeLimit<T>(promise: Promise<T>, limitMs: number, errorMessage?: string) {- if (!promise || !promise.then) { // it's not actually a promise+ if (!promise || !promise.then) {+ // it's not actually a promisereturn promise;}@@ -323,7 +324,7 @@ function timeLimit<T>(promise: Promise<T>, limitMs: number, errorMessage?: strinreturn new Promise<T>((res, rej) => {let resolved = false;- promise.then(result => {+ promise.then((result) => {resolved = true;res(result);@@ -339,8 +340,8 @@ function timeLimit<T>(promise: Promise<T>, limitMs: number, errorMessage?: strinfunction initHelpDropdown($el: JQuery<HTMLElement>) {// stop inside clicks from closing the menu- const $dropdownMenu = $el.find('.help-dropdown .dropdown-menu');- $dropdownMenu.on('click', e => e.stopPropagation());+ const $dropdownMenu = $el.find(".help-dropdown .dropdown-menu");+ $dropdownMenu.on("click", (e) => e.stopPropagation());// previous propagation stop will also block help buttons from being opened, so we need to re-init for this elementinitHelpButtons($dropdownMenu);@@ -354,21 +355,21 @@ function openHelp($button: JQuery<HTMLElement>) {if (helpPage) {const url = wikiBaseUrl + helpPage;- window.open(url, '_blank');+ window.open(url, "_blank");}}function initHelpButtons($el: JQuery<HTMLElement> | JQuery<Window>) {// for some reason, the .on(event, listener, handler) does not work here (e.g. Options -> Sync -> Help button)// so we do it manually- $el.on("click", e => {+ $el.on("click", (e) => {const $helpButton = $(e.target).closest("[data-help-page]");openHelp($helpButton);});}function filterAttributeName(name: string) {- return name.replace(/[^\p{L}\p{N}_:]/ug, "");+ return name.replace(/[^\p{L}\p{N}_:]/gu, "");}const ATTR_NAME_MATCHER = new RegExp("^[\\p{L}\\p{N}_:]+$", "u");@@ -393,12 +394,12 @@ function areObjectsEqual(...args: unknown[]) {let leftChain: Object[];let rightChain: Object[];- function compare2Objects (x: unknown, y: unknown) {+ function compare2Objects(x: unknown, y: unknown) {let p;// remember that NaN === NaN returns false// and isNaN(undefined) returns true- if (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)) {+ if (typeof x === "number" && typeof y === "number" && isNaN(x) && isNaN(y)) {return true;}@@ -412,11 +413,13 @@ function areObjectsEqual(...args: unknown[]) {// Works in case when functions are created in constructor.// Comparing dates is a common scenario. Another built-ins?// We can even handle functions passed across iframes- if ((typeof x === 'function' && typeof y === 'function') ||+ if (+ (typeof x === "function" && typeof y === "function") ||(x instanceof Date && y instanceof Date) ||(x instanceof RegExp && y instanceof RegExp) ||(x instanceof String && y instanceof String) ||- (x instanceof Number && y instanceof Number)) {+ (x instanceof Number && y instanceof Number)+ ) {return x.toString() === y.toString();}@@ -447,8 +450,7 @@ function areObjectsEqual(...args: unknown[]) {for (p in y) {if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {return false;- }- else if (typeof (y as any)[p] !== typeof (x as any)[p]) {+ } else if (typeof (y as any)[p] !== typeof (x as any)[p]) {return false;}}@@ -456,15 +458,13 @@ function areObjectsEqual(...args: unknown[]) {for (p in x) {if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {return false;- }- else if (typeof (y as any)[p] !== typeof (x as any)[p]) {+ } else if (typeof (y as any)[p] !== typeof (x as any)[p]) {return false;}- switch (typeof ((x as any)[p])) {- case 'object':- case 'function':-+ switch (typeof (x as any)[p]) {+ case "object":+ case "function":leftChain.push(x);rightChain.push(y);@@ -493,7 +493,6 @@ function areObjectsEqual(...args: unknown[]) {}for (i = 1, l = arguments.length; i < l; i++) {-leftChain = []; //Todo: this can be cachedrightChain = [];@@ -531,11 +530,11 @@ function createImageSrcUrl(note: { noteId: string; title: string }) {*/function downloadSvg(nameWithoutExtension: string, svgContent: string) {const filename = `${nameWithoutExtension}.svg`;- const element = document.createElement('a');- element.setAttribute('href', `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgContent)}`);- element.setAttribute('download', filename);+ const element = document.createElement("a");+ element.setAttribute("href", `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgContent)}`);+ element.setAttribute("download", filename);- element.style.display = 'none';+ element.style.display = "none";document.body.appendChild(element);element.click();@@ -555,13 +554,12 @@ function downloadSvg(nameWithoutExtension: string, svgContent: string) {* @returns*/function compareVersions(v1: string, v2: string): number {-// Remove 'v' prefix and everything after dash if present- v1 = v1.replace(/^v/, '').split('-')[0];- v2 = v2.replace(/^v/, '').split('-')[0];+ v1 = v1.replace(/^v/, "").split("-")[0];+ v2 = v2.replace(/^v/, "").split("-")[0];- const v1parts = v1.split('.').map(Number);- const v2parts = v2.split('.').map(Number);+ const v1parts = v1.split(".").map(Number);+ const v2parts = v2.split(".").map(Number);// Pad shorter version with zeroswhile (v1parts.length < 3) v1parts.push(0);@@ -593,10 +591,7 @@ function isUpdateAvailable(latestVersion: string, currentVersion: string): boole}function isLaunchBarConfig(noteId: string) {- return [- "_lbRoot", "_lbAvailableLaunchers", "_lbVisibleLaunchers",- "_lbMobileRoot", "_lbMobileAvailableLaunchers", "_lbMobileVisibleLaunchers"- ].includes(noteId);+ return ["_lbRoot", "_lbAvailableLaunchers", "_lbVisibleLaunchers", "_lbMobileRoot", "_lbMobileAvailableLaunchers", "_lbMobileVisibleLaunchers"].includes(noteId);}export default {diff --git a/src/public/app/services/validation_error.ts b/src/public/app/services/validation_error.tsindex a37841a891..d04edc76f3 100644--- a/src/public/app/services/validation_error.ts+++ b/src/public/app/services/validation_error.ts@@ -4,4 +4,4 @@ export default class ValidationError {(this as any)[key] = resp[key];}}-}\ No newline at end of file+}diff --git a/src/public/app/services/ws.ts b/src/public/app/services/ws.tsindex 061673470b..d6c392b5c3 100644--- a/src/public/app/services/ws.ts+++ b/src/public/app/services/ws.ts@@ -1,11 +1,11 @@-import utils from './utils.js';+import utils from "./utils.js";import toastService from "./toast.js";import server from "./server.js";import options from "./options.js";import frocaUpdater from "./froca_updater.js";import appContext from "../components/app_context.js";-import { t } from './i18n.js';-import { EntityChange } from '../server_types.js';+import { t } from "./i18n.js";+import { EntityChange } from "../server_types.js";type MessageHandler = (message: any) => void;const messageHandlers: MessageHandler[] = [];@@ -21,11 +21,13 @@ function logError(message: string) {console.error(utils.now(), message); // needs to be separate from .trace()if (ws && ws.readyState === 1) {- ws.send(JSON.stringify({- type: 'log-error',- error: message,- stack: new Error().stack- }));+ ws.send(+ JSON.stringify({+ type: "log-error",+ error: message,+ stack: new Error().stack+ })+ );}}@@ -33,10 +35,12 @@ function logInfo(message: string) {console.log(utils.now(), message);if (ws && ws.readyState === 1) {- ws.send(JSON.stringify({- type: 'log-info',- info: message- }));+ ws.send(+ JSON.stringify({+ type: "log-info",+ info: message+ })+ );}}@@ -54,9 +58,7 @@ let consumeQueuePromise: Promise<void> | null = null;const processedEntityChangeIds = new Set();function logRows(entityChanges: EntityChange[]) {- const filteredRows = entityChanges.filter(row =>- !processedEntityChangeIds.has(row.id)- && (row.entityName !== 'options' || row.entityId !== 'openNoteContexts'));+ const filteredRows = entityChanges.filter((row) => !processedEntityChangeIds.has(row.id) && (row.entityName !== "options" || row.entityId !== "openNoteContexts"));if (filteredRows.length > 0) {console.debug(utils.now(), "Frontend update data: ", filteredRows);@@ -111,28 +113,21 @@ async function handleMessage(event: MessageEvent<any>) {messageHandler(message);}- if (message.type === 'ping') {+ if (message.type === "ping") {lastPingTs = Date.now();- }- else if (message.type === 'reload-frontend') {+ } else if (message.type === "reload-frontend") {utils.reloadFrontendApp("received request from backend to reload frontend");- }- else if (message.type === 'frontend-update') {+ } else if (message.type === "frontend-update") {await executeFrontendUpdate(message.data.entityChanges);- }- else if (message.type === 'sync-hash-check-failed') {+ } else if (message.type === "sync-hash-check-failed") {toastService.showError(t("ws.sync-check-failed"), 60000);- }- else if (message.type === 'consistency-checks-failed') {+ } else if (message.type === "consistency-checks-failed") {toastService.showError(t("ws.consistency-checks-failed"), 50 * 60000);- }- else if (message.type === 'api-log-messages') {- appContext.triggerEvent("apiLogMessages", {noteId: message.noteId, messages: message.messages});- }- else if (message.type === 'toast') {+ } else if (message.type === "api-log-messages") {+ appContext.triggerEvent("apiLogMessages", { noteId: message.noteId, messages: message.messages });+ } else if (message.type === "toast") {toastService.showMessage(message.message);- }- else if (message.type === 'execute-script') {+ } else if (message.type === "execute-script") {// TODO: Remove after porting the file// @ts-ignoreconst bundleService = (await import("../services/bundle.js")).default as any;@@ -163,7 +158,7 @@ function waitForEntityChangeId(desiredEntityChangeId: number) {desiredEntityChangeId: desiredEntityChangeId,resolvePromise: res,start: Date.now()- })+ });});}@@ -172,15 +167,17 @@ function waitForMaxKnownEntityChangeId() {}function checkEntityChangeIdListeners() {- entityChangeIdReachedListeners- .filter(l => l.desiredEntityChangeId <= lastProcessedEntityChangeId)- .forEach(l => l.resolvePromise());+ entityChangeIdReachedListeners.filter((l) => l.desiredEntityChangeId <= lastProcessedEntityChangeId).forEach((l) => l.resolvePromise());- entityChangeIdReachedListeners = entityChangeIdReachedListeners- .filter(l => l.desiredEntityChangeId > lastProcessedEntityChangeId);+ entityChangeIdReachedListeners = entityChangeIdReachedListeners.filter((l) => l.desiredEntityChangeId > lastProcessedEntityChangeId);- entityChangeIdReachedListeners.filter(l => Date.now() > l.start - 60000)- .forEach(l => console.log(`Waiting for entityChangeId ${l.desiredEntityChangeId} while last processed is ${lastProcessedEntityChangeId} (last accepted ${lastAcceptedEntityChangeId}) for ${Math.floor((Date.now() - l.start) / 1000)}s`));+ entityChangeIdReachedListeners+ .filter((l) => Date.now() > l.start - 60000)+ .forEach((l) =>+ console.log(+ `Waiting for entityChangeId ${l.desiredEntityChangeId} while last processed is ${lastProcessedEntityChangeId} (last accepted ${lastAcceptedEntityChangeId}) for ${Math.floor((Date.now() - l.start) / 1000)}s`+ )+ );}async function consumeFrontendUpdateData() {@@ -188,20 +185,18 @@ async function consumeFrontendUpdateData() {const allEntityChanges = frontendUpdateDataQueue;frontendUpdateDataQueue = [];- const nonProcessedEntityChanges = allEntityChanges.filter(ec => !processedEntityChangeIds.has(ec.id));+ const nonProcessedEntityChanges = allEntityChanges.filter((ec) => !processedEntityChangeIds.has(ec.id));try {await utils.timeLimit(frocaUpdater.processEntityChanges(nonProcessedEntityChanges), 30000);- }- catch (e: any) {+ } catch (e: any) {logError(`Encountered error ${e.message}: ${e.stack}, reloading frontend.`);- if (!glob.isDev && !options.is('debugModeEnabled')) {+ if (!glob.isDev && !options.is("debugModeEnabled")) {// if there's an error in updating the frontend, then the easy option to recover is to reload the frontend completelyutils.reloadFrontendApp();- }- else {+ } else {console.log("nonProcessedEntityChanges causing the timeout", nonProcessedEntityChanges);toastService.showError(t("ws.encountered-error", { message: e.message }));@@ -235,16 +230,20 @@ function connectWebSocket() {async function sendPing() {if (Date.now() - lastPingTs > 30000) {- console.log(utils.now(), "Lost websocket connection to the backend. If you keep having this issue repeatedly, you might want to check your reverse proxy (nginx, apache) configuration and allow/unblock WebSocket.");+ console.log(+ utils.now(),+ "Lost websocket connection to the backend. If you keep having this issue repeatedly, you might want to check your reverse proxy (nginx, apache) configuration and allow/unblock WebSocket."+ );}if (ws.readyState === ws.OPEN) {- ws.send(JSON.stringify({- type: 'ping',- lastEntityChangeId: lastAcceptedEntityChangeId- }));- }- else if (ws.readyState === ws.CLOSED || ws.readyState === ws.CLOSING) {+ ws.send(+ JSON.stringify({+ type: "ping",+ lastEntityChangeId: lastAcceptedEntityChangeId+ })+ );+ } else if (ws.readyState === ws.CLOSED || ws.readyState === ws.CLOSING) {console.log(utils.now(), "WS closed or closing, trying to reconnect");ws = connectWebSocket();@@ -265,4 +264,3 @@ export default {waitForMaxKnownEntityChangeId,getMaxKnownEntityChangeSyncId: () => lastAcceptedEntityChangeSyncId};-diff --git a/src/public/app/setup.js b/src/public/app/setup.jsindex c40d0fb8ee..0c12534a81 100644--- a/src/public/app/setup.js+++ b/src/public/app/setup.js@@ -1,5 +1,5 @@import utils from "./services/utils.js";-import macInit from './services/mac_init.js';+import macInit from "./services/mac_init.js";macInit.init();@@ -26,14 +26,13 @@ function SetupModel() {this.setupTypeSelected = () => !!this.setupType();this.selectSetupType = () => {- if (this.setupType() === 'new-document') {- this.step('new-document-in-progress');+ if (this.setupType() === "new-document") {+ this.step("new-document-in-progress");- $.post('api/setup/new-document').then(() => {+ $.post("api/setup/new-document").then(() => {window.location.replace("./setup");});- }- else {+ } else {this.step(this.setupType());}};@@ -60,39 +59,36 @@ function SetupModel() {}// not using server.js because it loads too many dependencies- const resp = await $.post('api/setup/sync-from-server', {+ const resp = await $.post("api/setup/sync-from-server", {syncServerHost: syncServerHost,syncProxy: syncProxy,password: password});- if (resp.result === 'success') {- this.step('sync-in-progress');+ if (resp.result === "success") {+ this.step("sync-in-progress");setInterval(checkOutstandingSyncs, 1000);hideAlert();- }- else {+ } else {showAlert(`Sync setup failed: ${resp.error}`);}};}async function checkOutstandingSyncs() {- const { outstandingPullCount, initialized } = await $.get('api/sync/stats');+ const { outstandingPullCount, initialized } = await $.get("api/sync/stats");if (initialized) {if (utils.isElectron()) {- const remote = utils.dynamicRequire('@electron/remote');+ const remote = utils.dynamicRequire("@electron/remote");remote.app.relaunch();remote.app.exit(0);- }- else {+ } else {utils.reloadFrontendApp();}- }- else {+ } else {$("#outstanding-syncs").html(outstandingPullCount);}}@@ -106,6 +102,6 @@ function hideAlert() {$("#alert").hide();}-ko.applyBindings(new SetupModel(), document.getElementById('setup-dialog'));+ko.applyBindings(new SetupModel(), document.getElementById("setup-dialog"));$("#setup-dialog").show();diff --git a/src/public/app/share.js b/src/public/app/share.jsindex 03ad925154..3c3282497a 100644--- a/src/public/app/share.js+++ b/src/public/app/share.js@@ -13,11 +13,15 @@ async function fetchNote(noteId = null) {return await resp.json();}-document.addEventListener('DOMContentLoaded', () => {- const toggleMenuButton = document.getElementById('toggleMenuButton');- const layout = document.getElementById('layout');+document.addEventListener(+ "DOMContentLoaded",+ () => {+ const toggleMenuButton = document.getElementById("toggleMenuButton");+ const layout = document.getElementById("layout");- if (toggleMenuButton && layout) {- toggleMenuButton.addEventListener('click', () => layout.classList.toggle('showMenu'));- }-}, false);+ if (toggleMenuButton && layout) {+ toggleMenuButton.addEventListener("click", () => layout.classList.toggle("showMenu"));+ }+ },+ false+);diff --git a/src/public/app/utils/formatters.ts b/src/public/app/utils/formatters.tsindex 398aa678b0..755cc8153c 100644--- a/src/public/app/utils/formatters.ts+++ b/src/public/app/utils/formatters.ts@@ -16,20 +16,19 @@ export function formatDateTime(date: string | Date | number, dateStyle: DateTime} else {// Invalid typethrow new TypeError(`Invalid type for the "date" argument.`);- };+ }if (timeStyle !== "none" && dateStyle !== "none") {// Format the date and time- const formatter = new Intl.DateTimeFormat(navigator.language, {dateStyle, timeStyle});+ const formatter = new Intl.DateTimeFormat(navigator.language, { dateStyle, timeStyle });return formatter.format(parsedDate);} else if (timeStyle === "none" && dateStyle !== "none") {// Format only the date- return parsedDate.toLocaleDateString(locale, {dateStyle});+ return parsedDate.toLocaleDateString(locale, { dateStyle });} else if (dateStyle === "none" && timeStyle !== "none") {// Format only the time- return parsedDate.toLocaleTimeString(locale, {timeStyle});+ return parsedDate.toLocaleTimeString(locale, { timeStyle });}throw new Error("Incorrect state.");}-diff --git a/src/public/app/utils/mutex.ts b/src/public/app/utils/mutex.tsindex c37e780031..76ea57b0d3 100644--- a/src/public/app/utils/mutex.ts+++ b/src/public/app/utils/mutex.ts@@ -7,22 +7,21 @@ export default class Mutex {lock() {let resolveFun: () => void;- const subPromise = new Promise<void>(resolve => resolveFun = () => resolve());+ const subPromise = new Promise<void>((resolve) => (resolveFun = () => resolve()));// Caller gets a promise that resolves when the current outstanding lock resolvesconst newPromise = this.current.then(() => resolveFun);// Don't allow the next request until the new promise is donethis.current = subPromise;// Return the new promisereturn newPromise;- };+ }async runExclusively(cb: () => Promise<void>) {const unlock = await this.lock();try {return await cb();- }- finally {+ } finally {unlock();}}diff --git a/src/public/app/widgets/api_log.js b/src/public/app/widgets/api_log.jsindex b1a85a4869..a3c7e41d38 100644--- a/src/public/app/widgets/api_log.js+++ b/src/public/app/widgets/api_log.js@@ -33,23 +33,21 @@ const TPL = `}</style>- <div class="bx bx-x close-api-log-button" title="${t('api_log.close')}"></div>+ <div class="bx bx-x close-api-log-button" title="${t("api_log.close")}"></div><div class="api-log-container"></div></div>`;export default class ApiLogWidget extends NoteContextAwareWidget {isEnabled() {- return this.note- && this.note.mime.startsWith('application/javascript;env=')- && super.isEnabled();+ return this.note && this.note.mime.startsWith("application/javascript;env=") && super.isEnabled();}doRender() {this.$widget = $(TPL);this.toggle(false);- this.$logContainer = this.$widget.find('.api-log-container');+ this.$logContainer = this.$widget.find(".api-log-container");this.$closeButton = this.$widget.find(".close-api-log-button");this.$closeButton.on("click", () => this.toggle(false));}@@ -58,7 +56,7 @@ export default class ApiLogWidget extends NoteContextAwareWidget {this.$logContainer.empty();}- apiLogMessagesEvent({messages, noteId}) {+ apiLogMessagesEvent({ messages, noteId }) {if (!this.isNote(noteId)) {return;}diff --git a/src/public/app/widgets/attachment_detail.js b/src/public/app/widgets/attachment_detail.jsindex c0d27dd9e1..263722018e 100644--- a/src/public/app/widgets/attachment_detail.js+++ b/src/public/app/widgets/attachment_detail.js@@ -114,86 +114,78 @@ export default class AttachmentDetailWidget extends BasicWidget {}async refresh() {- this.$widget.find('.attachment-detail-wrapper')- .empty()- .append(- $(TPL)- .find('.attachment-detail-wrapper')- .html()- );- this.$wrapper = this.$widget.find('.attachment-detail-wrapper');+ this.$widget.find(".attachment-detail-wrapper").empty().append($(TPL).find(".attachment-detail-wrapper").html());+ this.$wrapper = this.$widget.find(".attachment-detail-wrapper");this.$wrapper.addClass(this.isFullDetail ? "full-detail" : "list-view");if (!this.isFullDetail) {- this.$wrapper.find('.attachment-title').append(+ this.$wrapper.find(".attachment-title").append(await linkService.createLink(this.attachment.ownerId, {title: this.attachment.title,viewScope: {- viewMode: 'attachments',+ viewMode: "attachments",attachmentId: this.attachment.attachmentId}}));} else {- this.$wrapper.find('.attachment-title')- .text(this.attachment.title);+ this.$wrapper.find(".attachment-title").text(this.attachment.title);}- const $deletionWarning = this.$wrapper.find('.attachment-deletion-warning');- const {utcDateScheduledForErasureSince} = this.attachment;+ const $deletionWarning = this.$wrapper.find(".attachment-deletion-warning");+ const { utcDateScheduledForErasureSince } = this.attachment;if (utcDateScheduledForErasureSince) {this.$wrapper.addClass("scheduled-for-deletion");const scheduledSinceTimestamp = utils.parseDate(utcDateScheduledForErasureSince)?.getTime();- const intervalMs = options.getInt('eraseUnusedAttachmentsAfterSeconds') * 1000;+ const intervalMs = options.getInt("eraseUnusedAttachmentsAfterSeconds") * 1000;const deletionTimestamp = scheduledSinceTimestamp + intervalMs;const willBeDeletedInMs = deletionTimestamp - Date.now();$deletionWarning.show();if (willBeDeletedInMs >= 60000) {- $deletionWarning.text(t('attachment_detail_2.will_be_deleted_in', { time: utils.formatTimeInterval(willBeDeletedInMs) }));+ $deletionWarning.text(t("attachment_detail_2.will_be_deleted_in", { time: utils.formatTimeInterval(willBeDeletedInMs) }));} else {- $deletionWarning.text(t('attachment_detail_2.will_be_deleted_soon'));+ $deletionWarning.text(t("attachment_detail_2.will_be_deleted_soon"));}- $deletionWarning.append(t('attachment_detail_2.deletion_reason'));+ $deletionWarning.append(t("attachment_detail_2.deletion_reason"));} else {this.$wrapper.removeClass("scheduled-for-deletion");$deletionWarning.hide();}- this.$wrapper.find('.attachment-details')- .text(t('attachment_detail_2.role_and_size', { role: this.attachment.role, size: utils.formatSize(this.attachment.contentLength) }));- this.$wrapper.find('.attachment-actions-container').append(this.attachmentActionsWidget.render());+ this.$wrapper.find(".attachment-details").text(t("attachment_detail_2.role_and_size", { role: this.attachment.role, size: utils.formatSize(this.attachment.contentLength) }));+ this.$wrapper.find(".attachment-actions-container").append(this.attachmentActionsWidget.render());- const {$renderedContent} = await contentRenderer.getRenderedContent(this.attachment, { imageHasZoom: this.isFullDetail });- this.$wrapper.find('.attachment-content-wrapper').append($renderedContent);+ const { $renderedContent } = await contentRenderer.getRenderedContent(this.attachment, { imageHasZoom: this.isFullDetail });+ this.$wrapper.find(".attachment-content-wrapper").append($renderedContent);}async copyAttachmentLinkToClipboard() {- if (this.attachment.role === 'image') {- imageService.copyImageReferenceToClipboard(this.$wrapper.find('.attachment-content-wrapper'));- } else if (this.attachment.role === 'file') {+ if (this.attachment.role === "image") {+ imageService.copyImageReferenceToClipboard(this.$wrapper.find(".attachment-content-wrapper"));+ } else if (this.attachment.role === "file") {const $link = await linkService.createLink(this.attachment.ownerId, {referenceLink: true,viewScope: {- viewMode: 'attachments',+ viewMode: "attachments",attachmentId: this.attachment.attachmentId}});utils.copyHtmlToClipboard($link[0].outerHTML);- toastService.showMessage(t('attachment_detail_2.link_copied'));+ toastService.showMessage(t("attachment_detail_2.link_copied"));} else {- throw new Error(t('attachment_detail_2.unrecognized_role', { role: this.attachment.role }));+ throw new Error(t("attachment_detail_2.unrecognized_role", { role: this.attachment.role }));}}- async entitiesReloadedEvent({loadResults}) {- const attachmentRow = loadResults.getAttachmentRows().find(att => att.attachmentId === this.attachment.attachmentId);+ async entitiesReloadedEvent({ loadResults }) {+ const attachmentRow = loadResults.getAttachmentRows().find((att) => att.attachmentId === this.attachment.attachmentId);if (attachmentRow) {if (attachmentRow.isDeleted) {diff --git a/src/public/app/widgets/attribute_widgets/attribute_detail.ts b/src/public/app/widgets/attribute_widgets/attribute_detail.tsindex f05f411240..17d4d1d2f0 100644--- a/src/public/app/widgets/attribute_widgets/attribute_detail.ts+++ b/src/public/app/widgets/attribute_widgets/attribute_detail.ts@@ -4,7 +4,7 @@ import froca from "../../services/froca.js";import linkService from "../../services/link.js";import attributeAutocompleteService from "../../services/attribute_autocomplete.js";import noteAutocompleteService from "../../services/note_autocomplete.js";-import promotedAttributeDefinitionParser from '../../services/promoted_attribute_definition_parser.js';+import promotedAttributeDefinitionParser from "../../services/promoted_attribute_definition_parser.js";import NoteContextAwareWidget from "../note_context_aware_widget.js";import SpacedUpdate from "../../services/spaced_update.js";import utils from "../../services/utils.js";@@ -72,25 +72,25 @@ const TPL = `</style><div style="display: flex; justify-content: space-between; margin-bottom: 8px;">- <h5 class="attr-detail-title">${t('attribute_detail.attr_detail_title')}</h5>+ <h5 class="attr-detail-title">${t("attribute_detail.attr_detail_title")}</h5>- <span class="bx bx-x close-attr-detail-button" title="${t('attribute_detail.close_button_title')}"></span>+ <span class="bx bx-x close-attr-detail-button" title="${t("attribute_detail.close_button_title")}"></span></div>- <div class="attr-is-owned-by">${t('attribute_detail.attr_is_owned_by')}</div>+ <div class="attr-is-owned-by">${t("attribute_detail.attr_is_owned_by")}</div><table class="attr-edit-table">- <tr title="${t('attribute_detail.attr_name_title')}">- <th>${t('attribute_detail.name')}</th>+ <tr title="${t("attribute_detail.attr_name_title")}">+ <th>${t("attribute_detail.name")}</th><td><input type="text" class="attr-input-name form-control" /></td></tr><tr class="attr-help"></tr><tr class="attr-row-value">- <th>${t('attribute_detail.value')}</th>+ <th>${t("attribute_detail.value")}</th><td><input type="text" class="attr-input-value form-control" /></td></tr><tr class="attr-row-target-note">- <th title="${t('attribute_detail.target_note_title')}">${t('attribute_detail.target_note')}</th>+ <th title="${t("attribute_detail.target_note_title")}">${t("attribute_detail.target_note")}</th><td><div class="input-group"><input type="text" class="attr-input-target-note form-control" />@@ -98,12 +98,12 @@ const TPL = `</td></tr><tr class="attr-row-promoted"- title="${t('attribute_detail.promoted_title')}">- <th>${t('attribute_detail.promoted')}</th>+ title="${t("attribute_detail.promoted_title")}">+ <th>${t("attribute_detail.promoted")}</th><td><input type="checkbox" class="attr-input-promoted form-check" /></td></tr><tr class="attr-row-promoted-alias">- <th title="${t('attribute_detail.promoted_alias_title')}">${t('attribute_detail.promoted_alias')}</th>+ <th title="${t("attribute_detail.promoted_alias_title")}">${t("attribute_detail.promoted_alias")}</th><td><div class="input-group"><input type="text" class="attr-input-promoted-alias form-control" />@@ -111,47 +111,47 @@ const TPL = `</td></tr><tr class="attr-row-multiplicity">- <th title="${t('attribute_detail.multiplicity_title')}">${t('attribute_detail.multiplicity')}</th>+ <th title="${t("attribute_detail.multiplicity_title")}">${t("attribute_detail.multiplicity")}</th><td><select class="attr-input-multiplicity form-control">- <option value="single">${t('attribute_detail.single_value')}</option>- <option value="multi">${t('attribute_detail.multi_value')}</option>+ <option value="single">${t("attribute_detail.single_value")}</option>+ <option value="multi">${t("attribute_detail.multi_value")}</option></select></td></tr><tr class="attr-row-label-type">- <th title="${t('attribute_detail.label_type_title')}">${t('attribute_detail.label_type')}</th>+ <th title="${t("attribute_detail.label_type_title")}">${t("attribute_detail.label_type")}</th><td><select class="attr-input-label-type form-control">- <option value="text">${t('attribute_detail.text')}</option>- <option value="number">${t('attribute_detail.number')}</option>- <option value="boolean">${t('attribute_detail.boolean')}</option>- <option value="date">${t('attribute_detail.date')}</option>- <option value="datetime">${t('attribute_detail.date_time')}</option>- <option value="time">${t('attribute_detail.time')}</option>- <option value="url">${t('attribute_detail.url')}</option>+ <option value="text">${t("attribute_detail.text")}</option>+ <option value="number">${t("attribute_detail.number")}</option>+ <option value="boolean">${t("attribute_detail.boolean")}</option>+ <option value="date">${t("attribute_detail.date")}</option>+ <option value="datetime">${t("attribute_detail.date_time")}</option>+ <option value="time">${t("attribute_detail.time")}</option>+ <option value="url">${t("attribute_detail.url")}</option></select></td></tr><tr class="attr-row-number-precision">- <th title="${t('attribute_detail.precision_title')}">${t('attribute_detail.precision')}</th>+ <th title="${t("attribute_detail.precision_title")}">${t("attribute_detail.precision")}</th><td><div class="input-group"><input type="number" class="form-control attr-input-number-precision" style="text-align: right">- <span class="input-group-text">${t('attribute_detail.digits')}</span>+ <span class="input-group-text">${t("attribute_detail.digits")}</span></div></td></tr><tr class="attr-row-inverse-relation">- <th title="${t('attribute_detail.inverse_relation_title')}">${t('attribute_detail.inverse_relation')}</th>+ <th title="${t("attribute_detail.inverse_relation_title")}">${t("attribute_detail.inverse_relation")}</th><td><div class="input-group"><input type="text" class="attr-input-inverse-relation form-control" /></div></td></tr>- <tr title="${t('attribute_detail.inheritable_title')}">- <th>${t('attribute_detail.inheritable')}</th>+ <tr title="${t("attribute_detail.inheritable_title")}">+ <th>${t("attribute_detail.inheritable")}</th><td><input type="checkbox" class="attr-input-inheritable form-check" /></td></tr></table>@@ -159,113 +159,113 @@ const TPL = `<div class="attr-save-delete-button-container"><button class="btn btn-primary btn-sm attr-save-changes-and-close-button"style="flex-grow: 1; margin-right: 20px">- ${t('attribute_detail.save_and_close')}</button>+ ${t("attribute_detail.save_and_close")}</button><button class="btn btn-secondary btn-sm attr-delete-button">- ${t('attribute_detail.delete')}</button>+ ${t("attribute_detail.delete")}</button></div><div class="related-notes-container"><br/>- <h5 class="related-notes-tile">${t('attribute_detail.related_notes_title')}</h5>+ <h5 class="related-notes-tile">${t("attribute_detail.related_notes_title")}</h5><ul class="related-notes-list"></ul>- <div class="related-notes-more-notes">${t('attribute_detail.more_notes')}</div>+ <div class="related-notes-more-notes">${t("attribute_detail.more_notes")}</div></div></div>`;const DISPLAYED_NOTES = 10;const ATTR_TITLES: Record<string, string> = {- "label": t('attribute_detail.label'),- "label-definition": t('attribute_detail.label_definition'),- "relation": t('attribute_detail.relation'),- "relation-definition": t('attribute_detail.relation_definition')+ label: t("attribute_detail.label"),+ "label-definition": t("attribute_detail.label_definition"),+ relation: t("attribute_detail.relation"),+ "relation-definition": t("attribute_detail.relation_definition")};const ATTR_HELP: Record<string, Record<string, string>> = {- "label": {- "disableVersioning": t('attribute_detail.disable_versioning'),- "calendarRoot": t('attribute_detail.calendar_root'),- "archived": t('attribute_detail.archived'),- "excludeFromExport": t('attribute_detail.exclude_from_export'),- "run": t('attribute_detail.run'),- "runOnInstance": t('attribute_detail.run_on_instance'),- "runAtHour": t('attribute_detail.run_at_hour'),- "disableInclusion": t('attribute_detail.disable_inclusion'),- "sorted": t('attribute_detail.sorted'),- "sortDirection": t('attribute_detail.sort_direction'),- "sortFoldersFirst": t('attribute_detail.sort_folders_first'),- "top": t('attribute_detail.top'),- "hidePromotedAttributes": t('attribute_detail.hide_promoted_attributes'),- "readOnly": t('attribute_detail.read_only'),- "autoReadOnlyDisabled": t('attribute_detail.auto_read_only_disabled'),- "appCss": t('attribute_detail.app_css'),- "appTheme": t('attribute_detail.app_theme'),- "appThemeBase": t('attribute_detail.app_theme_base'),- "cssClass": t('attribute_detail.css_class'),- "iconClass": t('attribute_detail.icon_class'),- "pageSize": t('attribute_detail.page_size'),- "customRequestHandler": t('attribute_detail.custom_request_handler'),- "customResourceProvider": t('attribute_detail.custom_resource_provider'),- "widget": t('attribute_detail.widget'),- "workspace": t('attribute_detail.workspace'),- "workspaceIconClass": t('attribute_detail.workspace_icon_class'),- "workspaceTabBackgroundColor": t('attribute_detail.workspace_tab_background_color'),- "workspaceCalendarRoot": t('attribute_detail.workspace_calendar_root'),- "workspaceTemplate": t('attribute_detail.workspace_template'),- "searchHome": t('attribute_detail.search_home'),- "workspaceSearchHome": t('attribute_detail.workspace_search_home'),- "inbox": t('attribute_detail.inbox'),- "workspaceInbox": t('attribute_detail.workspace_inbox'),- "sqlConsoleHome": t('attribute_detail.sql_console_home'),- "bookmarkFolder": t('attribute_detail.bookmark_folder'),- "shareHiddenFromTree": t('attribute_detail.share_hidden_from_tree'),- "shareExternalLink": t('attribute_detail.share_external_link'),- "shareAlias": t('attribute_detail.share_alias'),- "shareOmitDefaultCss": t('attribute_detail.share_omit_default_css'),- "shareRoot": t('attribute_detail.share_root'),- "shareDescription": t('attribute_detail.share_description'),- "shareRaw": t('attribute_detail.share_raw'),- "shareDisallowRobotIndexing": t('attribute_detail.share_disallow_robot_indexing'),- "shareCredentials": t('attribute_detail.share_credentials'),- "shareIndex": t('attribute_detail.share_index'),- "displayRelations": t('attribute_detail.display_relations'),- "hideRelations": t('attribute_detail.hide_relations'),- "titleTemplate": t('attribute_detail.title_template'),- "template": t('attribute_detail.template'),- "toc": t('attribute_detail.toc'),- "color": t('attribute_detail.color'),- "keyboardShortcut": t('attribute_detail.keyboard_shortcut'),- "keepCurrentHoisting": t('attribute_detail.keep_current_hoisting'),- "executeButton": t('attribute_detail.execute_button'),- "executeDescription": t('attribute_detail.execute_description'),- "excludeFromNoteMap": t('attribute_detail.exclude_from_note_map'),- "newNotesOnTop": t('attribute_detail.new_notes_on_top'),- "hideHighlightWidget": t('attribute_detail.hide_highlight_widget')+ label: {+ disableVersioning: t("attribute_detail.disable_versioning"),+ calendarRoot: t("attribute_detail.calendar_root"),+ archived: t("attribute_detail.archived"),+ excludeFromExport: t("attribute_detail.exclude_from_export"),+ run: t("attribute_detail.run"),+ runOnInstance: t("attribute_detail.run_on_instance"),+ runAtHour: t("attribute_detail.run_at_hour"),+ disableInclusion: t("attribute_detail.disable_inclusion"),+ sorted: t("attribute_detail.sorted"),+ sortDirection: t("attribute_detail.sort_direction"),+ sortFoldersFirst: t("attribute_detail.sort_folders_first"),+ top: t("attribute_detail.top"),+ hidePromotedAttributes: t("attribute_detail.hide_promoted_attributes"),+ readOnly: t("attribute_detail.read_only"),+ autoReadOnlyDisabled: t("attribute_detail.auto_read_only_disabled"),+ appCss: t("attribute_detail.app_css"),+ appTheme: t("attribute_detail.app_theme"),+ appThemeBase: t("attribute_detail.app_theme_base"),+ cssClass: t("attribute_detail.css_class"),+ iconClass: t("attribute_detail.icon_class"),+ pageSize: t("attribute_detail.page_size"),+ customRequestHandler: t("attribute_detail.custom_request_handler"),+ customResourceProvider: t("attribute_detail.custom_resource_provider"),+ widget: t("attribute_detail.widget"),+ workspace: t("attribute_detail.workspace"),+ workspaceIconClass: t("attribute_detail.workspace_icon_class"),+ workspaceTabBackgroundColor: t("attribute_detail.workspace_tab_background_color"),+ workspaceCalendarRoot: t("attribute_detail.workspace_calendar_root"),+ workspaceTemplate: t("attribute_detail.workspace_template"),+ searchHome: t("attribute_detail.search_home"),+ workspaceSearchHome: t("attribute_detail.workspace_search_home"),+ inbox: t("attribute_detail.inbox"),+ workspaceInbox: t("attribute_detail.workspace_inbox"),+ sqlConsoleHome: t("attribute_detail.sql_console_home"),+ bookmarkFolder: t("attribute_detail.bookmark_folder"),+ shareHiddenFromTree: t("attribute_detail.share_hidden_from_tree"),+ shareExternalLink: t("attribute_detail.share_external_link"),+ shareAlias: t("attribute_detail.share_alias"),+ shareOmitDefaultCss: t("attribute_detail.share_omit_default_css"),+ shareRoot: t("attribute_detail.share_root"),+ shareDescription: t("attribute_detail.share_description"),+ shareRaw: t("attribute_detail.share_raw"),+ shareDisallowRobotIndexing: t("attribute_detail.share_disallow_robot_indexing"),+ shareCredentials: t("attribute_detail.share_credentials"),+ shareIndex: t("attribute_detail.share_index"),+ displayRelations: t("attribute_detail.display_relations"),+ hideRelations: t("attribute_detail.hide_relations"),+ titleTemplate: t("attribute_detail.title_template"),+ template: t("attribute_detail.template"),+ toc: t("attribute_detail.toc"),+ color: t("attribute_detail.color"),+ keyboardShortcut: t("attribute_detail.keyboard_shortcut"),+ keepCurrentHoisting: t("attribute_detail.keep_current_hoisting"),+ executeButton: t("attribute_detail.execute_button"),+ executeDescription: t("attribute_detail.execute_description"),+ excludeFromNoteMap: t("attribute_detail.exclude_from_note_map"),+ newNotesOnTop: t("attribute_detail.new_notes_on_top"),+ hideHighlightWidget: t("attribute_detail.hide_highlight_widget")},- "relation": {- "runOnNoteCreation": t('attribute_detail.run_on_note_creation'),- "runOnChildNoteCreation": t('attribute_detail.run_on_child_note_creation'),- "runOnNoteTitleChange": t('attribute_detail.run_on_note_title_change'),- "runOnNoteContentChange": t('attribute_detail.run_on_note_content_change'),- "runOnNoteChange": t('attribute_detail.run_on_note_change'),- "runOnNoteDeletion": t('attribute_detail.run_on_note_deletion'),- "runOnBranchCreation": t('attribute_detail.run_on_branch_creation'),- "runOnBranchChange": t('attribute_detail.run_on_branch_change'),- "runOnBranchDeletion": t('attribute_detail.run_on_branch_deletion'),- "runOnAttributeCreation": t('attribute_detail.run_on_attribute_creation'),- "runOnAttributeChange": t('attribute_detail.run_on_attribute_change'),- "template": t('attribute_detail.relation_template'),- "inherit": t('attribute_detail.inherit'),- "renderNote": t('attribute_detail.render_note'),- "widget": t('attribute_detail.widget_relation'),- "shareCss": t('attribute_detail.share_css'),- "shareJs": t('attribute_detail.share_js'),- "shareTemplate": t('attribute_detail.share_template'),- "shareFavicon": t('attribute_detail.share_favicon')+ relation: {+ runOnNoteCreation: t("attribute_detail.run_on_note_creation"),+ runOnChildNoteCreation: t("attribute_detail.run_on_child_note_creation"),+ runOnNoteTitleChange: t("attribute_detail.run_on_note_title_change"),+ runOnNoteContentChange: t("attribute_detail.run_on_note_content_change"),+ runOnNoteChange: t("attribute_detail.run_on_note_change"),+ runOnNoteDeletion: t("attribute_detail.run_on_note_deletion"),+ runOnBranchCreation: t("attribute_detail.run_on_branch_creation"),+ runOnBranchChange: t("attribute_detail.run_on_branch_change"),+ runOnBranchDeletion: t("attribute_detail.run_on_branch_deletion"),+ runOnAttributeCreation: t("attribute_detail.run_on_attribute_creation"),+ runOnAttributeChange: t("attribute_detail.run_on_attribute_change"),+ template: t("attribute_detail.relation_template"),+ inherit: t("attribute_detail.inherit"),+ renderNote: t("attribute_detail.render_note"),+ widget: t("attribute_detail.widget_relation"),+ shareCss: t("attribute_detail.share_css"),+ shareJs: t("attribute_detail.share_js"),+ shareTemplate: t("attribute_detail.share_template"),+ shareFavicon: t("attribute_detail.share_favicon")}};@@ -288,7 +288,6 @@ interface SearchRelatedResponse {}export default class AttributeDetailWidget extends NoteContextAwareWidget {-private $title!: JQuery<HTMLElement>;private $inputName!: JQuery<HTMLElement>;private $inputValue!: JQuery<HTMLElement>;@@ -335,39 +334,40 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {this.$widget = $(TPL);- shortcutService.bindElShortcut(this.$widget, 'ctrl+return', () => this.saveAndClose());- shortcutService.bindElShortcut(this.$widget, 'esc', () => this.cancelAndClose());-+ shortcutService.bindElShortcut(this.$widget, "ctrl+return", () => this.saveAndClose());+ shortcutService.bindElShortcut(this.$widget, "esc", () => this.cancelAndClose());- this.$title = this.$widget.find('.attr-detail-title');+ this.$title = this.$widget.find(".attr-detail-title");- this.$inputName = this.$widget.find('.attr-input-name');- this.$inputName.on('input', ev => {- if (!(ev.originalEvent as KeyboardEvent)?.isComposing) { // https://github.com/zadam/trilium/pull/3812+ this.$inputName = this.$widget.find(".attr-input-name");+ this.$inputName.on("input", (ev) => {+ if (!(ev.originalEvent as KeyboardEvent)?.isComposing) {+ // https://github.com/zadam/trilium/pull/3812this.userEditedAttribute();}});- this.$inputName.on('change', () => this.userEditedAttribute());- this.$inputName.on('autocomplete:closed', () => this.userEditedAttribute());+ this.$inputName.on("change", () => this.userEditedAttribute());+ this.$inputName.on("autocomplete:closed", () => this.userEditedAttribute());- this.$inputName.on('focus', () => {+ this.$inputName.on("focus", () => {attributeAutocompleteService.initAttributeNameAutocomplete({$el: this.$inputName,- attributeType: () => ['relation', 'relation-definition'].includes(this.attrType || "") ? 'relation' : 'label',+ attributeType: () => (["relation", "relation-definition"].includes(this.attrType || "") ? "relation" : "label"),open: true});});- this.$rowValue = this.$widget.find('.attr-row-value');- this.$inputValue = this.$widget.find('.attr-input-value');- this.$inputValue.on('input', ev => {- if (!(ev.originalEvent as KeyboardEvent)?.isComposing) { // https://github.com/zadam/trilium/pull/3812+ this.$rowValue = this.$widget.find(".attr-row-value");+ this.$inputValue = this.$widget.find(".attr-input-value");+ this.$inputValue.on("input", (ev) => {+ if (!(ev.originalEvent as KeyboardEvent)?.isComposing) {+ // https://github.com/zadam/trilium/pull/3812this.userEditedAttribute();}});- this.$inputValue.on('change', () => this.userEditedAttribute());- this.$inputValue.on('autocomplete:closed', () => this.userEditedAttribute());- this.$inputValue.on('focus', () => {+ this.$inputValue.on("change", () => this.userEditedAttribute());+ this.$inputValue.on("autocomplete:closed", () => this.userEditedAttribute());+ this.$inputValue.on("focus", () => {attributeAutocompleteService.initLabelValueAutocomplete({$el: this.$inputValue,open: true,@@ -375,86 +375,84 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {});});- this.$rowPromoted = this.$widget.find('.attr-row-promoted');- this.$inputPromoted = this.$widget.find('.attr-input-promoted');- this.$inputPromoted.on('change', () => this.userEditedAttribute());+ this.$rowPromoted = this.$widget.find(".attr-row-promoted");+ this.$inputPromoted = this.$widget.find(".attr-input-promoted");+ this.$inputPromoted.on("change", () => this.userEditedAttribute());- this.$rowPromotedAlias = this.$widget.find('.attr-row-promoted-alias');- this.$inputPromotedAlias = this.$widget.find('.attr-input-promoted-alias');- this.$inputPromotedAlias.on('change', () => this.userEditedAttribute());+ this.$rowPromotedAlias = this.$widget.find(".attr-row-promoted-alias");+ this.$inputPromotedAlias = this.$widget.find(".attr-input-promoted-alias");+ this.$inputPromotedAlias.on("change", () => this.userEditedAttribute());- this.$rowMultiplicity = this.$widget.find('.attr-row-multiplicity');- this.$inputMultiplicity = this.$widget.find('.attr-input-multiplicity');- this.$inputMultiplicity.on('change', () => this.userEditedAttribute());+ this.$rowMultiplicity = this.$widget.find(".attr-row-multiplicity");+ this.$inputMultiplicity = this.$widget.find(".attr-input-multiplicity");+ this.$inputMultiplicity.on("change", () => this.userEditedAttribute());- this.$rowLabelType = this.$widget.find('.attr-row-label-type');- this.$inputLabelType = this.$widget.find('.attr-input-label-type');- this.$inputLabelType.on('change', () => this.userEditedAttribute());+ this.$rowLabelType = this.$widget.find(".attr-row-label-type");+ this.$inputLabelType = this.$widget.find(".attr-input-label-type");+ this.$inputLabelType.on("change", () => this.userEditedAttribute());- this.$rowNumberPrecision = this.$widget.find('.attr-row-number-precision');- this.$inputNumberPrecision = this.$widget.find('.attr-input-number-precision');- this.$inputNumberPrecision.on('change', () => this.userEditedAttribute());+ this.$rowNumberPrecision = this.$widget.find(".attr-row-number-precision");+ this.$inputNumberPrecision = this.$widget.find(".attr-input-number-precision");+ this.$inputNumberPrecision.on("change", () => this.userEditedAttribute());- this.$rowInverseRelation = this.$widget.find('.attr-row-inverse-relation');- this.$inputInverseRelation = this.$widget.find('.attr-input-inverse-relation');- this.$inputInverseRelation.on('input', ev => {- if (!(ev.originalEvent as KeyboardEvent)?.isComposing) { // https://github.com/zadam/trilium/pull/3812+ this.$rowInverseRelation = this.$widget.find(".attr-row-inverse-relation");+ this.$inputInverseRelation = this.$widget.find(".attr-input-inverse-relation");+ this.$inputInverseRelation.on("input", (ev) => {+ if (!(ev.originalEvent as KeyboardEvent)?.isComposing) {+ // https://github.com/zadam/trilium/pull/3812this.userEditedAttribute();}});- this.$rowTargetNote = this.$widget.find('.attr-row-target-note');- this.$inputTargetNote = this.$widget.find('.attr-input-target-note');+ this.$rowTargetNote = this.$widget.find(".attr-row-target-note");+ this.$inputTargetNote = this.$widget.find(".attr-input-target-note");- noteAutocompleteService.initNoteAutocomplete(this.$inputTargetNote, { allowCreatingNotes: true })- .on('autocomplete:noteselected', (event, suggestion, dataset) => {- if (!suggestion.notePath) {- return false;- }+ noteAutocompleteService.initNoteAutocomplete(this.$inputTargetNote, { allowCreatingNotes: true }).on("autocomplete:noteselected", (event, suggestion, dataset) => {+ if (!suggestion.notePath) {+ return false;+ }- const pathChunks = suggestion.notePath.split('/');+ const pathChunks = suggestion.notePath.split("/");- this.attribute.value = pathChunks[pathChunks.length - 1]; // noteId+ this.attribute.value = pathChunks[pathChunks.length - 1]; // noteId- this.triggerCommand('updateAttributeList', { attributes: this.allAttributes });- this.updateRelatedNotes();- });+ this.triggerCommand("updateAttributeList", { attributes: this.allAttributes });+ this.updateRelatedNotes();+ });- this.$inputInheritable = this.$widget.find('.attr-input-inheritable');- this.$inputInheritable.on('change', () => this.userEditedAttribute());+ this.$inputInheritable = this.$widget.find(".attr-input-inheritable");+ this.$inputInheritable.on("change", () => this.userEditedAttribute());- this.$closeAttrDetailButton = this.$widget.find('.close-attr-detail-button');- this.$closeAttrDetailButton.on('click', () => this.cancelAndClose());+ this.$closeAttrDetailButton = this.$widget.find(".close-attr-detail-button");+ this.$closeAttrDetailButton.on("click", () => this.cancelAndClose());- this.$attrIsOwnedBy = this.$widget.find('.attr-is-owned-by');+ this.$attrIsOwnedBy = this.$widget.find(".attr-is-owned-by");- this.$attrSaveDeleteButtonContainer = this.$widget.find('.attr-save-delete-button-container');+ this.$attrSaveDeleteButtonContainer = this.$widget.find(".attr-save-delete-button-container");- this.$saveAndCloseButton = this.$widget.find('.attr-save-changes-and-close-button');- this.$saveAndCloseButton.on('click', () => this.saveAndClose());+ this.$saveAndCloseButton = this.$widget.find(".attr-save-changes-and-close-button");+ this.$saveAndCloseButton.on("click", () => this.saveAndClose());- this.$deleteButton = this.$widget.find('.attr-delete-button');- this.$deleteButton.on('click', async () => {- await this.triggerCommand('updateAttributeList', {- attributes: this.allAttributes.filter(attr => attr !== this.attribute)+ this.$deleteButton = this.$widget.find(".attr-delete-button");+ this.$deleteButton.on("click", async () => {+ await this.triggerCommand("updateAttributeList", {+ attributes: this.allAttributes.filter((attr) => attr !== this.attribute)});- await this.triggerCommand('saveAttributes');+ await this.triggerCommand("saveAttributes");this.hide();});- this.$attrHelp = this.$widget.find('.attr-help');+ this.$attrHelp = this.$widget.find(".attr-help");- this.$relatedNotesContainer = this.$widget.find('.related-notes-container');- this.$relatedNotesTitle = this.$relatedNotesContainer.find('.related-notes-tile');- this.$relatedNotesList = this.$relatedNotesContainer.find('.related-notes-list');- this.$relatedNotesMoreNotes = this.$relatedNotesContainer.find('.related-notes-more-notes');+ this.$relatedNotesContainer = this.$widget.find(".related-notes-container");+ this.$relatedNotesTitle = this.$relatedNotesContainer.find(".related-notes-tile");+ this.$relatedNotesList = this.$relatedNotesContainer.find(".related-notes-list");+ this.$relatedNotesMoreNotes = this.$relatedNotesContainer.find(".related-notes-more-notes");- $(window).on('mousedown', e => {- if (!$(e.target).closest(this.$widget[0]).length- && !$(e.target).closest(".algolia-autocomplete").length- && !$(e.target).closest("#context-menu-container").length) {+ $(window).on("mousedown", (e) => {+ if (!$(e.target).closest(this.$widget[0]).length && !$(e.target).closest(".algolia-autocomplete").length && !$(e.target).closest("#context-menu-container").length) {this.hide();}});@@ -471,13 +469,9 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {this.attrType = this.getAttrType(attribute);- const attrName =- this.attrType === 'label-definition' ? attribute.name.substr(6)- : (this.attrType === 'relation-definition' ? attribute.name.substr(9) : attribute.name);+ const attrName = this.attrType === "label-definition" ? attribute.name.substr(6) : this.attrType === "relation-definition" ? attribute.name.substr(9) : attribute.name;- const definition = this.attrType?.endsWith('-definition')- ? promotedAttributeDefinitionParser.parse(attribute.value || "")- : {};+ const definition = this.attrType?.endsWith("-definition") ? promotedAttributeDefinitionParser.parse(attribute.value || "") : {};if (this.attrType) {this.$title.text(ATTR_TITLES[this.attrType]);@@ -497,75 +491,51 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {this.$attrIsOwnedBy.show().empty()- .append(attribute.type === 'label' ? 'Label' : 'Relation')+ .append(attribute.type === "label" ? "Label" : "Relation").append(` ${t("attribute_detail.is_owned_by_note")} `)- .append(await linkService.createLink(attribute.noteId))+ .append(await linkService.createLink(attribute.noteId));}- const disabledFn = (() => !isOwned ? "true" : undefined);+ const disabledFn = () => (!isOwned ? "true" : undefined);- this.$inputName- .val(attrName)- .attr('readonly', disabledFn);+ this.$inputName.val(attrName).attr("readonly", disabledFn);- this.$rowValue.toggle(this.attrType === 'label');- this.$rowTargetNote.toggle(this.attrType === 'relation');+ this.$rowValue.toggle(this.attrType === "label");+ this.$rowTargetNote.toggle(this.attrType === "relation");- this.$rowPromoted.toggle(['label-definition', 'relation-definition'].includes(this.attrType || ""));- this.$inputPromoted- .prop("checked", !!definition.isPromoted)- .attr('disabled', disabledFn);+ this.$rowPromoted.toggle(["label-definition", "relation-definition"].includes(this.attrType || ""));+ this.$inputPromoted.prop("checked", !!definition.isPromoted).attr("disabled", disabledFn);this.$rowPromotedAlias.toggle(!!definition.isPromoted);- this.$inputPromotedAlias- .val(definition.promotedAlias || "")- .attr('disabled', disabledFn);-- this.$rowMultiplicity.toggle(['label-definition', 'relation-definition'].includes(this.attrType || ""));- this.$inputMultiplicity- .val(definition.multiplicity || "")- .attr('disabled', disabledFn);-- this.$rowLabelType.toggle(this.attrType === 'label-definition');- this.$inputLabelType- .val(definition.labelType || "")- .attr('disabled', disabledFn);-- this.$rowNumberPrecision.toggle(this.attrType === 'label-definition' && definition.labelType === 'number');- this.$inputNumberPrecision- .val(definition.numberPrecision || "")- .attr('disabled', disabledFn);-- this.$rowInverseRelation.toggle(this.attrType === 'relation-definition');- this.$inputInverseRelation- .val(definition.inverseRelation || "")- .attr('disabled', disabledFn);-- if (attribute.type === 'label') {- this.$inputValue- .val(attribute.value || "")- .attr('readonly', disabledFn);- }- else if (attribute.type === 'relation') {- this.$inputTargetNote- .attr('readonly', disabledFn)- .val("")- .setSelectedNotePath("");+ this.$inputPromotedAlias.val(definition.promotedAlias || "").attr("disabled", disabledFn);++ this.$rowMultiplicity.toggle(["label-definition", "relation-definition"].includes(this.attrType || ""));+ this.$inputMultiplicity.val(definition.multiplicity || "").attr("disabled", disabledFn);++ this.$rowLabelType.toggle(this.attrType === "label-definition");+ this.$inputLabelType.val(definition.labelType || "").attr("disabled", disabledFn);++ this.$rowNumberPrecision.toggle(this.attrType === "label-definition" && definition.labelType === "number");+ this.$inputNumberPrecision.val(definition.numberPrecision || "").attr("disabled", disabledFn);++ this.$rowInverseRelation.toggle(this.attrType === "relation-definition");+ this.$inputInverseRelation.val(definition.inverseRelation || "").attr("disabled", disabledFn);++ if (attribute.type === "label") {+ this.$inputValue.val(attribute.value || "").attr("readonly", disabledFn);+ } else if (attribute.type === "relation") {+ this.$inputTargetNote.attr("readonly", disabledFn).val("").setSelectedNotePath("");if (attribute.value) {const targetNote = await froca.getNote(attribute.value);if (targetNote) {- this.$inputTargetNote- .val(targetNote ? targetNote.title : "")- .setSelectedNotePath(attribute.value);+ this.$inputTargetNote.val(targetNote ? targetNote.title : "").setSelectedNotePath(attribute.value);}}}- this.$inputInheritable- .prop("checked", !!attribute.isInheritable)- .attr('disabled', disabledFn);+ this.$inputInheritable.prop("checked", !!attribute.isInheritable).attr("disabled", disabledFn);this.updateHelp();@@ -581,16 +551,11 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {.css("left", detPosition.left).css("right", detPosition.right).css("top", y - offset.top + 70)- .css("max-height",- outerHeight + y > height - 50- ? height - y - 50- : 10000);+ .css("max-height", outerHeight + y > height - 50 ? height - y - 50 : 10000);}- if (focus === 'name') {- this.$inputName- .trigger('focus')- .trigger('select');+ if (focus === "name") {+ this.$inputName.trigger("focus").trigger("select");}}@@ -618,7 +583,7 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {}async saveAndClose() {- await this.triggerCommand('saveAttributes');+ await this.triggerCommand("saveAttributes");this.hide();@@ -626,7 +591,7 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {}async cancelAndClose() {- await this.triggerCommand('reloadAttributes');+ await this.triggerCommand("reloadAttributes");this.hide();@@ -642,24 +607,18 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {updateHelp() {const attrName = String(this.$inputName.val());- if (this.attrType && this.attrType in ATTR_HELP &&- attrName && attrName in ATTR_HELP[this.attrType]) {+ if (this.attrType && this.attrType in ATTR_HELP && attrName && attrName in ATTR_HELP[this.attrType]) {this.$attrHelp.empty()- .append($("<td colspan=2>")- .append($("<strong>").text(attrName))- .append(" - ")- .append(ATTR_HELP[this.attrType][attrName])- )+ .append($("<td colspan=2>").append($("<strong>").text(attrName)).append(" - ").append(ATTR_HELP[this.attrType][attrName])).show();- }- else {+ } else {this.$attrHelp.empty().hide();}}async updateRelatedNotes() {- let { results, count } = await server.post<SearchRelatedResponse>('search-related', this.attribute);+ let { results, count } = await server.post<SearchRelatedResponse>("search-related", this.attribute);for (const res of results) {res.noteId = res.notePathArray[res.notePathArray.length - 1];@@ -676,16 +635,14 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {this.$relatedNotesList.empty();const displayedResults = results.length <= DISPLAYED_NOTES ? results : results.slice(0, DISPLAYED_NOTES);- const displayedNotes = await froca.getNotes(displayedResults.map(res => res.noteId));+ const displayedNotes = await froca.getNotes(displayedResults.map((res) => res.noteId));const hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId;for (const note of displayedNotes) {const notePath = note.getBestNotePathString(hoistedNoteId);const $noteLink = await linkService.createLink(notePath, { showNotePath: true });- this.$relatedNotesList.append(- $("<li>").append($noteLink)- );+ this.$relatedNotesList.append($("<li>").append($noteLink));}if (results.length > DISPLAYED_NOTES) {@@ -697,20 +654,18 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {}getAttrType(attribute: Attribute) {- if (attribute.type === 'label') {- if (attribute.name.startsWith('label:')) {+ if (attribute.type === "label") {+ if (attribute.name.startsWith("label:")) {return "label-definition";- } else if (attribute.name.startsWith('relation:')) {+ } else if (attribute.name.startsWith("relation:")) {return "relation-definition";} else {return "label";}- }- else if (attribute.type === 'relation') {+ } else if (attribute.type === "relation") {return "relation";- }- else {- this.$title.text('');+ } else {+ this.$title.text("");}}@@ -724,26 +679,24 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {this.$inputName.val(attrName);}- if (this.attrType === 'label-definition') {+ if (this.attrType === "label-definition") {attrName = `label:${attrName}`;- } else if (this.attrType === 'relation-definition') {+ } else if (this.attrType === "relation-definition") {attrName = `relation:${attrName}`;}this.attribute.name = attrName;this.attribute.isInheritable = this.$inputInheritable.is(":checked");- if (this.attrType?.endsWith('-definition')) {+ if (this.attrType?.endsWith("-definition")) {this.attribute.value = this.buildDefinitionValue();- }- else if (this.attrType === 'relation') {+ } else if (this.attrType === "relation") {this.attribute.value = this.$inputTargetNote.getSelectedNoteId() || "";- }- else {+ } else {this.attribute.value = String(this.$inputValue.val());}- this.triggerCommand('updateAttributeList', { attributes: this.allAttributes });+ this.triggerCommand("updateAttributeList", { attributes: this.allAttributes });}buildDefinitionValue() {@@ -752,28 +705,26 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {if (this.$inputPromoted.is(":checked")) {props.push("promoted");- if (this.$inputPromotedAlias.val() !== '') {+ if (this.$inputPromotedAlias.val() !== "") {props.push(`alias=${this.$inputPromotedAlias.val()}`);}}props.push(this.$inputMultiplicity.val());- if (this.attrType === 'label-definition') {+ if (this.attrType === "label-definition") {props.push(this.$inputLabelType.val());- if (this.$inputLabelType.val() === 'number' && this.$inputNumberPrecision.val() !== '') {+ if (this.$inputLabelType.val() === "number" && this.$inputNumberPrecision.val() !== "") {props.push(`precision=${this.$inputNumberPrecision.val()}`);}- } else if (this.attrType === 'relation-definition' && String(this.$inputInverseRelation.val())?.trim().length > 0) {+ } else if (this.attrType === "relation-definition" && String(this.$inputInverseRelation.val())?.trim().length > 0) {const inverseRelationName = this.$inputInverseRelation.val();props.push(`inverse=${utils.filterAttributeName(String(inverseRelationName))}`);}- this.$rowNumberPrecision.toggle(- this.attrType === 'label-definition'- && this.$inputLabelType.val() === 'number');+ this.$rowNumberPrecision.toggle(this.attrType === "label-definition" && this.$inputLabelType.val() === "number");this.$rowPromotedAlias.toggle(this.$inputPromoted.is(":checked"));@@ -787,7 +738,7 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget {createLink(noteId: string) {return $("<a>", {href: `#root/${noteId}`,- class: 'reference-link'+ class: "reference-link"});}diff --git a/src/public/app/widgets/attribute_widgets/attribute_editor.ts b/src/public/app/widgets/attribute_widgets/attribute_editor.tsindex d01825c235..68dafbcbc9 100644--- a/src/public/app/widgets/attribute_widgets/attribute_editor.ts+++ b/src/public/app/widgets/attribute_widgets/attribute_editor.ts@@ -86,10 +86,10 @@ const TPL = `const mentionSetup: MentionConfig = {feeds: [{- marker: '@',- feed: queryText => noteAutocompleteService.autocompleteSourceForCKEditor(queryText),- itemRenderer: item => {- const itemElement = document.createElement('button');+ marker: "@",+ feed: (queryText) => noteAutocompleteService.autocompleteSourceForCKEditor(queryText),+ itemRenderer: (item) => {+ const itemElement = document.createElement("button");itemElement.innerHTML = `${item.highlightedNotePathTitle} `;@@ -98,29 +98,29 @@ const mentionSetup: MentionConfig = {minimumCharacters: 0},{- marker: '#',- feed: async queryText => {+ marker: "#",+ feed: async (queryText) => {const names = await server.get<string[]>(`attribute-names/?type=label&query=${encodeURIComponent(queryText)}`);- return names.map(name => {+ return names.map((name) => {return {id: `#${name}`,name: name- }+ };});},minimumCharacters: 0},{- marker: '~',- feed: async queryText => {+ marker: "~",+ feed: async (queryText) => {const names = await server.get<string[]>(`attribute-names/?type=relation&query=${encodeURIComponent(queryText)}`);- return names.map(name => {+ return names.map((name) => {return {id: `~${name}`,name: name- }+ };});},minimumCharacters: 0@@ -130,53 +130,53 @@ const mentionSetup: MentionConfig = {const editorConfig = {removePlugins: [- 'Heading',- 'Link',- 'Autoformat',- 'Bold',- 'Italic',- 'Underline',- 'Strikethrough',- 'Code',- 'Superscript',- 'Subscript',- 'BlockQuote',- 'Image',- 'ImageCaption',- 'ImageStyle',- 'ImageToolbar',- 'ImageUpload',- 'ImageResize',- 'List',- 'TodoList',- 'PasteFromOffice',- 'Table',- 'TableToolbar',- 'TableProperties',- 'TableCellProperties',- 'Indent',- 'IndentBlock',- 'BlockToolbar',- 'ParagraphButtonUI',- 'HeadingButtonsUI',- 'UploadimagePlugin',- 'InternalLinkPlugin',- 'MarkdownImportPlugin',- 'CuttonotePlugin',- 'TextTransformation',- 'Font',- 'FontColor',- 'FontBackgroundColor',- 'CodeBlock',- 'SelectAll',- 'IncludeNote',- 'CutToNote',- 'Mathematics',- 'AutoformatMath',- 'indentBlockShortcutPlugin',- 'removeFormatLinksPlugin',- 'Footnotes',- 'Mermaid'+ "Heading",+ "Link",+ "Autoformat",+ "Bold",+ "Italic",+ "Underline",+ "Strikethrough",+ "Code",+ "Superscript",+ "Subscript",+ "BlockQuote",+ "Image",+ "ImageCaption",+ "ImageStyle",+ "ImageToolbar",+ "ImageUpload",+ "ImageResize",+ "List",+ "TodoList",+ "PasteFromOffice",+ "Table",+ "TableToolbar",+ "TableProperties",+ "TableCellProperties",+ "Indent",+ "IndentBlock",+ "BlockToolbar",+ "ParagraphButtonUI",+ "HeadingButtonsUI",+ "UploadimagePlugin",+ "InternalLinkPlugin",+ "MarkdownImportPlugin",+ "CuttonotePlugin",+ "TextTransformation",+ "Font",+ "FontColor",+ "FontBackgroundColor",+ "CodeBlock",+ "SelectAll",+ "IncludeNote",+ "CutToNote",+ "Mathematics",+ "AutoformatMath",+ "indentBlockShortcutPlugin",+ "removeFormatLinksPlugin",+ "Footnotes",+ "Mermaid"],toolbar: {items: []@@ -187,11 +187,7 @@ const editorConfig = {type AttributeCommandNames = FilteredCommandNames<CommandData>;-export default class AttributeEditorWidget extends NoteContextAwareWidget implements- EventListener<"entitiesReloaded">,- EventListener<"addNewLabel">,- EventListener<"addNewRelation"> {-+export default class AttributeEditorWidget extends NoteContextAwareWidget implements EventListener<"entitiesReloaded">, EventListener<"addNewLabel">, EventListener<"addNewRelation"> {private attributeDetailWidget: AttributeDetailWidget;private $editor!: JQuery<HTMLElement>;private $addNewAttributeButton!: JQuery<HTMLElement>;@@ -210,11 +206,11 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implemdoRender() {this.$widget = $(TPL);- this.$editor = this.$widget.find('.attribute-list-editor');+ this.$editor = this.$widget.find(".attribute-list-editor");this.initialized = this.initEditor();- this.$editor.on('keydown', async e => {+ this.$editor.on("keydown", async (e) => {if (e.which === 13) {// allow autocomplete to fill the result textareasetTimeout(() => this.save(), 100);@@ -223,48 +219,48 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implemthis.attributeDetailWidget.hide();});- this.$editor.on('blur', () => setTimeout(() => this.save(), 100)); // Timeout to fix https://github.com/zadam/trilium/issues/4160+ this.$editor.on("blur", () => setTimeout(() => this.save(), 100)); // Timeout to fix https://github.com/zadam/trilium/issues/4160- this.$addNewAttributeButton = this.$widget.find('.add-new-attribute-button');- this.$addNewAttributeButton.on('click', e => this.addNewAttribute(e));+ this.$addNewAttributeButton = this.$widget.find(".add-new-attribute-button");+ this.$addNewAttributeButton.on("click", (e) => this.addNewAttribute(e));- this.$saveAttributesButton = this.$widget.find('.save-attributes-button');- this.$saveAttributesButton.on('click', () => this.save());+ this.$saveAttributesButton = this.$widget.find(".save-attributes-button");+ this.$saveAttributesButton.on("click", () => this.save());- this.$errors = this.$widget.find('.attribute-errors');+ this.$errors = this.$widget.find(".attribute-errors");}addNewAttribute(e: JQuery.ClickEvent) {contextMenuService.show<AttributeCommandNames>({x: e.pageX,y: e.pageY,- orientation: 'left',+ orientation: "left",items: [{ title: t("attribute_editor.add_new_label"), command: "addNewLabel", uiIcon: "bx bx-hash" },{ title: t("attribute_editor.add_new_relation"), command: "addNewRelation", uiIcon: "bx bx-transfer" },{ title: "----" },{ title: t("attribute_editor.add_new_label_definition"), command: "addNewLabelDefinition", uiIcon: "bx bx-empty" },- { title: t("attribute_editor.add_new_relation_definition"), command: "addNewRelationDefinition", uiIcon: "bx bx-empty" },+ { title: t("attribute_editor.add_new_relation_definition"), command: "addNewRelationDefinition", uiIcon: "bx bx-empty" }],selectMenuItemHandler: ({ command }) => this.handleAddNewAttributeCommand(command)});}// triggered from keyboard shortcut- async addNewLabelEvent({ntxId}: EventData<"addNewLabel">) {+ async addNewLabelEvent({ ntxId }: EventData<"addNewLabel">) {if (this.isNoteContext(ntxId)) {await this.refresh();- this.handleAddNewAttributeCommand('addNewLabel');+ this.handleAddNewAttributeCommand("addNewLabel");}}// triggered from keyboard shortcut- async addNewRelationEvent({ntxId}: EventData<"addNewRelation">) {+ async addNewRelationEvent({ ntxId }: EventData<"addNewRelation">) {if (this.isNoteContext(ntxId)) {await this.refresh();- this.handleAddNewAttributeCommand('addNewRelation');+ this.handleAddNewAttributeCommand("addNewRelation");}}@@ -280,22 +276,22 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implemlet name;let value;- if (command === 'addNewLabel') {- type = 'label';- name = 'myLabel';- value = '';- } else if (command === 'addNewRelation') {- type = 'relation';- name = 'myRelation';- value = '';- } else if (command === 'addNewLabelDefinition') {- type = 'label';- name = 'label:myLabel';- value = 'promoted,single,text';- } else if (command === 'addNewRelationDefinition') {- type = 'label';- name = 'relation:myRelation';- value = 'promoted,single';+ if (command === "addNewLabel") {+ type = "label";+ name = "myLabel";+ value = "";+ } else if (command === "addNewRelation") {+ type = "relation";+ name = "myRelation";+ value = "";+ } else if (command === "addNewLabelDefinition") {+ type = "label";+ name = "label:myLabel";+ value = "promoted,single,text";+ } else if (command === "addNewRelationDefinition") {+ type = "label";+ name = "relation:myRelation";+ value = "promoted,single";} else {return;}@@ -323,7 +319,7 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implemisOwned: true,x: (rect.left + rect.right) / 2,y: rect.bottom,- focus: 'name'+ focus: "name"});}, 100);}@@ -343,10 +339,10 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implemthis.$saveAttributesButton.fadeOut();// blink the attribute text to give a visual hint that save has been executed- this.$editor.css('opacity', 0);+ this.$editor.css("opacity", 0);// revert back- setTimeout(() => this.$editor.css('opacity', 1), 100);+ setTimeout(() => this.$editor.css("opacity", 1), 100);}}@@ -359,7 +355,8 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implem}getPreprocessedData() {- const str = this.textEditor.getData()+ const str = this.textEditor+ .getData().replace(/<a[^>]+href="(#[A-Za-z0-9_/]*)"[^>]*>[^<]*<\/a>/g, "$1").replace(/ /g, " "); // otherwise .text() below outputs non-breaking space in unicode@@ -371,18 +368,22 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implemthis.$widget.show();- this.$editor.on("click", e => this.handleEditorClick(e));+ this.$editor.on("click", (e) => this.handleEditorClick(e));this.textEditor = await CKEditor.BalloonEditor.create(this.$editor[0], editorConfig);- this.textEditor.model.document.on('change:data', () => this.dataChanged());- this.textEditor.editing.view.document.on('enter', (event, data) => {- // disable entering new line - see https://github.com/ckeditor/ckeditor5/issues/9422- data.preventDefault();- event.stop();- }, {priority: 'high'});+ this.textEditor.model.document.on("change:data", () => this.dataChanged());+ this.textEditor.editing.view.document.on(+ "enter",+ (event, data) => {+ // disable entering new line - see https://github.com/ckeditor/ckeditor5/issues/9422+ data.preventDefault();+ event.stop();+ },+ { priority: "high" }+ );// disable spellcheck for attribute editor- this.textEditor.editing.view.change(writer => writer.setAttribute('spellcheck', 'false', this.textEditor.editing.view.document.getRoot()));+ this.textEditor.editing.view.change((writer) => writer.setAttribute("spellcheck", "false", this.textEditor.editing.view.document.getRoot()));}dataChanged() {@@ -390,8 +391,7 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implemif (this.lastSavedContent === this.textEditor.getData()) {this.$saveAttributesButton.fadeOut();- }- else {+ } else {this.$saveAttributesButton.fadeIn();}@@ -412,8 +412,7 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implemtry {parsedAttrs = attributeParser.lexAndParse(this.getPreprocessedData(), true);- }- catch (e) {+ } catch (e) {// the input is incorrect because the user messed up with it and now needs to fix it manuallyreturn null;}@@ -421,8 +420,7 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implemlet matchedAttr = null;for (const attr of parsedAttrs) {- if (attr.startIndex && clickIndex > attr.startIndex &&- attr.endIndex && clickIndex <= attr.endIndex) {+ if (attr.startIndex && clickIndex > attr.startIndex && attr.endIndex && clickIndex <= attr.endIndex) {matchedAttr = attr;break;}@@ -430,7 +428,7 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implemsetTimeout(() => {if (matchedAttr) {- this.$editor.tooltip('hide');+ this.$editor.tooltip("hide");this.attributeDetailWidget.showAttributeDetail({allAttributes: parsedAttrs,@@ -439,13 +437,11 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implemx: e.pageX,y: e.pageY});- }- else {+ } else {this.showHelpTooltip();}}, 100);- }- else {+ } else {this.showHelpTooltip();}}@@ -454,14 +450,14 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implemthis.attributeDetailWidget.hide();this.$editor.tooltip({- trigger: 'focus',+ trigger: "focus",html: true,title: HELP_TEXT,- placement: 'bottom',+ placement: "bottom",offset: "0,30"});- this.$editor.tooltip('show');+ this.$editor.tooltip("show");}getClickIndex(pos: TextPosition) {@@ -472,8 +468,8 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implemwhile (curNode.previousSibling) {curNode = curNode.previousSibling;- if (curNode.name === 'reference') {- clickIndex += curNode._attrs.get('notePath').length + 1;+ if (curNode.name === "reference") {+ clickIndex += curNode._attrs.get("notePath").length + 1;} else {clickIndex += curNode.data.length;}@@ -483,9 +479,9 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implem}async loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string) {- const {noteId} = linkService.parseNavigationStateFromUrl(href);+ const { noteId } = linkService.parseNavigationStateFromUrl(href);const note = noteId ? await froca.getNote(noteId, true) : null;- const title = note ? note.title : '[missing]';+ const title = note ? note.title : "[missing]";$el.text(title);}@@ -530,19 +526,18 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget implem}focus() {- this.$editor.trigger('focus');+ this.$editor.trigger("focus");- this.textEditor.model.change( writer => {- const positionAt = writer.createPositionAt(this.textEditor.model.document.getRoot(), 'end');+ this.textEditor.model.change((writer) => {+ const positionAt = writer.createPositionAt(this.textEditor.model.document.getRoot(), "end");writer.setSelection(positionAt);- } );+ });}- entitiesReloadedEvent({loadResults}: EventData<"entitiesReloaded">) {- if (loadResults.getAttributeRows(this.componentId).find(attr => attributeService.isAffecting(attr, this.note))) {+ entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {+ if (loadResults.getAttributeRows(this.componentId).find((attr) => attributeService.isAffecting(attr, this.note))) {this.refresh();}}-}diff --git a/src/public/app/widgets/basic_widget.ts b/src/public/app/widgets/basic_widget.tsindex bbf7347752..ec10acde6d 100644--- a/src/public/app/widgets/basic_widget.ts+++ b/src/public/app/widgets/basic_widget.ts@@ -14,7 +14,7 @@ export class TypedBasicWidget<T extends TypedComponent<any>> extends TypedComponsuper();this.attrs = {- style: ''+ style: ""};this.classes = [];@@ -101,13 +101,13 @@ export class TypedBasicWidget<T extends TypedComponent<any>> extends TypedCompon}collapsible() {- this.css('min-height', '0');- this.css('min-width', '0');+ this.css("min-height", "0");+ this.css("min-width", "0");return this;}filling() {- this.css('flex-grow', '1');+ this.css("flex-grow", "1");return this;}@@ -127,31 +127,28 @@ export class TypedBasicWidget<T extends TypedComponent<any>> extends TypedComponthis.logRenderingError(e);}- this.$widget.attr('data-component-id', this.componentId);- this.$widget- .addClass('component')- .prop('component', this);+ this.$widget.attr("data-component-id", this.componentId);+ this.$widget.addClass("component").prop("component", this);if (!this.isEnabled()) {this.toggleInt(false);}if (this.cssEl) {- const css = this.cssEl.trim().startsWith('<style>') ? this.cssEl : `<style>${this.cssEl}</style>`;+ const css = this.cssEl.trim().startsWith("<style>") ? this.cssEl : `<style>${this.cssEl}</style>`;this.$widget.append(css);}for (const key in this.attrs) {- if (key === 'style') {+ if (key === "style") {if (this.attrs[key]) {- let style = this.$widget.attr('style');+ let style = this.$widget.attr("style");style = style ? `${style}; ${this.attrs[key]}` : this.attrs[key];this.$widget.attr(key, style);}- }- else {+ } else {this.$widget.attr(key, this.attrs[key]);}}@@ -209,19 +206,19 @@ export class TypedBasicWidget<T extends TypedComponent<any>> extends TypedCompondoRender() {}toggleInt(show: boolean) {- this.$widget.toggleClass('hidden-int', !show);+ this.$widget.toggleClass("hidden-int", !show);}isHiddenInt() {- return this.$widget.hasClass('hidden-int');+ return this.$widget.hasClass("hidden-int");}toggleExt(show: boolean) {- this.$widget.toggleClass('hidden-ext', !show);+ this.$widget.toggleClass("hidden-ext", !show);}isHiddenExt() {- return this.$widget.hasClass('hidden-ext');+ return this.$widget.hasClass("hidden-ext");}canBeShown() {@@ -245,8 +242,7 @@ export class TypedBasicWidget<T extends TypedComponent<any>> extends TypedCompongetClosestNtxId() {if (this.$widget) {return this.$widget.closest("[data-ntx-id]").attr("data-ntx-id");- }- else {+ } else {return null;}}@@ -259,6 +255,4 @@ export class TypedBasicWidget<T extends TypedComponent<any>> extends TypedCompon** For information on using widgets, see the tutorial {@tutorial widget_basics}.*/-export default class BasicWidget extends TypedBasicWidget<Component> {--}+export default class BasicWidget extends TypedBasicWidget<Component> {}diff --git a/src/public/app/widgets/bookmark_buttons.js b/src/public/app/widgets/bookmark_buttons.jsindex 1cb519e699..7675222399 100644--- a/src/public/app/widgets/bookmark_buttons.js+++ b/src/public/app/widgets/bookmark_buttons.js@@ -16,15 +16,12 @@ export default class BookmarkButtons extends FlexContainer {this.children = [];this.noteIds = [];- const bookmarkParentNote = await froca.getNote('_lbBookmarks');+ const bookmarkParentNote = await froca.getNote("_lbBookmarks");for (const note of await bookmarkParentNote.getChildNotes()) {this.noteIds.push(note.noteId);- const buttonWidget = note.isLabelTruthy("bookmarkFolder")- ? new BookmarkFolderWidget(note)- : new OpenNoteButtonWidget(note)- .class("launcher-button");+ const buttonWidget = note.isLabelTruthy("bookmarkFolder") ? new BookmarkFolderWidget(note) : new OpenNoteButtonWidget(note).class("launcher-button");if (this.settings.titlePlacement) {if (!buttonWidget.settings) {buttonWidget = {};@@ -44,15 +41,12 @@ export default class BookmarkButtons extends FlexContainer {this.refresh();}- entitiesReloadedEvent({loadResults}) {- if (loadResults.getBranchRows().find(branch => branch.parentNoteId === '_lbBookmarks')) {+ entitiesReloadedEvent({ loadResults }) {+ if (loadResults.getBranchRows().find((branch) => branch.parentNoteId === "_lbBookmarks")) {this.refresh();}- if (loadResults.getAttributeRows().find(attr => attr.type === 'label'- && ['iconClass', 'workspaceIconClass', 'bookmarkFolder'].includes(attr.name)- && this.noteIds.includes(attr.noteId))- ) {+ if (loadResults.getAttributeRows().find((attr) => attr.type === "label" && ["iconClass", "workspaceIconClass", "bookmarkFolder"].includes(attr.name) && this.noteIds.includes(attr.noteId))) {this.refresh();}}diff --git a/src/public/app/widgets/bookmark_switch.js b/src/public/app/widgets/bookmark_switch.jsindex ab9055df1c..acf940c7ac 100644--- a/src/public/app/widgets/bookmark_switch.js+++ b/src/public/app/widgets/bookmark_switch.js@@ -5,9 +5,11 @@ import { t } from "../services/i18n.js";export default class BookmarkSwitchWidget extends SwitchWidget {isEnabled() {- return super.isEnabled()+ return (+ super.isEnabled() &&// it's not possible to bookmark root because that would clone it under bookmarks and thus create a cycle- && !['root', '_hidden'].includes(this.noteId);+ !["root", "_hidden"].includes(this.noteId)+ );}doRender() {@@ -29,14 +31,14 @@ export default class BookmarkSwitchWidget extends SwitchWidget {}async refreshWithNote(note) {- const isBookmarked = !!note.getParentBranches().find(b => b.parentNoteId === '_lbBookmarks');+ const isBookmarked = !!note.getParentBranches().find((b) => b.parentNoteId === "_lbBookmarks");this.$switchOn.toggle(!isBookmarked);this.$switchOff.toggle(isBookmarked);}- entitiesReloadedEvent({loadResults}) {- if (loadResults.getBranchRows().find(b => b.noteId === this.noteId)) {+ entitiesReloadedEvent({ loadResults }) {+ if (loadResults.getBranchRows().find((b) => b.noteId === this.noteId)) {this.refresh();}}diff --git a/src/public/app/widgets/bulk_actions/abstract_bulk_action.ts b/src/public/app/widgets/bulk_actions/abstract_bulk_action.tsindex d1cf333b5a..436f8fbd86 100644--- a/src/public/app/widgets/bulk_actions/abstract_bulk_action.ts+++ b/src/public/app/widgets/bulk_actions/abstract_bulk_action.ts@@ -31,9 +31,10 @@ export default abstract class AbstractBulkAction {try {const $rendered = this.doRender();- $rendered.find('.action-conf-del')- .on('click', () => this.deleteAction())- .attr('title', t('abstract_bulk_action.remove_this_search_action'));+ $rendered+ .find(".action-conf-del")+ .on("click", () => this.deleteAction())+ .attr("title", t("abstract_bulk_action.remove_this_search_action"));utils.initHelpDropdown($rendered);@@ -46,15 +47,17 @@ export default abstract class AbstractBulkAction {// to be overriddenabstract doRender(): JQuery<HTMLElement>;- static get actionName() { return ""; }+ static get actionName() {+ return "";+ }async saveAction(data: {}) {const actionObject = Object.assign({ name: (this.constructor as typeof AbstractBulkAction).actionName }, data);await server.put(`notes/${this.attribute.noteId}/attribute`, {attributeId: this.attribute.attributeId,- type: 'label',- name: 'action',+ type: "label",+ name: "action",value: JSON.stringify(actionObject)});diff --git a/src/public/app/widgets/bulk_actions/execute_script.ts b/src/public/app/widgets/bulk_actions/execute_script.tsindex f28a5b3486..6d363d8b75 100644--- a/src/public/app/widgets/bulk_actions/execute_script.ts+++ b/src/public/app/widgets/bulk_actions/execute_script.ts@@ -5,7 +5,7 @@ import AbstractBulkAction from "./abstract_bulk_action.js";const TPL = `<tr><td>- ${t('execute_script.execute_script')}+ ${t("execute_script.execute_script")}</td><td><input type="text"@@ -17,13 +17,13 @@ const TPL = `<div class="dropdown help-dropdown"><span class="bx bx-help-circle icon-action" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span><div class="dropdown-menu dropdown-menu-right p-4">- ${t('execute_script.help_text')}+ ${t("execute_script.help_text")}- ${t('execute_script.example_1')}+ ${t("execute_script.example_1")}<pre>note.title = note.title + ' - suffix';</pre>- ${t('execute_script.example_2')}+ ${t("execute_script.example_2")}<pre>for (const attr of note.getOwnedAttributes) { attr.markAsDeleted(); }</pre></div>@@ -35,19 +35,23 @@ const TPL = `</tr>`;export default class ExecuteScriptBulkAction extends AbstractBulkAction {- static get actionName() { return "executeScript"; }- static get actionTitle() { return t("execute_script.execute_script"); }+ static get actionName() {+ return "executeScript";+ }+ static get actionTitle() {+ return t("execute_script.execute_script");+ }doRender() {const $action = $(TPL);- const $script = $action.find('.script');+ const $script = $action.find(".script");$script.val(this.actionDef.script || "");const spacedUpdate = new SpacedUpdate(async () => {await this.saveAction({ script: $script.val() });}, 1000);- $script.on('input', () => spacedUpdate.scheduleUpdate());+ $script.on("input", () => spacedUpdate.scheduleUpdate());return $action;}diff --git a/src/public/app/widgets/bulk_actions/label/add_label.ts b/src/public/app/widgets/bulk_actions/label/add_label.tsindex d5e4fa6fb0..df0c1e0067 100644--- a/src/public/app/widgets/bulk_actions/label/add_label.ts+++ b/src/public/app/widgets/bulk_actions/label/add_label.ts@@ -39,16 +39,20 @@ const TPL = `</tr>`;export default class AddLabelBulkAction extends AbstractBulkAction {- static get actionName() { return "addLabel"; }- static get actionTitle() { return t("add_label.add_label"); }+ static get actionName() {+ return "addLabel";+ }+ static get actionTitle() {+ return t("add_label.add_label");+ }doRender() {const $action = $(TPL);- const $labelName = $action.find('.label-name');+ const $labelName = $action.find(".label-name");$labelName.val(this.actionDef.labelName || "");- const $labelValue = $action.find('.label-value');+ const $labelValue = $action.find(".label-value");$labelValue.val(this.actionDef.labelValue || "");const spacedUpdate = new SpacedUpdate(async () => {@@ -58,8 +62,8 @@ export default class AddLabelBulkAction extends AbstractBulkAction {});}, 1000);- $labelName.on('input', () => spacedUpdate.scheduleUpdate());- $labelValue.on('input', () => spacedUpdate.scheduleUpdate());+ $labelName.on("input", () => spacedUpdate.scheduleUpdate());+ $labelValue.on("input", () => spacedUpdate.scheduleUpdate());return $action;}diff --git a/src/public/app/widgets/bulk_actions/label/delete_label.ts b/src/public/app/widgets/bulk_actions/label/delete_label.tsindex ba2c393a01..4fc92499a3 100644--- a/src/public/app/widgets/bulk_actions/label/delete_label.ts+++ b/src/public/app/widgets/bulk_actions/label/delete_label.ts@@ -20,19 +20,23 @@ const TPL = `</tr>`;export default class DeleteLabelBulkAction extends AbstractBulkAction {- static get actionName() { return "deleteLabel"; }- static get actionTitle() { return t("delete_label.delete_label"); }+ static get actionName() {+ return "deleteLabel";+ }+ static get actionTitle() {+ return t("delete_label.delete_label");+ }doRender() {const $action = $(TPL);- const $labelName = $action.find('.label-name');+ const $labelName = $action.find(".label-name");$labelName.val(this.actionDef.labelName || "");const spacedUpdate = new SpacedUpdate(async () => {await this.saveAction({ labelName: $labelName.val() });- }, 1000)+ }, 1000);- $labelName.on('input', () => spacedUpdate.scheduleUpdate());+ $labelName.on("input", () => spacedUpdate.scheduleUpdate());return $action;}diff --git a/src/public/app/widgets/bulk_actions/label/rename_label.ts b/src/public/app/widgets/bulk_actions/label/rename_label.tsindex c250e795c9..afda38a81e 100644--- a/src/public/app/widgets/bulk_actions/label/rename_label.ts+++ b/src/public/app/widgets/bulk_actions/label/rename_label.ts@@ -29,16 +29,20 @@ const TPL = `</tr>`;export default class RenameLabelBulkAction extends AbstractBulkAction {- static get actionName() { return "renameLabel"; }- static get actionTitle() { return t("rename_label.rename_label"); }+ static get actionName() {+ return "renameLabel";+ }+ static get actionTitle() {+ return t("rename_label.rename_label");+ }doRender() {const $action = $(TPL);- const $oldLabelName = $action.find('.old-label-name');+ const $oldLabelName = $action.find(".old-label-name");$oldLabelName.val(this.actionDef.oldLabelName || "");- const $newLabelName = $action.find('.new-label-name');+ const $newLabelName = $action.find(".new-label-name");$newLabelName.val(this.actionDef.newLabelName || "");const spacedUpdate = new SpacedUpdate(async () => {@@ -48,8 +52,8 @@ export default class RenameLabelBulkAction extends AbstractBulkAction {});}, 1000);- $oldLabelName.on('input', () => spacedUpdate.scheduleUpdate());- $newLabelName.on('input', () => spacedUpdate.scheduleUpdate());+ $oldLabelName.on("input", () => spacedUpdate.scheduleUpdate());+ $newLabelName.on("input", () => spacedUpdate.scheduleUpdate());return $action;}diff --git a/src/public/app/widgets/bulk_actions/label/update_label_value.ts b/src/public/app/widgets/bulk_actions/label/update_label_value.tsindex 56137e5fd6..dcd731bd53 100644--- a/src/public/app/widgets/bulk_actions/label/update_label_value.ts+++ b/src/public/app/widgets/bulk_actions/label/update_label_value.ts@@ -34,16 +34,20 @@ const TPL = `</tr>`;export default class UpdateLabelValueBulkAction extends AbstractBulkAction {- static get actionName() { return "updateLabelValue"; }- static get actionTitle() { return t("update_label_value.update_label_value"); }+ static get actionName() {+ return "updateLabelValue";+ }+ static get actionTitle() {+ return t("update_label_value.update_label_value");+ }doRender() {const $action = $(TPL);- const $labelName = $action.find('.label-name');+ const $labelName = $action.find(".label-name");$labelName.val(this.actionDef.labelName || "");- const $labelValue = $action.find('.label-value');+ const $labelValue = $action.find(".label-value");$labelValue.val(this.actionDef.labelValue || "");const spacedUpdate = new SpacedUpdate(async () => {@@ -51,10 +55,10 @@ export default class UpdateLabelValueBulkAction extends AbstractBulkAction {labelName: $labelName.val(),labelValue: $labelValue.val()});- }, 1000)+ }, 1000);- $labelName.on('input', () => spacedUpdate.scheduleUpdate());- $labelValue.on('input', () => spacedUpdate.scheduleUpdate());+ $labelName.on("input", () => spacedUpdate.scheduleUpdate());+ $labelValue.on("input", () => spacedUpdate.scheduleUpdate());return $action;}diff --git a/src/public/app/widgets/bulk_actions/note/delete_note.ts b/src/public/app/widgets/bulk_actions/note/delete_note.tsindex d1708dd030..3899390c9e 100644--- a/src/public/app/widgets/bulk_actions/note/delete_note.ts+++ b/src/public/app/widgets/bulk_actions/note/delete_note.ts@@ -25,8 +25,12 @@ const TPL = `</tr>`;export default class DeleteNoteBulkAction extends AbstractBulkAction {- static get actionName() { return "deleteNote"; }- static get actionTitle() { return t("delete_note.delete_note"); }+ static get actionName() {+ return "deleteNote";+ }+ static get actionTitle() {+ return t("delete_note.delete_note");+ }doRender() {return $(TPL);diff --git a/src/public/app/widgets/bulk_actions/note/delete_revisions.ts b/src/public/app/widgets/bulk_actions/note/delete_revisions.tsindex d6363f3aba..25ecf247f1 100644--- a/src/public/app/widgets/bulk_actions/note/delete_revisions.ts+++ b/src/public/app/widgets/bulk_actions/note/delete_revisions.ts@@ -5,13 +5,13 @@ const TPL = `<tr><td colspan="2"><span class="bx bx-trash"></span>- ${t('delete_revisions.delete_note_revisions')}+ ${t("delete_revisions.delete_note_revisions")}</td><td class="button-column"><div class="dropdown help-dropdown"><span class="bx bx-help-circle icon-action" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span><div class="dropdown-menu dropdown-menu-right p-4">- ${t('delete_revisions.all_past_note_revisions')}+ ${t("delete_revisions.all_past_note_revisions")}</div></div><span class="bx bx-x icon-action action-conf-del"></span>@@ -19,8 +19,12 @@ const TPL = `</tr>`;export default class DeleteRevisionsBulkAction extends AbstractBulkAction {- static get actionName() { return "deleteRevisions"; }- static get actionTitle() { return t('delete_revisions.delete_note_revisions'); }+ static get actionName() {+ return "deleteRevisions";+ }+ static get actionTitle() {+ return t("delete_revisions.delete_note_revisions");+ }doRender() {return $(TPL);diff --git a/src/public/app/widgets/bulk_actions/note/move_note.ts b/src/public/app/widgets/bulk_actions/note/move_note.tsindex 440cd4bd6d..7d11270126 100644--- a/src/public/app/widgets/bulk_actions/note/move_note.ts+++ b/src/public/app/widgets/bulk_actions/note/move_note.ts@@ -7,12 +7,12 @@ const TPL = `<tr><td colspan="2"><div style="display: flex; align-items: center">- <div style="margin-right: 10px;" class="text-nowrap">${t('move_note.move_note')}</div>+ <div style="margin-right: 10px;" class="text-nowrap">${t("move_note.move_note")}</div>- <div style="margin-right: 10px;" class="text-nowrap">${t('move_note.to')}</div>+ <div style="margin-right: 10px;" class="text-nowrap">${t("move_note.to")}</div><div class="input-group">- <input type="text" class="form-control target-parent-note" placeholder="${t('move_note.target_parent_note')}"/>+ <input type="text" class="form-control target-parent-note" placeholder="${t("move_note.target_parent_note")}"/></div></div></td>@@ -20,12 +20,12 @@ const TPL = `<div class="dropdown help-dropdown"><span class="bx bx-help-circle icon-action" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span><div class="dropdown-menu dropdown-menu-right p-4">- <p>${t('move_note.on_all_matched_notes')}:</p>+ <p>${t("move_note.on_all_matched_notes")}:</p><ul style="margin-bottom: 0;">- <li>${t('move_note.move_note_new_parent')}</li>- <li>${t('move_note.clone_note_new_parent')}</li>- <li>${t('move_note.nothing_will_happen')}</li>+ <li>${t("move_note.move_note_new_parent")}</li>+ <li>${t("move_note.clone_note_new_parent")}</li>+ <li>${t("move_note.nothing_will_happen")}</li></ul></div></div>@@ -35,25 +35,29 @@ const TPL = `</tr>`;export default class MoveNoteBulkAction extends AbstractBulkAction {- static get actionName() { return "moveNote"; }- static get actionTitle() { return t('move_note.move_note'); }+ static get actionName() {+ return "moveNote";+ }+ static get actionTitle() {+ return t("move_note.move_note");+ }doRender() {const $action = $(TPL);- const $targetParentNote = $action.find('.target-parent-note');+ const $targetParentNote = $action.find(".target-parent-note");noteAutocompleteService.initNoteAutocomplete($targetParentNote);$targetParentNote.setNote(this.actionDef.targetParentNoteId);- $targetParentNote.on('autocomplete:closed', () => spacedUpdate.scheduleUpdate());+ $targetParentNote.on("autocomplete:closed", () => spacedUpdate.scheduleUpdate());const spacedUpdate = new SpacedUpdate(async () => {await this.saveAction({targetParentNoteId: $targetParentNote.getSelectedNoteId()});- }, 1000)+ }, 1000);- $targetParentNote.on('input', () => spacedUpdate.scheduleUpdate());+ $targetParentNote.on("input", () => spacedUpdate.scheduleUpdate());return $action;}diff --git a/src/public/app/widgets/bulk_actions/note/rename_note.ts b/src/public/app/widgets/bulk_actions/note/rename_note.tsindex 355992707c..0f610ebcce 100644--- a/src/public/app/widgets/bulk_actions/note/rename_note.ts+++ b/src/public/app/widgets/bulk_actions/note/rename_note.ts@@ -6,27 +6,27 @@ const TPL = `<tr><td colspan="2"><div style="display: flex; align-items: center">- <div style="margin-right: 10px; flex-shrink: 0;">${t('rename_note.rename_note_title_to')}</div>+ <div style="margin-right: 10px; flex-shrink: 0;">${t("rename_note.rename_note_title_to")}</div><input type="text"class="form-control new-title"- placeholder="${t('rename_note.new_note_title')}"- title="${t('rename_note.click_help_icon')}"/>+ placeholder="${t("rename_note.new_note_title")}"+ title="${t("rename_note.click_help_icon")}"/></div></td><td class="button-column"><div class="dropdown help-dropdown"><span class="bx bx-help-circle icon-action" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span><div class="dropdown-menu dropdown-menu-right p-4">- <p>${t('rename_note.evaluated_as_js_string')}</p>+ <p>${t("rename_note.evaluated_as_js_string")}</p><ul>- <li>${t('rename_note.example_note')}</li>- <li>${t('rename_note.example_new_title')}</li>- <li>${t('rename_note.example_date_prefix')}</li>+ <li>${t("rename_note.example_note")}</li>+ <li>${t("rename_note.example_new_title")}</li>+ <li>${t("rename_note.example_date_prefix")}</li></ul>- ${t('rename_note.api_docs')}+ ${t("rename_note.api_docs")}</div></div>@@ -35,22 +35,26 @@ const TPL = `</tr>`;export default class RenameNoteBulkAction extends AbstractBulkAction {- static get actionName() { return "renameNote"; }- static get actionTitle() { return t('rename_note.rename_note'); }+ static get actionName() {+ return "renameNote";+ }+ static get actionTitle() {+ return t("rename_note.rename_note");+ }doRender() {const $action = $(TPL);- const $newTitle = $action.find('.new-title');+ const $newTitle = $action.find(".new-title");$newTitle.val(this.actionDef.newTitle || "");const spacedUpdate = new SpacedUpdate(async () => {await this.saveAction({- newTitle: $newTitle.val(),+ newTitle: $newTitle.val()});}, 1000);- $newTitle.on('input', () => spacedUpdate.scheduleUpdate());+ $newTitle.on("input", () => spacedUpdate.scheduleUpdate());return $action;}diff --git a/src/public/app/widgets/bulk_actions/relation/add_relation.ts b/src/public/app/widgets/bulk_actions/relation/add_relation.tsindex 6dfb6c06d1..55efee54dd 100644--- a/src/public/app/widgets/bulk_actions/relation/add_relation.ts+++ b/src/public/app/widgets/bulk_actions/relation/add_relation.ts@@ -7,19 +7,19 @@ const TPL = `<tr><td colspan="2"><div style="display: flex; align-items: center">- <div style="margin-right: 10px;" class="text-nowrap">${t('add_relation.add_relation')}</div>+ <div style="margin-right: 10px;" class="text-nowrap">${t("add_relation.add_relation")}</div><input type="text"class="form-control relation-name"- placeholder="${t('add_relation.relation_name')}"+ placeholder="${t("add_relation.relation_name")}"pattern="[\\p{L}\\p{N}_:]+"style="flex-shrink: 3"- title="${t('add_relation.allowed_characters')}"/>+ title="${t("add_relation.allowed_characters")}"/>- <div style="margin-right: 10px; margin-left: 10px;" class="text-nowrap">${t('add_relation.to')}</div>+ <div style="margin-right: 10px; margin-left: 10px;" class="text-nowrap">${t("add_relation.to")}</div><div class="input-group" style="flex-shrink: 2">- <input type="text" class="form-control target-note" placeholder="${t('add_relation.target_note')}"/>+ <input type="text" class="form-control target-note" placeholder="${t("add_relation.target_note")}"/></div></div></td>@@ -27,7 +27,7 @@ const TPL = `<div class="dropdown help-dropdown"><span class="bx bx-help-circle icon-action" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span><div class="dropdown-menu dropdown-menu-right p-4">- ${t('add_relation.create_relation_on_all_matched_notes')}+ ${t("add_relation.create_relation_on_all_matched_notes")}</div></div>@@ -36,20 +36,24 @@ const TPL = `</tr>`;export default class AddRelationBulkAction extends AbstractBulkAction {- static get actionName() { return "addRelation"; }- static get actionTitle() { return t('add_relation.add_relation'); }+ static get actionName() {+ return "addRelation";+ }+ static get actionTitle() {+ return t("add_relation.add_relation");+ }doRender() {const $action = $(TPL);- const $relationName = $action.find('.relation-name');+ const $relationName = $action.find(".relation-name");$relationName.val(this.actionDef.relationName || "");- const $targetNote = $action.find('.target-note');+ const $targetNote = $action.find(".target-note");noteAutocompleteService.initNoteAutocomplete($targetNote);$targetNote.setNote(this.actionDef.targetNoteId);- $targetNote.on('autocomplete:closed', () => spacedUpdate.scheduleUpdate());+ $targetNote.on("autocomplete:closed", () => spacedUpdate.scheduleUpdate());const spacedUpdate = new SpacedUpdate(async () => {await this.saveAction({@@ -58,8 +62,8 @@ export default class AddRelationBulkAction extends AbstractBulkAction {});}, 1000);- $relationName.on('input', () => spacedUpdate.scheduleUpdate());- $targetNote.on('input', () => spacedUpdate.scheduleUpdate());+ $relationName.on("input", () => spacedUpdate.scheduleUpdate());+ $targetNote.on("input", () => spacedUpdate.scheduleUpdate());return $action;}diff --git a/src/public/app/widgets/bulk_actions/relation/delete_relation.ts b/src/public/app/widgets/bulk_actions/relation/delete_relation.tsindex f382841a8d..379f4760c4 100644--- a/src/public/app/widgets/bulk_actions/relation/delete_relation.ts+++ b/src/public/app/widgets/bulk_actions/relation/delete_relation.ts@@ -5,15 +5,15 @@ import { t } from "../../../services/i18n.js";const TPL = `<tr><td>- ${t('delete_relation.delete_relation')}+ ${t("delete_relation.delete_relation")}</td><td><div style="display: flex; align-items: center"><input type="text"class="form-control relation-name"pattern="[\\p{L}\\p{N}_:]+"- placeholder="${t('delete_relation.relation_name')}"- title="${t('delete_relation.allowed_characters')}"/>+ placeholder="${t("delete_relation.relation_name")}"+ title="${t("delete_relation.allowed_characters")}"/></div></td><td class="button-column">@@ -22,19 +22,23 @@ const TPL = `</tr>`;export default class DeleteRelationBulkAction extends AbstractBulkAction {- static get actionName() { return "deleteRelation"; }- static get actionTitle() { return t('delete_relation.delete_relation'); }+ static get actionName() {+ return "deleteRelation";+ }+ static get actionTitle() {+ return t("delete_relation.delete_relation");+ }doRender() {const $action = $(TPL);- const $relationName = $action.find('.relation-name');+ const $relationName = $action.find(".relation-name");$relationName.val(this.actionDef.relationName || "");const spacedUpdate = new SpacedUpdate(async () => {await this.saveAction({ relationName: $relationName.val() });}, 1000);- $relationName.on('input', () => spacedUpdate.scheduleUpdate());+ $relationName.on("input", () => spacedUpdate.scheduleUpdate());return $action;}diff --git a/src/public/app/widgets/bulk_actions/relation/rename_relation.ts b/src/public/app/widgets/bulk_actions/relation/rename_relation.tsindex a2b3e98862..5cb8dc35ba 100644--- a/src/public/app/widgets/bulk_actions/relation/rename_relation.ts+++ b/src/public/app/widgets/bulk_actions/relation/rename_relation.ts@@ -6,21 +6,21 @@ const TPL = `<tr><td colspan="2"><div style="display: flex; align-items: center">- <div style="margin-right: 10px; flex-shrink: 0;">${t('rename_relation.rename_relation_from')}</div>+ <div style="margin-right: 10px; flex-shrink: 0;">${t("rename_relation.rename_relation_from")}</div><input type="text"class="form-control old-relation-name"- placeholder="${t('rename_relation.old_name')}"+ placeholder="${t("rename_relation.old_name")}"pattern="[\\p{L}\\p{N}_:]+"- title="${t('rename_relation.allowed_characters')}"/>+ title="${t("rename_relation.allowed_characters")}"/>- <div style="margin-right: 10px; margin-left: 10px;" class="text-nowrap">${t('rename_relation.to')}</div>+ <div style="margin-right: 10px; margin-left: 10px;" class="text-nowrap">${t("rename_relation.to")}</div><input type="text"class="form-control new-relation-name"- placeholder="${t('rename_relation.new_name')}"+ placeholder="${t("rename_relation.new_name")}"pattern="[\\p{L}\\p{N}_:]+"- title="${t('rename_relation.allowed_characters')}"/>+ title="${t("rename_relation.allowed_characters")}"/></div></td><td class="button-column">@@ -29,16 +29,20 @@ const TPL = `</tr>`;export default class RenameRelationBulkAction extends AbstractBulkAction {- static get actionName() { return "renameRelation"; }- static get actionTitle() { return t('rename_relation.rename_relation'); }+ static get actionName() {+ return "renameRelation";+ }+ static get actionTitle() {+ return t("rename_relation.rename_relation");+ }doRender() {const $action = $(TPL);- const $oldRelationName = $action.find('.old-relation-name');+ const $oldRelationName = $action.find(".old-relation-name");$oldRelationName.val(this.actionDef.oldRelationName || "");- const $newRelationName = $action.find('.new-relation-name');+ const $newRelationName = $action.find(".new-relation-name");$newRelationName.val(this.actionDef.newRelationName || "");const spacedUpdate = new SpacedUpdate(async () => {@@ -48,8 +52,8 @@ export default class RenameRelationBulkAction extends AbstractBulkAction {});}, 1000);- $oldRelationName.on('input', () => spacedUpdate.scheduleUpdate());- $newRelationName.on('input', () => spacedUpdate.scheduleUpdate());+ $oldRelationName.on("input", () => spacedUpdate.scheduleUpdate());+ $newRelationName.on("input", () => spacedUpdate.scheduleUpdate());return $action;}diff --git a/src/public/app/widgets/bulk_actions/relation/update_relation_target.ts b/src/public/app/widgets/bulk_actions/relation/update_relation_target.tsindex f4b28d034e..e839e8c41e 100644--- a/src/public/app/widgets/bulk_actions/relation/update_relation_target.ts+++ b/src/public/app/widgets/bulk_actions/relation/update_relation_target.ts@@ -7,19 +7,19 @@ const TPL = `<tr><td colspan="2"><div style="display: flex; align-items: center">- <div style="margin-right: 10px;" class="text-nowrap">${t('update_relation_target.update_relation')}</div>+ <div style="margin-right: 10px;" class="text-nowrap">${t("update_relation_target.update_relation")}</div><input type="text"class="form-control relation-name"- placeholder="${t('update_relation_target.relation_name')}"+ placeholder="${t("update_relation_target.relation_name")}"pattern="[\\p{L}\\p{N}_:]+"style="flex-shrink: 3"- title="${t('update_relation_target.allowed_characters')}"/>+ title="${t("update_relation_target.allowed_characters")}"/>- <div style="margin-right: 10px; margin-left: 10px;" class="text-nowrap">${t('update_relation_target.to')}</div>+ <div style="margin-right: 10px; margin-left: 10px;" class="text-nowrap">${t("update_relation_target.to")}</div><div class="input-group" style="flex-shrink: 2">- <input type="text" class="form-control target-note" placeholder="${t('update_relation_target.target_note')}"/>+ <input type="text" class="form-control target-note" placeholder="${t("update_relation_target.target_note")}"/></div></div></td>@@ -27,11 +27,11 @@ const TPL = `<div class="dropdown help-dropdown"><span class="bx bx-help-circle icon-action" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span><div class="dropdown-menu dropdown-menu-right p-4">- <p>${t('update_relation_target.on_all_matched_notes')}:</p>+ <p>${t("update_relation_target.on_all_matched_notes")}:</p><ul style="margin-bottom: 0;">- <li>${t('update_relation_target.create_given_relation')}</li>- <li>${t('update_relation_target.change_target_note')}</li>+ <li>${t("update_relation_target.create_given_relation")}</li>+ <li>${t("update_relation_target.change_target_note")}</li></ul></div></div>@@ -41,20 +41,24 @@ const TPL = `</tr>`;export default class UpdateRelationTargetBulkAction extends AbstractBulkAction {- static get actionName() { return "updateRelationTarget"; }- static get actionTitle() { return t('update_relation_target.update_relation_target'); }+ static get actionName() {+ return "updateRelationTarget";+ }+ static get actionTitle() {+ return t("update_relation_target.update_relation_target");+ }doRender() {const $action = $(TPL);- const $relationName = $action.find('.relation-name');+ const $relationName = $action.find(".relation-name");$relationName.val(this.actionDef.relationName || "");- const $targetNote = $action.find('.target-note');+ const $targetNote = $action.find(".target-note");noteAutocompleteService.initNoteAutocomplete($targetNote);$targetNote.setNote(this.actionDef.targetNoteId);- $targetNote.on('autocomplete:closed', () => spacedUpdate.scheduleUpdate());+ $targetNote.on("autocomplete:closed", () => spacedUpdate.scheduleUpdate());const spacedUpdate = new SpacedUpdate(async () => {await this.saveAction({@@ -63,8 +67,8 @@ export default class UpdateRelationTargetBulkAction extends AbstractBulkAction {});}, 1000);- $relationName.on('input', () => spacedUpdate.scheduleUpdate());- $targetNote.on('input', () => spacedUpdate.scheduleUpdate());+ $relationName.on("input", () => spacedUpdate.scheduleUpdate());+ $targetNote.on("input", () => spacedUpdate.scheduleUpdate());return $action;}diff --git a/src/public/app/widgets/buttons/abstract_button.ts b/src/public/app/widgets/buttons/abstract_button.tsindex 9b26c392e6..c30c23593e 100644--- a/src/public/app/widgets/buttons/abstract_button.ts+++ b/src/public/app/widgets/buttons/abstract_button.ts@@ -16,7 +16,6 @@ export interface AbstractButtonWidgetSettings {}export default class AbstractButtonWidget<SettingsT extends AbstractButtonWidgetSettings> extends NoteContextAwareWidget {-protected settings!: SettingsT;protected tooltip!: bootstrap.Tooltip;@@ -31,13 +30,13 @@ export default class AbstractButtonWidget<SettingsT extends AbstractButtonWidgetthis.tooltip = new bootstrap.Tooltip(this.$widget, {html: true,title: () => this.getTitle(),- trigger: 'hover',+ trigger: "hover",placement: this.settings.titlePlacement,- fallbackPlacements: [ this.settings.titlePlacement ]- })+ fallbackPlacements: [this.settings.titlePlacement]+ });if (this.settings.onContextMenu) {- this.$widget.on("contextmenu", e => {+ this.$widget.on("contextmenu", (e) => {this.tooltip.hide();if (this.settings.onContextMenu) {@@ -52,9 +51,7 @@ export default class AbstractButtonWidget<SettingsT extends AbstractButtonWidget}getTitle() {- return typeof this.settings.title === "function"- ? this.settings.title()- : this.settings.title;+ return typeof this.settings.title === "function" ? this.settings.title() : this.settings.title;}refreshIcon() {@@ -64,9 +61,7 @@ export default class AbstractButtonWidget<SettingsT extends AbstractButtonWidget}}- const icon = typeof this.settings.icon === "function"- ? this.settings.icon()- : this.settings.icon;+ const icon = typeof this.settings.icon === "function" ? this.settings.icon() : this.settings.icon;if (icon) {this.$widget.addClass(icon);diff --git a/src/public/app/widgets/buttons/attachments_actions.js b/src/public/app/widgets/buttons/attachments_actions.jsindex b4a15dabae..da8fd0d9a5 100644--- a/src/public/app/widgets/buttons/attachments_actions.js+++ b/src/public/app/widgets/buttons/attachments_actions.js@@ -41,36 +41,36 @@ const TPL = `<div class="dropdown-menu dropdown-menu-right"><li data-trigger-command="openAttachment" class="dropdown-item"- title="${t('attachments_actions.open_externally_title')}"><span class="bx bx-file-find"></span> ${t('attachments_actions.open_externally')}</li>+ title="${t("attachments_actions.open_externally_title")}"><span class="bx bx-file-find"></span> ${t("attachments_actions.open_externally")}</li><li data-trigger-command="openAttachmentCustom" class="dropdown-item"- title="${t('attachments_actions.open_custom_title')}"><span class="bx bx-customize"></span> ${t('attachments_actions.open_custom')}</li>+ title="${t("attachments_actions.open_custom_title")}"><span class="bx bx-customize"></span> ${t("attachments_actions.open_custom")}</li><li data-trigger-command="downloadAttachment" class="dropdown-item">- <span class="bx bx-download"></span> ${t('attachments_actions.download')}</li>+ <span class="bx bx-download"></span> ${t("attachments_actions.download")}</li><li data-trigger-command="copyAttachmentLinkToClipboard" class="dropdown-item"><span class="bx bx-link">- </span> ${t('attachments_actions.copy_link_to_clipboard')}</li>+ </span> ${t("attachments_actions.copy_link_to_clipboard")}</li><div class="dropdown-divider"></div><li data-trigger-command="uploadNewAttachmentRevision" class="dropdown-item"><span class="bx bx-upload">- </span> ${t('attachments_actions.upload_new_revision')}</li>+ </span> ${t("attachments_actions.upload_new_revision")}</li><li data-trigger-command="renameAttachment" class="dropdown-item">- <span class="bx bx-rename"></span> ${t('attachments_actions.rename_attachment')}</li>+ <span class="bx bx-rename"></span> ${t("attachments_actions.rename_attachment")}</li><li data-trigger-command="deleteAttachment" class="dropdown-item">- <span class="bx bx-trash destructive-action-icon"></span> ${t('attachments_actions.delete_attachment')}</li>+ <span class="bx bx-trash destructive-action-icon"></span> ${t("attachments_actions.delete_attachment")}</li><div class="dropdown-divider"></div><li data-trigger-command="convertAttachmentIntoNote" class="dropdown-item"><span class="bx bx-note">- </span> ${t('attachments_actions.convert_attachment_into_note')}</li>+ </span> ${t("attachments_actions.convert_attachment_into_note")}</li></div>@@ -92,46 +92,34 @@ export default class AttachmentActionsWidget extends BasicWidget {doRender() {this.$widget = $(TPL);this.dropdown = bootstrap.Dropdown.getOrCreateInstance(this.$widget.find("[data-bs-toggle='dropdown']"));- this.$widget.on('click', '.dropdown-item', () => this.dropdown.toggle());+ this.$widget.on("click", ".dropdown-item", () => this.dropdown.toggle());this.$uploadNewRevisionInput = this.$widget.find(".attachment-upload-new-revision-input");- this.$uploadNewRevisionInput.on('change', async () => {+ this.$uploadNewRevisionInput.on("change", async () => {const fileToUpload = this.$uploadNewRevisionInput[0].files[0]; // copy to allow reset below- this.$uploadNewRevisionInput.val('');+ this.$uploadNewRevisionInput.val("");const result = await server.upload(`attachments/${this.attachmentId}/file`, fileToUpload);if (result.uploaded) {- toastService.showMessage(t('attachments_actions.upload_success'));+ toastService.showMessage(t("attachments_actions.upload_success"));} else {- toastService.showError(t('attachments_actions.upload_failed'));+ toastService.showError(t("attachments_actions.upload_failed"));}});const isElectron = utils.isElectron();if (!this.isFullDetail) {const $openAttachmentButton = this.$widget.find("[data-trigger-command='openAttachment']");- $openAttachmentButton- .addClass("disabled")- .append($('<span class="bx bx-info-circle disabled-tooltip" />')- .attr("title", t('attachments_actions.open_externally_detail_page'))- );+ $openAttachmentButton.addClass("disabled").append($('<span class="bx bx-info-circle disabled-tooltip" />').attr("title", t("attachments_actions.open_externally_detail_page")));if (isElectron) {const $openAttachmentCustomButton = this.$widget.find("[data-trigger-command='openAttachmentCustom']");- $openAttachmentCustomButton- .addClass("disabled")- .append($('<span class="bx bx-info-circle disabled-tooltip" />')- .attr("title", t('attachments_actions.open_externally_detail_page'))- );+ $openAttachmentCustomButton.addClass("disabled").append($('<span class="bx bx-info-circle disabled-tooltip" />').attr("title", t("attachments_actions.open_externally_detail_page")));}}if (!isElectron) {const $openAttachmentCustomButton = this.$widget.find("[data-trigger-command='openAttachmentCustom']");- $openAttachmentCustomButton- .addClass("disabled")- .append($('<span class="bx bx-info-circle disabled-tooltip" />')- .attr("title", t('attachments_actions.open_custom_client_only'))- );+ $openAttachmentCustomButton.addClass("disabled").append($('<span class="bx bx-info-circle disabled-tooltip" />').attr("title", t("attachments_actions.open_custom_client_only")));}}@@ -148,7 +136,7 @@ export default class AttachmentActionsWidget extends BasicWidget {}async uploadNewAttachmentRevisionCommand() {- this.$uploadNewRevisionInput.trigger('click');+ this.$uploadNewRevisionInput.trigger("click");}async copyAttachmentLinkToClipboardCommand() {@@ -156,29 +144,29 @@ export default class AttachmentActionsWidget extends BasicWidget {}async deleteAttachmentCommand() {- if (!await dialogService.confirm(t('attachments_actions.delete_confirm', { title: this.attachment.title }))) {+ if (!(await dialogService.confirm(t("attachments_actions.delete_confirm", { title: this.attachment.title })))) {return;}await server.remove(`attachments/${this.attachmentId}`);- toastService.showMessage(t('attachments_actions.delete_success', { title: this.attachment.title }));+ toastService.showMessage(t("attachments_actions.delete_success", { title: this.attachment.title }));}async convertAttachmentIntoNoteCommand() {- if (!await dialogService.confirm(t('attachments_actions.convert_confirm', { title: this.attachment.title }))) {+ if (!(await dialogService.confirm(t("attachments_actions.convert_confirm", { title: this.attachment.title })))) {return;}- const { note: newNote } = await server.post(`attachments/${this.attachmentId}/convert-to-note`)- toastService.showMessage(t('attachments_actions.convert_success', { title: this.attachment.title }));+ const { note: newNote } = await server.post(`attachments/${this.attachmentId}/convert-to-note`);+ toastService.showMessage(t("attachments_actions.convert_success", { title: this.attachment.title }));await ws.waitForMaxKnownEntityChangeId();await appContext.tabManager.getActiveContext().setNote(newNote.noteId);}async renameAttachmentCommand() {const attachmentTitle = await dialogService.prompt({- title: t('attachments_actions.rename_attachment'),- message: t('attachments_actions.enter_new_name'),+ title: t("attachments_actions.rename_attachment"),+ message: t("attachments_actions.enter_new_name"),defaultValue: this.attachment.title});diff --git a/src/public/app/widgets/buttons/bookmark_folder.js b/src/public/app/widgets/buttons/bookmark_folder.jsindex e627208b51..7a7d46423f 100644--- a/src/public/app/widgets/buttons/bookmark_folder.js+++ b/src/public/app/widgets/buttons/bookmark_folder.js@@ -53,8 +53,8 @@ export default class BookmarkFolderWidget extends RightDropdownButtonWidget {doRender() {super.doRender();- this.$parentNote = this.$dropdownContent.find('.parent-note');- this.$childrenNotes = this.$dropdownContent.find('.children-notes');+ this.$parentNote = this.$dropdownContent.find(".parent-note");+ this.$childrenNotes = this.$dropdownContent.find(".children-notes");}async dropdownShown() {@@ -66,19 +66,10 @@ export default class BookmarkFolderWidget extends RightDropdownButtonWidget {showNoteIcon: true};- this.$parentNote.append(- (await linkService.createLink(this.note.noteId, linkOptions))- .addClass("note-link")- );+ this.$parentNote.append((await linkService.createLink(this.note.noteId, linkOptions)).addClass("note-link"));for (const childNote of await this.note.getChildNotes()) {- this.$childrenNotes.append(- $("<li>")- .append(- (await linkService.createLink(childNote.noteId, linkOptions))- .addClass("note-link")- )- );+ this.$childrenNotes.append($("<li>").append((await linkService.createLink(childNote.noteId, linkOptions)).addClass("note-link")));}}diff --git a/src/public/app/widgets/buttons/button_from_note.js b/src/public/app/widgets/buttons/button_from_note.jsindex 31d93195ad..8e64acb414 100644--- a/src/public/app/widgets/buttons/button_from_note.js+++ b/src/public/app/widgets/buttons/button_from_note.js@@ -28,26 +28,22 @@ export default class ButtonFromNoteWidget extends CommandButtonWidget {return;}- froca.getNote(buttonNoteId).then(note => {+ froca.getNote(buttonNoteId).then((note) => {this.settings.icon = note.getIcon();this.refreshIcon();});}- entitiesReloadedEvent({loadResults}) {+ entitiesReloadedEvent({ loadResults }) {const buttonNote = froca.getNoteFromCache(this.buttonNoteIdProvider());if (!buttonNote) {return;}- if (loadResults.getAttributeRows(this.componentId).find(attr =>- attr.type === 'label'- && attr.name === 'iconClass'- && attributeService.isAffecting(attr, buttonNote))) {-+ if (loadResults.getAttributeRows(this.componentId).find((attr) => attr.type === "label" && attr.name === "iconClass" && attributeService.isAffecting(attr, buttonNote))) {this.updateIcon();}}-}\ No newline at end of file+}diff --git a/src/public/app/widgets/buttons/calendar.js b/src/public/app/widgets/buttons/calendar.jsindex 609f771a40..9c5d815071 100644--- a/src/public/app/widgets/buttons/calendar.js+++ b/src/public/app/widgets/buttons/calendar.js@@ -40,7 +40,9 @@ const DROPDOWN_TPL = `aria-expanded="false"data-calendar-input="month"></button><ul class="dropdown-menu" data-calendar-input="month-list">- ${Object.entries(MONTHS).map(([i, month]) => `<li><button class="dropdown-item" data-value=${i}>${month}</button></li>`).join("")}+ ${Object.entries(MONTHS)+ .map(([i, month]) => `<li><button class="dropdown-item" data-value=${i}>${month}</button></li>`)+ .join("")}</ul><button class="calendar-btn bx bx-chevron-right" data-calendar-toggle="next"></button>@@ -61,15 +63,7 @@ const DROPDOWN_TPL = `<div class="calendar-body" data-calendar-area="month"></div></div>`;-const DAYS_OF_WEEK = [- t("calendar.sun"),- t("calendar.mon"),- t("calendar.tue"),- t("calendar.wed"),- t("calendar.thu"),- t("calendar.fri"),- t("calendar.sat")-];+const DAYS_OF_WEEK = [t("calendar.sun"), t("calendar.mon"), t("calendar.tue"), t("calendar.wed"), t("calendar.thu"), t("calendar.fri"), t("calendar.sat")];export default class CalendarWidget extends RightDropdownButtonWidget {constructor(title, icon) {@@ -91,18 +85,18 @@ export default class CalendarWidget extends RightDropdownButtonWidget {e.stopPropagation();});this.monthDropdown = bootstrap.Dropdown.getOrCreateInstance(this.$monthSelect);- this.$dropdownContent.find('[data-calendar-input="month-list"] button').on("click", (e) => {+ this.$dropdownContent.find('[data-calendar-input="month-list"] button').on("click", (e) => {this.date.setMonth(e.target.dataset.value);this.createMonth();this.monthDropdown.hide();});this.$next = this.$dropdownContent.find('[data-calendar-toggle="next"]');- this.$next.on('click', () => {+ this.$next.on("click", () => {this.date.setMonth(this.date.getMonth() + 1);this.createMonth();});this.$previous = this.$dropdownContent.find('[data-calendar-toggle="previous"]');- this.$previous.on('click', e => {+ this.$previous.on("click", (e) => {this.date.setMonth(this.date.getMonth() - 1);this.createMonth();});@@ -114,34 +108,33 @@ export default class CalendarWidget extends RightDropdownButtonWidget {this.createMonth();});this.$nextYear = this.$dropdownContent.find('[data-calendar-toggle="nextYear"]');- this.$nextYear.on('click', () => {+ this.$nextYear.on("click", () => {this.date.setFullYear(this.date.getFullYear() + 1);this.createMonth();});this.$previousYear = this.$dropdownContent.find('[data-calendar-toggle="previousYear"]');- this.$previousYear.on('click', e => {+ this.$previousYear.on("click", (e) => {this.date.setFullYear(this.date.getFullYear() - 1);this.createMonth();});- this.$dropdownContent.find('.calendar-header').on("click", e => e.stopPropagation());+ this.$dropdownContent.find(".calendar-header").on("click", (e) => e.stopPropagation());- this.$dropdownContent.on('click', '.calendar-date', async ev => {- const date = $(ev.target).closest('.calendar-date').attr('data-calendar-date');+ this.$dropdownContent.on("click", ".calendar-date", async (ev) => {+ const date = $(ev.target).closest(".calendar-date").attr("data-calendar-date");const note = await dateNoteService.getDayNote(date);if (note) {appContext.tabManager.getActiveContext().setNote(note.noteId);this.dropdown.hide();- }- else {+ } else {toastService.showError(t("calendar.cannot_find_day_note"));}ev.stopPropagation();- });-+ });+// Prevent dismissing the calendar popup by clicking on an empty space inside it.this.$dropdownContent.on("click", (e) => e.stopPropagation());}@@ -175,10 +168,8 @@ export default class CalendarWidget extends RightDropdownButtonWidget {}createDay(dateNotesForMonth, num, day) {- const $newDay = $('<a>')- .addClass("calendar-date")- .attr('data-calendar-date', utils.formatDateISO(this.date));- const $date = $('<span>').html(num);+ const $newDay = $("<a>").addClass("calendar-date").attr("data-calendar-date", utils.formatDateISO(this.date));+ const $date = $("<span>").html(num);// if it's the first day of the monthif (num === 1) {@@ -187,24 +178,23 @@ export default class CalendarWidget extends RightDropdownButtonWidget {// 1 2 3 4 5 6 0// Mo Tu We Th Fr Sa Sulet dayOffset = day - this.firstDayOfWeek;- if (dayOffset < 0)- dayOffset = 7 + dayOffset;- $newDay.css("marginLeft", (dayOffset * 14.28) + '%');+ if (dayOffset < 0) dayOffset = 7 + dayOffset;+ $newDay.css("marginLeft", dayOffset * 14.28 + "%");}const dateNoteId = dateNotesForMonth[utils.formatDateISO(this.date)];if (dateNoteId) {- $newDay.addClass('calendar-date-exists');+ $newDay.addClass("calendar-date-exists");$newDay.attr("data-href", `#root/${dateNoteId}`);}if (this.isEqual(this.date, this.activeDate)) {- $newDay.addClass('calendar-date-active');+ $newDay.addClass("calendar-date-active");}if (this.isEqual(this.date, this.todaysDate)) {- $newDay.addClass('calendar-date-today');+ $newDay.addClass("calendar-date-today");}$newDay.append($date);@@ -212,13 +202,11 @@ export default class CalendarWidget extends RightDropdownButtonWidget {}isEqual(a, b) {- if (!a && b || a && !b) {+ if ((!a && b) || (a && !b)) {return false;}- return a.getFullYear() === b.getFullYear()- && a.getMonth() === b.getMonth()- && a.getDate() === b.getDate();+ return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();}async createMonth() {@@ -229,12 +217,7 @@ export default class CalendarWidget extends RightDropdownButtonWidget {const currentMonth = this.date.getMonth();while (this.date.getMonth() === currentMonth) {- const $day = this.createDay(- dateNotesForMonth,- this.date.getDate(),- this.date.getDay(),- this.date.getFullYear()- );+ const $day = this.createDay(dateNotesForMonth, this.date.getDate(), this.date.getDay(), this.date.getFullYear());this.$month.append($day);@@ -256,5 +239,4 @@ export default class CalendarWidget extends RightDropdownButtonWidget {this.manageFirstDayOfWeek();this.createMonth();}-}diff --git a/src/public/app/widgets/buttons/close_pane_button.js b/src/public/app/widgets/buttons/close_pane_button.jsindex b236894f0d..c41bdfc10d 100644--- a/src/public/app/widgets/buttons/close_pane_button.js+++ b/src/public/app/widgets/buttons/close_pane_button.js@@ -3,12 +3,15 @@ import OnClickButtonWidget from "./onclick_button.js";export default class ClosePaneButton extends OnClickButtonWidget {isEnabled() {- return super.isEnabled()+ return (+ super.isEnabled() &&// main note context should not be closeable- && this.noteContext && !!this.noteContext.mainNtxId;+ this.noteContext &&+ !!this.noteContext.mainNtxId+ );}- async noteContextReorderEvent({ntxIdsInOrder}) {+ async noteContextReorderEvent({ ntxIdsInOrder }) {this.refresh();}diff --git a/src/public/app/widgets/buttons/command_button.ts b/src/public/app/widgets/buttons/command_button.tsindex affe737c1c..0bfb8625cf 100644--- a/src/public/app/widgets/buttons/command_button.ts+++ b/src/public/app/widgets/buttons/command_button.ts@@ -4,11 +4,11 @@ import AbstractButtonWidget, { AbstractButtonWidgetSettings } from "./abstract_blet actions: Action[];-keyboardActionsService.getActions().then(as => actions = as);+keyboardActionsService.getActions().then((as) => (actions = as));// TODO: Is this actually used?export type ClickHandler = (widget: CommandButtonWidget, e: JQuery.ClickEvent<any, any, any, any>) => void;-type CommandOrCallback = (CommandNames | (() => CommandNames));+type CommandOrCallback = CommandNames | (() => CommandNames);interface CommandButtonWidgetSettings extends AbstractButtonWidgetSettings {command?: CommandOrCallback;@@ -16,11 +16,10 @@ interface CommandButtonWidgetSettings extends AbstractButtonWidgetSettings {}export default class CommandButtonWidget extends AbstractButtonWidget<CommandButtonWidgetSettings> {-constructor() {super();this.settings = {- titlePlacement: 'right',+ titlePlacement: "right",title: null,icon: null,onContextMenu: null@@ -46,7 +45,7 @@ export default class CommandButtonWidget extends AbstractButtonWidget<CommandButgetTitle() {const title = super.getTitle();- const action = actions.find(act => act.actionName === this._command);+ const action = actions.find((act) => act.actionName === this._command);if (action && action.effectiveShortcuts.length > 0) {return `${title} (${action.effectiveShortcuts.join(", ")})`;@@ -66,8 +65,6 @@ export default class CommandButtonWidget extends AbstractButtonWidget<CommandBut}get _command() {- return typeof this.settings.command === "function"- ? this.settings.command()- : this.settings.command;+ return typeof this.settings.command === "function" ? this.settings.command() : this.settings.command;}}diff --git a/src/public/app/widgets/buttons/create_pane_button.js b/src/public/app/widgets/buttons/create_pane_button.jsindex 1c072548aa..04231d8d43 100644--- a/src/public/app/widgets/buttons/create_pane_button.js+++ b/src/public/app/widgets/buttons/create_pane_button.js@@ -8,7 +8,7 @@ export default class CreatePaneButton extends OnClickButtonWidget {this.icon("bx-dock-right").title(t("create_pane_button.create_new_split")).titlePlacement("bottom")- .onClick(widget => widget.triggerCommand("openNewNoteSplit", { ntxId: widget.getClosestNtxId() }))+ .onClick((widget) => widget.triggerCommand("openNewNoteSplit", { ntxId: widget.getClosestNtxId() })).class("icon-action");}}diff --git a/src/public/app/widgets/buttons/edit_button.js b/src/public/app/widgets/buttons/edit_button.jsindex 50c490dc2b..b55d445844 100644--- a/src/public/app/widgets/buttons/edit_button.js+++ b/src/public/app/widgets/buttons/edit_button.js@@ -6,9 +6,7 @@ import { t } from "../../services/i18n.js";export default class EditButton extends OnClickButtonWidget {isEnabled() {- return super.isEnabled()- && this.note- && this.noteContext.viewScope.viewMode === 'default';+ return super.isEnabled() && this.note && this.noteContext.viewScope.viewMode === "default";}constructor() {@@ -17,10 +15,10 @@ export default class EditButton extends OnClickButtonWidget {this.icon("bx-edit-alt").title(t("edit_button.edit_this_note")).titlePlacement("bottom")- .onClick(widget => {+ .onClick((widget) => {this.noteContext.viewScope.readOnlyTemporarilyDisabled = true;- appContext.triggerEvent('readOnlyTemporarilyDisabled', {noteContext: this.noteContext});+ appContext.triggerEvent("readOnlyTemporarilyDisabled", { noteContext: this.noteContext });this.refresh();});@@ -29,8 +27,7 @@ export default class EditButton extends OnClickButtonWidget {async refreshWithNote(note) {if (note.isProtected && !protectedSessionHolder.isProtectedSessionAvailable()) {this.toggleInt(false);- }- else {+ } else {// prevent flickering by assuming hidden before async operationthis.toggleInt(false);@@ -53,19 +50,15 @@ export default class EditButton extends OnClickButtonWidget {await super.refreshWithNote(note);}- entitiesReloadedEvent({loadResults}) {- if (loadResults.getAttributeRows().find(- attr => attr.type === 'label'- && attr.name.toLowerCase().includes("readonly")- && attributeService.isAffecting(attr, this.note)- )) {+ entitiesReloadedEvent({ loadResults }) {+ if (loadResults.getAttributeRows().find((attr) => attr.type === "label" && attr.name.toLowerCase().includes("readonly") && attributeService.isAffecting(attr, this.note))) {this.noteContext.viewScope.readOnlyTemporarilyDisabled = false;this.refresh();}}- async noteTypeMimeChangedEvent({noteId}) {+ async noteTypeMimeChangedEvent({ noteId }) {if (this.isNote(noteId)) {await this.refresh();}diff --git a/src/public/app/widgets/buttons/global_menu.ts b/src/public/app/widgets/buttons/global_menu.tsindex d7893499fe..1f906b1fdc 100644--- a/src/public/app/widgets/buttons/global_menu.ts+++ b/src/public/app/widgets/buttons/global_menu.ts@@ -108,13 +108,13 @@ const TPL = `<ul class="dropdown-menu dropdown-menu-right"><li class="dropdown-item" data-trigger-command="openNewWindow"><span class="bx bx-window-open"></span>- ${t('global_menu.open_new_window')}+ ${t("global_menu.open_new_window")}<kbd data-command="openNewWindow"></kbd></li><li class="dropdown-item" data-trigger-command="showShareSubtree"><span class="bx bx-share-alt"></span>- ${t('global_menu.show_shared_notes_subtree')}+ ${t("global_menu.show_shared_notes_subtree")}</li><div class="dropdown-divider"></div>@@ -122,92 +122,92 @@ const TPL = `<span class="zoom-container dropdown-item dropdown-item-container"><div><span class="bx bx-empty"></span>- ${t('global_menu.zoom')}+ ${t("global_menu.zoom")}</div><div class="zoom-buttons">- <a data-trigger-command="toggleFullscreen" title="${t('global_menu.toggle_fullscreen')}" class="bx bx-expand-alt"></a>+ <a data-trigger-command="toggleFullscreen" title="${t("global_menu.toggle_fullscreen")}" class="bx bx-expand-alt"></a> - <a data-trigger-command="zoomOut" title="${t('global_menu.zoom_out')}" class="bx bx-minus"></a>+ <a data-trigger-command="zoomOut" title="${t("global_menu.zoom_out")}" class="bx bx-minus"></a>- <span data-trigger-command="zoomReset" title="${t('global_menu.reset_zoom_level')}" class="zoom-state"></span>+ <span data-trigger-command="zoomReset" title="${t("global_menu.reset_zoom_level")}" class="zoom-state"></span>- <a data-trigger-command="zoomIn" title="${t('global_menu.zoom_in')}" class="bx bx-plus"></a>+ <a data-trigger-command="zoomIn" title="${t("global_menu.zoom_in")}" class="bx bx-plus"></a></div></span><li class="dropdown-item toggle-pin"><span class="bx bx-pin"></span>- ${t('title_bar_buttons.window-on-top')}+ ${t("title_bar_buttons.window-on-top")}</li><div class="dropdown-divider zoom-container-separator"></div><li class="dropdown-item switch-to-mobile-version-button" data-trigger-command="switchToMobileVersion"><span class="bx bx-mobile"></span>- ${t('global_menu.switch_to_mobile_version')}+ ${t("global_menu.switch_to_mobile_version")}</li><li class="dropdown-item switch-to-desktop-version-button" data-trigger-command="switchToDesktopVersion"><span class="bx bx-desktop"></span>- ${t('global_menu.switch_to_desktop_version')}+ ${t("global_menu.switch_to_desktop_version")}</li><li class="dropdown-item" data-trigger-command="showLaunchBarSubtree"><span class="bx ${utils.isMobile() ? "bx-mobile" : "bx-sidebar"}"></span>- ${t('global_menu.configure_launchbar')}+ ${t("global_menu.configure_launchbar")}</li><li class="dropdown-item dropdown-submenu"><span class="dropdown-toggle"><span class="bx bx-chip"></span>- ${t('global_menu.advanced')}+ ${t("global_menu.advanced")}</span><ul class="dropdown-menu"><li class="dropdown-item" data-trigger-command="showHiddenSubtree"><span class="bx bx-hide"></span>- ${t('global_menu.show_hidden_subtree')}+ ${t("global_menu.show_hidden_subtree")}</li><li class="dropdown-item" data-trigger-command="showSearchHistory"><span class="bx bx-search-alt"></span>- ${t('global_menu.open_search_history')}+ ${t("global_menu.open_search_history")}</li><div class="dropdown-divider"></div><li class="dropdown-item" data-trigger-command="showBackendLog"><span class="bx bx-detail"></span>- ${t('global_menu.show_backend_log')}+ ${t("global_menu.show_backend_log")}<kbd data-command="showBackendLog"></kbd></li><li class="dropdown-item" data-trigger-command="showSQLConsole"><span class="bx bx-data"></span>- ${t('global_menu.open_sql_console')}+ ${t("global_menu.open_sql_console")}<kbd data-command="showSQLConsole"></kbd></li><li class="dropdown-item" data-trigger-command="showSQLConsoleHistory"><span class="bx bx-data"></span>- ${t('global_menu.open_sql_console_history')}+ ${t("global_menu.open_sql_console_history")}</li><div class="dropdown-divider"></div><li class="dropdown-item open-dev-tools-button" data-trigger-command="openDevTools"><span class="bx bx-bug-alt"></span>- ${t('global_menu.open_dev_tools')}+ ${t("global_menu.open_dev_tools")}<kbd data-command="openDevTools"></kbd></li><li class="dropdown-item" data-trigger-command="reloadFrontendApp"- title="${t('global_menu.reload_hint')}">+ title="${t("global_menu.reload_hint")}"><span class="bx bx-refresh"></span>- ${t('global_menu.reload_frontend')}+ ${t("global_menu.reload_frontend")}<kbd data-command="reloadFrontendApp"></kbd></li>@@ -216,20 +216,20 @@ const TPL = `<li class="dropdown-item" data-trigger-command="showOptions"><span class="bx bx-cog"></span>- ${t('global_menu.options')}+ ${t("global_menu.options")}</li><div class="dropdown-divider desktop-only"></div><li class="dropdown-item show-help-button" data-trigger-command="showHelp"><span class="bx bx-help-circle"></span>- ${t('global_menu.show_help')}+ ${t("global_menu.show_help")}<kbd data-command="showHelp"></kbd></li><li class="dropdown-item show-about-dialog-button"><span class="bx bx-info-circle"></span>- ${t('global_menu.about')}+ ${t("global_menu.about")}</li><li class="dropdown-item update-to-latest-version-button" data-trigger-command="downloadLatestVersion">@@ -242,14 +242,13 @@ const TPL = `<li class="dropdown-item logout-button" data-trigger-command="logout"><span class="bx bx-log-out"></span>- ${t('global_menu.logout')}+ ${t("global_menu.logout")}</li></ul></div>`;export default class GlobalMenuWidget extends BasicWidget {-private updateAvailableWidget: UpdateAvailableWidget;private isHorizontalLayout: boolean;private tooltip!: bootstrap.Tooltip;@@ -272,10 +271,11 @@ export default class GlobalMenuWidget extends BasicWidget {this.$widget.addClass("dropend");}- const $globalMenuButton = this.$widget.find(".global-menu-button")+ const $globalMenuButton = this.$widget.find(".global-menu-button");if (!this.isHorizontalLayout) {- $globalMenuButton.prepend($(`\- <svg viewBox="0 0 256 256" data-bs-toggle="tooltip" title="${t('global_menu.menu')}">+ $globalMenuButton.prepend(+ $(`\+ <svg viewBox="0 0 256 256" data-bs-toggle="tooltip" title="${t("global_menu.menu")}"><g><path class="st0" d="m202.9 112.7c-22.5 16.1-54.5 12.8-74.9 6.3l14.8-11.8 14.1-11.3 49.1-39.3-51.2 35.9-14.3 10-14.9 10.5c0.7-21.2 7-49.9 28.6-65.4 1.8-1.3 3.9-2.6 6.1-3.8 2.7-1.5 5.7-2.9 8.8-4.1 27.1-11.1 68.5-15.3 85.2-9.5 0.1 16.2-15.9 45.4-33.9 65.9-2.4 2.8-4.9 5.4-7.4 7.8-3.4 3.5-6.8 6.4-10.1 8.8z"/><path class="st1" d="m213.1 104c-22.2 12.6-51.4 9.3-70.3 3.2l14.1-11.3 49.1-39.3-51.2 35.9-14.3 10c0.5-18.1 4.9-42.1 19.7-58.6 2.7-1.5 5.7-2.9 8.8-4.1 27.1-11.1 68.5-15.3 85.2-9.5 0.1 16.2-15.9 45.4-33.9 65.9-2.3 2.8-4.8 5.4-7.2 7.8z"/>@@ -289,7 +289,8 @@ export default class GlobalMenuWidget extends BasicWidget {<path class="st7" d="m75.4 54.8c18.9 12 28.4 35.6 31.6 52.6l-14.5-6.3-50.6-22 48.7 24.9 13.6 6.9c-14.1 6.8-34.5 13-53.3 8.2-2.3-1.5-4.5-3.2-6.8-5.1-19.8-16.4-40.2-46.4-42.6-61.5 12.4-6.5 41.5-5.8 64.8-0.3 3.1 0.8 6.2 1.6 9.1 2.6z"/><path class="st8" d="m66.3 52.2c15.3 12.8 23.3 33.6 26.1 48.9l-50.6-22 48.8 24.9c-12.2 6-29.6 11.8-46.5 10-19.8-16.4-40.2-46.4-42.6-61.5 12.4-6.5 41.5-5.8 64.8-0.3z"/></g>- </svg>`));+ </svg>`)+ );//TODO: Fix once bootstrap is imported via modules.//@ts-ignorethis.tooltip = new bootstrap.Tooltip(this.$widget.find("[data-bs-toggle='tooltip']"), { trigger: "hover" });@@ -303,7 +304,7 @@ export default class GlobalMenuWidget extends BasicWidget {alignment: "bottom"});- this.$widget.find(".show-about-dialog-button").on('click', () => this.triggerCommand("openAboutDialog"));+ this.$widget.find(".show-about-dialog-button").on("click", () => this.triggerCommand("openAboutDialog"));const isElectron = utils.isElectron();@@ -311,15 +312,15 @@ export default class GlobalMenuWidget extends BasicWidget {if (isElectron) {this.$widget.on("click", ".toggle-pin", (e) => {const $el = $(e.target);- const remote = utils.dynamicRequire('@electron/remote');+ const remote = utils.dynamicRequire("@electron/remote");const focusedWindow = remote.BrowserWindow.getFocusedWindow();- const isAlwaysOnTop = focusedWindow.isAlwaysOnTop()+ const isAlwaysOnTop = focusedWindow.isAlwaysOnTop();if (isAlwaysOnTop) {- focusedWindow.setAlwaysOnTop(false)- $el.removeClass('active');+ focusedWindow.setAlwaysOnTop(false);+ $el.removeClass("active");} else {focusedWindow.setAlwaysOnTop(true);- $el.addClass('active');+ $el.addClass("active");}});}@@ -331,22 +332,20 @@ export default class GlobalMenuWidget extends BasicWidget {this.$widget.find(".switch-to-mobile-version-button").toggle(!isElectron && utils.isDesktop());this.$widget.find(".switch-to-desktop-version-button").toggle(!isElectron && utils.isMobile());- this.$widget.on('click', '.dropdown-item', e => {+ this.$widget.on("click", ".dropdown-item", (e) => {if ($(e.target).parent(".zoom-buttons")) {return;}this.dropdown.toggle();});- this.$widget.on('click', '.dropdown-submenu', e => {- if ($(e.target).children(".dropdown-menu").length === 1 || $(e.target).hasClass('dropdown-toggle')) {+ this.$widget.on("click", ".dropdown-submenu", (e) => {+ if ($(e.target).children(".dropdown-menu").length === 1 || $(e.target).hasClass("dropdown-toggle")) {e.stopPropagation();}- })+ });- this.$widget.find(".global-menu-button-update-available").append(- this.updateAvailableWidget.render()- );+ this.$widget.find(".global-menu-button-update-available").append(this.updateAvailableWidget.render());this.$updateToLatestVersionButton = this.$widget.find(".update-to-latest-version-button");@@ -356,7 +355,7 @@ export default class GlobalMenuWidget extends BasicWidget {}this.$zoomState = this.$widget.find(".zoom-state");- this.$widget.on('show.bs.dropdown', () => {+ this.$widget.on("show.bs.dropdown", () => {this.updateZoomState();if (this.tooltip) {this.tooltip.hide();@@ -364,10 +363,11 @@ export default class GlobalMenuWidget extends BasicWidget {}});if (this.tooltip) {- this.$widget.on('hide.bs.dropdown', () => this.tooltip.enable());+ this.$widget.on("hide.bs.dropdown", () => this.tooltip.enable());}- this.$widget.find(".zoom-buttons").on("click",+ this.$widget.find(".zoom-buttons").on(+ "click",// delay to wait for the actual zoom change() => setTimeout(() => this.updateZoomState(), 300));@@ -382,7 +382,7 @@ export default class GlobalMenuWidget extends BasicWidget {return;}- const zoomFactor = utils.dynamicRequire('electron').webFrame.getZoomFactor();+ const zoomFactor = utils.dynamicRequire("electron").webFrame.getZoomFactor();const zoomPercent = Math.round(zoomFactor * 100);this.$zoomState.text(`${zoomPercent}%`);@@ -391,7 +391,7 @@ export default class GlobalMenuWidget extends BasicWidget {async updateVersionStatus() {await options.initializedPromise;- if (options.get("checkForUpdates") !== 'true') {+ if (options.get("checkForUpdates") !== "true") {return;}diff --git a/src/public/app/widgets/buttons/history_navigation.js b/src/public/app/widgets/buttons/history_navigation.jsindex bb320a84cb..4fdaec363c 100644--- a/src/public/app/widgets/buttons/history_navigation.js+++ b/src/public/app/widgets/buttons/history_navigation.js@@ -12,7 +12,7 @@ export default class HistoryNavigationButton extends ButtonFromNoteWidget {.command(() => command).titlePlacement("right").buttonNoteIdProvider(() => launcherNote.noteId)- .onContextMenu(e => this.showContextMenu(e))+ .onContextMenu((e) => this.showContextMenu(e)).class("launcher-button");}@@ -20,7 +20,7 @@ export default class HistoryNavigationButton extends ButtonFromNoteWidget {super.doRender();if (utils.isElectron()) {- this.webContents = utils.dynamicRequire('@electron/remote').getCurrentWebContents();+ this.webContents = utils.dynamicRequire("@electron/remote").getCurrentWebContents();// without this, the history is preserved across frontend reloadsthis.webContents.clearHistory();@@ -34,7 +34,8 @@ export default class HistoryNavigationButton extends ButtonFromNoteWidget {// API is broken and will be replaced: https://github.com/electron/electron/issues/33899// until then no context menu- if (true) { // avoid warning in dev console+ if (true) {+ // avoid warning in dev consolereturn;}@@ -48,17 +49,21 @@ export default class HistoryNavigationButton extends ButtonFromNoteWidget {for (const idx in this.webContents.history) {const url = this.webContents.history[idx];- const [_, notePathWithTab] = url.split('#');+ const [_, notePathWithTab] = url.split("#");// broken: use linkService.parseNavigationStateFromUrl();- const [notePath, ntxId] = notePathWithTab.split('-');+ const [notePath, ntxId] = notePathWithTab.split("-");const title = await treeService.getNotePathTitle(notePath);items.push({title,idx,- uiIcon: idx == activeIndex ? "bx bx-radio-circle-marked" : // compare with type coercion!- (idx < activeIndex ? "bx bx-left-arrow-alt" : "bx bx-right-arrow-alt")+ uiIcon:+ idx == activeIndex+ ? "bx bx-radio-circle-marked" // compare with type coercion!+ : idx < activeIndex+ ? "bx bx-left-arrow-alt"+ : "bx bx-right-arrow-alt"});}@@ -72,7 +77,7 @@ export default class HistoryNavigationButton extends ButtonFromNoteWidget {x: e.pageX,y: e.pageY,items,- selectMenuItemHandler: ({idx}) => this.webContents.goToIndex(idx)+ selectMenuItemHandler: ({ idx }) => this.webContents.goToIndex(idx)});}diff --git a/src/public/app/widgets/buttons/launcher/abstract_launcher.js b/src/public/app/widgets/buttons/launcher/abstract_launcher.jsindex 3e9cd1f6dc..0bdb703671 100644--- a/src/public/app/widgets/buttons/launcher/abstract_launcher.js+++ b/src/public/app/widgets/buttons/launcher/abstract_launcher.js@@ -11,7 +11,7 @@ export default class AbstractLauncher extends OnClickButtonWidget {/** @type {FNote} */this.launcherNote = launcherNote;- for (const label of launcherNote.getOwnedLabels('keyboardShortcut')) {+ for (const label of launcherNote.getOwnedLabels("keyboardShortcut")) {this.bindNoteShortcutHandler(label);}}@@ -23,18 +23,19 @@ export default class AbstractLauncher extends OnClickButtonWidget {bindNoteShortcutHandler(labelOrRow) {const namespace = labelOrRow.attributeId;- if (labelOrRow.isDeleted) { // only applicable if row+ if (labelOrRow.isDeleted) {+ // only applicable if rowshortcutService.removeGlobalShortcut(namespace);} else {shortcutService.bindGlobalShortcut(labelOrRow.value, () => this.launch(), namespace);}}- entitiesReloadedEvent({loadResults}) {+ entitiesReloadedEvent({ loadResults }) {for (const attr of loadResults.getAttributeRows()) {- if (attr.noteId === this.launcherNote.noteId && attr.type === 'label' && attr.name === 'keyboardShortcut') {+ if (attr.noteId === this.launcherNote.noteId && attr.type === "label" && attr.name === "keyboardShortcut") {this.bindNoteShortcutHandler(attr);- } else if (attr.type === 'label' && attr.name === 'iconClass' && attributesService.isAffecting(attr, this.launcherNote)) {+ } else if (attr.type === "label" && attr.name === "iconClass" && attributesService.isAffecting(attr, this.launcherNote)) {this.refreshIcon();}}diff --git a/src/public/app/widgets/buttons/launcher/note_launcher.js b/src/public/app/widgets/buttons/launcher/note_launcher.jsindex 40c6628919..c06a562f6d 100644--- a/src/public/app/widgets/buttons/launcher/note_launcher.js+++ b/src/public/app/widgets/buttons/launcher/note_launcher.js@@ -20,7 +20,7 @@ export default class NoteLauncher extends AbstractLauncher {.icon(() => this.launcherNote.getIcon()).onClick((widget, evt) => this.launch(evt)).onAuxClick((widget, evt) => this.launch(evt))- .onContextMenu(evt => {+ .onContextMenu((evt) => {const targetNoteId = this.getTargetNoteId();if (!targetNoteId) {return;@@ -56,7 +56,7 @@ export default class NoteLauncher extends AbstractLauncher {}getTargetNoteId() {- const targetNoteId = this.launcherNote.getRelationValue('target');+ const targetNoteId = this.launcherNote.getRelationValue("target");if (!targetNoteId) {dialogService.info(t("note_launcher.this_launcher_doesnt_define_target_note"));@@ -67,14 +67,14 @@ export default class NoteLauncher extends AbstractLauncher {}getHoistedNoteId() {- return this.launcherNote.getRelationValue('hoistedNote')- || appContext.tabManager.getActiveContext().hoistedNoteId;+ return this.launcherNote.getRelationValue("hoistedNote") || appContext.tabManager.getActiveContext().hoistedNoteId;}getTitle() {- const shortcuts = this.launcherNote.getLabels("keyboardShortcut")- .map(l => l.value)- .filter(v => !!v)+ const shortcuts = this.launcherNote+ .getLabels("keyboardShortcut")+ .map((l) => l.value)+ .filter((v) => !!v).join(", ");let title = super.getTitle();diff --git a/src/public/app/widgets/buttons/launcher/script_launcher.js b/src/public/app/widgets/buttons/launcher/script_launcher.jsindex 71ca35f1c3..466ce45eca 100644--- a/src/public/app/widgets/buttons/launcher/script_launcher.js+++ b/src/public/app/widgets/buttons/launcher/script_launcher.js@@ -10,10 +10,10 @@ export default class ScriptLauncher extends AbstractLauncher {}async launch() {- if (this.launcherNote.isLabelTruthy('scriptInLauncherContent')) {+ if (this.launcherNote.isLabelTruthy("scriptInLauncherContent")) {await this.launcherNote.executeScript();} else {- const script = await this.launcherNote.getRelationTarget('script');+ const script = await this.launcherNote.getRelationTarget("script");await script.executeScript();}diff --git a/src/public/app/widgets/buttons/left_pane_toggle.js b/src/public/app/widgets/buttons/left_pane_toggle.jsindex f58c529e39..a5bf2d37ed 100644--- a/src/public/app/widgets/buttons/left_pane_toggle.js+++ b/src/public/app/widgets/buttons/left_pane_toggle.js@@ -14,16 +14,12 @@ export default class LeftPaneToggleWidget extends CommandButtonWidget {return "bx-sidebar";}- return (options.is('leftPaneVisible') ? "bx-chevrons-left" : "bx-chevrons-right");+ return options.is("leftPaneVisible") ? "bx-chevrons-left" : "bx-chevrons-right";};- this.settings.title = () => options.is('leftPaneVisible')- ? t("left_pane_toggle.hide_panel")- : t("left_pane_toggle.show_panel");+ this.settings.title = () => (options.is("leftPaneVisible") ? t("left_pane_toggle.hide_panel") : t("left_pane_toggle.show_panel"));- this.settings.command = () => options.is('leftPaneVisible')- ? "hideLeftPane"- : "showLeftPane";+ this.settings.command = () => (options.is("leftPaneVisible") ? "hideLeftPane" : "showLeftPane");if (isHorizontalLayout) {this.settings.titlePlacement = "bottom";@@ -33,10 +29,10 @@ export default class LeftPaneToggleWidget extends CommandButtonWidget {refreshIcon() {super.refreshIcon();- splitService.setupLeftPaneResizer(options.is('leftPaneVisible'));+ splitService.setupLeftPaneResizer(options.is("leftPaneVisible"));}- entitiesReloadedEvent({loadResults}) {+ entitiesReloadedEvent({ loadResults }) {if (loadResults.isOptionReloaded("leftPaneVisible")) {this.refreshIcon();}diff --git a/src/public/app/widgets/buttons/move_pane_button.js b/src/public/app/widgets/buttons/move_pane_button.jsindex dc21431dee..fa1a73783e 100644--- a/src/public/app/widgets/buttons/move_pane_button.js+++ b/src/public/app/widgets/buttons/move_pane_button.js@@ -13,7 +13,7 @@ export default class MovePaneButton extends OnClickButtonWidget {.titlePlacement("bottom").onClick(async (widget, e) => {e.stopPropagation();- widget.triggerCommand("moveThisNoteSplit", {ntxId: widget.getClosestNtxId(), isMovingLeft: this.isMovingLeft});+ widget.triggerCommand("moveThisNoteSplit", { ntxId: widget.getClosestNtxId(), isMovingLeft: this.isMovingLeft });}).class("icon-action");}@@ -27,7 +27,7 @@ export default class MovePaneButton extends OnClickButtonWidget {// movable if the current context is not a main context, i.e. non-null mainNtxIdreturn !!this.noteContext?.mainNtxId;} else {- const currentIndex = appContext.tabManager.noteContexts.findIndex(c => c.ntxId === this.ntxId);+ const currentIndex = appContext.tabManager.noteContexts.findIndex((c) => c.ntxId === this.ntxId);const nextContext = appContext.tabManager.noteContexts[currentIndex + 1];// movable if the next context is not null and not a main context, i.e. non-null mainNtxIdreturn !!nextContext?.mainNtxId;diff --git a/src/public/app/widgets/buttons/note_actions.js b/src/public/app/widgets/buttons/note_actions.jsindex e1ae64b382..e2efce0348 100644--- a/src/public/app/widgets/buttons/note_actions.js+++ b/src/public/app/widgets/buttons/note_actions.js@@ -40,43 +40,43 @@ const TPL = `<div class="dropdown-menu dropdown-menu-right"><li data-trigger-command="convertNoteIntoAttachment" class="dropdown-item">- <span class="bx bx-paperclip"></span> ${t('note_actions.convert_into_attachment')}+ <span class="bx bx-paperclip"></span> ${t("note_actions.convert_into_attachment")}</li><li data-trigger-command="renderActiveNote" class="dropdown-item render-note-button">- <span class="bx bx-extension"></span> ${t('note_actions.re_render_note')}<kbd data-command="renderActiveNote"></kbd>+ <span class="bx bx-extension"></span> ${t("note_actions.re_render_note")}<kbd data-command="renderActiveNote"></kbd></li><li data-trigger-command="findInText" class="dropdown-item find-in-text-button">- <span class='bx bx-search'></span> ${t('note_actions.search_in_note')}<kbd data-command="findInText"></kbd>+ <span class='bx bx-search'></span> ${t("note_actions.search_in_note")}<kbd data-command="findInText"></kbd></li><li data-trigger-command="printActiveNote" class="dropdown-item print-active-note-button">- <span class="bx bx-printer"></span> ${t('note_actions.print_note')}<kbd data-command="printActiveNote"></kbd></li>+ <span class="bx bx-printer"></span> ${t("note_actions.print_note")}<kbd data-command="printActiveNote"></kbd></li><div class="dropdown-divider"></div>- <li class="dropdown-item import-files-button"><span class="bx bx-import"></span> ${t('note_actions.import_files')}</li>+ <li class="dropdown-item import-files-button"><span class="bx bx-import"></span> ${t("note_actions.import_files")}</li>- <li class="dropdown-item export-note-button"><span class="bx bx-export"></span> ${t('note_actions.export_note')}</li>+ <li class="dropdown-item export-note-button"><span class="bx bx-export"></span> ${t("note_actions.export_note")}</li><div class="dropdown-divider"></div>- <li data-trigger-command="openNoteExternally" class="dropdown-item open-note-externally-button" title="${t('note_actions.open_note_externally_title')}">- <span class="bx bx-file-find"></span> ${t('note_actions.open_note_externally')}<kbd data-command="openNoteExternally"></kbd>+ <li data-trigger-command="openNoteExternally" class="dropdown-item open-note-externally-button" title="${t("note_actions.open_note_externally_title")}">+ <span class="bx bx-file-find"></span> ${t("note_actions.open_note_externally")}<kbd data-command="openNoteExternally"></kbd></li><li data-trigger-command="openNoteCustom" class="dropdown-item open-note-custom-button">- <span class="bx bx-customize"></span> ${t('note_actions.open_note_custom')}<kbd data-command="openNoteCustom"></kbd>+ <span class="bx bx-customize"></span> ${t("note_actions.open_note_custom")}<kbd data-command="openNoteCustom"></kbd></li><li data-trigger-command="showNoteSource" class="dropdown-item show-source-button">- <span class="bx bx-code"></span> ${t('note_actions.note_source')}<kbd data-command="showNoteSource"></kbd>+ <span class="bx bx-code"></span> ${t("note_actions.note_source")}<kbd data-command="showNoteSource"></kbd></li>@@ -84,39 +84,39 @@ const TPL = `<li data-trigger-command="forceSaveRevision" class="dropdown-item save-revision-button">- <span class="bx bx-save"></span> ${t('note_actions.save_revision')}<kbd data-command="forceSaveRevision"></kbd>+ <span class="bx bx-save"></span> ${t("note_actions.save_revision")}<kbd data-command="forceSaveRevision"></kbd></li>- <li class="dropdown-item delete-note-button"><span class="bx bx-trash destructive-action-icon"></span> ${t('note_actions.delete_note')}</li>+ <li class="dropdown-item delete-note-button"><span class="bx bx-trash destructive-action-icon"></span> ${t("note_actions.delete_note")}</li><div class="dropdown-divider"></div><li data-trigger-command="showAttachments" class="dropdown-item show-attachments-button">- <span class="bx bx-paperclip"></span> ${t('note_actions.note_attachments')}<kbd data-command="showAttachments"></kbd>+ <span class="bx bx-paperclip"></span> ${t("note_actions.note_attachments")}<kbd data-command="showAttachments"></kbd></li></div></div>`;export default class NoteActionsWidget extends NoteContextAwareWidget {isEnabled() {- return this.note?.type !== 'launcher';+ return this.note?.type !== "launcher";}doRender() {this.$widget = $(TPL);- this.$widget.on('show.bs.dropdown', () => this.refreshVisibility(this.note));+ this.$widget.on("show.bs.dropdown", () => this.refreshVisibility(this.note));this.$convertNoteIntoAttachmentButton = this.$widget.find("[data-trigger-command='convertNoteIntoAttachment']");- this.$findInTextButton = this.$widget.find('.find-in-text-button');- this.$printActiveNoteButton = this.$widget.find('.print-active-note-button');- this.$showSourceButton = this.$widget.find('.show-source-button');- this.$showAttachmentsButton = this.$widget.find('.show-attachments-button');- this.$renderNoteButton = this.$widget.find('.render-note-button');+ this.$findInTextButton = this.$widget.find(".find-in-text-button");+ this.$printActiveNoteButton = this.$widget.find(".print-active-note-button");+ this.$showSourceButton = this.$widget.find(".show-source-button");+ this.$showAttachmentsButton = this.$widget.find(".show-attachments-button");+ this.$renderNoteButton = this.$widget.find(".render-note-button");this.$saveRevisionButton = this.$widget.find(".save-revision-button");- this.$exportNoteButton = this.$widget.find('.export-note-button');+ this.$exportNoteButton = this.$widget.find(".export-note-button");this.$exportNoteButton.on("click", () => {if (this.$exportNoteButton.hasClass("disabled")) {return;@@ -128,17 +128,17 @@ export default class NoteActionsWidget extends NoteContextAwareWidget {});});- this.$importNoteButton = this.$widget.find('.import-files-button');- this.$importNoteButton.on("click", () => this.triggerCommand("showImportDialog", {noteId: this.noteId}));+ this.$importNoteButton = this.$widget.find(".import-files-button");+ this.$importNoteButton.on("click", () => this.triggerCommand("showImportDialog", { noteId: this.noteId }));- this.$widget.on('click', '.dropdown-item', () => this.$widget.find("[data-bs-toggle='dropdown']").dropdown('toggle'));+ this.$widget.on("click", ".dropdown-item", () => this.$widget.find("[data-bs-toggle='dropdown']").dropdown("toggle"));this.$openNoteExternallyButton = this.$widget.find(".open-note-externally-button");this.$openNoteCustomButton = this.$widget.find(".open-note-custom-button");this.$deleteNoteButton = this.$widget.find(".delete-note-button");this.$deleteNoteButton.on("click", () => {- if (this.note.noteId === 'root') {+ if (this.note.noteId === "root") {return;}@@ -151,36 +151,37 @@ export default class NoteActionsWidget extends NoteContextAwareWidget {this.$convertNoteIntoAttachmentButton.toggle(note.isEligibleForConversionToAttachment());- this.toggleDisabled(this.$findInTextButton, ['text', 'code', 'book'].includes(note.type));+ this.toggleDisabled(this.$findInTextButton, ["text", "code", "book"].includes(note.type));this.toggleDisabled(this.$showAttachmentsButton, !isInOptions);- this.toggleDisabled(this.$showSourceButton, ['text', 'code', 'relationMap', 'mermaid', 'canvas', 'mindMap'].includes(note.type));+ this.toggleDisabled(this.$showSourceButton, ["text", "code", "relationMap", "mermaid", "canvas", "mindMap"].includes(note.type));- this.toggleDisabled(this.$printActiveNoteButton, ['text', 'code'].includes(note.type));+ this.toggleDisabled(this.$printActiveNoteButton, ["text", "code"].includes(note.type));- this.$renderNoteButton.toggle(note.type === 'render');+ this.$renderNoteButton.toggle(note.type === "render");- this.toggleDisabled(this.$openNoteExternallyButton, utils.isElectron() && !['search', 'book'].includes(note.type));- this.toggleDisabled(this.$openNoteCustomButton,- utils.isElectron()- && !utils.isMac() // no implementation for Mac yet- && !['search', 'book'].includes(note.type)+ this.toggleDisabled(this.$openNoteExternallyButton, utils.isElectron() && !["search", "book"].includes(note.type));+ this.toggleDisabled(+ this.$openNoteCustomButton,+ utils.isElectron() &&+ !utils.isMac() && // no implementation for Mac yet+ !["search", "book"].includes(note.type));// I don't want to handle all special notes like this, but intuitively user might want to export content of backend log- this.toggleDisabled(this.$exportNoteButton, !['_backendLog'].includes(note.noteId) && !isInOptions);+ this.toggleDisabled(this.$exportNoteButton, !["_backendLog"].includes(note.noteId) && !isInOptions);- this.toggleDisabled(this.$importNoteButton, !['search'].includes(note.type) && !isInOptions);+ this.toggleDisabled(this.$importNoteButton, !["search"].includes(note.type) && !isInOptions);this.toggleDisabled(this.$deleteNoteButton, !isInOptions);this.toggleDisabled(this.$saveRevisionButton, !isInOptions);}async convertNoteIntoAttachmentCommand() {- if (!await dialogService.confirm(t("note_actions.convert_into_attachment_prompt", { title: this.note.title }))) {+ if (!(await dialogService.confirm(t("note_actions.convert_into_attachment_prompt", { title: this.note.title })))) {return;}- const {attachment: newAttachment} = await server.post(`notes/${this.noteId}/convert-to-attachment`);+ const { attachment: newAttachment } = await server.post(`notes/${this.noteId}/convert-to-attachment`);if (!newAttachment) {toastService.showMessage(t("note_actions.convert_into_attachment_failed", { title: this.note.title }));@@ -191,7 +192,7 @@ export default class NoteActionsWidget extends NoteContextAwareWidget {await ws.waitForMaxKnownEntityChangeId();await appContext.tabManager.getActiveContext().setNote(newAttachment.ownerId, {viewScope: {- viewMode: 'attachments',+ viewMode: "attachments",attachmentId: newAttachment.attachmentId}});@@ -199,13 +200,13 @@ export default class NoteActionsWidget extends NoteContextAwareWidget {toggleDisabled($el, enable) {if (enable) {- $el.removeAttr('disabled');+ $el.removeAttr("disabled");} else {- $el.attr('disabled', 'disabled');+ $el.attr("disabled", "disabled");}}- entitiesReloadedEvent({loadResults}) {+ entitiesReloadedEvent({ loadResults }) {if (loadResults.isNoteReloaded(this.noteId)) {this.refresh();}diff --git a/src/public/app/widgets/buttons/onclick_button.ts b/src/public/app/widgets/buttons/onclick_button.tsindex 16685c6c66..90ef6661ce 100644--- a/src/public/app/widgets/buttons/onclick_button.ts+++ b/src/public/app/widgets/buttons/onclick_button.ts@@ -10,11 +10,10 @@ interface OnClickButtonWidgetSettings extends AbstractButtonWidgetSettings {}export default class OnClickButtonWidget extends AbstractButtonWidget<OnClickButtonWidgetSettings> {-constructor() {super();this.settings = {- titlePlacement: 'right',+ titlePlacement: "right",title: null,icon: null,onContextMenu: null@@ -25,7 +24,7 @@ export default class OnClickButtonWidget extends AbstractButtonWidget<OnClickButsuper.doRender();if (this.settings.onClick) {- this.$widget.on("click", e => {+ this.$widget.on("click", (e) => {this.$widget.tooltip("hide");if (this.settings.onClick) {@@ -37,7 +36,7 @@ export default class OnClickButtonWidget extends AbstractButtonWidget<OnClickBut}if (this.settings.onAuxClick) {- this.$widget.on("auxclick", e => {+ this.$widget.on("auxclick", (e) => {this.$widget.tooltip("hide");if (this.settings.onAuxClick) {diff --git a/src/public/app/widgets/buttons/open_note_button_widget.js b/src/public/app/widgets/buttons/open_note_button_widget.jsindex fe8c476c96..279c5d670e 100644--- a/src/public/app/widgets/buttons/open_note_button_widget.js+++ b/src/public/app/widgets/buttons/open_note_button_widget.js@@ -13,7 +13,7 @@ export default class OpenNoteButtonWidget extends OnClickButtonWidget {.icon(() => this.noteToOpen.getIcon()).onClick((widget, evt) => this.launch(evt)).onAuxClick((widget, evt) => this.launch(evt))- .onContextMenu(evt => linkContextMenuService.openContextMenu(this.noteToOpen.noteId, evt));+ .onContextMenu((evt) => linkContextMenuService.openContextMenu(this.noteToOpen.noteId, evt));}async launch(evt) {diff --git a/src/public/app/widgets/buttons/protected_session_status.js b/src/public/app/widgets/buttons/protected_session_status.jsindex 2a9a14f14a..e5dde7d3d3 100644--- a/src/public/app/widgets/buttons/protected_session_status.js+++ b/src/public/app/widgets/buttons/protected_session_status.js@@ -8,17 +8,11 @@ export default class ProtectedSessionStatusWidget extends CommandButtonWidget {this.class("launcher-button");- this.settings.icon = () => protectedSessionHolder.isProtectedSessionAvailable()- ? "bx-check-shield"- : "bx-shield-quarter";+ this.settings.icon = () => (protectedSessionHolder.isProtectedSessionAvailable() ? "bx-check-shield" : "bx-shield-quarter");- this.settings.title = () => protectedSessionHolder.isProtectedSessionAvailable()- ? t("protected_session_status.active")- : t("protected_session_status.inactive");+ this.settings.title = () => (protectedSessionHolder.isProtectedSessionAvailable() ? t("protected_session_status.active") : t("protected_session_status.inactive"));- this.settings.command = () => protectedSessionHolder.isProtectedSessionAvailable()- ? "leaveProtectedSession"- : "enterProtectedSession";+ this.settings.command = () => (protectedSessionHolder.isProtectedSessionAvailable() ? "leaveProtectedSession" : "enterProtectedSession");}protectedSessionStartedEvent() {diff --git a/src/public/app/widgets/buttons/revisions_button.js b/src/public/app/widgets/buttons/revisions_button.jsindex b3c0bbbcf8..086644a46d 100644--- a/src/public/app/widgets/buttons/revisions_button.js+++ b/src/public/app/widgets/buttons/revisions_button.js@@ -5,14 +5,10 @@ export default class RevisionsButton extends CommandButtonWidget {constructor() {super();- this.icon('bx-history')- .title(t("revisions_button.note_revisions"))- .command("showRevisions")- .titlePlacement("bottom")- .class("icon-action");+ this.icon("bx-history").title(t("revisions_button.note_revisions")).command("showRevisions").titlePlacement("bottom").class("icon-action");}isEnabled() {- return super.isEnabled() && !['launcher', 'doc'].includes(this.note?.type);+ return super.isEnabled() && !["launcher", "doc"].includes(this.note?.type);}}diff --git a/src/public/app/widgets/buttons/right_dropdown_button.js b/src/public/app/widgets/buttons/right_dropdown_button.jsindex 0646d886a2..822923d5a8 100644--- a/src/public/app/widgets/buttons/right_dropdown_button.js+++ b/src/public/app/widgets/buttons/right_dropdown_button.js@@ -21,7 +21,7 @@ export default class RightDropdownButtonWidget extends BasicWidget {this.dropdownTpl = dropdownTpl;this.settings = {- titlePlacement: "right"+ titlePlacement: "right"};}@@ -33,16 +33,17 @@ export default class RightDropdownButtonWidget extends BasicWidget {this.$tooltip = this.$widget.find(".tooltip-trigger").attr("title", this.title);this.tooltip = new bootstrap.Tooltip(this.$tooltip, {placement: this.settings.titlePlacement,- fallbackPlacements: [ this.settings.titlePlacement ]+ fallbackPlacements: [this.settings.titlePlacement]});- this.$widget.find(".right-dropdown-button")+ this.$widget+ .find(".right-dropdown-button").addClass(this.iconClass).on("click", () => this.tooltip.hide())- .on('mouseenter', () => this.tooltip.show())- .on('mouseleave', () => this.tooltip.hide());+ .on("mouseenter", () => this.tooltip.show())+ .on("mouseleave", () => this.tooltip.hide());- this.$widget.on('show.bs.dropdown', async () => {+ this.$widget.on("show.bs.dropdown", async () => {await this.dropdownShown();const rect = this.$dropdownMenu[0].getBoundingClientRect();@@ -58,5 +59,5 @@ export default class RightDropdownButtonWidget extends BasicWidget {}// to be overridden- async dropdownShow() { }+ async dropdownShow() {}}diff --git a/src/public/app/widgets/buttons/show_highlights_list_widget_button.js b/src/public/app/widgets/buttons/show_highlights_list_widget_button.jsindex 9a7d99eb73..81bbda738d 100644--- a/src/public/app/widgets/buttons/show_highlights_list_widget_button.js+++ b/src/public/app/widgets/buttons/show_highlights_list_widget_button.js@@ -5,10 +5,7 @@ import { t } from "../../services/i18n.js";export default class ShowHighlightsListWidgetButton extends OnClickButtonWidget {isEnabled() {- return super.isEnabled()- && this.note- && this.note.type === 'text'- && this.noteContext.viewScope.viewMode === 'default';+ return super.isEnabled() && this.note && this.note.type === "text" && this.noteContext.viewScope.viewMode === "default";}constructor() {@@ -17,7 +14,7 @@ export default class ShowHighlightsListWidgetButton extends OnClickButtonWidgetthis.icon("bx-highlight").title(t("show_highlights_list_widget_button.show_highlights_list")).titlePlacement("bottom")- .onClick(widget => {+ .onClick((widget) => {this.noteContext.viewScope.highlightsListTemporarilyHidden = false;appContext.triggerEvent("showHighlightsListWidget", { noteId: this.noteId });this.toggleInt(false);@@ -35,9 +32,11 @@ export default class ShowHighlightsListWidgetButton extends OnClickButtonWidgetasync entitiesReloadedEvent({ loadResults }) {if (loadResults.isNoteContentReloaded(this.noteId)) {await this.refresh();- } else if (loadResults.getAttributeRows().find(attr => attr.type === 'label'- && (attr.name.toLowerCase().includes('readonly') || attr.name === 'hideHighlightWidget')- && attributeService.isAffecting(attr, this.note))) {+ } else if (+ loadResults+ .getAttributeRows()+ .find((attr) => attr.type === "label" && (attr.name.toLowerCase().includes("readonly") || attr.name === "hideHighlightWidget") && attributeService.isAffecting(attr, this.note))+ ) {await this.refresh();}}diff --git a/src/public/app/widgets/buttons/show_toc_widget_button.js b/src/public/app/widgets/buttons/show_toc_widget_button.jsindex c4f4262f9d..226d482a41 100644--- a/src/public/app/widgets/buttons/show_toc_widget_button.js+++ b/src/public/app/widgets/buttons/show_toc_widget_button.js@@ -5,10 +5,7 @@ import { t } from "../../services/i18n.js";export default class ShowTocWidgetButton extends OnClickButtonWidget {isEnabled() {- return super.isEnabled()- && this.note- && this.note.type === 'text'- && this.noteContext.viewScope.viewMode === 'default';+ return super.isEnabled() && this.note && this.note.type === "text" && this.noteContext.viewScope.viewMode === "default";}constructor() {@@ -17,7 +14,7 @@ export default class ShowTocWidgetButton extends OnClickButtonWidget {this.icon("bx-objects-horizontal-left").title(t("show_toc_widget_button.show_toc")).titlePlacement("bottom")- .onClick(widget => {+ .onClick((widget) => {this.noteContext.viewScope.tocTemporarilyHidden = false;appContext.triggerEvent("showTocWidget", { noteId: this.noteId });this.toggleInt(false);@@ -35,9 +32,11 @@ export default class ShowTocWidgetButton extends OnClickButtonWidget {async entitiesReloadedEvent({ loadResults }) {if (loadResults.isNoteContentReloaded(this.noteId)) {await this.refresh();- } else if (loadResults.getAttributeRows().find(attr => attr.type === 'label'- && (attr.name.toLowerCase().includes('readonly') || attr.name === 'toc')- && attributeService.isAffecting(attr, this.note))) {+ } else if (+ loadResults+ .getAttributeRows()+ .find((attr) => attr.type === "label" && (attr.name.toLowerCase().includes("readonly") || attr.name === "toc") && attributeService.isAffecting(attr, this.note))+ ) {await this.refresh();}}diff --git a/src/public/app/widgets/buttons/update_available.ts b/src/public/app/widgets/buttons/update_available.tsindex 238c16fcf6..b8ed93d5a7 100644--- a/src/public/app/widgets/buttons/update_available.ts+++ b/src/public/app/widgets/buttons/update_available.ts@@ -25,7 +25,7 @@ const TPL = `}</style>- <span class="bx bx-sync global-menu-button-update-available-button" title="${t('update_available.update_available')}"></span>+ <span class="bx bx-sync global-menu-button-update-available-button" title="${t("update_available.update_available")}"></span></div>`;diff --git a/src/public/app/widgets/containers/container.ts b/src/public/app/widgets/containers/container.tsindex 8f488a5521..56fe050a01 100644--- a/src/public/app/widgets/containers/container.ts+++ b/src/public/app/widgets/containers/container.ts@@ -2,7 +2,6 @@ import Component, { TypedComponent } from "../../components/component.js";import BasicWidget, { TypedBasicWidget } from "../basic_widget.js";export default class Container<T extends TypedComponent<any>> extends TypedBasicWidget<T> {-doRender() {this.$widget = $(`<div>`);this.renderChildren();@@ -20,11 +19,9 @@ export default class Container<T extends TypedComponent<any>> extends TypedBasicif ("render" in widget) {this.$widget.append(typedWidget.render());}-} catch (e: any) {typedWidget.logRenderingError(e);}}}-}diff --git a/src/public/app/widgets/containers/flex_container.ts b/src/public/app/widgets/containers/flex_container.tsindex cb70b11815..62660a4eea 100644--- a/src/public/app/widgets/containers/flex_container.ts+++ b/src/public/app/widgets/containers/flex_container.ts@@ -4,15 +4,13 @@ import Container from "./container.js";export type FlexDirection = "row" | "column";export default class FlexContainer<T extends TypedComponent<any>> extends Container<T> {-constructor(direction: FlexDirection) {super();- if (!direction || !['row', 'column'].includes(direction)) {+ if (!direction || !["row", "column"].includes(direction)) {throw new Error(`Direction argument given as '${direction}', use either 'row' or 'column'`);}this.attrs.style = `display: flex; flex-direction: ${direction};`;}-}diff --git a/src/public/app/widgets/containers/launcher.ts b/src/public/app/widgets/containers/launcher.tsindex bfeea5f6b0..a1b86cdda4 100644--- a/src/public/app/widgets/containers/launcher.ts+++ b/src/public/app/widgets/containers/launcher.ts@@ -16,12 +16,11 @@ import { CommandNames } from "../../components/app_context.js";interface InnerWidget extends BasicWidget {settings?: {- titlePlacement: "bottom"- }+ titlePlacement: "bottom";+ };}export default class LauncherWidget extends BasicWidget {-private innerWidget!: InnerWidget;private isHorizontalLayout: boolean;@@ -40,33 +39,30 @@ export default class LauncherWidget extends BasicWidget {}async initLauncher(note: FNote) {- if (note.type !== 'launcher') {+ if (note.type !== "launcher") {throw new Error(`Note '${note.noteId}' '${note.title}' is not a launcher even though it's in the launcher subtree`);}- if (!utils.isDesktop() && note.isLabelTruthy('desktopOnly')) {+ if (!utils.isDesktop() && note.isLabelTruthy("desktopOnly")) {return false;}const launcherType = note.getLabelValue("launcherType");- if (glob.TRILIUM_SAFE_MODE && launcherType === 'customWidget') {+ if (glob.TRILIUM_SAFE_MODE && launcherType === "customWidget") {return false;}let widget: BasicWidget;- if (launcherType === 'command') {- widget = this.initCommandLauncherWidget(note)- .class("launcher-button");- } else if (launcherType === 'note') {- widget = new NoteLauncher(note)- .class("launcher-button");- } else if (launcherType === 'script') {- widget = new ScriptLauncher(note)- .class("launcher-button");- } else if (launcherType === 'customWidget') {+ if (launcherType === "command") {+ widget = this.initCommandLauncherWidget(note).class("launcher-button");+ } else if (launcherType === "note") {+ widget = new NoteLauncher(note).class("launcher-button");+ } else if (launcherType === "script") {+ widget = new ScriptLauncher(note).class("launcher-button");+ } else if (launcherType === "customWidget") {widget = await this.initCustomWidget(note);- } else if (launcherType === 'builtinWidget') {+ } else if (launcherType === "builtinWidget") {widget = this.initBuiltinWidget(note);} else {throw new Error(`Unrecognized launcher type '${launcherType}' for launcher '${note.noteId}' title '${note.title}'`);@@ -93,7 +89,7 @@ export default class LauncherWidget extends BasicWidget {}async initCustomWidget(note: FNote) {- const widget = await note.getRelationTarget('widget');+ const widget = await note.getRelationTarget("widget");if (widget) {return await widget.executeScript();diff --git a/src/public/app/widgets/containers/launcher_container.ts b/src/public/app/widgets/containers/launcher_container.tsindex e0f5740279..55d83030bb 100644--- a/src/public/app/widgets/containers/launcher_container.ts+++ b/src/public/app/widgets/containers/launcher_container.ts@@ -10,8 +10,8 @@ export default class LauncherContainer extends FlexContainer<LauncherWidget> {constructor(isHorizontalLayout: boolean) {super(isHorizontalLayout ? "row" : "column");- this.id('launcher-container');- this.css(isHorizontalLayout ? "width" : 'height', '100%');+ this.id("launcher-container");+ this.css(isHorizontalLayout ? "width" : "height", "100%");this.filling();this.isHorizontalLayout = isHorizontalLayout;@@ -21,7 +21,7 @@ export default class LauncherContainer extends FlexContainer<LauncherWidget> {async load() {await froca.initializedPromise;- const visibleLaunchersRootId = utils.isMobile() ? '_lbMobileVisibleLaunchers' : '_lbVisibleLaunchers';+ const visibleLaunchersRootId = utils.isMobile() ? "_lbMobileVisibleLaunchers" : "_lbVisibleLaunchers";const visibleLaunchersRoot = await froca.getNote(visibleLaunchersRootId, true);if (!visibleLaunchersRoot) {@@ -40,8 +40,7 @@ export default class LauncherContainer extends FlexContainer<LauncherWidget> {if (success) {newChildren.push(launcherWidget);}- }- catch (e) {+ } catch (e) {console.error(e);}}@@ -52,17 +51,17 @@ export default class LauncherContainer extends FlexContainer<LauncherWidget> {this.$widget.empty();this.renderChildren();- await this.handleEventInChildren('initialRenderComplete');+ await this.handleEventInChildren("initialRenderComplete");const activeContext = appContext.tabManager.getActiveContext();if (activeContext) {- await this.handleEvent('setNoteContext', {+ await this.handleEvent("setNoteContext", {noteContext: activeContext});if (activeContext.notePath) {- await this.handleEvent('noteSwitched', {+ await this.handleEvent("noteSwitched", {noteContext: activeContext,notePath: activeContext.notePath});@@ -70,8 +69,8 @@ export default class LauncherContainer extends FlexContainer<LauncherWidget> {}}- entitiesReloadedEvent({loadResults}: EventData<"entitiesReloaded">) {- if (loadResults.getBranchRows().find(branch => branch.parentNoteId && froca.getNoteFromCache(branch.parentNoteId)?.isLaunchBarConfig())) {+ entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {+ if (loadResults.getBranchRows().find((branch) => branch.parentNoteId && froca.getNoteFromCache(branch.parentNoteId)?.isLaunchBarConfig())) {// changes in note placement require reload of all launchers, all other changes are handled by individual// launchersthis.load();diff --git a/src/public/app/widgets/containers/left_pane_container.js b/src/public/app/widgets/containers/left_pane_container.jsindex fa1915a1e3..81a13d171e 100644--- a/src/public/app/widgets/containers/left_pane_container.js+++ b/src/public/app/widgets/containers/left_pane_container.js@@ -4,27 +4,27 @@ import appContext from "../../components/app_context.js";export default class LeftPaneContainer extends FlexContainer {constructor() {- super('column');+ super("column");- this.id('left-pane');- this.css('height', '100%');+ this.id("left-pane");+ this.css("height", "100%");this.collapsible();}isEnabled() {- return super.isEnabled() && options.is('leftPaneVisible');+ return super.isEnabled() && options.is("leftPaneVisible");}- entitiesReloadedEvent({loadResults}) {+ entitiesReloadedEvent({ loadResults }) {if (loadResults.isOptionReloaded("leftPaneVisible")) {const visible = this.isEnabled();this.toggleInt(visible);if (visible) {- this.triggerEvent('focusTree');+ this.triggerEvent("focusTree");} else {const activeNoteContext = appContext.tabManager.getActiveContext();- this.triggerEvent('focusOnDetail', {ntxId: activeNoteContext.ntxId});+ this.triggerEvent("focusOnDetail", { ntxId: activeNoteContext.ntxId });}}}diff --git a/src/public/app/widgets/containers/ribbon_container.js b/src/public/app/widgets/containers/ribbon_container.jsindex d6dcbe95c0..b9517be157 100644--- a/src/public/app/widgets/containers/ribbon_container.js+++ b/src/public/app/widgets/containers/ribbon_container.js@@ -122,8 +122,7 @@ export default class RibbonContainer extends NoteContextAwareWidget {}isEnabled() {- return super.isEnabled()- && this.noteContext.viewScope.viewMode === 'default';+ return super.isEnabled() && this.noteContext.viewScope.viewMode === "default";}ribbon(widget) {@@ -145,24 +144,20 @@ export default class RibbonContainer extends NoteContextAwareWidget {doRender() {this.$widget = $(TPL);- this.$tabContainer = this.$widget.find('.ribbon-tab-container');- this.$buttonContainer = this.$widget.find('.ribbon-button-container');- this.$bodyContainer = this.$widget.find('.ribbon-body-container');+ this.$tabContainer = this.$widget.find(".ribbon-tab-container");+ this.$buttonContainer = this.$widget.find(".ribbon-button-container");+ this.$bodyContainer = this.$widget.find(".ribbon-body-container");for (const ribbonWidget of this.ribbonWidgets) {- this.$bodyContainer.append(- $('<div class="ribbon-body">')- .attr('data-ribbon-component-id', ribbonWidget.componentId)- .append(ribbonWidget.render())- );+ this.$bodyContainer.append($('<div class="ribbon-body">').attr("data-ribbon-component-id", ribbonWidget.componentId).append(ribbonWidget.render()));}for (const buttonWidget of this.buttonWidgets) {this.$buttonContainer.append(buttonWidget.render());}- this.$tabContainer.on('click', '.ribbon-tab-title', e => {- const $ribbonTitle = $(e.target).closest('.ribbon-tab-title');+ this.$tabContainer.on("click", ".ribbon-tab-title", (e) => {+ const $ribbonTitle = $(e.target).closest(".ribbon-tab-title");this.toggleRibbonTab($ribbonTitle);});@@ -171,11 +166,11 @@ export default class RibbonContainer extends NoteContextAwareWidget {toggleRibbonTab($ribbonTitle, refreshActiveTab = true) {const activate = !$ribbonTitle.hasClass("active");- this.$tabContainer.find('.ribbon-tab-title').removeClass("active");- this.$bodyContainer.find('.ribbon-body').removeClass("active");+ this.$tabContainer.find(".ribbon-tab-title").removeClass("active");+ this.$bodyContainer.find(".ribbon-body").removeClass("active");if (activate) {- const ribbonComponendId = $ribbonTitle.attr('data-ribbon-component-id');+ const ribbonComponendId = $ribbonTitle.attr("data-ribbon-component-id");const wasAlreadyActive = this.lastActiveComponentId === ribbonComponendId;@@ -187,7 +182,7 @@ export default class RibbonContainer extends NoteContextAwareWidget {const activeChild = this.getActiveRibbonWidget();if (activeChild && (refreshActiveTab || !wasAlreadyActive)) {- const handleEventPromise = activeChild.handleEvent('noteSwitched', {noteContext: this.noteContext, notePath: this.notePath});+ const handleEventPromise = activeChild.handleEvent("noteSwitched", { noteContext: this.noteContext, notePath: this.notePath });if (refreshActiveTab) {if (handleEventPromise) {@@ -223,12 +218,9 @@ export default class RibbonContainer extends NoteContextAwareWidget {}const $ribbonTitle = $('<div class="ribbon-tab-title">')- .attr('data-ribbon-component-id', ribbonWidget.componentId)- .attr('data-ribbon-component-name', ribbonWidget.name)- .append($('<span class="ribbon-tab-title-icon">')- .addClass(ret.icon)- .attr("title", ret.title)- .attr('data-toggle-command', ribbonWidget.toggleCommand))+ .attr("data-ribbon-component-id", ribbonWidget.componentId)+ .attr("data-ribbon-component-name", ribbonWidget.name)+ .append($('<span class="ribbon-tab-title-icon">').addClass(ret.icon).attr("title", ret.title).attr("data-toggle-command", ribbonWidget.toggleCommand)).append(" ").append($('<span class="ribbon-tab-title-label">').text(ret.title));@@ -244,17 +236,16 @@ export default class RibbonContainer extends NoteContextAwareWidget {}}- keyboardActionsService.getActions().then(actions => {- this.$tabContainer.find('.ribbon-tab-title-icon').tooltip({- title: function() {+ keyboardActionsService.getActions().then((actions) => {+ this.$tabContainer.find(".ribbon-tab-title-icon").tooltip({+ title: function () {const toggleCommandName = $(this).attr("data-toggle-command");- const action = actions.find(act => act.actionName === toggleCommandName);+ const action = actions.find((act) => act.actionName === toggleCommandName);const title = $(this).attr("data-title");if (action && action.effectiveShortcuts.length > 0) {return `${title} (${action.effectiveShortcuts.join(", ")})`;- }- else {+ } else {return title;}}@@ -267,9 +258,8 @@ export default class RibbonContainer extends NoteContextAwareWidget {if ($ribbonTabToActivate) {this.toggleRibbonTab($ribbonTabToActivate, false);- }- else {- this.$bodyContainer.find('.ribbon-body').removeClass("active");+ } else {+ this.$bodyContainer.find(".ribbon-body").removeClass("active");}}@@ -280,16 +270,16 @@ export default class RibbonContainer extends NoteContextAwareWidget {}ensureOwnedAttributesAreOpen(ntxId) {- if (this.isNoteContext(ntxId) && !this.isRibbonTabActive('ownedAttributes')) {- this.toggleRibbonTabWithName('ownedAttributes', ntxId);+ if (this.isNoteContext(ntxId) && !this.isRibbonTabActive("ownedAttributes")) {+ this.toggleRibbonTabWithName("ownedAttributes", ntxId);}}- addNewLabelEvent({ntxId}) {+ addNewLabelEvent({ ntxId }) {this.ensureOwnedAttributesAreOpen(ntxId);}- addNewRelationEvent({ntxId}) {+ addNewRelationEvent({ ntxId }) {this.ensureOwnedAttributesAreOpen(ntxId);}@@ -313,18 +303,16 @@ export default class RibbonContainer extends NoteContextAwareWidget {componentName = componentName[0].toLowerCase() + componentName.substr(1);this.toggleRibbonTabWithName(componentName, data.ntxId);- }- else {+ } else {return super.handleEvent(name, data);}}async handleEventInChildren(name, data) {- if (['activeContextChanged', 'setNoteContext'].includes(name)) {+ if (["activeContextChanged", "setNoteContext"].includes(name)) {// won't trigger .refresh();- await super.handleEventInChildren('setNoteContext', data);- }- else if (this.isEnabled() || name === 'initialRenderComplete') {+ await super.handleEventInChildren("setNoteContext", data);+ } else if (this.isEnabled() || name === "initialRenderComplete") {const activeRibbonWidget = this.getActiveRibbonWidget();// forward events only to active ribbon tab, inactive ones don't need to be updated@@ -338,15 +326,14 @@ export default class RibbonContainer extends NoteContextAwareWidget {}}- entitiesReloadedEvent({loadResults}) {+ entitiesReloadedEvent({ loadResults }) {if (loadResults.isNoteReloaded(this.noteId) && this.lastNoteType !== this.note.type) {// note type influences the list of available ribbon tabs the most// check for the type is so that we don't update on each title renamethis.lastNoteType = this.note.type;this.refresh();- }- else if (loadResults.getAttributeRows(this.componentId).find(attr => attributeService.isAffecting(attr, this.note))) {+ } else if (loadResults.getAttributeRows(this.componentId).find((attr) => attributeService.isAffecting(attr, this.note))) {this.refreshWithNote(this.note, true);}}@@ -358,15 +345,15 @@ export default class RibbonContainer extends NoteContextAwareWidget {/*** Executed as soon as the user presses the "Edit" floating button in a read-only text note.- *+ ** <p>* We need to refresh the ribbon for cases such as the classic editor which relies on the read-only state.*/- readOnlyTemporarilyDisabledEvent() {+ readOnlyTemporarilyDisabledEvent() {this.refresh();}getActiveRibbonWidget() {- return this.ribbonWidgets.find(ch => ch.componentId === this.lastActiveComponentId)+ return this.ribbonWidgets.find((ch) => ch.componentId === this.lastActiveComponentId);}}diff --git a/src/public/app/widgets/containers/right_pane_container.ts b/src/public/app/widgets/containers/right_pane_container.tsindex 9612aceff3..4325935fe5 100644--- a/src/public/app/widgets/containers/right_pane_container.ts+++ b/src/public/app/widgets/containers/right_pane_container.ts@@ -3,37 +3,32 @@ import splitService from "../../services/resizer.js";import RightPanelWidget from "../right_panel_widget.js";export default class RightPaneContainer extends FlexContainer<RightPanelWidget> {-private rightPaneHidden: boolean;constructor() {- super('column');+ super("column");- this.id('right-pane');- this.css('height', '100%');+ this.id("right-pane");+ this.css("height", "100%");this.collapsible();this.rightPaneHidden = false;}isEnabled() {- return super.isEnabled()- && !this.rightPaneHidden- && this.children.length > 0- && !!this.children.find(ch => ch.isEnabled() && ch.canBeShown());+ return super.isEnabled() && !this.rightPaneHidden && this.children.length > 0 && !!this.children.find((ch) => ch.isEnabled() && ch.canBeShown());}handleEventInChildren(name: string, data: unknown) {const promise = super.handleEventInChildren(name, data);- if (['activeContextChanged', 'noteSwitchedAndActivated', 'noteSwitched'].includes(name)) {+ if (["activeContextChanged", "noteSwitchedAndActivated", "noteSwitched"].includes(name)) {// the right pane is displayed only if some child widget is active,// we'll reevaluate the visibility based on events which are probable to cause visibility change// but these events need to be finished and only then we checkif (promise) {promise.then(() => this.reEvaluateRightPaneVisibilityCommand());- }- else {+ } else {this.reEvaluateRightPaneVisibilityCommand();}}diff --git a/src/public/app/widgets/containers/root_container.js b/src/public/app/widgets/containers/root_container.jsindex 65e35fb8b0..4eac279ac7 100644--- a/src/public/app/widgets/containers/root_container.js+++ b/src/public/app/widgets/containers/root_container.js@@ -4,7 +4,7 @@ export default class RootContainer extends FlexContainer {constructor(isHorizontalLayout) {super(isHorizontalLayout ? "column" : "row");- this.id('root-widget');- this.css('height', '100dvh');+ this.id("root-widget");+ this.css("height", "100dvh");}}diff --git a/src/public/app/widgets/containers/scrolling_container.js b/src/public/app/widgets/containers/scrolling_container.jsindex f13994353d..70162cb106 100644--- a/src/public/app/widgets/containers/scrolling_container.js+++ b/src/public/app/widgets/containers/scrolling_container.js@@ -5,35 +5,32 @@ export default class ScrollingContainer extends Container {super();this.class("scrolling-container");- this.css('overflow', 'auto');- this.css('scroll-behavior', 'smooth');- this.css('position', 'relative');+ this.css("overflow", "auto");+ this.css("scroll-behavior", "smooth");+ this.css("position", "relative");}- setNoteContextEvent({noteContext}) {+ setNoteContextEvent({ noteContext }) {/** @var {NoteContext} */this.noteContext = noteContext;}- async noteSwitchedEvent({noteContext, notePath}) {+ async noteSwitchedEvent({ noteContext, notePath }) {this.$widget.scrollTop(0);}- async noteSwitchedAndActivatedEvent({noteContext, notePath}) {+ async noteSwitchedAndActivatedEvent({ noteContext, notePath }) {this.noteContext = noteContext;this.$widget.scrollTop(0);}- async activeContextChangedEvent({noteContext}) {+ async activeContextChangedEvent({ noteContext }) {this.noteContext = noteContext;}handleEventInChildren(name, data) {- if (name === 'readOnlyTemporarilyDisabled'- && this.noteContext- && this.noteContext.ntxId === data.noteContext.ntxId) {-+ if (name === "readOnlyTemporarilyDisabled" && this.noteContext && this.noteContext.ntxId === data.noteContext.ntxId) {const scrollTop = this.$widget.scrollTop();const promise = super.handleEventInChildren(name, data);@@ -42,13 +39,12 @@ export default class ScrollingContainer extends Container {promise.then(() => setTimeout(() => this.$widget.scrollTop(scrollTop), 500));return promise;- }- else {+ } else {return super.handleEventInChildren(name, data);}}- scrollContainerToCommand({position}) {+ scrollContainerToCommand({ position }) {this.$widget.scrollTop(position);}}diff --git a/src/public/app/widgets/containers/split_note_container.js b/src/public/app/widgets/containers/split_note_container.jsindex 59831de1ba..2e7d8c9cbf 100644--- a/src/public/app/widgets/containers/split_note_container.js+++ b/src/public/app/widgets/containers/split_note_container.js@@ -3,38 +3,38 @@ import appContext from "../../components/app_context.js";export default class SplitNoteContainer extends FlexContainer {constructor(widgetFactory) {- super('row');+ super("row");this.widgetFactory = widgetFactory;this.widgets = {};- this.class('split-note-container-widget');- this.css('flex-grow', '1');+ this.class("split-note-container-widget");+ this.css("flex-grow", "1");this.collapsible();}- async newNoteContextCreatedEvent({noteContext}) {+ async newNoteContextCreatedEvent({ noteContext }) {const widget = this.widgetFactory();const $renderedWidget = widget.render();$renderedWidget.attr("data-ntx-id", noteContext.ntxId);- $renderedWidget.on('click', () => appContext.tabManager.activateNoteContext(noteContext.ntxId));+ $renderedWidget.on("click", () => appContext.tabManager.activateNoteContext(noteContext.ntxId));this.$widget.append($renderedWidget);- widget.handleEvent('initialRenderComplete');+ widget.handleEvent("initialRenderComplete");widget.toggleExt(false);this.widgets[noteContext.ntxId] = widget;- await widget.handleEvent('setNoteContext', { noteContext });+ await widget.handleEvent("setNoteContext", { noteContext });this.child(widget);}- async openNewNoteSplitEvent({ntxId, notePath, hoistedNoteId, viewScope}) {+ async openNewNoteSplitEvent({ ntxId, notePath, hoistedNoteId, viewScope }) {const mainNtxId = appContext.tabManager.getActiveMainContext().ntxId;if (!ntxId) {@@ -48,33 +48,30 @@ export default class SplitNoteContainer extends FlexContainer {const noteContext = await appContext.tabManager.openEmptyTab(null, hoistedNoteId, mainNtxId);// remove the original position of newly created note context- const ntxIds = appContext.tabManager.children.map(c => c.ntxId)- .filter(id => id !== noteContext.ntxId);+ const ntxIds = appContext.tabManager.children.map((c) => c.ntxId).filter((id) => id !== noteContext.ntxId);// insert the note context after the originating note contextntxIds.splice(ntxIds.indexOf(ntxId) + 1, 0, noteContext.ntxId);- this.triggerCommand("noteContextReorder", {ntxIdsInOrder: ntxIds});+ this.triggerCommand("noteContextReorder", { ntxIdsInOrder: ntxIds });// move the note context rendered widget after the originating widget- this.$widget.find(`[data-ntx-id="${noteContext.ntxId}"]`)- .insertAfter(this.$widget.find(`[data-ntx-id="${ntxId}"]`));+ this.$widget.find(`[data-ntx-id="${noteContext.ntxId}"]`).insertAfter(this.$widget.find(`[data-ntx-id="${ntxId}"]`));await appContext.tabManager.activateNoteContext(noteContext.ntxId);if (notePath) {await noteContext.setNote(notePath, viewScope);- }- else {+ } else {await noteContext.setEmpty();}}- closeThisNoteSplitCommand({ntxId}) {+ closeThisNoteSplitCommand({ ntxId }) {appContext.tabManager.removeNoteContext(ntxId);}- async moveThisNoteSplitCommand({ntxId, isMovingLeft}) {+ async moveThisNoteSplitCommand({ ntxId, isMovingLeft }) {if (!ntxId) {logError("empty ntxId!");return;@@ -82,7 +79,7 @@ export default class SplitNoteContainer extends FlexContainer {const contexts = appContext.tabManager.noteContexts;- const currentIndex = contexts.findIndex(c => c.ntxId === ntxId);+ const currentIndex = contexts.findIndex((c) => c.ntxId === ntxId);const leftIndex = isMovingLeft ? currentIndex - 1 : currentIndex;if (currentIndex === -1 || leftIndex < 0 || leftIndex + 1 >= contexts.length) {@@ -95,24 +92,18 @@ export default class SplitNoteContainer extends FlexContainer {return;}- const ntxIds = contexts.map(c => c.ntxId);- const newNtxIds = [- ...ntxIds.slice(0, leftIndex),- ntxIds[leftIndex + 1],- ntxIds[leftIndex],- ...ntxIds.slice(leftIndex + 2),- ];+ const ntxIds = contexts.map((c) => c.ntxId);+ const newNtxIds = [...ntxIds.slice(0, leftIndex), ntxIds[leftIndex + 1], ntxIds[leftIndex], ...ntxIds.slice(leftIndex + 2)];const isChangingMainContext = !contexts[leftIndex].mainNtxId;this.triggerCommand("noteContextReorder", {ntxIdsInOrder: newNtxIds,oldMainNtxId: isChangingMainContext ? ntxIds[leftIndex] : null,- newMainNtxId: isChangingMainContext ? ntxIds[leftIndex + 1]: null,+ newMainNtxId: isChangingMainContext ? ntxIds[leftIndex + 1] : null});// reorder the note context widgets- this.$widget.find(`[data-ntx-id="${ntxIds[leftIndex]}"]`)- .insertAfter(this.$widget.find(`[data-ntx-id="${ntxIds[leftIndex + 1]}"]`));+ this.$widget.find(`[data-ntx-id="${ntxIds[leftIndex]}"]`).insertAfter(this.$widget.find(`[data-ntx-id="${ntxIds[leftIndex + 1]}"]`));// activate context that now contains the original noteawait appContext.tabManager.activateNoteContext(isMovingLeft ? ntxIds[leftIndex + 1] : ntxIds[leftIndex]);@@ -126,8 +117,8 @@ export default class SplitNoteContainer extends FlexContainer {this.refresh();}- noteContextRemovedEvent({ntxIds}) {- this.children = this.children.filter(c => !ntxIds.includes(c.ntxId));+ noteContextRemovedEvent({ ntxIds }) {+ this.children = this.children.filter((c) => !ntxIds.includes(c.ntxId));for (const ntxId of ntxIds) {this.$widget.find(`[data-ntx-id="${ntxId}"]`).remove();@@ -136,13 +127,12 @@ export default class SplitNoteContainer extends FlexContainer {}}- contextsReopenedEvent({ntxId, afterNtxId}) {+ contextsReopenedEvent({ ntxId, afterNtxId }) {if (ntxId === undefined || afterNtxId === undefined) {// no single split reopenedreturn;}- this.$widget.find(`[data-ntx-id="${ntxId}"]`)- .insertAfter(this.$widget.find(`[data-ntx-id="${afterNtxId}"]`));+ this.$widget.find(`[data-ntx-id="${ntxId}"]`).insertAfter(this.$widget.find(`[data-ntx-id="${afterNtxId}"]`));}async refresh() {@@ -169,7 +159,7 @@ export default class SplitNoteContainer extends FlexContainer {* activation, further note switches are always propagated to the tabs.*/handleEventInChildren(name, data) {- if (['noteSwitched', 'noteSwitchedAndActivated'].includes(name)) {+ if (["noteSwitched", "noteSwitchedAndActivated"].includes(name)) {// this event is propagated only to the widgets of a particular tabconst widget = this.widgets[data.noteContext.ntxId];@@ -177,23 +167,16 @@ export default class SplitNoteContainer extends FlexContainer {return Promise.resolve();}- if (widget.hasBeenAlreadyShown- || name === 'noteSwitchedAndActivated'- || appContext.tabManager.getActiveMainContext() === data.noteContext.getMainContext()- ) {+ if (widget.hasBeenAlreadyShown || name === "noteSwitchedAndActivated" || appContext.tabManager.getActiveMainContext() === data.noteContext.getMainContext()) {widget.hasBeenAlreadyShown = true;- return [- widget.handleEvent('noteSwitched', data),- this.refreshNotShown(data)- ];- }- else {+ return [widget.handleEvent("noteSwitched", data), this.refreshNotShown(data)];+ } else {return Promise.resolve();}}- if (name === 'activeContextChanged') {+ if (name === "activeContextChanged") {return this.refreshNotShown(data);} else {return super.handleEventInChildren(name, data);@@ -209,7 +192,7 @@ export default class SplitNoteContainer extends FlexContainer {if (!widget.hasBeenAlreadyShown) {widget.hasBeenAlreadyShown = true;- promises.push(widget.handleEvent('activeContextChanged', {noteContext: subContext}));+ promises.push(widget.handleEvent("activeContextChanged", { noteContext: subContext }));}}diff --git a/src/public/app/widgets/dialogs/about.js b/src/public/app/widgets/dialogs/about.jsindex 15b011bdfe..db3fe4c5e0 100644--- a/src/public/app/widgets/dialogs/about.js+++ b/src/public/app/widgets/dialogs/about.js@@ -1,18 +1,17 @@-import { formatDateTime } from "../../utils/formatters.js"+import { formatDateTime } from "../../utils/formatters.js";import { t } from "../../services/i18n.js";import BasicWidget from "../basic_widget.js";import openService from "../../services/open.js";import server from "../../services/server.js";import utils from "../../services/utils.js";-const TPL = `<div class="about-dialog modal fade mx-auto" tabindex="-1" role="dialog"><div class="modal-dialog modal-lg" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">${t("about.title")}</h5>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('about.close')}"></button>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("about.close")}"></button></div><div class="modal-body"><table class="table table-borderless">@@ -71,23 +70,25 @@ export default class AboutDialog extends BasicWidget {}async refresh() {- const appInfo = await server.get('app-info');+ const appInfo = await server.get("app-info");this.$appVersion.text(appInfo.appVersion);this.$dbVersion.text(appInfo.dbVersion);this.$syncVersion.text(appInfo.syncVersion);this.$buildDate.text(formatDateTime(appInfo.buildDate));this.$buildRevision.text(appInfo.buildRevision);- this.$buildRevision.attr('href', `https://github.com/TriliumNext/Notes/commit/${appInfo.buildRevision}`);+ this.$buildRevision.attr("href", `https://github.com/TriliumNext/Notes/commit/${appInfo.buildRevision}`);if (utils.isElectron()) {- this.$dataDirectory.html($('<a></a>', {- href: '#',- text: appInfo.dataDirectory,- }));- this.$dataDirectory.find("a").on('click', (event) => {+ this.$dataDirectory.html(+ $("<a></a>", {+ href: "#",+ text: appInfo.dataDirectory+ })+ );+ this.$dataDirectory.find("a").on("click", (event) => {event.preventDefault();openService.openDirectory(appInfo.dataDirectory);- })+ });} else {this.$dataDirectory.text(appInfo.dataDirectory);}diff --git a/src/public/app/widgets/dialogs/add_link.js b/src/public/app/widgets/dialogs/add_link.jsindex 964a520009..d60356869f 100644--- a/src/public/app/widgets/dialogs/add_link.js+++ b/src/public/app/widgets/dialogs/add_link.js@@ -1,5 +1,5 @@import { t } from "../../services/i18n.js";-import treeService from '../../services/tree.js';+import treeService from "../../services/tree.js";import noteAutocompleteService from "../../services/note_autocomplete.js";import utils from "../../services/utils.js";import BasicWidget from "../basic_widget.js";@@ -9,17 +9,17 @@ const TPL = `<div class="modal-dialog modal-lg" style="max-width: 1000px" role="document"><div class="modal-content"><div class="modal-header">- <h5 class="modal-title flex-grow-1">${t('add_link.add_link')}</h5>- <button type="button" class="help-button" title="${t('add_link.help_on_links')}" data-help-page="links.html">?</button>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('add_link.close')}"></button>+ <h5 class="modal-title flex-grow-1">${t("add_link.add_link")}</h5>+ <button type="button" class="help-button" title="${t("add_link.help_on_links")}" data-help-page="links.html">?</button>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("add_link.close")}"></button></div><form class="add-link-form"><div class="modal-body"><div class="form-group">- <label for="add-link-note-autocomplete">${t('add_link.note')}</label>+ <label for="add-link-note-autocomplete">${t("add_link.note")}</label><div class="input-group">- <input class="add-link-note-autocomplete form-control" placeholder="${t('add_link.search_note')}">+ <input class="add-link-note-autocomplete form-control" placeholder="${t("add_link.search_note")}"></div></div>@@ -27,20 +27,20 @@ const TPL = `<div class="add-link-title-radios form-check"><label class="form-check-label"><input class="form-check-input" type="radio" name="link-type" value="reference-link" checked>- ${t('add_link.link_title_mirrors')}+ ${t("add_link.link_title_mirrors")}</label></div><div class="add-link-title-radios form-check"><label class="form-check-label"><input class="form-check-input" type="radio" name="link-type" value="hyper-link">- ${t('add_link.link_title_arbitrary')}+ ${t("add_link.link_title_arbitrary")}</label></div><div class="add-link-title-form-group form-group"><br/><label>- ${t('add_link.link_title')}+ ${t("add_link.link_title")}<input class="link-title form-control" style="width: 100%;"></label>@@ -48,7 +48,7 @@ const TPL = `</div></div><div class="modal-footer">- <button type="submit" class="btn btn-primary">${t('add_link.button_add_link')}</button>+ <button type="submit" class="btn btn-primary">${t("add_link.button_add_link")}</button></div></form></div>@@ -68,20 +68,18 @@ export default class AddLinkDialog extends BasicWidget {/** @var TextTypeWidget */this.textTypeWidget = null;- this.$form.on('submit', () => {+ this.$form.on("submit", () => {if (this.$autoComplete.getSelectedNotePath()) {- this.$widget.modal('hide');+ this.$widget.modal("hide");- const linkTitle = this.getLinkType() === 'reference-link' ? null : this.$linkTitle.val();+ const linkTitle = this.getLinkType() === "reference-link" ? null : this.$linkTitle.val();this.textTypeWidget.addLink(this.$autoComplete.getSelectedNotePath(), linkTitle);- }- else if (this.$autoComplete.getSelectedExternalLink()) {- this.$widget.modal('hide');+ } else if (this.$autoComplete.getSelectedExternalLink()) {+ this.$widget.modal("hide");this.textTypeWidget.addLink(this.$autoComplete.getSelectedExternalLink(), this.$linkTitle.val());- }- else {+ } else {logError("No link to add.");}@@ -89,18 +87,17 @@ export default class AddLinkDialog extends BasicWidget {});}- async showAddLinkDialogEvent({textTypeWidget, text = ''}) {+ async showAddLinkDialogEvent({ textTypeWidget, text = "" }) {this.textTypeWidget = textTypeWidget;this.$addLinkTitleSettings.toggle(!this.textTypeWidget.hasSelection());- this.$addLinkTitleSettings.find('input[type=radio]').on('change', e => this.updateTitleSettingsVisibility(e));+ this.$addLinkTitleSettings.find("input[type=radio]").on("change", (e) => this.updateTitleSettingsVisibility(e));// with selection hyperlink is impliedif (this.textTypeWidget.hasSelection()) {this.$addLinkTitleSettings.find("input[value='hyper-link']").prop("checked", true);- }- else {+ } else {this.$addLinkTitleSettings.find("input[value='reference-link']").prop("checked", true);}@@ -108,10 +105,10 @@ export default class AddLinkDialog extends BasicWidget {utils.openDialog(this.$widget);- this.$autoComplete.val('');- this.$linkTitle.val('');+ this.$autoComplete.val("");+ this.$linkTitle.val("");- const setDefaultLinkTitle = async noteId => {+ const setDefaultLinkTitle = async (noteId) => {const noteTitle = await treeService.getNoteTitle(noteId);this.$linkTitle.val(noteTitle);@@ -122,7 +119,7 @@ export default class AddLinkDialog extends BasicWidget {allowCreatingNotes: true});- this.$autoComplete.on('autocomplete:noteselected', (event, suggestion, dataset) => {+ this.$autoComplete.on("autocomplete:noteselected", (event, suggestion, dataset) => {if (!suggestion.notePath) {return false;}@@ -136,7 +133,7 @@ export default class AddLinkDialog extends BasicWidget {}});- this.$autoComplete.on('autocomplete:externallinkselected', (event, suggestion, dataset) => {+ this.$autoComplete.on("autocomplete:externallinkselected", (event, suggestion, dataset) => {if (!suggestion.externalLink) {return false;}@@ -146,11 +143,10 @@ export default class AddLinkDialog extends BasicWidget {this.$linkTitle.val(suggestion.externalLink);});- this.$autoComplete.on('autocomplete:cursorchanged', (event, suggestion, dataset) => {+ this.$autoComplete.on("autocomplete:cursorchanged", (event, suggestion, dataset) => {if (suggestion.externalLink) {- this.$linkTitle.val(suggestion.externalLink)- }- else {+ this.$linkTitle.val(suggestion.externalLink);+ } else {const noteId = treeService.getNoteIdFromUrl(suggestion.notePath);if (noteId) {@@ -161,28 +157,25 @@ export default class AddLinkDialog extends BasicWidget {if (text && text.trim()) {noteAutocompleteService.setText(this.$autoComplete, text);- }- else {+ } else {noteAutocompleteService.showRecentNotes(this.$autoComplete);}- this.$autoComplete- .trigger('focus')- .trigger('select'); // to be able to quickly remove entered text+ this.$autoComplete.trigger("focus").trigger("select"); // to be able to quickly remove entered text}getLinkType() {if (this.$autoComplete.getSelectedExternalLink()) {- return 'external-link';+ return "external-link";}- return this.$addLinkTitleSettings.find('input[type=radio]:checked').val();+ return this.$addLinkTitleSettings.find("input[type=radio]:checked").val();}updateTitleSettingsVisibility() {const linkType = this.getLinkType();- this.$addLinkTitleFormGroup.toggle(linkType !== 'reference-link');- this.$addLinkTitleRadios.toggle(linkType !== 'external-link')+ this.$addLinkTitleFormGroup.toggle(linkType !== "reference-link");+ this.$addLinkTitleRadios.toggle(linkType !== "external-link");}}diff --git a/src/public/app/widgets/dialogs/branch_prefix.js b/src/public/app/widgets/dialogs/branch_prefix.jsindex ca50071017..9eaa440dcd 100644--- a/src/public/app/widgets/dialogs/branch_prefix.js+++ b/src/public/app/widgets/dialogs/branch_prefix.js@@ -1,5 +1,5 @@-import treeService from '../../services/tree.js';-import server from '../../services/server.js';+import treeService from "../../services/tree.js";+import server from "../../services/server.js";import froca from "../../services/froca.js";import toastService from "../../services/toast.js";import utils from "../../services/utils.js";@@ -14,13 +14,13 @@ const TPL = `<div class="branch-prefix-dialog modal fade mx-auto" tabindex="-1"<form class="branch-prefix-form"><div class="modal-content"><div class="modal-header">- <h5 class="modal-title flex-grow-1">${t('branch_prefix.edit_branch_prefix')}</h5>- <button class="help-button" type="button" data-help-page="tree-concepts.html#prefix" title="${t('branch_prefix.help_on_tree_prefix')}">?</button>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('branch_prefix.close')}"></button>+ <h5 class="modal-title flex-grow-1">${t("branch_prefix.edit_branch_prefix")}</h5>+ <button class="help-button" type="button" data-help-page="tree-concepts.html#prefix" title="${t("branch_prefix.help_on_tree_prefix")}">?</button>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("branch_prefix.close")}"></button></div><div class="modal-body"><div class="form-group">- <label for="branch-prefix-input">${t('branch_prefix.prefix')}</label> + <label for="branch-prefix-input">${t("branch_prefix.prefix")}</label> <div class="input-group"><input class="branch-prefix-input form-control">@@ -29,7 +29,7 @@ const TPL = `<div class="branch-prefix-dialog modal fade mx-auto" tabindex="-1"</div></div><div class="modal-footer">- <button class="btn btn-primary btn-sm">${t('branch_prefix.save')}</button>+ <button class="btn btn-primary btn-sm">${t("branch_prefix.save")}</button></div></div></form>@@ -42,15 +42,15 @@ export default class BranchPrefixDialog extends BasicWidget {this.modal = bootstrap.Modal.getOrCreateInstance(this.$widget);this.$form = this.$widget.find(".branch-prefix-form");this.$treePrefixInput = this.$widget.find(".branch-prefix-input");- this.$noteTitle = this.$widget.find('.branch-prefix-note-title');+ this.$noteTitle = this.$widget.find(".branch-prefix-note-title");- this.$form.on('submit', () => {+ this.$form.on("submit", () => {this.savePrefix();return false;});- this.$widget.on('shown.bs.modal', () => this.$treePrefixInput.trigger('focus'));+ this.$widget.on("shown.bs.modal", () => this.$treePrefixInput.trigger("focus"));}async refresh(notePath) {@@ -63,13 +63,13 @@ export default class BranchPrefixDialog extends BasicWidget {branchId = await froca.getBranchId(parentNoteId, noteId);const branch = froca.getBranch(branchId);- if (!branch || branch.noteId === 'root') {+ if (!branch || branch.noteId === "root") {return;}const parentNote = await froca.getNote(branch.parentNoteId);- if (parentNote.type === 'search') {+ if (parentNote.type === "search") {return;}@@ -95,6 +95,6 @@ export default class BranchPrefixDialog extends BasicWidget {this.modal.hide();- toastService.showMessage(t('branch_prefix.branch_prefix_saved'));+ toastService.showMessage(t("branch_prefix.branch_prefix_saved"));}}diff --git a/src/public/app/widgets/dialogs/bulk_actions.js b/src/public/app/widgets/dialogs/bulk_actions.jsindex f21286500a..af9b4616b9 100644--- a/src/public/app/widgets/dialogs/bulk_actions.js+++ b/src/public/app/widgets/dialogs/bulk_actions.js@@ -38,27 +38,27 @@ const TPL = `<div class="modal-dialog modal-xl" role="document"><div class="modal-content"><div class="modal-header">- <h5 class="modal-title">${t('bulk_actions.bulk_actions')}</h5>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('bulk_actions.close')}"></button>+ <h5 class="modal-title">${t("bulk_actions.bulk_actions")}</h5>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("bulk_actions.close")}"></button></div><div class="modal-body">- <h4>${t('bulk_actions.affected_notes')}: <span class="affected-note-count">0</span></h4>+ <h4>${t("bulk_actions.affected_notes")}: <span class="affected-note-count">0</span></h4><div class="form-check"><input id="include-descendants" class="include-descendants form-check-input" type="checkbox" value="">- <label for="include-descendants" class="form-check-label">${t('bulk_actions.include_descendants')}</label>+ <label for="include-descendants" class="form-check-label">${t("bulk_actions.include_descendants")}</label></div>- <h4>${t('bulk_actions.available_actions')}</h4>+ <h4>${t("bulk_actions.available_actions")}</h4><table class="bulk-available-action-list"></table>- <h4>${t('bulk_actions.chosen_actions')}</h4>+ <h4>${t("bulk_actions.chosen_actions")}</h4><table class="bulk-existing-action-list"></table></div><div class="modal-footer">- <button type="submit" class="execute-bulk-actions btn btn-primary">${t('bulk_actions.execute_bulk_actions')}</button>+ <button type="submit" class="execute-bulk-actions btn btn-primary">${t("bulk_actions.execute_bulk_actions")}</button></div></div></div>@@ -75,10 +75,10 @@ export default class BulkActionsDialog extends BasicWidget {this.$availableActionList = this.$widget.find(".bulk-available-action-list");this.$existingActionList = this.$widget.find(".bulk-existing-action-list");- this.$widget.on('click', '[data-action-add]', async event => {- const actionName = $(event.target).attr('data-action-add');+ this.$widget.on("click", "[data-action-add]", async (event) => {+ const actionName = $(event.target).attr("data-action-add");- await bulkActionService.addAction('_bulkAction', actionName);+ await bulkActionService.addAction("_bulkAction", actionName);await this.refresh();});@@ -90,7 +90,7 @@ export default class BulkActionsDialog extends BasicWidget {includeDescendants: this.$includeDescendants.is(":checked")});- toastService.showMessage(t('bulk_actions.bulk_actions_executed'), 3000);+ toastService.showMessage(t("bulk_actions.bulk_actions_executed"), 3000);utils.closeActiveDialog();});@@ -99,23 +99,23 @@ export default class BulkActionsDialog extends BasicWidget {async refresh() {this.renderAvailableActions();- const {affectedNoteCount} = await server.post('bulk-action/affected-notes', {+ const { affectedNoteCount } = await server.post("bulk-action/affected-notes", {noteIds: this.selectedOrActiveNoteIds,includeDescendants: this.$includeDescendants.is(":checked")});this.$affectedNoteCount.text(affectedNoteCount);- const bulkActionNote = await froca.getNote('_bulkAction');+ const bulkActionNote = await froca.getNote("_bulkAction");const actions = bulkActionService.parseActions(bulkActionNote);this.$existingActionList.empty();if (actions.length > 0) {- this.$existingActionList.append(...actions.map(action => action.render()));+ this.$existingActionList.append(...actions.map((action) => action.render()));} else {- this.$existingActionList.append($("<p>").text(t('bulk_actions.none_yet')))+ this.$existingActionList.append($("<p>").text(t("bulk_actions.none_yet")));}}@@ -129,25 +129,16 @@ export default class BulkActionsDialog extends BasicWidget {.append($actionGroupList);for (const action of actionGroup.actions) {- $actionGroupList.append(- $('<button class="btn btn-sm">')- .attr('data-action-add', action.actionName)- .text(action.actionTitle)- );+ $actionGroupList.append($('<button class="btn btn-sm">').attr("data-action-add", action.actionName).text(action.actionTitle));}this.$availableActionList.append($actionGroup);}}- entitiesReloadedEvent({loadResults}) {+ entitiesReloadedEvent({ loadResults }) {// only refreshing deleted attrs, otherwise components update themselves- if (loadResults.getAttributeRows().find(row =>- row.type === 'label'- && row.name === 'action'- && row.noteId === '_bulkAction'- && row.isDeleted)) {-+ if (loadResults.getAttributeRows().find((row) => row.type === "label" && row.name === "action" && row.noteId === "_bulkAction" && row.isDeleted)) {// this may be triggered from e.g., sync without open widget, then no need to refresh the widgetif (this.selectedOrActiveNoteIds && this.$widget.is(":visible")) {this.refresh();@@ -155,7 +146,7 @@ export default class BulkActionsDialog extends BasicWidget {}}- async openBulkActionsDialogEvent({selectedOrActiveNoteIds}) {+ async openBulkActionsDialogEvent({ selectedOrActiveNoteIds }) {this.selectedOrActiveNoteIds = selectedOrActiveNoteIds;this.$includeDescendants.prop("checked", false);diff --git a/src/public/app/widgets/dialogs/clone_to.js b/src/public/app/widgets/dialogs/clone_to.jsindex 7020635388..0098f340ad 100644--- a/src/public/app/widgets/dialogs/clone_to.js+++ b/src/public/app/widgets/dialogs/clone_to.js@@ -13,34 +13,34 @@ const TPL = `<div class="modal-dialog modal-lg" style="max-width: 1000px" role="document"><div class="modal-content"><div class="modal-header">- <h5 class="modal-title flex-grow-1">${t('clone_to.clone_notes_to')}</h5>- <button type="button" class="help-button" title="${t('clone_to.help_on_links')}" data-help-page="cloning-notes.html">?</button>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('clone_to.close')}"></button>+ <h5 class="modal-title flex-grow-1">${t("clone_to.clone_notes_to")}</h5>+ <button type="button" class="help-button" title="${t("clone_to.help_on_links")}" data-help-page="cloning-notes.html">?</button>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("clone_to.close")}"></button></div><form class="clone-to-form"><div class="modal-body">- <h5>${t('clone_to.notes_to_clone')}</h5>+ <h5>${t("clone_to.notes_to_clone")}</h5><ul class="clone-to-note-list" style="max-height: 200px; overflow: auto;"></ul><div class="form-group"><label style="width: 100%">- ${t('clone_to.target_parent_note')}+ ${t("clone_to.target_parent_note")}<div class="input-group">- <input class="clone-to-note-autocomplete form-control" placeholder="${t('clone_to.search_for_note_by_its_name')}">+ <input class="clone-to-note-autocomplete form-control" placeholder="${t("clone_to.search_for_note_by_its_name")}"></div></label></div>- <div class="form-group" title="${t('clone_to.cloned_note_prefix_title')}">+ <div class="form-group" title="${t("clone_to.cloned_note_prefix_title")}"><label style="width: 100%">- ${t('clone_to.prefix_optional')}+ ${t("clone_to.prefix_optional")}<input class="clone-prefix form-control" style="width: 100%;"></label></div></div><div class="modal-footer">- <button type="submit" class="btn btn-primary">${t('clone_to.clone_to_selected_note')}</button>+ <button type="submit" class="btn btn-primary">${t("clone_to.clone_to_selected_note")}</button></div></form></div>@@ -61,16 +61,15 @@ export default class CloneToDialog extends BasicWidget {this.$clonePrefix = this.$widget.find(".clone-prefix");this.$noteList = this.$widget.find(".clone-to-note-list");- this.$form.on('submit', () => {+ this.$form.on("submit", () => {const notePath = this.$noteAutoComplete.getSelectedNotePath();if (notePath) {- this.$widget.modal('hide');+ this.$widget.modal("hide");this.cloneNotesTo(notePath);- }- else {- logError(t('clone_to.no_path_to_clone_to'));+ } else {+ logError(t("clone_to.no_path_to_clone_to"));}return false;@@ -92,7 +91,7 @@ export default class CloneToDialog extends BasicWidget {utils.openDialog(this.$widget);- this.$noteAutoComplete.val('').trigger('focus');+ this.$noteAutoComplete.val("").trigger("focus");this.$noteList.empty();@@ -116,7 +115,7 @@ export default class CloneToDialog extends BasicWidget {const clonedNote = await froca.getNote(cloneNoteId);const targetNote = await froca.getBranch(targetBranchId).getNote();- toastService.showMessage(t('clone_to.note_cloned', { clonedTitle: clonedNote.title, targetTitle: targetNote.title }));+ toastService.showMessage(t("clone_to.note_cloned", { clonedTitle: clonedNote.title, targetTitle: targetNote.title }));}}}diff --git a/src/public/app/widgets/dialogs/confirm.ts b/src/public/app/widgets/dialogs/confirm.tsindex 9ccda11ee3..b29f0f8485 100644--- a/src/public/app/widgets/dialogs/confirm.ts+++ b/src/public/app/widgets/dialogs/confirm.ts@@ -8,8 +8,8 @@ const TPL = `<div class="modal-dialog modal-dialog-scrollable" role="document"><div class="modal-content"><div class="modal-header">- <h5 class="modal-title">${t('confirm.confirmation')}</h5>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('confirm.close')}"></button>+ <h5 class="modal-title">${t("confirm.confirmation")}</h5>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("confirm.close")}"></button></div><div class="modal-body"><div class="confirm-dialog-content"></div>@@ -17,11 +17,11 @@ const TPL = `<div class="confirm-dialog-custom"></div></div><div class="modal-footer">- <button class="confirm-dialog-cancel-button btn btn-sm">${t('confirm.cancel')}</button>+ <button class="confirm-dialog-cancel-button btn btn-sm">${t("confirm.cancel")}</button> - <button class="confirm-dialog-ok-button btn btn-primary btn-sm">${t('confirm.ok')}</button>+ <button class="confirm-dialog-ok-button btn btn-primary btn-sm">${t("confirm.ok")}</button></div></div></div>@@ -31,7 +31,7 @@ type ConfirmDialogCallback = (val: false | ConfirmDialogOptions) => void;export interface ConfirmDialogOptions {confirmed: boolean;- isDeleteNoteChecked: boolean+ isDeleteNoteChecked: boolean;}// For "showConfirmDialog"@@ -43,11 +43,10 @@ export interface ConfirmWithMessageOptions {export interface ConfirmWithTitleOptions {title: string;- callback: ConfirmDialogCallback;+ callback: ConfirmDialogCallback;}export default class ConfirmDialog extends BasicWidget {-private resolve: ConfirmDialogCallback | null;private modal!: bootstrap.Modal;@@ -74,7 +73,7 @@ export default class ConfirmDialog extends BasicWidget {this.$cancelButton = this.$widget.find(".confirm-dialog-cancel-button");this.$custom = this.$widget.find(".confirm-dialog-custom");- this.$widget.on('shown.bs.modal', () => this.$okButton.trigger("focus"));+ this.$widget.on("shown.bs.modal", () => this.$okButton.trigger("focus"));this.$widget.on("hidden.bs.modal", () => {if (this.resolve) {@@ -82,23 +81,23 @@ export default class ConfirmDialog extends BasicWidget {}if (this.$originallyFocused) {- this.$originallyFocused.trigger('focus');+ this.$originallyFocused.trigger("focus");this.$originallyFocused = null;}});- this.$cancelButton.on('click', () => this.doResolve(false));- this.$okButton.on('click', () => this.doResolve(true));+ this.$cancelButton.on("click", () => this.doResolve(false));+ this.$okButton.on("click", () => this.doResolve(true));}showConfirmDialogEvent({ message, callback }: ConfirmWithMessageOptions) {- this.$originallyFocused = $(':focus');+ this.$originallyFocused = $(":focus");this.$custom.hide();glob.activeDialog = this.$widget;- if (typeof message === 'string') {+ if (typeof message === "string") {message = $("<div>").text(message);}@@ -108,28 +107,27 @@ export default class ConfirmDialog extends BasicWidget {this.resolve = callback;}-+showConfirmDeleteNoteBoxWithNoteDialogEvent({ title, callback }: ConfirmWithTitleOptions) {glob.activeDialog = this.$widget;- this.$confirmContent.text(`${t('confirm.are_you_sure_remove_note', { title: title })}`);+ this.$confirmContent.text(`${t("confirm.are_you_sure_remove_note", { title: title })}`);- this.$custom.empty()+ this.$custom+ .empty().append("<br/>")- .append($("<div>")- .addClass("form-check")- .append(- $("<label>")- .addClass("form-check-label")- .attr("style", "text-decoration: underline dotted var(--main-text-color)")- .attr("title", `${t('confirm.if_you_dont_check')}`)- .append(- $("<input>")- .attr("type", "checkbox")- .addClass(`form-check-input ${DELETE_NOTE_BUTTON_CLASS}`)- )- .append(`${t('confirm.also_delete_note')}`)- ));+ .append(+ $("<div>")+ .addClass("form-check")+ .append(+ $("<label>")+ .addClass("form-check-label")+ .attr("style", "text-decoration: underline dotted var(--main-text-color)")+ .attr("title", `${t("confirm.if_you_dont_check")}`)+ .append($("<input>").attr("type", "checkbox").addClass(`form-check-input ${DELETE_NOTE_BUTTON_CLASS}`))+ .append(`${t("confirm.also_delete_note")}`)+ )+ );this.$custom.show();diff --git a/src/public/app/widgets/dialogs/delete_notes.ts b/src/public/app/widgets/dialogs/delete_notes.tsindex c4aa28a757..0781c46187 100644--- a/src/public/app/widgets/dialogs/delete_notes.ts+++ b/src/public/app/widgets/dialogs/delete_notes.ts@@ -14,7 +14,7 @@ interface Response {export interface ResolveOptions {proceed: boolean;- deleteAllClones?: boolean;+ deleteAllClones?: boolean;eraseNotes?: boolean;}@@ -29,51 +29,50 @@ const TPL = `<div class="modal-dialog modal-dialog-scrollable modal-xl" role="document"><div class="modal-content"><div class="modal-header">- <h4 class="modal-title">${t('delete_notes.delete_notes_preview')}</h4>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('delete_notes.close')}"></button>+ <h4 class="modal-title">${t("delete_notes.delete_notes_preview")}</h4>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("delete_notes.close")}"></button></div><div class="modal-body"><div class="form-checkbox"><input id="delete-all-clones" class="delete-all-clones form-check-input" value="1" type="checkbox">- <label for="delete-all-clones" class="form-check-label">${t('delete_notes.delete_all_clones_description')}</label>+ <label for="delete-all-clones" class="form-check-label">${t("delete_notes.delete_all_clones_description")}</label></div><div class="form-checkbox" style="margin-bottom: 1rem"><input id="erase-notes" class="erase-notes form-check-input" value="1" type="checkbox">- <label for="erase-notes" class="form-check-label">${t('delete_notes.erase_notes_warning')}</label>+ <label for="erase-notes" class="form-check-label">${t("delete_notes.erase_notes_warning")}</label></div><div class="delete-notes-list-wrapper">- <h4>${t('delete_notes.notes_to_be_deleted', { noteCount: '<span class="deleted-notes-count"></span>' })}</h4>+ <h4>${t("delete_notes.notes_to_be_deleted", { noteCount: '<span class="deleted-notes-count"></span>' })}</h4><ul class="delete-notes-list" style="max-height: 200px; overflow: auto;"></ul></div><div class="no-note-to-delete-wrapper alert alert-info">- ${t('delete_notes.no_note_to_delete')}+ ${t("delete_notes.no_note_to_delete")}</div><div class="broken-relations-wrapper"><div class="alert alert-danger">- <h4>${t('delete_notes.broken_relations_to_be_deleted', { relationCount: '<span class="broke-relations-count"></span>'})}</h4>+ <h4>${t("delete_notes.broken_relations_to_be_deleted", { relationCount: '<span class="broke-relations-count"></span>' })}</h4><ul class="broken-relations-list" style="max-height: 200px; overflow: auto;"></ul></div></div></div><div class="modal-footer">- <button class="delete-notes-dialog-cancel-button btn btn-sm">${t('delete_notes.cancel')}</button>+ <button class="delete-notes-dialog-cancel-button btn btn-sm">${t("delete_notes.cancel")}</button> - <button class="delete-notes-dialog-ok-button btn btn-primary btn-sm">${t('delete_notes.ok')}</button>+ <button class="delete-notes-dialog-ok-button btn btn-primary btn-sm">${t("delete_notes.ok")}</button></div></div></div></div>`;export default class DeleteNotesDialog extends BasicWidget {-private branchIds: string[] | null;private resolve!: (options: ResolveOptions) => void;@@ -113,15 +112,15 @@ export default class DeleteNotesDialog extends BasicWidget {this.$deleteAllClones = this.$widget.find(".delete-all-clones");this.$eraseNotes = this.$widget.find(".erase-notes");- this.$widget.on('shown.bs.modal', () => this.$okButton.trigger("focus"));+ this.$widget.on("shown.bs.modal", () => this.$okButton.trigger("focus"));- this.$cancelButton.on('click', () => {+ this.$cancelButton.on("click", () => {utils.closeActiveDialog();- this.resolve({proceed: false});+ this.resolve({ proceed: false });});- this.$okButton.on('click', () => {+ this.$okButton.on("click", () => {utils.closeActiveDialog();this.resolve({@@ -131,11 +130,11 @@ export default class DeleteNotesDialog extends BasicWidget {});});- this.$deleteAllClones.on('click', () => this.renderDeletePreview());+ this.$deleteAllClones.on("click", () => this.renderDeletePreview());}async renderDeletePreview() {- const response = await server.post<Response>('delete-notes-preview', {+ const response = await server.post<Response>("delete-notes-preview", {branchIdsToDelete: this.branchIds,deleteAllClones: this.forceDeleteAllClones || this.isDeleteAllClonesChecked()});@@ -147,11 +146,7 @@ export default class DeleteNotesDialog extends BasicWidget {this.$noNoteToDeleteWrapper.toggle(response.noteIdsToBeDeleted.length === 0);for (const note of await froca.getNotes(response.noteIdsToBeDeleted)) {- this.$deleteNotesList.append(- $("<li>").append(- await linkService.createLink(note.noteId, {showNotePath: true})- )- );+ this.$deleteNotesList.append($("<li>").append(await linkService.createLink(note.noteId, { showNotePath: true })));}this.$deletedNotesCount.text(response.noteIdsToBeDeleted.length);@@ -159,20 +154,22 @@ export default class DeleteNotesDialog extends BasicWidget {this.$brokenRelationsListWrapper.toggle(response.brokenRelations.length > 0);this.$brokenRelationsCount.text(response.brokenRelations.length);- await froca.getNotes(response.brokenRelations.map(br => br.noteId));+ await froca.getNotes(response.brokenRelations.map((br) => br.noteId));for (const attr of response.brokenRelations) {this.$brokenRelationsList.append(- $("<li>").html(t("delete_notes.deleted_relation_text", {- note: (await linkService.createLink(attr.value)).html(),- relation: `<code>${attr.name}</code>`,- source: (await linkService.createLink(attr.noteId)).html()- }))+ $("<li>").html(+ t("delete_notes.deleted_relation_text", {+ note: (await linkService.createLink(attr.value)).html(),+ relation: `<code>${attr.name}</code>`,+ source: (await linkService.createLink(attr.noteId)).html()+ })+ ));}}- async showDeleteNotesDialogEvent({branchIdsToDelete, callback, forceDeleteAllClones}: ShowDeleteNotesDialogOpts) {+ async showDeleteNotesDialogEvent({ branchIdsToDelete, callback, forceDeleteAllClones }: ShowDeleteNotesDialogOpts) {this.branchIds = branchIdsToDelete;this.forceDeleteAllClones = forceDeleteAllClones;@@ -180,9 +177,7 @@ export default class DeleteNotesDialog extends BasicWidget {utils.openDialog(this.$widget);- this.$deleteAllClones- .prop("checked", !!forceDeleteAllClones)- .prop("disabled", !!forceDeleteAllClones);+ this.$deleteAllClones.prop("checked", !!forceDeleteAllClones).prop("disabled", !!forceDeleteAllClones);this.$eraseNotes.prop("checked", false);diff --git a/src/public/app/widgets/dialogs/export.js b/src/public/app/widgets/dialogs/export.jsindex 7854acc91f..438d4eca51 100644--- a/src/public/app/widgets/dialogs/export.js+++ b/src/public/app/widgets/dialogs/export.js@@ -33,15 +33,15 @@ const TPL = `<div class="modal-dialog modal-lg" role="document"><div class="modal-content"><div class="modal-header">- <h5 class="modal-title">${t('export.export_note_title')} <span class="export-note-title"></span></h5>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('export.close')}"></button>+ <h5 class="modal-title">${t("export.export_note_title")} <span class="export-note-title"></span></h5>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("export.close")}"></button></div><form class="export-form"><div class="modal-body"><div class="form-check"><label class="form-check-label"><input class="export-type-subtree form-check-input" type="radio" name="export-type" value="subtree">- ${t('export.export_type_subtree')}+ ${t("export.export_type_subtree")}</label></div>@@ -49,21 +49,21 @@ const TPL = `<div class="form-check"><label class="form-check-label"><input class="form-check-input" type="radio" name="export-subtree-format" value="html">- ${t('export.format_html_zip')}+ ${t("export.format_html_zip")}</label></div><div class="form-check"><label class="form-check-label"><input class="form-check-input" type="radio" name="export-subtree-format" value="markdown">- ${t('export.format_markdown')}+ ${t("export.format_markdown")}</label></div><div class="form-check"><label class="form-check-label"><input class="form-check-input" type="radio" name="export-subtree-format" value="opml">- ${t('export.format_opml')}+ ${t("export.format_opml")}</label></div>@@ -71,14 +71,14 @@ const TPL = `<div class="form-check"><label class="form-check-label"><input class="form-check-input" type="radio" name="opml-version" value="1.0">- ${t('export.opml_version_1')}+ ${t("export.opml_version_1")}</label></div><div class="form-check"><label class="form-check-label"><input class="form-check-input" type="radio" name="opml-version" value="2.0">- ${t('export.opml_version_2')}+ ${t("export.opml_version_2")}</label></div></div>@@ -87,7 +87,7 @@ const TPL = `<div class="form-check"><label class="form-check-label"><input class="form-check-input" type="radio" name="export-type" value="single">- ${t('export.export_type_single')}+ ${t("export.export_type_single")}</label></div>@@ -95,20 +95,20 @@ const TPL = `<div class="form-check"><label class="form-check-label"><input class="form-check-input" type="radio" name="export-single-format" value="html">- ${t('export.format_html')}+ ${t("export.format_html")}</label></div><div class="form-check"><label class="form-check-label"><input class="form-check-input" type="radio" name="export-single-format" value="markdown">- ${t('export.format_markdown')}+ ${t("export.format_markdown")}</label></div></div></div><div class="modal-footer">- <button class="export-button btn btn-primary">${t('export.export')}</button>+ <button class="export-button btn btn-primary">${t("export.export")}</button></div></form></div>@@ -119,7 +119,7 @@ export default class ExportDialog extends BasicWidget {constructor() {super();- this.taskId = '';+ this.taskId = "";this.branchId = null;}@@ -135,39 +135,34 @@ export default class ExportDialog extends BasicWidget {this.$exportButton = this.$widget.find(".export-button");this.$opmlVersions = this.$widget.find(".opml-versions");- this.$form.on('submit', () => {+ this.$form.on("submit", () => {this.modal.hide();const exportType = this.$widget.find("input[name='export-type']:checked").val();if (!exportType) {- toastService.showError(t('export.choose_export_type'));+ toastService.showError(t("export.choose_export_type"));return;}- const exportFormat = exportType === 'subtree'- ? this.$widget.find("input[name=export-subtree-format]:checked").val()- : this.$widget.find("input[name=export-single-format]:checked").val();+ const exportFormat = exportType === "subtree" ? this.$widget.find("input[name=export-subtree-format]:checked").val() : this.$widget.find("input[name=export-single-format]:checked").val();- const exportVersion = exportFormat === 'opml'- ? this.$widget.find("input[name='opml-version']:checked").val()- : "1.0";+ const exportVersion = exportFormat === "opml" ? this.$widget.find("input[name='opml-version']:checked").val() : "1.0";this.exportBranch(this.branchId, exportType, exportFormat, exportVersion);return false;});- this.$widget.find('input[name=export-type]').on('change', e => {- if (e.currentTarget.value === 'subtree') {+ this.$widget.find("input[name=export-type]").on("change", (e) => {+ if (e.currentTarget.value === "subtree") {if (this.$widget.find("input[name=export-subtree-format]:checked").length === 0) {this.$widget.find("input[name=export-subtree-format]:first").prop("checked", true);}this.$subtreeFormats.slideDown();this.$singleFormats.slideUp();- }- else {+ } else {if (this.$widget.find("input[name=export-single-format]:checked").length === 0) {this.$widget.find("input[name=export-single-format]:first").prop("checked", true);}@@ -177,29 +172,26 @@ export default class ExportDialog extends BasicWidget {}});- this.$widget.find('input[name=export-subtree-format]').on('change', e => {- if (e.currentTarget.value === 'opml') {+ this.$widget.find("input[name=export-subtree-format]").on("change", (e) => {+ if (e.currentTarget.value === "opml") {this.$opmlVersions.slideDown();- }- else {+ } else {this.$opmlVersions.slideUp();}});}async showExportDialogEvent({ notePath, defaultType }) {- this.taskId = '';+ this.taskId = "";this.$exportButton.removeAttr("disabled");- if (defaultType === 'subtree') {- this.$subtreeType.prop("checked", true).trigger('change');+ if (defaultType === "subtree") {+ this.$subtreeType.prop("checked", true).trigger("change");- this.$widget.find("input[name=export-subtree-format]:checked").trigger('change');- }- else if (defaultType === 'single') {- this.$singleType.prop("checked", true).trigger('change');- }- else {+ this.$widget.find("input[name=export-subtree-format]:checked").trigger("change");+ } else if (defaultType === "single") {+ this.$singleType.prop("checked", true).trigger("change");+ } else {throw new Error(`Unrecognized type '${defaultType}'`);}@@ -222,27 +214,25 @@ export default class ExportDialog extends BasicWidget {}}-ws.subscribeToMessages(async message => {+ws.subscribeToMessages(async (message) => {const makeToast = (id, message) => ({id: id,- title: t('export.export_status'),+ title: t("export.export_status"),message: message,icon: "arrow-square-up-right"});- if (message.taskType !== 'export') {+ if (message.taskType !== "export") {return;}- if (message.type === 'taskError') {+ if (message.type === "taskError") {toastService.closePersistent(message.taskId);toastService.showError(message.message);- }- else if (message.type === 'taskProgressCount') {- toastService.showPersistent(makeToast(message.taskId, t('export.export_in_progress', { progressCount: message.progressCount })));- }- else if (message.type === 'taskSucceeded') {- const toast = makeToast(message.taskId, t('export.export_finished_successfully'));+ } else if (message.type === "taskProgressCount") {+ toastService.showPersistent(makeToast(message.taskId, t("export.export_in_progress", { progressCount: message.progressCount })));+ } else if (message.type === "taskSucceeded") {+ const toast = makeToast(message.taskId, t("export.export_finished_successfully"));toast.closeAfter = 5000;toastService.showPersistent(toast);diff --git a/src/public/app/widgets/dialogs/help.ts b/src/public/app/widgets/dialogs/help.tsindex 831f35d541..4d926eeb07 100644--- a/src/public/app/widgets/dialogs/help.ts+++ b/src/public/app/widgets/dialogs/help.ts@@ -7,25 +7,25 @@ const TPL = `<div class="modal-dialog" role="document" style="min-width: 90%;"><div class="modal-content" style="height: auto;"><div class="modal-header">- <h5 class="modal-title">${t('help.fullDocumentation')}</h5>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('help.close')}"></button>+ <h5 class="modal-title">${t("help.fullDocumentation")}</h5>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("help.close")}"></button></div><div class="modal-body" style="overflow: auto;"><div class="help-cards row row-cols-md-3 g-3"><div class="card"><div class="card-body">- <h5 class="card-title">${t('help.noteNavigation')}</h5>+ <h5 class="card-title">${t("help.noteNavigation")}</h5><p class="card-text"><ul>- <li>${t('help.goUpDown')}</li>- <li>${t('help.collapseExpand')}</li>- <li><kbd data-command="backInNoteHistory">${t('help.notSet')}</kbd>, <kbd data-command="forwardInNoteHistory">${t('help.notSet')}</kbd> - ${t('help.goBackForwards')}</li>- <li><kbd data-command="jumpToNote">${t('help.notSet')}</kbd> - ${t('help.showJumpToNoteDialog')}</li>- <li><kbd data-command="scrollToActiveNote">${t('help.notSet')}</kbd> - ${t('help.scrollToActiveNote')}</li>- <li>${t('help.jumpToParentNote')}</li>- <li><kbd data-command="collapseTree">${t('help.notSet')}</kbd> - ${t('help.collapseWholeTree')}</li>- <li><kbd data-command="collapseSubtree">${t('help.notSet')}</kbd> - ${t('help.collapseSubTree')}</li>+ <li>${t("help.goUpDown")}</li>+ <li>${t("help.collapseExpand")}</li>+ <li><kbd data-command="backInNoteHistory">${t("help.notSet")}</kbd>, <kbd data-command="forwardInNoteHistory">${t("help.notSet")}</kbd> - ${t("help.goBackForwards")}</li>+ <li><kbd data-command="jumpToNote">${t("help.notSet")}</kbd> - ${t("help.showJumpToNoteDialog")}</li>+ <li><kbd data-command="scrollToActiveNote">${t("help.notSet")}</kbd> - ${t("help.scrollToActiveNote")}</li>+ <li>${t("help.jumpToParentNote")}</li>+ <li><kbd data-command="collapseTree">${t("help.notSet")}</kbd> - ${t("help.collapseWholeTree")}</li>+ <li><kbd data-command="collapseSubtree">${t("help.notSet")}</kbd> - ${t("help.collapseSubTree")}</li></ul></p></div>@@ -33,18 +33,18 @@ const TPL = `<div class="card"><div class="card-body">- <h5 class="card-title">${t('help.tabShortcuts')}</h5>+ <h5 class="card-title">${t("help.tabShortcuts")}</h5><p class="card-text"><ul>- <li>${t('help.newTabNoteLink')}</li>+ <li>${t("help.newTabNoteLink")}</li></ul>- <h6>${t('help.onlyInDesktop')}:</h6>+ <h6>${t("help.onlyInDesktop")}:</h6><ul>- <li><kbd data-command="openNewTab">${t('help.notSet')}</kbd> ${t('help.openEmptyTab')}</li>- <li><kbd data-command="closeActiveTab">${t('help.notSet')}</kbd> ${t('help.closeActiveTab')}</li>- <li><kbd data-command="activateNextTab">${t('help.notSet')}</kbd> ${t('help.activateNextTab')}</li>- <li><kbd data-command="activatePreviousTab">${t('help.notSet')}</kbd> ${t('help.activatePreviousTab')}</li>+ <li><kbd data-command="openNewTab">${t("help.notSet")}</kbd> ${t("help.openEmptyTab")}</li>+ <li><kbd data-command="closeActiveTab">${t("help.notSet")}</kbd> ${t("help.closeActiveTab")}</li>+ <li><kbd data-command="activateNextTab">${t("help.notSet")}</kbd> ${t("help.activateNextTab")}</li>+ <li><kbd data-command="activatePreviousTab">${t("help.notSet")}</kbd> ${t("help.activatePreviousTab")}</li></ul></p></div>@@ -52,13 +52,13 @@ const TPL = `<div class="card"><div class="card-body">- <h5 class="card-title">${t('help.creatingNotes')}</h5>+ <h5 class="card-title">${t("help.creatingNotes")}</h5><p class="card-text"><ul>- <li><kbd data-command="createNoteAfter">${t('help.notSet')}</kbd> - ${t('help.createNoteAfter')}</li>- <li><kbd data-command="createNoteInto">${t('help.notSet')}</kbd> - ${t('help.createNoteInto')}</li>- <li><kbd data-command="editBranchPrefix">${t('help.notSet')}</kbd> - ${t('help.editBranchPrefix')}</li>+ <li><kbd data-command="createNoteAfter">${t("help.notSet")}</kbd> - ${t("help.createNoteAfter")}</li>+ <li><kbd data-command="createNoteInto">${t("help.notSet")}</kbd> - ${t("help.createNoteInto")}</li>+ <li><kbd data-command="editBranchPrefix">${t("help.notSet")}</kbd> - ${t("help.editBranchPrefix")}</li></ul></p></div>@@ -66,19 +66,19 @@ const TPL = `<div class="card"><div class="card-body">- <h5 class="card-title">${t('help.movingCloningNotes')}</h5>+ <h5 class="card-title">${t("help.movingCloningNotes")}</h5><p class="card-text"><ul>- <li><kbd data-command="moveNoteUp">${t('help.notSet')}</kbd>, <kbd data-command="moveNoteDown">${t('help.notSet')}</kbd> - ${t('help.moveNoteUpDown')}</li>- <li><kbd data-command="moveNoteUpInHierarchy">${t('help.notSet')}</kbd>, <kbd data-command="moveNoteDownInHierarchy">${t('help.notSet')}</kbd> - ${t('help.moveNoteUpHierarchy')}</li>- <li><kbd data-command="addNoteAboveToSelection">${t('help.notSet')}</kbd>, <kbd data-command="addNoteBelowToSelection">${t('help.notSet')}</kbd> - ${t('help.multiSelectNote')}</li>- <li><kbd data-command="selectAllNotesInParent">${t('help.notSet')}</kbd> - ${t('help.selectAllNotes')}</li>- <li>${t('help.selectNote')}</li>- <li><kbd data-command="copyNotesToClipboard">${t('help.notSet')}</kbd> - ${t('help.copyNotes')}</li>- <li><kbd data-command="cutNotesToClipboard">${t('help.notSet')}</kbd> - ${t('help.cutNotes')}</li>- <li><kbd data-command="pasteNotesFromClipboard">${t('help.notSet')}</kbd> - ${t('help.pasteNotes')}</li>- <li><kbd data-command="deleteNotes">${t('help.notSet')}</kbd> - ${t('help.deleteNotes')}</li>+ <li><kbd data-command="moveNoteUp">${t("help.notSet")}</kbd>, <kbd data-command="moveNoteDown">${t("help.notSet")}</kbd> - ${t("help.moveNoteUpDown")}</li>+ <li><kbd data-command="moveNoteUpInHierarchy">${t("help.notSet")}</kbd>, <kbd data-command="moveNoteDownInHierarchy">${t("help.notSet")}</kbd> - ${t("help.moveNoteUpHierarchy")}</li>+ <li><kbd data-command="addNoteAboveToSelection">${t("help.notSet")}</kbd>, <kbd data-command="addNoteBelowToSelection">${t("help.notSet")}</kbd> - ${t("help.multiSelectNote")}</li>+ <li><kbd data-command="selectAllNotesInParent">${t("help.notSet")}</kbd> - ${t("help.selectAllNotes")}</li>+ <li>${t("help.selectNote")}</li>+ <li><kbd data-command="copyNotesToClipboard">${t("help.notSet")}</kbd> - ${t("help.copyNotes")}</li>+ <li><kbd data-command="cutNotesToClipboard">${t("help.notSet")}</kbd> - ${t("help.cutNotes")}</li>+ <li><kbd data-command="pasteNotesFromClipboard">${t("help.notSet")}</kbd> - ${t("help.pasteNotes")}</li>+ <li><kbd data-command="deleteNotes">${t("help.notSet")}</kbd> - ${t("help.deleteNotes")}</li></ul></p></div>@@ -86,16 +86,16 @@ const TPL = `<div class="card"><div class="card-body">- <h5 class="card-title">${t('help.editingNotes')}</h5>+ <h5 class="card-title">${t("help.editingNotes")}</h5><p class="card-text"><ul>- <li><kbd data-command="editNoteTitle">${t('help.notSet')}</kbd> ${t('help.editNoteTitle')}</li>- <li>${t('help.createEditLink')}</li>- <li><kbd data-command="addLinkToText">${t('help.notSet')}</kbd> - ${t('help.createInternalLink')}</li>- <li><kbd data-command="followLinkUnderCursor">${t('help.notSet')}</kbd> - ${t('help.followLink')}</li>- <li><kbd data-command="insertDateTimeToText">${t('help.notSet')}</kbd> - ${t('help.insertDateTime')}</li>- <li><kbd data-command="scrollToActiveNote">${t('help.notSet')}</kbd> - ${t('help.jumpToTreePane')}</li>+ <li><kbd data-command="editNoteTitle">${t("help.notSet")}</kbd> ${t("help.editNoteTitle")}</li>+ <li>${t("help.createEditLink")}</li>+ <li><kbd data-command="addLinkToText">${t("help.notSet")}</kbd> - ${t("help.createInternalLink")}</li>+ <li><kbd data-command="followLinkUnderCursor">${t("help.notSet")}</kbd> - ${t("help.followLink")}</li>+ <li><kbd data-command="insertDateTimeToText">${t("help.notSet")}</kbd> - ${t("help.insertDateTime")}</li>+ <li><kbd data-command="scrollToActiveNote">${t("help.notSet")}</kbd> - ${t("help.jumpToTreePane")}</li></ul></p></div>@@ -103,14 +103,14 @@ const TPL = `<div class="card"><div class="card-body">- <h5 class="card-title"><a class="external" href="https://triliumnext.github.io/Docs/Wiki/text-notes.html#markdown--autoformat">${t('help.markdownAutoformat')}</a></h5>+ <h5 class="card-title"><a class="external" href="https://triliumnext.github.io/Docs/Wiki/text-notes.html#markdown--autoformat">${t("help.markdownAutoformat")}</a></h5><p class="card-text"><ul>- <li>${t('help.headings')}</li>- <li>${t('help.bulletList')}</li>- <li>${t('help.numberedList')}</li>- <li>${t('help.blockQuote')}</li>+ <li>${t("help.headings")}</li>+ <li>${t("help.bulletList")}</li>+ <li>${t("help.numberedList")}</li>+ <li>${t("help.blockQuote")}</li></ul></p></div>@@ -118,13 +118,13 @@ const TPL = `<div class="card"><div class="card-body">- <h5 class="card-title">${t('help.troubleshooting')}</h5>+ <h5 class="card-title">${t("help.troubleshooting")}</h5><p class="card-text"><ul>- <li><kbd data-command="reloadFrontendApp">${t('help.notSet')}</kbd> - ${t('help.reloadFrontend')}</li>- <li><kbd data-command="openDevTools">${t('help.notSet')}</kbd> - ${t('help.showDevTools')}</li>- <li><kbd data-command="showSQLConsole">${t('help.notSet')}</kbd> - ${t('help.showSQLConsole')}</li>+ <li><kbd data-command="reloadFrontendApp">${t("help.notSet")}</kbd> - ${t("help.reloadFrontend")}</li>+ <li><kbd data-command="openDevTools">${t("help.notSet")}</kbd> - ${t("help.showDevTools")}</li>+ <li><kbd data-command="showSQLConsole">${t("help.notSet")}</kbd> - ${t("help.showSQLConsole")}</li></ul></p></div>@@ -132,12 +132,12 @@ const TPL = `<div class="card"><div class="card-body">- <h5 class="card-title">${t('help.other')}</h5>+ <h5 class="card-title">${t("help.other")}</h5><p class="card-text"><ul>- <li><kbd data-command="quickSearch">${t('help.notSet')}</kbd> - ${t('help.quickSearch')}</li>- <li><kbd data-command="findInText">${t('help.notSet')}</kbd> - ${t('help.inPageSearch')}</li>+ <li><kbd data-command="quickSearch">${t("help.notSet")}</kbd> - ${t("help.quickSearch")}</li>+ <li><kbd data-command="findInText">${t("help.notSet")}</kbd> - ${t("help.inPageSearch")}</li></ul></p></div>diff --git a/src/public/app/widgets/dialogs/import.js b/src/public/app/widgets/dialogs/import.jsindex c2059eb98c..cf09fff2d9 100644--- a/src/public/app/widgets/dialogs/import.js+++ b/src/public/app/widgets/dialogs/import.js@@ -1,4 +1,4 @@-import utils from '../../services/utils.js';+import utils from "../../services/utils.js";import treeService from "../../services/tree.js";import importService from "../../services/import.js";import options from "../../services/options.js";@@ -10,65 +10,65 @@ const TPL = `<div class="modal-dialog modal-lg" role="document"><div class="modal-content"><div class="modal-header">- <h5 class="modal-title">${t('import.importIntoNote')}</h5>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('import.close')}"></button>+ <h5 class="modal-title">${t("import.importIntoNote")}</h5>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("import.close")}"></button></div><form class="import-form"><div class="modal-body"><div class="form-group">- <label for="import-file-upload-input"><strong>${t('import.chooseImportFile')}</strong></label>+ <label for="import-file-upload-input"><strong>${t("import.chooseImportFile")}</strong></label><input type="file" class="import-file-upload-input form-control-file" multiple />- <p>${t('import.importDescription')} <strong class="import-note-title"></strong>.+ <p>${t("import.importDescription")} <strong class="import-note-title"></strong>.</div><div class="form-group">- <strong>${t('import.options')}:</strong>+ <strong>${t("import.options")}:</strong><div class="checkbox">- <label data-bs-toggle="tooltip" title="${t('import.safeImportTooltip')}">+ <label data-bs-toggle="tooltip" title="${t("import.safeImportTooltip")}"><input class="safe-import-checkbox" value="1" type="checkbox" checked>- <span>${t('import.safeImport')}</span>+ <span>${t("import.safeImport")}</span></label></div><div class="checkbox">- <label data-bs-toggle="tooltip" title="${t('import.explodeArchivesTooltip')}">+ <label data-bs-toggle="tooltip" title="${t("import.explodeArchivesTooltip")}"><input class="explode-archives-checkbox" value="1" type="checkbox" checked>- <span>${t('import.explodeArchives')}</span>+ <span>${t("import.explodeArchives")}</span></label></div><div class="checkbox">- <label data-bs-toggle="tooltip" title="${t('import.shrinkImagesTooltip')}">- <input class="shrink-images-checkbox" value="1" type="checkbox" checked> <span>${t('import.shrinkImages')}</span>+ <label data-bs-toggle="tooltip" title="${t("import.shrinkImagesTooltip")}">+ <input class="shrink-images-checkbox" value="1" type="checkbox" checked> <span>${t("import.shrinkImages")}</span></label></div><div class="checkbox"><label><input class="text-imported-as-text-checkbox" value="1" type="checkbox" checked>- ${t('import.textImportedAsText')}+ ${t("import.textImportedAsText")}</label></div><div class="checkbox"><label>- <input class="code-imported-as-code-checkbox" value="1" type="checkbox" checked> ${t('import.codeImportedAsCode')}+ <input class="code-imported-as-code-checkbox" value="1" type="checkbox" checked> ${t("import.codeImportedAsCode")}</label></div><div class="checkbox"><label><input class="replace-underscores-with-spaces-checkbox" value="1" type="checkbox" checked>- ${t('import.replaceUnderscoresWithSpaces')}+ ${t("import.replaceUnderscoresWithSpaces")}</label></div></div></div><div class="modal-footer">- <button class="import-button btn btn-primary">${t('import.import')}</button>+ <button class="import-button btn btn-primary">${t("import.import")}</button></div></form></div>@@ -97,7 +97,7 @@ export default class ImportDialog extends BasicWidget {this.$explodeArchivesCheckbox = this.$widget.find(".explode-archives-checkbox");this.$replaceUnderscoresWithSpacesCheckbox = this.$widget.find(".replace-underscores-with-spaces-checkbox");- this.$form.on('submit', () => {+ this.$form.on("submit", () => {// disabling so that import is not triggered again.this.$importButton.attr("disabled", "disabled");@@ -106,16 +106,15 @@ export default class ImportDialog extends BasicWidget {return false;});- this.$fileUploadInput.on('change', () => {+ this.$fileUploadInput.on("change", () => {if (this.$fileUploadInput.val()) {this.$importButton.removeAttr("disabled");- }- else {+ } else {this.$importButton.attr("disabled", "disabled");}});- let _ = [...this.$widget.find('[data-bs-toggle="tooltip"]')].forEach(element => {+ let _ = [...this.$widget.find('[data-bs-toggle="tooltip"]')].forEach((element) => {bootstrap.Tooltip.getOrCreateInstance(element, {html: true});@@ -125,10 +124,10 @@ export default class ImportDialog extends BasicWidget {async showImportDialogEvent({ noteId }) {this.parentNoteId = noteId;- this.$fileUploadInput.val('').trigger('change'); // to trigger Import button disabling listener below+ this.$fileUploadInput.val("").trigger("change"); // to trigger Import button disabling listener belowthis.$safeImportCheckbox.prop("checked", true);- this.$shrinkImagesCheckbox.prop("checked", options.is('compressImages'));+ this.$shrinkImagesCheckbox.prop("checked", options.is("compressImages"));this.$textImportedAsTextCheckbox.prop("checked", true);this.$codeImportedAsCodeCheckbox.prop("checked", true);this.$explodeArchivesCheckbox.prop("checked", true);@@ -142,7 +141,7 @@ export default class ImportDialog extends BasicWidget {async importIntoNote(parentNoteId) {const files = Array.from(this.$fileUploadInput[0].files); // shallow copy since we're resetting the upload button below- const boolToString = $el => $el.is(":checked") ? "true" : "false";+ const boolToString = ($el) => ($el.is(":checked") ? "true" : "false");const options = {safeImport: boolToString(this.$safeImportCheckbox),@@ -153,8 +152,8 @@ export default class ImportDialog extends BasicWidget {replaceUnderscoresWithSpaces: boolToString(this.$replaceUnderscoresWithSpacesCheckbox)};- this.$widget.modal('hide');+ this.$widget.modal("hide");- await importService.uploadFiles('notes', parentNoteId, files, options);+ await importService.uploadFiles("notes", parentNoteId, files, options);}}diff --git a/src/public/app/widgets/dialogs/include_note.js b/src/public/app/widgets/dialogs/include_note.jsindex 192795ccf0..5778306eb9 100644--- a/src/public/app/widgets/dialogs/include_note.js+++ b/src/public/app/widgets/dialogs/include_note.js@@ -1,6 +1,6 @@import { t } from "../../services/i18n.js";-import treeService from '../../services/tree.js';-import noteAutocompleteService from '../../services/note_autocomplete.js';+import treeService from "../../services/tree.js";+import noteAutocompleteService from "../../services/note_autocomplete.js";import utils from "../../services/utils.js";import froca from "../../services/froca.js";import BasicWidget from "../basic_widget.js";@@ -10,35 +10,35 @@ const TPL = `<div class="modal-dialog modal-lg" role="document"><div class="modal-content"><div class="modal-header">- <h5 class="modal-title">${t('include_note.dialog_title')}</h5>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('include_note.close')}"></button>+ <h5 class="modal-title">${t("include_note.dialog_title")}</h5>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("include_note.close")}"></button></div><form class="include-note-form"><div class="modal-body"><div class="form-group">- <label for="include-note-autocomplete">${t('include_note.label_note')}</label>+ <label for="include-note-autocomplete">${t("include_note.label_note")}</label><div class="input-group">- <input class="include-note-autocomplete form-control" placeholder="${t('include_note.placeholder_search')}">+ <input class="include-note-autocomplete form-control" placeholder="${t("include_note.placeholder_search")}"></div></div>- ${t('include_note.box_size_prompt')}+ ${t("include_note.box_size_prompt")}<div class="form-check"><input class="form-check-input" type="radio" name="include-note-box-size" value="small">- <label class="form-check-label">${t('include_note.box_size_small')}</label>+ <label class="form-check-label">${t("include_note.box_size_small")}</label></div><div class="form-check"><input class="form-check-input" type="radio" name="include-note-box-size" value="medium" checked>- <label class="form-check-label">${t('include_note.box_size_medium')}</label>+ <label class="form-check-label">${t("include_note.box_size_medium")}</label></div><div class="form-check"><input class="form-check-input" type="radio" name="include-note-box-size" value="full">- <label class="form-check-label">${t('include_note.box_size_full')}</label>+ <label class="form-check-label">${t("include_note.box_size_full")}</label></div></div><div class="modal-footer">- <button type="submit" class="btn btn-primary">${t('include_note.button_include')}</button>+ <button type="submit" class="btn btn-primary">${t("include_note.button_include")}</button></div></form></div>@@ -51,7 +51,7 @@ export default class IncludeNoteDialog extends BasicWidget {this.modal = bootstrap.Modal.getOrCreateInstance(this.$widget);this.$form = this.$widget.find(".include-note-form");this.$autoComplete = this.$widget.find(".include-note-autocomplete");- this.$form.on('submit', () => {+ this.$form.on("submit", () => {const notePath = this.$autoComplete.getSelectedNotePath();if (notePath) {@@ -62,7 +62,7 @@ export default class IncludeNoteDialog extends BasicWidget {}return false;- })+ });}async showIncludeNoteDialogEvent({ textTypeWidget }) {@@ -70,13 +70,11 @@ export default class IncludeNoteDialog extends BasicWidget {await this.refresh();utils.openDialog(this.$widget);- this.$autoComplete- .trigger('focus')- .trigger('select'); // to be able to quickly remove entered text+ this.$autoComplete.trigger("focus").trigger("select"); // to be able to quickly remove entered text}async refresh(widget) {- this.$autoComplete.val('');+ this.$autoComplete.val("");noteAutocompleteService.initNoteAutocomplete(this.$autoComplete, {hideGoToSelectedNoteButton: true,allowCreatingNotes: true@@ -89,7 +87,7 @@ export default class IncludeNoteDialog extends BasicWidget {const note = await froca.getNote(noteId);const boxSize = $("input[name='include-note-box-size']:checked").val();- if (['image', 'canvas', 'mermaid'].includes(note.type)) {+ if (["image", "canvas", "mermaid"].includes(note.type)) {// there's no benefit to use insert note functionlity for images,// so we'll just add an IMG tagthis.textTypeWidget.addImage(noteId);diff --git a/src/public/app/widgets/dialogs/info.js b/src/public/app/widgets/dialogs/info.jsindex fce06510e2..655bc4bca9 100644--- a/src/public/app/widgets/dialogs/info.js+++ b/src/public/app/widgets/dialogs/info.js@@ -34,7 +34,7 @@ export default class InfoDialog extends BasicWidget {this.$infoContent = this.$widget.find(".info-dialog-content");this.$okButton = this.$widget.find(".info-dialog-ok-button");- this.$widget.on('shown.bs.modal', () => this.$okButton.trigger("focus"));+ this.$widget.on("shown.bs.modal", () => this.$okButton.trigger("focus"));this.$widget.on("hidden.bs.modal", () => {if (this.resolve) {@@ -42,16 +42,16 @@ export default class InfoDialog extends BasicWidget {}if (this.$originallyFocused) {- this.$originallyFocused.trigger('focus');+ this.$originallyFocused.trigger("focus");this.$originallyFocused = null;}});- this.$okButton.on('click', () => this.modal.hide());+ this.$okButton.on("click", () => this.modal.hide());}showInfoDialogEvent({ message, callback }) {- this.$originallyFocused = $(':focus');+ this.$originallyFocused = $(":focus");this.$infoContent.text(message);diff --git a/src/public/app/widgets/dialogs/jump_to_note.js b/src/public/app/widgets/dialogs/jump_to_note.jsindex 82e7337e07..4b2aceb51c 100644--- a/src/public/app/widgets/dialogs/jump_to_note.js+++ b/src/public/app/widgets/dialogs/jump_to_note.js@@ -1,5 +1,5 @@import { t } from "../../services/i18n.js";-import noteAutocompleteService from '../../services/note_autocomplete.js';+import noteAutocompleteService from "../../services/note_autocomplete.js";import utils from "../../services/utils.js";import appContext from "../../components/app_context.js";import BasicWidget from "../basic_widget.js";@@ -10,15 +10,15 @@ const TPL = `<div class="jump-to-note-dialog modal mx-auto" tabindex="-1" role="<div class="modal-content"><div class="modal-header"><div class="input-group">- <input class="jump-to-note-autocomplete form-control" placeholder="${t('jump_to_note.search_placeholder')}">+ <input class="jump-to-note-autocomplete form-control" placeholder="${t("jump_to_note.search_placeholder")}"></div>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('jump_to_note.close')}"></button>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("jump_to_note.close")}"></button></div><div class="modal-body"><div class="algolia-autocomplete-container jump-to-note-results"></div></div><div class="modal-footer">- <button class="show-in-full-text-button btn btn-sm">${t('jump_to_note.search_button')}</button>+ <button class="show-in-full-text-button btn btn-sm">${t("jump_to_note.search_button")}</button></div></div></div>@@ -40,13 +40,13 @@ export default class JumpToNoteDialog extends BasicWidget {this.$autoComplete = this.$widget.find(".jump-to-note-autocomplete");this.$results = this.$widget.find(".jump-to-note-results");this.$showInFullTextButton = this.$widget.find(".show-in-full-text-button");- this.$showInFullTextButton.on('click', e => this.showInFullText(e));+ this.$showInFullTextButton.on("click", (e) => this.showInFullText(e));- shortcutService.bindElShortcut(this.$widget, 'ctrl+return', e => this.showInFullText(e));+ shortcutService.bindElShortcut(this.$widget, "ctrl+return", (e) => this.showInFullText(e));}async jumpToNoteEvent() {- const dialogPromise = utils.openDialog(this.$widget)+ const dialogPromise = utils.openDialog(this.$widget);if (utils.isMobile()) {dialogPromise.then(($dialog) => {const el = $dialog.find(">.modal-dialog")[0];@@ -78,15 +78,16 @@ export default class JumpToNoteDialog extends BasicWidget {}async refresh() {- noteAutocompleteService.initNoteAutocomplete(this.$autoComplete, {- allowCreatingNotes: true,- hideGoToSelectedNoteButton: true,- allowJumpToSearchNotes: true,- container: this.$results- })+ noteAutocompleteService+ .initNoteAutocomplete(this.$autoComplete, {+ allowCreatingNotes: true,+ hideGoToSelectedNoteButton: true,+ allowJumpToSearchNotes: true,+ container: this.$results+ })// clear any event listener added in previous invocation of this function- .off('autocomplete:noteselected')- .on('autocomplete:noteselected', function (event, suggestion, dataset) {+ .off("autocomplete:noteselected")+ .on("autocomplete:noteselected", function (event, suggestion, dataset) {if (!suggestion.notePath) {return false;}@@ -105,8 +106,8 @@ export default class JumpToNoteDialog extends BasicWidget {// hack, the actual search value is stored in <pre> element next to the search input// this is important because the search input value is replaced with the suggestion note's title.autocomplete("val", this.$autoComplete.next().text())- .trigger('focus')- .trigger('select');+ .trigger("focus")+ .trigger("select");}}@@ -117,7 +118,7 @@ export default class JumpToNoteDialog extends BasicWidget {const searchString = this.$autoComplete.val();- this.triggerCommand('searchNotes', { searchString });+ this.triggerCommand("searchNotes", { searchString });this.modal.hide();}diff --git a/src/public/app/widgets/dialogs/markdown_import.js b/src/public/app/widgets/dialogs/markdown_import.jsindex 720155b268..26cdd20cd4 100644--- a/src/public/app/widgets/dialogs/markdown_import.js+++ b/src/public/app/widgets/dialogs/markdown_import.js@@ -36,18 +36,18 @@ export default class MarkdownImportDialog extends BasicWidget {doRender() {this.$widget = $(TPL);this.modal = bootstrap.Modal.getOrCreateInstance(this.$widget);- this.$importTextarea = this.$widget.find('.markdown-import-textarea');- this.$importButton = this.$widget.find('.markdown-import-button');+ this.$importTextarea = this.$widget.find(".markdown-import-textarea");+ this.$importButton = this.$widget.find(".markdown-import-button");- this.$importButton.on('click', () => this.sendForm());+ this.$importButton.on("click", () => this.sendForm());- this.$widget.on('shown.bs.modal', () => this.$importTextarea.trigger('focus'));+ this.$widget.on("shown.bs.modal", () => this.$importTextarea.trigger("focus"));- shortcutService.bindElShortcut(this.$widget, 'ctrl+return', () => this.sendForm());+ shortcutService.bindElShortcut(this.$widget, "ctrl+return", () => this.sendForm());}async convertMarkdownToHtml(markdownContent) {- const { htmlContent } = await server.post('other/render-markdown', { markdownContent });+ const { htmlContent } = await server.post("other/render-markdown", { markdownContent });const textEditor = await appContext.tabManager.getActiveContext().getTextEditor();@@ -64,17 +64,16 @@ export default class MarkdownImportDialog extends BasicWidget {}async importMarkdownInlineEvent() {- if (appContext.tabManager.getActiveContextNoteType() !== 'text') {+ if (appContext.tabManager.getActiveContextNoteType() !== "text") {return;}if (utils.isElectron()) {- const { clipboard } = utils.dynamicRequire('electron');+ const { clipboard } = utils.dynamicRequire("electron");const text = clipboard.readText();this.convertMarkdownToHtml(text);- }- else {+ } else {utils.openDialog(this.$widget);}}@@ -86,6 +85,6 @@ export default class MarkdownImportDialog extends BasicWidget {await this.convertMarkdownToHtml(text);- this.$importTextarea.val('');+ this.$importTextarea.val("");}}diff --git a/src/public/app/widgets/dialogs/move_to.js b/src/public/app/widgets/dialogs/move_to.jsindex 4d28b99fbe..061af25dbb 100644--- a/src/public/app/widgets/dialogs/move_to.js+++ b/src/public/app/widgets/dialogs/move_to.js@@ -51,16 +51,15 @@ export default class MoveToDialog extends BasicWidget {this.$noteAutoComplete = this.$widget.find(".move-to-note-autocomplete");this.$noteList = this.$widget.find(".move-to-note-list");- this.$form.on('submit', () => {+ this.$form.on("submit", () => {const notePath = this.$noteAutoComplete.getSelectedNotePath();if (notePath) {- this.$widget.modal('hide');+ this.$widget.modal("hide");- const {noteId, parentNoteId} = treeService.getNoteIdAndParentIdFromUrl(notePath);- froca.getBranchId(parentNoteId, noteId).then(branchId => this.moveNotesTo(branchId));- }- else {+ const { noteId, parentNoteId } = treeService.getNoteIdAndParentIdFromUrl(notePath);+ froca.getBranchId(parentNoteId, noteId).then((branchId) => this.moveNotesTo(branchId));+ } else {logError(t("move_to.error_no_path"));}@@ -68,12 +67,12 @@ export default class MoveToDialog extends BasicWidget {});}- async moveBranchIdsToEvent({branchIds}) {+ async moveBranchIdsToEvent({ branchIds }) {this.movedBranchIds = branchIds;utils.openDialog(this.$widget);- this.$noteAutoComplete.val('').trigger('focus');+ this.$noteAutoComplete.val("").trigger("focus");this.$noteList.empty();diff --git a/src/public/app/widgets/dialogs/note_type_chooser.ts b/src/public/app/widgets/dialogs/note_type_chooser.tsindex d2b855cc65..21178433ab 100644--- a/src/public/app/widgets/dialogs/note_type_chooser.ts+++ b/src/public/app/widgets/dialogs/note_type_chooser.ts@@ -52,7 +52,6 @@ export interface ChooseNoteTypeResponse {type Callback = (data: ChooseNoteTypeResponse) => void;export default class NoteTypeChooserDialog extends BasicWidget {-private resolve: Callback | null;private dropdown!: bootstrap.Dropdown;private modal!: JQuery<HTMLElement>;@@ -85,30 +84,30 @@ export default class NoteTypeChooserDialog extends BasicWidget {}if (this.$originalFocused) {- this.$originalFocused.trigger('focus');+ this.$originalFocused.trigger("focus");this.$originalFocused = null;}glob.activeDialog = this.$originalDialog;});- this.$noteTypeDropdown.on('click', '.dropdown-item', e => this.doResolve(e));+ this.$noteTypeDropdown.on("click", ".dropdown-item", (e) => this.doResolve(e));- this.$noteTypeDropdown.on('focus', '.dropdown-item', e => {- this.$noteTypeDropdown.find('.dropdown-item').each((i, el) => {- $(el).toggleClass('active', el === e.target);+ this.$noteTypeDropdown.on("focus", ".dropdown-item", (e) => {+ this.$noteTypeDropdown.find(".dropdown-item").each((i, el) => {+ $(el).toggleClass("active", el === e.target);});});- this.$noteTypeDropdown.on('keydown', '.dropdown-item', e => {- if (e.key === 'Enter') {+ this.$noteTypeDropdown.on("keydown", ".dropdown-item", (e) => {+ if (e.key === "Enter") {this.doResolve(e);e.preventDefault();return false;}});- this.$noteTypeDropdown.parent().on('hide.bs.dropdown', e => {+ this.$noteTypeDropdown.parent().on("hide.bs.dropdown", (e) => {// prevent closing dropdown by clicking outside// TODO: Check if this actually works.//@ts-ignore@@ -119,17 +118,17 @@ export default class NoteTypeChooserDialog extends BasicWidget {}async chooseNoteTypeEvent({ callback }: { callback: Callback }) {- this.$originalFocused = $(':focus');+ this.$originalFocused = $(":focus");const noteTypes = await noteTypesService.getNoteTypeItems();this.$noteTypeDropdown.empty();for (const noteType of noteTypes) {- if (noteType.title === '----') {+ if (noteType.title === "----") {this.$noteTypeDropdown.append($('<h6 class="dropdown-header">').append(t("note_type_chooser.templates")));} else {- const commandItem = (noteType as MenuCommandItem<CommandNames>)+ const commandItem = noteType as MenuCommandItem<CommandNames>;this.$noteTypeDropdown.append($('<a class="dropdown-item" tabindex="0">').attr("data-note-type", commandItem.type || "")diff --git a/src/public/app/widgets/dialogs/password_not_set.js b/src/public/app/widgets/dialogs/password_not_set.jsindex 0d00dba187..b8816f370f 100644--- a/src/public/app/widgets/dialogs/password_not_set.js+++ b/src/public/app/widgets/dialogs/password_not_set.js@@ -27,7 +27,7 @@ export default class PasswordNoteSetDialog extends BasicWidget {this.$openPasswordOptionsButton = this.$widget.find(".open-password-options-button");this.$openPasswordOptionsButton.on("click", () => {this.modal.hide();- this.triggerCommand("showOptions", { section: '_optionsPassword' });+ this.triggerCommand("showOptions", { section: "_optionsPassword" });});}diff --git a/src/public/app/widgets/dialogs/prompt.ts b/src/public/app/widgets/dialogs/prompt.tsindex 7bdc239566..67ea509535 100644--- a/src/public/app/widgets/dialogs/prompt.ts+++ b/src/public/app/widgets/dialogs/prompt.ts@@ -9,7 +9,7 @@ const TPL = `<form class="prompt-dialog-form"><div class="modal-header"><h5 class="prompt-title modal-title">${t("prompt.title")}</h5>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('prompt.close')}"></button>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("prompt.close")}"></button></div><div class="modal-body"></div><div class="modal-footer">@@ -38,10 +38,9 @@ export interface PromptDialogOptions {export type PromptShownDialogCallback = ((callback: ShownCallbackData) => void) | null;export default class PromptDialog extends BasicWidget {-private resolve: ((val: string | null) => void) | null;private shownCb: PromptShownDialogCallback;-+private modal!: bootstrap.Modal;private $dialogBody!: JQuery<HTMLElement>;private $question!: JQuery<HTMLElement> | null;@@ -65,7 +64,7 @@ export default class PromptDialog extends BasicWidget {this.$question = null;this.$answer = null;- this.$widget.on('shown.bs.modal', () => {+ this.$widget.on("shown.bs.modal", () => {if (this.shownCb) {this.shownCb({$dialog: this.$widget,@@ -75,7 +74,7 @@ export default class PromptDialog extends BasicWidget {});}- this.$answer?.trigger('focus').select();+ this.$answer?.trigger("focus").select();});this.$widget.on("hidden.bs.modal", () => {@@ -84,7 +83,7 @@ export default class PromptDialog extends BasicWidget {}});- this.$form.on('submit', e => {+ this.$form.on("submit", (e) => {e.preventDefault();if (this.resolve) {this.resolve(this.$answer?.val() as string);@@ -110,11 +109,7 @@ export default class PromptDialog extends BasicWidget {.addClass("form-control").val(defaultValue || "");- this.$dialogBody.empty().append(- $("<div>")- .addClass("form-group")- .append(this.$question)- .append(this.$answer));+ this.$dialogBody.empty().append($("<div>").addClass("form-group").append(this.$question).append(this.$answer));utils.openDialog(this.$widget, false);}diff --git a/src/public/app/widgets/dialogs/protected_session_password.js b/src/public/app/widgets/dialogs/protected_session_password.jsindex 6d730d6599..8aabd17963 100644--- a/src/public/app/widgets/dialogs/protected_session_password.js+++ b/src/public/app/widgets/dialogs/protected_session_password.js@@ -32,7 +32,7 @@ export default class ProtectedSessionPasswordDialog extends BasicWidget {this.$passwordForm = this.$widget.find(".protected-session-password-form");this.$passwordInput = this.$widget.find(".protected-session-password");- this.$passwordForm.on('submit', () => {+ this.$passwordForm.on("submit", () => {const password = this.$passwordInput.val();this.$passwordInput.val("");@@ -45,7 +45,7 @@ export default class ProtectedSessionPasswordDialog extends BasicWidget {showProtectedSessionPasswordDialogEvent() {utils.openDialog(this.$widget);- this.$passwordInput.trigger('focus');+ this.$passwordInput.trigger("focus");}closeProtectedSessionPasswordDialogEvent() {diff --git a/src/public/app/widgets/dialogs/recent_changes.js b/src/public/app/widgets/dialogs/recent_changes.jsindex 4198b57868..49a03b74ab 100644--- a/src/public/app/widgets/dialogs/recent_changes.js+++ b/src/public/app/widgets/dialogs/recent_changes.js@@ -1,14 +1,14 @@-import { formatDateTime } from "../../utils/formatters.js"+import { formatDateTime } from "../../utils/formatters.js";import { t } from "../../services/i18n.js";import appContext from "../../components/app_context.js";import BasicWidget from "../basic_widget.js";import dialogService from "../../services/dialog.js";import froca from "../../services/froca.js";import hoistedNoteService from "../../services/hoisted_note.js";-import linkService from '../../services/link.js';-import server from '../../services/server.js';+import linkService from "../../services/link.js";+import server from "../../services/server.js";import toastService from "../../services/toast.js";-import utils from '../../services/utils.js';+import utils from "../../services/utils.js";import ws from "../../services/ws.js";const TPL = `@@ -16,9 +16,9 @@ const TPL = `<div class="modal-dialog modal-lg modal-dialog-scrollable" role="document"><div class="modal-content"><div class="modal-header">- <h5 class="modal-title flex-grow-1">${t('recent_changes.title')}</h5>- <button class="erase-deleted-notes-now-button btn btn-sm" style="padding: 0 10px">${t('recent_changes.erase_notes_button')}</button>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('recent_changes.close')}"></button>+ <h5 class="modal-title flex-grow-1">${t("recent_changes.title")}</h5>+ <button class="erase-deleted-notes-now-button btn btn-sm" style="padding: 0 10px">${t("recent_changes.erase_notes_button")}</button>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("recent_changes.close")}"></button></div><div class="modal-body"><div class="recent-changes-content"></div>@@ -35,10 +35,10 @@ export default class RecentChangesDialog extends BasicWidget {this.$content = this.$widget.find(".recent-changes-content");this.$eraseDeletedNotesNow = this.$widget.find(".erase-deleted-notes-now-button");this.$eraseDeletedNotesNow.on("click", () => {- server.post('notes/erase-deleted-notes-now').then(() => {+ server.post("notes/erase-deleted-notes-now").then(() => {this.refresh();- toastService.showMessage(t('recent_changes.deleted_notes_message'));+ toastService.showMessage(t("recent_changes.deleted_notes_message"));});});}@@ -59,21 +59,24 @@ export default class RecentChangesDialog extends BasicWidget {const recentChangesRows = await server.get(`recent-changes/${this.ancestorNoteId}`);// preload all notes into cache- await froca.getNotes(recentChangesRows.map(r => r.noteId), true);+ await froca.getNotes(+ recentChangesRows.map((r) => r.noteId),+ true+ );this.$content.empty();if (recentChangesRows.length === 0) {- this.$content.append(t('recent_changes.no_changes_message'));+ this.$content.append(t("recent_changes.no_changes_message"));}const groupedByDate = this.groupByDate(recentChangesRows);for (const [dateDay, dayChanges] of groupedByDate) {- const $changesList = $('<ul>');+ const $changesList = $("<ul>");const formattedDate = formatDateTime(dateDay, "full", "none");- const dayEl = $('<div>').append($('<b>').text(formattedDate)).append($changesList);+ const dayEl = $("<div>").append($("<b>").text(formattedDate)).append($changesList);for (const change of dayChanges) {const formattedTime = formatDateTime(change.date, "none", "short");@@ -83,16 +86,13 @@ export default class RecentChangesDialog extends BasicWidget {if (change.current_isDeleted) {$noteLink = $("<span>");- $noteLink.append($("<span>")- .addClass("note-title")- .text(change.current_title)- );+ $noteLink.append($("<span>").addClass("note-title").text(change.current_title));if (change.canBeUndeleted) {const $undeleteLink = $(`<a href="javascript:">`)- .text(t('recent_changes.undelete_link'))- .on('click', async () => {- const text = t('recent_changes.confirm_undelete');+ .text(t("recent_changes.undelete_link"))+ .on("click", async () => {+ const text = t("recent_changes.confirm_undelete");if (await dialogService.confirm(text)) {await server.put(`notes/${change.noteId}/undelete`);@@ -105,10 +105,7 @@ export default class RecentChangesDialog extends BasicWidget {}});- $noteLink- .append(' (')- .append($undeleteLink)- .append(')');+ $noteLink.append(" (").append($undeleteLink).append(")");}} else {const note = await froca.getNote(change.noteId);@@ -124,23 +121,21 @@ export default class RecentChangesDialog extends BasicWidget {}}- $changesList.append($('<li>')- .on("click", (e) => {- // Skip clicks on the link or deleted notes- if (e.target?.nodeName !== "A" && !change.current_isDeleted) {- // Open the current note- appContext.tabManager.getActiveContext().setNote(change.noteId);- }- })- .addClass(() => {- if (change.current_isDeleted) return "deleted-note";- })- .append(- $("<span>")- .text(formattedTime)- .attr("title", change.date)- )- .append($noteLink.addClass("note-title")));+ $changesList.append(+ $("<li>")+ .on("click", (e) => {+ // Skip clicks on the link or deleted notes+ if (e.target?.nodeName !== "A" && !change.current_isDeleted) {+ // Open the current note+ appContext.tabManager.getActiveContext().setNote(change.noteId);+ }+ })+ .addClass(() => {+ if (change.current_isDeleted) return "deleted-note";+ })+ .append($("<span>").text(formattedTime).attr("title", change.date))+ .append($noteLink.addClass("note-title"))+ );}this.$content.append(dayEl);diff --git a/src/public/app/widgets/dialogs/revisions.js b/src/public/app/widgets/dialogs/revisions.jsindex 077af547ad..4821581a9b 100644--- a/src/public/app/widgets/dialogs/revisions.js+++ b/src/public/app/widgets/dialogs/revisions.js@@ -1,6 +1,6 @@import { t } from "../../services/i18n.js";-import utils from '../../services/utils.js';-import server from '../../services/server.js';+import utils from "../../services/utils.js";+import server from "../../services/server.js";import toastService from "../../services/toast.js";import appContext from "../../components/app_context.js";import libraryLoader from "../../services/library_loader.js";@@ -98,28 +98,30 @@ export default class RevisionsDialog extends BasicWidget {this.$eraseAllRevisionsButton = this.$widget.find(".revisions-erase-all-revisions-button");this.$snapshotInterval = this.$widget.find(".revisions-snapshot-interval");this.$maximumRevisions = this.$widget.find(".maximum-revisions-for-current-note");- this.$revisionSettingsButton = this.$widget.find(".revision-settings-button")+ this.$revisionSettingsButton = this.$widget.find(".revision-settings-button");this.listDropdown.show();- this.$listDropdown.parent().on('hide.bs.dropdown', e => {+ this.$listDropdown.parent().on("hide.bs.dropdown", (e) => {// Prevent closing dropdown by pressing ESC and clicking outsidee.preventDefault();});- document.addEventListener('keydown', e => {- // Close the revision dialog when revision element is focused and ESC is pressed- if (e.key === 'Escape' ||- e.target.classList.contains(['dropdown-item', 'active'])) {- this.modal.hide();- }- }, true)-- this.$widget.on('shown.bs.modal', () => {- this.$list.find(`[data-revision-id="${this.revisionId}"]`)- .trigger('focus');+ document.addEventListener(+ "keydown",+ (e) => {+ // Close the revision dialog when revision element is focused and ESC is pressed+ if (e.key === "Escape" || e.target.classList.contains(["dropdown-item", "active"])) {+ this.modal.hide();+ }+ },+ true+ );++ this.$widget.on("shown.bs.modal", () => {+ this.$list.find(`[data-revision-id="${this.revisionId}"]`).trigger("focus");});- this.$eraseAllRevisionsButton.on('click', async () => {+ this.$eraseAllRevisionsButton.on("click", async () => {const text = t("revisions.confirm_delete_all");if (await dialogService.confirm(text)) {@@ -131,16 +133,16 @@ export default class RevisionsDialog extends BasicWidget {}});- this.$list.on('focus', '.dropdown-item', e => {- this.$list.find('.dropdown-item').each((i, el) => {- $(el).toggleClass('active', el === e.target);+ this.$list.on("focus", ".dropdown-item", (e) => {+ this.$list.find(".dropdown-item").each((i, el) => {+ $(el).toggleClass("active", el === e.target);});this.setContentPane();});- this.$revisionSettingsButton.on('click', async () => {- appContext.tabManager.openContextWithNote('_optionsOther', { activate: true });+ this.$revisionSettingsButton.on("click", async () => {+ appContext.tabManager.openContextWithNote("_optionsOther", { activate: true });});}@@ -162,8 +164,8 @@ export default class RevisionsDialog extends BasicWidget {this.$list.append($('<a class="dropdown-item" tabindex="0">').text(`${item.dateLastEdited.substr(0, 16)} (${utils.formatSize(item.contentLength)})`)- .attr('data-revision-id', item.revisionId)- .attr('title', t("revisions.revision_last_edited", { date: item.dateLastEdited }))+ .attr("data-revision-id", item.revisionId)+ .attr("title", t("revisions.revision_last_edited", { date: item.dateLastEdited })));}@@ -181,21 +183,21 @@ export default class RevisionsDialog extends BasicWidget {this.$eraseAllRevisionsButton.toggle(this.revisionItems.length > 0);// Show the footer of the revisions dialog- this.$snapshotInterval.text(t("revisions.snapshot_interval", { seconds: options.getInt('revisionSnapshotTimeInterval') }))+ this.$snapshotInterval.text(t("revisions.snapshot_interval", { seconds: options.getInt("revisionSnapshotTimeInterval") }));let revisionsNumberLimit = parseInt(this.note.getLabelValue("versioningLimit") ?? "");if (!Number.isInteger(revisionsNumberLimit)) {- revisionsNumberLimit = parseInt(options.getInt('revisionSnapshotNumberLimit'));+ revisionsNumberLimit = parseInt(options.getInt("revisionSnapshotNumberLimit"));}if (revisionsNumberLimit === -1) {- revisionsNumberLimit = "∞"+ revisionsNumberLimit = "∞";}- this.$maximumRevisions.text(t("revisions.maximum_revisions", { number: revisionsNumberLimit }))+ this.$maximumRevisions.text(t("revisions.maximum_revisions", { number: revisionsNumberLimit }));}async setContentPane() {- const revisionId = this.$list.find(".active").attr('data-revision-id');+ const revisionId = this.$list.find(".active").attr("data-revision-id");- const revisionItem = this.revisionItems.find(r => r.revisionId === revisionId);+ const revisionItem = this.revisionItems.find((r) => r.revisionId === revisionId);this.$title.html(revisionItem.title);@@ -209,7 +211,7 @@ export default class RevisionsDialog extends BasicWidget {const $restoreRevisionButton = $(`<button class="btn btn-sm" type="button">${t("revisions.restore_button")}</button>`);- $restoreRevisionButton.on('click', async () => {+ $restoreRevisionButton.on("click", async () => {const text = t("revisions.confirm_restore");if (await dialogService.confirm(text)) {@@ -223,7 +225,7 @@ export default class RevisionsDialog extends BasicWidget {const $eraseRevisionButton = $(`<button class="btn btn-sm" type="button">${t("revisions.delete_button")}</button>`);- $eraseRevisionButton.on('click', async () => {+ $eraseRevisionButton.on("click", async () => {const text = t("revisions.confirm_delete");if (await dialogService.confirm(text)) {@@ -236,18 +238,14 @@ export default class RevisionsDialog extends BasicWidget {});if (!revisionItem.isProtected || protectedSessionHolder.isProtectedSessionAvailable()) {- this.$titleButtons- .append($restoreRevisionButton)- .append(' ');+ this.$titleButtons.append($restoreRevisionButton).append(" ");}- this.$titleButtons- .append($eraseRevisionButton)- .append(' ');+ this.$titleButtons.append($eraseRevisionButton).append(" ");const $downloadButton = $(`<button class="btn btn-sm btn-primary" type="button">${t("revisions.download_button")}</button>`);- $downloadButton.on('click', () => openService.downloadRevision(revisionItem.noteId, revisionItem.revisionId));+ $downloadButton.on("click", () => openService.downloadRevision(revisionItem.noteId, revisionItem.revisionId));if (!revisionItem.isProtected || protectedSessionHolder.isProtectedSessionAvailable()) {this.$titleButtons.append($downloadButton);@@ -259,65 +257,52 @@ export default class RevisionsDialog extends BasicWidget {const fullRevision = await server.get(`revisions/${revisionItem.revisionId}`);- if (revisionItem.type === 'text') {+ if (revisionItem.type === "text") {this.$content.html(fullRevision.content);- if (this.$content.find('span.math-tex').length > 0) {+ if (this.$content.find("span.math-tex").length > 0) {await libraryLoader.requireLibrary(libraryLoader.KATEX);renderMathInElement(this.$content[0], { trust: true });}- } else if (revisionItem.type === 'code') {+ } else if (revisionItem.type === "code") {this.$content.html($("<pre>").text(fullRevision.content));- } else if (revisionItem.type === 'image') {+ } else if (revisionItem.type === "image") {if (fullRevision.mime === "image/svg+xml") {let encodedSVG = encodeURIComponent(fullRevision.content); //Base64 of other format images may be embedded in svg- this.$content.html($("<img>")- .attr("src", `data:${fullRevision.mime};utf8,${encodedSVG}`)- .css("max-width", "100%")- .css("max-height", "100%"));+ this.$content.html($("<img>").attr("src", `data:${fullRevision.mime};utf8,${encodedSVG}`).css("max-width", "100%").css("max-height", "100%"));} else {- this.$content.html($("<img>")- // the reason why we put this inline as base64 is that we do not want to let user copy this- // as a URL to be used in a note. Instead, if they copy and paste it into a note, it will be uploaded as a new note- .attr("src", `data:${fullRevision.mime};base64,${fullRevision.content}`)- .css("max-width", "100%")- .css("max-height", "100%"));+ this.$content.html(+ $("<img>")+ // the reason why we put this inline as base64 is that we do not want to let user copy this+ // as a URL to be used in a note. Instead, if they copy and paste it into a note, it will be uploaded as a new note+ .attr("src", `data:${fullRevision.mime};base64,${fullRevision.content}`)+ .css("max-width", "100%")+ .css("max-height", "100%")+ );}- } else if (revisionItem.type === 'file') {+ } else if (revisionItem.type === "file") {const $table = $("<table cellpadding='10'>")- .append($("<tr>").append(- $("<th>").text(t("revisions.mime")),- $("<td>").text(revisionItem.mime)- ))- .append($("<tr>").append(- $("<th>").text(t("revisions.file_size")),- $("<td>").text(utils.formatSize(revisionItem.contentLength))- ));+ .append($("<tr>").append($("<th>").text(t("revisions.mime")), $("<td>").text(revisionItem.mime)))+ .append($("<tr>").append($("<th>").text(t("revisions.file_size")), $("<td>").text(utils.formatSize(revisionItem.contentLength))));if (fullRevision.content) {- $table.append($("<tr>").append(- $('<td colspan="2">').append(- $('<div style="font-weight: bold;">').text(t("revisions.preview")),- $('<pre class="file-preview-content"></pre>')- .text(fullRevision.content)+ $table.append(+ $("<tr>").append(+ $('<td colspan="2">').append($('<div style="font-weight: bold;">').text(t("revisions.preview")), $('<pre class="file-preview-content"></pre>').text(fullRevision.content)))- ));+ );}this.$content.html($table);} else if (["canvas", "mindMap"].includes(revisionItem.type)) {const encodedTitle = encodeURIComponent(revisionItem.title);- this.$content.html($("<img>")- .attr("src", `api/revisions/${revisionItem.revisionId}/image/${encodedTitle}?${Math.random()}`)- .css("max-width", "100%"));- } else if (revisionItem.type === 'mermaid') {+ this.$content.html($("<img>").attr("src", `api/revisions/${revisionItem.revisionId}/image/${encodedTitle}?${Math.random()}`).css("max-width", "100%"));+ } else if (revisionItem.type === "mermaid") {const encodedTitle = encodeURIComponent(revisionItem.title);- this.$content.html($("<img>")- .attr("src", `api/revisions/${revisionItem.revisionId}/image/${encodedTitle}?${Math.random()}`)- .css("max-width", "100%"));+ this.$content.html($("<img>").attr("src", `api/revisions/${revisionItem.revisionId}/image/${encodedTitle}?${Math.random()}`).css("max-width", "100%"));this.$content.append($("<pre>").text(fullRevision.content));} else {diff --git a/src/public/app/widgets/dialogs/sort_child_notes.js b/src/public/app/widgets/dialogs/sort_child_notes.jsindex e8cf598f5f..69428cde9b 100644--- a/src/public/app/widgets/dialogs/sort_child_notes.js+++ b/src/public/app/widgets/dialogs/sort_child_notes.js@@ -69,7 +69,7 @@ export default class SortChildNotesDialog extends BasicWidget {this.$widget = $(TPL);this.$form = this.$widget.find(".sort-child-notes-form");- this.$form.on('submit', async () => {+ this.$form.on("submit", async () => {const sortBy = this.$form.find("input[name='sort-by']:checked").val();const sortDirection = this.$form.find("input[name='sort-direction']:checked").val();const foldersFirst = this.$form.find("input[name='sort-folders-first']").is(":checked");@@ -87,6 +87,6 @@ export default class SortChildNotesDialog extends BasicWidget {utils.openDialog(this.$widget);- this.$form.find('input:first').focus();+ this.$form.find("input:first").focus();}}diff --git a/src/public/app/widgets/dialogs/upload_attachments.js b/src/public/app/widgets/dialogs/upload_attachments.jsindex 92040a63c5..5bf9661b11 100644--- a/src/public/app/widgets/dialogs/upload_attachments.js+++ b/src/public/app/widgets/dialogs/upload_attachments.js@@ -1,5 +1,5 @@import { t } from "../../services/i18n.js";-import utils from '../../services/utils.js';+import utils from "../../services/utils.js";import treeService from "../../services/tree.js";import importService from "../../services/import.js";import options from "../../services/options.js";@@ -11,7 +11,7 @@ const TPL = `<div class="modal-content"><div class="modal-header"><h5 class="modal-title">${t("upload_attachments.upload_attachments_to_note")}</h5>- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t('upload_attachments.close')}"></button>+ <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="${t("upload_attachments.close")}"></button></div><form class="upload-attachment-form"><div class="modal-body">@@ -55,18 +55,17 @@ export default class UploadAttachmentsDialog extends BasicWidget {this.$uploadButton = this.$widget.find(".upload-attachment-button");this.$shrinkImagesCheckbox = this.$widget.find(".shrink-images-checkbox");- this.$form.on('submit', () => {+ this.$form.on("submit", () => {// disabling so that import is not triggered again.this.$uploadButton.attr("disabled", "disabled");this.uploadAttachments(this.parentNoteId);return false;});- this.$fileUploadInput.on('change', () => {+ this.$fileUploadInput.on("change", () => {if (this.$fileUploadInput.val()) {this.$uploadButton.removeAttr("disabled");- }- else {+ } else {this.$uploadButton.attr("disabled", "disabled");}});@@ -79,8 +78,8 @@ export default class UploadAttachmentsDialog extends BasicWidget {async showUploadAttachmentsDialogEvent({ noteId }) {this.parentNoteId = noteId;- this.$fileUploadInput.val('').trigger('change'); // to trigger upload button disabling listener below- this.$shrinkImagesCheckbox.prop("checked", options.is('compressImages'));+ this.$fileUploadInput.val("").trigger("change"); // to trigger upload button disabling listener below+ this.$shrinkImagesCheckbox.prop("checked", options.is("compressImages"));this.$noteTitle.text(await treeService.getNoteTitle(this.parentNoteId));@@ -90,14 +89,14 @@ export default class UploadAttachmentsDialog extends BasicWidget {async uploadAttachments(parentNoteId) {const files = Array.from(this.$fileUploadInput[0].files); // shallow copy since we're resetting the upload button below- const boolToString = $el => $el.is(":checked") ? "true" : "false";+ const boolToString = ($el) => ($el.is(":checked") ? "true" : "false");const options = {- shrinkImages: boolToString(this.$shrinkImagesCheckbox),+ shrinkImages: boolToString(this.$shrinkImagesCheckbox)};this.modal.hide();- await importService.uploadFiles('attachments', parentNoteId, files, options);+ await importService.uploadFiles("attachments", parentNoteId, files, options);}}diff --git a/src/public/app/widgets/editability_select.js b/src/public/app/widgets/editability_select.jsindex 3d17a83bf4..937fdf0076 100644--- a/src/public/app/widgets/editability_select.js+++ b/src/public/app/widgets/editability_select.js@@ -1,4 +1,4 @@-import attributeService from '../services/attributes.js';+import attributeService from "../services/attributes.js";import NoteContextAwareWidget from "./note_context_aware_widget.js";import { t } from "../services/i18n.js";@@ -47,48 +47,46 @@ export default class EditabilitySelectWidget extends NoteContextAwareWidget {this.$editabilityActiveDesc = this.$widget.find(".editability-active-desc");- this.$widget.on('click', '.dropdown-item',- async e => {- this.dropdown.toggle();+ this.$widget.on("click", ".dropdown-item", async (e) => {+ this.dropdown.toggle();- const editability = $(e.target).closest("[data-editability]").attr("data-editability");+ const editability = $(e.target).closest("[data-editability]").attr("data-editability");- for (const ownedAttr of this.note.getOwnedLabels()) {- if (['readOnly', 'autoReadOnlyDisabled'].includes(ownedAttr.name)) {- await attributeService.removeAttributeById(this.noteId, ownedAttr.attributeId);- }+ for (const ownedAttr of this.note.getOwnedLabels()) {+ if (["readOnly", "autoReadOnlyDisabled"].includes(ownedAttr.name)) {+ await attributeService.removeAttributeById(this.noteId, ownedAttr.attributeId);}+ }- if (editability !== 'auto') {- await attributeService.addLabel(this.noteId, editability);- }- });+ if (editability !== "auto") {+ await attributeService.addLabel(this.noteId, editability);+ }+ });}async refreshWithNote(note) {- let editability = 'auto'+ let editability = "auto";- if (this.note.isLabelTruthy('readOnly')) {- editability = 'readOnly';- }- else if (this.note.isLabelTruthy('autoReadOnlyDisabled')) {- editability = 'autoReadOnlyDisabled';+ if (this.note.isLabelTruthy("readOnly")) {+ editability = "readOnly";+ } else if (this.note.isLabelTruthy("autoReadOnlyDisabled")) {+ editability = "autoReadOnlyDisabled";}const labels = {- "auto": t("editability_select.auto"),- "readOnly": t("editability_select.read_only"),- "autoReadOnlyDisabled": t("editability_select.always_editable")- }+ auto: t("editability_select.auto"),+ readOnly: t("editability_select.read_only"),+ autoReadOnlyDisabled: t("editability_select.always_editable")+ };- this.$widget.find('.dropdown-item').removeClass("selected");+ this.$widget.find(".dropdown-item").removeClass("selected");this.$widget.find(`.dropdown-item[data-editability='${editability}']`).addClass("selected");this.$editabilityActiveDesc.text(labels[editability]);}entitiesReloadedEvent({ loadResults }) {- if (loadResults.getAttributeRows().find(attr => attr.noteId === this.noteId)) {+ if (loadResults.getAttributeRows().find((attr) => attr.noteId === this.noteId)) {this.refresh();}}diff --git a/src/public/app/widgets/find.js b/src/public/app/widgets/find.jsindex a3c9124c2d..f373af52a2 100644--- a/src/public/app/widgets/find.js+++ b/src/public/app/widgets/find.js@@ -11,7 +11,7 @@ import FindInCode from "./find_in_code.js";import FindInHtml from "./find_in_html.js";const findWidgetDelayMillis = 200;-const waitForEnter = (findWidgetDelayMillis < 0);+const waitForEnter = findWidgetDelayMillis < 0;// tabIndex=-1 on the checkbox labels is necessary, so when clicking on the label,// the focusout handler is called with relatedTarget equal to the label instead@@ -47,7 +47,7 @@ const TPL = `<div class="find-widget-box"><div class="input-group find-widget-search-term-input-group">- <input type="text" class="form-control find-widget-search-term-input" placeholder="${t('find.find_placeholder')}">+ <input type="text" class="form-control find-widget-search-term-input" placeholder="${t("find.find_placeholder")}"><button class="btn btn-outline-secondary bx bxs-chevron-up find-widget-previous-button" type="button"></button><button class="btn btn-outline-secondary bx bxs-chevron-down find-widget-next-button" type="button"></button></div>@@ -55,14 +55,14 @@ const TPL = `<div class="form-check"><label tabIndex="-1" class="form-check-label"><input type="checkbox" class="form-check-input find-widget-case-sensitive-checkbox">- ${t('find.case_sensitive')}+ ${t("find.case_sensitive")}</label></div><div class="form-check"><label tabIndex="-1" class="form-check-label"><input type="checkbox" class="form-check-input find-widget-match-words-checkbox">- ${t('find.match_words')}+ ${t("find.match_words")}</label></div>@@ -78,9 +78,9 @@ const TPL = `</div><div class="replace-widget-box" style='display: none'>- <input type="text" class="form-control replace-widget-replacetext-input" placeholder="${t('find.replace_placeholder')}">- <button class="btn btn-sm replace-widget-replaceall-button" type="button">${t('find.replace_all')}</button>- <button class="btn btn-sm replace-widget-replace-button" type="button">${t('find.replace')}</button>+ <input type="text" class="form-control replace-widget-replacetext-input" placeholder="${t("find.replace_placeholder")}">+ <button class="btn btn-sm replace-widget-replaceall-button" type="button">${t("find.replace_all")}</button>+ <button class="btn btn-sm replace-widget-replace-button" type="button">${t("find.replace")}</button></div></div>`;@@ -104,9 +104,9 @@ export default class FindWidget extends NoteContextAwareWidget {doRender() {this.$widget = $(TPL);this.$widget.hide();- this.$input = this.$widget.find('.find-widget-search-term-input');- this.$currentFound = this.$widget.find('.find-widget-current-found');- this.$totalFound = this.$widget.find('.find-widget-total-found');+ this.$input = this.$widget.find(".find-widget-search-term-input");+ this.$currentFound = this.$widget.find(".find-widget-current-found");+ this.$totalFound = this.$widget.find(".find-widget-total-found");this.$caseSensitiveCheckbox = this.$widget.find(".find-widget-case-sensitive-checkbox");this.$caseSensitiveCheckbox.change(() => this.performFind());this.$matchWordsCheckbox = this.$widget.find(".find-widget-match-words-checkbox");@@ -125,25 +125,25 @@ export default class FindWidget extends NoteContextAwareWidget {this.$replaceButton = this.$widget.find(".replace-widget-replace-button");this.$replaceButton.on("click", () => this.replace());- this.$input.keydown(async e => {- if ((e.metaKey || e.ctrlKey) && (e.key === 'F' || e.key === 'f')) {+ this.$input.keydown(async (e) => {+ if ((e.metaKey || e.ctrlKey) && (e.key === "F" || e.key === "f")) {// If ctrl+f is pressed when the findbox is shown, select the// whole input to findthis.$input.select();- } else if (e.key === 'Enter' || e.key === 'F3') {+ } else if (e.key === "Enter" || e.key === "F3") {await this.findNext(e?.shiftKey ? -1 : 1);e.preventDefault();return false;}});- this.$widget.keydown(async e => {- if (e.key === 'Escape') {+ this.$widget.keydown(async (e) => {+ if (e.key === "Escape") {await this.closeSearch();}});- this.$input.on('input', () => this.startSearch());+ this.$input.on("input", () => this.startSearch());return this.$widget;}@@ -153,26 +153,26 @@ export default class FindWidget extends NoteContextAwareWidget {return;}- if (!['text', 'code', 'render'].includes(this.note.type)) {+ if (!["text", "code", "render"].includes(this.note.type)) {return;}this.handler = await this.getHandler();-+const isReadOnly = await this.noteContext.isReadOnly();- let selectedText = '';- if (this.note.type === 'code' && !isReadOnly){+ let selectedText = "";+ if (this.note.type === "code" && !isReadOnly) {const codeEditor = await this.noteContext.getCodeEditor();selectedText = codeEditor.getSelection();- }else{+ } else {selectedText = window.getSelection().toString() || "";}this.$widget.show();this.$input.focus();- if (['text', 'code'].includes(this.note.type) && !isReadOnly) {+ if (["text", "code"].includes(this.note.type) && !isReadOnly) {this.$replaceWidgetBox.show();- }else{+ } else {this.$replaceWidgetBox.hide();}@@ -201,7 +201,7 @@ export default class FindWidget extends NoteContextAwareWidget {}async getHandler() {- if (this.note.type === 'render') {+ if (this.note.type === "render") {return this.htmlHandler;}@@ -210,9 +210,7 @@ export default class FindWidget extends NoteContextAwareWidget {if (readOnly) {return this.htmlHandler;} else {- return this.note.type === "code"- ? this.codeHandler- : this.textHandler;+ return this.note.type === "code" ? this.codeHandler : this.textHandler;}}@@ -241,9 +239,9 @@ export default class FindWidget extends NoteContextAwareWidget {* @returns {Promise<void>}*/async findNext(direction) {- if (this.$totalFound.text()=="?"){+ if (this.$totalFound.text() == "?") {await this.performFind();- return+ return;}const searchTerm = this.$input.val();if (waitForEnter && this.searchTerm !== searchTerm) {@@ -273,7 +271,7 @@ export default class FindWidget extends NoteContextAwareWidget {const matchCase = this.$caseSensitiveCheckbox.prop("checked");const wholeWord = this.$matchWordsCheckbox.prop("checked");- const {totalFound, currentFound} = await this.handler.performFind(searchTerm, matchCase, wholeWord);+ const { totalFound, currentFound } = await this.handler.performFind(searchTerm, matchCase, wholeWord);this.$totalFound.text(totalFound);this.$currentFound.text(currentFound);@@ -307,15 +305,13 @@ export default class FindWidget extends NoteContextAwareWidget {}isEnabled() {- return super.isEnabled() && ['text', 'code', 'render'].includes(this.note.type);+ return super.isEnabled() && ["text", "code", "render"].includes(this.note.type);}async entitiesReloadedEvent({ loadResults }) {if (loadResults.isNoteContentReloaded(this.noteId)) {- this.$totalFound.text("?")- } else if (loadResults.getAttributeRows().find(attr => attr.type === 'label'- && (attr.name.toLowerCase().includes('readonly'))- && attributeService.isAffecting(attr, this.note))) {+ this.$totalFound.text("?");+ } else if (loadResults.getAttributeRows().find((attr) => attr.type === "label" && attr.name.toLowerCase().includes("readonly") && attributeService.isAffecting(attr, this.note))) {this.closeSearch();}}diff --git a/src/public/app/widgets/find_in_code.js b/src/public/app/widgets/find_in_code.jsindex 672e0c9b84..da34767223 100644--- a/src/public/app/widgets/find_in_code.js+++ b/src/public/app/widgets/find_in_code.js@@ -46,8 +46,7 @@ export default class FindInCode {// complicated regexp, see// https://github.com/ckeditor/ckeditor5/blob/b95e2faf817262ac0e1e21993d9c0bde3f1be594/packages/ckeditor5-find-and-replace/src/utils.js#L145const wholeWordChar = wholeWord ? "\\b" : "";- const re = new RegExp(wholeWordChar + searchTerm + wholeWordChar,- 'g' + (matchCase ? '' : 'i'));+ const re = new RegExp(wholeWordChar + searchTerm + wholeWordChar, "g" + (matchCase ? "" : "i"));let curLine = 0;let curChar = 0;let curMatch = null;@@ -59,7 +58,7 @@ export default class FindInCode {codeEditor.operation(() => {for (let i = 0; i < text.length; ++i) {// Fetch the next match if it's the first time or if past the current match start- if ((curMatch == null) || (curMatch.index < i)) {+ if (curMatch == null || curMatch.index < i) {curMatch = re.exec(text);if (curMatch == null) {// No more matches@@ -69,19 +68,17 @@ export default class FindInCode {// Create a non-selected highlight marker for the match, the// selected marker highlight will be done laterif (i === curMatch.index) {- let fromPos = { "line" : curLine, "ch" : curChar };+ let fromPos = { line: curLine, ch: curChar };// If multiline is supported, this needs to recalculate curLine since the match may span lines- let toPos = { "line" : curLine, "ch" : curChar + curMatch[0].length};+ let toPos = { line: curLine, ch: curChar + curMatch[0].length };// or css = "color: #f3"- let marker = doc.markText( fromPos, toPos, { "className" : FIND_RESULT_CSS_CLASSNAME });+ let marker = doc.markText(fromPos, toPos, { className: FIND_RESULT_CSS_CLASSNAME });findResult.push(marker);// Set the first match beyond the cursor as the current matchif (currentFound === -1) {const cursorPos = codeEditor.getCursor();- if ((fromPos.line > cursorPos.line) ||- ((fromPos.line === cursorPos.line) &&- (fromPos.ch >= cursorPos.ch))){+ if (fromPos.line > cursorPos.line || (fromPos.line === cursorPos.line && fromPos.ch >= cursorPos.ch)) {currentFound = totalFound;}}@@ -103,14 +100,12 @@ export default class FindInCode {// Calculate curfound if not already, highlight it as selectedif (totalFound > 0) {- currentFound = Math.max(0, currentFound)+ currentFound = Math.max(0, currentFound);let marker = findResult[currentFound];let pos = marker.find();codeEditor.scrollIntoView(pos.to);marker.clear();- findResult[currentFound] = doc.markText( pos.from, pos.to,- { "className" : FIND_RESULT_SELECTED_CSS_CLASSNAME }- );+ findResult[currentFound] = doc.markText(pos.from, pos.to, { className: FIND_RESULT_SELECTED_CSS_CLASSNAME });}return {@@ -130,19 +125,13 @@ export default class FindInCode {let marker = this.findResult[currentFound];let pos = marker.find();marker.clear();- marker = doc.markText(- pos.from, pos.to,- { "className" : FIND_RESULT_CSS_CLASSNAME }- );+ marker = doc.markText(pos.from, pos.to, { className: FIND_RESULT_CSS_CLASSNAME });this.findResult[currentFound] = marker;marker = this.findResult[nextFound];pos = marker.find();marker.clear();- marker = doc.markText(- pos.from, pos.to,- { "className" : FIND_RESULT_SELECTED_CSS_CLASSNAME }- );+ marker = doc.markText(pos.from, pos.to, { className: FIND_RESULT_SELECTED_CSS_CLASSNAME });this.findResult[nextFound] = marker;codeEditor.scrollIntoView(pos.from);@@ -172,7 +161,7 @@ export default class FindInCode {}async replace(replaceText) {// this.findResult may be undefined and null- if (!this.findResult || this.findResult.length===0){+ if (!this.findResult || this.findResult.length === 0) {return;}let currentFound = -1;@@ -206,7 +195,7 @@ export default class FindInCode {}}async replaceAll(replaceText) {- if (!this.findResult || this.findResult.length===0){+ if (!this.findResult || this.findResult.length === 0) {return;}const codeEditor = await this.getCodeEditor();diff --git a/src/public/app/widgets/find_in_html.js b/src/public/app/widgets/find_in_html.jsindex 7bdecb5291..1c4b809710 100644--- a/src/public/app/widgets/find_in_html.js+++ b/src/public/app/widgets/find_in_html.js@@ -24,7 +24,7 @@ export default class FindInHtml {const wholeWordChar = wholeWord ? "\\b" : "";const regExp = new RegExp(wholeWordChar + utils.escapeRegExp(searchTerm) + wholeWordChar, matchCase ? "g" : "gi");- return new Promise(res => {+ return new Promise((res) => {$content.unmark({done: () => {$content.markRegExp(regExp, {@@ -82,7 +82,7 @@ export default class FindInHtml {const $content = await this.parent.noteContext.getContentElement();const $contentWiget = appContext.getComponentByEl($content);- $contentWiget.triggerCommand("scrollContainerTo", {position});+ $contentWiget.triggerCommand("scrollContainerTo", { position });}}}diff --git a/src/public/app/widgets/find_in_text.js b/src/public/app/widgets/find_in_text.jsindex a3f142d4f5..9ce9c7c400 100644--- a/src/public/app/widgets/find_in_text.js+++ b/src/public/app/widgets/find_in_text.js@@ -18,7 +18,7 @@ export default class FindInText {let currentFound = -1;// Clear- const findAndReplaceEditing = textEditor.plugins.get('FindAndReplaceEditing');+ const findAndReplaceEditing = textEditor.plugins.get("FindAndReplaceEditing");findAndReplaceEditing.state.clear(model);findAndReplaceEditing.stop();this.editingState = findAndReplaceEditing.state;@@ -30,8 +30,8 @@ export default class FindInText {// let re = new RegExp(searchTerm, 'gi');// let m = text.match(re);// totalFound = m ? m.length : 0;- const options = { "matchCase": matchCase, "wholeWords": wholeWord };- findResult = textEditor.execute('find', searchTerm, options);+ const options = { matchCase: matchCase, wholeWords: wholeWord };+ findResult = textEditor.execute("find", searchTerm, options);totalFound = findResult.results.length;// Find the result beyond the cursorconst cursorPos = model.document.selection.getLastPosition();@@ -53,8 +53,8 @@ export default class FindInText {currentFound = Math.max(0, currentFound);// XXX Do this accessing the private data?// See https://github.com/ckeditor/ckeditor5/blob/b95e2faf817262ac0e1e21993d9c0bde3f1be594/packages/ckeditor5-find-and-replace/src/findnextcommand.js- for (let i = 0 ; i < currentFound; ++i) {- textEditor.execute('findNext', searchTerm);+ for (let i = 0; i < currentFound; ++i) {+ textEditor.execute("findNext", searchTerm);}}@@ -72,9 +72,9 @@ export default class FindInText {// curFound wrap around above assumes findNext and// findPrevious wraparound, which is what they doif (direction > 0) {- textEditor.execute('findNext');+ textEditor.execute("findNext");} else {- textEditor.execute('findPrevious');+ textEditor.execute("findPrevious");}}@@ -90,10 +90,10 @@ export default class FindInText {// https://github.com/ckeditor/ckeditor5/blob/b95e2faf817262ac0e1e21993d9c0bde3f1be594/packages/ckeditor5-find-and-replace/src/findandreplace.js#L92// XXX Roll our own since already done for codeEditor and// will probably allow more refactoring?- let findAndReplaceEditing = textEditor.plugins.get('FindAndReplaceEditing');+ let findAndReplaceEditing = textEditor.plugins.get("FindAndReplaceEditing");findAndReplaceEditing.state.clear(model);findAndReplaceEditing.stop();- model.change(writer => {+ model.change((writer) => {writer.setSelection(range, 0);});textEditor.editing.view.scrollToTheSelection();@@ -107,14 +107,14 @@ export default class FindInText {async replace(replaceText) {if (this.editingState !== undefined && this.editingState.highlightedResult !== null) {const textEditor = await this.getTextEditor();- textEditor.execute('replace', replaceText, this.editingState.highlightedResult);+ textEditor.execute("replace", replaceText, this.editingState.highlightedResult);}}async replaceAll(replaceText) {- if (this.editingState !== undefined && this.editingState.results.length > 0) {+ if (this.editingState !== undefined && this.editingState.results.length > 0) {const textEditor = await this.getTextEditor();- textEditor.execute('replaceAll', replaceText, this.editingState.results);+ textEditor.execute("replaceAll", replaceText, this.editingState.results);}}}diff --git a/src/public/app/widgets/floating_buttons/code_buttons.js b/src/public/app/widgets/floating_buttons/code_buttons.jsindex 676aeee088..2dfa411b85 100644--- a/src/public/app/widgets/floating_buttons/code_buttons.js+++ b/src/public/app/widgets/floating_buttons/code_buttons.js@@ -16,50 +16,47 @@ const TPL = `}</style>- <button data-trigger-command="runActiveNote" class="execute-button floating-button btn" title="${t('code_buttons.execute_button_title')}">+ <button data-trigger-command="runActiveNote" class="execute-button floating-button btn" title="${t("code_buttons.execute_button_title")}"><span class="bx bx-run"></span></button>- <button class="trilium-api-docs-button floating-button btn" title="${t('code_buttons.trilium_api_docs_button_title')}">+ <button class="trilium-api-docs-button floating-button btn" title="${t("code_buttons.trilium_api_docs_button_title")}"><span class="bx bx-help-circle"></span></button>- <button class="save-to-note-button floating-button btn" title="${t('code_buttons.save_to_note_button_title')}">+ <button class="save-to-note-button floating-button btn" title="${t("code_buttons.save_to_note_button_title")}"><span class="bx bx-save"></span></button></div>`;export default class CodeButtonsWidget extends NoteContextAwareWidget {isEnabled() {- return super.isEnabled()- && this.note- && (this.note.mime.startsWith('application/javascript') || this.note.mime === 'text/x-sqlite;schema=trilium');+ return super.isEnabled() && this.note && (this.note.mime.startsWith("application/javascript") || this.note.mime === "text/x-sqlite;schema=trilium");}doRender() {this.$widget = $(TPL);this.$openTriliumApiDocsButton = this.$widget.find(".trilium-api-docs-button");this.$openTriliumApiDocsButton.on("click", () => {- toastService.showMessage(t('code_buttons.opening_api_docs_message'));+ toastService.showMessage(t("code_buttons.opening_api_docs_message"));if (this.note.mime.endsWith("frontend")) {window.open("https://zadam.github.io/trilium/frontend_api/FrontendScriptApi.html", "_blank");- }- else {+ } else {window.open("https://zadam.github.io/trilium/backend_api/BackendScriptApi.html", "_blank");}});- this.$executeButton = this.$widget.find('.execute-button');- this.$saveToNoteButton = this.$widget.find('.save-to-note-button');- this.$saveToNoteButton.on('click', async () => {- const {notePath} = await server.post("special-notes/save-sql-console", {sqlConsoleNoteId: this.noteId});+ this.$executeButton = this.$widget.find(".execute-button");+ this.$saveToNoteButton = this.$widget.find(".save-to-note-button");+ this.$saveToNoteButton.on("click", async () => {+ const { notePath } = await server.post("special-notes/save-sql-console", { sqlConsoleNoteId: this.noteId });await ws.waitForMaxKnownEntityChangeId();await appContext.tabManager.getActiveContext().setNote(notePath);- toastService.showMessage(t('code_buttons.sql_console_saved_message', { notePath: await treeService.getNotePathTitle(notePath) }));+ toastService.showMessage(t("code_buttons.sql_console_saved_message", { notePath: await treeService.getNotePathTitle(notePath) }));});keyboardActionService.updateDisplayedShortcuts(this.$widget);@@ -70,20 +67,14 @@ export default class CodeButtonsWidget extends NoteContextAwareWidget {}async refreshWithNote(note) {- this.$executeButton.toggle(- note.mime.startsWith('application/javascript')- || note.mime === 'text/x-sqlite;schema=trilium'- );+ this.$executeButton.toggle(note.mime.startsWith("application/javascript") || note.mime === "text/x-sqlite;schema=trilium");- this.$saveToNoteButton.toggle(- note.mime === 'text/x-sqlite;schema=trilium'- && note.isHiddenCompletely()- );+ this.$saveToNoteButton.toggle(note.mime === "text/x-sqlite;schema=trilium" && note.isHiddenCompletely());- this.$openTriliumApiDocsButton.toggle(note.mime.startsWith('application/javascript;env='));+ this.$openTriliumApiDocsButton.toggle(note.mime.startsWith("application/javascript;env="));}- async noteTypeMimeChangedEvent({noteId}) {+ async noteTypeMimeChangedEvent({ noteId }) {if (this.isNote(noteId)) {await this.refresh();}diff --git a/src/public/app/widgets/floating_buttons/copy_image_reference_button.js b/src/public/app/widgets/floating_buttons/copy_image_reference_button.jsindex 44748b8d3f..64eff526b3 100644--- a/src/public/app/widgets/floating_buttons/copy_image_reference_button.js+++ b/src/public/app/widgets/floating_buttons/copy_image_reference_button.js@@ -6,7 +6,7 @@ import imageService from "../../services/image.js";const TPL = `<button type="button"class="copy-image-reference-button"- title="${t('copy_image_reference_button.button_title')}">+ title="${t("copy_image_reference_button.button_title")}"><span class="bx bx-copy"></span><div class="hidden-image-copy"></div>@@ -14,10 +14,7 @@ const TPL = `export default class CopyImageReferenceButton extends NoteContextAwareWidget {isEnabled() {- return super.isEnabled()- && ['mermaid', 'canvas', 'mindMap'].includes(this.note?.type)- && this.note.isContentAvailable()- && this.noteContext?.viewScope.viewMode === 'default';+ return super.isEnabled() && ["mermaid", "canvas", "mindMap"].includes(this.note?.type) && this.note.isContentAvailable() && this.noteContext?.viewScope.viewMode === "default";}doRender() {@@ -26,11 +23,8 @@ export default class CopyImageReferenceButton extends NoteContextAwareWidget {this.$widget = $(TPL);this.$hiddenImageCopy = this.$widget.find(".hidden-image-copy");- this.$widget.on('click', () => {- this.$hiddenImageCopy.empty().append(- $("<img>")- .attr("src", utils.createImageSrcUrl(this.note))- );+ this.$widget.on("click", () => {+ this.$hiddenImageCopy.empty().append($("<img>").attr("src", utils.createImageSrcUrl(this.note)));imageService.copyImageReferenceToClipboard(this.$hiddenImageCopy);diff --git a/src/public/app/widgets/floating_buttons/floating_buttons.js b/src/public/app/widgets/floating_buttons/floating_buttons.jsindex 8e8db3292d..30e650645d 100644--- a/src/public/app/widgets/floating_buttons/floating_buttons.js+++ b/src/public/app/widgets/floating_buttons/floating_buttons.js@@ -79,7 +79,7 @@ const TPL = `</style><button type="button" class="show-floating-buttons-button btn bx bx-chevrons-left"- title="${t('show_floating_buttons_button.button_title')}"></button>+ title="${t("show_floating_buttons_button.button_title")}"></button></div></div>`;@@ -95,7 +95,7 @@ export default class FloatingButtons extends NoteContextAwareWidget {async refreshWithNote(note) {this.toggle(true);- this.$widget.find(".show-floating-buttons-button").on('click', () => this.toggle(true));+ this.$widget.find(".show-floating-buttons-button").on("click", () => this.toggle(true));}toggle(show) {diff --git a/src/public/app/widgets/floating_buttons/hide_floating_buttons_button.js b/src/public/app/widgets/floating_buttons/hide_floating_buttons_button.jsindex a0fa71d6ab..4b66404a22 100644--- a/src/public/app/widgets/floating_buttons/hide_floating_buttons_button.js+++ b/src/public/app/widgets/floating_buttons/hide_floating_buttons_button.js@@ -28,7 +28,7 @@ const TPL = `<button type="button"class="close-floating-buttons-button btn bx bx-chevrons-right"- title="${t('hide_floating_buttons_button.button_title')}"></button>+ title="${t("hide_floating_buttons_button.button_title")}"></button></div>`;@@ -37,7 +37,7 @@ export default class HideFloatingButtonsButton extends NoteContextAwareWidget {super.doRender();this.$widget = $(TPL);- this.$widget.on('click', () => this.triggerCommand('hideFloatingButtons'));+ this.$widget.on("click", () => this.triggerCommand("hideFloatingButtons"));this.contentSized();}}diff --git a/src/public/app/widgets/floating_buttons/relation_map_buttons.js b/src/public/app/widgets/floating_buttons/relation_map_buttons.jsindex 63aa0ad187..74de1852bd 100644--- a/src/public/app/widgets/floating_buttons/relation_map_buttons.js+++ b/src/public/app/widgets/floating_buttons/relation_map_buttons.js@@ -12,26 +12,26 @@ const TPL = `<button type="button"class="relation-map-create-child-note floating-button btn bx bx-folder-plus"- title="${t('relation_map_buttons.create_child_note_title')}"></button>+ title="${t("relation_map_buttons.create_child_note_title")}"></button><button type="button"class="relation-map-reset-pan-zoom floating-button btn bx bx-crop"- title="${t('relation_map_buttons.reset_pan_zoom_title')}"></button>+ title="${t("relation_map_buttons.reset_pan_zoom_title")}"></button><div class="btn-group"><button type="button"class="relation-map-zoom-in floating-button btn bx bx-zoom-in"- title="${t('relation_map_buttons.zoom_in_title')}"></button>+ title="${t("relation_map_buttons.zoom_in_title")}"></button><button type="button"class="relation-map-zoom-out floating-button btn bx bx-zoom-out"- title="${t('relation_map_buttons.zoom_out_title')}"></button>+ title="${t("relation_map_buttons.zoom_out_title")}"></button></div></div>`;export default class RelationMapButtons extends NoteContextAwareWidget {isEnabled() {- return super.isEnabled() && this.note?.type === 'relationMap';+ return super.isEnabled() && this.note?.type === "relationMap";}doRender() {@@ -43,11 +43,11 @@ export default class RelationMapButtons extends NoteContextAwareWidget {this.$zoomOutButton = this.$widget.find(".relation-map-zoom-out");this.$resetPanZoomButton = this.$widget.find(".relation-map-reset-pan-zoom");- this.$createChildNote.on('click', () => this.triggerEvent('relationMapCreateChildNote', {ntxId: this.ntxId}));- this.$resetPanZoomButton.on('click', () => this.triggerEvent('relationMapResetPanZoom', {ntxId: this.ntxId}));+ this.$createChildNote.on("click", () => this.triggerEvent("relationMapCreateChildNote", { ntxId: this.ntxId }));+ this.$resetPanZoomButton.on("click", () => this.triggerEvent("relationMapResetPanZoom", { ntxId: this.ntxId }));- this.$zoomInButton.on('click', () => this.triggerEvent('relationMapResetZoomIn', {ntxId: this.ntxId}));- this.$zoomOutButton.on('click', () => this.triggerEvent('relationMapResetZoomOut', {ntxId: this.ntxId}));+ this.$zoomInButton.on("click", () => this.triggerEvent("relationMapResetZoomIn", { ntxId: this.ntxId }));+ this.$zoomOutButton.on("click", () => this.triggerEvent("relationMapResetZoomOut", { ntxId: this.ntxId }));this.contentSized();}}diff --git a/src/public/app/widgets/floating_buttons/svg_export_button.js b/src/public/app/widgets/floating_buttons/svg_export_button.jsindex 6b25ad553a..b098b18c2d 100644--- a/src/public/app/widgets/floating_buttons/svg_export_button.js+++ b/src/public/app/widgets/floating_buttons/svg_export_button.js@@ -4,24 +4,21 @@ import NoteContextAwareWidget from "../note_context_aware_widget.js";const TPL = `<button type="button"class="export-svg-button"- title="${t('svg_export_button.button_title')}">+ title="${t("svg_export_button.button_title")}"><span class="bx bx-export"></span></button>`;export default class SvgExportButton extends NoteContextAwareWidget {isEnabled() {- return super.isEnabled()- && [ "mermaid", "mindMap" ].includes(this.note?.type)- && this.note.isContentAvailable()- && this.noteContext?.viewScope.viewMode === 'default';+ return super.isEnabled() && ["mermaid", "mindMap"].includes(this.note?.type) && this.note.isContentAvailable() && this.noteContext?.viewScope.viewMode === "default";}doRender() {super.doRender();this.$widget = $(TPL);- this.$widget.on('click', () => this.triggerEvent('exportSvg', {ntxId: this.ntxId}));+ this.$widget.on("click", () => this.triggerEvent("exportSvg", { ntxId: this.ntxId }));this.contentSized();}}diff --git a/src/public/app/widgets/floating_buttons/zpetne_odkazy.js b/src/public/app/widgets/floating_buttons/zpetne_odkazy.jsindex 9b6ee2885c..5f4bcf3b35 100644--- a/src/public/app/widgets/floating_buttons/zpetne_odkazy.js+++ b/src/public/app/widgets/floating_buttons/zpetne_odkazy.js@@ -67,9 +67,9 @@ const TPL = `export default class BacklinksWidget extends NoteContextAwareWidget {doRender() {this.$widget = $(TPL);- this.$count = this.$widget.find('.backlinks-count');- this.$items = this.$widget.find('.backlinks-items');- this.$ticker = this.$widget.find('.backlinks-ticker');+ this.$count = this.$widget.find(".backlinks-count");+ this.$items = this.$widget.find(".backlinks-items");+ this.$ticker = this.$widget.find(".backlinks-ticker");this.$count.on("click", () => {this.$items.toggle();@@ -86,7 +86,7 @@ export default class BacklinksWidget extends NoteContextAwareWidget {async refreshWithNote(note) {this.clearItems();- if (this.noteContext?.viewScope?.viewMode !== 'default') {+ if (this.noteContext?.viewScope?.viewMode !== "default") {this.toggle(false);return;}@@ -102,7 +102,7 @@ export default class BacklinksWidget extends NoteContextAwareWidget {this.toggle(true);this.$count.text(// i18next plural- `${t('zpetne_odkazy.backlink', {count: resp.count})}`+ `${t("zpetne_odkazy.backlink", { count: resp.count })}`);}@@ -127,21 +127,22 @@ export default class BacklinksWidget extends NoteContextAwareWidget {return;}- await froca.getNotes(backlinks.map(bl => bl.noteId)); // prefetch all+ await froca.getNotes(backlinks.map((bl) => bl.noteId)); // prefetch allfor (const backlink of backlinks) {const $item = $("<div>");- $item.append(await linkService.createLink(backlink.noteId, {- showNoteIcon: true,- showNotePath: true,- showTooltip: false- }));+ $item.append(+ await linkService.createLink(backlink.noteId, {+ showNoteIcon: true,+ showNotePath: true,+ showTooltip: false+ })+ );if (backlink.relationName) {- $item.append($("<p>").text(`${t('zpetne_odkazy.relation')}: ${backlink.relationName}`));- }- else {+ $item.append($("<p>").text(`${t("zpetne_odkazy.relation")}: ${backlink.relationName}`));+ } else {$item.append(...backlink.excerpts);}diff --git a/src/public/app/widgets/highlights_list.ts b/src/public/app/widgets/highlights_list.tsindex 403049629a..ab314bf0a9 100644--- a/src/public/app/widgets/highlights_list.ts+++ b/src/public/app/widgets/highlights_list.ts@@ -44,7 +44,6 @@ const TPL = `<div class="highlights-list-widget"></div>`;export default class HighlightsListWidget extends RightPanelWidget {-private $highlightsList!: JQuery<HTMLElement>;get widgetTitle() {@@ -57,7 +56,7 @@ export default class HighlightsListWidget extends RightPanelWidget {.icon("bx-cog").title(t("highlights_list_2.options")).titlePlacement("left")- .onClick(() => appContext.tabManager.openContextWithNote('_optionsTextNotes', { activate: true }))+ .onClick(() => appContext.tabManager.openContextWithNote("_optionsTextNotes", { activate: true })).class("icon-action"),new OnClickButtonWidget().icon("bx-x")@@ -68,15 +67,14 @@ export default class HighlightsListWidget extends RightPanelWidget {}isEnabled() {- return super.isEnabled()- && this.note != null && this.note.type === 'text'- && !this.noteContext?.viewScope?.highlightsListTemporarilyHidden- && this.noteContext?.viewScope?.viewMode === 'default';+ return (+ super.isEnabled() && this.note != null && this.note.type === "text" && !this.noteContext?.viewScope?.highlightsListTemporarilyHidden && this.noteContext?.viewScope?.viewMode === "default"+ );}async doRenderBody() {this.$body.empty().append($(TPL));- this.$highlightsList = this.$body.find('.highlights-list');+ this.$highlightsList = this.$body.find(".highlights-list");}async refreshWithNote(note: FNote | null | undefined) {@@ -91,9 +89,9 @@ export default class HighlightsListWidget extends RightPanelWidget {this.toggleInt(false);}- const optionsHighlightsList = JSON.parse(options.get('highlightsList'));+ const optionsHighlightsList = JSON.parse(options.get("highlightsList"));- if (note?.isLabelTruthy('hideHighlightWidget') || !optionsHighlightsList.length) {+ if (note?.isLabelTruthy("hideHighlightWidget") || !optionsHighlightsList.length) {this.toggleInt(false);this.triggerCommand("reEvaluateRightPaneVisibility");return;@@ -102,7 +100,7 @@ export default class HighlightsListWidget extends RightPanelWidget {let $highlightsList: JQuery<HTMLElement> | null = null;let hlLiCount = -1;// Check for type text unconditionally in case alwaysShowWidget is set- if (note && this.note?.type === 'text') {+ if (note && this.note?.type === "text") {const noteComplement = await note.getNoteComplement();if (noteComplement && "content" in noteComplement) {({ $highlightsList, hlLiCount } = await this.getHighlightList(noteComplement.content, optionsHighlightsList));@@ -129,7 +127,7 @@ export default class HighlightsListWidget extends RightPanelWidget {extractOuterTag(htmlStr: string | null) {if (htmlStr === null) {- return null+ return null;}// Regular expressions that match only the outermost tagconst regex = /^<([a-zA-Z]+)([^>]*)>/;@@ -175,7 +173,7 @@ export default class HighlightsListWidget extends RightPanelWidget {throwOnError: false});} catch (e) {- if (e instanceof ReferenceError && e.message.includes('katex is not defined')) {+ if (e instanceof ReferenceError && e.message.includes("katex is not defined")) {// Load KaTeX if it is not already loadedawait libraryLoader.requireLibrary(libraryLoader.KATEX);try {@@ -212,7 +210,8 @@ export default class HighlightsListWidget extends RightPanelWidget {const regex5 = /<u>[\s\S]*?<\/u>/g;// Possible values in optionsHighlightsList: '["bold","italic","underline","color","bgColor"]'// element priority: span>i>strong>u- let findSubStr = "", combinedRegexStr = "";+ let findSubStr = "",+ combinedRegexStr = "";if (optionsHighlightsList.includes("bgColor")) {findSubStr += `,span[style*="background-color"]:not(section.include-note span[style*="background-color"])`;combinedRegexStr += `|${regex1.source}`;@@ -234,16 +233,17 @@ export default class HighlightsListWidget extends RightPanelWidget {combinedRegexStr += `|${regex5.source}`;}- findSubStr = findSubStr.substring(1)+ findSubStr = findSubStr.substring(1);combinedRegexStr = `(` + combinedRegexStr.substring(1) + `)`;- const combinedRegex = new RegExp(combinedRegexStr, 'gi');+ const combinedRegex = new RegExp(combinedRegexStr, "gi");const $highlightsList = $("<ol>");- let prevEndIndex = -1, hlLiCount = 0;+ let prevEndIndex = -1,+ hlLiCount = 0;let prevSubHtml: string | null = null;// Used to determine if a string is only a formulaconst onlyMathRegex = /^<span class="math-tex">\\\([^\)]*?\)<\/span>(?:<span class="math-tex">\\\([^\)]*?\)<\/span>)*$/;- for (let match = null, hltIndex = 0; ((match = combinedRegex.exec(content)) !== null); hltIndex++) {+ for (let match = null, hltIndex = 0; (match = combinedRegex.exec(content)) !== null; hltIndex++) {const subHtml = match[0];const startIndex = match.index;const endIndex = combinedRegex.lastIndex;@@ -266,12 +266,12 @@ export default class HighlightsListWidget extends RightPanelWidget {const substring = content.substring(prevEndIndex, startIndex);//If the two elements have the same style and there are only formulas in between, append the formulas and the current element to the end of the previous element.if (this.areOuterTagsConsistent(prevSubHtml, subHtml) && onlyMathRegex.test(substring)) {- const $lastLi = $highlightsList.children('li').last();+ const $lastLi = $highlightsList.children("li").last();$lastLi.append(await this.replaceMathTextWithKatax(substring));$lastLi.append(subHtml);} else {$highlightsList.append(- $('<li>')+ $("<li>").html(subHtml).on("click", () => this.jumpToHighlightsList(findSubStr, hltIndex)));@@ -301,48 +301,59 @@ export default class HighlightsListWidget extends RightPanelWidget {let targetElement;if (isReadOnly) {const $container = await this.noteContext.getContentElement();- targetElement = $container.find(findSubStr).filter(function () {- if (findSubStr.indexOf("color") >= 0 && findSubStr.indexOf("background-color") < 0) {- let color = this.style.color;- const $el = $(this as HTMLElement);- return !($el.prop('tagName') === "SPAN" && color === "");- } else {- return true;- }- }).filter(function () {- const $el = $(this as HTMLElement);- return $el.parent(findSubStr).length === 0- && $el.parent().parent(findSubStr).length === 0- && $el.parent().parent().parent(findSubStr).length === 0- && $el.parent().parent().parent().parent(findSubStr).length === 0;- })- } else {- const textEditor = await this.noteContext.getTextEditor();- if (textEditor) {- targetElement = $(textEditor.editing.view.domRoots.values().next().value).find(findSubStr).filter(function () {- // When finding span[style*="color"] but not looking for span[style*="background-color"],- // the background-color error will be regarded as color, so it needs to be filtered- const $el = $(this as HTMLElement);+ targetElement = $container+ .find(findSubStr)+ .filter(function () {if (findSubStr.indexOf("color") >= 0 && findSubStr.indexOf("background-color") < 0) {let color = this.style.color;- return !($el.prop('tagName') === "SPAN" && color === "");+ const $el = $(this as HTMLElement);+ return !($el.prop("tagName") === "SPAN" && color === "");} else {return true;}- }).filter(function () {- // Need to filter out the child elements of the element that has been found- const $el = $(this as HTMLElement);- return $el.parent(findSubStr).length === 0- && $el.parent().parent(findSubStr).length === 0- && $el.parent().parent().parent(findSubStr).length === 0- && $el.parent().parent().parent().parent(findSubStr).length === 0;})+ .filter(function () {+ const $el = $(this as HTMLElement);+ return (+ $el.parent(findSubStr).length === 0 &&+ $el.parent().parent(findSubStr).length === 0 &&+ $el.parent().parent().parent(findSubStr).length === 0 &&+ $el.parent().parent().parent().parent(findSubStr).length === 0+ );+ });+ } else {+ const textEditor = await this.noteContext.getTextEditor();+ if (textEditor) {+ targetElement = $(textEditor.editing.view.domRoots.values().next().value)+ .find(findSubStr)+ .filter(function () {+ // When finding span[style*="color"] but not looking for span[style*="background-color"],+ // the background-color error will be regarded as color, so it needs to be filtered+ const $el = $(this as HTMLElement);+ if (findSubStr.indexOf("color") >= 0 && findSubStr.indexOf("background-color") < 0) {+ let color = this.style.color;+ return !($el.prop("tagName") === "SPAN" && color === "");+ } else {+ return true;+ }+ })+ .filter(function () {+ // Need to filter out the child elements of the element that has been found+ const $el = $(this as HTMLElement);+ return (+ $el.parent(findSubStr).length === 0 &&+ $el.parent().parent(findSubStr).length === 0 &&+ $el.parent().parent().parent(findSubStr).length === 0 &&+ $el.parent().parent().parent().parent(findSubStr).length === 0+ );+ });}}if (targetElement) {targetElement[itemIndex].scrollIntoView({- behavior: "smooth", block: "center"+ behavior: "smooth",+ block: "center"});}}@@ -352,23 +363,25 @@ export default class HighlightsListWidget extends RightPanelWidget {this.noteContext.viewScope.highlightsListTemporarilyHidden = true;}await this.refresh();- this.triggerCommand('reEvaluateRightPaneVisibility');+ this.triggerCommand("reEvaluateRightPaneVisibility");appContext.triggerEvent("reEvaluateHighlightsListWidgetVisibility", { noteId: this.noteId });}async showHighlightsListWidgetEvent({ noteId }: EventData<"showHighlightsListWidget">) {if (this.noteId === noteId) {await this.refresh();- this.triggerCommand('reEvaluateRightPaneVisibility');+ this.triggerCommand("reEvaluateRightPaneVisibility");}}async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {if (this.noteId && loadResults.isNoteContentReloaded(this.noteId)) {await this.refresh();- } else if (loadResults.getAttributeRows().find(attr => attr.type === 'label'- && (attr.name?.toLowerCase().includes('readonly') || attr.name === 'hideHighlightWidget')- && attributeService.isAffecting(attr, this.note))) {+ } else if (+ loadResults+ .getAttributeRows()+ .find((attr) => attr.type === "label" && (attr.name?.toLowerCase().includes("readonly") || attr.name === "hideHighlightWidget") && attributeService.isAffecting(attr, this.note))+ ) {await this.refresh();}}diff --git a/src/public/app/widgets/icon_list.ts b/src/public/app/widgets/icon_list.tsindex d06b0930f4..ed0c1aa980 100644--- a/src/public/app/widgets/icon_list.ts+++ b/src/public/app/widgets/icon_list.ts@@ -15,11188 +15,10245 @@ interface Icon {}const categories: Category[] = [- {"name": "All categories", "id": 0},+ { name: "All categories", id: 0 },{- "name": "Accessibility",- "id": 94+ name: "Accessibility",+ id: 94},{- "name": "Alert",- "id": 95+ name: "Alert",+ id: 95},{- "name": "Animals",- "id": 125+ name: "Animals",+ id: 125},{- "name": "Arrow",- "id": 96+ name: "Arrow",+ id: 96},{- "name": "Brands",- "id": 97+ name: "Brands",+ id: 97},{- "name": "Building",- "id": 98+ name: "Building",+ id: 98},{- "name": "Business",- "id": 99+ name: "Business",+ id: 99},{- "name": "Code",- "id": 100+ name: "Code",+ id: 100},{- "name": "Communication",- "id": 101+ name: "Communication",+ id: 101},{- "name": "Design",- "id": 102+ name: "Design",+ id: 102},{- "name": "Device",- "id": 103+ name: "Device",+ id: 103},{- "name": "E-Commerce",- "id": 104+ name: "E-Commerce",+ id: 104},{- "name": "Emoji",- "id": 105+ name: "Emoji",+ id: 105},{- "name": "Files \u0026 Folders",- "id": 106+ name: "Files \u0026 Folders",+ id: 106},{- "name": "Finance",- "id": 107+ name: "Finance",+ id: 107},{- "name": "Food \u0026 Beverage",- "id": 108+ name: "Food \u0026 Beverage",+ id: 108},{- "name": "Health",- "id": 109+ name: "Health",+ id: 109},{- "name": "Interface",- "id": 110+ name: "Interface",+ id: 110},{- "name": "Layout",- "id": 111+ name: "Layout",+ id: 111},{- "name": "Loader",- "id": 112+ name: "Loader",+ id: 112},{- "name": "Misc",- "id": 113+ name: "Misc",+ id: 113},{- "name": "Music",- "id": 114+ name: "Music",+ id: 114},{- "name": "Network",- "id": 115+ name: "Network",+ id: 115},{- "name": "Object",- "id": 116+ name: "Object",+ id: 116},{- "name": "Photo \u0026 Video",- "id": 117+ name: "Photo \u0026 Video",+ id: 117},{- "name": "Shape",- "id": 118+ name: "Shape",+ id: 118},{- "name": "Sports \u0026 Games",- "id": 119+ name: "Sports \u0026 Games",+ id: 119},{- "name": "Time",- "id": 120+ name: "Time",+ id: 120},{- "name": "Travel",- "id": 121+ name: "Travel",+ id: 121},{- "name": "User",- "id": 122+ name: "User",+ id: 122},{- "name": "Weather",- "id": 123+ name: "Weather",+ id: 123},{- "name": "Writing",- "id": 124+ name: "Writing",+ id: 124}];const icons: Icon[] = [{- "name": "child",- "slug": "child-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "child",+ slug: "child-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "balloon",- "slug": "balloon-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "balloon",+ slug: "balloon-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "coffee-bean",- "slug": "coffee-bean-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "coffee-bean",+ slug: "coffee-bean-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "pear",- "slug": "pear-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "pear",+ slug: "pear-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "sushi",- "slug": "sushi-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "sushi",+ slug: "sushi-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "sushi",- "slug": "sushi-regular",- "category_id": 108,- "type_of_icon": "REGULAR"+ name: "sushi",+ slug: "sushi-regular",+ category_id: 108,+ type_of_icon: "REGULAR"},{- "name": "shower",- "slug": "shower-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "shower",+ slug: "shower-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "shower",- "slug": "shower-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "shower",+ slug: "shower-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "typescript",- "slug": "typescript-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "typescript",+ slug: "typescript-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "graphql",- "slug": "graphql-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "graphql",+ slug: "graphql-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "rfid",- "slug": "rfid-regular",- "category_id": 115,- "type_of_icon": "REGULAR"+ name: "rfid",+ slug: "rfid-regular",+ category_id: 115,+ type_of_icon: "REGULAR"},{- "name": "universal-access",- "slug": "universal-access-solid",- "category_id": 94,- "type_of_icon": "SOLID"+ name: "universal-access",+ slug: "universal-access-solid",+ category_id: 94,+ type_of_icon: "SOLID"},{- "name": "universal-access",- "slug": "universal-access-regular",- "category_id": 94,- "type_of_icon": "REGULAR"+ name: "universal-access",+ slug: "universal-access-regular",+ category_id: 94,+ type_of_icon: "REGULAR"},{- "name": "castle",- "slug": "castle-solid",- "category_id": 98,- "type_of_icon": "SOLID",- "term": [- "fort",- "secure"- ]+ name: "castle",+ slug: "castle-solid",+ category_id: 98,+ type_of_icon: "SOLID",+ term: ["fort", "secure"]},{- "name": "shield-minus",- "slug": "shield-minus-solid",- "category_id": 100,- "type_of_icon": "SOLID"+ name: "shield-minus",+ slug: "shield-minus-solid",+ category_id: 100,+ type_of_icon: "SOLID"},{- "name": "shield-minus",- "slug": "shield-minus-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "shield-minus",+ slug: "shield-minus-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "shield-plus",- "slug": "shield-plus-solid",- "category_id": 100,- "type_of_icon": "SOLID"+ name: "shield-plus",+ slug: "shield-plus-solid",+ category_id: 100,+ type_of_icon: "SOLID"},{- "name": "shield-plus",- "slug": "shield-plus-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "shield-plus",+ slug: "shield-plus-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "vertical-bottom",- "slug": "vertical-bottom-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "vertical-bottom",+ slug: "vertical-bottom-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "vertical-top",- "slug": "vertical-top-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "vertical-top",+ slug: "vertical-top-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "horizontal-right",- "slug": "horizontal-right-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "horizontal-right",+ slug: "horizontal-right-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "horizontal-left",- "slug": "horizontal-left-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "horizontal-left",+ slug: "horizontal-left-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "objects-vertical-bottom",- "slug": "objects-vertical-bottom-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "objects-vertical-bottom",+ slug: "objects-vertical-bottom-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "objects-vertical-bottom",- "slug": "objects-vertical-bottom-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "objects-vertical-bottom",+ slug: "objects-vertical-bottom-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "objects-vertical-center",- "slug": "objects-vertical-center-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "objects-vertical-center",+ slug: "objects-vertical-center-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "objects-vertical-center",- "slug": "objects-vertical-center-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "objects-vertical-center",+ slug: "objects-vertical-center-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "objects-vertical-top",- "slug": "objects-vertical-top-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "objects-vertical-top",+ slug: "objects-vertical-top-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "objects-vertical-top",- "slug": "objects-vertical-top-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "objects-vertical-top",+ slug: "objects-vertical-top-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "objects-horizontal-right",- "slug": "objects-horizontal-right-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "objects-horizontal-right",+ slug: "objects-horizontal-right-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "objects-horizontal-right",- "slug": "objects-horizontal-right-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "objects-horizontal-right",+ slug: "objects-horizontal-right-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "objects-horizontal-center",- "slug": "objects-horizontal-center-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "objects-horizontal-center",+ slug: "objects-horizontal-center-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "objects-horizontal-center",- "slug": "objects-horizontal-center-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "objects-horizontal-center",+ slug: "objects-horizontal-center-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "objects-horizontal-left",- "slug": "objects-horizontal-left-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "objects-horizontal-left",+ slug: "objects-horizontal-left-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "objects-horizontal-left",- "slug": "objects-horizontal-left-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "objects-horizontal-left",+ slug: "objects-horizontal-left-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "color",- "slug": "color-solid",- "category_id": 102,- "type_of_icon": "SOLID",- "term": [- "palette",- "wheel"- ]+ name: "color",+ slug: "color-solid",+ category_id: 102,+ type_of_icon: "SOLID",+ term: ["palette", "wheel"]},{- "name": "color",- "slug": "color-regular",- "category_id": 102,- "type_of_icon": "REGULAR",- "term": [- "palette",- "wheel"- ]+ name: "color",+ slug: "color-regular",+ category_id: 102,+ type_of_icon: "REGULAR",+ term: ["palette", "wheel"]},{- "name": "reflect-horizontal",- "slug": "reflect-horizontal-regular",- "category_id": 111,- "type_of_icon": "REGULAR",- "term": [- "flip"- ]+ name: "reflect-horizontal",+ slug: "reflect-horizontal-regular",+ category_id: 111,+ type_of_icon: "REGULAR",+ term: ["flip"]},{- "name": "reflect-vertical",- "slug": "reflect-vertical-regular",- "category_id": 111,- "type_of_icon": "REGULAR",- "term": [- "flip"- ]+ name: "reflect-vertical",+ slug: "reflect-vertical-regular",+ category_id: 111,+ type_of_icon: "REGULAR",+ term: ["flip"]},{- "name": "postgresql",- "slug": "postgresql-logo",- "category_id": 100,- "type_of_icon": "LOGO",- "term": [- "database",- "db",- "sql"- ]- },- {- "name": "mongodb",- "slug": "mongodb-logo",- "category_id": 100,- "type_of_icon": "LOGO",- "term": [- "database",- "db"- ]- },- {- "name": "deezer",- "slug": "deezer-logo",- "category_id": 114,- "type_of_icon": "LOGO",- "term": [- "music"- ]- },- {- "name": "xing",- "slug": "xing-logo",- "category_id": 97,- "type_of_icon": "LOGO",- "term": [- "search"- ]- },- {- "name": "cart-add",- "slug": "cart-add-regular",- "category_id": 104,- "type_of_icon": "REGULAR",- "term": [- "buy"- ]- },- {- "name": "cart-download",- "slug": "cart-download-regular",- "category_id": 104,- "type_of_icon": "REGULAR",- "term": [- "buy"- ]- },- {- "name": "no-signal",- "slug": "no-signal-regular",- "category_id": 115,- "type_of_icon": "REGULAR",- "term": [- "network",- "connection"- ]- },- {- "name": "signal-5",- "slug": "signal-5-regular",- "category_id": 115,- "type_of_icon": "REGULAR",- "term": [- "network",- "connection"- ]- },- {- "name": "signal-4",- "slug": "signal-4-regular",- "category_id": 115,- "type_of_icon": "REGULAR",- "term": [- "network",- "connection"- ]- },- {- "name": "signal-3",- "slug": "signal-3-regular",- "category_id": 115,- "type_of_icon": "REGULAR",- "term": [- "network",- "connection"- ]- },- {- "name": "signal-2",- "slug": "signal-2-regular",- "category_id": 115,- "type_of_icon": "REGULAR",- "term": [- "network",- "connection"- ]- },- {- "name": "signal-1",- "slug": "signal-1-regular",- "category_id": 115,- "type_of_icon": "REGULAR",- "term": [- "network",- "connection"- ]- },- {- "name": "cheese",- "slug": "cheese-solid",- "category_id": 108,- "type_of_icon": "SOLID"- },- {- "name": "cheese",- "slug": "cheese-regular",- "category_id": 108,- "type_of_icon": "REGULAR"- },- {- "name": "hard-hat",- "slug": "hard-hat-solid",- "category_id": 98,- "type_of_icon": "SOLID",- "term": [- "construction",- "worker",- "labour"- ]- },- {- "name": "hard-hat",- "slug": "hard-hat-regular",- "category_id": 98,- "type_of_icon": "REGULAR",- "term": [- "construction",- "worker",- "labour"- ]- },- {- "name": "home-alt-2",- "slug": "home-alt-2-solid",- "category_id": 98,- "type_of_icon": "SOLID"- },- {- "name": "home-alt-2",- "slug": "home-alt-2-regular",- "category_id": 98,- "type_of_icon": "REGULAR"- },- {- "name": "meta",- "slug": "meta-logo",- "category_id": 97,- "type_of_icon": "LOGO",- "term": [- "facebook",- "social media"- ]- },- {- "name": "lemon",- "slug": "lemon-solid",- "category_id": 108,- "type_of_icon": "SOLID",- "term": [- "lime",- "fruit",- "vegetable"- ]- },- {- "name": "lemon",- "slug": "lemon-regular",- "category_id": 108,- "type_of_icon": "REGULAR",- "term": [- "lime",- "fruit",- "vegetable"- ]- },- {- "name": "cable-car",- "slug": "cable-car-solid",- "category_id": 121,- "type_of_icon": "SOLID",- "term": [- "transportation",- "hill",- "travel"- ]- },- {- "name": "cable-car",- "slug": "cable-car-regular",- "category_id": 121,- "type_of_icon": "REGULAR",- "term": [- "transportation",- "hill",- "travel"- ]- },- {- "name": "cricket-ball",- "slug": "cricket-ball-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "sport"- ]- },- {- "name": "cricket-ball",- "slug": "cricket-ball-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "sport"- ]- },- {- "name": "tree-alt",- "slug": "tree-alt-solid",- "category_id": 121,- "type_of_icon": "SOLID",- "term": [- "forest",- "christmas"- ]- },- {- "name": "male-female",- "slug": "male-female-regular",- "category_id": 122,- "type_of_icon": "REGULAR"- },- {- "name": "invader",- "slug": "invader-solid",- "category_id": 119,- "type_of_icon": "SOLID"- },- {- "name": "baguette",- "slug": "baguette-solid",- "category_id": 108,- "type_of_icon": "SOLID",- "term": [- "bread",- "bake",- "baking",- "food",- "nutrition"- ]- },- {- "name": "baguette",- "slug": "baguette-regular",- "category_id": 108,- "type_of_icon": "REGULAR",- "term": [- "bread",- "bake",- "baking",- "food",- "nutrition"- ]- },- {- "name": "fork",- "slug": "fork-regular",- "category_id": 108,- "type_of_icon": "REGULAR",- "term": [- "utensil",- "restaurant"- ]- },- {- "name": "knife",- "slug": "knife-regular",- "category_id": 108,- "type_of_icon": "REGULAR",- "term": [- "utensil",- "restaurant"- ]- },- {- "name": "circle-half",- "slug": "circle-half-solid",- "category_id": 118,- "type_of_icon": "SOLID"- },- {- "name": "circle-half",- "slug": "circle-half-regular",- "category_id": 118,- "type_of_icon": "REGULAR"- },- {- "name": "circle-three-quarter",- "slug": "circle-three-quarter-solid",- "category_id": 118,- "type_of_icon": "SOLID"- },- {- "name": "circle-three-quarter",- "slug": "circle-three-quarter-regular",- "category_id": 118,- "type_of_icon": "REGULAR"- },- {- "name": "circle-quarter",- "slug": "circle-quarter-solid",- "category_id": 118,- "type_of_icon": "SOLID"- },- {- "name": "circle-quarter",- "slug": "circle-quarter-regular",- "category_id": 118,- "type_of_icon": "REGULAR"- },- {- "name": "bowl-rice",- "slug": "bowl-rice-solid",- "category_id": 108,- "type_of_icon": "SOLID",- "term": [- "food"- ]- },- {- "name": "bowl-rice",- "slug": "bowl-rice-regular",- "category_id": 108,- "type_of_icon": "REGULAR",- "term": [- "food"- ]- },- {- "name": "bowl-hot",- "slug": "bowl-hot-solid",- "category_id": 108,- "type_of_icon": "SOLID",- "term": [- "food",- "heat"- ]- },- {- "name": "bowl-hot",- "slug": "bowl-hot-regular",- "category_id": 108,- "type_of_icon": "REGULAR",- "term": [- "food",- "heat"- ]- },- {- "name": "popsicle",- "slug": "popsicle-solid",- "category_id": 108,- "type_of_icon": "SOLID",- "term": [- "ice cream",- "dessert"- ]- },+ name: "postgresql",+ slug: "postgresql-logo",+ category_id: 100,+ type_of_icon: "LOGO",+ term: ["database", "db", "sql"]+ },+ {+ name: "mongodb",+ slug: "mongodb-logo",+ category_id: 100,+ type_of_icon: "LOGO",+ term: ["database", "db"]+ },+ {+ name: "deezer",+ slug: "deezer-logo",+ category_id: 114,+ type_of_icon: "LOGO",+ term: ["music"]+ },+ {+ name: "xing",+ slug: "xing-logo",+ category_id: 97,+ type_of_icon: "LOGO",+ term: ["search"]+ },+ {+ name: "cart-add",+ slug: "cart-add-regular",+ category_id: 104,+ type_of_icon: "REGULAR",+ term: ["buy"]+ },+ {+ name: "cart-download",+ slug: "cart-download-regular",+ category_id: 104,+ type_of_icon: "REGULAR",+ term: ["buy"]+ },+ {+ name: "no-signal",+ slug: "no-signal-regular",+ category_id: 115,+ type_of_icon: "REGULAR",+ term: ["network", "connection"]+ },+ {+ name: "signal-5",+ slug: "signal-5-regular",+ category_id: 115,+ type_of_icon: "REGULAR",+ term: ["network", "connection"]+ },+ {+ name: "signal-4",+ slug: "signal-4-regular",+ category_id: 115,+ type_of_icon: "REGULAR",+ term: ["network", "connection"]+ },+ {+ name: "signal-3",+ slug: "signal-3-regular",+ category_id: 115,+ type_of_icon: "REGULAR",+ term: ["network", "connection"]+ },+ {+ name: "signal-2",+ slug: "signal-2-regular",+ category_id: 115,+ type_of_icon: "REGULAR",+ term: ["network", "connection"]+ },+ {+ name: "signal-1",+ slug: "signal-1-regular",+ category_id: 115,+ type_of_icon: "REGULAR",+ term: ["network", "connection"]+ },+ {+ name: "cheese",+ slug: "cheese-solid",+ category_id: 108,+ type_of_icon: "SOLID"+ },+ {+ name: "cheese",+ slug: "cheese-regular",+ category_id: 108,+ type_of_icon: "REGULAR"+ },+ {+ name: "hard-hat",+ slug: "hard-hat-solid",+ category_id: 98,+ type_of_icon: "SOLID",+ term: ["construction", "worker", "labour"]+ },+ {+ name: "hard-hat",+ slug: "hard-hat-regular",+ category_id: 98,+ type_of_icon: "REGULAR",+ term: ["construction", "worker", "labour"]+ },+ {+ name: "home-alt-2",+ slug: "home-alt-2-solid",+ category_id: 98,+ type_of_icon: "SOLID"+ },+ {+ name: "home-alt-2",+ slug: "home-alt-2-regular",+ category_id: 98,+ type_of_icon: "REGULAR"+ },+ {+ name: "meta",+ slug: "meta-logo",+ category_id: 97,+ type_of_icon: "LOGO",+ term: ["facebook", "social media"]+ },+ {+ name: "lemon",+ slug: "lemon-solid",+ category_id: 108,+ type_of_icon: "SOLID",+ term: ["lime", "fruit", "vegetable"]+ },+ {+ name: "lemon",+ slug: "lemon-regular",+ category_id: 108,+ type_of_icon: "REGULAR",+ term: ["lime", "fruit", "vegetable"]+ },+ {+ name: "cable-car",+ slug: "cable-car-solid",+ category_id: 121,+ type_of_icon: "SOLID",+ term: ["transportation", "hill", "travel"]+ },+ {+ name: "cable-car",+ slug: "cable-car-regular",+ category_id: 121,+ type_of_icon: "REGULAR",+ term: ["transportation", "hill", "travel"]+ },+ {+ name: "cricket-ball",+ slug: "cricket-ball-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["sport"]+ },+ {+ name: "cricket-ball",+ slug: "cricket-ball-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["sport"]+ },+ {+ name: "tree-alt",+ slug: "tree-alt-solid",+ category_id: 121,+ type_of_icon: "SOLID",+ term: ["forest", "christmas"]+ },+ {+ name: "male-female",+ slug: "male-female-regular",+ category_id: 122,+ type_of_icon: "REGULAR"+ },+ {+ name: "invader",+ slug: "invader-solid",+ category_id: 119,+ type_of_icon: "SOLID"+ },+ {+ name: "baguette",+ slug: "baguette-solid",+ category_id: 108,+ type_of_icon: "SOLID",+ term: ["bread", "bake", "baking", "food", "nutrition"]+ },+ {+ name: "baguette",+ slug: "baguette-regular",+ category_id: 108,+ type_of_icon: "REGULAR",+ term: ["bread", "bake", "baking", "food", "nutrition"]+ },+ {+ name: "fork",+ slug: "fork-regular",+ category_id: 108,+ type_of_icon: "REGULAR",+ term: ["utensil", "restaurant"]+ },+ {+ name: "knife",+ slug: "knife-regular",+ category_id: 108,+ type_of_icon: "REGULAR",+ term: ["utensil", "restaurant"]+ },+ {+ name: "circle-half",+ slug: "circle-half-solid",+ category_id: 118,+ type_of_icon: "SOLID"+ },+ {+ name: "circle-half",+ slug: "circle-half-regular",+ category_id: 118,+ type_of_icon: "REGULAR"+ },+ {+ name: "circle-three-quarter",+ slug: "circle-three-quarter-solid",+ category_id: 118,+ type_of_icon: "SOLID"+ },+ {+ name: "circle-three-quarter",+ slug: "circle-three-quarter-regular",+ category_id: 118,+ type_of_icon: "REGULAR"+ },+ {+ name: "circle-quarter",+ slug: "circle-quarter-solid",+ category_id: 118,+ type_of_icon: "SOLID"+ },+ {+ name: "circle-quarter",+ slug: "circle-quarter-regular",+ category_id: 118,+ type_of_icon: "REGULAR"+ },+ {+ name: "bowl-rice",+ slug: "bowl-rice-solid",+ category_id: 108,+ type_of_icon: "SOLID",+ term: ["food"]+ },+ {+ name: "bowl-rice",+ slug: "bowl-rice-regular",+ category_id: 108,+ type_of_icon: "REGULAR",+ term: ["food"]+ },+ {+ name: "bowl-hot",+ slug: "bowl-hot-solid",+ category_id: 108,+ type_of_icon: "SOLID",+ term: ["food", "heat"]+ },+ {+ name: "bowl-hot",+ slug: "bowl-hot-regular",+ category_id: 108,+ type_of_icon: "REGULAR",+ term: ["food", "heat"]+ },+ {+ name: "popsicle",+ slug: "popsicle-solid",+ category_id: 108,+ type_of_icon: "SOLID",+ term: ["ice cream", "dessert"]+ },+ {+ name: "popsicle",+ slug: "popsicle-regular",+ category_id: 108,+ type_of_icon: "REGULAR",+ term: ["ice cream", "dessert"]+ },+ {+ name: "cross",+ slug: "cross-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["gaming", "crosshair", "aim"]+ },+ {+ name: "scatter-chart",+ slug: "scatter-chart-regular",+ category_id: 99,+ type_of_icon: "REGULAR"+ },+ {+ name: "money-withdraw",+ slug: "money-withdraw-regular",+ category_id: 107,+ type_of_icon: "REGULAR",+ term: ["atm"]+ },+ {+ name: "candles",+ slug: "candles-regular",+ category_id: 107,+ type_of_icon: "REGULAR",+ term: ["trading", "stock"]+ },+ {+ name: "math",+ slug: "math-regular",+ category_id: 100,+ type_of_icon: "REGULAR"+ },+ {+ name: "party",+ slug: "party-regular",+ category_id: 105,+ type_of_icon: "REGULAR",+ term: ["celebration"]+ },+ {+ name: "leaf",+ slug: "leaf-regular",+ category_id: 123,+ type_of_icon: "REGULAR",+ term: ["plant", "crop", "nature"]+ },+ {+ name: "injection",+ slug: "injection-regular",+ category_id: 109,+ type_of_icon: "REGULAR",+ term: ["syringe", "dose"]+ },+ {+ name: "expand-vertical",+ slug: "expand-vertical-regular",+ category_id: 111,+ type_of_icon: "REGULAR"+ },+ {+ name: "expand-horizontal",+ slug: "expand-horizontal-regular",+ category_id: 111,+ type_of_icon: "REGULAR"+ },+ {+ name: "collapse-vertical",+ slug: "collapse-vertical-regular",+ category_id: 111,+ type_of_icon: "REGULAR"+ },+ {+ name: "collapse-horizontal",+ slug: "collapse-horizontal-regular",+ category_id: 111,+ type_of_icon: "REGULAR"+ },+ {+ name: "collapse-alt",+ slug: "collapse-alt-regular",+ category_id: 111,+ type_of_icon: "REGULAR"+ },+ {+ name: "party",+ slug: "party-solid",+ category_id: 105,+ type_of_icon: "SOLID",+ term: ["celebration"]+ },+ {+ name: "leaf",+ slug: "leaf-solid",+ category_id: 123,+ type_of_icon: "SOLID",+ term: ["plant", "crop", "nature"]+ },+ {+ name: "injection",+ slug: "injection-solid",+ category_id: 109,+ type_of_icon: "SOLID",+ term: ["syringe", "dose"]+ },+ {+ name: "dog",+ slug: "dog-solid",+ category_id: 125,+ type_of_icon: "SOLID",+ term: ["pet", "canine"]+ },+ {+ name: "cat",+ slug: "cat-solid",+ category_id: 125,+ type_of_icon: "SOLID",+ term: ["pet"]+ },{- "name": "popsicle",- "slug": "popsicle-regular",- "category_id": 108,- "type_of_icon": "REGULAR",- "term": [- "ice cream",- "dessert"- ]+ name: "upwork",+ slug: "upwork-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "cross",- "slug": "cross-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "gaming",- "crosshair",- "aim"- ]+ name: "netlify",+ slug: "netlify-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "scatter-chart",- "slug": "scatter-chart-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "java",+ slug: "java-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "money-withdraw",- "slug": "money-withdraw-regular",- "category_id": 107,- "type_of_icon": "REGULAR",- "term": [- "atm"- ]- },- {- "name": "candles",- "slug": "candles-regular",- "category_id": 107,- "type_of_icon": "REGULAR",- "term": [- "trading",- "stock"- ]- },- {- "name": "math",- "slug": "math-regular",- "category_id": 100,- "type_of_icon": "REGULAR"- },- {- "name": "party",- "slug": "party-regular",- "category_id": 105,- "type_of_icon": "REGULAR",- "term": [- "celebration"- ]- },- {- "name": "leaf",- "slug": "leaf-regular",- "category_id": 123,- "type_of_icon": "REGULAR",- "term": [- "plant",- "crop",- "nature"- ]- },- {- "name": "injection",- "slug": "injection-regular",- "category_id": 109,- "type_of_icon": "REGULAR",- "term": [- "syringe",- "dose"- ]- },- {- "name": "expand-vertical",- "slug": "expand-vertical-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "heroku",+ slug: "heroku-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "expand-horizontal",- "slug": "expand-horizontal-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "go-lang",+ slug: "go-lang-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "collapse-vertical",- "slug": "collapse-vertical-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "gmail",+ slug: "gmail-logo",+ category_id: 101,+ type_of_icon: "LOGO"},{- "name": "collapse-horizontal",- "slug": "collapse-horizontal-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "flask",+ slug: "flask-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "collapse-alt",- "slug": "collapse-alt-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "99designs",+ slug: "99designs-logo",+ category_id: 102,+ type_of_icon: "LOGO"},{- "name": "party",- "slug": "party-solid",- "category_id": 105,- "type_of_icon": "SOLID",- "term": [- "celebration"- ]+ name: "venmo",+ slug: "venmo-logo",+ category_id: 107,+ type_of_icon: "LOGO"},{- "name": "leaf",- "slug": "leaf-solid",- "category_id": 123,- "type_of_icon": "SOLID",- "term": [- "plant",- "crop",- "nature"- ]+ name: "qr",+ slug: "qr-REGULAR",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "injection",- "slug": "injection-solid",- "category_id": 109,- "type_of_icon": "SOLID",- "term": [- "syringe",- "dose"- ]+ name: "qr-scan",+ slug: "qr-scan-logo",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "dog",- "slug": "dog-solid",- "category_id": 125,- "type_of_icon": "SOLID",- "term": [- "pet",- "canine"- ]+ name: "docker",+ slug: "docker-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "cat",- "slug": "cat-solid",- "category_id": 125,- "type_of_icon": "SOLID",- "term": [- "pet"- ]+ name: "aws",+ slug: "aws-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "upwork",- "slug": "upwork-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "hand",+ slug: "hand",+ category_id: 113,+ type_of_icon: "SOLID",+ term: ["palm", "stop"]},{- "name": "netlify",- "slug": "netlify-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "podcast",+ slug: "podcast-regular",+ category_id: 114,+ type_of_icon: "REGULAR",+ term: ["audiobook", "radio"]},{- "name": "java",- "slug": "java-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "checkbox-minus",+ slug: "checkbox-minus-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "heroku",- "slug": "heroku-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "checkbox-minus",+ slug: "checkbox-minus-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "go-lang",- "slug": "go-lang-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "speaker",+ slug: "speaker-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "gmail",- "slug": "gmail-logo",- "category_id": 101,- "type_of_icon": "LOGO"+ name: "speaker",+ slug: "speaker-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "flask",- "slug": "flask-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "registered",+ slug: "registered-solid",+ category_id: 97,+ type_of_icon: "SOLID"},{- "name": "99designs",- "slug": "99designs-logo",- "category_id": 102,- "type_of_icon": "LOGO"+ name: "registered",+ slug: "registered-regular",+ category_id: 97,+ type_of_icon: "REGULAR"},{- "name": "venmo",- "slug": "venmo-logo",- "category_id": 107,- "type_of_icon": "LOGO"+ name: "phone-off",+ slug: "phone-off-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "qr",- "slug": "qr-REGULAR",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "phone-off",+ slug: "phone-off-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "qr-scan",- "slug": "qr-scan-logo",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "tiktok",+ slug: "tiktok-logo",+ category_id: 97,+ type_of_icon: "LOGO",+ term: ["social media", "entertainment"]},{- "name": "docker",- "slug": "docker-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "sketch",+ slug: "sketch-logo",+ category_id: 97,+ type_of_icon: "LOGO",+ term: ["web design"]},{- "name": "aws",- "slug": "aws-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "steam",+ slug: "steam-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "hand",- "slug": "hand",- "category_id": 113,- "type_of_icon": "SOLID",- "term": [- "palm",- "stop"- ]+ name: "trip-advisor",+ slug: "trip-advisor-logo",+ category_id: 97,+ type_of_icon: "LOGO",+ term: ["travel"]},{- "name": "podcast",- "slug": "podcast-regular",- "category_id": 114,- "type_of_icon": "REGULAR",- "term": [- "audiobook",- "radio"- ]+ name: "visual-studio",+ slug: "visual-studio-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "checkbox-minus",- "slug": "checkbox-minus-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "unity",+ slug: "unity-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "checkbox-minus",- "slug": "checkbox-minus-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "php",+ slug: "php-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "speaker",- "slug": "speaker-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "discord-alt",+ slug: "discord-alt-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "speaker",- "slug": "speaker-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "flutter",+ slug: "flutter-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "registered",- "slug": "registered-solid",- "category_id": 97,- "type_of_icon": "SOLID"+ name: "mastodon",+ slug: "mastodon-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "registered",- "slug": "registered-regular",- "category_id": 97,- "type_of_icon": "REGULAR"+ name: "tailwind-css",+ slug: "tailwind-css-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "phone-off",- "slug": "phone-off-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "buildings",+ slug: "buildings-regular",+ category_id: 98,+ type_of_icon: "REGULAR",+ term: ["city", "colony", "skyline", "skyscrapers"]},{- "name": "phone-off",- "slug": "phone-off-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "buildings",+ slug: "buildings-solid",+ category_id: 98,+ type_of_icon: "SOLID",+ term: ["city", "colony", "skyline", "skyscrapers"]},{- "name": "tiktok",- "slug": "tiktok-logo",- "category_id": 97,- "type_of_icon": "LOGO",- "term": [- "social media",- "entertainment"- ]+ name: "store-alt",+ slug: "store-alt-regular",+ category_id: 104,+ type_of_icon: "REGULAR",+ term: ["shop", "market"]},{- "name": "sketch",- "slug": "sketch-logo",- "category_id": 97,- "type_of_icon": "LOGO",- "term": [- "web design"- ]+ name: "store-alt",+ slug: "store-alt-solid",+ category_id: 104,+ type_of_icon: "SOLID",+ term: ["shop", "market"]},{- "name": "steam",- "slug": "steam-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "bar-chart-alt-2",+ slug: "bar-chart-alt-2-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "trip-advisor",- "slug": "trip-advisor-logo",- "category_id": 97,- "type_of_icon": "LOGO",- "term": [- "travel"- ]+ name: "bar-chart-alt-2",+ slug: "bar-chart-alt-2-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "visual-studio",- "slug": "visual-studio-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "message-dots",+ slug: "message-dots-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["loading", "chat", "comment"]},{- "name": "unity",- "slug": "unity-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "message-dots",+ slug: "message-dots-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["loading", "chat", "comment"]},{- "name": "php",- "slug": "php-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "message-rounded-dots",+ slug: "message-rounded-dots-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["loading", "chat", "comment"]},{- "name": "discord-alt",- "slug": "discord-alt-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "message-rounded-dots",+ slug: "message-rounded-dots-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["loading", "chat", "comment"]},{- "name": "flutter",- "slug": "flutter-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "devices",+ slug: "devices-solid",+ category_id: 103,+ type_of_icon: "SOLID",+ term: ["mobile", "tab"]},{- "name": "mastodon",- "slug": "mastodon-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "memory-card",+ slug: "memory-card-regular",+ category_id: 103,+ type_of_icon: "REGULAR",+ term: ["sd card", "storage"]},{- "name": "tailwind-css",- "slug": "tailwind-css-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "memory-card",+ slug: "memory-card-solid",+ category_id: 103,+ type_of_icon: "SOLID",+ term: ["sd card", "storage"]},{- "name": "buildings",- "slug": "buildings-regular",- "category_id": 98,- "type_of_icon": "REGULAR",- "term": [- "city",- "colony",- "skyline",- "skyscrapers"- ]+ name: "wallet-alt",+ slug: "wallet-alt-regular",+ category_id: 107,+ type_of_icon: "REGULAR",+ term: ["money"]},- {- "name": "buildings",- "slug": "buildings-solid",- "category_id": 98,- "type_of_icon": "SOLID",- "term": [- "city",- "colony",- "skyline",- "skyscrapers"- ]- },- {- "name": "store-alt",- "slug": "store-alt-regular",- "category_id": 104,- "type_of_icon": "REGULAR",- "term": [- "shop",- "market"- ]- },- {- "name": "store-alt",- "slug": "store-alt-solid",- "category_id": 104,- "type_of_icon": "SOLID",- "term": [- "shop",- "market"- ]- },- {- "name": "bar-chart-alt-2",- "slug": "bar-chart-alt-2-regular",- "category_id": 99,- "type_of_icon": "REGULAR"- },- {- "name": "bar-chart-alt-2",- "slug": "bar-chart-alt-2-solid",- "category_id": 99,- "type_of_icon": "SOLID"- },- {- "name": "message-dots",- "slug": "message-dots-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "loading",- "chat",- "comment"- ]- },- {- "name": "message-dots",- "slug": "message-dots-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "loading",- "chat",- "comment"- ]- },- {- "name": "message-rounded-dots",- "slug": "message-rounded-dots-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "loading",- "chat",- "comment"- ]- },- {- "name": "message-rounded-dots",- "slug": "message-rounded-dots-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "loading",- "chat",- "comment"- ]- },- {- "name": "devices",- "slug": "devices-solid",- "category_id": 103,- "type_of_icon": "SOLID",- "term": [- "mobile",- "tab"- ]- },- {- "name": "memory-card",- "slug": "memory-card-regular",- "category_id": 103,- "type_of_icon": "REGULAR",- "term": [- "sd card",- "storage"- ]- },- {- "name": "memory-card",- "slug": "memory-card-solid",- "category_id": 103,- "type_of_icon": "SOLID",- "term": [- "sd card",- "storage"- ]- },- {- "name": "wallet-alt",- "slug": "wallet-alt-regular",- "category_id": 107,- "type_of_icon": "REGULAR",- "term": [- "money"- ]- },- {- "name": "wallet-alt",- "slug": "wallet-alt-solid",- "category_id": 107,- "type_of_icon": "SOLID",- "term": [- "money"- ]- },- {- "name": "bank",- "slug": "bank-solid",- "category_id": 98,- "type_of_icon": "SOLID",- "term": [- "institution",- "money",- "safe"- ]- },- {- "name": "slideshow",- "slug": "slideshow-regular",- "category_id": 99,- "type_of_icon": "REGULAR",- "term": [- "presentation",- "keynote"- ]- },- {- "name": "slideshow",- "slug": "slideshow-solid",- "category_id": 99,- "type_of_icon": "SOLID",- "term": [- "presentation",- "keynote"- ]- },- {- "name": "message-square",- "slug": "message-square-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-square-dots",- "slug": "message-square-dots-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "loading",- "chat",- "comment"- ]- },- {- "name": "message-square",- "slug": "message-square-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-square-dots",- "slug": "message-square-dots-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "loading",- "chat",- "comment"- ]- },- {- "name": "book-content",- "slug": "book-content-regular",- "category_id": 124,- "type_of_icon": "REGULAR"- },- {- "name": "book-content",- "slug": "book-content-solid",- "category_id": 124,- "type_of_icon": "SOLID"- },- {- "name": "chat",- "slug": "chat-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "discussion",- "talk",- "comments",- "messages"- ]- },- {- "name": "chat",- "slug": "chat-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "discussion",- "talk",- "comments",- "messages"- ]- },- {- "name": "edit-alt",- "slug": "edit-alt-regular",- "category_id": 124,- "type_of_icon": "REGULAR",- "term": [- "writing",- "note",- "pencil"- ]- },- {- "name": "edit-alt",- "slug": "edit-alt-solid",- "category_id": 124,- "type_of_icon": "SOLID",- "term": [- "writing",- "note",- "pencil"- ]- },- {- "name": "mouse-alt",- "slug": "mouse-alt-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ {+ name: "wallet-alt",+ slug: "wallet-alt-solid",+ category_id: 107,+ type_of_icon: "SOLID",+ term: ["money"]+ },+ {+ name: "bank",+ slug: "bank-solid",+ category_id: 98,+ type_of_icon: "SOLID",+ term: ["institution", "money", "safe"]},{- "name": "mouse-alt",- "slug": "mouse-alt-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "slideshow",+ slug: "slideshow-regular",+ category_id: 99,+ type_of_icon: "REGULAR",+ term: ["presentation", "keynote"]},{- "name": "bug-alt",- "slug": "bug-alt-regular",- "category_id": 100,- "type_of_icon": "REGULAR",- "term": [- "error",- "warning"- ]+ name: "slideshow",+ slug: "slideshow-solid",+ category_id: 99,+ type_of_icon: "SOLID",+ term: ["presentation", "keynote"]},{- "name": "bug-alt",- "slug": "bug-alt-solid",- "category_id": 100,- "type_of_icon": "SOLID",- "term": [- "error",- "warning"- ]+ name: "message-square",+ slug: "message-square-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "notepad",- "slug": "notepad-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "message-square-dots",+ slug: "message-square-dots-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["loading", "chat", "comment"]},{- "name": "notepad",- "slug": "notepad-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "message-square",+ slug: "message-square-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "video-recording",- "slug": "video-recording-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "message-square-dots",+ slug: "message-square-dots-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["loading", "chat", "comment"]},{- "name": "video-recording",- "slug": "video-recording-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "book-content",+ slug: "book-content-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "shape-square",- "slug": "shape-square-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "book-content",+ slug: "book-content-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "shape-triangle",- "slug": "shape-triangle-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "chat",+ slug: "chat-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["discussion", "talk", "comments", "messages"]},{- "name": "direction-left",- "slug": "direction-left-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "chat",+ slug: "chat-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["discussion", "talk", "comments", "messages"]},{- "name": "ghost",- "slug": "ghost-regular",- "category_id": 105,- "type_of_icon": "REGULAR",- "term": [- "spooky",- "horror",- "scary"- ]+ name: "edit-alt",+ slug: "edit-alt-regular",+ category_id: 124,+ type_of_icon: "REGULAR",+ term: ["writing", "note", "pencil"]},{- "name": "ghost",- "slug": "ghost-solid",- "category_id": 105,- "type_of_icon": "SOLID",- "term": [- "spooky",- "horror",- "scary"- ]+ name: "edit-alt",+ slug: "edit-alt-solid",+ category_id: 124,+ type_of_icon: "SOLID",+ term: ["writing", "note", "pencil"]},{- "name": "mail-send",- "slug": "mail-send-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "mouse-alt",+ slug: "mouse-alt-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "code-alt",- "slug": "code-alt-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "mouse-alt",+ slug: "mouse-alt-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "grid",- "slug": "grid-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "bug-alt",+ slug: "bug-alt-regular",+ category_id: 100,+ type_of_icon: "REGULAR",+ term: ["error", "warning"]},{- "name": "quote-single-left",- "slug": "quote-single-left-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "bug-alt",+ slug: "bug-alt-solid",+ category_id: 100,+ type_of_icon: "SOLID",+ term: ["error", "warning"]},{- "name": "quote-single-right",- "slug": "quote-single-right-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "notepad",+ slug: "notepad-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "user-pin",- "slug": "user-pin-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "notepad",+ slug: "notepad-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "user-pin",- "slug": "user-pin-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "video-recording",+ slug: "video-recording-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "run",- "slug": "run-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "video-recording",+ slug: "video-recording-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "copy-alt",- "slug": "copy-alt-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "shape-square",+ slug: "shape-square-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "copy-alt",- "slug": "copy-alt-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "shape-triangle",+ slug: "shape-triangle-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "transfer-alt",- "slug": "transfer-alt-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "direction-left",+ slug: "direction-left-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "file-doc",- "slug": "file-doc-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "ghost",+ slug: "ghost-regular",+ category_id: 105,+ type_of_icon: "REGULAR",+ term: ["spooky", "horror", "scary"]},{- "name": "file-html",- "slug": "file-html-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "ghost",+ slug: "ghost-solid",+ category_id: 105,+ type_of_icon: "SOLID",+ term: ["spooky", "horror", "scary"]},{- "name": "comment-detail",- "slug": "comment-detail-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "mail-send",+ slug: "mail-send-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "comment-add",- "slug": "comment-add-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "message",- "new",- "plus"- ]+ name: "code-alt",+ slug: "code-alt-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "file-css",- "slug": "file-css-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "grid",+ slug: "grid-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "file-js",- "slug": "file-js-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "quote-single-left",+ slug: "quote-single-left-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "file-json",- "slug": "file-json-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "quote-single-right",+ slug: "quote-single-right-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "file-md",- "slug": "file-md-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "user-pin",+ slug: "user-pin-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "file-txt",- "slug": "file-txt-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "user-pin",+ slug: "user-pin-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "file-png",- "slug": "file-png-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "run",+ slug: "run-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "file-jpg",- "slug": "file-jpg-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "copy-alt",+ slug: "copy-alt-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "file-gif",- "slug": "file-gif-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "copy-alt",+ slug: "copy-alt-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "analyse",- "slug": "analyse-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "transfer-alt",+ slug: "transfer-alt-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "book-open",- "slug": "book-open-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "file-doc",+ slug: "file-doc-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "plane-take-off",- "slug": "plane-take-off-solid",- "category_id": 121,- "type_of_icon": "SOLID",- "term": [- "flight",- "fly"- ]+ name: "file-html",+ slug: "file-html-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "plane-land",- "slug": "plane-land-solid",- "category_id": 121,- "type_of_icon": "SOLID",- "term": [- "flight",- "fly",- "landing"- ]+ name: "comment-detail",+ slug: "comment-detail-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "parking",- "slug": "parking-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "comment-add",+ slug: "comment-add-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "message", "new", "plus"]},{- "name": "id-card",- "slug": "id-card-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "file-css",+ slug: "file-css-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "adjust-alt",- "slug": "adjust-alt-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "file-js",+ slug: "file-js-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "landscape",- "slug": "landscape-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "file-json",+ slug: "file-json-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "landscape",- "slug": "landscape-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "file-md",+ slug: "file-md-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "traffic",- "slug": "traffic-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "file-txt",+ slug: "file-txt-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "comment",- "slug": "comment-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "file-png",+ slug: "file-png-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "comment",- "slug": "comment-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "file-jpg",+ slug: "file-jpg-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "comment-dots",- "slug": "comment-dots-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "loading",- "message",- "chat"- ]+ name: "file-gif",+ slug: "file-gif-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "comment-dots",- "slug": "comment-dots-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "loading",- "message",- "chat"- ]+ name: "analyse",+ slug: "analyse-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "wine",- "slug": "wine-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "book-open",+ slug: "book-open-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "pyramid",- "slug": "pyramid-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "plane-take-off",+ slug: "plane-take-off-solid",+ category_id: 121,+ type_of_icon: "SOLID",+ term: ["flight", "fly"]},{- "name": "pyramid",- "slug": "pyramid-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "plane-land",+ slug: "plane-land-solid",+ category_id: 121,+ type_of_icon: "SOLID",+ term: ["flight", "fly", "landing"]},{- "name": "cylinder",- "slug": "cylinder-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "parking",+ slug: "parking-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "cylinder",- "slug": "cylinder-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "id-card",+ slug: "id-card-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "graduation",- "slug": "graduation-solid",- "category_id": 124,- "type_of_icon": "SOLID",- "term": [- "scholar",- "college"- ]+ name: "adjust-alt",+ slug: "adjust-alt-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "lock-alt",- "slug": "lock-alt-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "landscape",+ slug: "landscape-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "lock-alt",- "slug": "lock-alt-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "landscape",+ slug: "landscape-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "lock-open-alt",- "slug": "lock-open-alt-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "traffic",+ slug: "traffic-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "lock-open-alt",- "slug": "lock-open-alt-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "comment",+ slug: "comment-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "hourglass-top",- "slug": "hourglass-top-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "comment",+ slug: "comment-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "hourglass-bottom",- "slug": "hourglass-bottom-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "comment-dots",+ slug: "comment-dots-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["loading", "message", "chat"]},{- "name": "left-arrow-alt",- "slug": "left-arrow-alt-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "comment-dots",+ slug: "comment-dots-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["loading", "message", "chat"]},{- "name": "right-arrow-alt",- "slug": "right-arrow-alt-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "wine",+ slug: "wine-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "up-arrow-alt",- "slug": "up-arrow-alt-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "pyramid",+ slug: "pyramid-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "down-arrow-alt",- "slug": "down-arrow-alt-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "pyramid",+ slug: "pyramid-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "shape-circle",- "slug": "shape-circle-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "cylinder",+ slug: "cylinder-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "cycling",- "slug": "cycling-regular",- "category_id": 119,- "type_of_icon": "REGULAR"+ name: "cylinder",+ slug: "cylinder-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "dna",- "slug": "dna-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "graduation",+ slug: "graduation-solid",+ category_id: 124,+ type_of_icon: "SOLID",+ term: ["scholar", "college"]},{- "name": "bowling-ball",- "slug": "bowling-ball-regular",- "category_id": 119,- "type_of_icon": "REGULAR"+ name: "lock-alt",+ slug: "lock-alt-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "bowling-ball",- "slug": "bowling-ball-solid",- "category_id": 119,- "type_of_icon": "SOLID"+ name: "lock-alt",+ slug: "lock-alt-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "search-alt-2",- "slug": "search-alt-2-regular",- "category_id": 110,- "type_of_icon": "REGULAR",- "term": [- "magnifying glass"- ]+ name: "lock-open-alt",+ slug: "lock-open-alt-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "search-alt-2",- "slug": "search-alt-2-solid",- "category_id": 110,- "type_of_icon": "SOLID",- "term": [- "magnifying glass"- ]+ name: "lock-open-alt",+ slug: "lock-open-alt-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "plus-medical",- "slug": "plus-medical-regular",- "category_id": 109,- "type_of_icon": "REGULAR",- "term": [- "hospital",- "doctor",- "medicine"- ]+ name: "hourglass-top",+ slug: "hourglass-top-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "street-view",- "slug": "street-view-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "hourglass-bottom",+ slug: "hourglass-bottom-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "droplet",- "slug": "droplet-regular",- "category_id": 123,- "type_of_icon": "REGULAR"+ name: "left-arrow-alt",+ slug: "left-arrow-alt-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "droplet-half",- "slug": "droplet-half-solid",- "category_id": 102,- "type_of_icon": "SOLID"+ name: "right-arrow-alt",+ slug: "right-arrow-alt-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "paint-roll",- "slug": "paint-roll-regular",- "category_id": 102,- "type_of_icon": "REGULAR"+ name: "up-arrow-alt",+ slug: "up-arrow-alt-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "paint-roll",- "slug": "paint-roll-solid",- "category_id": 102,- "type_of_icon": "SOLID"+ name: "down-arrow-alt",+ slug: "down-arrow-alt-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "shield-alt-2",- "slug": "shield-alt-2-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "shape-circle",+ slug: "shape-circle-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "shield-alt-2",- "slug": "shield-alt-2-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "cycling",+ slug: "cycling-regular",+ category_id: 119,+ type_of_icon: "REGULAR"},{- "name": "error-alt",- "slug": "error-alt-regular",- "category_id": 95,- "type_of_icon": "REGULAR"+ name: "dna",+ slug: "dna-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "error-alt",- "slug": "error-alt-solid",- "category_id": 95,- "type_of_icon": "SOLID"+ name: "bowling-ball",+ slug: "bowling-ball-regular",+ category_id: 119,+ type_of_icon: "REGULAR"},{- "name": "square",- "slug": "square-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "bowling-ball",+ slug: "bowling-ball-solid",+ category_id: 119,+ type_of_icon: "SOLID"},{- "name": "square",- "slug": "square-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "search-alt-2",+ slug: "search-alt-2-regular",+ category_id: 110,+ type_of_icon: "REGULAR",+ term: ["magnifying glass"]},{- "name": "square-rounded",- "slug": "square-rounded-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "search-alt-2",+ slug: "search-alt-2-solid",+ category_id: 110,+ type_of_icon: "SOLID",+ term: ["magnifying glass"]},{- "name": "square-rounded",- "slug": "square-rounded-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "plus-medical",+ slug: "plus-medical-regular",+ category_id: 109,+ type_of_icon: "REGULAR",+ term: ["hospital", "doctor", "medicine"]},{- "name": "polygon",- "slug": "polygon-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "street-view",+ slug: "street-view-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "polygon",- "slug": "polygon-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "droplet",+ slug: "droplet-regular",+ category_id: 123,+ type_of_icon: "REGULAR"},{- "name": "cube-alt",- "slug": "cube-alt-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "droplet-half",+ slug: "droplet-half-solid",+ category_id: 102,+ type_of_icon: "SOLID"},{- "name": "cube-alt",- "slug": "cube-alt-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "paint-roll",+ slug: "paint-roll-regular",+ category_id: 102,+ type_of_icon: "REGULAR"},{- "name": "cuboid",- "slug": "cuboid-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "paint-roll",+ slug: "paint-roll-solid",+ category_id: 102,+ type_of_icon: "SOLID"},{- "name": "cuboid",- "slug": "cuboid-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "shield-alt-2",+ slug: "shield-alt-2-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "user-voice",- "slug": "user-voice-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "shield-alt-2",+ slug: "shield-alt-2-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "user-voice",- "slug": "user-voice-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "error-alt",+ slug: "error-alt-regular",+ category_id: 95,+ type_of_icon: "REGULAR"},{- "name": "accessibility",- "slug": "accessibility-regular",- "category_id": 94,- "type_of_icon": "REGULAR",- "term": [- "handicap",- "wheelchair",- "injury"- ]+ name: "error-alt",+ slug: "error-alt-solid",+ category_id: 95,+ type_of_icon: "SOLID"},{- "name": "building-house",- "slug": "building-house-regular",- "category_id": 98,- "type_of_icon": "REGULAR"+ name: "square",+ slug: "square-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "building-house",- "slug": "building-house-solid",- "category_id": 98,- "type_of_icon": "SOLID"+ name: "square",+ slug: "square-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "doughnut-chart",- "slug": "doughnut-chart-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "square-rounded",+ slug: "square-rounded-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "doughnut-chart",- "slug": "doughnut-chart-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "square-rounded",+ slug: "square-rounded-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "circle",- "slug": "circle-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "polygon",+ slug: "polygon-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "log-in-circle",- "slug": "log-in-circle-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "polygon",+ slug: "polygon-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "log-in-circle",- "slug": "log-in-circle-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "cube-alt",+ slug: "cube-alt-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "log-out-circle",- "slug": "log-out-circle-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "cube-alt",+ slug: "cube-alt-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "log-out-circle",- "slug": "log-out-circle-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "cuboid",+ slug: "cuboid-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "log-in",- "slug": "log-in-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "cuboid",+ slug: "cuboid-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "log-out",- "slug": "log-out-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "user-voice",+ slug: "user-voice-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "notification",- "slug": "notification-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "user-voice",+ slug: "user-voice-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "notification-off",- "slug": "notification-off-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "accessibility",+ slug: "accessibility-regular",+ category_id: 94,+ type_of_icon: "REGULAR",+ term: ["handicap", "wheelchair", "injury"]},{- "name": "check-square",- "slug": "check-square-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "building-house",+ slug: "building-house-regular",+ category_id: 98,+ type_of_icon: "REGULAR"},{- "name": "check-square",- "slug": "check-square-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "building-house",+ slug: "building-house-solid",+ category_id: 98,+ type_of_icon: "SOLID"},{- "name": "message-alt",- "slug": "message-alt-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "doughnut-chart",+ slug: "doughnut-chart-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "message-alt",- "slug": "message-alt-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "doughnut-chart",+ slug: "doughnut-chart-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "message-alt-dots",- "slug": "message-alt-dots-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "loading",- "chat",- "comment"- ]+ name: "circle",+ slug: "circle-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "message-alt-dots",- "slug": "message-alt-dots-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "loading",- "chat",- "comment"- ]+ name: "log-in-circle",+ slug: "log-in-circle-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "no-entry",- "slug": "no-entry-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "log-in-circle",+ slug: "log-in-circle-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "no-entry",- "slug": "no-entry-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "log-out-circle",+ slug: "log-out-circle-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "traffic-barrier",- "slug": "traffic-barrier-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "log-out-circle",+ slug: "log-out-circle-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "component",- "slug": "component-solid",- "category_id": 100,- "type_of_icon": "SOLID"+ name: "log-in",+ slug: "log-in-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "plane-alt",- "slug": "plane-alt-solid",- "category_id": 121,- "type_of_icon": "SOLID",- "term": [- "flight",- "fly"- ]+ name: "log-out",+ slug: "log-out-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "palette",- "slug": "palette-regular",- "category_id": 102,- "type_of_icon": "REGULAR",- "term": [- "color",- "colour",- "painting"- ]+ name: "notification",+ slug: "notification-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "palette",- "slug": "palette-solid",- "category_id": 102,- "type_of_icon": "SOLID",- "term": [- "color",- "colour",- "painting"- ]+ name: "notification-off",+ slug: "notification-off-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "basket",- "slug": "basket-regular",- "category_id": 104,- "type_of_icon": "REGULAR"+ name: "check-square",+ slug: "check-square-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "basket",- "slug": "basket-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "check-square",+ slug: "check-square-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "purchase-tag-alt",- "slug": "purchase-tag-alt-regular",- "category_id": 104,- "type_of_icon": "REGULAR",- "term": [- "price",- "cost"- ]+ name: "message-alt",+ slug: "message-alt-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "purchase-tag-alt",- "slug": "purchase-tag-alt-solid",- "category_id": 104,- "type_of_icon": "SOLID",- "term": [- "price",- "cost"- ]+ name: "message-alt",+ slug: "message-alt-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "receipt",- "slug": "receipt-regular",- "category_id": 104,- "type_of_icon": "REGULAR"+ name: "message-alt-dots",+ slug: "message-alt-dots-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["loading", "chat", "comment"]},{- "name": "receipt",- "slug": "receipt-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "message-alt-dots",+ slug: "message-alt-dots-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["loading", "chat", "comment"]},{- "name": "line-chart",- "slug": "line-chart-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "no-entry",+ slug: "no-entry-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "map-pin",- "slug": "map-pin-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "no-entry",+ slug: "no-entry-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "map-pin",- "slug": "map-pin-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "traffic-barrier",+ slug: "traffic-barrier-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "hive",- "slug": "hive-regular",- "category_id": 113,- "type_of_icon": "REGULAR"+ name: "component",+ slug: "component-solid",+ category_id: 100,+ type_of_icon: "SOLID"},{- "name": "band-aid",- "slug": "band-aid-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "plane-alt",+ slug: "plane-alt-solid",+ category_id: 121,+ type_of_icon: "SOLID",+ term: ["flight", "fly"]},{- "name": "band-aid",- "slug": "band-aid-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "palette",+ slug: "palette-regular",+ category_id: 102,+ type_of_icon: "REGULAR",+ term: ["color", "colour", "painting"]},{- "name": "credit-card-alt",- "slug": "credit-card-alt-regular",- "category_id": 107,- "type_of_icon": "REGULAR",- "term": [- "finance",- "money",- "debit"- ]+ name: "palette",+ slug: "palette-solid",+ category_id: 102,+ type_of_icon: "SOLID",+ term: ["color", "colour", "painting"]},{- "name": "credit-card-alt",- "slug": "credit-card-alt-solid",- "category_id": 107,- "type_of_icon": "SOLID",- "term": [- "finance",- "money",- "debit"- ]+ name: "basket",+ slug: "basket-regular",+ category_id: 104,+ type_of_icon: "REGULAR"},{- "name": "credit-card",- "slug": "credit-card-solid",- "category_id": 107,- "type_of_icon": "SOLID",- "term": [- "finance",- "money",- "debit"- ]+ name: "basket",+ slug: "basket-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "wifi-off",- "slug": "wifi-off-regular",- "category_id": 115,- "type_of_icon": "REGULAR"+ name: "purchase-tag-alt",+ slug: "purchase-tag-alt-regular",+ category_id: 104,+ type_of_icon: "REGULAR",+ term: ["price", "cost"]},{- "name": "paint",- "slug": "paint-solid",- "category_id": 102,- "type_of_icon": "SOLID"+ name: "purchase-tag-alt",+ slug: "purchase-tag-alt-solid",+ category_id: 104,+ type_of_icon: "SOLID",+ term: ["price", "cost"]},{- "name": "brightness-half",- "slug": "brightness-half-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "receipt",+ slug: "receipt-regular",+ category_id: 104,+ type_of_icon: "REGULAR"},{- "name": "brightness-half",- "slug": "brightness-half-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "receipt",+ slug: "receipt-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "brightness",- "slug": "brightness-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "line-chart",+ slug: "line-chart-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "brightness",- "slug": "brightness-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "map-pin",+ slug: "map-pin-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "filter-alt",- "slug": "filter-alt-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "map-pin",+ slug: "map-pin-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "dialpad-alt",- "slug": "dialpad-alt-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "keypad"- ]+ name: "hive",+ slug: "hive-regular",+ category_id: 113,+ type_of_icon: "REGULAR"},{- "name": "border-right",- "slug": "border-right-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "band-aid",+ slug: "band-aid-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "border-left",- "slug": "border-left-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "band-aid",+ slug: "band-aid-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "border-top",- "slug": "border-top-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "credit-card-alt",+ slug: "credit-card-alt-regular",+ category_id: 107,+ type_of_icon: "REGULAR",+ term: ["finance", "money", "debit"]},{- "name": "border-bottom",- "slug": "border-bottom-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "credit-card-alt",+ slug: "credit-card-alt-solid",+ category_id: 107,+ type_of_icon: "SOLID",+ term: ["finance", "money", "debit"]},{- "name": "border-all",- "slug": "border-all-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "credit-card",+ slug: "credit-card-solid",+ category_id: 107,+ type_of_icon: "SOLID",+ term: ["finance", "money", "debit"]},{- "name": "mobile-landscape",- "slug": "mobile-landscape-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "wifi-off",+ slug: "wifi-off-regular",+ category_id: 115,+ type_of_icon: "REGULAR"},{- "name": "mobile-vibration",- "slug": "mobile-vibration-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "paint",+ slug: "paint-solid",+ category_id: 102,+ type_of_icon: "SOLID"},{- "name": "rectangle",- "slug": "rectangle-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "brightness-half",+ slug: "brightness-half-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "right-arrow",- "slug": "right-arrow-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "brightness-half",+ slug: "brightness-half-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "left-arrow",- "slug": "left-arrow-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "brightness",+ slug: "brightness-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "up-arrow",- "slug": "up-arrow-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "brightness",+ slug: "brightness-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "down-arrow",- "slug": "down-arrow-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "filter-alt",+ slug: "filter-alt-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "right-top-arrow-circle",- "slug": "right-top-arrow-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "dialpad-alt",+ slug: "dialpad-alt-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["keypad"]},{- "name": "right-down-arrow-circle",- "slug": "right-down-arrow-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "border-right",+ slug: "border-right-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "left-top-arrow-circle",- "slug": "left-top-arrow-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "border-left",+ slug: "border-left-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "left-down-arrow-circle",- "slug": "left-down-arrow-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "border-top",+ slug: "border-top-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "institution",- "slug": "institution-solid",- "category_id": 98,- "type_of_icon": "SOLID"+ name: "border-bottom",+ slug: "border-bottom-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "school",- "slug": "school-solid",- "category_id": 98,- "type_of_icon": "SOLID"+ name: "border-all",+ slug: "border-all-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "chalkboard",- "slug": "chalkboard-solid",- "category_id": 99,- "type_of_icon": "SOLID",- "term": [- "whiteboard",- "teaching"- ]+ name: "mobile-landscape",+ slug: "mobile-landscape-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "skip-previous-circle",- "slug": "skip-previous-circle-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "mobile-vibration",+ slug: "mobile-vibration-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "skip-next-circle",- "slug": "skip-next-circle-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "rectangle",+ slug: "rectangle-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "data",- "slug": "data-solid",- "category_id": 100,- "type_of_icon": "SOLID"+ name: "right-arrow",+ slug: "right-arrow-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "mobile",- "slug": "mobile-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "left-arrow",+ slug: "left-arrow-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "folder-minus",- "slug": "folder-minus-solid",- "category_id": 106,- "type_of_icon": "SOLID",- "term": [- "remove",- "delete"- ]+ name: "up-arrow",+ slug: "up-arrow-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "bell-plus",- "slug": "bell-plus-solid",- "category_id": 95,- "type_of_icon": "SOLID",- "term": [- "alert",- "notification"- ]+ name: "down-arrow",+ slug: "down-arrow-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "bell-minus",- "slug": "bell-minus-solid",- "category_id": 95,- "type_of_icon": "SOLID",- "term": [- "alert",- "notification"- ]+ name: "right-top-arrow-circle",+ slug: "right-top-arrow-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "search",- "slug": "search-solid",- "category_id": 110,- "type_of_icon": "SOLID",- "term": [- "magnifying glass"- ]+ name: "right-down-arrow-circle",+ slug: "right-down-arrow-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "zoom-in",- "slug": "zoom-in-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "left-top-arrow-circle",+ slug: "left-top-arrow-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "zoom-out",- "slug": "zoom-out-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "left-down-arrow-circle",+ slug: "left-down-arrow-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "grid",- "slug": "grid-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "institution",+ slug: "institution-solid",+ category_id: 98,+ type_of_icon: "SOLID"},{- "name": "user-x",- "slug": "user-x-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "school",+ slug: "school-solid",+ category_id: 98,+ type_of_icon: "SOLID"},{- "name": "user-check",- "slug": "user-check-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "chalkboard",+ slug: "chalkboard-solid",+ category_id: 99,+ type_of_icon: "SOLID",+ term: ["whiteboard", "teaching"]},{- "name": "compass",- "slug": "compass-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "skip-previous-circle",+ slug: "skip-previous-circle-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "gas-pump",- "slug": "gas-pump-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "skip-next-circle",+ slug: "skip-next-circle-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "stopwatch",- "slug": "stopwatch-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "data",+ slug: "data-solid",+ category_id: 100,+ type_of_icon: "SOLID"},{- "name": "timer",- "slug": "timer-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "mobile",+ slug: "mobile-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "time",- "slug": "time-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "folder-minus",+ slug: "folder-minus-solid",+ category_id: 106,+ type_of_icon: "SOLID",+ term: ["remove", "delete"]},{- "name": "pie-chart-alt-2",- "slug": "pie-chart-alt-2-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "bell-plus",+ slug: "bell-plus-solid",+ category_id: 95,+ type_of_icon: "SOLID",+ term: ["alert", "notification"]},{- "name": "pie-chart-alt-2",- "slug": "pie-chart-alt-2-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "bell-minus",+ slug: "bell-minus-solid",+ category_id: 95,+ type_of_icon: "SOLID",+ term: ["alert", "notification"]},{- "name": "time-five",- "slug": "time-five-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "search",+ slug: "search-solid",+ category_id: 110,+ type_of_icon: "SOLID",+ term: ["magnifying glass"]},{- "name": "time-five",- "slug": "time-five-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "zoom-in",+ slug: "zoom-in-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "instagram-alt",- "slug": "instagram-alt-logo",- "category_id": 97,- "type_of_icon": "LOGO",- "term": [- "social media"- ]+ name: "zoom-out",+ slug: "zoom-out-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "bookmarks",- "slug": "bookmarks-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "grid",+ slug: "grid-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "bookmark-minus",- "slug": "bookmark-minus-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "user-x",+ slug: "user-x-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "briefcase-alt-2",- "slug": "briefcase-alt-2-regular",- "category_id": 99,- "type_of_icon": "REGULAR",- "term": [- "work",- "travel",- "suitcase"- ]+ name: "user-check",+ slug: "user-check-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "briefcase-alt-2",- "slug": "briefcase-alt-2-solid",- "category_id": 99,- "type_of_icon": "SOLID",- "term": [- "work",- "travel",- "suitcase"- ]+ name: "compass",+ slug: "compass-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "brush-alt",- "slug": "brush-alt-regular",- "category_id": 102,- "type_of_icon": "REGULAR"+ name: "gas-pump",+ slug: "gas-pump-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "calendar",- "slug": "calendar-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "stopwatch",+ slug: "stopwatch-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "calendar-alt",- "slug": "calendar-alt-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "timer",+ slug: "timer-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "calendar-plus",- "slug": "calendar-plus-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "time",+ slug: "time-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "calendar-minus",- "slug": "calendar-minus-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "pie-chart-alt-2",+ slug: "pie-chart-alt-2-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "calendar-x",- "slug": "calendar-x-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "pie-chart-alt-2",+ slug: "pie-chart-alt-2-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "calendar-check",- "slug": "calendar-check-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "time-five",+ slug: "time-five-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "calendar-event",- "slug": "calendar-event-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "time-five",+ slug: "time-five-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "customize",- "slug": "customize-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "instagram-alt",+ slug: "instagram-alt-logo",+ category_id: 97,+ type_of_icon: "LOGO",+ term: ["social media"]},{- "name": "customize",- "slug": "customize-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "bookmarks",+ slug: "bookmarks-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "carousel",- "slug": "carousel-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "bookmark-minus",+ slug: "bookmark-minus-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "rewind-circle",- "slug": "rewind-circle-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "briefcase-alt-2",+ slug: "briefcase-alt-2-regular",+ category_id: 99,+ type_of_icon: "REGULAR",+ term: ["work", "travel", "suitcase"]},{- "name": "fast-forward-circle",- "slug": "fast-forward-circle-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "briefcase-alt-2",+ slug: "briefcase-alt-2-solid",+ category_id: 99,+ type_of_icon: "SOLID",+ term: ["work", "travel", "suitcase"]},{- "name": "mobile-vibration",- "slug": "mobile-vibration-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "brush-alt",+ slug: "brush-alt-regular",+ category_id: 102,+ type_of_icon: "REGULAR"},{- "name": "quote-alt-left",- "slug": "quote-alt-left-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "calendar",+ slug: "calendar-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "quote-alt-right",- "slug": "quote-alt-right-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "calendar-alt",+ slug: "calendar-alt-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "layout",- "slug": "layout-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "calendar-plus",+ slug: "calendar-plus-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "radio",- "slug": "radio-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "calendar-minus",+ slug: "calendar-minus-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "printer",- "slug": "printer-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "calendar-x",+ slug: "calendar-x-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "sort-a-z",- "slug": "sort-a-z-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "calendar-check",+ slug: "calendar-check-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "sort-z-a",- "slug": "sort-z-a-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "calendar-event",+ slug: "calendar-event-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "conversation",- "slug": "conversation-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "discussion"- ]+ name: "customize",+ slug: "customize-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "brush-alt",- "slug": "brush-alt-solid",- "category_id": 102,- "type_of_icon": "SOLID"+ name: "customize",+ slug: "customize-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "exit",- "slug": "exit-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "carousel",+ slug: "carousel-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "exit",- "slug": "exit-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "rewind-circle",+ slug: "rewind-circle-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "extension",- "slug": "extension-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "fast-forward-circle",+ slug: "fast-forward-circle-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "extension",- "slug": "extension-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "mobile-vibration",+ slug: "mobile-vibration-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "file-find",- "slug": "file-find-solid",- "category_id": 106,- "type_of_icon": "SOLID",- "term": [- "search"- ]+ name: "quote-alt-left",+ slug: "quote-alt-left-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "face",- "slug": "face-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "quote-alt-right",+ slug: "quote-alt-right-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "face",- "slug": "face-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "layout",+ slug: "layout-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "file-find",- "slug": "file-find-regular",- "category_id": 106,- "type_of_icon": "REGULAR",- "term": [- "search"- ]+ name: "radio",+ slug: "radio-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "label",- "slug": "label-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "printer",+ slug: "printer-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "label",- "slug": "label-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "sort-a-z",+ slug: "sort-a-z-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "check-shield",- "slug": "check-shield-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "sort-z-a",+ slug: "sort-z-a-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "check-shield",- "slug": "check-shield-solid",- "category_id": 100,- "type_of_icon": "SOLID"+ name: "conversation",+ slug: "conversation-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "discussion"]},{- "name": "border-radius",- "slug": "border-radius-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "brush-alt",+ slug: "brush-alt-solid",+ category_id: 102,+ type_of_icon: "SOLID"},{- "name": "add-to-queue",- "slug": "add-to-queue-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "exit",+ slug: "exit-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "add-to-queue",- "slug": "add-to-queue-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "exit",+ slug: "exit-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "archive-in",- "slug": "archive-in-regular",- "category_id": 106,- "type_of_icon": "REGULAR"+ name: "extension",+ slug: "extension-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "archive-in",- "slug": "archive-in-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "extension",+ slug: "extension-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "archive-out",- "slug": "archive-out-regular",- "category_id": 106,- "type_of_icon": "REGULAR"+ name: "file-find",+ slug: "file-find-solid",+ category_id: 106,+ type_of_icon: "SOLID",+ term: ["search"]},{- "name": "archive-out",- "slug": "archive-out-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "face",+ slug: "face-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "alarm-add",- "slug": "alarm-add-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "face",+ slug: "face-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "alarm-add",- "slug": "alarm-add-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "file-find",+ slug: "file-find-regular",+ category_id: 106,+ type_of_icon: "REGULAR",+ term: ["search"]},{- "name": "space-bar",- "slug": "space-bar-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "label",+ slug: "label-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "image-alt",- "slug": "image-alt-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "label",+ slug: "label-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "image-add",- "slug": "image-add-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "check-shield",+ slug: "check-shield-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "image-add",- "slug": "image-add-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "check-shield",+ slug: "check-shield-solid",+ category_id: 100,+ type_of_icon: "SOLID"},{- "name": "fridge",- "slug": "fridge-regular",- "category_id": 108,- "type_of_icon": "REGULAR"+ name: "border-radius",+ slug: "border-radius-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "fridge",- "slug": "fridge-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "add-to-queue",+ slug: "add-to-queue-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "dish",- "slug": "dish-regular",- "category_id": 108,- "type_of_icon": "REGULAR"+ name: "add-to-queue",+ slug: "add-to-queue-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "dish",- "slug": "dish-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "archive-in",+ slug: "archive-in-regular",+ category_id: 106,+ type_of_icon: "REGULAR"},{- "name": "spa",- "slug": "spa-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "archive-in",+ slug: "archive-in-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "spa",- "slug": "spa-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "archive-out",+ slug: "archive-out-regular",+ category_id: 106,+ type_of_icon: "REGULAR"},{- "name": "cake",- "slug": "cake-regular",- "category_id": 108,- "type_of_icon": "REGULAR"+ name: "archive-out",+ slug: "archive-out-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "cake",- "slug": "cake-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "alarm-add",+ slug: "alarm-add-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "city",- "slug": "city-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "alarm-add",+ slug: "alarm-add-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "bolt-circle",- "slug": "bolt-circle-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "space-bar",+ slug: "space-bar-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "bolt-circle",- "slug": "bolt-circle-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "image-alt",+ slug: "image-alt-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "tone",- "slug": "tone-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "image-add",+ slug: "image-add-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "bitcoin",- "slug": "bitcoin-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "image-add",+ slug: "image-add-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "lira",- "slug": "lira-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "fridge",+ slug: "fridge-regular",+ category_id: 108,+ type_of_icon: "REGULAR"},{- "name": "ruble",- "slug": "ruble-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "fridge",+ slug: "fridge-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "caret-up-circle",- "slug": "caret-up-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "dish",+ slug: "dish-regular",+ category_id: 108,+ type_of_icon: "REGULAR"},{- "name": "caret-down-circle",- "slug": "caret-down-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "dish",+ slug: "dish-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "caret-left-circle",- "slug": "caret-left-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "spa",+ slug: "spa-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "caret-right-circle",- "slug": "caret-right-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "spa",+ slug: "spa-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "rupee",- "slug": "rupee-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "cake",+ slug: "cake-regular",+ category_id: 108,+ type_of_icon: "REGULAR"},{- "name": "euro",- "slug": "euro-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "cake",+ slug: "cake-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "pound",- "slug": "pound-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "city",+ slug: "city-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "won",- "slug": "won-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "bolt-circle",+ slug: "bolt-circle-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "yen",- "slug": "yen-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "bolt-circle",+ slug: "bolt-circle-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "shekel",- "slug": "shekel-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "tone",+ slug: "tone-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "facebook-circle",- "slug": "facebook-circle-logo",- "category_id": 97,- "type_of_icon": "LOGO",- "term": [- "social media"- ]+ name: "bitcoin",+ slug: "bitcoin-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "jquery",- "slug": "jquery-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "lira",+ slug: "lira-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "imdb",- "slug": "imdb-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "ruble",+ slug: "ruble-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "pinterest-alt",- "slug": "pinterest-alt-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "caret-up-circle",+ slug: "caret-up-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "tone",- "slug": "tone-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "caret-down-circle",+ slug: "caret-down-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "health",- "slug": "health-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "caret-left-circle",+ slug: "caret-left-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "baby-carriage",- "slug": "baby-carriage-solid",- "category_id": 94,- "type_of_icon": "SOLID",- "term": [- "child",- "pregnancy",- "birth"- ]+ name: "caret-right-circle",+ slug: "caret-right-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "clinic",- "slug": "clinic-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "rupee",+ slug: "rupee-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "hand-up",- "slug": "hand-up-solid",- "category_id": 96,- "type_of_icon": "SOLID",- "term": [- "finger",- "point",- "direction"- ]+ name: "euro",+ slug: "euro-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "hand-right",- "slug": "hand-right-solid",- "category_id": 96,- "type_of_icon": "SOLID",- "term": [- "finger",- "point",- "direction"- ]+ name: "pound",+ slug: "pound-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "hand-down",- "slug": "hand-down-solid",- "category_id": 96,- "type_of_icon": "SOLID",- "term": [- "finger",- "point",- "direction"- ]+ name: "won",+ slug: "won-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "hand-left",- "slug": "hand-left-solid",- "category_id": 96,- "type_of_icon": "SOLID",- "term": [- "finger",- "point",- "direction"- ]+ name: "yen",+ slug: "yen-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "male",- "slug": "male-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "shekel",+ slug: "shekel-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "female",- "slug": "female-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "facebook-circle",+ slug: "facebook-circle-logo",+ category_id: 97,+ type_of_icon: "LOGO",+ term: ["social media"]},{- "name": "male-sign",- "slug": "male-sign-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "jquery",+ slug: "jquery-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "female-sign",- "slug": "female-sign-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "imdb",+ slug: "imdb-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "clinic",- "slug": "clinic-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "pinterest-alt",+ slug: "pinterest-alt-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "offer",- "slug": "offer-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "tone",+ slug: "tone-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "food-tag",- "slug": "food-tag-regular",- "category_id": 108,- "type_of_icon": "REGULAR"+ name: "health",+ slug: "health-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "food-menu",- "slug": "food-menu-regular",- "category_id": 108,- "type_of_icon": "REGULAR"+ name: "baby-carriage",+ slug: "baby-carriage-solid",+ category_id: 94,+ type_of_icon: "SOLID",+ term: ["child", "pregnancy", "birth"]},{- "name": "food-menu",- "slug": "food-menu-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "clinic",+ slug: "clinic-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "camera-plus",- "slug": "camera-plus-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "hand-up",+ slug: "hand-up-solid",+ category_id: 96,+ type_of_icon: "SOLID",+ term: ["finger", "point", "direction"]},{- "name": "business",- "slug": "business-solid",- "category_id": 98,- "type_of_icon": "SOLID",- "term": [- "skyline",- "skyscraper",- "city"- ]+ name: "hand-right",+ slug: "hand-right-solid",+ category_id: 96,+ type_of_icon: "SOLID",+ term: ["finger", "point", "direction"]},{- "name": "meh-alt",- "slug": "meh-alt-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "hand-down",+ slug: "hand-down-solid",+ category_id: 96,+ type_of_icon: "SOLID",+ term: ["finger", "point", "direction"]},{- "name": "wink-tongue",- "slug": "wink-tongue-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "hand-left",+ slug: "hand-left-solid",+ category_id: 96,+ type_of_icon: "SOLID",+ term: ["finger", "point", "direction"]},{- "name": "happy-alt",- "slug": "happy-alt-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "male",+ slug: "male-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "cool",- "slug": "cool-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "female",+ slug: "female-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "tired",- "slug": "tired-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "male-sign",+ slug: "male-sign-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "smile",- "slug": "smile-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "female-sign",+ slug: "female-sign-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "angry",- "slug": "angry-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "clinic",+ slug: "clinic-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "happy-heart-eyes",- "slug": "happy-heart-eyes-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "offer",+ slug: "offer-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "dizzy",- "slug": "dizzy-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "food-tag",+ slug: "food-tag-regular",+ category_id: 108,+ type_of_icon: "REGULAR"},{- "name": "wink-smile",- "slug": "wink-smile-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "food-menu",+ slug: "food-menu-regular",+ category_id: 108,+ type_of_icon: "REGULAR"},{- "name": "confused",- "slug": "confused-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "food-menu",+ slug: "food-menu-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "sleepy",- "slug": "sleepy-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "camera-plus",+ slug: "camera-plus-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "shocked",- "slug": "shocked-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "business",+ slug: "business-solid",+ category_id: 98,+ type_of_icon: "SOLID",+ term: ["skyline", "skyscraper", "city"]},{- "name": "happy-beaming",- "slug": "happy-beaming-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "meh-alt",+ slug: "meh-alt-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "meh-blank",- "slug": "meh-blank-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "wink-tongue",+ slug: "wink-tongue-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "laugh",- "slug": "laugh-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "happy-alt",+ slug: "happy-alt-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "upside-down",- "slug": "upside-down-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "cool",+ slug: "cool-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "angry",- "slug": "angry-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "tired",+ slug: "tired-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "happy-heart-eyes",- "slug": "happy-heart-eyes-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "smile",+ slug: "smile-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "dizzy",- "slug": "dizzy-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "angry",+ slug: "angry-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "wink-smile",- "slug": "wink-smile-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "happy-heart-eyes",+ slug: "happy-heart-eyes-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "smile",- "slug": "smile-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "dizzy",+ slug: "dizzy-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "meh",- "slug": "meh-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "wink-smile",+ slug: "wink-smile-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "meh-alt",- "slug": "meh-alt-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "confused",+ slug: "confused-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "confused",- "slug": "confused-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "sleepy",+ slug: "sleepy-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "sleepy",- "slug": "sleepy-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "shocked",+ slug: "shocked-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "sad",- "slug": "sad-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "happy-beaming",+ slug: "happy-beaming-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "happy",- "slug": "happy-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "meh-blank",+ slug: "meh-blank-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "shocked",- "slug": "shocked-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "laugh",+ slug: "laugh-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "happy-beaming",- "slug": "happy-beaming-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "upside-down",+ slug: "upside-down-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "tired",- "slug": "tired-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "angry",+ slug: "angry-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "cool",- "slug": "cool-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "happy-heart-eyes",+ slug: "happy-heart-eyes-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "meh-blank",- "slug": "meh-blank-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "dizzy",+ slug: "dizzy-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "laugh",- "slug": "laugh-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "wink-smile",+ slug: "wink-smile-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "happy-alt",- "slug": "happy-alt-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "smile",+ slug: "smile-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "upside-down",- "slug": "upside-down-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "meh",+ slug: "meh-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "wink-tongue",- "slug": "wink-tongue-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "meh-alt",+ slug: "meh-alt-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "adobe",- "slug": "adobe-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "confused",+ slug: "confused-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "algolia",- "slug": "algolia-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "sleepy",+ slug: "sleepy-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "audible",- "slug": "audible-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "sad",+ slug: "sad-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "figma",- "slug": "figma-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "happy",+ slug: "happy-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "etsy",- "slug": "etsy-logo",- "category_id": 104,- "type_of_icon": "LOGO"+ name: "shocked",+ slug: "shocked-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "gitlab",- "slug": "gitlab-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "happy-beaming",+ slug: "happy-beaming-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "patreon",- "slug": "patreon-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "tired",+ slug: "tired-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "redbubble",- "slug": "redbubble-logo",- "category_id": 104,- "type_of_icon": "LOGO"+ name: "cool",+ slug: "cool-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "diamond",- "slug": "diamond-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "meh-blank",+ slug: "meh-blank-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "comment-error",- "slug": "comment-error-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "laugh",+ slug: "laugh-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "vial",- "slug": "vial-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "happy-alt",+ slug: "happy-alt-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "align-left",- "slug": "align-left-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "upside-down",+ slug: "upside-down-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "align-middle",- "slug": "align-middle-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "wink-tongue",+ slug: "wink-tongue-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "align-right",- "slug": "align-right-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "adobe",+ slug: "adobe-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "arrow-back",- "slug": "arrow-back-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "algolia",+ slug: "algolia-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "bell-minus",- "slug": "bell-minus-regular",- "category_id": 95,- "type_of_icon": "REGULAR",- "term": [- "alert",- "notification"- ]+ name: "audible",+ slug: "audible-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "bell-off",- "slug": "bell-off-regular",- "category_id": 95,- "type_of_icon": "REGULAR",- "term": [- "alert",- "notification",- "silent"- ]+ name: "figma",+ slug: "figma-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "bell-plus",- "slug": "bell-plus-regular",- "category_id": 95,- "type_of_icon": "REGULAR",- "term": [- "alert",- "notification"- ]+ name: "etsy",+ slug: "etsy-logo",+ category_id: 104,+ type_of_icon: "LOGO"},{- "name": "bell",- "slug": "bell-regular",- "category_id": 95,- "type_of_icon": "REGULAR",- "term": [- "alert",- "notification"- ]+ name: "gitlab",+ slug: "gitlab-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "bookmark",- "slug": "bookmark-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "patreon",+ slug: "patreon-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "bookmarks",- "slug": "bookmarks-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "redbubble",+ slug: "redbubble-logo",+ category_id: 104,+ type_of_icon: "LOGO"},{- "name": "bullseye",- "slug": "bullseye-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "diamond",+ slug: "diamond-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "camera-off",- "slug": "camera-off-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "comment-error",+ slug: "comment-error-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "camera",- "slug": "camera-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "vial",+ slug: "vial-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "captions",- "slug": "captions-regular",- "category_id": 94,- "type_of_icon": "REGULAR",- "term": [- "subtitles",- "subs",- "cc"- ]+ name: "align-left",+ slug: "align-left-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "checkbox-checked",- "slug": "checkbox-checked-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "align-middle",+ slug: "align-middle-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "checkbox",- "slug": "checkbox-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "align-right",+ slug: "align-right-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "checkbox-square",- "slug": "checkbox-square-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "arrow-back",+ slug: "arrow-back-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "chevron-down",- "slug": "chevron-down-regular",- "category_id": 96,- "type_of_icon": "REGULAR",- "term": [- "arrow"- ]+ name: "bell-minus",+ slug: "bell-minus-regular",+ category_id: 95,+ type_of_icon: "REGULAR",+ term: ["alert", "notification"]},{- "name": "chevron-up",- "slug": "chevron-up-regular",- "category_id": 96,- "type_of_icon": "REGULAR",- "term": [- "arrow"- ]+ name: "bell-off",+ slug: "bell-off-regular",+ category_id: 95,+ type_of_icon: "REGULAR",+ term: ["alert", "notification", "silent"]},{- "name": "chevron-left",- "slug": "chevron-left-regular",- "category_id": 96,- "type_of_icon": "REGULAR",- "term": [- "arrow"- ]+ name: "bell-plus",+ slug: "bell-plus-regular",+ category_id: 95,+ type_of_icon: "REGULAR",+ term: ["alert", "notification"]},{- "name": "chevron-right",- "slug": "chevron-right-regular",- "category_id": 96,- "type_of_icon": "REGULAR",- "term": [- "arrow"- ]+ name: "bell",+ slug: "bell-regular",+ category_id: 95,+ type_of_icon: "REGULAR",+ term: ["alert", "notification"]},{- "name": "chevrons-down",- "slug": "chevrons-down-regular",- "category_id": 96,- "type_of_icon": "REGULAR",- "term": [- "arrow"- ]+ name: "bookmark",+ slug: "bookmark-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "chevrons-up",- "slug": "chevrons-up-regular",- "category_id": 96,- "type_of_icon": "REGULAR",- "term": [- "arrow"- ]+ name: "bookmarks",+ slug: "bookmarks-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "chevrons-right",- "slug": "chevrons-right-regular",- "category_id": 96,- "type_of_icon": "REGULAR",- "term": [- "arrow"- ]+ name: "bullseye",+ slug: "bullseye-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "chevrons-left",- "slug": "chevrons-left-regular",- "category_id": 96,- "type_of_icon": "REGULAR",- "term": [- "arrow"- ]+ name: "camera-off",+ slug: "camera-off-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "clipboard",- "slug": "clipboard-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "camera",+ slug: "camera-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "code-curly",- "slug": "code-curly-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "captions",+ slug: "captions-regular",+ category_id: 94,+ type_of_icon: "REGULAR",+ term: ["subtitles", "subs", "cc"]},{- "name": "code",- "slug": "code-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "checkbox-checked",+ slug: "checkbox-checked-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "coffee",- "slug": "coffee-regular",- "category_id": 108,- "type_of_icon": "REGULAR"+ name: "checkbox",+ slug: "checkbox-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "copy",- "slug": "copy-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "checkbox-square",+ slug: "checkbox-square-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "copyright",- "slug": "copyright-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "chevron-down",+ slug: "chevron-down-regular",+ category_id: 96,+ type_of_icon: "REGULAR",+ term: ["arrow"]},{- "name": "down-arrow-circle",- "slug": "down-arrow-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "chevron-up",+ slug: "chevron-up-regular",+ category_id: 96,+ type_of_icon: "REGULAR",+ term: ["arrow"]},{- "name": "error-circle",- "slug": "error-circle-regular",- "category_id": 95,- "type_of_icon": "REGULAR"+ name: "chevron-left",+ slug: "chevron-left-regular",+ category_id: 96,+ type_of_icon: "REGULAR",+ term: ["arrow"]},{- "name": "error",- "slug": "error-regular",- "category_id": 95,- "type_of_icon": "REGULAR"+ name: "chevron-right",+ slug: "chevron-right-regular",+ category_id: 96,+ type_of_icon: "REGULAR",+ term: ["arrow"]},{- "name": "exit-fullscreen",- "slug": "exit-fullscreen-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "chevrons-down",+ slug: "chevrons-down-regular",+ category_id: 96,+ type_of_icon: "REGULAR",+ term: ["arrow"]},{- "name": "fast-forward-circle",- "slug": "fast-forward-circle-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "chevrons-up",+ slug: "chevrons-up-regular",+ category_id: 96,+ type_of_icon: "REGULAR",+ term: ["arrow"]},{- "name": "fast-forward",- "slug": "fast-forward-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "chevrons-right",+ slug: "chevrons-right-regular",+ category_id: 96,+ type_of_icon: "REGULAR",+ term: ["arrow"]},{- "name": "first-page",- "slug": "first-page-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "chevrons-left",+ slug: "chevrons-left-regular",+ category_id: 96,+ type_of_icon: "REGULAR",+ term: ["arrow"]},{- "name": "folder-minus",- "slug": "folder-minus-regular",- "category_id": 106,- "type_of_icon": "REGULAR",- "term": [- "remove",- "delete"- ]+ name: "clipboard",+ slug: "clipboard-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "folder-plus",- "slug": "folder-plus-regular",- "category_id": 106,- "type_of_icon": "REGULAR",- "term": [- "add",- "folder add",- "new folder"- ]+ name: "code-curly",+ slug: "code-curly-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "folder",- "slug": "folder-regular",- "category_id": 106,- "type_of_icon": "REGULAR"+ name: "code",+ slug: "code-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "fullscreen",- "slug": "fullscreen-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "coffee",+ slug: "coffee-regular",+ category_id: 108,+ type_of_icon: "REGULAR"},{- "name": "hide",- "slug": "hide-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "copy",+ slug: "copy-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "image",- "slug": "image-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "copyright",+ slug: "copyright-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "info-circle",- "slug": "info-circle-regular",- "category_id": 94,- "type_of_icon": "REGULAR"+ name: "down-arrow-circle",+ slug: "down-arrow-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "align-justify",- "slug": "align-justify-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "error-circle",+ slug: "error-circle-regular",+ category_id: 95,+ type_of_icon: "REGULAR"},{- "name": "key",- "slug": "key-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "error",+ slug: "error-regular",+ category_id: 95,+ type_of_icon: "REGULAR"},{- "name": "last-page",- "slug": "last-page-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "exit-fullscreen",+ slug: "exit-fullscreen-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "left-arrow-circle",- "slug": "left-arrow-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "fast-forward-circle",+ slug: "fast-forward-circle-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "left-down-arrow-circle",- "slug": "left-down-arrow-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "fast-forward",+ slug: "fast-forward-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "left-indent",- "slug": "left-indent-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "first-page",+ slug: "first-page-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "left-top-arrow-circle",- "slug": "left-top-arrow-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "folder-minus",+ slug: "folder-minus-regular",+ category_id: 106,+ type_of_icon: "REGULAR",+ term: ["remove", "delete"]},{- "name": "menu",- "slug": "menu-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "folder-plus",+ slug: "folder-plus-regular",+ category_id: 106,+ type_of_icon: "REGULAR",+ term: ["add", "folder add", "new folder"]},{- "name": "microphone",- "slug": "microphone-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "folder",+ slug: "folder-regular",+ category_id: 106,+ type_of_icon: "REGULAR"},{- "name": "minus-circle",- "slug": "minus-circle-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "fullscreen",+ slug: "fullscreen-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "moon",- "slug": "moon-regular",- "category_id": 123,- "type_of_icon": "REGULAR"+ name: "hide",+ slug: "hide-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "pause-circle",- "slug": "pause-circle-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "image",+ slug: "image-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "pause",- "slug": "pause-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "info-circle",+ slug: "info-circle-regular",+ category_id: 94,+ type_of_icon: "REGULAR"},{- "name": "play-circle",- "slug": "play-circle-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "align-justify",+ slug: "align-justify-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "play",- "slug": "play-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "key",+ slug: "key-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "plus-circle",- "slug": "plus-circle-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "last-page",+ slug: "last-page-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "question-mark",- "slug": "question-mark-regular",- "category_id": 94,- "type_of_icon": "REGULAR"+ name: "left-arrow-circle",+ slug: "left-arrow-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "radio-circle-marked",- "slug": "radio-circle-marked-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "left-down-arrow-circle",+ slug: "left-down-arrow-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "radio-circle",- "slug": "radio-circle-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "left-indent",+ slug: "left-indent-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "rectangle",- "slug": "rectangle-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "left-top-arrow-circle",+ slug: "left-top-arrow-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "rewind",- "slug": "rewind-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "menu",+ slug: "menu-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "reset",- "slug": "reset-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "microphone",+ slug: "microphone-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "right-arrow-circle",- "slug": "right-arrow-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "minus-circle",+ slug: "minus-circle-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "right-down-arrow-circle",- "slug": "right-down-arrow-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "moon",+ slug: "moon-regular",+ category_id: 123,+ type_of_icon: "REGULAR"},{- "name": "right-indent",- "slug": "right-indent-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "pause-circle",+ slug: "pause-circle-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "right-top-arrow-circle",- "slug": "right-top-arrow-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "pause",+ slug: "pause-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "rss",- "slug": "rss-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "play-circle",+ slug: "play-circle-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "search",- "slug": "search-regular",- "category_id": 110,- "type_of_icon": "REGULAR",- "term": [- "magnifying glass"- ]+ name: "play",+ slug: "play-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "show",- "slug": "show-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "plus-circle",+ slug: "plus-circle-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "skip-next",- "slug": "skip-next-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "question-mark",+ slug: "question-mark-regular",+ category_id: 94,+ type_of_icon: "REGULAR"},{- "name": "skip-previous",- "slug": "skip-previous-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "radio-circle-marked",+ slug: "radio-circle-marked-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "stop-circle",- "slug": "stop-circle-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "radio-circle",+ slug: "radio-circle-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "stop",- "slug": "stop-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "rectangle",+ slug: "rectangle-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "stopwatch",- "slug": "stopwatch-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "rewind",+ slug: "rewind-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "sync",- "slug": "sync-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "reset",+ slug: "reset-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "time",- "slug": "time-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "right-arrow-circle",+ slug: "right-arrow-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "toggle-left",- "slug": "toggle-left-regular",- "category_id": 110,- "type_of_icon": "REGULAR",- "term": [- "switch"- ]+ name: "right-down-arrow-circle",+ slug: "right-down-arrow-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "toggle-right",- "slug": "toggle-right-regular",- "category_id": 110,- "type_of_icon": "REGULAR",- "term": [- "switch"- ]+ name: "right-indent",+ slug: "right-indent-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "trending-down",- "slug": "trending-down-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "right-top-arrow-circle",+ slug: "right-top-arrow-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "trending-up",- "slug": "trending-up-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "rss",+ slug: "rss-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "up-arrow-circle",- "slug": "up-arrow-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "search",+ slug: "search-regular",+ category_id: 110,+ type_of_icon: "REGULAR",+ term: ["magnifying glass"]},{- "name": "vertical-center",- "slug": "vertical-center-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "show",+ slug: "show-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "video",- "slug": "video-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "skip-next",+ slug: "skip-next-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "volume-full",- "slug": "volume-full-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "skip-previous",+ slug: "skip-previous-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "volume-low",- "slug": "volume-low-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "stop-circle",+ slug: "stop-circle-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "volume-mute",- "slug": "volume-mute-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "stop",+ slug: "stop-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "volume",- "slug": "volume-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "stopwatch",+ slug: "stopwatch-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "x-circle",- "slug": "x-circle-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "sync",+ slug: "sync-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "zoom-in",- "slug": "zoom-in-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "time",+ slug: "time-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "zoom-out",- "slug": "zoom-out-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "toggle-left",+ slug: "toggle-left-regular",+ category_id: 110,+ type_of_icon: "REGULAR",+ term: ["switch"]},{- "name": "archive",- "slug": "archive-regular",- "category_id": 106,- "type_of_icon": "REGULAR"+ name: "toggle-right",+ slug: "toggle-right-regular",+ category_id: 110,+ type_of_icon: "REGULAR",+ term: ["switch"]},{- "name": "at",- "slug": "at-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "trending-down",+ slug: "trending-down-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "bar-chart-alt",- "slug": "bar-chart-alt-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "trending-up",+ slug: "trending-up-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "bar-chart-square",- "slug": "bar-chart-square-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "up-arrow-circle",+ slug: "up-arrow-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "bar-chart",- "slug": "bar-chart-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "vertical-center",+ slug: "vertical-center-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "basketball",- "slug": "basketball-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "nba"- ]+ name: "video",+ slug: "video-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "block",- "slug": "block-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "volume-full",+ slug: "volume-full-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "book-bookmark",- "slug": "book-bookmark-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "volume-low",+ slug: "volume-low-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "book",- "slug": "book-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "volume-mute",+ slug: "volume-mute-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "bookmark-minus",- "slug": "bookmark-minus-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "volume",+ slug: "volume-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "bookmark-plus",- "slug": "bookmark-plus-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "x-circle",+ slug: "x-circle-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "briefcase",- "slug": "briefcase-regular",- "category_id": 99,- "type_of_icon": "REGULAR",- "term": [- "work",- "travel",- "suitcase"- ]+ name: "zoom-in",+ slug: "zoom-in-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "broadcast",- "slug": "broadcast-regular",- "category_id": 115,- "type_of_icon": "REGULAR"+ name: "zoom-out",+ slug: "zoom-out-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "building",- "slug": "building-regular",- "category_id": 98,- "type_of_icon": "REGULAR"+ name: "archive",+ slug: "archive-regular",+ category_id: 106,+ type_of_icon: "REGULAR"},{- "name": "bug",- "slug": "bug-regular",- "category_id": 100,- "type_of_icon": "REGULAR",- "term": [- "error",- "warning"- ]+ name: "at",+ slug: "at-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "bluetooth",- "slug": "bluetooth-regular",- "category_id": 115,- "type_of_icon": "REGULAR"+ name: "bar-chart-alt",+ slug: "bar-chart-alt-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "bulb",- "slug": "bulb-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "bar-chart-square",+ slug: "bar-chart-square-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "buoy",- "slug": "buoy-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "bar-chart",+ slug: "bar-chart-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "calendar-plus",- "slug": "calendar-plus-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "basketball",+ slug: "basketball-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["nba"]},{- "name": "calendar-check",- "slug": "calendar-check-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "block",+ slug: "block-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "calendar-minus",- "slug": "calendar-minus-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "book-bookmark",+ slug: "book-bookmark-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "calendar-x",- "slug": "calendar-x-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "book",+ slug: "book-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "calendar",- "slug": "calendar-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "bookmark-minus",+ slug: "bookmark-minus-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "chart",- "slug": "chart-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "bookmark-plus",+ slug: "bookmark-plus-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "cloud-download",- "slug": "cloud-download-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "briefcase",+ slug: "briefcase-regular",+ category_id: 99,+ type_of_icon: "REGULAR",+ term: ["work", "travel", "suitcase"]},{- "name": "cloud-upload",- "slug": "cloud-upload-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "broadcast",+ slug: "broadcast-regular",+ category_id: 115,+ type_of_icon: "REGULAR"},{- "name": "cloud",- "slug": "cloud-regular",- "category_id": 123,- "type_of_icon": "REGULAR"+ name: "building",+ slug: "building-regular",+ category_id: 98,+ type_of_icon: "REGULAR"},{- "name": "terminal",- "slug": "terminal-regular",- "category_id": 100,- "type_of_icon": "REGULAR",- "term": [- "command line"- ]+ name: "bug",+ slug: "bug-regular",+ category_id: 100,+ type_of_icon: "REGULAR",+ term: ["error", "warning"]},{- "name": "crosshair",- "slug": "crosshair-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "bluetooth",+ slug: "bluetooth-regular",+ category_id: 115,+ type_of_icon: "REGULAR"},{- "name": "compass",- "slug": "compass-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "bulb",+ slug: "bulb-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "data",- "slug": "data-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "buoy",+ slug: "buoy-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "desktop",- "slug": "desktop-regular",- "category_id": 103,- "type_of_icon": "REGULAR",- "term": [- "monitor",- "display"- ]+ name: "calendar-plus",+ slug: "calendar-plus-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "directions",- "slug": "directions-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "calendar-check",+ slug: "calendar-check-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "dollar",- "slug": "dollar-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "calendar-minus",+ slug: "calendar-minus-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "dots-horizontal-rounded",- "slug": "dots-horizontal-rounded-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "calendar-x",+ slug: "calendar-x-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "dots-horizontal",- "slug": "dots-horizontal-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "calendar",+ slug: "calendar-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "dots-vertical-rounded",- "slug": "dots-vertical-rounded-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "chart",+ slug: "chart-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "dots-vertical",- "slug": "dots-vertical-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "cloud-download",+ slug: "cloud-download-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "download",- "slug": "download-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "cloud-upload",+ slug: "cloud-upload-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "envelope",- "slug": "envelope-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "letter",- "mail",- "email",- "communication"- ]+ name: "cloud",+ slug: "cloud-regular",+ category_id: 123,+ type_of_icon: "REGULAR"},{- "name": "gift",- "slug": "gift-regular",- "category_id": 104,- "type_of_icon": "REGULAR"+ name: "terminal",+ slug: "terminal-regular",+ category_id: 100,+ type_of_icon: "REGULAR",+ term: ["command line"]},{- "name": "globe",- "slug": "globe-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "crosshair",+ slug: "crosshair-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "devices",- "slug": "devices-regular",- "category_id": 103,- "type_of_icon": "REGULAR",- "term": [- "mobile",- "tab"- ]+ name: "compass",+ slug: "compass-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "headphone",- "slug": "headphone-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "data",+ slug: "data-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "heart",- "slug": "heart-regular",- "category_id": 109,- "type_of_icon": "REGULAR",- "term": [- "health"- ]+ name: "desktop",+ slug: "desktop-regular",+ category_id: 103,+ type_of_icon: "REGULAR",+ term: ["monitor", "display"]},{- "name": "home",- "slug": "home-regular",- "category_id": 98,- "type_of_icon": "REGULAR"+ name: "directions",+ slug: "directions-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "laptop",- "slug": "laptop-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "dollar",+ slug: "dollar-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "layer",- "slug": "layer-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "dots-horizontal-rounded",+ slug: "dots-horizontal-rounded-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "link-alt",- "slug": "link-alt-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "dots-horizontal",+ slug: "dots-horizontal-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "link",- "slug": "link-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "dots-vertical-rounded",+ slug: "dots-vertical-rounded-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "list-plus",- "slug": "list-plus-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "dots-vertical",+ slug: "dots-vertical-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "list-ul",- "slug": "list-ul-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "download",+ slug: "download-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "list-minus",- "slug": "list-minus-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "envelope",+ slug: "envelope-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["letter", "mail", "email", "communication"]},{- "name": "lock-open",- "slug": "lock-open-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "gift",+ slug: "gift-regular",+ category_id: 104,+ type_of_icon: "REGULAR"},{- "name": "lock",- "slug": "lock-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "globe",+ slug: "globe-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "map-alt",- "slug": "map-alt-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "devices",+ slug: "devices-regular",+ category_id: 103,+ type_of_icon: "REGULAR",+ term: ["mobile", "tab"]},{- "name": "map",- "slug": "map-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "headphone",+ slug: "headphone-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "message-rounded",- "slug": "message-rounded-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "heart",+ slug: "heart-regular",+ category_id: 109,+ type_of_icon: "REGULAR",+ term: ["health"]},{- "name": "message",- "slug": "message-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "home",+ slug: "home-regular",+ category_id: 98,+ type_of_icon: "REGULAR"},{- "name": "mobile-alt",- "slug": "mobile-alt-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "laptop",+ slug: "laptop-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "mobile",- "slug": "mobile-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "layer",+ slug: "layer-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "navigation",- "slug": "navigation-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "link-alt",+ slug: "link-alt-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "phone",- "slug": "phone-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "link",+ slug: "link-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "pie-chart",- "slug": "pie-chart-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "list-plus",+ slug: "list-plus-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "send",- "slug": "send-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "list-ul",+ slug: "list-ul-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "sidebar",- "slug": "sidebar-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "list-minus",+ slug: "list-minus-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "sitemap",- "slug": "sitemap-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "lock-open",+ slug: "lock-open-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "spreadsheet",- "slug": "spreadsheet-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "lock",+ slug: "lock-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "tab",- "slug": "tab-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "map-alt",+ slug: "map-alt-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "tag",- "slug": "tag-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "map",+ slug: "map-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "target-lock",- "slug": "target-lock-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "message-rounded",+ slug: "message-rounded-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "tennis-ball",- "slug": "tennis-ball-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "deuce"- ]+ name: "message",+ slug: "message-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "alarm",- "slug": "alarm-regular",- "category_id": 120,- "type_of_icon": "REGULAR",- "term": [- "alert"- ]+ name: "mobile-alt",+ slug: "mobile-alt-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "upload",- "slug": "upload-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "mobile",+ slug: "mobile-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "usb",- "slug": "usb-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "navigation",+ slug: "navigation-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "video-off",- "slug": "video-off-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "phone",+ slug: "phone-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "voicemail",- "slug": "voicemail-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "pie-chart",+ slug: "pie-chart-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "wifi",- "slug": "wifi-regular",- "category_id": 115,- "type_of_icon": "REGULAR"+ name: "send",+ slug: "send-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "window-open",- "slug": "window-open-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "sidebar",+ slug: "sidebar-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "window",- "slug": "window-regular",- "category_id": 110,- "type_of_icon": "REGULAR",- "term": [- "browser"- ]+ name: "sitemap",+ slug: "sitemap-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "windows",- "slug": "windows-regular",- "category_id": 110,- "type_of_icon": "REGULAR",- "term": [- "browser"- ]+ name: "spreadsheet",+ slug: "spreadsheet-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "duplicate",- "slug": "duplicate-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "tab",+ slug: "tab-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "table",- "slug": "table-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "tag",+ slug: "tag-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "x",- "slug": "x-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "target-lock",+ slug: "target-lock-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "adjust",- "slug": "adjust-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "tennis-ball",+ slug: "tennis-ball-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["deuce"]},{- "name": "album",- "slug": "album-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "alarm",+ slug: "alarm-regular",+ category_id: 120,+ type_of_icon: "REGULAR",+ term: ["alert"]},{- "name": "anchor",- "slug": "anchor-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "upload",+ slug: "upload-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "award",- "slug": "award-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "usb",+ slug: "usb-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "bold",- "slug": "bold-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "video-off",+ slug: "video-off-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "calculator",- "slug": "calculator-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "voicemail",+ slug: "voicemail-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "cart",- "slug": "cart-regular",- "category_id": 104,- "type_of_icon": "REGULAR"+ name: "wifi",+ slug: "wifi-regular",+ category_id: 115,+ type_of_icon: "REGULAR"},{- "name": "check",- "slug": "check-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "window-open",+ slug: "window-open-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "cloud-drizzle",- "slug": "cloud-drizzle-regular",- "category_id": 123,- "type_of_icon": "REGULAR"+ name: "window",+ slug: "window-regular",+ category_id: 110,+ type_of_icon: "REGULAR",+ term: ["browser"]},{- "name": "cloud-light-rain",- "slug": "cloud-light-rain-regular",- "category_id": 123,- "type_of_icon": "REGULAR"+ name: "windows",+ slug: "windows-regular",+ category_id: 110,+ type_of_icon: "REGULAR",+ term: ["browser"]},{- "name": "cloud-lightning",- "slug": "cloud-lightning-regular",- "category_id": 123,- "type_of_icon": "REGULAR"+ name: "duplicate",+ slug: "duplicate-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "cloud-rain",- "slug": "cloud-rain-regular",- "category_id": 123,- "type_of_icon": "REGULAR"+ name: "table",+ slug: "table-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "cloud-snow",- "slug": "cloud-snow-regular",- "category_id": 123,- "type_of_icon": "REGULAR"+ name: "x",+ slug: "x-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "cog",- "slug": "cog-regular",- "category_id": 110,- "type_of_icon": "REGULAR",- "term": [- "gear",- "setting"- ]+ name: "adjust",+ slug: "adjust-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "columns",- "slug": "columns-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "album",+ slug: "album-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "credit-card",- "slug": "credit-card-regular",- "category_id": 107,- "type_of_icon": "REGULAR",- "term": [- "finance",- "money",- "debit"- ]+ name: "anchor",+ slug: "anchor-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "crop",- "slug": "crop-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "award",+ slug: "award-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "cube",- "slug": "cube-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "bold",+ slug: "bold-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "cut",- "slug": "cut-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "calculator",+ slug: "calculator-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "detail",- "slug": "detail-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "cart",+ slug: "cart-regular",+ category_id: 104,+ type_of_icon: "REGULAR"},{- "name": "shield-quarter",- "slug": "shield-quarter-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "check",+ slug: "check-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "edit",- "slug": "edit-regular",- "category_id": 124,- "type_of_icon": "REGULAR",- "term": [- "writing",- "note",- "pencil"- ]+ name: "cloud-drizzle",+ slug: "cloud-drizzle-regular",+ category_id: 123,+ type_of_icon: "REGULAR"},{- "name": "file",- "slug": "file-regular",- "category_id": 106,- "type_of_icon": "REGULAR"+ name: "cloud-light-rain",+ slug: "cloud-light-rain-regular",+ category_id: 123,+ type_of_icon: "REGULAR"},{- "name": "filter",- "slug": "filter-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "cloud-lightning",+ slug: "cloud-lightning-regular",+ category_id: 123,+ type_of_icon: "REGULAR"},{- "name": "font",- "slug": "font-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "cloud-rain",+ slug: "cloud-rain-regular",+ category_id: 123,+ type_of_icon: "REGULAR"},{- "name": "git-branch",- "slug": "git-branch-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "cloud-snow",+ slug: "cloud-snow-regular",+ category_id: 123,+ type_of_icon: "REGULAR"},{- "name": "git-commit",- "slug": "git-commit-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "cog",+ slug: "cog-regular",+ category_id: 110,+ type_of_icon: "REGULAR",+ term: ["gear", "setting"]},{- "name": "git-compare",- "slug": "git-compare-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "columns",+ slug: "columns-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "git-merge",- "slug": "git-merge-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "credit-card",+ slug: "credit-card-regular",+ category_id: 107,+ type_of_icon: "REGULAR",+ term: ["finance", "money", "debit"]},{- "name": "git-pull-request",- "slug": "git-pull-request-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "crop",+ slug: "crop-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "git-repo-forked",- "slug": "git-repo-forked-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "cube",+ slug: "cube-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "group",- "slug": "group-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "cut",+ slug: "cut-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "hash",- "slug": "hash-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "detail",+ slug: "detail-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "heading",- "slug": "heading-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "shield-quarter",+ slug: "shield-quarter-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "home-alt",- "slug": "home-alt-regular",- "category_id": 98,- "type_of_icon": "REGULAR"+ name: "edit",+ slug: "edit-regular",+ category_id: 124,+ type_of_icon: "REGULAR",+ term: ["writing", "note", "pencil"]},{- "name": "italic",- "slug": "italic-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "file",+ slug: "file-regular",+ category_id: 106,+ type_of_icon: "REGULAR"},{- "name": "joystick",- "slug": "joystick-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "filter",+ slug: "filter-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "link-external",- "slug": "link-external-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "font",+ slug: "font-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "log-in",- "slug": "log-in-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "git-branch",+ slug: "git-branch-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "log-out",- "slug": "log-out-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "git-commit",+ slug: "git-commit-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "microphone-off",- "slug": "microphone-off-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "git-compare",+ slug: "git-compare-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "minus",- "slug": "minus-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "git-merge",+ slug: "git-merge-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "mouse",- "slug": "mouse-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "git-pull-request",+ slug: "git-pull-request-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "move",- "slug": "move-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "git-repo-forked",+ slug: "git-repo-forked-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "music",- "slug": "music-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "group",+ slug: "group-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "notification",- "slug": "notification-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "hash",+ slug: "hash-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "package",- "slug": "package-regular",- "category_id": 104,- "type_of_icon": "REGULAR",- "term": [- "box",- "shipping",- "delivery"- ]+ name: "heading",+ slug: "heading-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "paragraph",- "slug": "paragraph-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "home-alt",+ slug: "home-alt-regular",+ category_id: 98,+ type_of_icon: "REGULAR"},{- "name": "paste",- "slug": "paste-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "italic",+ slug: "italic-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "pencil",- "slug": "pencil-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "joystick",+ slug: "joystick-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "pin",- "slug": "pin-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "link-external",+ slug: "link-external-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "plus",- "slug": "plus-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "log-in",+ slug: "log-in-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "power-off",- "slug": "power-off-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "log-out",+ slug: "log-out-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "pulse",- "slug": "pulse-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "microphone-off",+ slug: "microphone-off-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "save",- "slug": "save-regular",- "category_id": 116,- "type_of_icon": "REGULAR",- "term": [- "floppy disk"- ]+ name: "minus",+ slug: "minus-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "screenshot",- "slug": "screenshot-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "mouse",+ slug: "mouse-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "select-multiple",- "slug": "select-multiple-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "move",+ slug: "move-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "share-alt",- "slug": "share-alt-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "music",+ slug: "music-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "share",- "slug": "share-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "notification",+ slug: "notification-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "shield-alt",- "slug": "shield-alt-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "package",+ slug: "package-regular",+ category_id: 104,+ type_of_icon: "REGULAR",+ term: ["box", "shipping", "delivery"]},{- "name": "shield",- "slug": "shield-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "paragraph",+ slug: "paragraph-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "shopping-bag",- "slug": "shopping-bag-regular",- "category_id": 104,- "type_of_icon": "REGULAR"+ name: "paste",+ slug: "paste-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "shuffle",- "slug": "shuffle-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "pencil",+ slug: "pencil-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "sort",- "slug": "sort-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "pin",+ slug: "pin-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "star",- "slug": "star-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "plus",+ slug: "plus-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "sun",- "slug": "sun-regular",- "category_id": 123,- "type_of_icon": "REGULAR"+ name: "power-off",+ slug: "power-off-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "text",- "slug": "text-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "pulse",+ slug: "pulse-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "trash",- "slug": "trash-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "save",+ slug: "save-regular",+ category_id: 116,+ type_of_icon: "REGULAR",+ term: ["floppy disk"]},{- "name": "trophy",- "slug": "trophy-regular",- "category_id": 119,- "type_of_icon": "REGULAR"+ name: "screenshot",+ slug: "screenshot-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "underline",- "slug": "underline-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "select-multiple",+ slug: "select-multiple-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "user-check",- "slug": "user-check-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "share-alt",+ slug: "share-alt-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "user-circle",- "slug": "user-circle-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "share",+ slug: "share-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "user-minus",- "slug": "user-minus-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "shield-alt",+ slug: "shield-alt-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "user-plus",- "slug": "user-plus-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "shield",+ slug: "shield-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "user-x",- "slug": "user-x-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "shopping-bag",+ slug: "shopping-bag-regular",+ category_id: 104,+ type_of_icon: "REGULAR"},{- "name": "user",- "slug": "user-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "shuffle",+ slug: "shuffle-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "barcode",- "slug": "barcode-regular",- "category_id": 104,- "type_of_icon": "REGULAR"+ name: "sort",+ slug: "sort-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "crown",- "slug": "crown-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "star",+ slug: "star-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "dislike",- "slug": "dislike-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "sun",+ slug: "sun-regular",+ category_id: 123,+ type_of_icon: "REGULAR"},{- "name": "down-arrow",- "slug": "down-arrow-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "text",+ slug: "text-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "export",- "slug": "export-regular",- "category_id": 106,- "type_of_icon": "REGULAR"+ name: "trash",+ slug: "trash-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "facebook",- "slug": "facebook-logo",- "category_id": 97,- "type_of_icon": "LOGO",- "term": [- "social media"- ]+ name: "trophy",+ slug: "trophy-regular",+ category_id: 119,+ type_of_icon: "REGULAR"},{- "name": "first-aid",- "slug": "first-aid-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "underline",+ slug: "underline-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "flag",- "slug": "flag-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "user-check",+ slug: "user-check-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "github",- "slug": "github-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "user-circle",+ slug: "user-circle-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "google",- "slug": "google-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "user-minus",+ slug: "user-minus-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "history",- "slug": "history-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "user-plus",+ slug: "user-plus-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "instagram",- "slug": "instagram-logo",- "category_id": 97,- "type_of_icon": "LOGO",- "term": [- "social media"- ]+ name: "user-x",+ slug: "user-x-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "joystick-alt",- "slug": "joystick-alt-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "user",+ slug: "user-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "left-arrow",- "slug": "left-arrow-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "barcode",+ slug: "barcode-regular",+ category_id: 104,+ type_of_icon: "REGULAR"},{- "name": "like",- "slug": "like-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "crown",+ slug: "crown-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "list-check",- "slug": "list-check-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "dislike",+ slug: "dislike-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "poll",- "slug": "poll-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "down-arrow",+ slug: "down-arrow-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "radar",- "slug": "radar-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "export",+ slug: "export-regular",+ category_id: 106,+ type_of_icon: "REGULAR"},{- "name": "redo",- "slug": "redo-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "facebook",+ slug: "facebook-logo",+ category_id: 97,+ type_of_icon: "LOGO",+ term: ["social media"]},{- "name": "reply-all",- "slug": "reply-all-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "first-aid",+ slug: "first-aid-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "reply",- "slug": "reply-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "flag",+ slug: "flag-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "repost",- "slug": "repost-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "github",+ slug: "github-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "revision",- "slug": "revision-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "google",+ slug: "google-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "right-arrow",- "slug": "right-arrow-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "history",+ slug: "history-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "subdirectory-left",- "slug": "subdirectory-left-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "instagram",+ slug: "instagram-logo",+ category_id: 97,+ type_of_icon: "LOGO",+ term: ["social media"]},{- "name": "subdirectory-right",- "slug": "subdirectory-right-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "joystick-alt",+ slug: "joystick-alt-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "support",- "slug": "support-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "left-arrow",+ slug: "left-arrow-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "timer",- "slug": "timer-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "like",+ slug: "like-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "twitter",- "slug": "twitter-logo",- "category_id": 97,- "type_of_icon": "LOGO",- "term": [- "social media"- ]+ name: "list-check",+ slug: "list-check-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "undo",- "slug": "undo-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "poll",+ slug: "poll-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "up-arrow",- "slug": "up-arrow-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "radar",+ slug: "radar-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "youtube",- "slug": "youtube-logo",- "category_id": 117,- "type_of_icon": "LOGO"+ name: "redo",+ slug: "redo-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "whatsapp",- "slug": "whatsapp-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "reply-all",+ slug: "reply-all-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "tumblr",- "slug": "tumblr-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "reply",+ slug: "reply-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "phone-call",- "slug": "phone-call-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "repost",+ slug: "repost-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "behance",- "slug": "behance-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "revision",+ slug: "revision-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "dribbble",- "slug": "dribbble-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "right-arrow",+ slug: "right-arrow-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "aperture",- "slug": "aperture-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "subdirectory-left",+ slug: "subdirectory-left-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "film",- "slug": "film-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "subdirectory-right",+ slug: "subdirectory-right-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "folder-open",- "slug": "folder-open-regular",- "category_id": 106,- "type_of_icon": "REGULAR"+ name: "support",+ slug: "support-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "task",- "slug": "task-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "timer",+ slug: "timer-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "server",- "slug": "server-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "twitter",+ slug: "twitter-logo",+ category_id: 97,+ type_of_icon: "LOGO",+ term: ["social media"]},{- "name": "battery",- "slug": "battery-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "undo",+ slug: "undo-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "calendar-alt",- "slug": "calendar-alt-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "up-arrow",+ slug: "up-arrow-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "import",- "slug": "import-regular",- "category_id": 106,- "type_of_icon": "REGULAR"+ name: "youtube",+ slug: "youtube-logo",+ category_id: 117,+ type_of_icon: "LOGO"},{- "name": "ruler",- "slug": "ruler-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "whatsapp",+ slug: "whatsapp-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "horizontal-center",- "slug": "horizontal-center-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "tumblr",+ slug: "tumblr-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "rotate-right",- "slug": "rotate-right-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "phone-call",+ slug: "phone-call-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "rename",- "slug": "rename-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "behance",+ slug: "behance-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "collapse",- "slug": "collapse-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "dribbble",+ slug: "dribbble-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "phone-incoming",- "slug": "phone-incoming-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "aperture",+ slug: "aperture-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "phone-outgoing",- "slug": "phone-outgoing-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "film",+ slug: "film-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "body",- "slug": "body-regular",- "category_id": 94,- "type_of_icon": "REGULAR",- "term": [- "male"- ]+ name: "folder-open",+ slug: "folder-open-regular",+ category_id: 106,+ type_of_icon: "REGULAR"},{- "name": "cast",- "slug": "cast-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "task",+ slug: "task-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "chip",- "slug": "chip-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "server",+ slug: "server-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "skip-next-circle",- "slug": "skip-next-circle-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "battery",+ slug: "battery-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "skip-previous-circle",- "slug": "skip-previous-circle-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "calendar-alt",+ slug: "calendar-alt-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "hdd",- "slug": "hdd-regular",- "category_id": 103,- "type_of_icon": "REGULAR",- "term": [- "storage",- "hard drive"- ]+ name: "import",+ slug: "import-regular",+ category_id: 106,+ type_of_icon: "REGULAR"},{- "name": "store",- "slug": "store-regular",- "category_id": 104,- "type_of_icon": "REGULAR",- "term": [- "shop",- "market"- ]+ name: "ruler",+ slug: "ruler-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "globe-alt",- "slug": "globe-alt-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "horizontal-center",+ slug: "horizontal-center-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "vimeo",- "slug": "vimeo-logo",- "category_id": 117,- "type_of_icon": "LOGO"+ name: "rotate-right",+ slug: "rotate-right-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "upvote",- "slug": "upvote-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "rename",+ slug: "rename-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "downvote",- "slug": "downvote-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "collapse",+ slug: "collapse-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "news",- "slug": "news-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "phone-incoming",+ slug: "phone-incoming-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "pie-chart-alt",- "slug": "pie-chart-alt-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "phone-outgoing",+ slug: "phone-outgoing-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "images",- "slug": "images-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "body",+ slug: "body-regular",+ category_id: 94,+ type_of_icon: "REGULAR",+ term: ["male"]},{- "name": "purchase-tag",- "slug": "purchase-tag-regular",- "category_id": 104,- "type_of_icon": "REGULAR",- "term": [- "price",- "cost"- ]+ name: "cast",+ slug: "cast-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "pen",- "slug": "pen-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "chip",+ slug: "chip-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "expand",- "slug": "expand-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "skip-next-circle",+ slug: "skip-next-circle-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "paperclip",- "slug": "paperclip-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "skip-previous-circle",+ slug: "skip-previous-circle-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "closet",- "slug": "closet-regular",- "category_id": 104,- "type_of_icon": "REGULAR"+ name: "hdd",+ slug: "hdd-regular",+ category_id: 103,+ type_of_icon: "REGULAR",+ term: ["storage", "hard drive"]},{- "name": "tv",- "slug": "tv-regular",- "category_id": 103,- "type_of_icon": "REGULAR",- "term": [- "television",- "monitor"- ]+ name: "store",+ slug: "store-regular",+ category_id: 104,+ type_of_icon: "REGULAR",+ term: ["shop", "market"]},{- "name": "collection",- "slug": "collection-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "globe-alt",+ slug: "globe-alt-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "station",- "slug": "station-regular",- "category_id": 115,- "type_of_icon": "REGULAR"+ name: "vimeo",+ slug: "vimeo-logo",+ category_id: 117,+ type_of_icon: "LOGO"},{- "name": "wallet",- "slug": "wallet-regular",- "category_id": 107,- "type_of_icon": "REGULAR",- "term": [- "money"- ]+ name: "upvote",+ slug: "upvote-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "briefcase-alt",- "slug": "briefcase-alt-regular",- "category_id": 99,- "type_of_icon": "REGULAR",- "term": [- "work",- "travel",- "suitcase"- ]+ name: "downvote",+ slug: "downvote-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "hourglass",- "slug": "hourglass-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "news",+ slug: "news-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "carousel",- "slug": "carousel-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "pie-chart-alt",+ slug: "pie-chart-alt-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "infinite",- "slug": "infinite-regular",- "category_id": 113,- "type_of_icon": "REGULAR"+ name: "images",+ slug: "images-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "plug",- "slug": "plug-regular",- "category_id": 116,- "type_of_icon": "REGULAR",- "term": [- "charging"- ]+ name: "purchase-tag",+ slug: "purchase-tag-regular",+ category_id: 104,+ type_of_icon: "REGULAR",+ term: ["price", "cost"]},{- "name": "notification-off",- "slug": "notification-off-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "pen",+ slug: "pen-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "window-close",- "slug": "window-close-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "expand",+ slug: "expand-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "command",- "slug": "command-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "paperclip",+ slug: "paperclip-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "grid-alt",- "slug": "grid-alt-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "closet",+ slug: "closet-regular",+ category_id: 104,+ type_of_icon: "REGULAR"},{- "name": "trash-alt",- "slug": "trash-alt-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "tv",+ slug: "tv-regular",+ category_id: 103,+ type_of_icon: "REGULAR",+ term: ["television", "monitor"]},{- "name": "chalkboard",- "slug": "chalkboard-regular",- "category_id": 99,- "type_of_icon": "REGULAR",- "term": [- "whiteboard",- "teaching"- ]+ name: "collection",+ slug: "collection-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "loader",- "slug": "loader-regular",- "category_id": 112,- "type_of_icon": "REGULAR"+ name: "station",+ slug: "station-regular",+ category_id: 115,+ type_of_icon: "REGULAR"},{- "name": "slider",- "slug": "slider-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "wallet",+ slug: "wallet-regular",+ category_id: 107,+ type_of_icon: "REGULAR",+ term: ["money"]},{- "name": "paper-plane",- "slug": "paper-plane-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "briefcase-alt",+ slug: "briefcase-alt-regular",+ category_id: 99,+ type_of_icon: "REGULAR",+ term: ["work", "travel", "suitcase"]},{- "name": "selection",- "slug": "selection-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "hourglass",+ slug: "hourglass-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "linkedin",- "slug": "linkedin-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "carousel",+ slug: "carousel-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "world",- "slug": "world-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "infinite",+ slug: "infinite-regular",+ category_id: 113,+ type_of_icon: "REGULAR"},{- "name": "dock-bottom",- "slug": "dock-bottom-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "plug",+ slug: "plug-regular",+ category_id: 116,+ type_of_icon: "REGULAR",+ term: ["charging"]},{- "name": "dock-right",- "slug": "dock-right-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "notification-off",+ slug: "notification-off-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "dock-top",- "slug": "dock-top-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "window-close",+ slug: "window-close-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "dock-left",- "slug": "dock-left-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "command",+ slug: "command-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "layout",- "slug": "layout-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "grid-alt",+ slug: "grid-alt-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "bitcoin",- "slug": "bitcoin-logo",- "category_id": 107,- "type_of_icon": "LOGO"+ name: "trash-alt",+ slug: "trash-alt-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "facebook-square",- "slug": "facebook-square-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "chalkboard",+ slug: "chalkboard-regular",+ category_id: 99,+ type_of_icon: "REGULAR",+ term: ["whiteboard", "teaching"]},{- "name": "alarm-off",- "slug": "alarm-off-regular",- "category_id": 120,- "type_of_icon": "REGULAR",- "term": [- "alert",- "silent"- ]+ name: "loader",+ slug: "loader-regular",+ category_id: 112,+ type_of_icon: "REGULAR"},{- "name": "wrench",- "slug": "wrench-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "slider",+ slug: "slider-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "loader-circle",- "slug": "loader-circle-regular",- "category_id": 112,- "type_of_icon": "REGULAR"+ name: "paper-plane",+ slug: "paper-plane-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "loader-alt",- "slug": "loader-alt-regular",- "category_id": 112,- "type_of_icon": "REGULAR"+ name: "selection",+ slug: "selection-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "car",- "slug": "car-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "linkedin",+ slug: "linkedin-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "cart-alt",- "slug": "cart-alt-regular",- "category_id": 104,- "type_of_icon": "REGULAR"+ name: "world",+ slug: "world-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "adjust",- "slug": "adjust-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "dock-bottom",+ slug: "dock-bottom-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "alarm",- "slug": "alarm-solid",- "category_id": 120,- "type_of_icon": "SOLID",- "term": [- "alert"- ]+ name: "dock-right",+ slug: "dock-right-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "alarm-off",- "slug": "alarm-off-solid",- "category_id": 120,- "type_of_icon": "SOLID",- "term": [- "alert",- "silent"- ]+ name: "dock-top",+ slug: "dock-top-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "album",- "slug": "album-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "dock-left",+ slug: "dock-left-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "archive",- "slug": "archive-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "layout",+ slug: "layout-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "camera",- "slug": "camera-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "bitcoin",+ slug: "bitcoin-logo",+ category_id: 107,+ type_of_icon: "LOGO"},{- "name": "camera-off",- "slug": "camera-off-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "facebook-square",+ slug: "facebook-square-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "folder",- "slug": "folder-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "alarm-off",+ slug: "alarm-off-regular",+ category_id: 120,+ type_of_icon: "REGULAR",+ term: ["alert", "silent"]},{- "name": "folder-plus",- "slug": "folder-plus-solid",- "category_id": 106,- "type_of_icon": "SOLID",- "term": [- "add",- "folder add",- "new folder"- ]+ name: "wrench",+ slug: "wrench-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "award",- "slug": "award-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "loader-circle",+ slug: "loader-circle-regular",+ category_id: 112,+ type_of_icon: "REGULAR"},{- "name": "bar-chart-square",- "slug": "bar-chart-square-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "loader-alt",+ slug: "loader-alt-regular",+ category_id: 112,+ type_of_icon: "REGULAR"},{- "name": "barcode",- "slug": "barcode-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "car",+ slug: "car-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "battery",- "slug": "battery-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "cart-alt",+ slug: "cart-alt-regular",+ category_id: 104,+ type_of_icon: "REGULAR"},{- "name": "battery-charging",- "slug": "battery-charging-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "adjust",+ slug: "adjust-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "battery-full",- "slug": "battery-full-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "alarm",+ slug: "alarm-solid",+ category_id: 120,+ type_of_icon: "SOLID",+ term: ["alert"]},{- "name": "bell",- "slug": "bell-solid",- "category_id": 95,- "type_of_icon": "SOLID",- "term": [- "alert",- "notification"- ]+ name: "alarm-off",+ slug: "alarm-off-solid",+ category_id: 120,+ type_of_icon: "SOLID",+ term: ["alert", "silent"]},{- "name": "bell-off",- "slug": "bell-off-solid",- "category_id": 95,- "type_of_icon": "SOLID",- "term": [- "alert",- "notification",- "silent"- ]+ name: "album",+ slug: "album-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "bolt",- "slug": "bolt-solid",- "category_id": 123,- "type_of_icon": "SOLID",- "term": [- "zap"- ]+ name: "archive",+ slug: "archive-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "book",- "slug": "book-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "camera",+ slug: "camera-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "book-bookmark",- "slug": "book-bookmark-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "camera-off",+ slug: "camera-off-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "bookmark",- "slug": "bookmark-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "folder",+ slug: "folder-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "bookmark-plus",- "slug": "bookmark-plus-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "folder-plus",+ slug: "folder-plus-solid",+ category_id: 106,+ type_of_icon: "SOLID",+ term: ["add", "folder add", "new folder"]},{- "name": "book-open",- "slug": "book-open-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "award",+ slug: "award-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "bookmark-star",- "slug": "bookmark-star-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "bar-chart-square",+ slug: "bar-chart-square-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "briefcase",- "slug": "briefcase-solid",- "category_id": 99,- "type_of_icon": "SOLID",- "term": [- "work",- "travel",- "suitcase"- ]+ name: "barcode",+ slug: "barcode-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "briefcase-alt",- "slug": "briefcase-alt-solid",- "category_id": 99,- "type_of_icon": "SOLID",- "term": [- "work",- "travel",- "suitcase"- ]+ name: "battery",+ slug: "battery-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "bug",- "slug": "bug-solid",- "category_id": 100,- "type_of_icon": "SOLID",- "term": [- "error",- "warning"- ]+ name: "battery-charging",+ slug: "battery-charging-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "building",- "slug": "building-solid",- "category_id": 98,- "type_of_icon": "SOLID"+ name: "battery-full",+ slug: "battery-full-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "bulb",- "slug": "bulb-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "bell",+ slug: "bell-solid",+ category_id: 95,+ type_of_icon: "SOLID",+ term: ["alert", "notification"]},{- "name": "buoy",- "slug": "buoy-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "bell-off",+ slug: "bell-off-solid",+ category_id: 95,+ type_of_icon: "SOLID",+ term: ["alert", "notification", "silent"]},{- "name": "calculator",- "slug": "calculator-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "bolt",+ slug: "bolt-solid",+ category_id: 123,+ type_of_icon: "SOLID",+ term: ["zap"]},{- "name": "captions",- "slug": "captions-solid",- "category_id": 94,- "type_of_icon": "SOLID",- "term": [- "subtitles",- "subs",- "cc"- ]+ name: "book",+ slug: "book-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "car",- "slug": "car-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "book-bookmark",+ slug: "book-bookmark-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "cart-alt",- "slug": "cart-alt-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "bookmark",+ slug: "bookmark-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "cart",- "slug": "cart-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "bookmark-plus",+ slug: "bookmark-plus-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "chart",- "slug": "chart-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "book-open",+ slug: "book-open-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "chip",- "slug": "chip-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "bookmark-star",+ slug: "bookmark-star-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "cloud-download",- "slug": "cloud-download-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "briefcase",+ slug: "briefcase-solid",+ category_id: 99,+ type_of_icon: "SOLID",+ term: ["work", "travel", "suitcase"]},{- "name": "cloud-upload",- "slug": "cloud-upload-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "briefcase-alt",+ slug: "briefcase-alt-solid",+ category_id: 99,+ type_of_icon: "SOLID",+ term: ["work", "travel", "suitcase"]},{- "name": "cloud",- "slug": "cloud-solid",- "category_id": 123,- "type_of_icon": "SOLID"+ name: "bug",+ slug: "bug-solid",+ category_id: 100,+ type_of_icon: "SOLID",+ term: ["error", "warning"]},{- "name": "coffee",- "slug": "coffee-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "building",+ slug: "building-solid",+ category_id: 98,+ type_of_icon: "SOLID"},{- "name": "cog",- "slug": "cog-solid",- "category_id": 110,- "type_of_icon": "SOLID",- "term": [- "gear",- "setting"- ]+ name: "bulb",+ slug: "bulb-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "collection",- "slug": "collection-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "buoy",+ slug: "buoy-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "contact",- "slug": "contact-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "calculator",+ slug: "calculator-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "copy",- "slug": "copy-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "captions",+ slug: "captions-solid",+ category_id: 94,+ type_of_icon: "SOLID",+ term: ["subtitles", "subs", "cc"]},{- "name": "coupon",- "slug": "coupon-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "car",+ slug: "car-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "crown",- "slug": "crown-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "cart-alt",+ slug: "cart-alt-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "cube",- "slug": "cube-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "cart",+ slug: "cart-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "detail",- "slug": "detail-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "chart",+ slug: "chart-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "discount",- "slug": "discount-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "chip",+ slug: "chip-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "dislike",- "slug": "dislike-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "cloud-download",+ slug: "cloud-download-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "dock-bottom",- "slug": "dock-bottom-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "cloud-upload",+ slug: "cloud-upload-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "dock-left",- "slug": "dock-left-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "cloud",+ slug: "cloud-solid",+ category_id: 123,+ type_of_icon: "SOLID"},{- "name": "dock-right",- "slug": "dock-right-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "coffee",+ slug: "coffee-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "dock-top",- "slug": "dock-top-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "cog",+ slug: "cog-solid",+ category_id: 110,+ type_of_icon: "SOLID",+ term: ["gear", "setting"]},{- "name": "down-arrow-circle",- "slug": "down-arrow-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "collection",+ slug: "collection-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "download",- "slug": "download-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "contact",+ slug: "contact-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "downvote",- "slug": "downvote-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "copy",+ slug: "copy-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "drink",- "slug": "drink-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "coupon",+ slug: "coupon-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "droplet",- "slug": "droplet-solid",- "category_id": 123,- "type_of_icon": "SOLID"+ name: "crown",+ slug: "crown-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "duplicate",- "slug": "duplicate-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "cube",+ slug: "cube-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "eject",- "slug": "eject-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "detail",+ slug: "detail-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "envelope",- "slug": "envelope-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "letter",- "mail",- "email",- "communication"- ]+ name: "discount",+ slug: "discount-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "error-circle",- "slug": "error-circle-solid",- "category_id": 95,- "type_of_icon": "SOLID"+ name: "dislike",+ slug: "dislike-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "error",- "slug": "error-solid",- "category_id": 95,- "type_of_icon": "SOLID"+ name: "dock-bottom",+ slug: "dock-bottom-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "file-image",- "slug": "file-image-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "dock-left",+ slug: "dock-left-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "file",- "slug": "file-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "dock-right",+ slug: "dock-right-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "filter-alt",- "slug": "filter-alt-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "dock-top",+ slug: "dock-top-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "first-aid",- "slug": "first-aid-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "down-arrow-circle",+ slug: "down-arrow-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "flag-alt",- "slug": "flag-alt-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "download",+ slug: "download-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "flag",- "slug": "flag-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "downvote",+ slug: "downvote-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "gift",- "slug": "gift-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "drink",+ slug: "drink-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "grid-alt",- "slug": "grid-alt-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "droplet",+ slug: "droplet-solid",+ category_id: 123,+ type_of_icon: "SOLID"},{- "name": "group",- "slug": "group-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "duplicate",+ slug: "duplicate-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "hdd",- "slug": "hdd-solid",- "category_id": 103,- "type_of_icon": "SOLID",- "term": [- "storage",- "hard drive"- ]+ name: "eject",+ slug: "eject-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "heart",- "slug": "heart-solid",- "category_id": 109,- "type_of_icon": "SOLID",- "term": [- "health"- ]+ name: "envelope",+ slug: "envelope-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["letter", "mail", "email", "communication"]},{- "name": "hide",- "slug": "hide-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "error-circle",+ slug: "error-circle-solid",+ category_id: 95,+ type_of_icon: "SOLID"},{- "name": "home",- "slug": "home-solid",- "category_id": 98,- "type_of_icon": "SOLID"+ name: "error",+ slug: "error-solid",+ category_id: 95,+ type_of_icon: "SOLID"},{- "name": "hot",- "slug": "hot-solid",- "category_id": 123,- "type_of_icon": "SOLID",- "term": [- "fire"- ]+ name: "file-image",+ slug: "file-image-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "hourglass",- "slug": "hourglass-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "file",+ slug: "file-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "image",- "slug": "image-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "filter-alt",+ slug: "filter-alt-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "inbox",- "slug": "inbox-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "first-aid",+ slug: "first-aid-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "info-circle",- "slug": "info-circle-solid",- "category_id": 94,- "type_of_icon": "SOLID"+ name: "flag-alt",+ slug: "flag-alt-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "joystick-alt",- "slug": "joystick-alt-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "flag",+ slug: "flag-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "joystick",- "slug": "joystick-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "gift",+ slug: "gift-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "layer",- "slug": "layer-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "grid-alt",+ slug: "grid-alt-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "left-arrow-circle",- "slug": "left-arrow-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "group",+ slug: "group-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "like",- "slug": "like-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "hdd",+ slug: "hdd-solid",+ category_id: 103,+ type_of_icon: "SOLID",+ term: ["storage", "hard drive"]},{- "name": "lock-open",- "slug": "lock-open-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "heart",+ slug: "heart-solid",+ category_id: 109,+ type_of_icon: "SOLID",+ term: ["health"]},{- "name": "lock",- "slug": "lock-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "hide",+ slug: "hide-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "map-alt",- "slug": "map-alt-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "home",+ slug: "home-solid",+ category_id: 98,+ type_of_icon: "SOLID"},{- "name": "map",- "slug": "map-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "hot",+ slug: "hot-solid",+ category_id: 123,+ type_of_icon: "SOLID",+ term: ["fire"]},{- "name": "message-rounded",- "slug": "message-rounded-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "hourglass",+ slug: "hourglass-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "message",- "slug": "message-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "image",+ slug: "image-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "microphone-off",- "slug": "microphone-off-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "inbox",+ slug: "inbox-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "microphone",- "slug": "microphone-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "info-circle",+ slug: "info-circle-solid",+ category_id: 94,+ type_of_icon: "SOLID"},{- "name": "minus-circle",- "slug": "minus-circle-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "joystick-alt",+ slug: "joystick-alt-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "moon",- "slug": "moon-solid",- "category_id": 123,- "type_of_icon": "SOLID"+ name: "joystick",+ slug: "joystick-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "mouse",- "slug": "mouse-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "layer",+ slug: "layer-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "music",- "slug": "music-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "left-arrow-circle",+ slug: "left-arrow-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "navigation",- "slug": "navigation-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "like",+ slug: "like-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "news",- "slug": "news-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "lock-open",+ slug: "lock-open-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "package",- "slug": "package-solid",- "category_id": 104,- "type_of_icon": "SOLID",- "term": [- "box",- "shipping",- "delivery"- ]+ name: "lock",+ slug: "lock-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "paper-plane",- "slug": "paper-plane-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "map-alt",+ slug: "map-alt-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "paste",- "slug": "paste-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "map",+ slug: "map-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "pen",- "slug": "pen-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "message-rounded",+ slug: "message-rounded-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "pencil",- "slug": "pencil-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "message",+ slug: "message-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "phone-call",- "slug": "phone-call-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "microphone-off",+ slug: "microphone-off-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "phone-incoming",- "slug": "phone-incoming-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "microphone",+ slug: "microphone-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "phone-outgoing",- "slug": "phone-outgoing-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "minus-circle",+ slug: "minus-circle-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "phone",- "slug": "phone-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "moon",+ slug: "moon-solid",+ category_id: 123,+ type_of_icon: "SOLID"},{- "name": "pie-chart-alt",- "slug": "pie-chart-alt-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "mouse",+ slug: "mouse-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "pie-chart",- "slug": "pie-chart-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "music",+ slug: "music-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "pin",- "slug": "pin-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "navigation",+ slug: "navigation-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "playlist",- "slug": "playlist-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "news",+ slug: "news-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "plug",- "slug": "plug-solid",- "category_id": 116,- "type_of_icon": "SOLID",- "term": [- "charging"- ]+ name: "package",+ slug: "package-solid",+ category_id: 104,+ type_of_icon: "SOLID",+ term: ["box", "shipping", "delivery"]},{- "name": "plus-circle",- "slug": "plus-circle-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "paper-plane",+ slug: "paper-plane-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "printer",- "slug": "printer-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "paste",+ slug: "paste-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "purchase-tag",- "slug": "purchase-tag-solid",- "category_id": 104,- "type_of_icon": "SOLID",- "term": [- "price",- "cost"- ]+ name: "pen",+ slug: "pen-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "quote-left",- "slug": "quote-left-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "pencil",+ slug: "pencil-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "quote-right",- "slug": "quote-right-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "phone-call",+ slug: "phone-call-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "radio",- "slug": "radio-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "phone-incoming",+ slug: "phone-incoming-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "rename",- "slug": "rename-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "phone-outgoing",+ slug: "phone-outgoing-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "report",- "slug": "report-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "phone",+ slug: "phone-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "right-arrow-circle",- "slug": "right-arrow-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "pie-chart-alt",+ slug: "pie-chart-alt-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "ruler",- "slug": "ruler-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "pie-chart",+ slug: "pie-chart-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "save",- "slug": "save-solid",- "category_id": 116,- "type_of_icon": "SOLID",- "term": [- "floppy disk"- ]+ name: "pin",+ slug: "pin-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "sort-alt",- "slug": "sort-alt-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "playlist",+ slug: "playlist-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "select-multiple",- "slug": "select-multiple-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "plug",+ slug: "plug-solid",+ category_id: 116,+ type_of_icon: "SOLID",+ term: ["charging"]},{- "name": "send",- "slug": "send-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "plus-circle",+ slug: "plus-circle-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "server",- "slug": "server-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "printer",+ slug: "printer-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "share-alt",- "slug": "share-alt-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "purchase-tag",+ slug: "purchase-tag-solid",+ category_id: 104,+ type_of_icon: "SOLID",+ term: ["price", "cost"]},{- "name": "share",- "slug": "share-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "quote-left",+ slug: "quote-left-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "shield",- "slug": "shield-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "quote-right",+ slug: "quote-right-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "shopping-bag-alt",- "slug": "shopping-bag-alt-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "radio",+ slug: "radio-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "shopping-bag",- "slug": "shopping-bag-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "rename",+ slug: "rename-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "show",- "slug": "show-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "report",+ slug: "report-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "happy",- "slug": "happy-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "right-arrow-circle",+ slug: "right-arrow-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "meh",- "slug": "meh-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "ruler",+ slug: "ruler-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "sad",- "slug": "sad-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "save",+ slug: "save-solid",+ category_id: 116,+ type_of_icon: "SOLID",+ term: ["floppy disk"]},{- "name": "spreadsheet",- "slug": "spreadsheet-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "sort-alt",+ slug: "sort-alt-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "star",- "slug": "star-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "select-multiple",+ slug: "select-multiple-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "store",- "slug": "store-solid",- "category_id": 104,- "type_of_icon": "SOLID",- "term": [- "shop",- "market"- ]+ name: "send",+ slug: "send-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "sun",- "slug": "sun-solid",- "category_id": 123,- "type_of_icon": "SOLID"+ name: "server",+ slug: "server-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "t-shirt",- "slug": "t-shirt-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "share-alt",+ slug: "share-alt-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "tag-x",- "slug": "tag-x-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "share",+ slug: "share-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "tag",- "slug": "tag-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "shield",+ slug: "shield-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "tennis-ball",- "slug": "tennis-ball-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "deuce"- ]+ name: "shopping-bag-alt",+ slug: "shopping-bag-alt-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "terminal",- "slug": "terminal-solid",- "category_id": 100,- "type_of_icon": "SOLID",- "term": [- "command line"- ]+ name: "shopping-bag",+ slug: "shopping-bag-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "to-top",- "slug": "to-top-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "show",+ slug: "show-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "toggle-left",- "slug": "toggle-left-solid",- "category_id": 110,- "type_of_icon": "SOLID",- "term": [- "switch"- ]+ name: "happy",+ slug: "happy-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "toggle-right",- "slug": "toggle-right-solid",- "category_id": 110,- "type_of_icon": "SOLID",- "term": [- "switch"- ]+ name: "meh",+ slug: "meh-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "torch",- "slug": "torch-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "sad",+ slug: "sad-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "trash-alt",- "slug": "trash-alt-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "spreadsheet",+ slug: "spreadsheet-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "trash",- "slug": "trash-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "star",+ slug: "star-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "trophy",- "slug": "trophy-solid",- "category_id": 119,- "type_of_icon": "SOLID"+ name: "store",+ slug: "store-solid",+ category_id: 104,+ type_of_icon: "SOLID",+ term: ["shop", "market"]},{- "name": "truck",- "slug": "truck-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "sun",+ slug: "sun-solid",+ category_id: 123,+ type_of_icon: "SOLID"},{- "name": "up-arrow-circle",- "slug": "up-arrow-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "t-shirt",+ slug: "t-shirt-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "upvote",- "slug": "upvote-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "tag-x",+ slug: "tag-x-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "user-circle",- "slug": "user-circle-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "tag",+ slug: "tag-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "user-detail",- "slug": "user-detail-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "tennis-ball",+ slug: "tennis-ball-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["deuce"]},{- "name": "user-minus",- "slug": "user-minus-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "terminal",+ slug: "terminal-solid",+ category_id: 100,+ type_of_icon: "SOLID",+ term: ["command line"]},{- "name": "user-plus",- "slug": "user-plus-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "to-top",+ slug: "to-top-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "user",- "slug": "user-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "toggle-left",+ slug: "toggle-left-solid",+ category_id: 110,+ type_of_icon: "SOLID",+ term: ["switch"]},{- "name": "video-off",- "slug": "video-off-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "toggle-right",+ slug: "toggle-right-solid",+ category_id: 110,+ type_of_icon: "SOLID",+ term: ["switch"]},{- "name": "video",- "slug": "video-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "torch",+ slug: "torch-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "videos",- "slug": "videos-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "trash-alt",+ slug: "trash-alt-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "volume-full",- "slug": "volume-full-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "trash",+ slug: "trash-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "volume-low",- "slug": "volume-low-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "trophy",+ slug: "trophy-solid",+ category_id: 119,+ type_of_icon: "SOLID"},{- "name": "volume-mute",- "slug": "volume-mute-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "truck",+ slug: "truck-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "volume",- "slug": "volume-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "up-arrow-circle",+ slug: "up-arrow-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "wallet",- "slug": "wallet-solid",- "category_id": 107,- "type_of_icon": "SOLID",- "term": [- "money"- ]+ name: "upvote",+ slug: "upvote-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "watch-alt",- "slug": "watch-alt-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "user-circle",+ slug: "user-circle-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "watch",- "slug": "watch-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "user-detail",+ slug: "user-detail-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "widget",- "slug": "widget-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "user-minus",+ slug: "user-minus-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "wrench",- "slug": "wrench-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "user-plus",+ slug: "user-plus-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "x-circle",- "slug": "x-circle-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "user",+ slug: "user-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "zap",- "slug": "zap-solid",- "category_id": 123,- "type_of_icon": "SOLID",- "term": [- "bolt"- ]+ name: "video-off",+ slug: "video-off-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "folder-open",- "slug": "folder-open-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "video",+ slug: "video-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "battery-low",- "slug": "battery-low-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "videos",+ slug: "videos-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "conversation",- "slug": "conversation-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "discussion"- ]+ name: "volume-full",+ slug: "volume-full-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "dashboard",- "slug": "dashboard-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "volume-low",+ slug: "volume-low-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "file-plus",- "slug": "file-plus-solid",- "category_id": 106,- "type_of_icon": "SOLID",- "term": [- "add",- "file add",- "new file"- ]+ name: "volume-mute",+ slug: "volume-mute-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "slider-alt",- "slug": "slider-alt-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "volume",+ slug: "volume-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "google-plus",- "slug": "google-plus-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "wallet",+ slug: "wallet-solid",+ category_id: 107,+ type_of_icon: "SOLID",+ term: ["money"]},{- "name": "google-plus-circle",- "slug": "google-plus-circle-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "watch-alt",+ slug: "watch-alt-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "linkedin-square",- "slug": "linkedin-square-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "watch",+ slug: "watch-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "medium",- "slug": "medium-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "widget",+ slug: "widget-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "medium-square",- "slug": "medium-square-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "wrench",+ slug: "wrench-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "skype",- "slug": "skype-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "x-circle",+ slug: "x-circle-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "slack-old",- "slug": "slack-old-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "zap",+ slug: "zap-solid",+ category_id: 123,+ type_of_icon: "SOLID",+ term: ["bolt"]},{- "name": "slack",- "slug": "slack-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "folder-open",+ slug: "folder-open-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "twitch",- "slug": "twitch-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "battery-low",+ slug: "battery-low-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "discord",- "slug": "discord-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "conversation",+ slug: "conversation-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "discussion"]},{- "name": "reddit",- "slug": "reddit-logo",- "category_id": 97,- "type_of_icon": "LOGO",- "term": [- "social media"- ]+ name: "dashboard",+ slug: "dashboard-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "pinterest",- "slug": "pinterest-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "file-plus",+ slug: "file-plus-solid",+ category_id: 106,+ type_of_icon: "SOLID",+ term: ["add", "file add", "new file"]},{- "name": "blogger",- "slug": "blogger-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "slider-alt",+ slug: "slider-alt-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "certification",- "slug": "certification-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "google-plus",+ slug: "google-plus-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "certification",- "slug": "certification-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "google-plus-circle",+ slug: "google-plus-circle-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "rocket",- "slug": "rocket-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "linkedin-square",+ slug: "linkedin-square-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "rocket",- "slug": "rocket-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "medium",+ slug: "medium-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "check-circle",- "slug": "check-circle-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "medium-square",+ slug: "medium-square-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "check-circle",- "slug": "check-circle-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "skype",+ slug: "skype-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "checkbox",- "slug": "checkbox-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "slack-old",+ slug: "slack-old-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "checkbox-checked",- "slug": "checkbox-checked-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "slack",+ slug: "slack-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "star-half",- "slug": "star-half-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "twitch",+ slug: "twitch-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "bus",- "slug": "bus-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "discord",+ slug: "discord-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "bus",- "slug": "bus-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "reddit",+ slug: "reddit-logo",+ category_id: 97,+ type_of_icon: "LOGO",+ term: ["social media"]},{- "name": "check-double",- "slug": "check-double-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "pinterest",+ slug: "pinterest-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "dumbbell",- "slug": "dumbbell-regular",- "category_id": 109,- "type_of_icon": "REGULAR",- "term": [- "gym",- "workout"- ]+ name: "blogger",+ slug: "blogger-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "bot",- "slug": "bot-regular",- "category_id": 105,- "type_of_icon": "REGULAR"+ name: "certification",+ slug: "certification-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "area",- "slug": "area-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "certification",+ slug: "certification-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "bot",- "slug": "bot-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "rocket",+ slug: "rocket-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "area",- "slug": "area-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "rocket",+ slug: "rocket-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "bed",- "slug": "bed-regular",- "category_id": 109,- "type_of_icon": "REGULAR",- "term": [- "sleep"- ]+ name: "check-circle",+ slug: "check-circle-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "bed",- "slug": "bed-solid",- "category_id": 109,- "type_of_icon": "SOLID",- "term": [- "sleep"- ]+ name: "check-circle",+ slug: "check-circle-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "bath",- "slug": "bath-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "checkbox",+ slug: "checkbox-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "bath",- "slug": "bath-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "checkbox-checked",+ slug: "checkbox-checked-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "train",- "slug": "train-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "star-half",+ slug: "star-half-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "train",- "slug": "train-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "bus",+ slug: "bus-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "taxi",- "slug": "taxi-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "bus",+ slug: "bus-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "taxi",- "slug": "taxi-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "check-double",+ slug: "check-double-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "movie",- "slug": "movie-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "dumbbell",+ slug: "dumbbell-regular",+ category_id: 109,+ type_of_icon: "REGULAR",+ term: ["gym", "workout"]},{- "name": "movie",- "slug": "movie-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "bot",+ slug: "bot-regular",+ category_id: 105,+ type_of_icon: "REGULAR"},{- "name": "hotel",- "slug": "hotel-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "area",+ slug: "area-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "planet",- "slug": "planet-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "bot",+ slug: "bot-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "planet",- "slug": "planet-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "area",+ slug: "area-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "list-ol",- "slug": "list-ol-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "bed",+ slug: "bed-regular",+ category_id: 109,+ type_of_icon: "REGULAR",+ term: ["sleep"]},{- "name": "video-plus",- "slug": "video-plus-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "bed",+ slug: "bed-solid",+ category_id: 109,+ type_of_icon: "SOLID",+ term: ["sleep"]},{- "name": "video-plus",- "slug": "video-plus-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "bath",+ slug: "bath-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "menu-alt-left",- "slug": "menu-alt-left-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "bath",+ slug: "bath-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "menu-alt-right",- "slug": "menu-alt-right-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "train",+ slug: "train-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "box",- "slug": "box-regular",- "category_id": 106,- "type_of_icon": "REGULAR",- "term": [- "archive"- ]+ name: "train",+ slug: "train-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "box",- "slug": "box-solid",- "category_id": 106,- "type_of_icon": "SOLID",- "term": [- "archive"- ]+ name: "taxi",+ slug: "taxi-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "key",- "slug": "key-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "taxi",+ slug: "taxi-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "restaurant",- "slug": "restaurant-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "movie",+ slug: "movie-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "swim",- "slug": "swim-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "movie",+ slug: "movie-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "water",- "slug": "water-regular",- "category_id": 123,- "type_of_icon": "REGULAR"+ name: "hotel",+ slug: "hotel-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "wind",- "slug": "wind-regular",- "category_id": 123,- "type_of_icon": "REGULAR",- "term": [- "breeze",- "gust",- "air"- ]+ name: "planet",+ slug: "planet-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "dialpad",- "slug": "dialpad-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "keypad"- ]+ name: "planet",+ slug: "planet-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "handicap",- "slug": "handicap-regular",- "category_id": 94,- "type_of_icon": "REGULAR",- "term": [- "wheelchair",- "injury"- ]+ name: "list-ol",+ slug: "list-ol-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "font-size",- "slug": "font-size-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "video-plus",+ slug: "video-plus-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "code-block",- "slug": "code-block-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "video-plus",+ slug: "video-plus-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "photo-album",- "slug": "photo-album-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "menu-alt-left",+ slug: "menu-alt-left-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "photo-album",- "slug": "photo-album-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "menu-alt-right",+ slug: "menu-alt-right-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "bell-ring",- "slug": "bell-ring-solid",- "category_id": 95,- "type_of_icon": "SOLID",- "term": [- "alert",- "notification"- ]+ name: "box",+ slug: "box-regular",+ category_id: 106,+ type_of_icon: "REGULAR",+ term: ["archive"]},{- "name": "apple",- "slug": "apple-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "box",+ slug: "box-solid",+ category_id: 106,+ type_of_icon: "SOLID",+ term: ["archive"]},{- "name": "android",- "slug": "android-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "key",+ slug: "key-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "play-store",- "slug": "play-store-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "restaurant",+ slug: "restaurant-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "windows",- "slug": "windows-logo",- "category_id": 97,- "type_of_icon": "LOGO",- "term": [- "browser"- ]+ name: "swim",+ slug: "swim-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "vk",- "slug": "vk-logo",- "category_id": 97,- "type_of_icon": "LOGO",- "term": [- "social media"- ]+ name: "water",+ slug: "water-regular",+ category_id: 123,+ type_of_icon: "REGULAR"},{- "name": "pocket",- "slug": "pocket-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "wind",+ slug: "wind-regular",+ category_id: 123,+ type_of_icon: "REGULAR",+ term: ["breeze", "gust", "air"]},{- "name": "strikethrough",- "slug": "strikethrough-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "dialpad",+ slug: "dialpad-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["keypad"]},{- "name": "file-blank",- "slug": "file-blank-regular",- "category_id": 106,- "type_of_icon": "REGULAR"+ name: "handicap",+ slug: "handicap-regular",+ category_id: 94,+ type_of_icon: "REGULAR",+ term: ["wheelchair", "injury"]},{- "name": "file-blank",- "slug": "file-blank-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "font-size",+ slug: "font-size-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "highlight",- "slug": "highlight-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "code-block",+ slug: "code-block-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "font-color",- "slug": "font-color-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "photo-album",+ slug: "photo-album-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "fingerprint",- "slug": "fingerprint-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "photo-album",+ slug: "photo-album-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "transfer",- "slug": "transfer-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "bell-ring",+ slug: "bell-ring-solid",+ category_id: 95,+ type_of_icon: "SOLID",+ term: ["alert", "notification"]},{- "name": "circle",- "slug": "circle-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "apple",+ slug: "apple-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "edit",- "slug": "edit-solid",- "category_id": 124,- "type_of_icon": "SOLID",- "term": [- "writing",- "note",- "pencil"- ]+ name: "android",+ slug: "android-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "ball",- "slug": "ball-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "football",- "rugby"- ]+ name: "play-store",+ slug: "play-store-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "ball",- "slug": "ball-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "football",- "rugby"- ]+ name: "windows",+ slug: "windows-logo",+ category_id: 97,+ type_of_icon: "LOGO",+ term: ["browser"]},{- "name": "football",- "slug": "football-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "soccer",- "goal"- ]+ name: "vk",+ slug: "vk-logo",+ category_id: 97,+ type_of_icon: "LOGO",+ term: ["social media"]},{- "name": "film",- "slug": "film-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "pocket",+ slug: "pocket-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "dollar-circle",- "slug": "dollar-circle-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "strikethrough",+ slug: "strikethrough-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "dollar-circle",- "slug": "dollar-circle-solid",- "category_id": 107,- "type_of_icon": "SOLID"+ name: "file-blank",+ slug: "file-blank-regular",+ category_id: 106,+ type_of_icon: "REGULAR"},{- "name": "skull",- "slug": "skull-solid",- "category_id": 105,- "type_of_icon": "SOLID"+ name: "file-blank",+ slug: "file-blank-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "messenger",- "slug": "messenger-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "highlight",+ slug: "highlight-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "search-alt",- "slug": "search-alt-regular",- "category_id": 110,- "type_of_icon": "REGULAR",- "term": [- "magnifying glass"- ]+ name: "font-color",+ slug: "font-color-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "image-alt",- "slug": "image-alt-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "fingerprint",+ slug: "fingerprint-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "microphone-alt",- "slug": "microphone-alt-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "transfer",+ slug: "transfer-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "analyse",- "slug": "analyse-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "circle",+ slug: "circle-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "x-square",- "slug": "x-square-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "edit",+ slug: "edit-solid",+ category_id: 124,+ type_of_icon: "SOLID",+ term: ["writing", "note", "pencil"]},{- "name": "plus-square",- "slug": "plus-square-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "ball",+ slug: "ball-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["football", "rugby"]},{- "name": "minus-square",- "slug": "minus-square-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "ball",+ slug: "ball-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["football", "rugby"]},{- "name": "disc",- "slug": "disc-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "football",+ slug: "football-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["soccer", "goal"]},{- "name": "disc",- "slug": "disc-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "film",+ slug: "film-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "equalizer",- "slug": "equalizer-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "dollar-circle",+ slug: "dollar-circle-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "stats",- "slug": "stats-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "dollar-circle",+ slug: "dollar-circle-solid",+ category_id: 107,+ type_of_icon: "SOLID"},{- "name": "move-horizontal",- "slug": "move-horizontal-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "skull",+ slug: "skull-solid",+ category_id: 105,+ type_of_icon: "SOLID"},{- "name": "move-vertical",- "slug": "move-vertical-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "messenger",+ slug: "messenger-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "flame",- "slug": "flame-solid",- "category_id": 123,- "type_of_icon": "SOLID"+ name: "search-alt",+ slug: "search-alt-regular",+ category_id: 110,+ type_of_icon: "REGULAR",+ term: ["magnifying glass"]},{- "name": "grid-horizontal",- "slug": "grid-horizontal-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "image-alt",+ slug: "image-alt-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "grid-vertical",- "slug": "grid-vertical-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "microphone-alt",+ slug: "microphone-alt-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "grid-small",- "slug": "grid-small-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "analyse",+ slug: "analyse-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "badge",- "slug": "badge-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "x-square",+ slug: "x-square-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "badge",- "slug": "badge-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "plus-square",+ slug: "plus-square-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "id-card",- "slug": "id-card-regular",- "category_id": 122,- "type_of_icon": "REGULAR"+ name: "minus-square",+ slug: "minus-square-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "sort-up",- "slug": "sort-up-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "disc",+ slug: "disc-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "sort-down",- "slug": "sort-down-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "disc",+ slug: "disc-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "note",- "slug": "note-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "equalizer",+ slug: "equalizer-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "note",- "slug": "note-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "stats",+ slug: "stats-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "test-tube",- "slug": "test-tube-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "move-horizontal",+ slug: "move-horizontal-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "help-circle",- "slug": "help-circle-regular",- "category_id": 94,- "type_of_icon": "REGULAR"+ name: "move-vertical",+ slug: "move-vertical-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "help-circle",- "slug": "help-circle-solid",- "category_id": 94,- "type_of_icon": "SOLID"+ name: "flame",+ slug: "flame-solid",+ category_id: 123,+ type_of_icon: "SOLID"},{- "name": "card",- "slug": "card-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "grid-horizontal",+ slug: "grid-horizontal-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "card",- "slug": "card-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "grid-vertical",+ slug: "grid-vertical-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "rewind-circle",- "slug": "rewind-circle-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "grid-small",+ slug: "grid-small-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "magnet",- "slug": "magnet-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "badge",+ slug: "badge-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "magnet",- "slug": "magnet-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "badge",+ slug: "badge-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "500px",- "slug": "500px-logo",- "category_id": 117,- "type_of_icon": "LOGO"+ name: "id-card",+ slug: "id-card-regular",+ category_id: 122,+ type_of_icon: "REGULAR"},{- "name": "angular",- "slug": "angular-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "sort-up",+ slug: "sort-up-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "codepen",- "slug": "codepen-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "sort-down",+ slug: "sort-down-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "creative-commons",- "slug": "creative-commons-logo",- "category_id": 117,- "type_of_icon": "LOGO"+ name: "note",+ slug: "note-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "digitalocean",- "slug": "digitalocean-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "note",+ slug: "note-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "deviantart",- "slug": "deviantart-logo",- "category_id": 117,- "type_of_icon": "LOGO"+ name: "test-tube",+ slug: "test-tube-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "discourse",- "slug": "discourse-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "help-circle",+ slug: "help-circle-regular",+ category_id: 94,+ type_of_icon: "REGULAR"},{- "name": "dropbox",- "slug": "dropbox-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "help-circle",+ slug: "help-circle-solid",+ category_id: 94,+ type_of_icon: "SOLID"},{- "name": "drupal",- "slug": "drupal-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "card",+ slug: "card-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "ebay",- "slug": "ebay-logo",- "category_id": 104,- "type_of_icon": "LOGO"+ name: "card",+ slug: "card-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "amazon",- "slug": "amazon-logo",- "category_id": 104,- "type_of_icon": "LOGO"+ name: "rewind-circle",+ slug: "rewind-circle-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "digg",- "slug": "digg-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "magnet",+ slug: "magnet-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "unsplash",- "slug": "unsplash-logo",- "category_id": 117,- "type_of_icon": "LOGO"+ name: "magnet",+ slug: "magnet-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "wikipedia",- "slug": "wikipedia-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "500px",+ slug: "500px-logo",+ category_id: 117,+ type_of_icon: "LOGO"},{- "name": "sass",- "slug": "sass-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "angular",+ slug: "angular-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "foursquare",- "slug": "foursquare-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "codepen",+ slug: "codepen-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "invision",- "slug": "invision-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "creative-commons",+ slug: "creative-commons-logo",+ category_id: 117,+ type_of_icon: "LOGO"},{- "name": "opera",- "slug": "opera-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "digitalocean",+ slug: "digitalocean-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "airbnb",- "slug": "airbnb-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "deviantart",+ slug: "deviantart-logo",+ category_id: 117,+ type_of_icon: "LOGO"},{- "name": "yelp",- "slug": "yelp-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "discourse",+ slug: "discourse-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "quora",- "slug": "quora-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "dropbox",+ slug: "dropbox-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "git",- "slug": "git-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "drupal",+ slug: "drupal-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "html5",- "slug": "html5-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "ebay",+ slug: "ebay-logo",+ category_id: 104,+ type_of_icon: "LOGO"},{- "name": "product-hunt",- "slug": "product-hunt-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "amazon",+ slug: "amazon-logo",+ category_id: 104,+ type_of_icon: "LOGO"},{- "name": "magento",- "slug": "magento-logo",- "category_id": 104,- "type_of_icon": "LOGO"+ name: "digg",+ slug: "digg-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "stack-overflow",- "slug": "stack-overflow-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "unsplash",+ slug: "unsplash-logo",+ category_id: 117,+ type_of_icon: "LOGO"},{- "name": "firefox",- "slug": "firefox-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "wikipedia",+ slug: "wikipedia-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "javascript",- "slug": "javascript-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "sass",+ slug: "sass-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "nodejs",- "slug": "nodejs-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "foursquare",+ slug: "foursquare-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "kickstarter",- "slug": "kickstarter-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "invision",+ slug: "invision-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "vuejs",- "slug": "vuejs-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "opera",+ slug: "opera-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "bing",- "slug": "bing-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "airbnb",+ slug: "airbnb-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "react",- "slug": "react-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "yelp",+ slug: "yelp-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "periscope",- "slug": "periscope-logo",- "category_id": 117,- "type_of_icon": "LOGO"+ name: "quora",+ slug: "quora-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "wordpress",- "slug": "wordpress-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "git",+ slug: "git-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "telegram",- "slug": "telegram-logo",- "category_id": 101,- "type_of_icon": "LOGO"+ name: "html5",+ slug: "html5-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "stripe",- "slug": "stripe-logo",- "category_id": 107,- "type_of_icon": "LOGO"+ name: "product-hunt",+ slug: "product-hunt-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "edge",- "slug": "edge-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "magento",+ slug: "magento-logo",+ category_id: 104,+ type_of_icon: "LOGO"},{- "name": "paypal",- "slug": "paypal-logo",- "category_id": 107,- "type_of_icon": "LOGO"+ name: "stack-overflow",+ slug: "stack-overflow-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "internet-explorer",- "slug": "internet-explorer-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "firefox",+ slug: "firefox-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "joomla",- "slug": "joomla-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "javascript",+ slug: "javascript-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "dailymotion",- "slug": "dailymotion-logo",- "category_id": 117,- "type_of_icon": "LOGO"+ name: "nodejs",+ slug: "nodejs-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "chrome",- "slug": "chrome-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "kickstarter",+ slug: "kickstarter-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "baidu",- "slug": "baidu-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "vuejs",+ slug: "vuejs-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "visa",- "slug": "visa-logo",- "category_id": 107,- "type_of_icon": "LOGO"+ name: "bing",+ slug: "bing-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "mastercard",- "slug": "mastercard-logo",- "category_id": 107,- "type_of_icon": "LOGO"+ name: "react",+ slug: "react-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "redux",- "slug": "redux-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "periscope",+ slug: "periscope-logo",+ category_id: 117,+ type_of_icon: "LOGO"},{- "name": "bootstrap",- "slug": "bootstrap-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "wordpress",+ slug: "wordpress-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "yahoo",- "slug": "yahoo-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "telegram",+ slug: "telegram-logo",+ category_id: 101,+ type_of_icon: "LOGO"},{- "name": "microsoft",- "slug": "microsoft-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "stripe",+ slug: "stripe-logo",+ category_id: 107,+ type_of_icon: "LOGO"},{- "name": "css3",- "slug": "css3-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "edge",+ slug: "edge-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "jsfiddle",- "slug": "jsfiddle-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "paypal",+ slug: "paypal-logo",+ category_id: 107,+ type_of_icon: "LOGO"},{- "name": "shopify",- "slug": "shopify-logo",- "category_id": 104,- "type_of_icon": "LOGO"+ name: "internet-explorer",+ slug: "internet-explorer-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "flickr",- "slug": "flickr-logo",- "category_id": 117,- "type_of_icon": "LOGO"+ name: "joomla",+ slug: "joomla-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "less",- "slug": "less-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "dailymotion",+ slug: "dailymotion-logo",+ category_id: 117,+ type_of_icon: "LOGO"},{- "name": "snapchat",- "slug": "snapchat-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "chrome",+ slug: "chrome-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "soundcloud",- "slug": "soundcloud-logo",- "category_id": 114,- "type_of_icon": "LOGO"+ name: "baidu",+ slug: "baidu-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "spotify",- "slug": "spotify-logo",- "category_id": 114,- "type_of_icon": "LOGO"+ name: "visa",+ slug: "visa-logo",+ category_id: 107,+ type_of_icon: "LOGO"},{- "name": "trello",- "slug": "trello-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "mastercard",+ slug: "mastercard-logo",+ category_id: 107,+ type_of_icon: "LOGO"},{- "name": "wix",- "slug": "wix-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "redux",+ slug: "redux-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "mailchimp",- "slug": "mailchimp-logo",- "category_id": 101,- "type_of_icon": "LOGO"+ name: "bootstrap",+ slug: "bootstrap-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "medium-old",- "slug": "medium-old-logo",- "category_id": 124,- "type_of_icon": "LOGO"+ name: "yahoo",+ slug: "yahoo-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "squarespace",- "slug": "squarespace-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "microsoft",+ slug: "microsoft-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "whatsapp-square",- "slug": "whatsapp-square-logo",- "category_id": 101,- "type_of_icon": "LOGO"+ name: "css3",+ slug: "css3-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "flickr-square",- "slug": "flickr-square-logo",- "category_id": 117,- "type_of_icon": "LOGO"+ name: "jsfiddle",+ slug: "jsfiddle-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "ambulance",- "slug": "ambulance-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "shopify",+ slug: "shopify-logo",+ category_id: 104,+ type_of_icon: "LOGO"},{- "name": "left-arrow-square",- "slug": "left-arrow-square-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "flickr",+ slug: "flickr-logo",+ category_id: 117,+ type_of_icon: "LOGO"},{- "name": "up-arrow-square",- "slug": "up-arrow-square-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "less",+ slug: "less-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "down-arrow-square",- "slug": "down-arrow-square-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "snapchat",+ slug: "snapchat-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "right-arrow-square",- "slug": "right-arrow-square-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "soundcloud",+ slug: "soundcloud-logo",+ category_id: 114,+ type_of_icon: "LOGO"},{- "name": "user-badge",- "slug": "user-badge-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "spotify",+ slug: "spotify-logo",+ category_id: 114,+ type_of_icon: "LOGO"},{- "name": "calendar-event",- "slug": "calendar-event-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "trello",+ slug: "trello-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "caret-left",- "slug": "caret-left-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "wix",+ slug: "wix-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "caret-up",- "slug": "caret-up-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "mailchimp",+ slug: "mailchimp-logo",+ category_id: 101,+ type_of_icon: "LOGO"},{- "name": "caret-right",- "slug": "caret-right-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "medium-old",+ slug: "medium-old-logo",+ category_id: 124,+ type_of_icon: "LOGO"},{- "name": "caret-down",- "slug": "caret-down-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "squarespace",+ slug: "squarespace-logo",+ category_id: 97,+ type_of_icon: "LOGO"},{- "name": "gas-pump",- "slug": "gas-pump-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "whatsapp-square",+ slug: "whatsapp-square-logo",+ category_id: 101,+ type_of_icon: "LOGO"},{- "name": "landmark",- "slug": "landmark-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "flickr-square",+ slug: "flickr-square-logo",+ category_id: 117,+ type_of_icon: "LOGO"},{- "name": "show-alt",- "slug": "show-alt-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "ambulance",+ slug: "ambulance-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "badge-check",- "slug": "badge-check-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "left-arrow-square",+ slug: "left-arrow-square-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "badge-check",- "slug": "badge-check-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "up-arrow-square",+ slug: "up-arrow-square-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "rotate-left",- "slug": "rotate-left-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "down-arrow-square",+ slug: "down-arrow-square-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "coffee-alt",- "slug": "coffee-alt-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "right-arrow-square",+ slug: "right-arrow-square-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "brush",- "slug": "brush-regular",- "category_id": 102,- "type_of_icon": "REGULAR",- "term": [- "color",- "colour",- "painting"- ]+ name: "user-badge",+ slug: "user-badge-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "brush",- "slug": "brush-solid",- "category_id": 102,- "type_of_icon": "SOLID",- "term": [- "color",- "colour",- "painting"- ]+ name: "calendar-event",+ slug: "calendar-event-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "keyboard",- "slug": "keyboard-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "caret-left",+ slug: "caret-left-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "megaphone",- "slug": "megaphone-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "caret-up",+ slug: "caret-up-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "directions",- "slug": "directions-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "caret-right",+ slug: "caret-right-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "direction-right",- "slug": "direction-right-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "caret-down",+ slug: "caret-down-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "unlink",- "slug": "unlink-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "gas-pump",+ slug: "gas-pump-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "paint",- "slug": "paint-regular",- "category_id": 102,- "type_of_icon": "REGULAR"+ name: "landmark",+ slug: "landmark-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "joystick-button",- "slug": "joystick-button-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "show-alt",+ slug: "show-alt-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "joystick-button",- "slug": "joystick-button-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "badge-check",+ slug: "badge-check-regular",+ category_id: 118,+ type_of_icon: "REGULAR"},{- "name": "font-family",- "slug": "font-family-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "badge-check",+ slug: "badge-check-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "flask",- "slug": "flask-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "rotate-left",+ slug: "rotate-left-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "capsule",- "slug": "capsule-solid",- "category_id": 109,- "type_of_icon": "SOLID",- "term": [- "medicine"- ]+ name: "coffee-alt",+ slug: "coffee-alt-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "color-fill",- "slug": "color-fill-solid",- "category_id": 102,- "type_of_icon": "SOLID"+ name: "brush",+ slug: "brush-regular",+ category_id: 102,+ type_of_icon: "REGULAR",+ term: ["color", "colour", "painting"]},{- "name": "hotel",- "slug": "hotel-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "brush",+ slug: "brush-solid",+ category_id: 102,+ type_of_icon: "SOLID",+ term: ["color", "colour", "painting"]},{- "name": "magic-wand",- "slug": "magic-wand-solid",- "category_id": 102,- "type_of_icon": "SOLID"+ name: "keyboard",+ slug: "keyboard-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "repeat",- "slug": "repeat-regular",- "category_id": 114,- "type_of_icon": "REGULAR"+ name: "megaphone",+ slug: "megaphone-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "eraser",- "slug": "eraser-solid",- "category_id": 102,- "type_of_icon": "SOLID",- "term": [- "rubber"- ]+ name: "directions",+ slug: "directions-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "cloud-rain",- "slug": "cloud-rain-solid",- "category_id": 123,- "type_of_icon": "SOLID"+ name: "direction-right",+ slug: "direction-right-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "cloud-lightning",- "slug": "cloud-lightning-solid",- "category_id": 123,- "type_of_icon": "SOLID"+ name: "unlink",+ slug: "unlink-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "eyedropper",- "slug": "eyedropper-solid",- "category_id": 102,- "type_of_icon": "SOLID"+ name: "paint",+ slug: "paint-regular",+ category_id: 102,+ type_of_icon: "REGULAR"},{- "name": "user-rectangle",- "slug": "user-rectangle-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "joystick-button",+ slug: "joystick-button-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "plane",- "slug": "plane-solid",- "category_id": 121,- "type_of_icon": "SOLID",- "term": [- "flight",- "fly"- ]+ name: "joystick-button",+ slug: "joystick-button-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "tree",- "slug": "tree-solid",- "category_id": 121,- "type_of_icon": "SOLID",- "term": [- "forest",- "christmas"- ]+ name: "font-family",+ slug: "font-family-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "factory",- "slug": "factory-solid",- "category_id": 98,- "type_of_icon": "SOLID"+ name: "flask",+ slug: "flask-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "ship",- "slug": "ship-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "capsule",+ slug: "capsule-solid",+ category_id: 109,+ type_of_icon: "SOLID",+ term: ["medicine"]},{- "name": "walk",- "slug": "walk-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "color-fill",+ slug: "color-fill-solid",+ category_id: 102,+ type_of_icon: "SOLID"},{- "name": "yin-yang",- "slug": "yin-yang-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "hotel",+ slug: "hotel-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "file-pdf",- "slug": "file-pdf-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "magic-wand",+ slug: "magic-wand-solid",+ category_id: 102,+ type_of_icon: "SOLID"},{- "name": "money",- "slug": "money-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "repeat",+ slug: "repeat-regular",+ category_id: 114,+ type_of_icon: "REGULAR"},{- "name": "home-circle",- "slug": "home-circle-regular",- "category_id": 98,- "type_of_icon": "REGULAR"+ name: "eraser",+ slug: "eraser-solid",+ category_id: 102,+ type_of_icon: "SOLID",+ term: ["rubber"]},{- "name": "home-circle",- "slug": "home-circle-solid",- "category_id": 98,- "type_of_icon": "SOLID"+ name: "cloud-rain",+ slug: "cloud-rain-solid",+ category_id: 123,+ type_of_icon: "SOLID"},{- "name": "location-plus",- "slug": "location-plus-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "cloud-lightning",+ slug: "cloud-lightning-solid",+ category_id: 123,+ type_of_icon: "SOLID"},{- "name": "location-plus",- "slug": "location-plus-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "eyedropper",+ slug: "eyedropper-solid",+ category_id: 102,+ type_of_icon: "SOLID"},{- "name": "arch",- "slug": "arch-regular",- "category_id": 98,- "type_of_icon": "REGULAR"+ name: "user-rectangle",+ slug: "user-rectangle-solid",+ category_id: 122,+ type_of_icon: "SOLID"},{- "name": "arch",- "slug": "arch-solid",- "category_id": 98,- "type_of_icon": "SOLID"+ name: "plane",+ slug: "plane-solid",+ category_id: 121,+ type_of_icon: "SOLID",+ term: ["flight", "fly"]},{- "name": "atom",- "slug": "atom-regular",- "category_id": 113,- "type_of_icon": "REGULAR"+ name: "tree",+ slug: "tree-solid",+ category_id: 121,+ type_of_icon: "SOLID",+ term: ["forest", "christmas"]},{- "name": "badge-dollar",- "slug": "badge-dollar-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "factory",+ slug: "factory-solid",+ category_id: 98,+ type_of_icon: "SOLID"},{- "name": "baseball",- "slug": "baseball-regular",- "category_id": 119,- "type_of_icon": "REGULAR"+ name: "ship",+ slug: "ship-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "beer",- "slug": "beer-regular",- "category_id": 108,- "type_of_icon": "REGULAR"+ name: "walk",+ slug: "walk-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "beer",- "slug": "beer-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "yin-yang",+ slug: "yin-yang-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "bible",- "slug": "bible-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "file-pdf",+ slug: "file-pdf-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "bible",- "slug": "bible-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "money",+ slug: "money-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "bomb",- "slug": "bomb-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "home-circle",+ slug: "home-circle-regular",+ category_id: 98,+ type_of_icon: "REGULAR"},{- "name": "bomb",- "slug": "bomb-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "home-circle",+ slug: "home-circle-solid",+ category_id: 98,+ type_of_icon: "SOLID"},{- "name": "bus-school",- "slug": "bus-school-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "location-plus",+ slug: "location-plus-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "bus-school",- "slug": "bus-school-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "location-plus",+ slug: "location-plus-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "cabinet",- "slug": "cabinet-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "arch",+ slug: "arch-regular",+ category_id: 98,+ type_of_icon: "REGULAR"},{- "name": "cabinet",- "slug": "cabinet-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "arch",+ slug: "arch-solid",+ category_id: 98,+ type_of_icon: "SOLID"},{- "name": "calendar-edit",- "slug": "calendar-edit-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "atom",+ slug: "atom-regular",+ category_id: 113,+ type_of_icon: "REGULAR"},{- "name": "calendar-edit",- "slug": "calendar-edit-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "badge-dollar",+ slug: "badge-dollar-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "car-wash",- "slug": "car-wash-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "baseball",+ slug: "baseball-regular",+ category_id: 119,+ type_of_icon: "REGULAR"},{- "name": "car-garage",- "slug": "car-garage-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "beer",+ slug: "beer-regular",+ category_id: 108,+ type_of_icon: "REGULAR"},{- "name": "car-mechanic",- "slug": "car-mechanic-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "beer",+ slug: "beer-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "car-crash",- "slug": "car-crash-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "bible",+ slug: "bible-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "coffee-togo",- "slug": "coffee-togo-regular",- "category_id": 108,- "type_of_icon": "REGULAR"+ name: "bible",+ slug: "bible-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "coffee-togo",- "slug": "coffee-togo-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "bomb",+ slug: "bomb-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "chess",- "slug": "chess-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "strategy"- ]+ name: "bomb",+ slug: "bomb-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "dryer",- "slug": "dryer-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "bus-school",+ slug: "bus-school-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "washer",- "slug": "washer-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "bus-school",+ slug: "bus-school-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "pointer",- "slug": "pointer-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "cabinet",+ slug: "cabinet-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "pointer",- "slug": "pointer-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "cabinet",+ slug: "cabinet-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "microchip",- "slug": "microchip-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "calendar-edit",+ slug: "calendar-edit-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "microchip",- "slug": "microchip-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "calendar-edit",+ slug: "calendar-edit-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "piano",- "slug": "piano-solid",- "category_id": 103,- "type_of_icon": "SOLID"+ name: "car-wash",+ slug: "car-wash-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "file-export",- "slug": "file-export-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "car-garage",+ slug: "car-garage-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "file-import",- "slug": "file-import-solid",- "category_id": 106,- "type_of_icon": "SOLID"+ name: "car-mechanic",+ slug: "car-mechanic-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "flag-checkered",- "slug": "flag-checkered-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "f1",- "racing"- ]+ name: "car-crash",+ slug: "car-crash-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "heart-circle",- "slug": "heart-circle-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "coffee-togo",+ slug: "coffee-togo-regular",+ category_id: 108,+ type_of_icon: "REGULAR"},{- "name": "heart-circle",- "slug": "heart-circle-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "coffee-togo",+ slug: "coffee-togo-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "heart-square",- "slug": "heart-square-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "chess",+ slug: "chess-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["strategy"]},{- "name": "heart-square",- "slug": "heart-square-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "dryer",+ slug: "dryer-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "home-heart",- "slug": "home-heart-regular",- "category_id": 98,- "type_of_icon": "REGULAR"+ name: "washer",+ slug: "washer-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "home-heart",- "slug": "home-heart-solid",- "category_id": 98,- "type_of_icon": "SOLID"+ name: "pointer",+ slug: "pointer-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "info-square",- "slug": "info-square-regular",- "category_id": 94,- "type_of_icon": "REGULAR"+ name: "pointer",+ slug: "pointer-solid",+ category_id: 110,+ type_of_icon: "SOLID"},{- "name": "info-square",- "slug": "info-square-solid",- "category_id": 94,- "type_of_icon": "SOLID"+ name: "microchip",+ slug: "microchip-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "layer-plus",- "slug": "layer-plus-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "microchip",+ slug: "microchip-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "layer-plus",- "slug": "layer-plus-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "piano",+ slug: "piano-solid",+ category_id: 103,+ type_of_icon: "SOLID"},{- "name": "layer-minus",- "slug": "layer-minus-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "file-export",+ slug: "file-export-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "layer-minus",- "slug": "layer-minus-solid",- "category_id": 111,- "type_of_icon": "SOLID"+ name: "file-import",+ slug: "file-import-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "recycle",- "slug": "recycle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "flag-checkered",+ slug: "flag-checkered-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["f1", "racing"]},{- "name": "traffic-cone",- "slug": "traffic-cone-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "heart-circle",+ slug: "heart-circle-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "traffic-cone",- "slug": "traffic-cone-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "heart-circle",+ slug: "heart-circle-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "wifi-2",- "slug": "wifi-2-regular",- "category_id": 115,- "type_of_icon": "REGULAR"+ name: "heart-square",+ slug: "heart-square-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "wifi-1",- "slug": "wifi-1-regular",- "category_id": 115,- "type_of_icon": "REGULAR"+ name: "heart-square",+ slug: "heart-square-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "wifi-0",- "slug": "wifi-0-regular",- "category_id": 115,- "type_of_icon": "REGULAR"+ name: "home-heart",+ slug: "home-heart-regular",+ category_id: 98,+ type_of_icon: "REGULAR"},{- "name": "mask",- "slug": "mask-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "home-heart",+ slug: "home-heart-solid",+ category_id: 98,+ type_of_icon: "SOLID"},{- "name": "mask",- "slug": "mask-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "info-square",+ slug: "info-square-regular",+ category_id: 94,+ type_of_icon: "REGULAR"},{- "name": "low-vision",- "slug": "low-vision-regular",- "category_id": 94,- "type_of_icon": "REGULAR",- "term": [- "eye",- "view",- "visibility"- ]+ name: "info-square",+ slug: "info-square-solid",+ category_id: 94,+ type_of_icon: "SOLID"},{- "name": "low-vision",- "slug": "low-vision-solid",- "category_id": 94,- "type_of_icon": "SOLID",- "term": [- "eye",- "view",- "visibility"- ]+ name: "layer-plus",+ slug: "layer-plus-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "radiation",- "slug": "radiation-solid",- "category_id": 95,- "type_of_icon": "SOLID",- "term": [- "hazard",- "danger"- ]+ name: "layer-plus",+ slug: "layer-plus-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "been-here",- "slug": "been-here-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "layer-minus",+ slug: "layer-minus-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "been-here",- "slug": "been-here-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "layer-minus",+ slug: "layer-minus-solid",+ category_id: 111,+ type_of_icon: "SOLID"},{- "name": "current-location",- "slug": "current-location-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "recycle",+ slug: "recycle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "arrow-from-top",- "slug": "arrow-from-top-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "traffic-cone",+ slug: "traffic-cone-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "arrow-from-top",- "slug": "arrow-from-top-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "traffic-cone",+ slug: "traffic-cone-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "arrow-from-bottom",- "slug": "arrow-from-bottom-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "wifi-2",+ slug: "wifi-2-regular",+ category_id: 115,+ type_of_icon: "REGULAR"},{- "name": "arrow-from-bottom",- "slug": "arrow-from-bottom-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "wifi-1",+ slug: "wifi-1-regular",+ category_id: 115,+ type_of_icon: "REGULAR"},{- "name": "arrow-from-left",- "slug": "arrow-from-left-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "wifi-0",+ slug: "wifi-0-regular",+ category_id: 115,+ type_of_icon: "REGULAR"},{- "name": "arrow-from-left",- "slug": "arrow-from-left-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "mask",+ slug: "mask-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "arrow-from-right",- "slug": "arrow-from-right-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "mask",+ slug: "mask-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "arrow-from-right",- "slug": "arrow-from-right-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "low-vision",+ slug: "low-vision-regular",+ category_id: 94,+ type_of_icon: "REGULAR",+ term: ["eye", "view", "visibility"]},{- "name": "arrow-to-right",- "slug": "arrow-to-right-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "low-vision",+ slug: "low-vision-solid",+ category_id: 94,+ type_of_icon: "SOLID",+ term: ["eye", "view", "visibility"]},{- "name": "arrow-to-right",- "slug": "arrow-to-right-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "radiation",+ slug: "radiation-solid",+ category_id: 95,+ type_of_icon: "SOLID",+ term: ["hazard", "danger"]},{- "name": "arrow-to-left",- "slug": "arrow-to-left-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "been-here",+ slug: "been-here-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "arrow-to-left",- "slug": "arrow-to-left-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "been-here",+ slug: "been-here-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "arrow-to-top",- "slug": "arrow-to-top-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "current-location",+ slug: "current-location-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "arrow-to-top",- "slug": "arrow-to-top-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "arrow-from-top",+ slug: "arrow-from-top-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "arrow-to-bottom",- "slug": "arrow-to-bottom-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "arrow-from-top",+ slug: "arrow-from-top-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "arrow-to-bottom",- "slug": "arrow-to-bottom-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "arrow-from-bottom",+ slug: "arrow-from-bottom-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "book-reader",- "slug": "book-reader-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "arrow-from-bottom",+ slug: "arrow-from-bottom-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "book-reader",- "slug": "book-reader-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "arrow-from-left",+ slug: "arrow-from-left-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "edit-location",- "slug": "edit-location-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "arrow-from-left",+ slug: "arrow-from-left-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "ev-station",- "slug": "ev-station-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "arrow-from-right",+ slug: "arrow-from-right-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "shapes",- "slug": "shapes-solid",- "category_id": 118,- "type_of_icon": "SOLID"+ name: "arrow-from-right",+ slug: "arrow-from-right-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "florist",- "slug": "florist-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "arrow-to-right",+ slug: "arrow-to-right-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "pizza",- "slug": "pizza-solid",- "category_id": 108,- "type_of_icon": "SOLID"+ name: "arrow-to-right",+ slug: "arrow-to-right-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "scan",- "slug": "scan-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "arrow-to-left",+ slug: "arrow-to-left-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "calendar-week",- "slug": "calendar-week-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "arrow-to-left",+ slug: "arrow-to-left-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "calendar-week",- "slug": "calendar-week-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "arrow-to-top",+ slug: "arrow-to-top-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "glasses",- "slug": "glasses-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "arrow-to-top",+ slug: "arrow-to-top-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "glasses-alt",- "slug": "glasses-alt-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "arrow-to-bottom",+ slug: "arrow-to-bottom-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "border-none",- "slug": "border-none-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "arrow-to-bottom",+ slug: "arrow-to-bottom-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "border-inner",- "slug": "border-inner-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "book-reader",+ slug: "book-reader-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "dice-1",- "slug": "dice-1-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "game",- "random"- ]+ name: "book-reader",+ slug: "book-reader-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "dice-1",- "slug": "dice-1-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "game",- "random"- ]+ name: "edit-location",+ slug: "edit-location-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "dice-2",- "slug": "dice-2-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "game",- "random"- ]+ name: "ev-station",+ slug: "ev-station-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "dice-2",- "slug": "dice-2-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "game",- "random"- ]- },- {- "name": "dice-3",- "slug": "dice-3-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "game",- "random"- ]- },- {- "name": "dice-3",- "slug": "dice-3-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "game",- "random"- ]- },- {- "name": "dice-4",- "slug": "dice-4-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "game",- "random"- ]- },- {- "name": "dice-4",- "slug": "dice-4-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "game",- "random"- ]- },- {- "name": "dice-5",- "slug": "dice-5-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "game",- "random"- ]- },- {- "name": "dice-5",- "slug": "dice-5-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "game",- "random"- ]- },- {- "name": "dice-6",- "slug": "dice-6-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "game",- "random"- ]- },- {- "name": "dice-6",- "slug": "dice-6-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "game",- "random"- ]- },- {- "name": "webcam",- "slug": "webcam-regular",- "category_id": 117,- "type_of_icon": "REGULAR"- },- {- "name": "webcam",- "slug": "webcam-solid",- "category_id": 117,- "type_of_icon": "SOLID"- },- {- "name": "spray-can",- "slug": "spray-can-regular",- "category_id": 102,- "type_of_icon": "REGULAR",- "term": [- "color",- "colour",- "paint spray"- ]- },- {- "name": "spray-can",- "slug": "spray-can-solid",- "category_id": 102,- "type_of_icon": "SOLID",- "term": [- "color",- "colour",- "paint spray"- ]- },- {- "name": "file-archive",- "slug": "file-archive-solid",- "category_id": 106,- "type_of_icon": "SOLID"- },- {- "name": "sticker",- "slug": "sticker-regular",- "category_id": 99,- "type_of_icon": "REGULAR"- },- {- "name": "sticker",- "slug": "sticker-solid",- "category_id": 99,- "type_of_icon": "SOLID"- },- {- "name": "tachometer",- "slug": "tachometer-regular",- "category_id": 121,- "type_of_icon": "REGULAR"- },- {- "name": "tachometer",- "slug": "tachometer-solid",- "category_id": 121,- "type_of_icon": "SOLID"- },- {- "name": "thermometer",- "slug": "thermometer-solid",- "category_id": 109,- "type_of_icon": "SOLID"- },- {- "name": "game",- "slug": "game-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "pacman"- ]- },- {- "name": "game",- "slug": "game-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "pacman"- ]- },- {- "name": "abacus",- "slug": "abacus-regular",- "category_id": 119,- "type_of_icon": "REGULAR"- },- {- "name": "alarm-snooze",- "slug": "alarm-snooze-regular",- "category_id": 120,- "type_of_icon": "REGULAR",- "term": [- "alert",- "zzz",- "sleep"- ]- },- {- "name": "alarm-snooze",- "slug": "alarm-snooze-solid",- "category_id": 120,- "type_of_icon": "SOLID",- "term": [- "alert",- "zzz",- "sleep"- ]- },- {- "name": "alarm-exclamation",- "slug": "alarm-exclamation-regular",- "category_id": 120,- "type_of_icon": "REGULAR",- "term": [- "alert",- "error"- ]+ name: "shapes",+ slug: "shapes-solid",+ category_id: 118,+ type_of_icon: "SOLID"},{- "name": "alarm-exclamation",- "slug": "alarm-exclamation-solid",- "category_id": 120,- "type_of_icon": "SOLID",- "term": [- "alert",- "error"- ]+ name: "florist",+ slug: "florist-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "chevrons-left",- "slug": "chevrons-left-solid",- "category_id": 96,- "type_of_icon": "SOLID",- "term": [- "arrow"- ]+ name: "pizza",+ slug: "pizza-solid",+ category_id: 108,+ type_of_icon: "SOLID"},{- "name": "chevrons-right",- "slug": "chevrons-right-solid",- "category_id": 96,- "type_of_icon": "SOLID",- "term": [- "arrow"- ]- },- {- "name": "chevrons-up",- "slug": "chevrons-up-solid",- "category_id": 96,- "type_of_icon": "SOLID",- "term": [- "arrow"- ]- },- {- "name": "chevrons-down",- "slug": "chevrons-down-solid",- "category_id": 96,- "type_of_icon": "SOLID",- "term": [- "arrow"- ]- },- {- "name": "chevron-down",- "slug": "chevron-down-solid",- "category_id": 96,- "type_of_icon": "SOLID",- "term": [- "arrow"- ]- },- {- "name": "chevron-up",- "slug": "chevron-up-solid",- "category_id": 96,- "type_of_icon": "SOLID",- "term": [- "arrow"- ]- },- {- "name": "chevron-right",- "slug": "chevron-right-solid",- "category_id": 96,- "type_of_icon": "SOLID",- "term": [- "arrow"- ]- },+ name: "scan",+ slug: "scan-regular",+ category_id: 117,+ type_of_icon: "REGULAR"+ },+ {+ name: "calendar-week",+ slug: "calendar-week-regular",+ category_id: 120,+ type_of_icon: "REGULAR"+ },{- "name": "chevron-left",- "slug": "chevron-left-solid",- "category_id": 96,- "type_of_icon": "SOLID",- "term": [- "arrow"- ]+ name: "calendar-week",+ slug: "calendar-week-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "guitar-amp",- "slug": "guitar-amp-solid",- "category_id": 114,- "type_of_icon": "SOLID"+ name: "glasses",+ slug: "glasses-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "up-arrow-alt",- "slug": "up-arrow-alt-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "glasses-alt",+ slug: "glasses-alt-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "down-arrow-alt",- "slug": "down-arrow-alt-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "border-none",+ slug: "border-none-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "left-arrow-alt",- "slug": "left-arrow-alt-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "border-inner",+ slug: "border-inner-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "right-arrow-alt",- "slug": "right-arrow-alt-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "dice-1",+ slug: "dice-1-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["game", "random"]},{- "name": "medal",- "slug": "medal-regular",- "category_id": 119,- "type_of_icon": "REGULAR",- "term": [- "honor",- "honour",- "achievement"- ]+ name: "dice-1",+ slug: "dice-1-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["game", "random"]},{- "name": "medal",- "slug": "medal-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "honor",- "honour",- "achievement"- ]+ name: "dice-2",+ slug: "dice-2-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["game", "random"]},{- "name": "shopping-bags",- "slug": "shopping-bags-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "dice-2",+ slug: "dice-2-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["game", "random"]},{- "name": "baseball",- "slug": "baseball-solid",- "category_id": 119,- "type_of_icon": "SOLID"+ name: "dice-3",+ slug: "dice-3-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["game", "random"]},{- "name": "task-x",- "slug": "task-x-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "dice-3",+ slug: "dice-3-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["game", "random"]},{- "name": "basketball",- "slug": "basketball-solid",- "category_id": 119,- "type_of_icon": "SOLID",- "term": [- "nba"- ]+ name: "dice-4",+ slug: "dice-4-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["game", "random"]},{- "name": "barcode-reader",- "slug": "barcode-reader-regular",- "category_id": 103,- "type_of_icon": "REGULAR"+ name: "dice-4",+ slug: "dice-4-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["game", "random"]},{- "name": "blanket",- "slug": "blanket-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "dice-5",+ slug: "dice-5-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["game", "random"]},{- "name": "blanket",- "slug": "blanket-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "dice-5",+ slug: "dice-5-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["game", "random"]},{- "name": "binoculars",- "slug": "binoculars-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "dice-6",+ slug: "dice-6-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["game", "random"]},{- "name": "bone",- "slug": "bone-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "dice-6",+ slug: "dice-6-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["game", "random"]},{- "name": "bone",- "slug": "bone-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "webcam",+ slug: "webcam-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "bong",- "slug": "bong-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "webcam",+ slug: "webcam-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "bong",- "slug": "bong-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "spray-can",+ slug: "spray-can-regular",+ category_id: 102,+ type_of_icon: "REGULAR",+ term: ["color", "colour", "paint spray"]},{- "name": "book-alt",- "slug": "book-alt-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "spray-can",+ slug: "spray-can-solid",+ category_id: 102,+ type_of_icon: "SOLID",+ term: ["color", "colour", "paint spray"]},{- "name": "book-alt",- "slug": "book-alt-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "file-archive",+ slug: "file-archive-solid",+ category_id: 106,+ type_of_icon: "SOLID"},{- "name": "book-heart",- "slug": "book-heart-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "sticker",+ slug: "sticker-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "book-heart",- "slug": "book-heart-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "sticker",+ slug: "sticker-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "book-add",- "slug": "book-add-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "tachometer",+ slug: "tachometer-regular",+ category_id: 121,+ type_of_icon: "REGULAR"},{- "name": "book-add",- "slug": "book-add-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "tachometer",+ slug: "tachometer-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "bracket",- "slug": "bracket-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "thermometer",+ slug: "thermometer-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "brain",- "slug": "brain-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "game",+ slug: "game-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["pacman"]},{- "name": "brain",- "slug": "brain-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "game",+ slug: "game-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["pacman"]},{- "name": "border-outer",- "slug": "border-outer-regular",- "category_id": 111,- "type_of_icon": "REGULAR"+ name: "abacus",+ slug: "abacus-regular",+ category_id: 119,+ type_of_icon: "REGULAR"},{- "name": "braille",- "slug": "braille-regular",- "category_id": 94,- "type_of_icon": "REGULAR"+ name: "alarm-snooze",+ slug: "alarm-snooze-regular",+ category_id: 120,+ type_of_icon: "REGULAR",+ term: ["alert", "zzz", "sleep"]},{- "name": "window-alt",- "slug": "window-alt-regular",- "category_id": 110,- "type_of_icon": "REGULAR",- "term": [- "browser"- ]+ name: "alarm-snooze",+ slug: "alarm-snooze-solid",+ category_id: 120,+ type_of_icon: "SOLID",+ term: ["alert", "zzz", "sleep"]},{- "name": "window-alt",- "slug": "window-alt-solid",- "category_id": 110,- "type_of_icon": "SOLID",- "term": [- "browser"- ]+ name: "alarm-exclamation",+ slug: "alarm-exclamation-regular",+ category_id: 120,+ type_of_icon: "REGULAR",+ term: ["alert", "error"]},{- "name": "calendar-heart",- "slug": "calendar-heart-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "alarm-exclamation",+ slug: "alarm-exclamation-solid",+ category_id: 120,+ type_of_icon: "SOLID",+ term: ["alert", "error"]},{- "name": "calendar-heart",- "slug": "calendar-heart-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "chevrons-left",+ slug: "chevrons-left-solid",+ category_id: 96,+ type_of_icon: "SOLID",+ term: ["arrow"]},{- "name": "wine",- "slug": "wine-regular",- "category_id": 108,- "type_of_icon": "REGULAR"+ name: "chevrons-right",+ slug: "chevrons-right-solid",+ category_id: 96,+ type_of_icon: "SOLID",+ term: ["arrow"]},{- "name": "vial",- "slug": "vial-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "chevrons-up",+ slug: "chevrons-up-solid",+ category_id: 96,+ type_of_icon: "SOLID",+ term: ["arrow"]},{- "name": "color-fill",- "slug": "color-fill-regular",- "category_id": 102,- "type_of_icon": "REGULAR"+ name: "chevrons-down",+ slug: "chevrons-down-solid",+ category_id: 96,+ type_of_icon: "SOLID",+ term: ["arrow"]},{- "name": "capsule",- "slug": "capsule-regular",- "category_id": 109,- "type_of_icon": "REGULAR",- "term": [- "medicine"- ]+ name: "chevron-down",+ slug: "chevron-down-solid",+ category_id: 96,+ type_of_icon: "SOLID",+ term: ["arrow"]},{- "name": "eraser",- "slug": "eraser-regular",- "category_id": 102,- "type_of_icon": "REGULAR",- "term": [- "rubber"- ]+ name: "chevron-up",+ slug: "chevron-up-solid",+ category_id: 96,+ type_of_icon: "SOLID",+ term: ["arrow"]},{- "name": "drink",- "slug": "drink-regular",- "category_id": 108,- "type_of_icon": "REGULAR"+ name: "chevron-right",+ slug: "chevron-right-solid",+ category_id: 96,+ type_of_icon: "SOLID",+ term: ["arrow"]},{- "name": "cctv",- "slug": "cctv-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "chevron-left",+ slug: "chevron-left-solid",+ category_id: 96,+ type_of_icon: "SOLID",+ term: ["arrow"]},{- "name": "cctv",- "slug": "cctv-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "guitar-amp",+ slug: "guitar-amp-solid",+ category_id: 114,+ type_of_icon: "SOLID"},{- "name": "chair",- "slug": "chair-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "up-arrow-alt",+ slug: "up-arrow-alt-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "network-chart",- "slug": "network-chart-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "down-arrow-alt",+ slug: "down-arrow-alt-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "network-chart",- "slug": "network-chart-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "left-arrow-alt",+ slug: "left-arrow-alt-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "vector",- "slug": "vector-regular",- "category_id": 102,- "type_of_icon": "REGULAR"+ name: "right-arrow-alt",+ slug: "right-arrow-alt-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "vector",- "slug": "vector-solid",- "category_id": 102,- "type_of_icon": "SOLID"+ name: "medal",+ slug: "medal-regular",+ category_id: 119,+ type_of_icon: "REGULAR",+ term: ["honor", "honour", "achievement"]},{- "name": "calendar-exclamation",- "slug": "calendar-exclamation-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "medal",+ slug: "medal-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["honor", "honour", "achievement"]},{- "name": "calendar-exclamation",- "slug": "calendar-exclamation-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "shopping-bags",+ slug: "shopping-bags-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "calendar-star",- "slug": "calendar-star-regular",- "category_id": 120,- "type_of_icon": "REGULAR"+ name: "baseball",+ slug: "baseball-solid",+ category_id: 119,+ type_of_icon: "SOLID"},{- "name": "calendar-star",- "slug": "calendar-star-solid",- "category_id": 120,- "type_of_icon": "SOLID"+ name: "task-x",+ slug: "task-x-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "camera-home",- "slug": "camera-home-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "basketball",+ slug: "basketball-solid",+ category_id: 119,+ type_of_icon: "SOLID",+ term: ["nba"]},{- "name": "camera-home",- "slug": "camera-home-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "barcode-reader",+ slug: "barcode-reader-regular",+ category_id: 103,+ type_of_icon: "REGULAR"},{- "name": "camera-movie",- "slug": "camera-movie-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "blanket",+ slug: "blanket-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "camera-movie",- "slug": "camera-movie-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "blanket",+ slug: "blanket-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "backpack",- "slug": "backpack-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "binoculars",+ slug: "binoculars-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "cart-download",- "slug": "cart-download-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "bone",+ slug: "bone-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "cart-add",- "slug": "cart-add-solid",- "category_id": 104,- "type_of_icon": "SOLID"+ name: "bone",+ slug: "bone-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "car-battery",- "slug": "car-battery-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "bong",+ slug: "bong-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "caret-right-circle",- "slug": "caret-right-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "bong",+ slug: "bong-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "caret-left-circle",- "slug": "caret-left-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "book-alt",+ slug: "book-alt-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "caret-up-circle",- "slug": "caret-up-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "book-alt",+ slug: "book-alt-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "caret-down-circle",- "slug": "caret-down-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "book-heart",+ slug: "book-heart-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "caret-right-square",- "slug": "caret-right-square-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "book-heart",+ slug: "book-heart-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "caret-right-square",- "slug": "caret-right-square-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "book-add",+ slug: "book-add-regular",+ category_id: 124,+ type_of_icon: "REGULAR"},{- "name": "caret-up-square",- "slug": "caret-up-square-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "book-add",+ slug: "book-add-solid",+ category_id: 124,+ type_of_icon: "SOLID"},{- "name": "caret-up-square",- "slug": "caret-up-square-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "bracket",+ slug: "bracket-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "caret-left-square",- "slug": "caret-left-square-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "brain",+ slug: "brain-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "caret-left-square",- "slug": "caret-left-square-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "brain",+ slug: "brain-solid",+ category_id: 109,+ type_of_icon: "SOLID"},{- "name": "caret-down-square",- "slug": "caret-down-square-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "border-outer",+ slug: "border-outer-regular",+ category_id: 111,+ type_of_icon: "REGULAR"},{- "name": "caret-down-square",- "slug": "caret-down-square-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "braille",+ slug: "braille-regular",+ category_id: 94,+ type_of_icon: "REGULAR"},{- "name": "shield-x",- "slug": "shield-x-regular",- "category_id": 100,- "type_of_icon": "REGULAR"+ name: "window-alt",+ slug: "window-alt-regular",+ category_id: 110,+ type_of_icon: "REGULAR",+ term: ["browser"]},{- "name": "shield-x",- "slug": "shield-x-solid",- "category_id": 100,- "type_of_icon": "SOLID"+ name: "window-alt",+ slug: "window-alt-solid",+ category_id: 110,+ type_of_icon: "SOLID",+ term: ["browser"]},{- "name": "line-chart-down",- "slug": "line-chart-down-regular",- "category_id": 99,- "type_of_icon": "REGULAR"+ name: "calendar-heart",+ slug: "calendar-heart-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "chevron-down-circle",- "slug": "chevron-down-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "calendar-heart",+ slug: "calendar-heart-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "chevron-down-circle",- "slug": "chevron-down-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "wine",+ slug: "wine-regular",+ category_id: 108,+ type_of_icon: "REGULAR"},{- "name": "chevron-up-circle",- "slug": "chevron-up-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "vial",+ slug: "vial-regular",+ category_id: 109,+ type_of_icon: "REGULAR"},{- "name": "chevron-up-circle",- "slug": "chevron-up-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "color-fill",+ slug: "color-fill-regular",+ category_id: 102,+ type_of_icon: "REGULAR"},{- "name": "chevron-left-circle",- "slug": "chevron-left-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "capsule",+ slug: "capsule-regular",+ category_id: 109,+ type_of_icon: "REGULAR",+ term: ["medicine"]},{- "name": "chevron-left-circle",- "slug": "chevron-left-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "eraser",+ slug: "eraser-regular",+ category_id: 102,+ type_of_icon: "REGULAR",+ term: ["rubber"]},{- "name": "chevron-right-circle",- "slug": "chevron-right-circle-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "drink",+ slug: "drink-regular",+ category_id: 108,+ type_of_icon: "REGULAR"},{- "name": "chevron-right-circle",- "slug": "chevron-right-circle-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "cctv",+ slug: "cctv-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "chevron-down-square",- "slug": "chevron-down-square-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "cctv",+ slug: "cctv-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "chevron-down-square",- "slug": "chevron-down-square-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "chair",+ slug: "chair-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "chevron-up-square",- "slug": "chevron-up-square-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "network-chart",+ slug: "network-chart-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "chevron-up-square",- "slug": "chevron-up-square-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "network-chart",+ slug: "network-chart-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "chevron-left-square",- "slug": "chevron-left-square-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "vector",+ slug: "vector-regular",+ category_id: 102,+ type_of_icon: "REGULAR"},{- "name": "chevron-left-square",- "slug": "chevron-left-square-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "vector",+ slug: "vector-solid",+ category_id: 102,+ type_of_icon: "SOLID"},{- "name": "chevron-right-square",- "slug": "chevron-right-square-regular",- "category_id": 96,- "type_of_icon": "REGULAR"+ name: "calendar-exclamation",+ slug: "calendar-exclamation-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "chevron-right-square",- "slug": "chevron-right-square-solid",- "category_id": 96,- "type_of_icon": "SOLID"+ name: "calendar-exclamation",+ slug: "calendar-exclamation-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "church",- "slug": "church-regular",- "category_id": 98,- "type_of_icon": "REGULAR"+ name: "calendar-star",+ slug: "calendar-star-regular",+ category_id: 120,+ type_of_icon: "REGULAR"},{- "name": "church",- "slug": "church-solid",- "category_id": 98,- "type_of_icon": "SOLID"+ name: "calendar-star",+ slug: "calendar-star-solid",+ category_id: 120,+ type_of_icon: "SOLID"},{- "name": "coin",- "slug": "coin-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "camera-home",+ slug: "camera-home-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "coin",- "slug": "coin-solid",- "category_id": 107,- "type_of_icon": "SOLID"+ name: "camera-home",+ slug: "camera-home-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "coin-stack",- "slug": "coin-stack-regular",- "category_id": 107,- "type_of_icon": "REGULAR"+ name: "camera-movie",+ slug: "camera-movie-regular",+ category_id: 117,+ type_of_icon: "REGULAR"},{- "name": "coin-stack",- "slug": "coin-stack-solid",- "category_id": 107,- "type_of_icon": "SOLID"+ name: "camera-movie",+ slug: "camera-movie-solid",+ category_id: 117,+ type_of_icon: "SOLID"},{- "name": "unite",- "slug": "unite-regular",- "category_id": 102,- "type_of_icon": "REGULAR"+ name: "backpack",+ slug: "backpack-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "minus-front",- "slug": "minus-front-regular",- "category_id": 102,- "type_of_icon": "REGULAR"+ name: "cart-download",+ slug: "cart-download-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "intersect",- "slug": "intersect-regular",- "category_id": 102,- "type_of_icon": "REGULAR"+ name: "cart-add",+ slug: "cart-add-solid",+ category_id: 104,+ type_of_icon: "SOLID"},{- "name": "exclude",- "slug": "exclude-regular",- "category_id": 102,- "type_of_icon": "REGULAR"+ name: "car-battery",+ slug: "car-battery-solid",+ category_id: 121,+ type_of_icon: "SOLID"},{- "name": "minus-back",- "slug": "minus-back-regular",- "category_id": 102,- "type_of_icon": "REGULAR"+ name: "caret-right-circle",+ slug: "caret-right-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "merge",- "slug": "merge-regular",- "category_id": 102,- "type_of_icon": "REGULAR"+ name: "caret-left-circle",+ slug: "caret-left-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "trim",- "slug": "trim-regular",- "category_id": 102,- "type_of_icon": "REGULAR"+ name: "caret-up-circle",+ slug: "caret-up-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "outline",- "slug": "outline-regular",- "category_id": 102,- "type_of_icon": "REGULAR"+ name: "caret-down-circle",+ slug: "caret-down-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "bullseye",- "slug": "bullseye-solid",- "category_id": 99,- "type_of_icon": "SOLID"+ name: "caret-right-square",+ slug: "caret-right-square-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "meteor",- "slug": "meteor-regular",- "category_id": 116,- "type_of_icon": "REGULAR"+ name: "caret-right-square",+ slug: "caret-right-square-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "meteor",- "slug": "meteor-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "caret-up-square",+ slug: "caret-up-square-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "refresh",- "slug": "refresh-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "caret-up-square",+ slug: "caret-up-square-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "home-smile",- "slug": "home-smile-regular",- "category_id": 98,- "type_of_icon": "REGULAR"+ name: "caret-left-square",+ slug: "caret-left-square-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "home-smile",- "slug": "home-smile-solid",- "category_id": 98,- "type_of_icon": "SOLID"+ name: "caret-left-square",+ slug: "caret-left-square-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "envelope-open",- "slug": "envelope-open-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "caret-down-square",+ slug: "caret-down-square-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "envelope-open",- "slug": "envelope-open-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "caret-down-square",+ slug: "caret-down-square-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "dev-to",- "slug": "dev-to-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "shield-x",+ slug: "shield-x-regular",+ category_id: 100,+ type_of_icon: "REGULAR"},{- "name": "message-alt-add",- "slug": "message-alt-add-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "comment",- "new",- "plus"- ]+ name: "shield-x",+ slug: "shield-x-solid",+ category_id: 100,+ type_of_icon: "SOLID"},{- "name": "message-alt-add",- "slug": "message-alt-add-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "comment",- "new",- "plus"- ]+ name: "line-chart-down",+ slug: "line-chart-down-regular",+ category_id: 99,+ type_of_icon: "REGULAR"},{- "name": "message-alt-check",- "slug": "message-alt-check-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "chevron-down-circle",+ slug: "chevron-down-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "message-alt-check",- "slug": "message-alt-check-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "chevron-down-circle",+ slug: "chevron-down-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "message-alt-error",- "slug": "message-alt-error-regular",- "category_id": 101,- "type_of_icon": "REGULAR"+ name: "chevron-up-circle",+ slug: "chevron-up-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "message-alt-error",- "slug": "message-alt-error-solid",- "category_id": 101,- "type_of_icon": "SOLID"+ name: "chevron-up-circle",+ slug: "chevron-up-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "message-alt-x",- "slug": "message-alt-x-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "comment",- "remove",- "delete"- ]+ name: "chevron-left-circle",+ slug: "chevron-left-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "message-alt-x",- "slug": "message-alt-x-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "comment",- "remove",- "delete"- ]+ name: "chevron-left-circle",+ slug: "chevron-left-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "message-alt-minus",- "slug": "message-alt-minus-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "comment",- "remove",- "delete"- ]- },- {- "name": "message-alt-minus",- "slug": "message-alt-minus-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "comment",- "remove",- "delete"- ]- },- {- "name": "message-alt-edit",- "slug": "message-alt-edit-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-alt-edit",- "slug": "message-alt-edit-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-alt-detail",- "slug": "message-alt-detail-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-alt-detail",- "slug": "message-alt-detail-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-rounded-check",- "slug": "message-rounded-check-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-rounded-check",- "slug": "message-rounded-check-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-rounded-error",- "slug": "message-rounded-error-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-rounded-error",- "slug": "message-rounded-error-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-rounded-x",- "slug": "message-rounded-x-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "comment",- "remove",- "delete"- ]- },- {- "name": "message-rounded-x",- "slug": "message-rounded-x-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "comment",- "remove",- "delete"- ]+ name: "chevron-right-circle",+ slug: "chevron-right-circle-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "message-rounded-minus",- "slug": "message-rounded-minus-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "comment",- "remove",- "delete"- ]+ name: "chevron-right-circle",+ slug: "chevron-right-circle-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "message-rounded-minus",- "slug": "message-rounded-minus-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "comment",- "remove",- "delete"- ]+ name: "chevron-down-square",+ slug: "chevron-down-square-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "message-rounded-edit",- "slug": "message-rounded-edit-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-rounded-edit",- "slug": "message-rounded-edit-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-rounded-add",- "slug": "message-rounded-add-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "comment",- "new",- "plus"- ]- },- {- "name": "message-rounded-add",- "slug": "message-rounded-add-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "comment",- "new",- "plus"- ]- },- {- "name": "message-rounded-detail",- "slug": "message-rounded-detail-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-rounded-detail",- "slug": "message-rounded-detail-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-check",- "slug": "message-check-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-check",- "slug": "message-check-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-error",- "slug": "message-error-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-error",- "slug": "message-error-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-x",- "slug": "message-x-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "comment",- "remove",- "delete"- ]- },- {- "name": "message-x",- "slug": "message-x-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "comment",- "remove",- "delete"- ]+ name: "chevron-down-square",+ slug: "chevron-down-square-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "message-minus",- "slug": "message-minus-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "comment",- "remove",- "delete"- ]- },- {- "name": "message-minus",- "slug": "message-minus-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "comment",- "remove",- "delete"- ]- },- {- "name": "message-edit",- "slug": "message-edit-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-edit",- "slug": "message-edit-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-add",- "slug": "message-add-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "comment",- "new",- "plus"- ]- },- {- "name": "message-add",- "slug": "message-add-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "comment",- "new",- "plus"- ]- },- {- "name": "message-detail",- "slug": "message-detail-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-detail",- "slug": "message-detail-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-square-check",- "slug": "message-square-check-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-square-check",- "slug": "message-square-check-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-square-error",- "slug": "message-square-error-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-square-error",- "slug": "message-square-error-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-square-x",- "slug": "message-square-x-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "comment",- "remove",- "delete"- ]- },- {- "name": "message-square-x",- "slug": "message-square-x-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "comment",- "remove",- "delete"- ]- },- {- "name": "message-square-minus",- "slug": "message-square-minus-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "comment",- "remove",- "delete"- ]- },- {- "name": "message-square-minus",- "slug": "message-square-minus-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "comment",- "remove",- "delete"- ]- },- {- "name": "message-square-edit",- "slug": "message-square-edit-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-square-edit",- "slug": "message-square-edit-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "message-square-add",- "slug": "message-square-add-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "comment",- "new",- "plus"- ]- },- {- "name": "message-square-add",- "slug": "message-square-add-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "comment",- "new",- "plus"- ]- },- {- "name": "message-square-detail",- "slug": "message-square-detail-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "message-square-detail",- "slug": "message-square-detail-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "comment-check",- "slug": "comment-check-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "comment-check",- "slug": "comment-check-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "comment-error",- "slug": "comment-error-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "comment-x",- "slug": "comment-x-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "message",- "remove",- "delete"- ]- },- {- "name": "comment-x",- "slug": "comment-x-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "message",- "remove",- "delete"- ]- },- {- "name": "comment-edit",- "slug": "comment-edit-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "comment-edit",- "slug": "comment-edit-solid",- "category_id": 101,- "type_of_icon": "SOLID"- },- {- "name": "comment-minus",- "slug": "comment-minus-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "message",- "remove",- "delete"- ]- },- {- "name": "comment-minus",- "slug": "comment-minus-solid",- "category_id": 101,- "type_of_icon": "SOLID",- "term": [- "chat",- "message",- "remove",- "delete"- ]- },- {- "name": "comment-add",- "slug": "comment-add-regular",- "category_id": 101,- "type_of_icon": "REGULAR",- "term": [- "chat",- "message",- "new",- "plus"- ]- },- {- "name": "comment-detail",- "slug": "comment-detail-regular",- "category_id": 101,- "type_of_icon": "REGULAR"- },- {- "name": "cookie",- "slug": "cookie-regular",- "category_id": 108,- "type_of_icon": "REGULAR",- "term": [- "biscuit"- ]+ name: "chevron-up-square",+ slug: "chevron-up-square-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "cookie",- "slug": "cookie-solid",- "category_id": 108,- "type_of_icon": "SOLID",- "term": [- "biscuit"- ]- },- {- "name": "copyright",- "slug": "copyright-solid",- "category_id": 99,- "type_of_icon": "SOLID"- },- {- "name": "credit-card-front",- "slug": "credit-card-front-regular",- "category_id": 107,- "type_of_icon": "REGULAR",- "term": [- "finance",- "money",- "debit"- ]+ name: "chevron-up-square",+ slug: "chevron-up-square-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "credit-card-front",- "slug": "credit-card-front-solid",- "category_id": 107,- "type_of_icon": "SOLID",- "term": [- "finance",- "money",- "debit"- ]+ name: "chevron-left-square",+ slug: "chevron-left-square-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "crop",- "slug": "crop-solid",- "category_id": 102,- "type_of_icon": "SOLID"+ name: "chevron-left-square",+ slug: "chevron-left-square-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "diamond",- "slug": "diamond-solid",- "category_id": 116,- "type_of_icon": "SOLID"+ name: "chevron-right-square",+ slug: "chevron-right-square-regular",+ category_id: 96,+ type_of_icon: "REGULAR"},{- "name": "door-open",- "slug": "door-open-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "chevron-right-square",+ slug: "chevron-right-square-solid",+ category_id: 96,+ type_of_icon: "SOLID"},{- "name": "door-open",- "slug": "door-open-solid",- "category_id": 121,- "type_of_icon": "SOLID"+ name: "church",+ slug: "church-regular",+ category_id: 98,+ type_of_icon: "REGULAR"},{- "name": "donate-heart",- "slug": "donate-heart-regular",- "category_id": 107,- "type_of_icon": "REGULAR",- "term": [- "donation",- "contribution"- ]+ name: "church",+ slug: "church-solid",+ category_id: 98,+ type_of_icon: "SOLID"},{- "name": "donate-heart",- "slug": "donate-heart-solid",- "category_id": 107,- "type_of_icon": "SOLID",- "term": [- "donation",- "contribution"- ]+ name: "coin",+ slug: "coin-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "donate-blood",- "slug": "donate-blood-regular",- "category_id": 109,- "type_of_icon": "REGULAR"+ name: "coin",+ slug: "coin-solid",+ category_id: 107,+ type_of_icon: "SOLID"},{- "name": "donate-blood",- "slug": "donate-blood-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "coin-stack",+ slug: "coin-stack-regular",+ category_id: 107,+ type_of_icon: "REGULAR"},{- "name": "shape-polygon",- "slug": "shape-polygon-regular",- "category_id": 118,- "type_of_icon": "REGULAR"+ name: "coin-stack",+ slug: "coin-stack-solid",+ category_id: 107,+ type_of_icon: "SOLID"},{- "name": "zoom",- "slug": "zoom-logo",- "category_id": 117,- "type_of_icon": "LOGO"+ name: "unite",+ slug: "unite-regular",+ category_id: 102,+ type_of_icon: "REGULAR"},{- "name": "microsoft-teams",- "slug": "microsoft-teams-logo",- "category_id": 99,- "type_of_icon": "LOGO"+ name: "minus-front",+ slug: "minus-front-regular",+ category_id: 102,+ type_of_icon: "REGULAR"},{- "name": "blender",- "slug": "blender-logo",- "category_id": 102,- "type_of_icon": "LOGO"+ name: "intersect",+ slug: "intersect-regular",+ category_id: 102,+ type_of_icon: "REGULAR"},{- "name": "kubernetes",- "slug": "kubernetes-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "exclude",+ slug: "exclude-regular",+ category_id: 102,+ type_of_icon: "REGULAR"},{- "name": "google-cloud",- "slug": "google-cloud-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "minus-back",+ slug: "minus-back-regular",+ category_id: 102,+ type_of_icon: "REGULAR"},{- "name": "django",- "slug": "django-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "merge",+ slug: "merge-regular",+ category_id: 102,+ type_of_icon: "REGULAR"},{- "name": "spring-boot",- "slug": "spring-boot-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "trim",+ slug: "trim-regular",+ category_id: 102,+ type_of_icon: "REGULAR"},{- "name": "tux",- "slug": "tux-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "outline",+ slug: "outline-regular",+ category_id: 102,+ type_of_icon: "REGULAR"},{- "name": "markdown",- "slug": "markdown-logo",- "category_id": 124,- "type_of_icon": "LOGO"+ name: "bullseye",+ slug: "bullseye-solid",+ category_id: 99,+ type_of_icon: "SOLID"},{- "name": "python",- "slug": "python-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "meteor",+ slug: "meteor-regular",+ category_id: 116,+ type_of_icon: "REGULAR"},{- "name": "ok-ru",- "slug": "ok-ru-logo",- "category_id": 97,- "type_of_icon": "LOGO"+ name: "meteor",+ slug: "meteor-solid",+ category_id: 116,+ type_of_icon: "SOLID"},{- "name": "firebase",- "slug": "firebase-logo",- "category_id": 100,- "type_of_icon": "LOGO"+ name: "refresh",+ slug: "refresh-regular",+ category_id: 110,+ type_of_icon: "REGULAR"},{- "name": "c-plus-plus",- "slug": "c-plus-plus-logo",- "category_id": 100,- "type_of_icon": "LOGO",- "term": [- "c++"- ]+ name: "home-smile",+ slug: "home-smile-regular",+ category_id: 98,+ type_of_icon: "REGULAR"},{- "name": "bookmark-heart",- "slug": "bookmark-heart-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "home-smile",+ slug: "home-smile-solid",+ category_id: 98,+ type_of_icon: "SOLID"},{- "name": "bookmark-heart",- "slug": "bookmark-heart-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "envelope-open",+ slug: "envelope-open-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "sort-alt-2",- "slug": "sort-alt-2-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "envelope-open",+ slug: "envelope-open-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "category",- "slug": "category-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "dev-to",+ slug: "dev-to-logo",+ category_id: 100,+ type_of_icon: "LOGO"},{- "name": "category",- "slug": "category-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "message-alt-add",+ slug: "message-alt-add-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "comment", "new", "plus"]},{- "name": "category-alt",- "slug": "category-alt-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "message-alt-add",+ slug: "message-alt-add-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "comment", "new", "plus"]},{- "name": "category-alt",- "slug": "category-alt-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "message-alt-check",+ slug: "message-alt-check-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "bookmark-alt",- "slug": "bookmark-alt-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "message-alt-check",+ slug: "message-alt-check-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "bookmark-alt",- "slug": "bookmark-alt-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "message-alt-error",+ slug: "message-alt-error-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "bookmark-alt-plus",- "slug": "bookmark-alt-plus-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "message-alt-error",+ slug: "message-alt-error-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "bookmark-alt-plus",- "slug": "bookmark-alt-plus-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "message-alt-x",+ slug: "message-alt-x-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "comment", "remove", "delete"]},{- "name": "bookmark-alt-minus",- "slug": "bookmark-alt-minus-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "message-alt-x",+ slug: "message-alt-x-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "comment", "remove", "delete"]},{- "name": "bookmark-alt-minus",- "slug": "bookmark-alt-minus-solid",- "category_id": 124,- "type_of_icon": "SOLID"+ name: "message-alt-minus",+ slug: "message-alt-minus-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "comment", "remove", "delete"]},{- "name": "face-mask",- "slug": "face-mask-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "message-alt-minus",+ slug: "message-alt-minus-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "comment", "remove", "delete"]},{- "name": "tv",- "slug": "tv-solid",- "category_id": 116,- "type_of_icon": "SOLID",- "term": [- "television",- "monitor"- ]+ name: "message-alt-edit",+ slug: "message-alt-edit-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "tag-alt",- "slug": "tag-alt-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "message-alt-edit",+ slug: "message-alt-edit-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "tag-alt",- "slug": "tag-alt-solid",- "category_id": 110,- "type_of_icon": "SOLID"+ name: "message-alt-detail",+ slug: "message-alt-detail-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "movie-play",- "slug": "movie-play-regular",- "category_id": 117,- "type_of_icon": "REGULAR"+ name: "message-alt-detail",+ slug: "message-alt-detail-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "movie-play",- "slug": "movie-play-solid",- "category_id": 117,- "type_of_icon": "SOLID"+ name: "message-rounded-check",+ slug: "message-rounded-check-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "user-account",- "slug": "user-account-solid",- "category_id": 122,- "type_of_icon": "SOLID"+ name: "message-rounded-check",+ slug: "message-rounded-check-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "expand-alt",- "slug": "expand-alt-regular",- "category_id": 110,- "type_of_icon": "REGULAR"+ name: "message-rounded-error",+ slug: "message-rounded-error-regular",+ category_id: 101,+ type_of_icon: "REGULAR"},{- "name": "library",- "slug": "library-regular",- "category_id": 124,- "type_of_icon": "REGULAR"+ name: "message-rounded-error",+ slug: "message-rounded-error-solid",+ category_id: 101,+ type_of_icon: "SOLID"},{- "name": "trip",- "slug": "trip-regular",- "category_id": 121,- "type_of_icon": "REGULAR"+ name: "message-rounded-x",+ slug: "message-rounded-x-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "comment", "remove", "delete"]},{- "name": "virus",- "slug": "virus-solid",- "category_id": 109,- "type_of_icon": "SOLID",- "term": [- "disease",- "covid",- "corona"- ]+ name: "message-rounded-x",+ slug: "message-rounded-x-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "comment", "remove", "delete"]},{- "name": "virus-block",- "slug": "virus-block-solid",- "category_id": 109,- "type_of_icon": "SOLID"+ name: "message-rounded-minus",+ slug: "message-rounded-minus-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "comment", "remove", "delete"]+ },+ {+ name: "message-rounded-minus",+ slug: "message-rounded-minus-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "comment", "remove", "delete"]+ },+ {+ name: "message-rounded-edit",+ slug: "message-rounded-edit-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "message-rounded-edit",+ slug: "message-rounded-edit-solid",+ category_id: 101,+ type_of_icon: "SOLID"+ },+ {+ name: "message-rounded-add",+ slug: "message-rounded-add-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "comment", "new", "plus"]+ },+ {+ name: "message-rounded-add",+ slug: "message-rounded-add-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "comment", "new", "plus"]+ },+ {+ name: "message-rounded-detail",+ slug: "message-rounded-detail-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "message-rounded-detail",+ slug: "message-rounded-detail-solid",+ category_id: 101,+ type_of_icon: "SOLID"+ },+ {+ name: "message-check",+ slug: "message-check-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "message-check",+ slug: "message-check-solid",+ category_id: 101,+ type_of_icon: "SOLID"+ },+ {+ name: "message-error",+ slug: "message-error-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "message-error",+ slug: "message-error-solid",+ category_id: 101,+ type_of_icon: "SOLID"+ },+ {+ name: "message-x",+ slug: "message-x-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "comment", "remove", "delete"]+ },+ {+ name: "message-x",+ slug: "message-x-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "comment", "remove", "delete"]+ },+ {+ name: "message-minus",+ slug: "message-minus-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "comment", "remove", "delete"]+ },+ {+ name: "message-minus",+ slug: "message-minus-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "comment", "remove", "delete"]+ },+ {+ name: "message-edit",+ slug: "message-edit-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "message-edit",+ slug: "message-edit-solid",+ category_id: 101,+ type_of_icon: "SOLID"+ },+ {+ name: "message-add",+ slug: "message-add-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "comment", "new", "plus"]+ },+ {+ name: "message-add",+ slug: "message-add-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "comment", "new", "plus"]+ },+ {+ name: "message-detail",+ slug: "message-detail-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "message-detail",+ slug: "message-detail-solid",+ category_id: 101,+ type_of_icon: "SOLID"+ },+ {+ name: "message-square-check",+ slug: "message-square-check-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "message-square-check",+ slug: "message-square-check-solid",+ category_id: 101,+ type_of_icon: "SOLID"+ },+ {+ name: "message-square-error",+ slug: "message-square-error-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "message-square-error",+ slug: "message-square-error-solid",+ category_id: 101,+ type_of_icon: "SOLID"+ },+ {+ name: "message-square-x",+ slug: "message-square-x-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "comment", "remove", "delete"]+ },+ {+ name: "message-square-x",+ slug: "message-square-x-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "comment", "remove", "delete"]+ },+ {+ name: "message-square-minus",+ slug: "message-square-minus-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "comment", "remove", "delete"]+ },+ {+ name: "message-square-minus",+ slug: "message-square-minus-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "comment", "remove", "delete"]+ },+ {+ name: "message-square-edit",+ slug: "message-square-edit-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "message-square-edit",+ slug: "message-square-edit-solid",+ category_id: 101,+ type_of_icon: "SOLID"+ },+ {+ name: "message-square-add",+ slug: "message-square-add-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "comment", "new", "plus"]+ },+ {+ name: "message-square-add",+ slug: "message-square-add-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "comment", "new", "plus"]+ },+ {+ name: "message-square-detail",+ slug: "message-square-detail-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "message-square-detail",+ slug: "message-square-detail-solid",+ category_id: 101,+ type_of_icon: "SOLID"+ },+ {+ name: "comment-check",+ slug: "comment-check-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "comment-check",+ slug: "comment-check-solid",+ category_id: 101,+ type_of_icon: "SOLID"+ },+ {+ name: "comment-error",+ slug: "comment-error-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "comment-x",+ slug: "comment-x-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "message", "remove", "delete"]+ },+ {+ name: "comment-x",+ slug: "comment-x-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "message", "remove", "delete"]+ },+ {+ name: "comment-edit",+ slug: "comment-edit-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "comment-edit",+ slug: "comment-edit-solid",+ category_id: 101,+ type_of_icon: "SOLID"+ },+ {+ name: "comment-minus",+ slug: "comment-minus-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "message", "remove", "delete"]+ },+ {+ name: "comment-minus",+ slug: "comment-minus-solid",+ category_id: 101,+ type_of_icon: "SOLID",+ term: ["chat", "message", "remove", "delete"]+ },+ {+ name: "comment-add",+ slug: "comment-add-regular",+ category_id: 101,+ type_of_icon: "REGULAR",+ term: ["chat", "message", "new", "plus"]+ },+ {+ name: "comment-detail",+ slug: "comment-detail-regular",+ category_id: 101,+ type_of_icon: "REGULAR"+ },+ {+ name: "cookie",+ slug: "cookie-regular",+ category_id: 108,+ type_of_icon: "REGULAR",+ term: ["biscuit"]+ },+ {+ name: "cookie",+ slug: "cookie-solid",+ category_id: 108,+ type_of_icon: "SOLID",+ term: ["biscuit"]+ },+ {+ name: "copyright",+ slug: "copyright-solid",+ category_id: 99,+ type_of_icon: "SOLID"+ },+ {+ name: "credit-card-front",+ slug: "credit-card-front-regular",+ category_id: 107,+ type_of_icon: "REGULAR",+ term: ["finance", "money", "debit"]+ },+ {+ name: "credit-card-front",+ slug: "credit-card-front-solid",+ category_id: 107,+ type_of_icon: "SOLID",+ term: ["finance", "money", "debit"]+ },+ {+ name: "crop",+ slug: "crop-solid",+ category_id: 102,+ type_of_icon: "SOLID"+ },+ {+ name: "diamond",+ slug: "diamond-solid",+ category_id: 116,+ type_of_icon: "SOLID"+ },+ {+ name: "door-open",+ slug: "door-open-regular",+ category_id: 121,+ type_of_icon: "REGULAR"+ },+ {+ name: "door-open",+ slug: "door-open-solid",+ category_id: 121,+ type_of_icon: "SOLID"+ },+ {+ name: "donate-heart",+ slug: "donate-heart-regular",+ category_id: 107,+ type_of_icon: "REGULAR",+ term: ["donation", "contribution"]+ },+ {+ name: "donate-heart",+ slug: "donate-heart-solid",+ category_id: 107,+ type_of_icon: "SOLID",+ term: ["donation", "contribution"]+ },+ {+ name: "donate-blood",+ slug: "donate-blood-regular",+ category_id: 109,+ type_of_icon: "REGULAR"+ },+ {+ name: "donate-blood",+ slug: "donate-blood-solid",+ category_id: 109,+ type_of_icon: "SOLID"+ },+ {+ name: "shape-polygon",+ slug: "shape-polygon-regular",+ category_id: 118,+ type_of_icon: "REGULAR"+ },+ {+ name: "zoom",+ slug: "zoom-logo",+ category_id: 117,+ type_of_icon: "LOGO"+ },+ {+ name: "microsoft-teams",+ slug: "microsoft-teams-logo",+ category_id: 99,+ type_of_icon: "LOGO"+ },+ {+ name: "blender",+ slug: "blender-logo",+ category_id: 102,+ type_of_icon: "LOGO"+ },+ {+ name: "kubernetes",+ slug: "kubernetes-logo",+ category_id: 100,+ type_of_icon: "LOGO"+ },+ {+ name: "google-cloud",+ slug: "google-cloud-logo",+ category_id: 97,+ type_of_icon: "LOGO"+ },+ {+ name: "django",+ slug: "django-logo",+ category_id: 100,+ type_of_icon: "LOGO"+ },+ {+ name: "spring-boot",+ slug: "spring-boot-logo",+ category_id: 100,+ type_of_icon: "LOGO"+ },+ {+ name: "tux",+ slug: "tux-logo",+ category_id: 97,+ type_of_icon: "LOGO"+ },+ {+ name: "markdown",+ slug: "markdown-logo",+ category_id: 124,+ type_of_icon: "LOGO"+ },+ {+ name: "python",+ slug: "python-logo",+ category_id: 100,+ type_of_icon: "LOGO"+ },+ {+ name: "ok-ru",+ slug: "ok-ru-logo",+ category_id: 97,+ type_of_icon: "LOGO"+ },+ {+ name: "firebase",+ slug: "firebase-logo",+ category_id: 100,+ type_of_icon: "LOGO"+ },+ {+ name: "c-plus-plus",+ slug: "c-plus-plus-logo",+ category_id: 100,+ type_of_icon: "LOGO",+ term: ["c++"]+ },+ {+ name: "bookmark-heart",+ slug: "bookmark-heart-regular",+ category_id: 124,+ type_of_icon: "REGULAR"+ },+ {+ name: "bookmark-heart",+ slug: "bookmark-heart-solid",+ category_id: 124,+ type_of_icon: "SOLID"+ },+ {+ name: "sort-alt-2",+ slug: "sort-alt-2-regular",+ category_id: 110,+ type_of_icon: "REGULAR"+ },+ {+ name: "category",+ slug: "category-regular",+ category_id: 110,+ type_of_icon: "REGULAR"+ },+ {+ name: "category",+ slug: "category-solid",+ category_id: 110,+ type_of_icon: "SOLID"+ },+ {+ name: "category-alt",+ slug: "category-alt-regular",+ category_id: 110,+ type_of_icon: "REGULAR"+ },+ {+ name: "category-alt",+ slug: "category-alt-solid",+ category_id: 110,+ type_of_icon: "SOLID"+ },+ {+ name: "bookmark-alt",+ slug: "bookmark-alt-regular",+ category_id: 124,+ type_of_icon: "REGULAR"+ },+ {+ name: "bookmark-alt",+ slug: "bookmark-alt-solid",+ category_id: 124,+ type_of_icon: "SOLID"+ },+ {+ name: "bookmark-alt-plus",+ slug: "bookmark-alt-plus-regular",+ category_id: 124,+ type_of_icon: "REGULAR"+ },+ {+ name: "bookmark-alt-plus",+ slug: "bookmark-alt-plus-solid",+ category_id: 124,+ type_of_icon: "SOLID"+ },+ {+ name: "bookmark-alt-minus",+ slug: "bookmark-alt-minus-regular",+ category_id: 124,+ type_of_icon: "REGULAR"+ },+ {+ name: "bookmark-alt-minus",+ slug: "bookmark-alt-minus-solid",+ category_id: 124,+ type_of_icon: "SOLID"+ },+ {+ name: "face-mask",+ slug: "face-mask-solid",+ category_id: 109,+ type_of_icon: "SOLID"+ },+ {+ name: "tv",+ slug: "tv-solid",+ category_id: 116,+ type_of_icon: "SOLID",+ term: ["television", "monitor"]+ },+ {+ name: "tag-alt",+ slug: "tag-alt-regular",+ category_id: 110,+ type_of_icon: "REGULAR"+ },+ {+ name: "tag-alt",+ slug: "tag-alt-solid",+ category_id: 110,+ type_of_icon: "SOLID"+ },+ {+ name: "movie-play",+ slug: "movie-play-regular",+ category_id: 117,+ type_of_icon: "REGULAR"+ },+ {+ name: "movie-play",+ slug: "movie-play-solid",+ category_id: 117,+ type_of_icon: "SOLID"+ },+ {+ name: "user-account",+ slug: "user-account-solid",+ category_id: 122,+ type_of_icon: "SOLID"+ },+ {+ name: "expand-alt",+ slug: "expand-alt-regular",+ category_id: 110,+ type_of_icon: "REGULAR"+ },+ {+ name: "library",+ slug: "library-regular",+ category_id: 124,+ type_of_icon: "REGULAR"+ },+ {+ name: "trip",+ slug: "trip-regular",+ category_id: 121,+ type_of_icon: "REGULAR"+ },+ {+ name: "virus",+ slug: "virus-solid",+ category_id: 109,+ type_of_icon: "SOLID",+ term: ["disease", "covid", "corona"]+ },+ {+ name: "virus-block",+ slug: "virus-block-solid",+ category_id: 109,+ type_of_icon: "SOLID"}];function getIconClass(icon: Icon) {- if (icon.type_of_icon === 'LOGO') {+ if (icon.type_of_icon === "LOGO") {return `bxl-${icon.name}`;- }- else if (icon.type_of_icon === 'SOLID') {+ } else if (icon.type_of_icon === "SOLID") {return `bxs-${icon.name}`;- }- else {+ } else {return `bx-${icon.name}`;}}diff --git a/src/public/app/widgets/mermaid.js b/src/public/app/widgets/mermaid.jsindex 703698dcf5..6923807af1 100644--- a/src/public/app/widgets/mermaid.js+++ b/src/public/app/widgets/mermaid.js@@ -29,7 +29,7 @@ const TPL = `<div class="mermaid-widget"></style><div class="mermaid-error alert alert-warning">- <p><strong>${t('mermaid.diagram_error')}</strong></p>+ <p><strong>${t("mermaid.diagram_error")}</strong></p><p class="error-content"></p></div>@@ -40,16 +40,13 @@ let idCounter = 1;export default class MermaidWidget extends NoteContextAwareWidget {isEnabled() {- return super.isEnabled()- && this.note?.type === 'mermaid'- && this.note.isContentAvailable()- && this.noteContext?.viewScope.viewMode === 'default';+ return super.isEnabled() && this.note?.type === "mermaid" && this.note.isContentAvailable() && this.noteContext?.viewScope.viewMode === "default";}doRender() {this.$widget = $(TPL);this.contentSized();- this.$display = this.$widget.find('.mermaid-render');+ this.$display = this.$widget.find(".mermaid-render");this.$errorContainer = this.$widget.find(".mermaid-error");this.$errorMessage = this.$errorContainer.find(".error-content");}@@ -75,9 +72,9 @@ export default class MermaidWidget extends NoteContextAwareWidget {if (this.dirtyAttachment) {const payload = {- role: 'image',- title: 'mermaid-export.svg',- mime: 'image/svg+xml',+ role: "image",+ title: "mermaid-export.svg",+ mime: "image/svg+xml",content: svg,position: 0};@@ -94,7 +91,7 @@ export default class MermaidWidget extends NoteContextAwareWidget {this.$display.attr("id", `mermaid-render-${idCounter}`);WZoom.create(`#mermaid-render-${idCounter}`, {- type: 'html',+ type: "html",maxScale: 50,speed: 1.3,zoomOnClick: false@@ -113,11 +110,11 @@ export default class MermaidWidget extends NoteContextAwareWidget {const content = blob.content || "";await loadElkIfNeeded(content);- const {svg} = await mermaid.mermaidAPI.render(`mermaid-graph-${idCounter}`, content);+ const { svg } = await mermaid.mermaidAPI.render(`mermaid-graph-${idCounter}`, content);return svg;}- async entitiesReloadedEvent({loadResults}) {+ async entitiesReloadedEvent({ loadResults }) {if (loadResults.isNoteContentReloaded(this.noteId)) {this.dirtyAttachment = true;@@ -125,7 +122,7 @@ export default class MermaidWidget extends NoteContextAwareWidget {}}- async exportSvgEvent({ntxId}) {+ async exportSvgEvent({ ntxId }) {if (!this.isNoteContext(ntxId) || this.note.type !== "mermaid") {return;}@@ -137,18 +134,18 @@ export default class MermaidWidget extends NoteContextAwareWidget {export function getMermaidConfig() {const documentStyle = window.getComputedStyle(document.documentElement);- const mermaidTheme = documentStyle.getPropertyValue('--mermaid-theme');+ const mermaidTheme = documentStyle.getPropertyValue("--mermaid-theme");return {theme: mermaidTheme.trim(),- securityLevel: 'antiscript',+ securityLevel: "antiscript",flow: { useMaxWidth: false },sequence: { useMaxWidth: false },gantt: { useMaxWidth: false },- "class": { useMaxWidth: false },+ class: { useMaxWidth: false },state: { useMaxWidth: false },pie: { useMaxWidth: true },journey: { useMaxWidth: false },- git: { useMaxWidth: false },+ git: { useMaxWidth: false }};}diff --git a/src/public/app/widgets/mobile_widgets/mobile_detail_menu.js b/src/public/app/widgets/mobile_widgets/mobile_detail_menu.jsindex 7ad1592e4a..29f7582715 100644--- a/src/public/app/widgets/mobile_widgets/mobile_detail_menu.js+++ b/src/public/app/widgets/mobile_widgets/mobile_detail_menu.js@@ -9,7 +9,6 @@ import { t } from "../../services/i18n.js";const TPL = `<button type="button" class="action-button bx" style="padding-top: 10px;"></button>`;class MobileDetailMenuWidget extends BasicWidget {-constructor(isHorizontalLayout) {super();this.isHorizontalLayout = isHorizontalLayout;@@ -20,23 +19,20 @@ class MobileDetailMenuWidget extends BasicWidget {this.$widget.addClass(this.isHorizontalLayout ? "bx-dots-vertical-rounded" : "bx-menu");- this.$widget.on("click", async e => {+ this.$widget.on("click", async (e) => {const note = appContext.tabManager.getActiveContextNote();contextMenu.show({x: e.pageX,y: e.pageY,items: [- { title: t("mobile_detail_menu.insert_child_note"), command: "insertChildNote", uiIcon: "bx bx-plus",- enabled: note.type !== 'search' },- { title: t("mobile_detail_menu.delete_this_note"), command: "delete", uiIcon: "bx bx-trash",- enabled: note.noteId !== 'root' }+ { title: t("mobile_detail_menu.insert_child_note"), command: "insertChildNote", uiIcon: "bx bx-plus", enabled: note.type !== "search" },+ { title: t("mobile_detail_menu.delete_this_note"), command: "delete", uiIcon: "bx bx-trash", enabled: note.noteId !== "root" }],- selectMenuItemHandler: async ({command}) => {+ selectMenuItemHandler: async ({ command }) => {if (command === "insertChildNote") {noteCreateService.createNote(appContext.tabManager.getActiveContextNotePath());- }- else if (command === "delete") {+ } else if (command === "delete") {const notePath = appContext.tabManager.getActiveContextNotePath();const branchId = await treeService.getBranchIdFromUrl(notePath);@@ -45,10 +41,9 @@ class MobileDetailMenuWidget extends BasicWidget {}if (await branchService.deleteNotes([branchId])) {- this.triggerCommand('setActiveScreen', {screen:'tree'})+ this.triggerCommand("setActiveScreen", { screen: "tree" });}- }- else {+ } else {throw new Error(t("mobile_detail_menu.error_unrecognized_command", { command }));}}diff --git a/src/public/app/widgets/mobile_widgets/screen_container.js b/src/public/app/widgets/mobile_widgets/screen_container.jsindex d008ddfd58..9fab0a4fc3 100644--- a/src/public/app/widgets/mobile_widgets/screen_container.js+++ b/src/public/app/widgets/mobile_widgets/screen_container.js@@ -7,7 +7,5 @@ export default class ScreenContainer extends FlexContainer {this.screenName = screenName;}- activeScreenChangedEvent({activeScreen}) {-- }+ activeScreenChangedEvent({ activeScreen }) {}}diff --git a/src/public/app/widgets/mobile_widgets/sidebar_container.ts b/src/public/app/widgets/mobile_widgets/sidebar_container.tsindex 1183f366c6..b1bf58e6ff 100644--- a/src/public/app/widgets/mobile_widgets/sidebar_container.ts+++ b/src/public/app/widgets/mobile_widgets/sidebar_container.ts@@ -16,7 +16,6 @@ const DRAG_CLOSED_START_THRESHOLD = 10;const DRAG_OPENED_START_THRESHOLD = 80;export default class SidebarContainer extends FlexContainer<BasicWidget> {-private screenName: Screen;/** The screen name that is currently active, according to the screen changed event. */private activeScreenName?: Screen;@@ -89,7 +88,7 @@ export default class SidebarContainer extends FlexContainer<BasicWidget> {const translatePercentage = Math.min(0, Math.max(this.currentTranslate + (deltaX / width) * 100, -100));this.translatePercentage = translatePercentage;this.sidebarEl.style.transform = `translateX(${translatePercentage}%)`;- this.backdropEl.style.opacity = String(Math.max(0, 1 + (translatePercentage / 100)));+ this.backdropEl.style.opacity = String(Math.max(0, 1 + translatePercentage / 100));}// Consume the event to prevent the user from doing the back to previous page gesture on iOS.@@ -108,8 +107,8 @@ export default class SidebarContainer extends FlexContainer<BasicWidget> {// If the sidebar is closed, snap the sidebar open only if the user swiped over a threshold.// When the sidebar is open, always close for a smooth experience.- const isOpen = (this.currentTranslate === -100 && this.translatePercentage > -(100 - DRAG_OPEN_THRESHOLD));- const screen = (isOpen ? "tree" : "detail");+ const isOpen = this.currentTranslate === -100 && this.translatePercentage > -(100 - DRAG_OPEN_THRESHOLD);+ const screen = isOpen ? "tree" : "detail";if (this.activeScreenName !== screen) {// Trigger the set active screen command for the rest of the UI to know whether the sidebar is active or not.@@ -131,7 +130,7 @@ export default class SidebarContainer extends FlexContainer<BasicWidget> {const sidebarEl = document.getElementById("mobile-sidebar-wrapper");const backdropEl = document.getElementById("mobile-sidebar-container");backdropEl?.addEventListener("click", () => {- this.triggerCommand('setActiveScreen', { screen: "detail" });+ this.triggerCommand("setActiveScreen", { screen: "detail" });});if (!sidebarEl || !backdropEl) {@@ -150,7 +149,7 @@ export default class SidebarContainer extends FlexContainer<BasicWidget> {}this.sidebarEl.classList.toggle("show", isOpen);- this.sidebarEl.style.transform = isOpen ? 'translateX(0)' : 'translateX(-100%)';+ this.sidebarEl.style.transform = isOpen ? "translateX(0)" : "translateX(-100%)";this.sidebarEl.style.transition = this.originalSidebarTransition;this.backdropEl.classList.toggle("show", isOpen);@@ -161,10 +160,9 @@ export default class SidebarContainer extends FlexContainer<BasicWidget> {this.dragState = DRAG_STATE_NONE;}- activeScreenChangedEvent({activeScreen}: EventData<"activeScreenChanged">) {+ activeScreenChangedEvent({ activeScreen }: EventData<"activeScreenChanged">) {this.activeScreenName = activeScreen;this.#setInitialState();this.#setSidebarOpen(activeScreen === this.screenName);}-}diff --git a/src/public/app/widgets/mobile_widgets/toggle_sidebar_button.js b/src/public/app/widgets/mobile_widgets/toggle_sidebar_button.jsindex 976aad3fbb..b41247bca7 100644--- a/src/public/app/widgets/mobile_widgets/toggle_sidebar_button.js+++ b/src/public/app/widgets/mobile_widgets/toggle_sidebar_button.js@@ -7,9 +7,11 @@ class ToggleSidebarButtonWidget extends BasicWidget {doRender() {this.$widget = $(TPL);- this.$widget.on('click', () => this.triggerCommand('setActiveScreen', {- screen: 'tree'- }));+ this.$widget.on("click", () =>+ this.triggerCommand("setActiveScreen", {+ screen: "tree"+ })+ );}}diff --git a/src/public/app/widgets/note_context_aware_widget.ts b/src/public/app/widgets/note_context_aware_widget.tsindex 5e1ec78501..596b92ac69 100644--- a/src/public/app/widgets/note_context_aware_widget.ts+++ b/src/public/app/widgets/note_context_aware_widget.ts@@ -8,14 +8,12 @@ import NoteContext from "../components/note_context.js";* @extends {BasicWidget}*/class NoteContextAwareWidget extends BasicWidget {-protected noteContext?: NoteContext;isNoteContext(ntxId: string | null | undefined) {if (Array.isArray(ntxId)) {return this.noteContext && ntxId.includes(this.noteContext.ntxId);- }- else {+ } else {return this.noteContext && this.noteContext.ntxId === ntxId;}}@@ -74,8 +72,7 @@ class NoteContextAwareWidget extends BasicWidget {throw e;}- }- else {+ } else {this.toggleInt(false);}}@@ -85,7 +82,7 @@ class NoteContextAwareWidget extends BasicWidget {*/async refreshWithNote(note: FNote | null | undefined) {}- async noteSwitchedEvent({noteContext, notePath}: EventData<"noteSwitched">) {+ async noteSwitchedEvent({ noteContext, notePath }: EventData<"noteSwitched">) {this.noteContext = noteContext;// if notePath does not match, then the noteContext has been switched to another note in the meantimeif (noteContext.notePath === notePath) {@@ -97,7 +94,7 @@ class NoteContextAwareWidget extends BasicWidget {await this.refresh();}- async activeContextChangedEvent({noteContext}: EventData<"activeContextChanged">) {+ async activeContextChangedEvent({ noteContext }: EventData<"activeContextChanged">) {this.noteContext = noteContext;await this.activeContextChanged();@@ -108,7 +105,7 @@ class NoteContextAwareWidget extends BasicWidget {}// when note is both switched and activated, this should not produce a double refresh- async noteSwitchedAndActivatedEvent({noteContext, notePath}: EventData<"noteSwitchedAndActivatedEvent">) {+ async noteSwitchedAndActivatedEvent({ noteContext, notePath }: EventData<"noteSwitchedAndActivatedEvent">) {this.noteContext = noteContext;// if notePath does not match, then the noteContext has been switched to another note in the meantime@@ -117,12 +114,12 @@ class NoteContextAwareWidget extends BasicWidget {}}- setNoteContextEvent({noteContext}: EventData<"setNoteContext">) {+ setNoteContextEvent({ noteContext }: EventData<"setNoteContext">) {/** @var {NoteContext} */this.noteContext = noteContext;}- async noteTypeMimeChangedEvent({noteId}: EventData<"noteTypeMimeChangedEvent">) {+ async noteTypeMimeChangedEvent({ noteId }: EventData<"noteTypeMimeChangedEvent">) {if (this.isNote(noteId)) {await this.refresh();}diff --git a/src/public/app/widgets/note_detail.js b/src/public/app/widgets/note_detail.jsindex f294b18ed5..22850c35e5 100644--- a/src/public/app/widgets/note_detail.js+++ b/src/public/app/widgets/note_detail.js@@ -48,26 +48,26 @@ const TPL = ``;const typeWidgetClasses = {- 'empty': EmptyTypeWidget,- 'editableText': EditableTextTypeWidget,- 'readOnlyText': ReadOnlyTextTypeWidget,- 'editableCode': EditableCodeTypeWidget,- 'readOnlyCode': ReadOnlyCodeTypeWidget,- 'file': FileTypeWidget,- 'image': ImageTypeWidget,- 'search': NoneTypeWidget,- 'render': RenderTypeWidget,- 'relationMap': RelationMapTypeWidget,- 'canvas': CanvasTypeWidget,- 'protectedSession': ProtectedSessionTypeWidget,- 'book': BookTypeWidget,- 'noteMap': NoteMapTypeWidget,- 'webView': WebViewTypeWidget,- 'doc': DocTypeWidget,- 'contentWidget': ContentWidgetTypeWidget,- 'attachmentDetail': AttachmentDetailTypeWidget,- 'attachmentList': AttachmentListTypeWidget,- 'mindMap': MindMapWidget+ empty: EmptyTypeWidget,+ editableText: EditableTextTypeWidget,+ readOnlyText: ReadOnlyTextTypeWidget,+ editableCode: EditableCodeTypeWidget,+ readOnlyCode: ReadOnlyCodeTypeWidget,+ file: FileTypeWidget,+ image: ImageTypeWidget,+ search: NoneTypeWidget,+ render: RenderTypeWidget,+ relationMap: RelationMapTypeWidget,+ canvas: CanvasTypeWidget,+ protectedSession: ProtectedSessionTypeWidget,+ book: BookTypeWidget,+ noteMap: NoteMapTypeWidget,+ webView: WebViewTypeWidget,+ doc: DocTypeWidget,+ contentWidget: ContentWidgetTypeWidget,+ attachmentDetail: AttachmentDetailTypeWidget,+ attachmentList: AttachmentListTypeWidget,+ mindMap: MindMapWidget};export default class NoteDetailWidget extends NoteContextAwareWidget {@@ -77,8 +77,8 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {this.typeWidgets = {};this.spacedUpdate = new SpacedUpdate(async () => {- const {note} = this.noteContext;- const {noteId} = note;+ const { note } = this.noteContext;+ const { noteId } = note;const data = await this.getTypeWidget().getData();@@ -117,7 +117,7 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {throw new Error(`Cannot find type widget for type '${this.type}'`);}- const typeWidget = this.typeWidgets[this.type] = new clazz();+ const typeWidget = (this.typeWidgets[this.type] = new clazz());typeWidget.spacedUpdate = this.spacedUpdate;typeWidget.setParent(this);@@ -126,10 +126,10 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {this.$widget.append($renderedWidget);- await typeWidget.handleEvent('setNoteContext', {noteContext: this.noteContext});+ await typeWidget.handleEvent("setNoteContext", { noteContext: this.noteContext });// this is happening in update(), so note has been already set, and we need to reflect this- await typeWidget.handleEvent('noteSwitched', {+ await typeWidget.handleEvent("noteSwitched", {noteContext: this.noteContext,notePath: this.noteContext.notePath});@@ -145,13 +145,10 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {*/checkFullHeight() {// https://github.com/zadam/trilium/issues/2522- this.$widget.toggleClass("full-height",- (- !this.noteContext.hasNoteList()- && ['canvas', 'webView', 'noteMap', 'mindMap'].includes(this.type)- && this.mime !== 'text/x-sqlite;schema=trilium'- )- || this.noteContext.viewScope.viewMode === 'attachments'+ this.$widget.toggleClass(+ "full-height",+ (!this.noteContext.hasNoteList() && ["canvas", "webView", "noteMap", "mindMap"].includes(this.type) && this.mime !== "text/x-sqlite;schema=trilium") ||+ this.noteContext.viewScope.viewMode === "attachments");}@@ -173,30 +170,30 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {let type = note.type;const viewScope = this.noteContext.viewScope;- if (viewScope.viewMode === 'source') {- type = 'readOnlyCode';- } else if (viewScope.viewMode === 'attachments') {- type = viewScope.attachmentId ? 'attachmentDetail' : 'attachmentList';- } else if (type === 'text' && await this.noteContext.isReadOnly()) {- type = 'readOnlyText';- } else if ((type === 'code' || type === 'mermaid') && await this.noteContext.isReadOnly()) {- type = 'readOnlyCode';- } else if (type === 'text') {- type = 'editableText';- } else if (type === 'code' || type === 'mermaid') {- type = 'editableCode';- } else if (type === 'launcher') {- type = 'doc';+ if (viewScope.viewMode === "source") {+ type = "readOnlyCode";+ } else if (viewScope.viewMode === "attachments") {+ type = viewScope.attachmentId ? "attachmentDetail" : "attachmentList";+ } else if (type === "text" && (await this.noteContext.isReadOnly())) {+ type = "readOnlyText";+ } else if ((type === "code" || type === "mermaid") && (await this.noteContext.isReadOnly())) {+ type = "readOnlyCode";+ } else if (type === "text") {+ type = "editableText";+ } else if (type === "code" || type === "mermaid") {+ type = "editableCode";+ } else if (type === "launcher") {+ type = "doc";}if (note.isProtected && !protectedSessionHolder.isProtectedSessionAvailable()) {- type = 'protectedSession';+ type = "protectedSession";}return type;}- async focusOnDetailEvent({ntxId}) {+ async focusOnDetailEvent({ ntxId }) {if (this.noteContext.ntxId !== ntxId) {return;}@@ -207,7 +204,7 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {widget.focus();}- async scrollToEndEvent({ntxId}) {+ async scrollToEndEvent({ ntxId }) {if (this.noteContext.ntxId !== ntxId) {return;}@@ -221,13 +218,13 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {}}- async beforeNoteSwitchEvent({noteContext}) {+ async beforeNoteSwitchEvent({ noteContext }) {if (this.isNoteContext(noteContext.ntxId)) {await this.spacedUpdate.updateNowIfNecessary();}}- async beforeNoteContextRemoveEvent({ntxIds}) {+ async beforeNoteContextRemoveEvent({ ntxIds }) {if (this.isNoteContext(ntxIds)) {await this.spacedUpdate.updateNowIfNecessary();}@@ -239,7 +236,7 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {await this.spacedUpdate.updateNowIfNecessary();}- return await this.parent.triggerCommand('runActiveNote', params);+ return await this.parent.triggerCommand("runActiveNote", params);}async printActiveNoteEvent() {@@ -255,7 +252,7 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {$promotedAttributes = (await attributeRenderer.renderNormalAttributes(this.note)).$renderedAttributes;}- const {assetPath} = window.glob;+ const { assetPath } = window.glob;const cssToLoad = [`${assetPath}/node_modules/codemirror/lib/codemirror.css`,`${assetPath}/libraries/ckeditor/ckeditor-content.css`,@@ -270,11 +267,8 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {cssToLoad.push(getStylesheetUrl("default:vs"));}- this.$widget.find('.note-detail-printable:visible').printThis({- header: $("<div>")- .append($("<h2>").text(this.note.title))- .append($promotedAttributes)- .prop('outerHTML'),+ this.$widget.find(".note-detail-printable:visible").printThis({+ header: $("<div>").append($("<h2>").text(this.note.title)).append($promotedAttributes).prop("outerHTML"),footer: `<script src="${assetPath}/node_modules/katex/dist/katex.min.js"></script>@@ -292,13 +286,13 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {});}- hoistedNoteChangedEvent({ntxId}) {+ hoistedNoteChangedEvent({ ntxId }) {if (this.isNoteContext(ntxId)) {this.refresh();}}- async entitiesReloadedEvent({loadResults}) {+ async entitiesReloadedEvent({ loadResults }) {// we're detecting note type change on the note_detail level, but triggering the noteTypeMimeChanged// globally, so it gets also to e.g. ribbon components. But this means that the event can be generated multiple// times if the same note is open in several tabs.@@ -310,31 +304,24 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {// this uses handleEvent to make sure that the ordinary content updates are propagated only in the subtree// to avoid the problem in #3365- this.handleEvent('noteTypeMimeChanged', {noteId: this.noteId});- }- else if (loadResults.isNoteReloaded(this.noteId, this.componentId)- && (this.type !== await this.getWidgetType() || this.mime !== this.note.mime)) {-+ this.handleEvent("noteTypeMimeChanged", { noteId: this.noteId });+ } else if (loadResults.isNoteReloaded(this.noteId, this.componentId) && (this.type !== (await this.getWidgetType()) || this.mime !== this.note.mime)) {// this needs to have a triggerEvent so that e.g., note type (not in the component subtree) is updated- this.triggerEvent('noteTypeMimeChanged', {noteId: this.noteId});- }- else {+ this.triggerEvent("noteTypeMimeChanged", { noteId: this.noteId });+ } else {const attrs = loadResults.getAttributeRows();- const label = attrs.find(attr =>- attr.type === 'label'- && ['readOnly', 'autoReadOnlyDisabled', 'cssClass', 'displayRelations', 'hideRelations'].includes(attr.name)- && attributeService.isAffecting(attr, this.note));+ const label = attrs.find(+ (attr) =>+ attr.type === "label" && ["readOnly", "autoReadOnlyDisabled", "cssClass", "displayRelations", "hideRelations"].includes(attr.name) && attributeService.isAffecting(attr, this.note)+ );- const relation = attrs.find(attr =>- attr.type === 'relation'- && ['template', 'inherit', 'renderNote'].includes(attr.name)- && attributeService.isAffecting(attr, this.note));+ const relation = attrs.find((attr) => attr.type === "relation" && ["template", "inherit", "renderNote"].includes(attr.name) && attributeService.isAffecting(attr, this.note));if (label || relation) {// probably incorrect event// calling this.refresh() is not enough since the event needs to be propagated to children as well- this.triggerEvent('noteTypeMimeChanged', {noteId: this.noteId});+ this.triggerEvent("noteTypeMimeChanged", { noteId: this.noteId });}}}@@ -343,13 +330,13 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {return this.spacedUpdate.isAllSavedAndTriggerUpdate();}- readOnlyTemporarilyDisabledEvent({noteContext}) {+ readOnlyTemporarilyDisabledEvent({ noteContext }) {if (this.isNoteContext(noteContext.ntxId)) {this.refresh();}}- async executeInActiveNoteDetailWidgetEvent({callback}) {+ async executeInActiveNoteDetailWidgetEvent({ callback }) {if (!this.isActiveNoteContext()) {return;}@@ -385,7 +372,7 @@ export default class NoteDetailWidget extends NoteContextAwareWidget {}}- async executeWithTypeWidgetEvent({resolve, ntxId}) {+ async executeWithTypeWidgetEvent({ resolve, ntxId }) {if (!this.isNoteContext(ntxId)) {return;}diff --git a/src/public/app/widgets/note_icon.js b/src/public/app/widgets/note_icon.jsindex e93e4e09bd..cbf26e8271 100644--- a/src/public/app/widgets/note_icon.js+++ b/src/public/app/widgets/note_icon.js@@ -82,39 +82,32 @@ const TPL = `export default class NoteIconWidget extends NoteContextAwareWidget {doRender() {this.$widget = $(TPL);- this.$icon = this.$widget.find('button.note-icon');- this.$iconList = this.$widget.find('.icon-list');- this.$iconList.on('click', 'span', async e => {- const clazz = $(e.target).attr('class');-- await attributeService.setLabel(this.noteId,- this.note.hasOwnedLabel('workspace') ? 'workspaceIconClass' : 'iconClass',- clazz- );+ this.$icon = this.$widget.find("button.note-icon");+ this.$iconList = this.$widget.find(".icon-list");+ this.$iconList.on("click", "span", async (e) => {+ const clazz = $(e.target).attr("class");++ await attributeService.setLabel(this.noteId, this.note.hasOwnedLabel("workspace") ? "workspaceIconClass" : "iconClass", clazz);});this.$iconCategory = this.$widget.find("select[name='icon-category']");- this.$iconCategory.on('change', () => this.renderDropdown());- this.$iconCategory.on('click', e => e.stopPropagation());+ this.$iconCategory.on("change", () => this.renderDropdown());+ this.$iconCategory.on("click", (e) => e.stopPropagation());this.$iconSearch = this.$widget.find("input[name='icon-search']");- this.$iconSearch.on('input', () => this.renderDropdown());+ this.$iconSearch.on("input", () => this.renderDropdown());this.$notePathList = this.$widget.find(".note-path-list");- this.$widget.on('show.bs.dropdown', async () => {- const {categories} = (await import('./icon_list.js')).default;+ this.$widget.on("show.bs.dropdown", async () => {+ const { categories } = (await import("./icon_list.js")).default;this.$iconCategory.empty();for (const category of categories) {- this.$iconCategory.append(- $("<option>")- .text(category.name)- .attr("value", category.id)- );+ this.$iconCategory.append($("<option>").text(category.name).attr("value", category.id));}- this.$iconSearch.val('');+ this.$iconSearch.val("");this.renderDropdown();});@@ -124,17 +117,14 @@ export default class NoteIconWidget extends NoteContextAwareWidget {this.$icon.removeClass().addClass(`${note.getIcon()} note-icon`);}- async entitiesReloadedEvent({loadResults}) {+ async entitiesReloadedEvent({ loadResults }) {if (loadResults.isNoteReloaded(this.noteId)) {this.refresh();return;}for (const attr of loadResults.getAttributeRows()) {- if (attr.type === 'label'- && ['iconClass', 'workspaceIconClass'].includes(attr.name)- && attributeService.isAffecting(attr, this.note)) {-+ if (attr.type === "label" && ["iconClass", "workspaceIconClass"].includes(attr.name) && attributeService.isAffecting(attr, this.note)) {this.refresh();break;}@@ -143,32 +133,30 @@ export default class NoteIconWidget extends NoteContextAwareWidget {async renderDropdown() {const iconToCount = await this.getIconToCountMap();- const {icons} = (await import('./icon_list.js')).default;+ const { icons } = (await import("./icon_list.js")).default;this.$iconList.empty();if (this.getIconLabels().length > 0) {this.$iconList.append(- $(`<div style="text-align: center">`)- .append(- $(`<button class="btn btn-sm">${t("note_icon.reset-default")}</button>`)- .on('click', () => this.getIconLabels()- .forEach(label => attributeService.removeAttributeById(this.noteId, label.attributeId))- )+ $(`<div style="text-align: center">`).append(+ $(`<button class="btn btn-sm">${t("note_icon.reset-default")}</button>`).on("click", () =>+ this.getIconLabels().forEach((label) => attributeService.removeAttributeById(this.noteId, label.attributeId)))+ ));}- const categoryId = parseInt(this.$iconCategory.find('option:selected').val());+ const categoryId = parseInt(this.$iconCategory.find("option:selected").val());const search = this.$iconSearch.val().trim().toLowerCase();- const filteredIcons = icons.filter(icon => {+ const filteredIcons = icons.filter((icon) => {if (categoryId && icon.category_id !== categoryId) {return false;}if (search) {- if (!icon.name.includes(search) && !icon.term?.find(t => t.includes(search))) {+ if (!icon.name.includes(search) && !icon.term?.find((t) => t.includes(search))) {return false;}}@@ -192,21 +180,20 @@ export default class NoteIconWidget extends NoteContextAwareWidget {async getIconToCountMap() {if (!this.iconToCountCache) {- this.iconToCountCache = server.get('other/icon-usage');- setTimeout(() => this.iconToCountCache = null, 20000); // invalidate cache after 20 seconds+ this.iconToCountCache = server.get("other/icon-usage");+ setTimeout(() => (this.iconToCountCache = null), 20000); // invalidate cache after 20 seconds}return (await this.iconToCountCache).iconClassToCountMap;}renderIcon(icon) {- return $('<span>')+ return $("<span>").addClass("bx " + icon.className).attr("title", icon.name);}getIconLabels() {- return this.note.getOwnedLabels()- .filter(label => ['workspaceIconClass', 'iconClass'].includes(label.name));+ return this.note.getOwnedLabels().filter((label) => ["workspaceIconClass", "iconClass"].includes(label.name));}}diff --git a/src/public/app/widgets/note_list.js b/src/public/app/widgets/note_list.jsindex 6f1fd8cf0b..c202bc5235 100644--- a/src/public/app/widgets/note_list.js+++ b/src/public/app/widgets/note_list.js@@ -26,16 +26,19 @@ export default class NoteListWidget extends NoteContextAwareWidget {doRender() {this.$widget = $(TPL);this.contentSized();- this.$content = this.$widget.find('.note-list-widget-content');+ this.$content = this.$widget.find(".note-list-widget-content");- const observer = new IntersectionObserver(entries => {- this.isIntersecting = entries[0].isIntersecting;+ const observer = new IntersectionObserver(+ (entries) => {+ this.isIntersecting = entries[0].isIntersecting;- this.checkRenderStatus();- }, {- rootMargin: '50px',- threshold: 0.1- });+ this.checkRenderStatus();+ },+ {+ rootMargin: "50px",+ threshold: 0.1+ }+ );// there seems to be a race condition on Firefox which triggers the observer only before the widget is visible// (intersection is false). https://github.com/zadam/trilium/issues/4165@@ -47,10 +50,7 @@ export default class NoteListWidget extends NoteContextAwareWidget {// console.log(`${this.noteIdRefreshed} === ${this.noteId}`, this.noteIdRefreshed === this.noteId);// console.log("this.shownNoteId !== this.noteId", this.shownNoteId !== this.noteId);- if (this.isIntersecting- && this.noteIdRefreshed === this.noteId- && this.shownNoteId !== this.noteId) {-+ if (this.isIntersecting && this.noteIdRefreshed === this.noteId && this.shownNoteId !== this.noteId) {this.shownNoteId = this.noteId;this.renderNoteList(this.note);}@@ -67,7 +67,7 @@ export default class NoteListWidget extends NoteContextAwareWidget {await super.refresh();}- async refreshNoteListEvent({noteId}) {+ async refreshNoteListEvent({ noteId }) {if (this.isNote(noteId)) {await this.renderNoteList(this.note);}@@ -78,7 +78,7 @@ export default class NoteListWidget extends NoteContextAwareWidget {* If it's evaluated before note detail, then it's clearly intersected (visible) although after note detail load* it is not intersected (visible) anymore.*/- noteDetailRefreshedEvent({ntxId}) {+ noteDetailRefreshedEvent({ ntxId }) {if (!this.isNoteContext(ntxId)) {return;}@@ -88,14 +88,14 @@ export default class NoteListWidget extends NoteContextAwareWidget {setTimeout(() => this.checkRenderStatus(), 100);}- notesReloadedEvent({noteIds}) {+ notesReloadedEvent({ noteIds }) {if (noteIds.includes(this.noteId)) {this.refresh();}}- entitiesReloadedEvent({loadResults}) {- if (loadResults.getAttributeRows().find(attr => attr.noteId === this.noteId && ['viewType', 'expanded', 'pageSize'].includes(attr.name))) {+ entitiesReloadedEvent({ loadResults }) {+ if (loadResults.getAttributeRows().find((attr) => attr.noteId === this.noteId && ["viewType", "expanded", "pageSize"].includes(attr.name))) {this.shownNoteId = null; // force renderthis.checkRenderStatus();diff --git a/src/public/app/widgets/note_map.js b/src/public/app/widgets/note_map.jsindex d5a263f418..6e91ff2ed6 100644--- a/src/public/app/widgets/note_map.js+++ b/src/public/app/widgets/note_map.js@@ -104,39 +104,38 @@ export default class NoteMapWidget extends NoteContextAwareWidget {this.$widget = $(TPL);const documentStyle = window.getComputedStyle(document.documentElement);- this.themeStyle = documentStyle.getPropertyValue('--theme-style')?.trim();+ this.themeStyle = documentStyle.getPropertyValue("--theme-style")?.trim();this.$container = this.$widget.find(".note-map-container");- this.$styleResolver = this.$widget.find('.style-resolver');+ this.$styleResolver = this.$widget.find(".style-resolver");new ResizeObserver(() => this.setDimensions()).observe(this.$container[0]);- this.$widget.find(".map-type-switcher button").on("click", async e => {+ this.$widget.find(".map-type-switcher button").on("click", async (e) => {const type = $(e.target).closest("button").attr("data-type");- await attributeService.setLabel(this.noteId, 'mapType', type);+ await attributeService.setLabel(this.noteId, "mapType", type);});// Reading the status of the Drag nodes Ui element. Changing it´s color when activated. Reading Force value of the link distance.- this.$widget.find('.fixnodes-type-switcher').on('click', async event => {+ this.$widget.find(".fixnodes-type-switcher").on("click", async (event) => {this.fixNodes = !this.fixNodes;- event.target.style.backgroundColor = this.fixNodes ? '#661822' : 'transparent';+ event.target.style.backgroundColor = this.fixNodes ? "#661822" : "transparent";});super.doRender();}setDimensions() {- if (!this.graph) { // no graph has been even rendered+ if (!this.graph) {+ // no graph has been even renderedreturn;}const $parent = this.$widget.parent();- this.graph- .height($parent.height())- .width($parent.width());+ this.graph.height($parent.height()).width($parent.width());}async refreshWithNote(note) {@@ -161,12 +160,12 @@ export default class NoteMapWidget extends NoteContextAwareWidget {this.graph = ForceGraph()(this.$container[0]).width(this.$container.width()).height(this.$container.height())- .onZoom(zoom => this.setZoomLevel(zoom.k))+ .onZoom((zoom) => this.setZoomLevel(zoom.k)).d3AlphaDecay(0.01).d3VelocityDecay(0.08)//Code to fixate nodes when dragged- .onNodeDragEnd(node => {+ .onNodeDragEnd((node) => {if (this.fixNodes) {node.fx = node.x;node.fy = node.y;@@ -176,23 +175,25 @@ export default class NoteMapWidget extends NoteContextAwareWidget {}})//check if hovered and set the hovernode variable, saving the hovered node object into it. Clear links variable everytime you hover. Without clearing links will stay highlighted- .onNodeHover(node => {+ .onNodeHover((node) => {hoverNode = node || null;highlightLinks.clear();})// set link width to immitate a highlight effekt. Checking the condition if any links are saved in the previous defined set highlightlinks- .linkWidth(link => (highlightLinks.has(link) ? 3 : 0.4))- .linkColor(link => (highlightLinks.has(link) ? 'white' : this.css.mutedTextColor))+ .linkWidth((link) => (highlightLinks.has(link) ? 3 : 0.4))+ .linkColor((link) => (highlightLinks.has(link) ? "white" : this.css.mutedTextColor)).linkDirectionalArrowLength(4).linkDirectionalArrowRelPos(0.95)// main code for highlighting hovered nodes and neighbours. here we "style" the nodes. the nodes are rendered several hundred times per second..nodeCanvasObject((node, ctx) => {- if (hoverNode == node) { //paint only hovered node- this.paintNode(node, '#661822', ctx);+ if (hoverNode == node) {+ //paint only hovered node+ this.paintNode(node, "#661822", ctx);neighbours.clear(); //clearing neighbours or the effect would be maintained after hovering is over- for (const link of data.links) { //check if node is part of a link in the canvas, if so add it´s neighbours and related links to the previous defined variables to paint the nodes+ for (const link of data.links) {+ //check if node is part of a link in the canvas, if so add it´s neighbours and related links to the previous defined variables to paint the nodesif (link.source.id == node.id || link.target.id == node.id) {neighbours.add(link.source);neighbours.add(link.target);@@ -200,8 +201,9 @@ export default class NoteMapWidget extends NoteContextAwareWidget {neighbours.delete(node);}}- } else if (neighbours.has(node) && hoverNode != null) { //paint neighbours- this.paintNode(node, '#9d6363', ctx);+ } else if (neighbours.has(node) && hoverNode != null) {+ //paint neighbours+ this.paintNode(node, "#9d6363", ctx);} else {this.paintNode(node, this.getColorForNode(node), ctx); //paint rest of nodes in canvas}@@ -214,15 +216,15 @@ export default class NoteMapWidget extends NoteContextAwareWidget {ctx.arc(node.x, node.y, this.noteIdToSizeMap[node.id], 0, 2 * Math.PI, false);ctx.fill();})- .nodeLabel(node => esc(node.name))+ .nodeLabel((node) => esc(node.name)).maxZoom(7).warmupTicks(30)- .onNodeClick(node => appContext.tabManager.getActiveContext().setNote(node.id))+ .onNodeClick((node) => appContext.tabManager.getActiveContext().setNote(node.id)).onNodeRightClick((node, e) => linkContextMenuService.openContextMenu(node.id, e));- if (this.mapType === 'link') {+ if (this.mapType === "link") {this.graph- .linkLabel(l => `${esc(l.source.name)} - <strong>${esc(l.name)}</strong> - ${esc(l.target.name)}`)+ .linkLabel((l) => `${esc(l.source.name)} - <strong>${esc(l.name)}</strong> - ${esc(l.target.name)}`).linkCanvasObject((link, ctx) => this.paintLink(link, ctx)).linkCanvasObjectMode(() => "after");}@@ -236,28 +238,28 @@ export default class NoteMapWidget extends NoteContextAwareWidget {const boundedCharge = Math.min(-3, charge);let distancevalue = 40; // default value for the link force of the nodes- this.$widget.find('.fixnodes-type-switcher input').on('change', async e => {- distancevalue = e.target.closest('input').value;- this.graph.d3Force('link').distance(distancevalue);+ this.$widget.find(".fixnodes-type-switcher input").on("change", async (e) => {+ distancevalue = e.target.closest("input").value;+ this.graph.d3Force("link").distance(distancevalue);this.renderData(data);});- this.graph.d3Force('center').strength(0.2);- this.graph.d3Force('charge').strength(boundedCharge);- this.graph.d3Force('charge').distanceMax(1000);+ this.graph.d3Force("center").strength(0.2);+ this.graph.d3Force("charge").strength(boundedCharge);+ this.graph.d3Force("charge").distanceMax(1000);this.renderData(data);}getMapRootNoteId() {- if (this.widgetMode === 'ribbon') {+ if (this.widgetMode === "ribbon") {return this.noteId;}let mapRootNoteId = this.note.getLabelValue("mapRootNoteId");- if (mapRootNoteId === 'hoisted') {+ if (mapRootNoteId === "hoisted") {mapRootNoteId = hoistedNoteService.getHoistedNoteId();} else if (!mapRootNoteId) {mapRootNoteId = appContext.tabManager.getActiveContext().parentNoteId;@@ -269,8 +271,8 @@ export default class NoteMapWidget extends NoteContextAwareWidget {getColorForNode(node) {if (node.color) {return node.color;- } else if (this.widgetMode === 'ribbon' && node.id === this.noteId) {- return 'red'; // subtree root mark as red+ } else if (this.widgetMode === "ribbon" && node.id === this.noteId) {+ return "red"; // subtree root mark as red} else {return this.generateColorFromString(node.type);}@@ -286,20 +288,21 @@ export default class NoteMapWidget extends NoteContextAwareWidget {hash = str.charCodeAt(i) + ((hash << 5) - hash);}- let color = '#';+ let color = "#";for (let i = 0; i < 3; i++) {- const value = (hash >> (i * 8)) & 0xFF;+ const value = (hash >> (i * 8)) & 0xff;- color += (`00${value.toString(16)}`).substr(-2);+ color += `00${value.toString(16)}`.substr(-2);}return color;}rgb2hex(rgb) {- return `#${rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)+ return `#${rgb+ .match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).slice(1)- .map(n => parseInt(n, 10).toString(16).padStart(2, '0'))- .join('')}`+ .map((n) => parseInt(n, 10).toString(16).padStart(2, "0"))+ .join("")}`;}setZoomLevel(level) {@@ -307,17 +310,15 @@ export default class NoteMapWidget extends NoteContextAwareWidget {}paintNode(node, color, ctx) {- const {x, y} = node;+ const { x, y } = node;const size = this.noteIdToSizeMap[node.id];ctx.fillStyle = color;ctx.beginPath();- ctx.arc(x, y, size*0.8, 0, 2 * Math.PI, false);+ ctx.arc(x, y, size * 0.8, 0, 2 * Math.PI, false);ctx.fill();- const toRender = this.zoomLevel > 2- || (this.zoomLevel > 1 && size > 6)- || (this.zoomLevel > 0.3 && size > 10);+ const toRender = this.zoomLevel > 2 || (this.zoomLevel > 1 && size > 6) || (this.zoomLevel > 0.3 && size > 10);if (!toRender) {return;@@ -325,8 +326,8 @@ export default class NoteMapWidget extends NoteContextAwareWidget {ctx.fillStyle = this.css.textColor;ctx.font = `${size}px ${this.css.fontFamily}`;- ctx.textAlign = 'center';- ctx.textBaseline = 'middle';+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";let title = node.name;@@ -343,11 +344,11 @@ export default class NoteMapWidget extends NoteContextAwareWidget {}ctx.font = `3px ${this.css.fontFamily}`;- ctx.textAlign = 'center';- ctx.textBaseline = 'middle';+ ctx.textAlign = "center";+ ctx.textBaseline = "middle";ctx.fillStyle = this.css.mutedTextColor;- const {source, target} = link;+ const { source, target } = link;const x = (source.x + target.x) / 2;const y = (source.y + target.y) / 2;@@ -387,7 +388,7 @@ export default class NoteMapWidget extends NoteContextAwareWidget {return {nodes: this.nodes,- links: links.map(link => ({+ links: links.map((link) => ({id: `${link.sourceNoteId}-${link.targetNoteId}`,source: link.sourceNoteId,target: link.targetNoteId,@@ -412,7 +413,7 @@ export default class NoteMapWidget extends NoteContextAwareWidget {sourceNoteId: link.sourceNoteId,targetNoteId: link.targetNoteId,names: [link.name]- }+ };}}@@ -422,8 +423,8 @@ export default class NoteMapWidget extends NoteContextAwareWidget {calculateNodeSizes(resp) {this.noteIdToSizeMap = {};- if (this.mapType === 'tree') {- const {noteIdToDescendantCountMap} = resp;+ if (this.mapType === "tree") {+ const { noteIdToDescendantCountMap } = resp;for (const noteId in noteIdToDescendantCountMap) {this.noteIdToSizeMap[noteId] = 4;@@ -434,8 +435,7 @@ export default class NoteMapWidget extends NoteContextAwareWidget {this.noteIdToSizeMap[noteId] += 1 + Math.round(Math.log(count) / Math.log(1.5));}}- }- else if (this.mapType === 'link') {+ } else if (this.mapType === "link") {const noteIdToLinkCount = {};for (const link of resp.links) {@@ -455,20 +455,19 @@ export default class NoteMapWidget extends NoteContextAwareWidget {renderData(data) {this.graph.graphData(data);- if (this.widgetMode === 'ribbon' && this.note?.type !== 'search') {+ if (this.widgetMode === "ribbon" && this.note?.type !== "search") {setTimeout(() => {this.setDimensions();const subGraphNoteIds = this.getSubGraphConnectedToCurrentNote(data);- this.graph.zoomToFit(400, 50, node => subGraphNoteIds.has(node.id));+ this.graph.zoomToFit(400, 50, (node) => subGraphNoteIds.has(node.id));if (subGraphNoteIds.size < 30) {this.graph.d3VelocityDecay(0.4);}}, 1000);- }- else {+ } else {if (data.nodes.length > 1) {setTimeout(() => {this.setDimensions();@@ -476,7 +475,7 @@ export default class NoteMapWidget extends NoteContextAwareWidget {const noteIdsWithLinks = this.getNoteIdsWithLinks(data);if (noteIdsWithLinks.size > 0) {- this.graph.zoomToFit(400, 30, node => noteIdsWithLinks.has(node.id));+ this.graph.zoomToFit(400, 30, (node) => noteIdsWithLinks.has(node.id));}if (noteIdsWithLinks.size < 30) {@@ -537,16 +536,11 @@ export default class NoteMapWidget extends NoteContextAwareWidget {}cleanup() {- this.$container.html('');+ this.$container.html("");}- entitiesReloadedEvent({loadResults}) {- if (loadResults.getAttributeRows(this.componentId).find(- attr =>- attr.type === 'label'- && ['mapType', 'mapRootNoteId'].includes(attr.name)- && attributeService.isAffecting(attr, this.note)- )) {+ entitiesReloadedEvent({ loadResults }) {+ if (loadResults.getAttributeRows(this.componentId).find((attr) => attr.type === "label" && ["mapType", "mapRootNoteId"].includes(attr.name) && attributeService.isAffecting(attr, this.note))) {this.refresh();}}diff --git a/src/public/app/widgets/note_title.js b/src/public/app/widgets/note_title.jsindex d18692228f..570b38b56c 100644--- a/src/public/app/widgets/note_title.js+++ b/src/public/app/widgets/note_title.js@@ -29,7 +29,7 @@ const TPL = `}</style>- <input autocomplete="off" value="" placeholder="${t('note_title.placeholder')}" class="note-title" tabindex="100">+ <input autocomplete="off" value="" placeholder="${t("note_title.placeholder")}" class="note-title" tabindex="100"></div>`;export default class NoteTitleWidget extends NoteContextAwareWidget {@@ -41,7 +41,7 @@ export default class NoteTitleWidget extends NoteContextAwareWidget {protectedSessionHolder.touchProtectedSessionIfNecessary(this.note);- await server.put(`notes/${this.noteId}/title`, {title}, this.componentId);+ await server.put(`notes/${this.noteId}/title`, { title }, this.componentId);});this.deleteNoteOnEscape = false;@@ -53,35 +53,29 @@ export default class NoteTitleWidget extends NoteContextAwareWidget {this.$widget = $(TPL);this.$noteTitle = this.$widget.find(".note-title");- this.$noteTitle.on('input', () => this.spacedUpdate.scheduleUpdate());+ this.$noteTitle.on("input", () => this.spacedUpdate.scheduleUpdate());- this.$noteTitle.on('blur', () => {+ this.$noteTitle.on("blur", () => {this.spacedUpdate.updateNowIfNecessary();this.deleteNoteOnEscape = false;});- shortcutService.bindElShortcut(this.$noteTitle, 'esc', () => {+ shortcutService.bindElShortcut(this.$noteTitle, "esc", () => {if (this.deleteNoteOnEscape && this.noteContext.isActive()) {branchService.deleteNotes(Object.values(this.noteContext.note.parentToBranch));}});- shortcutService.bindElShortcut(this.$noteTitle, 'return', () => {- this.triggerCommand('focusOnDetail', {ntxId: this.noteContext.ntxId});+ shortcutService.bindElShortcut(this.$noteTitle, "return", () => {+ this.triggerCommand("focusOnDetail", { ntxId: this.noteContext.ntxId });});}async refreshWithNote(note) {- const isReadOnly = (note.isProtected && !protectedSessionHolder.isProtectedSessionAvailable())- || utils.isLaunchBarConfig(note.noteId)- || this.noteContext.viewScope.viewMode !== 'default';-- this.$noteTitle.val(- isReadOnly- ? await this.noteContext.getNavigationTitle()- : note.title- );+ const isReadOnly = (note.isProtected && !protectedSessionHolder.isProtectedSessionAvailable()) || utils.isLaunchBarConfig(note.noteId) || this.noteContext.viewScope.viewMode !== "default";++ this.$noteTitle.val(isReadOnly ? await this.noteContext.getNavigationTitle() : note.title);this.$noteTitle.prop("readonly", isReadOnly);this.setProtectedStatus(note);@@ -92,13 +86,13 @@ export default class NoteTitleWidget extends NoteContextAwareWidget {this.$noteTitle.toggleClass("protected", !!note.isProtected);}- async beforeNoteSwitchEvent({noteContext}) {+ async beforeNoteSwitchEvent({ noteContext }) {if (this.isNoteContext(noteContext.ntxId)) {await this.spacedUpdate.updateNowIfNecessary();}}- async beforeNoteContextRemoveEvent({ntxIds}) {+ async beforeNoteContextRemoveEvent({ ntxIds }) {if (this.isNoteContext(ntxIds)) {await this.spacedUpdate.updateNowIfNecessary();}@@ -106,21 +100,19 @@ export default class NoteTitleWidget extends NoteContextAwareWidget {focusOnTitleEvent() {if (this.noteContext && this.noteContext.isActive()) {- this.$noteTitle.trigger('focus');+ this.$noteTitle.trigger("focus");}}- focusAndSelectTitleEvent({isNewNote} = {isNewNote: false}) {+ focusAndSelectTitleEvent({ isNewNote } = { isNewNote: false }) {if (this.noteContext && this.noteContext.isActive()) {- this.$noteTitle- .trigger('focus')- .trigger('select');+ this.$noteTitle.trigger("focus").trigger("select");this.deleteNoteOnEscape = isNewNote;}}- entitiesReloadedEvent({loadResults}) {+ entitiesReloadedEvent({ loadResults }) {if (loadResults.isNoteReloaded(this.noteId)) {// not updating the title specifically since the synced title might be older than what the user is currently typingthis.setProtectedStatus(this.note);diff --git a/src/public/app/widgets/note_tree.js b/src/public/app/widgets/note_tree.jsindex c0bb297f8e..04bf8a0ebe 100644--- a/src/public/app/widgets/note_tree.js+++ b/src/public/app/widgets/note_tree.js@@ -141,7 +141,7 @@ const TPL = `const MAX_SEARCH_RESULTS_IN_TREE = 100;// this has to be hanged on the actual elements to effectively intercept and stop click event-const cancelClickPropagation = e => e.stopPropagation();+const cancelClickPropagation = (e) => e.stopPropagation();export default class NoteTreeWidget extends NoteContextAwareWidget {constructor() {@@ -152,12 +152,12 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {doRender() {this.$widget = $(TPL);- this.$tree = this.$widget.find('.tree');+ this.$tree = this.$widget.find(".tree");this.$treeActions = this.$widget.find(".tree-actions");this.$tree.on("mousedown", ".unhoist-button", () => hoistedNoteService.unhoist());- this.$tree.on("mousedown", ".refresh-search-button", e => this.refreshSearch(e));- this.$tree.on("mousedown", ".add-note-button", e => {+ this.$tree.on("mousedown", ".refresh-search-button", (e) => this.refreshSearch(e));+ this.$tree.on("mousedown", ".add-note-button", (e) => {const node = $.ui.fancytree.getNode(e);const parentNotePath = treeService.getNotePath(node);@@ -166,14 +166,14 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {});});- this.$tree.on("mousedown", ".enter-workspace-button", e => {+ this.$tree.on("mousedown", ".enter-workspace-button", (e) => {const node = $.ui.fancytree.getNode(e);- this.triggerCommand('hoistNote', {noteId: node.data.noteId});+ this.triggerCommand("hoistNote", { noteId: node.data.noteId });});// fancytree doesn't support middle click, so this is a way to support it- this.$tree.on('mousedown', '.fancytree-title', e => {+ this.$tree.on("mousedown", ".fancytree-title", (e) => {if (e.which === 2) {const node = $.ui.fancytree.getNode(e);@@ -188,12 +188,12 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}});- this.$treeSettingsPopup = this.$widget.find('.tree-settings-popup');- this.$hideArchivedNotesCheckbox = this.$treeSettingsPopup.find('.hide-archived-notes');- this.$autoCollapseNoteTree = this.$treeSettingsPopup.find('.auto-collapse-note-tree');+ this.$treeSettingsPopup = this.$widget.find(".tree-settings-popup");+ this.$hideArchivedNotesCheckbox = this.$treeSettingsPopup.find(".hide-archived-notes");+ this.$autoCollapseNoteTree = this.$treeSettingsPopup.find(".auto-collapse-note-tree");- this.$treeSettingsButton = this.$widget.find('.tree-settings-button');- this.$treeSettingsButton.on("click", e => {+ this.$treeSettingsButton = this.$widget.find(".tree-settings-button");+ this.$treeSettingsButton.on("click", (e) => {if (this.$treeSettingsPopup.is(":visible")) {this.$treeSettingsPopup.hide();return;@@ -202,26 +202,27 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {this.$hideArchivedNotesCheckbox.prop("checked", this.hideArchivedNotes);this.$autoCollapseNoteTree.prop("checked", this.autoCollapseNoteTree);- const top = this.$treeActions[0].offsetTop - (this.$treeSettingsPopup.outerHeight());- const left = Math.max(- 0,- this.$treeActions[0].offsetLeft - this.$treeSettingsPopup.outerWidth() + this.$treeActions.outerWidth()- );+ const top = this.$treeActions[0].offsetTop - this.$treeSettingsPopup.outerHeight();+ const left = Math.max(0, this.$treeActions[0].offsetLeft - this.$treeSettingsPopup.outerWidth() + this.$treeActions.outerWidth());- this.$treeSettingsPopup.css({- top,- left- }).show();+ this.$treeSettingsPopup+ .css({+ top,+ left+ })+ .show();return false;});- this.$treeSettingsPopup.on("click", e => {e.stopPropagation();});+ this.$treeSettingsPopup.on("click", (e) => {+ e.stopPropagation();+ });- $(document).on('click', () => this.$treeSettingsPopup.hide());+ $(document).on("click", () => this.$treeSettingsPopup.hide());- this.$saveTreeSettingsButton = this.$treeSettingsPopup.find('.save-tree-settings-button');- this.$saveTreeSettingsButton.on('click', async () => {+ this.$saveTreeSettingsButton = this.$treeSettingsPopup.find(".save-tree-settings-button");+ this.$saveTreeSettingsButton.on("click", async () => {await this.setHideArchivedNotes(this.$hideArchivedNotesCheckbox.prop("checked"));await this.setAutoCollapseNoteTree(this.$autoCollapseNoteTree.prop("checked"));@@ -251,16 +252,11 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const subDistanceFromTop = subOffset.top + $sub.outerHeight(true);const subDistanceFromLeft = subOffset.left + $sub.outerWidth(true);- return conDistanceFromTop > subDistanceFromTop- && conOffset.top < subOffset.top- && conDistanceFromLeft > subDistanceFromLeft- && conOffset.left < subOffset.left;+ return conDistanceFromTop > subDistanceFromTop && conOffset.top < subOffset.top && conDistanceFromLeft > subDistanceFromLeft && conOffset.left < subOffset.left;};- this.$tree.on("mouseenter", "span.fancytree-title", e => {- e.currentTarget.title = isEnclosing(this.$tree, $(e.currentTarget))- ? ""- : e.currentTarget.innerText;+ this.$tree.on("mouseenter", "span.fancytree-title", (e) => {+ e.currentTarget.title = isEnclosing(this.$tree, $(e.currentTarget)) ? "" : e.currentTarget.innerText;});}@@ -300,14 +296,13 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const targetType = data.targetType;const node = data.node;- if (node.isSelected() && targetType === 'icon') {- this.triggerCommand('openBulkActionsDialog', {+ if (node.isSelected() && targetType === "icon") {+ this.triggerCommand("openBulkActionsDialog", {selectedOrActiveNoteIds: this.getSelectedOrActiveNoteIds(node)});return false;- }- else if (targetType === 'title' || targetType === 'icon') {+ } else if (targetType === "title" || targetType === "icon") {if (event.shiftKey) {const activeNode = this.getActiveNode();@@ -333,42 +328,38 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}node.setFocus(true);- }- else if ((!utils.isMac() && event.ctrlKey) || (utils.isMac() && event.metaKey)) {+ } else if ((!utils.isMac() && event.ctrlKey) || (utils.isMac() && event.metaKey)) {const notePath = treeService.getNotePath(node);appContext.tabManager.openTabWithNoteWithHoisting(notePath);- }- else if (event.altKey) {+ } else if (event.altKey) {node.setSelected(!node.isSelected());node.setFocus(true);- }- else if (data.node.isActive()) {+ } else if (data.node.isActive()) {// this is important for single column mobile view, otherwise it's not possible to see again previously displayed notethis.tree.reactivate(true);- }- else {+ } else {node.setActive();}return false;}},- beforeActivate: (event, {node}) => {+ beforeActivate: (event, { node }) => {// hidden subtree is hidden hackily - we want it to be present in the tree so that we can switch to it// without reloading the whole tree, but we want it to be hidden when hoisted to root. FancyTree allows// filtering the display only by ascendant - i.e. if the root is visible, all the descendants are as well.// We solve it by hiding the hidden subtree via CSS (class "hidden-node-is-hidden"),// but then we need to prevent activating it, e.g. by keyboard- if (hoistedNoteService.getHoistedNoteId() === '_hidden') {+ if (hoistedNoteService.getHoistedNoteId() === "_hidden") {// if we're hoisted in hidden subtree, we want to avoid crossing to "visible" tree,// which could happen via UP key from hidden root- return node.data.noteId !== 'root';+ return node.data.noteId !== "root";}// we're not hoisted to hidden subtree, the only way to cross is via DOWN key to the hidden root- return node.data.noteId !== '_hidden';+ return node.data.noteId !== "_hidden";},activate: async (event, data) => {// click event won't propagate so let's close context menu manually@@ -392,25 +383,21 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {autoExpandMS: 600,preventLazyParents: false,dragStart: (node, data) => {- if (node.data.noteId === "root"- || utils.isLaunchBarConfig(node.data.noteId)- || node.data.noteId.startsWith("_options")) {+ if (node.data.noteId === "root" || utils.isLaunchBarConfig(node.data.noteId) || node.data.noteId.startsWith("_options")) {return false;}- const notes = this.getSelectedOrActiveNodes(node).map(node => ({+ const notes = this.getSelectedOrActiveNodes(node).map((node) => ({noteId: node.data.noteId,branchId: node.data.branchId,title: node.title}));if (notes.length === 1) {- linkService.createLink(notes[0].noteId, {referenceLink: true, autoConvertToImage: true})- .then($link => data.dataTransfer.setData("text/html", $link[0].outerHTML));- }- else {- Promise.all(notes.map(note => linkService.createLink(note.noteId, {referenceLink: true, autoConvertToImage: true}))).then(links => {- const $list = $("<ul>").append(...links.map($link => $("<li>").append($link)));+ linkService.createLink(notes[0].noteId, { referenceLink: true, autoConvertToImage: true }).then(($link) => data.dataTransfer.setData("text/html", $link[0].outerHTML));+ } else {+ Promise.all(notes.map((note) => linkService.createLink(note.noteId, { referenceLink: true, autoConvertToImage: true }))).then((links) => {+ const $list = $("<ul>").append(...links.map(($link) => $("<li>").append($link)));data.dataTransfer.setData("text/html", $list[0].outerHTML);});@@ -420,25 +407,25 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {return true; // allow dragging to start},dragEnter: (node, data) => {- if (node.data.noteType === 'search') {+ if (node.data.noteType === "search") {return false;- } else if (node.data.noteId === '_lbRoot') {+ } else if (node.data.noteId === "_lbRoot") {return false;- } else if (node.data.noteId.startsWith('_options')) {+ } else if (node.data.noteId.startsWith("_options")) {return false;- } else if (node.data.noteType === 'launcher') {- return ['before', 'after'];- } else if (['_lbAvailableLaunchers', '_lbVisibleLaunchers'].includes(node.data.noteId)) {- return ['over'];+ } else if (node.data.noteType === "launcher") {+ return ["before", "after"];+ } else if (["_lbAvailableLaunchers", "_lbVisibleLaunchers"].includes(node.data.noteId)) {+ return ["over"];} else {return true;}},dragDrop: async (node, data) => {- if ((data.hitMode === 'over' && node.data.noteType === 'search') ||- (['after', 'before'].includes(data.hitMode)- && (node.data.noteId === hoistedNoteService.getHoistedNoteId() || node.getParent().data.noteType === 'search'))) {-+ if (+ (data.hitMode === "over" && node.data.noteType === "search") ||+ (["after", "before"].includes(data.hitMode) && (node.data.noteId === hoistedNoteService.getHoistedNoteId() || node.getParent().data.noteType === "search"))+ ) {await dialogService.info("Dropping notes into this location is not allowed.");return;@@ -449,9 +436,9 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {const files = [...dataTransfer.files]; // chrome has issue that dataTransfer.files empties after async operation- const importService = await import('../services/import.js');+ const importService = await import("../services/import.js");- importService.uploadFiles('notes', node.data.noteId, files, {+ importService.uploadFiles("notes", node.data.noteId, files, {safeImport: true,shrinkImages: true,textImportedAsText: true,@@ -459,15 +446,13 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {explodeArchives: true,replaceUnderscoresWithSpaces: true});- }- else {+ } else {const jsonStr = dataTransfer.getData("text");let notes = null;try {notes = JSON.parse(jsonStr);- }- catch (e) {+ } catch (e) {logError(`Cannot parse JSON '${jsonStr}' into notes for drop`);return;}@@ -475,7 +460,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {// This function MUST be defined to enable dropping of items on the tree.// data.hitMode is 'before', 'after', or 'over'.- const selectedBranchIds = notes.map(note => note.branchId);+ const selectedBranchIds = notes.map((note) => note.branchId);if (data.hitMode === "before") {branchService.moveBeforeBranch(selectedBranchIds, node.data.branchId);@@ -490,9 +475,9 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}},lazyLoad: (event, data) => {- const {noteId, noteType} = data.node.data;+ const { noteId, noteType } = data.node.data;- if (noteType === 'search') {+ if (noteType === "search") {const notePath = treeService.getNotePath(data.node.getParent());// this is a search cycle (search note is a descendant of its own search result)@@ -501,24 +486,26 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {return;}- data.result = froca.loadSearchNote(noteId).then(() => {- const note = froca.getNoteFromCache(noteId);+ data.result = froca+ .loadSearchNote(noteId)+ .then(() => {+ const note = froca.getNoteFromCache(noteId);- let childNoteIds = note.getChildNoteIds();+ let childNoteIds = note.getChildNoteIds();- if (note.type === 'search' && childNoteIds.length > MAX_SEARCH_RESULTS_IN_TREE) {- childNoteIds = childNoteIds.slice(0, MAX_SEARCH_RESULTS_IN_TREE);- }+ if (note.type === "search" && childNoteIds.length > MAX_SEARCH_RESULTS_IN_TREE) {+ childNoteIds = childNoteIds.slice(0, MAX_SEARCH_RESULTS_IN_TREE);+ }- return froca.getNotes(childNoteIds);- }).then(() => {- const note = froca.getNoteFromCache(noteId);+ return froca.getNotes(childNoteIds);+ })+ .then(() => {+ const note = froca.getNoteFromCache(noteId);- return this.prepareChildren(note);- });- }- else {- data.result = froca.loadSubTree(noteId).then(note => this.prepareChildren(note));+ return this.prepareChildren(note);+ });+ } else {+ data.result = froca.loadSubTree(noteId).then((note) => this.prepareChildren(note));}},clones: {@@ -543,34 +530,39 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const $span = $(node.span);- $span.find('.tree-item-button').remove();+ $span.find(".tree-item-button").remove();- const isHoistedNote = activeNoteContext && activeNoteContext.hoistedNoteId === note.noteId && note.noteId !== 'root';+ const isHoistedNote = activeNoteContext && activeNoteContext.hoistedNoteId === note.noteId && note.noteId !== "root";- if (note.hasLabel('workspace') && !isHoistedNote) {- const $enterWorkspaceButton = $(`<span class="tree-item-button enter-workspace-button bx bx-door-open" title="${t("note_tree.hoist-this-note-workspace")}"></span>`)- .on("click", cancelClickPropagation);+ if (note.hasLabel("workspace") && !isHoistedNote) {+ const $enterWorkspaceButton = $(`<span class="tree-item-button enter-workspace-button bx bx-door-open" title="${t("note_tree.hoist-this-note-workspace")}"></span>`).on(+ "click",+ cancelClickPropagation+ );$span.append($enterWorkspaceButton);}- if (note.type === 'search') {- const $refreshSearchButton = $(`<span class="tree-item-button refresh-search-button bx bx-refresh" title="${t("note_tree.refresh-saved-search-results")}"></span>`)- .on("click", cancelClickPropagation);+ if (note.type === "search") {+ const $refreshSearchButton = $(`<span class="tree-item-button refresh-search-button bx bx-refresh" title="${t("note_tree.refresh-saved-search-results")}"></span>`).on(+ "click",+ cancelClickPropagation+ );$span.append($refreshSearchButton);}- if (!['search', 'launcher'].includes(note.type) && !note.isOptions() && !note.isLaunchBarConfig()) {- const $createChildNoteButton = $(`<span class="tree-item-button add-note-button bx bx-plus" title="${t("note_tree.create-child-note")}"></span>`)- .on("click", cancelClickPropagation);+ if (!["search", "launcher"].includes(note.type) && !note.isOptions() && !note.isLaunchBarConfig()) {+ const $createChildNoteButton = $(`<span class="tree-item-button add-note-button bx bx-plus" title="${t("note_tree.create-child-note")}"></span>`).on(+ "click",+ cancelClickPropagation+ );$span.append($createChildNoteButton);}if (isHoistedNote) {- const $unhoistButton = $(`<span class="tree-item-button unhoist-button bx bx-door-open" title="${t("note_tree.unhoist")}"></span>`)- .on("click", cancelClickPropagation);+ const $unhoistButton = $(`<span class="tree-item-button unhoist-button bx bx-door-open" title="${t("note_tree.unhoist")}"></span>`).on("click", cancelClickPropagation);$span.append($unhoistButton);}@@ -585,11 +577,8 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}});},- select: (event, {node}) => {- if (hoistedNoteService.getHoistedNoteId() === 'root'- && node.data.noteId === '_hidden'- && node.isSelected()) {-+ select: (event, { node }) => {+ if (hoistedNoteService.getHoistedNoteId() === "root" && node.data.noteId === "_hidden" && node.isSelected()) {// hidden is hackily hidden from the tree via CSS when root is hoisted// make sure it's not selected by mistake, it could be e.g. deleted by mistake otherwisenode.setSelected(false);@@ -597,8 +586,9 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {return;}- $(node.span).find(".fancytree-custom-icon").attr("title",- node.isSelected() ? "Apply bulk actions on selected notes" : "");+ $(node.span)+ .find(".fancytree-custom-icon")+ .attr("title", node.isSelected() ? "Apply bulk actions on selected notes" : "");}});@@ -611,7 +601,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {touchStart = new Date().getTime();showTimeout = setTimeout(() => {this.showContextMenu(e);- }, 300)+ }, 300);});this.$tree.on("touchmove", ".fancytree-node", (e) => {@@ -622,16 +612,16 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {clearTimeout(showTimeout);});} else {- this.$tree.on('contextmenu', '.fancytree-node', e => {+ this.$tree.on("contextmenu", ".fancytree-node", (e) => {this.showContextMenu(e);return false; // blocks default browser right click menu});- this.getHotKeys().then(hotKeys => {+ this.getHotKeys().then((hotKeys) => {for (const key in hotKeys) {const handler = hotKeys[key];- $(this.tree.$container).on('keydown', null, key, evt => {+ $(this.tree.$container).on("keydown", null, key, (evt) => {const node = this.tree.getActiveNode();return handler(node, evt);// return false from the handler will stop default handling.@@ -650,12 +640,12 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const note = froca.getNoteFromCache(node.data.noteId);if (note.isLaunchBarConfig()) {- import("../menus/launcher_context_menu.js").then(({default: LauncherContextMenu}) => {+ import("../menus/launcher_context_menu.js").then(({ default: LauncherContextMenu }) => {const launcherContextMenu = new LauncherContextMenu(this, node);launcherContextMenu.show(e);});} else {- import("../menus/tree_context_menu.js").then(({default: TreeContextMenu}) => {+ import("../menus/tree_context_menu.js").then(({ default: TreeContextMenu }) => {const treeContextMenu = new TreeContextMenu(this, node);treeContextMenu.show(e);});@@ -663,7 +653,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}prepareRootNode() {- return this.prepareNode(froca.getBranch('none_root'));+ return this.prepareNode(froca.getBranch("none_root"));}/**@@ -678,7 +668,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {let childBranches = parentNote.getFilteredChildBranches();- if (parentNote.type === 'search' && childBranches.length > MAX_SEARCH_RESULTS_IN_TREE) {+ if (parentNote.type === "search" && childBranches.length > MAX_SEARCH_RESULTS_IN_TREE) {childBranches = childBranches.slice(0, MAX_SEARCH_RESULTS_IN_TREE);}@@ -686,7 +676,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {if (hideArchivedNotes) {const note = branch.getNoteFromCache();- if (note.hasLabel('archived')) {+ if (note.hasLabel("archived")) {continue;}}@@ -712,7 +702,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {return;}- const title = `${branch.prefix ? (`${branch.prefix} - `) : ""}${note.title}`;+ const title = `${branch.prefix ? `${branch.prefix} - ` : ""}${note.title}`;node.data.isProtected = note.isProtected;node.data.noteType = note.type;@@ -722,7 +712,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {node.title = utils.escapeHtml(title);if (node.isExpanded() !== branch.isExpanded) {- await node.setExpanded(branch.isExpanded, {noEvents: true, noAnimation: true});+ await node.setExpanded(branch.isExpanded, { noEvents: true, noAnimation: true });}node.renderTitle();@@ -740,7 +730,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {return null;}- const title = `${branch.prefix ? (`${branch.prefix} - `) : ""}${note.title}`;+ const title = `${branch.prefix ? `${branch.prefix} - ` : ""}${note.title}`;const isFolder = note.isFolder();@@ -756,7 +746,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {refKey: note.noteId,lazy: true,folder: isFolder,- expanded: branch.isExpanded && note.type !== 'search',+ expanded: branch.isExpanded && note.type !== "search",key: utils.randomString(12) // this should prevent some "duplicate key" errors};@@ -781,12 +771,11 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}if (note.getParentNoteIds().length > 1) {- const realClones = note.getParentNoteIds()- .map(noteId => froca.notes[noteId])- .filter(note => !!note)- .filter(note =>- !['_share', '_lbBookmarks'].includes(note.noteId)- && note.type !== 'search');+ const realClones = note+ .getParentNoteIds()+ .map((noteId) => froca.notes[noteId])+ .filter((note) => !!note)+ .filter((note) => !["_share", "_lbBookmarks"].includes(note.noteId) && note.type !== "search");if (realClones.length > 1) {extraClasses.push("multiple-parents");@@ -801,11 +790,12 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {extraClasses.push(utils.getNoteTypeClass(note.type));- if (note.mime) { // some notes should not have mime type (e.g. render)+ if (note.mime) {+ // some notes should not have mime type (e.g. render)extraClasses.push(utils.getMimeTypeClass(note.mime));}- if (note.hasLabel('archived')) {+ if (note.hasLabel("archived")) {extraClasses.push("archived");}@@ -828,7 +818,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const nodes = this.getSelectedNodes(true);// the node you start dragging should be included even if not selected- if (node && !nodes.find(n => n.key === node.key)) {+ if (node && !nodes.find((n) => n.key === node.key)) {nodes.push(node);}@@ -838,8 +828,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {// hidden subtree is hackily hidden via CSS when hoisted to root// make sure it's never selected for e.g. deletion in such a case- return nodes.filter(node => hoistedNoteService.getHoistedNoteId() !== 'root'- || node.data.noteId !== '_hidden');+ return nodes.filter((node) => hoistedNoteService.getHoistedNoteId() !== "root" || node.data.noteId !== "_hidden");}async setExpandedStatusForSubtree(node, isExpanded) {@@ -849,16 +838,16 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {node = this.getNodesByNoteId(hoistedNoteId)[0];}- const {branchIds} = await server.put(`branches/${node.data.branchId}/expanded-subtree/${isExpanded ? 1 : 0}`);+ const { branchIds } = await server.put(`branches/${node.data.branchId}/expanded-subtree/${isExpanded ? 1 : 0}`);- froca.getBranches(branchIds, true)- .forEach(branch => branch.isExpanded = !!isExpanded);+ froca.getBranches(branchIds, true).forEach((branch) => (branch.isExpanded = !!isExpanded));await this.batchUpdate(async () => {await node.load(true);- if (node.data.noteId !== hoistedNoteService.getHoistedNoteId()) { // hoisted note should always be expanded- await node.setExpanded(isExpanded, {noEvents: true, noAnimation: true});+ if (node.data.noteId !== hoistedNoteService.getHoistedNoteId()) {+ // hoisted note should always be expanded+ await node.setExpanded(isExpanded, { noEvents: true, noAnimation: true });}});@@ -875,7 +864,9 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {await this.setExpandedStatusForSubtree(node, false);}- collapseTreeEvent() {this.collapseTree();}+ collapseTreeEvent() {+ this.collapseTree();+ }/*** @returns {FancytreeNode|null}@@ -909,8 +900,8 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const node = await this.expandToNote(activeContext.notePath);if (node) {- await node.makeVisible({scrollIntoView: true});- node.setActive(true, {noEvents: true, noFocus: false});+ await node.makeVisible({ scrollIntoView: true });+ node.setActive(true, { noEvents: true, noFocus: false });}}}@@ -924,7 +915,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {async getNodeFromPath(notePath, expand = false, logErrors = true) {utils.assertArguments(notePath);/** @let {FancytreeNode} */- let parentNode = this.getNodesByNoteId('root')[0];+ let parentNode = this.getNodesByNoteId("root")[0];let resolvedNotePathSegments = await treeService.resolveNotePathToSegments(notePath, this.hoistedNoteId, logErrors);@@ -947,7 +938,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {if (expand) {if (!parentNode.isExpanded()) {- await parentNode.setExpanded(true, {noAnimation: true});+ await parentNode.setExpanded(true, { noAnimation: true });}// although the previous line should set the expanded status, it seems to happen asynchronously,@@ -960,7 +951,8 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {let foundChildNode = this.findChildNode(parentNode, childNoteId);- if (!foundChildNode) { // note might be recently created, so we'll force reload and try again+ if (!foundChildNode) {+ // note might be recently created, so we'll force reload and try againawait parentNode.load(true);foundChildNode = this.findChildNode(parentNode, childNoteId);@@ -973,8 +965,10 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const childNote = await froca.getNote(childNoteId);- if (!childNote || childNote.type !== 'image') {- ws.logError(`Can't find node for child node of noteId=${childNoteId} for parent of noteId=${parentNode.data.noteId} and hoistedNoteId=${hoistedNoteService.getHoistedNoteId()}, requested path is ${notePath}`);+ if (!childNote || childNote.type !== "image") {+ ws.logError(+ `Can't find node for child node of noteId=${childNoteId} for parent of noteId=${parentNode.data.noteId} and hoistedNoteId=${hoistedNoteService.getHoistedNoteId()}, requested path is ${notePath}`+ );}}@@ -991,7 +985,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {/** @returns {FancytreeNode} */findChildNode(parentNode, childNoteId) {- return parentNode.getChildren().find(childNode => childNode.data.noteId === childNoteId);+ return parentNode.getChildren().find((childNode) => childNode.data.noteId === childNoteId);}/** @returns {FancytreeNode} */@@ -1003,7 +997,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {getNodesByBranch(branch) {utils.assertArguments(branch);- return this.getNodesByNoteId(branch.noteId).filter(node => node.data.branchId === branch.branchId);+ return this.getNodesByNoteId(branch.noteId).filter((node) => node.data.branchId === branch.branchId);}/** @returns {FancytreeNode[]} */@@ -1026,9 +1020,10 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const oldActiveNode = this.getActiveNode();- const newActiveNode = this.noteContext?.notePath- && (!treeService.isNotePathInHiddenSubtree(this.noteContext.notePath) || await hoistedNoteService.isHoistedInHiddenSubtree())- && await this.getNodeFromPath(this.noteContext.notePath);+ const newActiveNode =+ this.noteContext?.notePath &&+ (!treeService.isNotePathInHiddenSubtree(this.noteContext.notePath) || (await hoistedNoteService.isHoistedInHiddenSubtree())) &&+ (await this.getNodeFromPath(this.noteContext.notePath));if (newActiveNode !== oldActiveNode) {let oldActiveNodeFocused = false;@@ -1045,8 +1040,8 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {await this.expandToNote(this.noteContext.notePath);}- newActiveNode.setActive(true, {noEvents: true, noFocus: !oldActiveNodeFocused});- newActiveNode.makeVisible({scrollIntoView: true});+ newActiveNode.setActive(true, { noEvents: true, noFocus: !oldActiveNodeFocused });+ newActiveNode.makeVisible({ scrollIntoView: true });}}@@ -1057,7 +1052,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const activeNode = $.ui.fancytree.getNode(e);activeNode.load(true);- activeNode.setExpanded(true, {noAnimation: true});+ activeNode.setExpanded(true, { noAnimation: true });toastService.showMessage(t("note_tree.saved-search-note-refreshed"));}@@ -1068,8 +1063,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {this.tree.enableUpdate(false);await cb();- }- finally {+ } finally {this.tree.enableUpdate(true);}}@@ -1091,14 +1085,15 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {*/const noteIdsToKeepExpanded = new Set(- appContext.tabManager.getNoteContexts()- .map(nc => nc.notePathArray)+ appContext.tabManager+ .getNoteContexts()+ .map((nc) => nc.notePathArray).flat());let noneCollapsedYet = true;- this.tree.getRootNode().visit(node => {+ this.tree.getRootNode().visit((node) => {if (node.isExpanded() && !noteIdsToKeepExpanded.has(node.data.noteId)) {node.setExpanded(false);@@ -1113,7 +1108,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}, 600 * 1000);}- async entitiesReloadedEvent({loadResults}) {+ async entitiesReloadedEvent({ loadResults }) {this.activityDetected();if (loadResults.isEmptyForTree()) {@@ -1149,15 +1144,15 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {#processAttributeRows(attributeRows, refreshCtx) {for (const attrRow of attributeRows) {- const dirtyingLabels = ['iconClass', 'cssClass', 'workspace', 'workspaceIconClass', 'color'];+ const dirtyingLabels = ["iconClass", "cssClass", "workspace", "workspaceIconClass", "color"];- if (attrRow.type === 'label' && dirtyingLabels.includes(attrRow.name)) {+ if (attrRow.type === "label" && dirtyingLabels.includes(attrRow.name)) {if (attrRow.isInheritable) {refreshCtx.noteIdsToReload.add(attrRow.noteId);} else {refreshCtx.noteIdsToUpdate.add(attrRow.noteId);}- } else if (attrRow.type === 'label' && attrRow.name === 'archived') {+ } else if (attrRow.type === "label" && attrRow.name === "archived") {const note = froca.getNoteFromCache(attrRow.noteId);if (note) {@@ -1167,10 +1162,10 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {refreshCtx.noteIdsToReload.add(parentNote.noteId);}}- } else if (attrRow.type === 'relation' && (attrRow.name === 'template' || attrRow.name === 'inherit')) {+ } else if (attrRow.type === "relation" && (attrRow.name === "template" || attrRow.name === "inherit")) {// missing handling of things inherited from templaterefreshCtx.noteIdsToReload.add(attrRow.noteId);- } else if (attrRow.type === 'relation' && attrRow.name === 'imageLink') {+ } else if (attrRow.type === "relation" && attrRow.name === "imageLink") {const note = froca.getNoteFromCache(attrRow.noteId);if (note && note.getChildNoteIds().includes(attrRow.value)) {@@ -1184,14 +1179,14 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}async #processBranchRows(branchRows, refreshCtx) {- const allBranchesDeleted = branchRows.every(branchRow => !!branchRow.isDeleted);+ const allBranchesDeleted = branchRows.every((branchRow) => !!branchRow.isDeleted);// activeNode is supposed to be moved when we find out activeNode is deleted but not all branches are deleted. save it for fixing activeNodePath after all nodes loaded.let movedActiveNode = null;let parentsOfAddedNodes = [];for (const branchRow of branchRows) {- if (branchRow.parentNoteId === '_share') {+ if (branchRow.parentNoteId === "_share") {// all shared notes have a sign in the tree, even the descendants of shared notesrefreshCtx.noteIdsToReload.add(branchRow.noteId);} else {@@ -1203,12 +1198,10 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {for (const node of this.getNodesByBranch(branchRow)) {if (node.isActive()) {if (allBranchesDeleted) {- const newActiveNode = node.getNextSibling()- || node.getPrevSibling()- || node.getParent();+ const newActiveNode = node.getNextSibling() || node.getPrevSibling() || node.getParent();if (newActiveNode) {- newActiveNode.setActive(true, {noEvents: true, noFocus: true});+ newActiveNode.setActive(true, { noEvents: true, noFocus: true });}} else {movedActiveNode = node;@@ -1223,7 +1216,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}} else {for (const parentNode of this.getNodesByNoteId(branchRow.parentNoteId)) {- parentsOfAddedNodes.push(parentNode)+ parentsOfAddedNodes.push(parentNode);if (parentNode.isFolder() && !parentNode.isLoaded()) {continue;@@ -1231,7 +1224,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const note = await froca.getNote(branchRow.noteId);const frocaBranch = froca.getBranch(branchRow.branchId);- const foundNode = (parentNode.getChildren() || []).find(child => child.data.noteId === branchRow.noteId);+ const foundNode = (parentNode.getChildren() || []).find((child) => child.data.noteId === branchRow.noteId);if (foundNode) {// the branch already exists in the treeif (branchRow.isExpanded !== foundNode.isExpanded()) {@@ -1291,7 +1284,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {async #setActiveNode(activeNotePath, activeNodeFocused, movedActiveNode, parentsOfAddedNodes) {if (movedActiveNode) {for (const parentNode of parentsOfAddedNodes) {- const foundNode = (parentNode.getChildren() || []).find(child => child.data.noteId === movedActiveNode.data.noteId);+ const foundNode = (parentNode.getChildren() || []).find((child) => child.data.noteId === movedActiveNode.data.noteId);if (foundNode) {activeNotePath = treeService.getNotePath(foundNode);break;@@ -1323,7 +1316,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {this.tree.$container.focus();}- await node.setActive(true, {noEvents: true, noFocus: !activeNodeFocused});+ await node.setActive(true, { noEvents: true, noFocus: !activeNodeFocused });}sortChildren(node) {@@ -1345,11 +1338,10 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const branch = froca.getBranch(branchId, true);if (!branch) {- if (branchId && branchId.startsWith('virt')) {+ if (branchId && branchId.startsWith("virt")) {// in case of virtual branches there's nothing to updatereturn;- }- else {+ } else {logError(`Cannot find branch=${branchId}`);return;}@@ -1377,12 +1369,12 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const node = await this.getNodeFromPath(activeNotePath, true);if (node) {- await node.setActive(true, {noEvents: true, noFocus: true});+ await node.setActive(true, { noEvents: true, noFocus: true });}}}- async hoistedNoteChangedEvent({ntxId}) {+ async hoistedNoteChangedEvent({ ntxId }) {if (this.isNoteContext(ntxId)) {await this.filterHoistedBranch(true);}@@ -1405,21 +1397,23 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {await this.getNodeFromPath(hoistedNotePath);- if (this.noteContext.hoistedNoteId === 'root') {+ if (this.noteContext.hoistedNoteId === "root") {this.tree.clearFilter();this.toggleHiddenNode(false); // show everything but the hidden subtree} else {// hack when hoisted note is cloned then it could be filtered multiple times while we want only 1- this.tree.filterBranches(node =>- node.data.noteId === this.noteContext.hoistedNoteId // optimization to not having always resolve the node path- && treeService.getNotePath(node) === hoistedNotePath);+ this.tree.filterBranches(+ (node) =>+ node.data.noteId === this.noteContext.hoistedNoteId && // optimization to not having always resolve the node path+ treeService.getNotePath(node) === hoistedNotePath+ );this.toggleHiddenNode(true); // hoisting will handle hidden note visibility}}toggleHiddenNode(show) {- const hiddenNode = this.getNodesByNoteId('_hidden')[0];+ const hiddenNode = this.getNodesByNoteId("_hidden")[0];$(hiddenNode.li).toggleClass("hidden-node-is-hidden", !show);}@@ -1428,18 +1422,18 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}async getHotKeys() {- const actions = await keyboardActionsService.getActionsForScope('note-tree');+ const actions = await keyboardActionsService.getActionsForScope("note-tree");const hotKeyMap = {};for (const action of actions) {for (const shortcut of action.effectiveShortcuts) {- hotKeyMap[shortcutService.normalizeShortcut(shortcut)] = node => {+ hotKeyMap[shortcutService.normalizeShortcut(shortcut)] = (node) => {const notePath = treeService.getNotePath(node);- this.triggerCommand(action.actionName, {node, notePath});+ this.triggerCommand(action.actionName, { node, notePath });return false;- }+ };}}@@ -1452,7 +1446,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {getSelectedOrActiveBranchIds(node) {const nodes = this.getSelectedOrActiveNodes(node);- return nodes.map(node => node.data.branchId);+ return nodes.map((node) => node.data.branchId);}/**@@ -1461,12 +1455,11 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {getSelectedOrActiveNoteIds(node) {const nodes = this.getSelectedOrActiveNodes(node);- return nodes.map(node => node.data.noteId);+ return nodes.map((node) => node.data.noteId);}- async deleteNotesCommand({node}) {- const branchIds = this.getSelectedOrActiveBranchIds(node)- .filter(branchId => !branchId.startsWith('virt-')); // search results can't be deleted+ async deleteNotesCommand({ node }) {+ const branchIds = this.getSelectedOrActiveBranchIds(node).filter((branchId) => !branchId.startsWith("virt-")); // search results can't be deletedif (!branchIds.length) {return;@@ -1478,16 +1471,16 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}canBeMovedUpOrDown(node) {- if (node.data.noteId === 'root') {+ if (node.data.noteId === "root") {return false;}const parentNote = froca.getNoteFromCache(node.getParent().data.noteId);- return !parentNote?.hasLabel('sorted');+ return !parentNote?.hasLabel("sorted");}- moveNoteUpCommand({node}) {+ moveNoteUpCommand({ node }) {if (!this.canBeMovedUpOrDown(node)) {return;}@@ -1499,7 +1492,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}}- moveNoteDownCommand({node}) {+ moveNoteDownCommand({ node }) {if (!this.canBeMovedUpOrDown(node)) {return;}@@ -1511,11 +1504,11 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}}- moveNoteUpInHierarchyCommand({node}) {+ moveNoteUpInHierarchyCommand({ node }) {branchService.moveNodeUpInHierarchy(node);}- moveNoteDownInHierarchyCommand({node}) {+ moveNoteDownInHierarchyCommand({ node }) {const toNode = node.getPrevSibling();if (toNode !== null) {@@ -1537,7 +1530,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const prevSibling = node.getPrevSibling();if (prevSibling) {- prevSibling.setActive(true, {noEvents: true});+ prevSibling.setActive(true, { noEvents: true });if (prevSibling.isSelected()) {node.setSelected(false);@@ -1561,7 +1554,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {const nextSibling = node.getNextSibling();if (nextSibling) {- nextSibling.setActive(true, {noEvents: true});+ nextSibling.setActive(true, { noEvents: true });if (nextSibling.isSelected()) {node.setSelected(false);@@ -1571,63 +1564,63 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}}- expandSubtreeCommand({node}) {+ expandSubtreeCommand({ node }) {this.expandTree(node);}- collapseSubtreeCommand({node}) {+ collapseSubtreeCommand({ node }) {this.collapseTree(node);}- async recentChangesInSubtreeCommand({node}) {- this.triggerCommand("showRecentChanges", {ancestorNoteId: node.data.noteId});+ async recentChangesInSubtreeCommand({ node }) {+ this.triggerCommand("showRecentChanges", { ancestorNoteId: node.data.noteId });}- selectAllNotesInParentCommand({node}) {+ selectAllNotesInParentCommand({ node }) {for (const child of node.getParent().getChildren()) {child.setSelected(true);}}- copyNotesToClipboardCommand({node}) {+ copyNotesToClipboardCommand({ node }) {clipboard.copy(this.getSelectedOrActiveBranchIds(node));}- cutNotesToClipboardCommand({node}) {+ cutNotesToClipboardCommand({ node }) {clipboard.cut(this.getSelectedOrActiveBranchIds(node));}- pasteNotesFromClipboardCommand({node}) {+ pasteNotesFromClipboardCommand({ node }) {clipboard.pasteInto(node.data.branchId);}- pasteNotesAfterFromClipboardCommand({node}) {+ pasteNotesAfterFromClipboardCommand({ node }) {clipboard.pasteAfter(node.data.branchId);}- async exportNoteCommand({node}) {+ async exportNoteCommand({ node }) {const notePath = treeService.getNotePath(node);- this.triggerCommand("showExportDialog", {notePath, defaultType: "subtree"});+ this.triggerCommand("showExportDialog", { notePath, defaultType: "subtree" });}- async importIntoNoteCommand({node}) {- this.triggerCommand("showImportDialog", {noteId: node.data.noteId});+ async importIntoNoteCommand({ node }) {+ this.triggerCommand("showImportDialog", { noteId: node.data.noteId });}- editNoteTitleCommand({node}) {- appContext.triggerCommand('focusOnTitle');+ editNoteTitleCommand({ node }) {+ appContext.triggerCommand("focusOnTitle");}- protectSubtreeCommand({node}) {+ protectSubtreeCommand({ node }) {protectedSessionService.protectNote(node.data.noteId, true, true);}- unprotectSubtreeCommand({node}) {+ unprotectSubtreeCommand({ node }) {protectedSessionService.protectNote(node.data.noteId, false, true);}- duplicateSubtreeCommand({node}) {+ duplicateSubtreeCommand({ node }) {const nodesToDuplicate = this.getSelectedOrActiveNodes(node);for (const nodeToDuplicate of nodesToDuplicate) {@@ -1643,28 +1636,28 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {}}- moveShortcutToVisibleCommand({node, selectedOrActiveBranchIds}) {- branchService.moveToParentNote(selectedOrActiveBranchIds, '_lbVisibleLaunchers');+ moveShortcutToVisibleCommand({ node, selectedOrActiveBranchIds }) {+ branchService.moveToParentNote(selectedOrActiveBranchIds, "_lbVisibleLaunchers");}- moveShortcutToAvailableCommand({node, selectedOrActiveBranchIds}) {- branchService.moveToParentNote(selectedOrActiveBranchIds, '_lbAvailableLaunchers');+ moveShortcutToAvailableCommand({ node, selectedOrActiveBranchIds }) {+ branchService.moveToParentNote(selectedOrActiveBranchIds, "_lbAvailableLaunchers");}- addNoteLauncherCommand({node}) {- this.createLauncherNote(node, 'note');+ addNoteLauncherCommand({ node }) {+ this.createLauncherNote(node, "note");}- addScriptLauncherCommand({node}) {- this.createLauncherNote(node, 'script');+ addScriptLauncherCommand({ node }) {+ this.createLauncherNote(node, "script");}- addWidgetLauncherCommand({node}) {- this.createLauncherNote(node, 'customWidget');+ addWidgetLauncherCommand({ node }) {+ this.createLauncherNote(node, "customWidget");}- addSpacerLauncherCommand({node}) {- this.createLauncherNote(node, 'spacer');+ addSpacerLauncherCommand({ node }) {+ this.createLauncherNote(node, "spacer");}async createLauncherNote(node, launcherType) {diff --git a/src/public/app/widgets/note_type.js b/src/public/app/widgets/note_type.jsindex 4ce86ca7d3..6ae1e2e22c 100644--- a/src/public/app/widgets/note_type.js+++ b/src/public/app/widgets/note_type.js@@ -1,30 +1,30 @@-import server from '../services/server.js';-import mimeTypesService from '../services/mime_types.js';+import server from "../services/server.js";+import mimeTypesService from "../services/mime_types.js";import NoteContextAwareWidget from "./note_context_aware_widget.js";import dialogService from "../services/dialog.js";-import { t } from '../services/i18n.js';+import { t } from "../services/i18n.js";const NOTE_TYPES = [{ type: "file", title: t("note_types.file"), selectable: false },{ type: "image", title: t("note_types.image"), selectable: false },{ type: "search", title: t("note_types.saved-search"), selectable: false },- { type: "noteMap", mime: '', title: t("note_types.note-map"), selectable: false },- { type: "launcher", mime: '', title: t("note_types.launcher"), selectable: false },- { type: "doc", mime: '', title: t("note_types.doc"), selectable: false },- { type: "contentWidget", mime: '', title: t("note_types.widget"), selectable: false },+ { type: "noteMap", mime: "", title: t("note_types.note-map"), selectable: false },+ { type: "launcher", mime: "", title: t("note_types.launcher"), selectable: false },+ { type: "doc", mime: "", title: t("note_types.doc"), selectable: false },+ { type: "contentWidget", mime: "", title: t("note_types.widget"), selectable: false },{ type: "text", mime: "text/html", title: t("note_types.text"), selectable: true },{ type: "relationMap", mime: "application/json", title: t("note_types.relation-map"), selectable: true },- { type: "mindMap", mime: "application/json", "title": t("note_types.mind-map"), selectable: true },- { type: "render", mime: '', title: t("note_types.render-note"), selectable: true },- { type: "canvas", mime: 'application/json', title: t("note_types.canvas"), selectable: true },- { type: "mermaid", mime: 'text/mermaid', title: t("note_types.mermaid-diagram"), selectable: true },- { type: "book", mime: '', title: t("note_types.book"), selectable: true },- { type: "webView", mime: '', title: t("note_types.web-view"), selectable: true },- { type: "code", mime: 'text/plain', title: t("note_types.code"), selectable: true }+ { type: "mindMap", mime: "application/json", title: t("note_types.mind-map"), selectable: true },+ { type: "render", mime: "", title: t("note_types.render-note"), selectable: true },+ { type: "canvas", mime: "application/json", title: t("note_types.canvas"), selectable: true },+ { type: "mermaid", mime: "text/mermaid", title: t("note_types.mermaid-diagram"), selectable: true },+ { type: "book", mime: "", title: t("note_types.book"), selectable: true },+ { type: "webView", mime: "", title: t("note_types.web-view"), selectable: true },+ { type: "code", mime: "text/plain", title: t("note_types.code"), selectable: true }];-const NOT_SELECTABLE_NOTE_TYPES = NOTE_TYPES.filter(nt => !nt.selectable).map(nt => nt.type);+const NOT_SELECTABLE_NOTE_TYPES = NOTE_TYPES.filter((nt) => !nt.selectable).map((nt) => nt.type);const TPL = `<div class="dropdown note-type-widget">@@ -49,18 +49,17 @@ export default class NoteTypeWidget extends NoteContextAwareWidget {this.dropdown = bootstrap.Dropdown.getOrCreateInstance(this.$widget.find("[data-bs-toggle='dropdown']"));- this.$widget.on('show.bs.dropdown', () => this.renderDropdown());+ this.$widget.on("show.bs.dropdown", () => this.renderDropdown());this.$noteTypeDropdown = this.$widget.find(".note-type-dropdown");this.$noteTypeButton = this.$widget.find(".note-type-button");this.$noteTypeDesc = this.$widget.find(".note-type-desc");- this.$widget.on('click', '.dropdown-item', () => this.dropdown.toggle());+ this.$widget.on("click", ".dropdown-item", () => this.dropdown.toggle());}async refreshWithNote(note) {- this.$noteTypeButton.prop("disabled",- () => NOT_SELECTABLE_NOTE_TYPES.includes(note.type));+ this.$noteTypeButton.prop("disabled", () => NOT_SELECTABLE_NOTE_TYPES.includes(note.type));this.$noteTypeDesc.text(await this.findTypeTitle(note.type, note.mime));@@ -71,27 +70,23 @@ export default class NoteTypeWidget extends NoteContextAwareWidget {async renderDropdown() {this.$noteTypeDropdown.empty();- for (const noteType of NOTE_TYPES.filter(nt => nt.selectable)) {+ for (const noteType of NOTE_TYPES.filter((nt) => nt.selectable)) {let $typeLink;if (noteType.type !== "code") {$typeLink = $('<a class="dropdown-item">').attr("data-note-type", noteType.type).append('<span class="check">✓</span> ')- .append($('<span>').text(noteType.title))- .on('click', e => {- const type = $typeLink.attr('data-note-type');- const noteType = NOTE_TYPES.find(nt => nt.type === type);+ .append($("<span>").text(noteType.title))+ .on("click", (e) => {+ const type = $typeLink.attr("data-note-type");+ const noteType = NOTE_TYPES.find((nt) => nt.type === type);this.save(noteType.type, noteType.mime);});} else {- this.$noteTypeDropdown- .append('<div class="dropdown-divider"></div>');- $typeLink = $('<a class="dropdown-item disabled">')- .attr("data-note-type", noteType.type)- .append('<span class="check">✓</span> ')- .append($('<strong>').text(noteType.title));+ this.$noteTypeDropdown.append('<div class="dropdown-divider"></div>');+ $typeLink = $('<a class="dropdown-item disabled">').attr("data-note-type", noteType.type).append('<span class="check">✓</span> ').append($("<strong>").text(noteType.title));}if (this.note.type === noteType.type) {@@ -109,14 +104,14 @@ export default class NoteTypeWidget extends NoteContextAwareWidget {const $mimeLink = $('<a class="dropdown-item">').attr("data-mime-type", mimeType.mime).append('<span class="check">✓</span> ')- .append($('<span>').text(mimeType.title))- .on('click', e => {- const $link = $(e.target).closest('.dropdown-item');+ .append($("<span>").text(mimeType.title))+ .on("click", (e) => {+ const $link = $(e.target).closest(".dropdown-item");- this.save('code', $link.attr('data-mime-type'));+ this.save("code", $link.attr("data-mime-type"));});- if (this.note.type === 'code' && this.note.mime === mimeType.mime) {+ if (this.note.type === "code" && this.note.mime === mimeType.mime) {$mimeLink.addClass("selected");this.$noteTypeDesc.text(mimeType.title);@@ -127,14 +122,13 @@ export default class NoteTypeWidget extends NoteContextAwareWidget {}async findTypeTitle(type, mime) {- if (type === 'code') {+ if (type === "code") {const mimeTypes = mimeTypesService.getMimeTypes();- const found = mimeTypes.find(mt => mt.mime === mime);+ const found = mimeTypes.find((mt) => mt.mime === mime);return found ? found.title : mime;- }- else {- const noteType = NOTE_TYPES.find(nt => nt.type === type);+ } else {+ const noteType = NOTE_TYPES.find((nt) => nt.type === type);return noteType ? noteType.title : type;}@@ -145,7 +139,7 @@ export default class NoteTypeWidget extends NoteContextAwareWidget {return;}- if (type !== this.note.type && !await this.confirmChangeIfContent()) {+ if (type !== this.note.type && !(await this.confirmChangeIfContent())) {return;}diff --git a/src/public/app/widgets/note_wrapper.js b/src/public/app/widgets/note_wrapper.jsindex 424cb6da73..baf444e617 100644--- a/src/public/app/widgets/note_wrapper.js+++ b/src/public/app/widgets/note_wrapper.js@@ -4,13 +4,12 @@ import attributeService from "../services/attributes.js";export default class NoteWrapperWidget extends FlexContainer {constructor() {- super('column');+ super("column");- this.css("flex-grow", "1")- .collapsible();+ this.css("flex-grow", "1").collapsible();}- setNoteContextEvent({noteContext}) {+ setNoteContextEvent({ noteContext }) {this.noteContext = noteContext;this.refresh();@@ -42,10 +41,7 @@ export default class NoteWrapperWidget extends FlexContainer {return;}- this.$widget.toggleClass("full-content-width",- ['image', 'mermaid', 'book', 'render', 'canvas', 'webView', 'mindMap'].includes(note.type)- || !!note?.isLabelTruthy('fullContentWidth')- );+ this.$widget.toggleClass("full-content-width", ["image", "mermaid", "book", "render", "canvas", "webView", "mindMap"].includes(note.type) || !!note?.isLabelTruthy("fullContentWidth"));this.$widget.addClass(note.getCssClass());@@ -55,13 +51,14 @@ export default class NoteWrapperWidget extends FlexContainer {this.$widget.toggleClass("protected", note.isProtected);}- async entitiesReloadedEvent({loadResults}) {+ async entitiesReloadedEvent({ loadResults }) {// listening on changes of note.type and CSS classconst noteId = this.noteContext?.noteId;- if (loadResults.isNoteReloaded(noteId)- || loadResults.getAttributeRows().find(attr => attr.type === 'label' && attr.name === 'cssClass' && attributeService.isAffecting(attr, this.noteContext?.note))) {-+ if (+ loadResults.isNoteReloaded(noteId) ||+ loadResults.getAttributeRows().find((attr) => attr.type === "label" && attr.name === "cssClass" && attributeService.isAffecting(attr, this.noteContext?.note))+ ) {this.refresh();}}diff --git a/src/public/app/widgets/protected_note_switch.js b/src/public/app/widgets/protected_note_switch.jsindex c7cd5c41ab..5833e0ddac 100644--- a/src/public/app/widgets/protected_note_switch.js+++ b/src/public/app/widgets/protected_note_switch.js@@ -18,7 +18,7 @@ export default class ProtectedNoteSwitchWidget extends SwitchWidget {}switchOff() {- protectedSessionService.protectNote(this.noteId, false, false)+ protectedSessionService.protectNote(this.noteId, false, false);}async refreshWithNote(note) {@@ -26,7 +26,7 @@ export default class ProtectedNoteSwitchWidget extends SwitchWidget {this.$switchOff.toggle(!!note.isProtected);}- entitiesReloadedEvent({loadResults}) {+ entitiesReloadedEvent({ loadResults }) {if (loadResults.isNoteReloaded(this.noteId)) {this.refresh();}diff --git a/src/public/app/widgets/quick_search.js b/src/public/app/widgets/quick_search.jsindex 17eeece6b7..dd7eef3cd6 100644--- a/src/public/app/widgets/quick_search.js+++ b/src/public/app/widgets/quick_search.js@@ -46,13 +46,13 @@ export default class QuickSearchWidget extends BasicWidget {this.$widget = $(TPL);this.dropdown = bootstrap.Dropdown.getOrCreateInstance(this.$widget.find("[data-bs-toggle='dropdown']"));- this.$searchString = this.$widget.find('.search-string');- this.$dropdownMenu = this.$widget.find('.dropdown-menu');+ this.$searchString = this.$widget.find(".search-string");+ this.$dropdownMenu = this.$widget.find(".dropdown-menu");- this.$widget.find('.input-group-prepend').on('shown.bs.dropdown', () => this.search());+ this.$widget.find(".input-group-prepend").on("shown.bs.dropdown", () => this.search());if (utils.isMobile()) {- this.$searchString.keydown(e => {+ this.$searchString.keydown((e) => {if (e.which === 13) {if (this.$dropdownMenu.is(":visible")) {this.search(); // just update already visible dropdown@@ -62,10 +62,10 @@ export default class QuickSearchWidget extends BasicWidget {e.preventDefault();e.stopPropagation();}- })+ });}- shortcutService.bindElShortcut(this.$searchString, 'return', () => {+ shortcutService.bindElShortcut(this.$searchString, "return", () => {if (this.$dropdownMenu.is(":visible")) {this.search(); // just update already visible dropdown} else {@@ -75,11 +75,11 @@ export default class QuickSearchWidget extends BasicWidget {this.$searchString.focus();});- shortcutService.bindElShortcut(this.$searchString, 'down', () => {- this.$dropdownMenu.find('.dropdown-item:not(.disabled):first').focus();+ shortcutService.bindElShortcut(this.$searchString, "down", () => {+ this.$dropdownMenu.find(".dropdown-item:not(.disabled):first").focus();});- shortcutService.bindElShortcut(this.$searchString, 'esc', () => {+ shortcutService.bindElShortcut(this.$searchString, "esc", () => {this.dropdown.hide();});@@ -101,9 +101,9 @@ export default class QuickSearchWidget extends BasicWidget {if (error) {let tooltip = new bootstrap.Tooltip(this.$searchString, {- trigger: 'manual',+ trigger: "manual",title: `Search error: ${error}`,- placement: 'right'+ placement: "right"});tooltip.show();@@ -121,17 +121,17 @@ export default class QuickSearchWidget extends BasicWidget {for (const note of await froca.getNotes(displayedNoteIds)) {const $link = await linkService.createLink(note.noteId, { showNotePath: true, showNoteIcon: true });- $link.addClass('dropdown-item');+ $link.addClass("dropdown-item");$link.attr("tabIndex", "0");- $link.on('click', e => {+ $link.on("click", (e) => {this.dropdown.hide();- if (!e.target || e.target.nodeName !== 'A') {+ if (!e.target || e.target.nodeName !== "A") {// click on the link is handled by link handling, but we want the whole item clickableappContext.tabManager.getActiveContext().setNote(note.noteId);}});- shortcutService.bindElShortcut($link, 'return', () => {+ shortcutService.bindElShortcut($link, "return", () => {this.dropdown.hide();appContext.tabManager.getActiveContext().setNote(note.noteId);@@ -141,21 +141,20 @@ export default class QuickSearchWidget extends BasicWidget {}if (searchResultNoteIds.length > MAX_DISPLAYED_NOTES) {- const numRemainingResults = (searchResultNoteIds.length - MAX_DISPLAYED_NOTES);+ const numRemainingResults = searchResultNoteIds.length - MAX_DISPLAYED_NOTES;this.$dropdownMenu.append(`<span class="dropdown-item disabled">${t("quick-search.more-results", { number: numRemainingResults })}</span>`);}- const $showInFullButton = $('<a class="dropdown-item" tabindex="0">')- .append($(`<button class="btn btn-sm">${t("quick-search.show-in-full-search")}</button>`));+ const $showInFullButton = $('<a class="dropdown-item" tabindex="0">').append($(`<button class="btn btn-sm">${t("quick-search.show-in-full-search")}</button>`));this.$dropdownMenu.append($(`<div class="dropdown-divider">`));this.$dropdownMenu.append($showInFullButton);- $showInFullButton.on('click', () => this.showInFullSearch());+ $showInFullButton.on("click", () => this.showInFullSearch());- shortcutService.bindElShortcut($showInFullButton, 'return', () => this.showInFullSearch());+ shortcutService.bindElShortcut($showInFullButton, "return", () => this.showInFullSearch());- shortcutService.bindElShortcut(this.$dropdownMenu.find('.dropdown-item:first'), 'up', () => this.$searchString.focus());+ shortcutService.bindElShortcut(this.$dropdownMenu.find(".dropdown-item:first"), "up", () => this.$searchString.focus());this.dropdown.update();}@@ -163,7 +162,7 @@ export default class QuickSearchWidget extends BasicWidget {async showInFullSearch() {this.dropdown.hide();- await appContext.triggerCommand('searchNotes', {+ await appContext.triggerCommand("searchNotes", {searchString: this.$searchString.val()});}diff --git a/src/public/app/widgets/quick_search_launcher.js b/src/public/app/widgets/quick_search_launcher.jsindex a173bca24d..2cd906470a 100644--- a/src/public/app/widgets/quick_search_launcher.js+++ b/src/public/app/widgets/quick_search_launcher.js@@ -3,14 +3,13 @@ import QuickSearchWidget from "./quick_search.js";/*** Similar to the {@link QuickSearchWidget} but meant to be included inside the launcher bar.- *+ ** <p>* Adds specific tweaks such as:- *+ ** - Hiding the widget on mobile.*/export default class QuickSearchLauncherWidget extends QuickSearchWidget {-constructor(isHorizontalLayout) {super();this.isHorizontalLayout = isHorizontalLayout;@@ -29,5 +28,4 @@ export default class QuickSearchLauncherWidget extends QuickSearchWidget {return super.isEnabled();}--}\ No newline at end of file+}diff --git a/src/public/app/widgets/ribbon_widgets/basic_properties.js b/src/public/app/widgets/ribbon_widgets/basic_properties.jsindex b8b6fabaad..f7cf9a602e 100644--- a/src/public/app/widgets/ribbon_widgets/basic_properties.js+++ b/src/public/app/widgets/ribbon_widgets/basic_properties.js@@ -60,14 +60,7 @@ export default class BasicPropertiesWidget extends NoteContextAwareWidget {this.sharedSwitchWidget = new SharedSwitchWidget().contentSized();this.templateSwitchWidget = new TemplateSwitchWidget().contentSized();- this.child(- this.noteTypeWidget,- this.protectedNoteSwitchWidget,- this.editabilitySelectWidget,- this.bookmarkSwitchWidget,- this.sharedSwitchWidget,- this.templateSwitchWidget- );+ this.child(this.noteTypeWidget, this.protectedNoteSwitchWidget, this.editabilitySelectWidget, this.bookmarkSwitchWidget, this.sharedSwitchWidget, this.templateSwitchWidget);}get name() {@@ -82,7 +75,7 @@ export default class BasicPropertiesWidget extends NoteContextAwareWidget {return {show: !this.note.isLaunchBarConfig(),title: t("basic_properties.basic_properties"),- icon: 'bx bx-slider'+ icon: "bx bx-slider"};}@@ -101,6 +94,6 @@ export default class BasicPropertiesWidget extends NoteContextAwareWidget {async refreshWithNote(note) {await super.refreshWithNote(note);- this.$widget.find(".editability-select-container").toggle(this.note && ['text', 'code'].includes(this.note.type))+ this.$widget.find(".editability-select-container").toggle(this.note && ["text", "code"].includes(this.note.type));}}diff --git a/src/public/app/widgets/ribbon_widgets/book_properties.js b/src/public/app/widgets/ribbon_widgets/book_properties.jsindex c597f02b68..efc49d1420 100644--- a/src/public/app/widgets/ribbon_widgets/book_properties.js+++ b/src/public/app/widgets/ribbon_widgets/book_properties.js@@ -53,7 +53,7 @@ export default class BookPropertiesWidget extends NoteContextAwareWidget {}isEnabled() {- return this.note && this.note.type === 'book';+ return this.note && this.note.type === "book";}getTitle() {@@ -61,7 +61,7 @@ export default class BookPropertiesWidget extends NoteContextAwareWidget {show: this.isEnabled(),activate: true,title: t("book_properties.book_properties"),- icon: 'bx bx-book'+ icon: "bx bx-book"};}@@ -69,48 +69,48 @@ export default class BookPropertiesWidget extends NoteContextAwareWidget {this.$widget = $(TPL);this.contentSized();- this.$viewTypeSelect = this.$widget.find('.view-type-select');- this.$viewTypeSelect.on('change', () => this.toggleViewType(this.$viewTypeSelect.val()));+ this.$viewTypeSelect = this.$widget.find(".view-type-select");+ this.$viewTypeSelect.on("change", () => this.toggleViewType(this.$viewTypeSelect.val()));- this.$expandChildrenButton = this.$widget.find('.expand-children-button');- this.$expandChildrenButton.on('click', async () => {- if (!this.note.isLabelTruthy('expanded')) {- await attributeService.addLabel(this.noteId, 'expanded');+ this.$expandChildrenButton = this.$widget.find(".expand-children-button");+ this.$expandChildrenButton.on("click", async () => {+ if (!this.note.isLabelTruthy("expanded")) {+ await attributeService.addLabel(this.noteId, "expanded");}- this.triggerCommand('refreshNoteList', {noteId: this.noteId});+ this.triggerCommand("refreshNoteList", { noteId: this.noteId });});- this.$collapseAllButton = this.$widget.find('.collapse-all-button');- this.$collapseAllButton.on('click', async () => {+ this.$collapseAllButton = this.$widget.find(".collapse-all-button");+ this.$collapseAllButton.on("click", async () => {// owned is important - we shouldn't remove inherited expanded labels- for (const expandedAttr of this.note.getOwnedLabels('expanded')) {+ for (const expandedAttr of this.note.getOwnedLabels("expanded")) {await attributeService.removeAttributeById(this.noteId, expandedAttr.attributeId);}- this.triggerCommand('refreshNoteList', {noteId: this.noteId});+ this.triggerCommand("refreshNoteList", { noteId: this.noteId });});}async refreshWithNote(note) {- const viewType = this.note.getLabelValue('viewType') || 'grid';+ const viewType = this.note.getLabelValue("viewType") || "grid";this.$viewTypeSelect.val(viewType);- this.$expandChildrenButton.toggle(viewType === 'list');- this.$collapseAllButton.toggle(viewType === 'list');+ this.$expandChildrenButton.toggle(viewType === "list");+ this.$collapseAllButton.toggle(viewType === "list");}async toggleViewType(type) {- if (type !== 'list' && type !== 'grid') {+ if (type !== "list" && type !== "grid") {throw new Error(t("book_properties.invalid_view_type", { type }));}- await attributeService.setLabel(this.noteId, 'viewType', type);+ await attributeService.setLabel(this.noteId, "viewType", type);}- entitiesReloadedEvent({loadResults}) {- if (loadResults.getAttributeRows().find(attr => attr.noteId === this.noteId && attr.name === 'viewType')) {+ entitiesReloadedEvent({ loadResults }) {+ if (loadResults.getAttributeRows().find((attr) => attr.noteId === this.noteId && attr.name === "viewType")) {this.refresh();}}diff --git a/src/public/app/widgets/ribbon_widgets/classic_editor_toolbar.js b/src/public/app/widgets/ribbon_widgets/classic_editor_toolbar.jsindex 7ff2cb7e11..25f4028422 100644--- a/src/public/app/widgets/ribbon_widgets/classic_editor_toolbar.js+++ b/src/public/app/widgets/ribbon_widgets/classic_editor_toolbar.js@@ -64,7 +64,6 @@ const TPL = `\* The ribbon item is active by default for text notes, as long as they are not in read-only mode.*/export default class ClassicEditorToolbar extends NoteContextAwareWidget {-constructor() {super();this.observer = new MutationObserver((e) => this.#onDropdownStateChanged(e));@@ -90,16 +89,14 @@ export default class ClassicEditorToolbar extends NoteContextAwareWidget {// Observe when a dropdown is expanded to apply a style that allows the dropdown to be visible, since we can't have the element both visible and the toolbar scrollable.this.observer.disconnect();this.observer.observe(this.$widget[0], {- attributeFilter: [ "aria-expanded" ],+ attributeFilter: ["aria-expanded"],subtree: true});}}#onDropdownStateChanged(e) {- const dropdownActive = e- .map((e) => e.target.ariaExpanded === "true")- .reduce((acc, e) => acc && e);+ const dropdownActive = e.map((e) => e.target.ariaExpanded === "true").reduce((acc, e) => acc && e);this.$widget[0].classList.toggle("dropdown-active", dropdownActive);}@@ -138,5 +135,4 @@ export default class ClassicEditorToolbar extends NoteContextAwareWidget {return true;}-}diff --git a/src/public/app/widgets/ribbon_widgets/edited_notes.js b/src/public/app/widgets/ribbon_widgets/edited_notes.jsindex 5f0f28e56b..437e734913 100644--- a/src/public/app/widgets/ribbon_widgets/edited_notes.js+++ b/src/public/app/widgets/ribbon_widgets/edited_notes.js@@ -28,33 +28,30 @@ export default class EditedNotesWidget extends NoteContextAwareWidget {}isEnabled() {- return super.isEnabled()- && this.note.hasOwnedLabel("dateNote");+ return super.isEnabled() && this.note.hasOwnedLabel("dateNote");}getTitle() {return {show: this.isEnabled(),// promoted attributes have priority over edited notes- activate:- (this.note.getPromotedDefinitionAttributes().length === 0 || !options.is('promotedAttributesOpenInRibbon'))- && options.is('editedNotesOpenInRibbon'),+ activate: (this.note.getPromotedDefinitionAttributes().length === 0 || !options.is("promotedAttributesOpenInRibbon")) && options.is("editedNotesOpenInRibbon"),title: t("edited_notes.title"),- icon: 'bx bx-calendar-edit'+ icon: "bx bx-calendar-edit"};}async doRender() {this.$widget = $(TPL);this.contentSized();- this.$list = this.$widget.find('.edited-notes-list');- this.$noneFound = this.$widget.find('.no-edited-notes-found');+ this.$list = this.$widget.find(".edited-notes-list");+ this.$noneFound = this.$widget.find(".no-edited-notes-found");}async refreshWithNote(note) {let editedNotes = await server.get(`edited-notes/${note.getLabelValue("dateNote")}`);- editedNotes = editedNotes.filter(n => n.noteId !== note.noteId);+ editedNotes = editedNotes.filter((n) => n.noteId !== note.noteId);this.$list.empty();this.$noneFound.hide();@@ -64,7 +61,7 @@ export default class EditedNotesWidget extends NoteContextAwareWidget {return;}- const noteIds = editedNotes.flatMap(n => n.noteId);+ const noteIds = editedNotes.flatMap((n) => n.noteId);await froca.getNotes(noteIds, true); // preload all at once@@ -74,16 +71,9 @@ export default class EditedNotesWidget extends NoteContextAwareWidget {if (editedNote.isDeleted) {const title = `${editedNote.title} ${t("edited_notes.deleted")}`;- $item.append(- $("<i>")- .text(title)- .attr("title", title)- );- }- else {- $item.append(editedNote.notePath- ? await linkService.createLink(editedNote.notePath.join("/"), {showNotePath: true})- : $("<span>").text(editedNote.title));+ $item.append($("<i>").text(title).attr("title", title));+ } else {+ $item.append(editedNote.notePath ? await linkService.createLink(editedNote.notePath.join("/"), { showNotePath: true }) : $("<span>").text(editedNote.title));}if (i < editedNotes.length - 1) {diff --git a/src/public/app/widgets/ribbon_widgets/file_properties.js b/src/public/app/widgets/ribbon_widgets/file_properties.jsindex ad864778af..26e6952800 100644--- a/src/public/app/widgets/ribbon_widgets/file_properties.js+++ b/src/public/app/widgets/ribbon_widgets/file_properties.js@@ -66,7 +66,7 @@ export default class FilePropertiesWidget extends NoteContextAwareWidget {}isEnabled() {- return this.note && this.note.type === 'file';+ return this.note && this.note.type === "file";}getTitle() {@@ -74,7 +74,7 @@ export default class FilePropertiesWidget extends NoteContextAwareWidget {show: this.isEnabled(),activate: true,title: t("file_properties.title"),- icon: 'bx bx-file'+ icon: "bx bx-file"};}@@ -90,16 +90,16 @@ export default class FilePropertiesWidget extends NoteContextAwareWidget {this.$uploadNewRevisionButton = this.$widget.find(".file-upload-new-revision");this.$uploadNewRevisionInput = this.$widget.find(".file-upload-new-revision-input");- this.$downloadButton.on('click', () => openService.downloadFileNote(this.noteId));- this.$openButton.on('click', () => openService.openNoteExternally(this.noteId, this.note.mime));+ this.$downloadButton.on("click", () => openService.downloadFileNote(this.noteId));+ this.$openButton.on("click", () => openService.openNoteExternally(this.noteId, this.note.mime));this.$uploadNewRevisionButton.on("click", () => {this.$uploadNewRevisionInput.trigger("click");});- this.$uploadNewRevisionInput.on('change', async () => {+ this.$uploadNewRevisionInput.on("change", async () => {const fileToUpload = this.$uploadNewRevisionInput[0].files[0]; // copy to allow reset below- this.$uploadNewRevisionInput.val('');+ this.$uploadNewRevisionInput.val("");const result = await server.upload(`notes/${this.noteId}/file`, fileToUpload);@@ -117,7 +117,7 @@ export default class FilePropertiesWidget extends NoteContextAwareWidget {this.$widget.show();this.$fileNoteId.text(note.noteId);- this.$fileName.text(note.getLabelValue('originalFileName') || "?");+ this.$fileName.text(note.getLabelValue("originalFileName") || "?");this.$fileType.text(note.mime);const blob = await this.note.getBlob();diff --git a/src/public/app/widgets/ribbon_widgets/image_properties.js b/src/public/app/widgets/ribbon_widgets/image_properties.jsindex 7ac67a8100..d24ea410cd 100644--- a/src/public/app/widgets/ribbon_widgets/image_properties.js+++ b/src/public/app/widgets/ribbon_widgets/image_properties.js@@ -47,7 +47,7 @@ export default class ImagePropertiesWidget extends NoteContextAwareWidget {}isEnabled() {- return this.note && this.note.type === 'image';+ return this.note && this.note.type === "image";}getTitle() {@@ -55,7 +55,7 @@ export default class ImagePropertiesWidget extends NoteContextAwareWidget {show: this.isEnabled(),activate: true,title: t("image_properties.title"),- icon: 'bx bx-image'+ icon: "bx bx-image"};}@@ -64,7 +64,7 @@ export default class ImagePropertiesWidget extends NoteContextAwareWidget {this.contentSized();this.$copyReferenceToClipboardButton = this.$widget.find(".image-copy-reference-to-clipboard");- this.$copyReferenceToClipboardButton.on('click', () => this.triggerEvent(`copyImageReferenceToClipboard`, {ntxId: this.noteContext.ntxId}));+ this.$copyReferenceToClipboardButton.on("click", () => this.triggerEvent(`copyImageReferenceToClipboard`, { ntxId: this.noteContext.ntxId }));this.$uploadNewRevisionButton = this.$widget.find(".image-upload-new-revision");this.$uploadNewRevisionInput = this.$widget.find(".image-upload-new-revision-input");@@ -74,18 +74,18 @@ export default class ImagePropertiesWidget extends NoteContextAwareWidget {this.$fileSize = this.$widget.find(".image-filesize");this.$openButton = this.$widget.find(".image-open");- this.$openButton.on('click', () => openService.openNoteExternally(this.noteId, this.note.mime));+ this.$openButton.on("click", () => openService.openNoteExternally(this.noteId, this.note.mime));this.$imageDownloadButton = this.$widget.find(".image-download");- this.$imageDownloadButton.on('click', () => openService.downloadFileNote(this.noteId));+ this.$imageDownloadButton.on("click", () => openService.downloadFileNote(this.noteId));this.$uploadNewRevisionButton.on("click", () => {this.$uploadNewRevisionInput.trigger("click");});- this.$uploadNewRevisionInput.on('change', async () => {+ this.$uploadNewRevisionInput.on("change", async () => {const fileToUpload = this.$uploadNewRevisionInput[0].files[0]; // copy to allow reset below- this.$uploadNewRevisionInput.val('');+ this.$uploadNewRevisionInput.val("");const result = await server.upload(`images/${this.noteId}`, fileToUpload);@@ -106,7 +106,7 @@ export default class ImagePropertiesWidget extends NoteContextAwareWidget {const blob = await this.note.getBlob();- this.$fileName.text(note.getLabelValue('originalFileName') || "?");+ this.$fileName.text(note.getLabelValue("originalFileName") || "?");this.$fileSize.text(utils.formatSize(blob.contentLength));this.$fileType.text(note.mime);}diff --git a/src/public/app/widgets/ribbon_widgets/inherited_attribute_list.js b/src/public/app/widgets/ribbon_widgets/inherited_attribute_list.jsindex 225c268626..6e6f435edf 100644--- a/src/public/app/widgets/ribbon_widgets/inherited_attribute_list.js+++ b/src/public/app/widgets/ribbon_widgets/inherited_attribute_list.js@@ -35,9 +35,7 @@ export default class InheritedAttributesWidget extends NoteContextAwareWidget {super();/** @type {AttributeDetailWidget} */- this.attributeDetailWidget = new AttributeDetailWidget()- .contentSized()- .setParent(this);+ this.attributeDetailWidget = new AttributeDetailWidget().contentSized().setParent(this);this.child(this.attributeDetailWidget);}@@ -54,7 +52,7 @@ export default class InheritedAttributesWidget extends NoteContextAwareWidget {this.$widget = $(TPL);this.contentSized();- this.$container = this.$widget.find('.inherited-attributes-container');+ this.$container = this.$widget.find(".inherited-attributes-container");this.$widget.append(this.attributeDetailWidget.render());}@@ -69,9 +67,9 @@ export default class InheritedAttributesWidget extends NoteContextAwareWidget {}for (const attribute of inheritedAttributes) {- const $attr = (await attributeRenderer.renderAttribute(attribute, false))- .on('click', e => {- setTimeout(() =>+ const $attr = (await attributeRenderer.renderAttribute(attribute, false)).on("click", (e) => {+ setTimeout(+ () =>this.attributeDetailWidget.showAttributeDetail({attribute: {noteId: attribute.noteId,@@ -83,17 +81,17 @@ export default class InheritedAttributesWidget extends NoteContextAwareWidget {isOwned: false,x: e.pageX,y: e.pageY- }), 100);- });+ }),+ 100+ );+ });- this.$container- .append($attr)- .append(" ");+ this.$container.append($attr).append(" ");}}getInheritedAttributes(note) {- const attrs = note.getAttributes().filter(attr => attr.noteId !== this.noteId);+ const attrs = note.getAttributes().filter((attr) => attr.noteId !== this.noteId);attrs.sort((a, b) => {if (a.noteId === b.noteId) {@@ -107,8 +105,8 @@ export default class InheritedAttributesWidget extends NoteContextAwareWidget {return attrs;}- entitiesReloadedEvent({loadResults}) {- if (loadResults.getAttributeRows(this.componentId).find(attr => attributeService.isAffecting(attr, this.note))) {+ entitiesReloadedEvent({ loadResults }) {+ if (loadResults.getAttributeRows(this.componentId).find((attr) => attributeService.isAffecting(attr, this.note))) {this.refresh();}}diff --git a/src/public/app/widgets/ribbon_widgets/note_info_widget.js b/src/public/app/widgets/ribbon_widgets/note_info_widget.jsindex f66cb459a0..5d5c47bf0b 100644--- a/src/public/app/widgets/ribbon_widgets/note_info_widget.js+++ b/src/public/app/widgets/ribbon_widgets/note_info_widget.js@@ -1,10 +1,9 @@-import { formatDateTime } from "../../utils/formatters.js"+import { formatDateTime } from "../../utils/formatters.js";import { t } from "../../services/i18n.js";import NoteContextAwareWidget from "../note_context_aware_widget.js";import server from "../../services/server.js";import utils from "../../services/utils.js";-const TPL = `<div class="note-info-widget"><style>@@ -79,7 +78,7 @@ export default class NoteInfoWidget extends NoteContextAwareWidget {return {show: this.isEnabled(),title: t("note_info_widget.title"),- icon: 'bx bx-info-circle'+ icon: "bx bx-info-circle"};}@@ -93,12 +92,12 @@ export default class NoteInfoWidget extends NoteContextAwareWidget {this.$type = this.$widget.find(".note-info-type");this.$mime = this.$widget.find(".note-info-mime");- this.$noteSizesWrapper = this.$widget.find('.note-sizes-wrapper');+ this.$noteSizesWrapper = this.$widget.find(".note-sizes-wrapper");this.$noteSize = this.$widget.find(".note-size");this.$subTreeSize = this.$widget.find(".subtree-size");this.$calculateButton = this.$widget.find(".calculate-button");- this.$calculateButton.on('click', async () => {+ this.$calculateButton.on("click", async () => {this.$noteSizesWrapper.show();this.$calculateButton.hide();@@ -122,13 +121,9 @@ export default class NoteInfoWidget extends NoteContextAwareWidget {const metadata = await server.get(`notes/${this.noteId}/metadata`);this.$noteId.text(note.noteId);- this.$dateCreated- .text(formatDateTime(metadata.dateCreated))- .attr("title", metadata.dateCreated);+ this.$dateCreated.text(formatDateTime(metadata.dateCreated)).attr("title", metadata.dateCreated);- this.$dateModified- .text(formatDateTime(metadata.dateModified))- .attr("title", metadata.dateModified);+ this.$dateModified.text(formatDateTime(metadata.dateModified)).attr("title", metadata.dateModified);this.$type.text(note.type);diff --git a/src/public/app/widgets/ribbon_widgets/note_map.js b/src/public/app/widgets/ribbon_widgets/note_map.jsindex 63dafca877..e9b8a6e05a 100644--- a/src/public/app/widgets/ribbon_widgets/note_map.js+++ b/src/public/app/widgets/ribbon_widgets/note_map.js@@ -36,7 +36,7 @@ export default class NoteMapRibbonWidget extends NoteContextAwareWidget {constructor() {super();- this.noteMapWidget = new NoteMapWidget('ribbon');+ this.noteMapWidget = new NoteMapWidget("ribbon");this.child(this.noteMapWidget);}@@ -52,7 +52,7 @@ export default class NoteMapRibbonWidget extends NoteContextAwareWidget {return {show: this.isEnabled(),title: t("note_map.title"),- icon: 'bx bxs-network-chart'+ icon: "bx bxs-network-chart"};}@@ -62,44 +62,44 @@ export default class NoteMapRibbonWidget extends NoteContextAwareWidget {this.$container = this.$widget.find(".note-map-container");this.$container.append(this.noteMapWidget.render());- this.openState = 'small';+ this.openState = "small";- this.$openFullButton = this.$widget.find('.open-full-button');- this.$openFullButton.on('click', () => {+ this.$openFullButton = this.$widget.find(".open-full-button");+ this.$openFullButton.on("click", () => {this.setFullHeight();this.$openFullButton.hide();this.$collapseButton.show();- this.openState = 'full';+ this.openState = "full";this.noteMapWidget.setDimensions();});- this.$collapseButton = this.$widget.find('.collapse-button');- this.$collapseButton.on('click', () => {+ this.$collapseButton = this.$widget.find(".collapse-button");+ this.$collapseButton.on("click", () => {this.setSmallSize();this.$openFullButton.show();this.$collapseButton.hide();- this.openState = 'small';+ this.openState = "small";this.noteMapWidget.setDimensions();});const handleResize = () => {- if (!this.noteMapWidget.graph) { // no graph has been even rendered+ if (!this.noteMapWidget.graph) {+ // no graph has been even renderedreturn;}- if (this.openState === 'full') {+ if (this.openState === "full") {this.setFullHeight();- }- else if (this.openState === 'small') {+ } else if (this.openState === "small") {this.setSmallSize();}- }+ };new ResizeObserver(handleResize).observe(this.$widget[0]);}@@ -108,19 +108,15 @@ export default class NoteMapRibbonWidget extends NoteContextAwareWidget {const SMALL_SIZE_HEIGHT = 300;const width = this.$widget.width();- this.$widget.find('.note-map-container')- .height(SMALL_SIZE_HEIGHT)- .width(width);+ this.$widget.find(".note-map-container").height(SMALL_SIZE_HEIGHT).width(width);}setFullHeight() {- const {top} = this.$widget[0].getBoundingClientRect();+ const { top } = this.$widget[0].getBoundingClientRect();const height = $(window).height() - top;const width = this.$widget.width();- this.$widget.find('.note-map-container')- .height(height)- .width(width);+ this.$widget.find(".note-map-container").height(height).width(width);}}diff --git a/src/public/app/widgets/ribbon_widgets/note_paths.js b/src/public/app/widgets/ribbon_widgets/note_paths.jsindex 45fd04122d..cabf4f39d4 100644--- a/src/public/app/widgets/ribbon_widgets/note_paths.js+++ b/src/public/app/widgets/ribbon_widgets/note_paths.js@@ -49,7 +49,7 @@ export default class NotePathsWidget extends NoteContextAwareWidget {return {show: true,title: t("note_paths.title"),- icon: 'bx bx-collection'+ icon: "bx bx-collection"};}@@ -59,22 +59,19 @@ export default class NotePathsWidget extends NoteContextAwareWidget {this.$notePathIntro = this.$widget.find(".note-path-intro");this.$notePathList = this.$widget.find(".note-path-list");- this.$widget.on('show.bs.dropdown', () => this.renderDropdown());+ this.$widget.on("show.bs.dropdown", () => this.renderDropdown());}async refreshWithNote(note) {this.$notePathList.empty();- if (this.noteId === 'root') {- this.$notePathList.empty().append(- await this.getRenderedPath('root')- );+ if (this.noteId === "root") {+ this.$notePathList.empty().append(await this.getRenderedPath("root"));return;}- const sortedNotePaths = this.note.getSortedNotePathRecords(this.hoistedNoteId)- .filter(notePath => !notePath.isHidden);+ const sortedNotePaths = this.note.getSortedNotePathRecords(this.hoistedNoteId).filter((notePath) => !notePath.isHidden);if (sortedNotePaths.length > 0) {this.$notePathIntro.text(t("note_paths.intro_placed"));@@ -85,7 +82,7 @@ export default class NotePathsWidget extends NoteContextAwareWidget {const renderedPaths = [];for (const notePathRecord of sortedNotePaths) {- const notePath = notePathRecord.notePath.join('/');+ const notePath = notePathRecord.notePath.join("/");renderedPaths.push(await this.getRenderedPath(notePath, notePathRecord));}@@ -96,11 +93,9 @@ export default class NotePathsWidget extends NoteContextAwareWidget {async getRenderedPath(notePath, notePathRecord = null) {const title = await treeService.getNotePathTitle(notePath);- const $noteLink = await linkService.createLink(notePath, {title});+ const $noteLink = await linkService.createLink(notePath, { title });- $noteLink- .find('a')- .addClass("no-tooltip-preview");+ $noteLink.find("a").addClass("no-tooltip-preview");const icons = [];@@ -127,16 +122,14 @@ export default class NotePathsWidget extends NoteContextAwareWidget {}if (icons.length > 0) {- $noteLink.append(` ${icons.join(' ')}`);+ $noteLink.append(` ${icons.join(" ")}`);}return $("<li>").append($noteLink);}- entitiesReloadedEvent({loadResults}) {- if (loadResults.getBranchRows().find(branch => branch.noteId === this.noteId)- || loadResults.isNoteReloaded(this.noteId)) {-+ entitiesReloadedEvent({ loadResults }) {+ if (loadResults.getBranchRows().find((branch) => branch.noteId === this.noteId) || loadResults.isNoteReloaded(this.noteId)) {this.refresh();}}diff --git a/src/public/app/widgets/ribbon_widgets/note_properties.js b/src/public/app/widgets/ribbon_widgets/note_properties.jsindex 5f7ef1d704..4aacdcba0f 100644--- a/src/public/app/widgets/ribbon_widgets/note_properties.js+++ b/src/public/app/widgets/ribbon_widgets/note_properties.js@@ -11,7 +11,7 @@ const TPL = `</style><div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap">- ${t('note_properties.this_note_was_originally_taken_from')} <a class="page-url external"></a>+ ${t("note_properties.this_note_was_originally_taken_from")} <a class="page-url external"></a></div></div>`;@@ -20,15 +20,15 @@ const TPL = `*/export default class NotePropertiesWidget extends NoteContextAwareWidget {isEnabled() {- return this.note && !!this.note.getLabelValue('pageUrl');+ return this.note && !!this.note.getLabelValue("pageUrl");}getTitle() {return {show: this.isEnabled(),activate: true,- title: t('note_properties.info'),- icon: 'bx bx-info-square'+ title: t("note_properties.info"),+ icon: "bx bx-info-square"};}@@ -36,15 +36,12 @@ export default class NotePropertiesWidget extends NoteContextAwareWidget {this.$widget = $(TPL);this.contentSized();- this.$pageUrl = this.$widget.find('.page-url');+ this.$pageUrl = this.$widget.find(".page-url");}async refreshWithNote(note) {- const pageUrl = note.getLabelValue('pageUrl');+ const pageUrl = note.getLabelValue("pageUrl");- this.$pageUrl- .attr('href', pageUrl)- .attr('title', pageUrl)- .text(pageUrl);+ this.$pageUrl.attr("href", pageUrl).attr("title", pageUrl).text(pageUrl);}}diff --git a/src/public/app/widgets/ribbon_widgets/owned_attribute_list.js b/src/public/app/widgets/ribbon_widgets/owned_attribute_list.jsindex 80838a0aa7..8addb139a1 100644--- a/src/public/app/widgets/ribbon_widgets/owned_attribute_list.js+++ b/src/public/app/widgets/ribbon_widgets/owned_attribute_list.js@@ -35,13 +35,9 @@ export default class OwnedAttributeListWidget extends NoteContextAwareWidget {constructor() {super();- this.attributeDetailWidget = new AttributeDetailWidget()- .contentSized()- .setParent(this);+ this.attributeDetailWidget = new AttributeDetailWidget().contentSized().setParent(this);- this.attributeEditorWidget = new AttributeEditorWidget(this.attributeDetailWidget)- .contentSized()- .setParent(this);+ this.attributeEditorWidget = new AttributeEditorWidget(this.attributeDetailWidget).contentSized().setParent(this);this.child(this.attributeEditorWidget, this.attributeDetailWidget);}@@ -49,7 +45,7 @@ export default class OwnedAttributeListWidget extends NoteContextAwareWidget {getTitle() {return {show: !this.note.isLaunchBarConfig(),- title: t('owned_attribute_list.owned_attributes'),+ title: t("owned_attribute_list.owned_attributes"),icon: "bx bx-list-check"};}@@ -58,10 +54,10 @@ export default class OwnedAttributeListWidget extends NoteContextAwareWidget {this.$widget = $(TPL);this.contentSized();- this.$widget.find('.attr-editor-placeholder').replaceWith(this.attributeEditorWidget.render());+ this.$widget.find(".attr-editor-placeholder").replaceWith(this.attributeEditorWidget.render());this.$widget.append(this.attributeDetailWidget.render());- this.$title = $('<div>');+ this.$title = $("<div>");}async saveAttributesCommand() {@@ -72,7 +68,7 @@ export default class OwnedAttributeListWidget extends NoteContextAwareWidget {await this.attributeEditorWidget.refresh();}- async updateAttributeListCommand({attributes}) {+ async updateAttributeListCommand({ attributes }) {await this.attributeEditorWidget.updateAttributeList(attributes);}diff --git a/src/public/app/widgets/ribbon_widgets/promoted_attributes.js b/src/public/app/widgets/ribbon_widgets/promoted_attributes.jsindex b4f7084a38..a538e43f8e 100644--- a/src/public/app/widgets/ribbon_widgets/promoted_attributes.js+++ b/src/public/app/widgets/ribbon_widgets/promoted_attributes.js@@ -89,8 +89,8 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget {return {show: true,- activate: options.is('promotedAttributesOpenInRibbon'),- title: t('promoted_attributes.promoted_attributes'),+ activate: options.is("promotedAttributesOpenInRibbon"),+ title: t("promoted_attributes.promoted_attributes"),icon: "bx bx-table"};}@@ -113,10 +113,10 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget {const $cells = [];for (const definitionAttr of promotedDefAttrs) {- const valueType = definitionAttr.name.startsWith('label:') ? 'label' : 'relation';+ const valueType = definitionAttr.name.startsWith("label:") ? "label" : "relation";const valueName = definitionAttr.name.substr(valueType.length + 1);- let valueAttrs = ownedAttributes.filter(el => el.name === valueName && el.type === valueType);+ let valueAttrs = ownedAttributes.filter((el) => el.name === valueName && el.type === valueType);if (valueAttrs.length === 0) {valueAttrs.push({@@ -127,7 +127,7 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget {});}- if (definitionAttr.getDefinition().multiplicity === 'single') {+ if (definitionAttr.getDefinition().multiplicity === "single") {valueAttrs = valueAttrs.slice(0, 1);}@@ -151,62 +151,68 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget {const $input = $("<input>").prop("tabindex", 200 + definitionAttr.position).prop("id", id)- .attr("data-attribute-id", valueAttr.noteId === this.noteId ? valueAttr.attributeId : '') // if not owned, we'll force creation of a new attribute instead of updating the inherited one+ .attr("data-attribute-id", valueAttr.noteId === this.noteId ? valueAttr.attributeId : "") // if not owned, we'll force creation of a new attribute instead of updating the inherited one.attr("data-attribute-type", valueAttr.type).attr("data-attribute-name", valueAttr.name).prop("value", valueAttr.value).addClass("form-control").addClass("promoted-attribute-input")- .on('change', event => this.promotedAttributeChanged(event));+ .on("change", (event) => this.promotedAttributeChanged(event));const $actionCell = $("<div>");- const $multiplicityCell = $("<td>")- .addClass("multiplicity")- .attr("nowrap", true);+ const $multiplicityCell = $("<td>").addClass("multiplicity").attr("nowrap", true);const $wrapper = $('<div class="promoted-attribute-cell">')- .append($("<label>").prop("for", id).text(definition.promotedAlias ?? valueName))+ .append(+ $("<label>")+ .prop("for", id)+ .text(definition.promotedAlias ?? valueName)+ ).append($("<div>").addClass("input-group").append($input)).append($actionCell).append($multiplicityCell);- if (valueAttr.type === 'label') {- if (definition.labelType === 'text') {+ if (valueAttr.type === "label") {+ if (definition.labelType === "text") {$input.prop("type", "text");// autocomplete for label values is just nice to have, mobile can keep labels editable without autocompleteif (utils.isDesktop()) {// no need to await for this, can be done asynchronously- server.get(`attribute-values/${encodeURIComponent(valueAttr.name)}`).then(attributeValues => {+ server.get(`attribute-values/${encodeURIComponent(valueAttr.name)}`).then((attributeValues) => {if (attributeValues.length === 0) {return;}- attributeValues = attributeValues.map(attribute => ({ value: attribute }));-- $input.autocomplete({- appendTo: document.querySelector('body'),- hint: false,- autoselect: false,- openOnFocus: true,- minLength: 0,- tabAutocomplete: false- }, [{- displayKey: 'value',- source: function (term, cb) {- term = term.toLowerCase();-- const filtered = attributeValues.filter(attr => attr.value.toLowerCase().includes(term));-- cb(filtered);- }- }]);-- $input.on('autocomplete:selected', e => this.promotedAttributeChanged(e));+ attributeValues = attributeValues.map((attribute) => ({ value: attribute }));++ $input.autocomplete(+ {+ appendTo: document.querySelector("body"),+ hint: false,+ autoselect: false,+ openOnFocus: true,+ minLength: 0,+ tabAutocomplete: false+ },+ [+ {+ displayKey: "value",+ source: function (term, cb) {+ term = term.toLowerCase();++ const filtered = attributeValues.filter((attr) => attr.value.toLowerCase().includes(term));++ cb(filtered);+ }+ }+ ]+ );++ $input.on("autocomplete:selected", (e) => this.promotedAttributeChanged(e));});}- }- else if (definition.labelType === 'number') {+ } else if (definition.labelType === "number") {$input.prop("type", "number");let step = 1;@@ -216,41 +222,32 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget {}$input.prop("step", step);- $input- .css("text-align", "right")- .css("width", "120");- }- else if (definition.labelType === 'boolean') {+ $input.css("text-align", "right").css("width", "120");+ } else if (definition.labelType === "boolean") {$input.prop("type", "checkbox");if (valueAttr.value === "true") {$input.prop("checked", "checked");}- }- else if (definition.labelType === 'date') {+ } else if (definition.labelType === "date") {$input.prop("type", "date");- }- else if (definition.labelType === 'datetime') {- $input.prop('type', 'datetime-local')- }- else if (definition.labelType === 'time') {- $input.prop('type', 'time')- }- else if (definition.labelType === 'url') {+ } else if (definition.labelType === "datetime") {+ $input.prop("type", "datetime-local");+ } else if (definition.labelType === "time") {+ $input.prop("type", "time");+ } else if (definition.labelType === "url") {$input.prop("placeholder", t("promoted_attributes.url_placeholder"));const $openButton = $("<span>").addClass("input-group-text open-external-link-button bx bx-window-open").prop("title", t("promoted_attributes.open_external_link"))- .on('click', () => window.open($input.val(), '_blank'));+ .on("click", () => window.open($input.val(), "_blank"));$input.after($openButton);- }- else {+ } else {ws.logError(t("promoted_attributes.unknown_label_type", { type: definitionAttr.labelType }));}- }- else if (valueAttr.type === 'relation') {+ } else if (valueAttr.type === "relation") {if (valueAttr.value) {$input.val(await treeService.getNoteTitle(valueAttr.value));}@@ -259,7 +256,7 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget {// no need to wait for thisnoteAutocompleteService.initNoteAutocomplete($input, { allowCreatingNotes: true });- $input.on('autocomplete:noteselected', (event, suggestion, dataset) => {+ $input.on("autocomplete:noteselected", (event, suggestion, dataset) => {this.promotedAttributeChanged(event);});@@ -268,8 +265,7 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget {// we can't provide user a way to edit the relation so make it read only$input.attr("readonly", "readonly");}- }- else {+ } else {ws.logError(t(`promoted_attributes.unknown_attribute_type`, { type: valueAttr.type }));return;}@@ -278,23 +274,27 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget {const $addButton = $("<span>").addClass("bx bx-plus pointer").prop("title", t("promoted_attributes.add_new_attribute"))- .on('click', async () => {- const $new = await this.createPromotedAttributeCell(definitionAttr, {- attributeId: "",- type: valueAttr.type,- name: valueName,- value: ""- }, valueName);+ .on("click", async () => {+ const $new = await this.createPromotedAttributeCell(+ definitionAttr,+ {+ attributeId: "",+ type: valueAttr.type,+ name: valueName,+ value: ""+ },+ valueName+ );$wrapper.after($new);- $new.find('input').trigger('focus');+ $new.find("input").trigger("focus");});const $removeButton = $("<span>").addClass("bx bx-trash pointer").prop("title", t("promoted_attributes.remove_this_attribute"))- .on('click', async () => {+ .on("click", async () => {const attributeId = $input.attr("data-attribute-id");if (attributeId) {@@ -305,12 +305,16 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget {const sameAttrSelector = `input[data-attribute-type='${valueAttr.type}'][data-attribute-name='${valueName}']`;if (this.$widget.find(sameAttrSelector).length <= 1) {- const $new = await this.createPromotedAttributeCell(definitionAttr, {- attributeId: "",- type: valueAttr.type,- name: valueName,- value: ""- }, valueName);+ const $new = await this.createPromotedAttributeCell(+ definitionAttr,+ {+ attributeId: "",+ type: valueAttr.type,+ name: valueName,+ value: ""+ },+ valueName+ );$wrapper.after($new);}@@ -318,11 +322,7 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget {$wrapper.remove();});- $multiplicityCell- .append(" ")- .append($addButton)- .append(" ")- .append($removeButton);+ $multiplicityCell.append(" ").append($addButton).append(" ").append($removeButton);}return $wrapper;@@ -334,23 +334,25 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget {let value;if ($attr.prop("type") === "checkbox") {- value = $attr.is(':checked') ? "true" : "false";- }- else if ($attr.attr("data-attribute-type") === "relation") {+ value = $attr.is(":checked") ? "true" : "false";+ } else if ($attr.attr("data-attribute-type") === "relation") {const selectedPath = $attr.getSelectedNotePath();value = selectedPath ? treeService.getNoteIdFromUrl(selectedPath) : "";- }- else {+ } else {value = $attr.val();}- const result = await server.put(`notes/${this.noteId}/attribute`, {- attributeId: $attr.attr("data-attribute-id"),- type: $attr.attr("data-attribute-type"),- name: $attr.attr("data-attribute-name"),- value: value- }, this.componentId);+ const result = await server.put(+ `notes/${this.noteId}/attribute`,+ {+ attributeId: $attr.attr("data-attribute-id"),+ type: $attr.attr("data-attribute-type"),+ name: $attr.attr("data-attribute-name"),+ value: value+ },+ this.componentId+ );$attr.attr("data-attribute-id", result.attributeId);}@@ -360,7 +362,7 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget {}entitiesReloadedEvent({ loadResults }) {- if (loadResults.getAttributeRows(this.componentId).find(attr => attributeService.isAffecting(attr, this.note))) {+ if (loadResults.getAttributeRows(this.componentId).find((attr) => attributeService.isAffecting(attr, this.note))) {this.refresh();}}diff --git a/src/public/app/widgets/ribbon_widgets/script_executor.js b/src/public/app/widgets/ribbon_widgets/script_executor.jsindex 0afc389b77..0b324d1d8d 100644--- a/src/public/app/widgets/ribbon_widgets/script_executor.js+++ b/src/public/app/widgets/ribbon_widgets/script_executor.js@@ -24,22 +24,24 @@ const TPL = `export default class ScriptExecutorWidget extends NoteContextAwareWidget {isEnabled() {- return super.isEnabled()- && this.note- && (this.note.mime.startsWith('application/javascript') || this.isTriliumSqlite())- && (this.note.hasLabel('executeDescription') || this.note.hasLabel('executeButton'));+ return (+ super.isEnabled() &&+ this.note &&+ (this.note.mime.startsWith("application/javascript") || this.isTriliumSqlite()) &&+ (this.note.hasLabel("executeDescription") || this.note.hasLabel("executeButton"))+ );}isTriliumSqlite() {- return this.note.mime === 'text/x-sqlite;schema=trilium';+ return this.note.mime === "text/x-sqlite;schema=trilium";}getTitle() {return {show: this.isEnabled(),activate: true,- title: this.isTriliumSqlite() ? t('script_executor.query') : t('script_executor.script'),- icon: 'bx bx-run'+ title: this.isTriliumSqlite() ? t("script_executor.query") : t("script_executor.script"),+ icon: "bx bx-run"};}@@ -47,19 +49,18 @@ export default class ScriptExecutorWidget extends NoteContextAwareWidget {this.$widget = $(TPL);this.contentSized();- this.$executeButton = this.$widget.find('.execute-button');- this.$executeDescription = this.$widget.find('.execute-description');+ this.$executeButton = this.$widget.find(".execute-button");+ this.$executeDescription = this.$widget.find(".execute-description");}async refreshWithNote(note) {- const executeTitle = note.getLabelValue('executeButton')- || (this.isTriliumSqlite() ? t('script_executor.execute_query') : t('script_executor.execute_script'));+ const executeTitle = note.getLabelValue("executeButton") || (this.isTriliumSqlite() ? t("script_executor.execute_query") : t("script_executor.execute_script"));this.$executeButton.text(executeTitle);- this.$executeButton.attr('title', executeTitle);+ this.$executeButton.attr("title", executeTitle);keyboardActionService.updateDisplayedShortcuts(this.$widget);- const executeDescription = note.getLabelValue('executeDescription');+ const executeDescription = note.getLabelValue("executeDescription");if (executeDescription) {this.$executeDescription.show().html(executeDescription);diff --git a/src/public/app/widgets/ribbon_widgets/search_definition.js b/src/public/app/widgets/ribbon_widgets/search_definition.jsindex 106355e582..3ab077fa9e 100644--- a/src/public/app/widgets/ribbon_widgets/search_definition.js+++ b/src/public/app/widgets/ribbon_widgets/search_definition.js@@ -74,54 +74,54 @@ const TPL = `<div class="search-settings"><table class="search-setting-table"><tr>- <td class="title-column">${t('search_definition.add_search_option')}</td>+ <td class="title-column">${t("search_definition.add_search_option")}</td><td colspan="2" class="add-search-option"><button type="button" class="btn btn-sm" data-search-option-add="searchString"><span class="bx bx-text"></span>- ${t('search_definition.search_string')}+ ${t("search_definition.search_string")}</button><button type="button" class="btn btn-sm" data-search-option-add="searchScript"><span class="bx bx-code"></span>- ${t('search_definition.search_script')}+ ${t("search_definition.search_script")}</button><button type="button" class="btn btn-sm" data-search-option-add="ancestor"><span class="bx bx-filter-alt"></span>- ${t('search_definition.ancestor')}+ ${t("search_definition.ancestor")}</button><button type="button" class="btn btn-sm" data-search-option-add="fastSearch"- title="${t('search_definition.fast_search_description')}">+ title="${t("search_definition.fast_search_description")}"><span class="bx bx-run"></span>- ${t('search_definition.fast_search')}+ ${t("search_definition.fast_search")}</button><button type="button" class="btn btn-sm" data-search-option-add="includeArchivedNotes"- title="${t('search_definition.include_archived_notes_description')}">+ title="${t("search_definition.include_archived_notes_description")}"><span class="bx bx-archive"></span>- ${t('search_definition.include_archived')}+ ${t("search_definition.include_archived")}</button><button type="button" class="btn btn-sm" data-search-option-add="orderBy"><span class="bx bx-arrow-from-top"></span>- ${t('search_definition.order_by')}+ ${t("search_definition.order_by")}</button>- <button type="button" class="btn btn-sm" data-search-option-add="limit" title="${t('search_definition.limit_description')}">+ <button type="button" class="btn btn-sm" data-search-option-add="limit" title="${t("search_definition.limit_description")}"><span class="bx bx-stop"></span>- ${t('search_definition.limit')}+ ${t("search_definition.limit")}</button>- <button type="button" class="btn btn-sm" data-search-option-add="debug" title="${t('search_definition.debug_description')}">+ <button type="button" class="btn btn-sm" data-search-option-add="debug" title="${t("search_definition.debug_description")}"><span class="bx bx-bug"></span>- ${t('search_definition.debug')}+ ${t("search_definition.debug")}</button><div class="dropdown" style="display: inline-block;"><button class="btn btn-sm dropdown-toggle action-add-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span class="bx bxs-zap"></span>- ${t('search_definition.action')}+ ${t("search_definition.action")}</button><div class="dropdown-menu action-list"></div></div>@@ -135,17 +135,17 @@ const TPL = `<div style="display: flex; justify-content: space-evenly"><button type="button" class="btn btn-sm search-button"><span class="bx bx-search"></span>- ${t('search_definition.search_button')}+ ${t("search_definition.search_button")}</button><button type="button" class="btn btn-sm search-and-execute-button"><span class="bx bxs-zap"></span>- ${t('search_definition.search_execute')}+ ${t("search_definition.search_execute")}</button><button type="button" class="btn btn-sm save-to-note-button"><span class="bx bx-save"></span>- ${t('search_definition.save_to_note')}+ ${t("search_definition.save_to_note")}</button></div></td>@@ -155,16 +155,7 @@ const TPL = `</div></div>`;-const OPTION_CLASSES = [- SearchString,- SearchScript,- Ancestor,- FastSearch,- IncludeArchivedNotes,- OrderBy,- Limit,- Debug-];+const OPTION_CLASSES = [SearchString, SearchScript, Ancestor, FastSearch, IncludeArchivedNotes, OrderBy, Limit, Debug];export default class SearchDefinitionWidget extends NoteContextAwareWidget {get name() {@@ -172,95 +163,89 @@ export default class SearchDefinitionWidget extends NoteContextAwareWidget {}isEnabled() {- return this.note && this.note.type === 'search';+ return this.note && this.note.type === "search";}getTitle() {return {show: this.isEnabled(),activate: true,- title: t('search_definition.search_parameters'),- icon: 'bx bx-search'+ title: t("search_definition.search_parameters"),+ icon: "bx bx-search"};}doRender() {this.$widget = $(TPL);this.contentSized();- this.$component = this.$widget.find('.search-definition-widget');- this.$actionList = this.$widget.find('.action-list');+ this.$component = this.$widget.find(".search-definition-widget");+ this.$actionList = this.$widget.find(".action-list");for (const actionGroup of bulkActionService.ACTION_GROUPS) {this.$actionList.append($('<h6 class="dropdown-header">').append(actionGroup.title));for (const action of actionGroup.actions) {- this.$actionList.append(- $('<a class="dropdown-item" href="#">')- .attr('data-action-add', action.actionName)- .text(action.actionTitle)- );+ this.$actionList.append($('<a class="dropdown-item" href="#">').attr("data-action-add", action.actionName).text(action.actionTitle));}}- this.$widget.on('click', '[data-search-option-add]', async event => {- const searchOptionName = $(event.target).attr('data-search-option-add');- const clazz = OPTION_CLASSES.find(SearchOptionClass => SearchOptionClass.optionName === searchOptionName);+ this.$widget.on("click", "[data-search-option-add]", async (event) => {+ const searchOptionName = $(event.target).attr("data-search-option-add");+ const clazz = OPTION_CLASSES.find((SearchOptionClass) => SearchOptionClass.optionName === searchOptionName);if (clazz) {await clazz.create(this.noteId);- }- else {- logError(t('search_definition.unknown_search_option', { searchOptionName }));+ } else {+ logError(t("search_definition.unknown_search_option", { searchOptionName }));}this.refresh();});- this.$widget.on('click', '[data-action-add]', async event => {- bootstrap.Dropdown.getOrCreateInstance(this.$widget.find('.action-add-toggle'));+ this.$widget.on("click", "[data-action-add]", async (event) => {+ bootstrap.Dropdown.getOrCreateInstance(this.$widget.find(".action-add-toggle"));- const actionName = $(event.target).attr('data-action-add');+ const actionName = $(event.target).attr("data-action-add");await bulkActionService.addAction(this.noteId, actionName);this.refresh();});- this.$searchOptions = this.$widget.find('.search-options');- this.$actionOptions = this.$widget.find('.action-options');+ this.$searchOptions = this.$widget.find(".search-options");+ this.$actionOptions = this.$widget.find(".action-options");- this.$searchButton = this.$widget.find('.search-button');- this.$searchButton.on('click', () => this.triggerCommand('refreshResults'));+ this.$searchButton = this.$widget.find(".search-button");+ this.$searchButton.on("click", () => this.triggerCommand("refreshResults"));- this.$searchAndExecuteButton = this.$widget.find('.search-and-execute-button');- this.$searchAndExecuteButton.on('click', () => this.searchAndExecute());+ this.$searchAndExecuteButton = this.$widget.find(".search-and-execute-button");+ this.$searchAndExecuteButton.on("click", () => this.searchAndExecute());- this.$saveToNoteButton = this.$widget.find('.save-to-note-button');- this.$saveToNoteButton.on('click', async () => {- const {notePath} = await server.post("special-notes/save-search-note", {searchNoteId: this.noteId});+ this.$saveToNoteButton = this.$widget.find(".save-to-note-button");+ this.$saveToNoteButton.on("click", async () => {+ const { notePath } = await server.post("special-notes/save-search-note", { searchNoteId: this.noteId });await ws.waitForMaxKnownEntityChangeId();await appContext.tabManager.getActiveContext().setNote(notePath);// Note the {{- notePathTitle}} in json file is not typo, it's unescaping// See https://www.i18next.com/translation-function/interpolation#unescape- toastService.showMessage(t('search_definition.search_note_saved', { notePathTitle: await treeService.getNotePathTitle(notePath) }));+ toastService.showMessage(t("search_definition.search_note_saved", { notePathTitle: await treeService.getNotePathTitle(notePath) }));});}async refreshResultsCommand() {try {- const {error} = await froca.loadSearchNote(this.noteId);+ const { error } = await froca.loadSearchNote(this.noteId);if (error) {- this.handleEvent('showSearchError', { error });+ this.handleEvent("showSearchError", { error });}- }- catch (e) {+ } catch (e) {toastService.showError(e.message);}- this.triggerEvent('searchRefreshed', {ntxId: this.noteContext.ntxId});+ this.triggerEvent("searchRefreshed", { ntxId: this.noteContext.ntxId });}async refreshSearchDefinitionCommand() {@@ -275,7 +260,7 @@ export default class SearchDefinitionWidget extends NoteContextAwareWidget {this.$searchOptions.empty();for (const OptionClass of OPTION_CLASSES) {- const {attributeType, optionName} = OptionClass;+ const { attributeType, optionName } = OptionClass;const attr = this.note.getAttribute(attributeType, optionName);@@ -291,30 +276,26 @@ export default class SearchDefinitionWidget extends NoteContextAwareWidget {const actions = bulkActionService.parseActions(this.note);- this.$actionOptions- .empty()- .append(...actions.map(action => action.render()));+ this.$actionOptions.empty().append(...actions.map((action) => action.render()));- this.$searchAndExecuteButton.css('visibility', actions.length > 0 ? 'visible' : '_hidden');+ this.$searchAndExecuteButton.css("visibility", actions.length > 0 ? "visible" : "_hidden");}getContent() {- return '';+ return "";}async searchAndExecute() {await server.post(`search-and-execute-note/${this.noteId}`);- this.triggerCommand('refreshResults');+ this.triggerCommand("refreshResults");- toastService.showMessage(t('search_definition.actions_executed'), 3000);+ toastService.showMessage(t("search_definition.actions_executed"), 3000);}- entitiesReloadedEvent({loadResults}) {+ entitiesReloadedEvent({ loadResults }) {// only refreshing deleted attrs, otherwise components update themselves- if (loadResults.getAttributeRows().find(attrRow =>- attrRow.type === 'label' && attrRow.name === 'action' && attrRow.isDeleted)) {-+ if (loadResults.getAttributeRows().find((attrRow) => attrRow.type === "label" && attrRow.name === "action" && attrRow.isDeleted)) {this.refresh();}}diff --git a/src/public/app/widgets/ribbon_widgets/similar_notes.js b/src/public/app/widgets/ribbon_widgets/similar_notes.jsindex 61cc79e4ca..7603a75183 100644--- a/src/public/app/widgets/ribbon_widgets/similar_notes.js+++ b/src/public/app/widgets/ribbon_widgets/similar_notes.js@@ -41,16 +41,14 @@ export default class SimilarNotesWidget extends NoteContextAwareWidget {}isEnabled() {- return super.isEnabled()- && this.note.type !== 'search'- && !this.note.isLabelTruthy('similarNotesWidgetDisabled');+ return super.isEnabled() && this.note.type !== "search" && !this.note.isLabelTruthy("similarNotesWidgetDisabled");}getTitle() {return {show: this.isEnabled(),- title: t('similar_notes.title'),- icon: 'bx bx-bar-chart'+ title: t("similar_notes.title"),+ icon: "bx bx-bar-chart"};}@@ -68,16 +66,16 @@ export default class SimilarNotesWidget extends NoteContextAwareWidget {const similarNotes = await server.get(`similar-notes/${this.noteId}`);if (similarNotes.length === 0) {- this.$similarNotesWrapper.empty().append(t('similar_notes.no_similar_notes_found'));+ this.$similarNotesWrapper.empty().append(t("similar_notes.no_similar_notes_found"));return;}- const noteIds = similarNotes.flatMap(note => note.notePath);+ const noteIds = similarNotes.flatMap((note) => note.notePath);await froca.getNotes(noteIds, true); // preload all at once- const $list = $('<div>');+ const $list = $("<div>");for (const similarNote of similarNotes) {const note = await froca.getNote(similarNote.noteId, true);@@ -86,8 +84,7 @@ export default class SimilarNotesWidget extends NoteContextAwareWidget {continue;}- const $item = (await linkService.createLink(similarNote.notePath.join("/")))- .css("font-size", 24 * (1 - 1 / (1 + similarNote.score)));+ const $item = (await linkService.createLink(similarNote.notePath.join("/"))).css("font-size", 24 * (1 - 1 / (1 + similarNote.score)));$list.append($item);}@@ -95,7 +92,7 @@ export default class SimilarNotesWidget extends NoteContextAwareWidget {this.$similarNotesWrapper.empty().append($list);}- entitiesReloadedEvent({loadResults}) {+ entitiesReloadedEvent({ loadResults }) {if (this.note && this.title !== this.note.title) {this.rendered = false;diff --git a/src/public/app/widgets/right_panel_widget.ts b/src/public/app/widgets/right_panel_widget.tsindex 0f2d113777..db12196866 100644--- a/src/public/app/widgets/right_panel_widget.ts+++ b/src/public/app/widgets/right_panel_widget.ts@@ -18,18 +18,23 @@ const WIDGET_TPL = `* This widget manages rendering panels in the right-hand pane.*/class RightPanelWidget extends NoteContextAwareWidget {-private $bodyWrapper!: JQuery<HTMLElement>;$body!: JQuery<HTMLElement>;private $title!: JQuery<HTMLElement>;private $buttons!: JQuery<HTMLElement>;/** Title to show in the panel. */- get widgetTitle() { return "Untitled widget"; }+ get widgetTitle() {+ return "Untitled widget";+ }- get widgetButtons(): AbstractButtonWidget<any>[] { return []; }+ get widgetButtons(): AbstractButtonWidget<any>[] {+ return [];+ }- get help() { return {}; }+ get help() {+ return {};+ }constructor() {super();@@ -44,24 +49,24 @@ class RightPanelWidget extends NoteContextAwareWidget {doRender() {this.$widget = $(WIDGET_TPL);this.contentSized();- this.$widget.find('[data-target]').attr('data-target', `#${this.componentId}`);+ this.$widget.find("[data-target]").attr("data-target", `#${this.componentId}`);- this.$bodyWrapper = this.$widget.find('.body-wrapper');- this.$bodyWrapper.attr('id', this.componentId); // for toggle to work we need id+ this.$bodyWrapper = this.$widget.find(".body-wrapper");+ this.$bodyWrapper.attr("id", this.componentId); // for toggle to work we need id- this.$body = this.$bodyWrapper.find('.card-body');+ this.$body = this.$bodyWrapper.find(".card-body");- this.$title = this.$widget.find('.card-header .card-header-title');+ this.$title = this.$widget.find(".card-header .card-header-title");this.$title.text(this.widgetTitle);- this.$buttons = this.$widget.find('.card-header .card-header-buttons');+ this.$buttons = this.$widget.find(".card-header .card-header-buttons");this.$buttons.empty();for (const buttonWidget of this.children) {this.$buttons.append((buttonWidget as BasicWidget).render());}- this.initialized = this.doRenderBody().catch(e => {+ this.initialized = this.doRenderBody().catch((e) => {this.logRenderingError(e);});}diff --git a/src/public/app/widgets/scroll_padding.js b/src/public/app/widgets/scroll_padding.jsindex f42b5e68ff..7763b51381 100644--- a/src/public/app/widgets/scroll_padding.js+++ b/src/public/app/widgets/scroll_padding.js@@ -11,8 +11,7 @@ export default class ScrollPaddingWidget extends NoteContextAwareWidget {this.$widget = $(TPL);this.contentSized();- this.$widget.on("click", () =>- this.triggerCommand('scrollToEnd', {ntxId: this.ntxId}));+ this.$widget.on("click", () => this.triggerCommand("scrollToEnd", { ntxId: this.ntxId }));}initialRenderCompleteEvent() {diff --git a/src/public/app/widgets/search_options/abstract_search_option.js b/src/public/app/widgets/search_options/abstract_search_option.jsindex 17b6873bb6..dd60aefc1d 100644--- a/src/public/app/widgets/search_options/abstract_search_option.js+++ b/src/public/app/widgets/search_options/abstract_search_option.js@@ -12,13 +12,13 @@ export default class AbstractSearchOption extends Component {this.note = note;}- static async setAttribute(noteId, type, name, value = '') {+ static async setAttribute(noteId, type, name, value = "") {await server.put(`notes/${noteId}/set-attribute`, { type, name, value });await ws.waitForMaxKnownEntityChangeId();}- async setAttribute(type, name, value = '') {+ async setAttribute(type, name, value = "") {await this.constructor.setAttribute(this.note.noteId, type, name, value);}@@ -26,16 +26,16 @@ export default class AbstractSearchOption extends Component {try {const $rendered = this.doRender();- $rendered.find('.search-option-del')- .on('click', () => this.deleteOption())- .attr('title', t('abstract_search_option.remove_this_search_option')); // 使用 t 函数处理 i18n 字符串+ $rendered+ .find(".search-option-del")+ .on("click", () => this.deleteOption())+ .attr("title", t("abstract_search_option.remove_this_search_option")); // 使用 t 函数处理 i18n 字符串utils.initHelpDropdown($rendered);return $rendered;- }- catch (e) {- logError(t('abstract_search_option.failed_rendering', { dto: JSON.stringify(this.attribute.dto), error: e.message, stack: e.stack })); // 使用 t 函数处理 i18n 字符串+ } catch (e) {+ logError(t("abstract_search_option.failed_rendering", { dto: JSON.stringify(this.attribute.dto), error: e.message, stack: e.stack })); // 使用 t 函数处理 i18n 字符串return null;}}@@ -48,7 +48,7 @@ export default class AbstractSearchOption extends Component {await ws.waitForMaxKnownEntityChangeId();- await this.triggerCommand('refreshSearchDefinition');+ await this.triggerCommand("refreshSearchDefinition");}async deleteAttribute(type, name) {diff --git a/src/public/app/widgets/search_options/ancestor.js b/src/public/app/widgets/search_options/ancestor.jsindex 8a56057f95..76450cd3fe 100644--- a/src/public/app/widgets/search_options/ancestor.js+++ b/src/public/app/widgets/search_options/ancestor.js@@ -6,42 +6,42 @@ const TPL = `<tr><td colspan="2"><div style="display: flex; align-items: center;">- <div style="margin-right: 10px">${t('ancestor.label')}:</div>+ <div style="margin-right: 10px">${t("ancestor.label")}:</div><div class="input-group" style="flex-shrink: 2">- <input class="ancestor form-control" placeholder="${t('ancestor.placeholder')}">+ <input class="ancestor form-control" placeholder="${t("ancestor.placeholder")}"></div>- <div style="margin-left: 10px; margin-right: 10px">${t('ancestor.depth_label')}:</div>+ <div style="margin-left: 10px; margin-right: 10px">${t("ancestor.depth_label")}:</div><select name="depth" class="form-select d-inline ancestor-depth" style="flex-shrink: 3">- <option value="">${t('ancestor.depth_doesnt_matter')}</option>- <option value="eq1">${t('ancestor.depth_eq', {count: 1})} (${t('ancestor.direct_children')})</option>- <option value="eq2">${t('ancestor.depth_eq', {count: 2})}</option>- <option value="eq3">${t('ancestor.depth_eq', {count: 3})}</option>- <option value="eq4">${t('ancestor.depth_eq', {count: 4})}</option>- <option value="eq5">${t('ancestor.depth_eq', {count: 5})}</option>- <option value="eq6">${t('ancestor.depth_eq', {count: 6})}</option>- <option value="eq7">${t('ancestor.depth_eq', {count: 7})}</option>- <option value="eq8">${t('ancestor.depth_eq', {count: 8})}</option>- <option value="eq9">${t('ancestor.depth_eq', {count: 9})}</option>- <option value="gt0">${t('ancestor.depth_gt', {count: 0})}</option>- <option value="gt1">${t('ancestor.depth_gt', {count: 1})}</option>- <option value="gt2">${t('ancestor.depth_gt', {count: 2})}</option>- <option value="gt3">${t('ancestor.depth_gt', {count: 3})}</option>- <option value="gt4">${t('ancestor.depth_gt', {count: 4})}</option>- <option value="gt5">${t('ancestor.depth_gt', {count: 5})}</option>- <option value="gt6">${t('ancestor.depth_gt', {count: 6})}</option>- <option value="gt7">${t('ancestor.depth_gt', {count: 7})}</option>- <option value="gt8">${t('ancestor.depth_gt', {count: 8})}</option>- <option value="gt9">${t('ancestor.depth_gt', {count: 9})}</option>- <option value="lt2">${t('ancestor.depth_lt', {count: 2})}</option>- <option value="lt3">${t('ancestor.depth_lt', {count: 3})}</option>- <option value="lt4">${t('ancestor.depth_lt', {count: 4})}</option>- <option value="lt5">${t('ancestor.depth_lt', {count: 5})}</option>- <option value="lt6">${t('ancestor.depth_lt', {count: 6})}</option>- <option value="lt7">${t('ancestor.depth_lt', {count: 7})}</option>- <option value="lt8">${t('ancestor.depth_lt', {count: 8})}</option>- <option value="lt9">${t('ancestor.depth_lt', {count: 9})}</option>+ <option value="">${t("ancestor.depth_doesnt_matter")}</option>+ <option value="eq1">${t("ancestor.depth_eq", { count: 1 })} (${t("ancestor.direct_children")})</option>+ <option value="eq2">${t("ancestor.depth_eq", { count: 2 })}</option>+ <option value="eq3">${t("ancestor.depth_eq", { count: 3 })}</option>+ <option value="eq4">${t("ancestor.depth_eq", { count: 4 })}</option>+ <option value="eq5">${t("ancestor.depth_eq", { count: 5 })}</option>+ <option value="eq6">${t("ancestor.depth_eq", { count: 6 })}</option>+ <option value="eq7">${t("ancestor.depth_eq", { count: 7 })}</option>+ <option value="eq8">${t("ancestor.depth_eq", { count: 8 })}</option>+ <option value="eq9">${t("ancestor.depth_eq", { count: 9 })}</option>+ <option value="gt0">${t("ancestor.depth_gt", { count: 0 })}</option>+ <option value="gt1">${t("ancestor.depth_gt", { count: 1 })}</option>+ <option value="gt2">${t("ancestor.depth_gt", { count: 2 })}</option>+ <option value="gt3">${t("ancestor.depth_gt", { count: 3 })}</option>+ <option value="gt4">${t("ancestor.depth_gt", { count: 4 })}</option>+ <option value="gt5">${t("ancestor.depth_gt", { count: 5 })}</option>+ <option value="gt6">${t("ancestor.depth_gt", { count: 6 })}</option>+ <option value="gt7">${t("ancestor.depth_gt", { count: 7 })}</option>+ <option value="gt8">${t("ancestor.depth_gt", { count: 8 })}</option>+ <option value="gt9">${t("ancestor.depth_gt", { count: 9 })}</option>+ <option value="lt2">${t("ancestor.depth_lt", { count: 2 })}</option>+ <option value="lt3">${t("ancestor.depth_lt", { count: 3 })}</option>+ <option value="lt4">${t("ancestor.depth_lt", { count: 4 })}</option>+ <option value="lt5">${t("ancestor.depth_lt", { count: 5 })}</option>+ <option value="lt6">${t("ancestor.depth_lt", { count: 6 })}</option>+ <option value="lt7">${t("ancestor.depth_lt", { count: 7 })}</option>+ <option value="lt8">${t("ancestor.depth_lt", { count: 8 })}</option>+ <option value="lt9">${t("ancestor.depth_lt", { count: 9 })}</option></select></div></td>@@ -51,45 +51,48 @@ const TPL = `</tr>`;export default class Ancestor extends AbstractSearchOption {- static get optionName() { return "ancestor" };- static get attributeType() { return "relation" };+ static get optionName() {+ return "ancestor";+ }+ static get attributeType() {+ return "relation";+ }static async create(noteId) {- await AbstractSearchOption.setAttribute(noteId, 'relation', 'ancestor', 'root');+ await AbstractSearchOption.setAttribute(noteId, "relation", "ancestor", "root");}doRender() {const $option = $(TPL);- const $ancestor = $option.find('.ancestor');- const $ancestorDepth = $option.find('.ancestor-depth');+ const $ancestor = $option.find(".ancestor");+ const $ancestorDepth = $option.find(".ancestor-depth");noteAutocompleteService.initNoteAutocomplete($ancestor);- $ancestor.on('autocomplete:closed', async () => {+ $ancestor.on("autocomplete:closed", async () => {const ancestorNoteId = $ancestor.getSelectedNoteId();if (ancestorNoteId) {- await this.setAttribute('relation', 'ancestor', ancestorNoteId);+ await this.setAttribute("relation", "ancestor", ancestorNoteId);}});- $ancestorDepth.on('change', async () => {+ $ancestorDepth.on("change", async () => {const ancestorDepth = $ancestorDepth.val();if (ancestorDepth) {- await this.setAttribute('label', 'ancestorDepth', ancestorDepth);- }- else {- await this.deleteAttribute('label', 'ancestorDepth');+ await this.setAttribute("label", "ancestorDepth", ancestorDepth);+ } else {+ await this.deleteAttribute("label", "ancestorDepth");}});- const ancestorNoteId = this.note.getRelationValue('ancestor');+ const ancestorNoteId = this.note.getRelationValue("ancestor");- if (ancestorNoteId !== 'root') {+ if (ancestorNoteId !== "root") {$ancestor.setNote(ancestorNoteId);}- const ancestorDepth = this.note.getLabelValue('ancestorDepth');+ const ancestorDepth = this.note.getLabelValue("ancestorDepth");if (ancestorDepth) {$ancestorDepth.val(ancestorDepth);@@ -99,7 +102,7 @@ export default class Ancestor extends AbstractSearchOption {}async deleteOption() {- await this.deleteAttribute('label', 'ancestorDepth');+ await this.deleteAttribute("label", "ancestorDepth");await super.deleteOption();}diff --git a/src/public/app/widgets/search_options/debug.js b/src/public/app/widgets/search_options/debug.jsindex 906c6590d2..9a732507b2 100644--- a/src/public/app/widgets/search_options/debug.js+++ b/src/public/app/widgets/search_options/debug.js@@ -20,11 +20,15 @@ const TPL = `</tr>`;export default class Debug extends AbstractSearchOption {- static get optionName() { return "debug" };- static get attributeType() { return "label" };+ static get optionName() {+ return "debug";+ }+ static get attributeType() {+ return "label";+ }static async create(noteId) {- await AbstractSearchOption.setAttribute(noteId,'label', 'debug');+ await AbstractSearchOption.setAttribute(noteId, "label", "debug");}doRender() {diff --git a/src/public/app/widgets/search_options/fast_search.js b/src/public/app/widgets/search_options/fast_search.jsindex dc4e828a03..b49e0eee69 100644--- a/src/public/app/widgets/search_options/fast_search.js+++ b/src/public/app/widgets/search_options/fast_search.js@@ -5,13 +5,13 @@ const TPL = `<tr data-search-option-conf="fastSearch"><td colSpan="2"><span class="bx bx-run"></span>- ${t('fast_search.fast_search')}+ ${t("fast_search.fast_search")}</td><td class="button-column"><div class="dropdown help-dropdown"><span class="bx bx-help-circle icon-action" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span><div class="dropdown-menu dropdown-menu-right p-4">- ${t('fast_search.description')}+ ${t("fast_search.description")}</div></div><span class="bx bx-x icon-action search-option-del"></span>@@ -19,11 +19,15 @@ const TPL = `</tr>`;export default class FastSearch extends AbstractSearchOption {- static get optionName() { return "fastSearch" };- static get attributeType() { return "label" };+ static get optionName() {+ return "fastSearch";+ }+ static get attributeType() {+ return "label";+ }static async create(noteId) {- await AbstractSearchOption.setAttribute(noteId,'label', 'fastSearch');+ await AbstractSearchOption.setAttribute(noteId, "label", "fastSearch");}doRender() {diff --git a/src/public/app/widgets/search_options/include_archived_notes.js b/src/public/app/widgets/search_options/include_archived_notes.jsindex 204545bf54..0e461d05ec 100644--- a/src/public/app/widgets/search_options/include_archived_notes.js+++ b/src/public/app/widgets/search_options/include_archived_notes.js@@ -5,7 +5,7 @@ const TPL = `<tr data-search-option-conf="includeArchivedNotes"><td colspan="2"><span class="bx bx-archive"></span>- ${t('include_archived_notes.include_archived_notes')}+ ${t("include_archived_notes.include_archived_notes")}</td><td class="button-column"><span class="bx bx-x icon-action search-option-del"></span>@@ -13,11 +13,15 @@ const TPL = `</tr>`;export default class IncludeArchivedNotes extends AbstractSearchOption {- static get optionName() { return "includeArchivedNotes" };- static get attributeType() { return "label" };+ static get optionName() {+ return "includeArchivedNotes";+ }+ static get attributeType() {+ return "label";+ }static async create(noteId) {- await AbstractSearchOption.setAttribute(noteId,'label', 'includeArchivedNotes');+ await AbstractSearchOption.setAttribute(noteId, "label", "includeArchivedNotes");}doRender() {diff --git a/src/public/app/widgets/search_options/limit.js b/src/public/app/widgets/search_options/limit.jsindex 48beaede0c..cc162cc64f 100644--- a/src/public/app/widgets/search_options/limit.js+++ b/src/public/app/widgets/search_options/limit.js@@ -5,7 +5,7 @@ const TPL = `<tr data-search-option-conf="limit"><td class="title-column"><span class="bx bx-stop"></span>- ${t('limit.limit')}+ ${t("limit.limit")}</td><td><input name="limit" class="form-control" type="number" min="1" step="1" />@@ -14,7 +14,7 @@ const TPL = `<div class="dropdown help-dropdown"><span class="bx bx-help-circle icon-action" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span><div class="dropdown-menu dropdown-menu-right p-4">- ${t('limit.take_first_x_results')}+ ${t("limit.take_first_x_results")}</div></div>@@ -23,20 +23,24 @@ const TPL = `</tr>`;export default class Limit extends AbstractSearchOption {- static get optionName() { return "limit" };- static get attributeType() { return "label" };+ static get optionName() {+ return "limit";+ }+ static get attributeType() {+ return "label";+ }static async create(noteId) {- await AbstractSearchOption.setAttribute(noteId, 'label', 'limit', '10');+ await AbstractSearchOption.setAttribute(noteId, "label", "limit", "10");}doRender() {const $option = $(TPL);- this.$limit = $option.find('input[name=limit]');- this.$limit.on('change', () => this.update());- this.$limit.on('input', () => this.update());- this.$limit.val(this.note.getLabelValue('limit'));+ this.$limit = $option.find("input[name=limit]");+ this.$limit.on("change", () => this.update());+ this.$limit.on("input", () => this.update());+ this.$limit.val(this.note.getLabelValue("limit"));return $option;}@@ -44,6 +48,6 @@ export default class Limit extends AbstractSearchOption {async update() {const limit = this.$limit.val();- await this.setAttribute('label', 'limit', limit);+ await this.setAttribute("label", "limit", limit);}}diff --git a/src/public/app/widgets/search_options/order_by.js b/src/public/app/widgets/search_options/order_by.jsindex acc812a948..3a27854c8e 100644--- a/src/public/app/widgets/search_options/order_by.js+++ b/src/public/app/widgets/search_options/order_by.js@@ -5,29 +5,29 @@ const TPL = `<tr data-search-option-conf="orderBy"><td class="title-column"><span class="bx bx-arrow-from-top"></span>- ${t('order_by.order_by')}+ ${t("order_by.order_by")}</td><td><select name="orderBy" class="form-control w-auto d-inline">- <option value="relevancy">${t('order_by.relevancy')}</option>- <option value="title">${t('order_by.title')}</option>- <option value="dateCreated">${t('order_by.date_created')}</option>- <option value="dateModified">${t('order_by.date_modified')}</option>- <option value="contentSize">${t('order_by.content_size')}</option>- <option value="contentAndAttachmentsSize">${t('order_by.content_and_attachments_size')}</option>- <option value="contentAndAttachmentsAndRevisionsSize">${t('order_by.content_and_attachments_and_revisions_size')}</option>- <option value="revisionCount">${t('order_by.revision_count')}</option>- <option value="childrenCount">${t('order_by.children_count')}</option>- <option value="parentCount">${t('order_by.parent_count')}</option>- <option value="ownedLabelCount">${t('order_by.owned_label_count')}</option>- <option value="ownedRelationCount">${t('order_by.owned_relation_count')}</option>- <option value="targetRelationCount">${t('order_by.target_relation_count')}</option>- <option value="random">${t('order_by.random')}</option>+ <option value="relevancy">${t("order_by.relevancy")}</option>+ <option value="title">${t("order_by.title")}</option>+ <option value="dateCreated">${t("order_by.date_created")}</option>+ <option value="dateModified">${t("order_by.date_modified")}</option>+ <option value="contentSize">${t("order_by.content_size")}</option>+ <option value="contentAndAttachmentsSize">${t("order_by.content_and_attachments_size")}</option>+ <option value="contentAndAttachmentsAndRevisionsSize">${t("order_by.content_and_attachments_and_revisions_size")}</option>+ <option value="revisionCount">${t("order_by.revision_count")}</option>+ <option value="childrenCount">${t("order_by.children_count")}</option>+ <option value="parentCount">${t("order_by.parent_count")}</option>+ <option value="ownedLabelCount">${t("order_by.owned_label_count")}</option>+ <option value="ownedRelationCount">${t("order_by.owned_relation_count")}</option>+ <option value="targetRelationCount">${t("order_by.target_relation_count")}</option>+ <option value="random">${t("order_by.random")}</option></select><select name="orderDirection" class="form-control w-auto d-inline">- <option value="asc">${t('order_by.asc')}</option>- <option value="desc">${t('order_by.desc')}</option>+ <option value="asc">${t("order_by.asc")}</option>+ <option value="desc">${t("order_by.desc")}</option></select></td><td class="button-column">@@ -36,38 +36,42 @@ const TPL = `</tr>`;export default class OrderBy extends AbstractSearchOption {- static get optionName() { return "orderBy" };- static get attributeType() { return "label" };+ static get optionName() {+ return "orderBy";+ }+ static get attributeType() {+ return "label";+ }static async create(noteId) {- await AbstractSearchOption.setAttribute(noteId, 'label', 'orderBy', 'relevancy');- await AbstractSearchOption.setAttribute(noteId, 'label', 'orderDirection', 'asc');+ await AbstractSearchOption.setAttribute(noteId, "label", "orderBy", "relevancy");+ await AbstractSearchOption.setAttribute(noteId, "label", "orderDirection", "asc");}doRender() {const $option = $(TPL);- const $orderBy = $option.find('select[name=orderBy]');- $orderBy.on('change', async () => {+ const $orderBy = $option.find("select[name=orderBy]");+ $orderBy.on("change", async () => {const orderBy = $orderBy.val();- await this.setAttribute('label', 'orderBy', orderBy);+ await this.setAttribute("label", "orderBy", orderBy);});- $orderBy.val(this.note.getLabelValue('orderBy'));+ $orderBy.val(this.note.getLabelValue("orderBy"));- const $orderDirection = $option.find('select[name=orderDirection]');- $orderDirection.on('change', async () => {+ const $orderDirection = $option.find("select[name=orderDirection]");+ $orderDirection.on("change", async () => {const orderDirection = $orderDirection.val();- await this.setAttribute('label', 'orderDirection', orderDirection);+ await this.setAttribute("label", "orderDirection", orderDirection);});- $orderDirection.val(this.note.getLabelValue('orderDirection') || 'asc');+ $orderDirection.val(this.note.getLabelValue("orderDirection") || "asc");return $option;}async deleteOption() {- await this.deleteAttribute('label', 'orderDirection');+ await this.deleteAttribute("label", "orderDirection");await super.deleteOption();}diff --git a/src/public/app/widgets/search_options/search_script.js b/src/public/app/widgets/search_options/search_script.jsindex 8c59f49475..ef9b730170 100644--- a/src/public/app/widgets/search_options/search_script.js+++ b/src/public/app/widgets/search_options/search_script.js@@ -5,26 +5,26 @@ import { t } from "../../services/i18n.js";const TPL = `<tr><td class="title-column">- ${t('search_script.title')}+ ${t("search_script.title")}</td><td><div class="input-group">- <input class="search-script form-control" placeholder="${t('search_script.placeholder')}">+ <input class="search-script form-control" placeholder="${t("search_script.placeholder")}"></div></td><td class="button-column"><div class="dropdown help-dropdown"><span class="bx bx-help-circle icon-action" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span><div class="dropdown-menu dropdown-menu-right p-4">- <p>${t('search_script.description1')}</p>+ <p>${t("search_script.description1")}</p>- <p>${t('search_script.description2')}</p>+ <p>${t("search_script.description2")}</p>- <p>${t('search_script.example_title')}</p>+ <p>${t("search_script.example_title")}</p>- <pre>${t('search_script.example_code')}</pre>+ <pre>${t("search_script.example_code")}</pre>- ${t('search_script.note')}+ ${t("search_script.note")}</div></div>@@ -33,29 +33,33 @@ const TPL = `</tr>`;export default class SearchScript extends AbstractSearchOption {- static get optionName() { return "searchScript" };- static get attributeType() { return "relation" };+ static get optionName() {+ return "searchScript";+ }+ static get attributeType() {+ return "relation";+ }static async create(noteId) {- await AbstractSearchOption.setAttribute(noteId, 'relation', 'searchScript', 'root');+ await AbstractSearchOption.setAttribute(noteId, "relation", "searchScript", "root");}doRender() {const $option = $(TPL);- const $searchScript = $option.find('.search-script');- noteAutocompleteService.initNoteAutocomplete($searchScript, {allowCreatingNotes: true});+ const $searchScript = $option.find(".search-script");+ noteAutocompleteService.initNoteAutocomplete($searchScript, { allowCreatingNotes: true });- $searchScript.on('autocomplete:closed', async () => {+ $searchScript.on("autocomplete:closed", async () => {const searchScriptNoteId = $searchScript.getSelectedNoteId();if (searchScriptNoteId) {- await this.setAttribute('relation', 'searchScript', searchScriptNoteId);+ await this.setAttribute("relation", "searchScript", searchScriptNoteId);}});- const searchScriptNoteId = this.note.getRelationValue('searchScript');+ const searchScriptNoteId = this.note.getRelationValue("searchScript");- if (searchScriptNoteId !== 'root') {+ if (searchScriptNoteId !== "root") {$searchScript.setNote(searchScriptNoteId);}diff --git a/src/public/app/widgets/search_options/search_string.js b/src/public/app/widgets/search_options/search_string.jsindex f71df76ac8..3d355ce179 100644--- a/src/public/app/widgets/search_options/search_string.js+++ b/src/public/app/widgets/search_options/search_string.js@@ -7,24 +7,24 @@ import { t } from "../../services/i18n.js";const TPL = `<tr>- <td class="title-column">${t('search_string.title_column')}</td>+ <td class="title-column">${t("search_string.title_column")}</td><td>- <textarea class="form-control search-string" placeholder="${t('search_string.placeholder')}"></textarea>+ <textarea class="form-control search-string" placeholder="${t("search_string.placeholder")}"></textarea></td><td class="button-column"><div class="dropdown help-dropdown"><span class="bx bx-help-circle icon-action" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></span><div class="dropdown-menu dropdown-menu-right p-4">- <strong>${t('search_string.search_syntax')}</strong> - ${t('search_string.also_see')} <a href="#" data-help-page="search.html">${t('search_string.complete_help')}</a>+ <strong>${t("search_string.search_syntax")}</strong> - ${t("search_string.also_see")} <a href="#" data-help-page="search.html">${t("search_string.complete_help")}</a><ul style="marigin-bottom: 0;">- <li>${t('search_string.full_text_search')}</li>- <li><code>#abc</code> - ${t('search_string.label_abc')}</li>- <li><code>#year = 2019</code> - ${t('search_string.label_year')}</li>- <li><code>#rock #pop</code> - ${t('search_string.label_rock_pop')}</li>- <li><code>#rock or #pop</code> - ${t('search_string.label_rock_or_pop')}</li>- <li><code>#year <= 2000</code> - ${t('search_string.label_year_comparison')}</li>- <li><code>note.dateCreated >= MONTH-1</code> - ${t('search_string.label_date_created')}</li>+ <li>${t("search_string.full_text_search")}</li>+ <li><code>#abc</code> - ${t("search_string.label_abc")}</li>+ <li><code>#year = 2019</code> - ${t("search_string.label_year")}</li>+ <li><code>#rock #pop</code> - ${t("search_string.label_rock_pop")}</li>+ <li><code>#rock or #pop</code> - ${t("search_string.label_rock_or_pop")}</li>+ <li><code>#year <= 2000</code> - ${t("search_string.label_year_comparison")}</li>+ <li><code>note.dateCreated >= MONTH-1</code> - ${t("search_string.label_date_created")}</li></ul></div></div>@@ -34,32 +34,36 @@ const TPL = `</tr>`;export default class SearchString extends AbstractSearchOption {- static get optionName() { return "searchString" };- static get attributeType() { return "label" };+ static get optionName() {+ return "searchString";+ }+ static get attributeType() {+ return "label";+ }static async create(noteId) {- await AbstractSearchOption.setAttribute(noteId, 'label', 'searchString');+ await AbstractSearchOption.setAttribute(noteId, "label", "searchString");}doRender() {const $option = $(TPL);- this.$searchString = $option.find('.search-string');- this.$searchString.on('input', () => this.spacedUpdate.scheduleUpdate());+ this.$searchString = $option.find(".search-string");+ this.$searchString.on("input", () => this.spacedUpdate.scheduleUpdate());- shortcutService.bindElShortcut(this.$searchString, 'return', async () => {+ shortcutService.bindElShortcut(this.$searchString, "return", async () => {// this also in effect disallows new lines in query string.// on one hand, this makes sense since search string is a label// on the other hand, it could be nice for structuring long search string. It's probably a niche case though.await this.spacedUpdate.updateNowIfNecessary();- this.triggerCommand('refreshResults');+ this.triggerCommand("refreshResults");});this.spacedUpdate = new SpacedUpdate(async () => {const searchString = this.$searchString.val();appContext.lastSearchString = searchString;- await this.setAttribute('label', 'searchString', searchString);+ await this.setAttribute("label", "searchString", searchString);if (this.note.title.startsWith(t("search_string.search_prefix"))) {await server.put(`notes/${this.note.noteId}/title`, {@@ -68,16 +72,16 @@ export default class SearchString extends AbstractSearchOption {}}, 1000);- this.$searchString.val(this.note.getLabelValue('searchString'));+ this.$searchString.val(this.note.getLabelValue("searchString"));return $option;}showSearchErrorEvent({ error }) {let tooltip = new bootstrap.Tooltip(this.$searchString, {- trigger: 'manual',- title: `${t('search_string.error', { error })}`,- placement: 'bottom'+ trigger: "manual",+ title: `${t("search_string.error", { error })}`,+ placement: "bottom"});tooltip.show();@@ -86,7 +90,10 @@ export default class SearchString extends AbstractSearchOption {}focusOnSearchDefinitionEvent() {- this.$searchString.val(this.$searchString.val().trim() || appContext.lastSearchString).focus().select();+ this.$searchString+ .val(this.$searchString.val().trim() || appContext.lastSearchString)+ .focus()+ .select();this.spacedUpdate.scheduleUpdate();}}diff --git a/src/public/app/widgets/search_result.js b/src/public/app/widgets/search_result.jsindex 390ecdae83..d18efff18d 100644--- a/src/public/app/widgets/search_result.js+++ b/src/public/app/widgets/search_result.js@@ -23,11 +23,11 @@ const TPL = `</style><div class="search-no-results alert alert-info">- ${t('search_result.no_notes_found')}+ ${t("search_result.no_notes_found")}</div><div class="search-not-executed-yet alert alert-info">- ${t('search_result.search_not_executed')}+ ${t("search_result.search_not_executed")}</div><div class="search-result-widget-content">@@ -36,16 +36,15 @@ const TPL = `export default class SearchResultWidget extends NoteContextAwareWidget {isEnabled() {- return super.isEnabled()- && this.note.type === 'search';+ return super.isEnabled() && this.note.type === "search";}doRender() {this.$widget = $(TPL);this.contentSized();- this.$content = this.$widget.find('.search-result-widget-content');- this.$noResults = this.$widget.find('.search-no-results');- this.$notExecutedYet = this.$widget.find('.search-not-executed-yet');+ this.$content = this.$widget.find(".search-result-widget-content");+ this.$noResults = this.$widget.find(".search-no-results");+ this.$notExecutedYet = this.$widget.find(".search-not-executed-yet");}async refreshWithNote(note) {@@ -57,7 +56,7 @@ export default class SearchResultWidget extends NoteContextAwareWidget {await noteListRenderer.renderList();}- searchRefreshedEvent({ntxId}) {+ searchRefreshedEvent({ ntxId }) {if (!this.isNoteContext(ntxId)) {return;}@@ -65,7 +64,7 @@ export default class SearchResultWidget extends NoteContextAwareWidget {this.refresh();}- notesReloadedEvent({noteIds}) {+ notesReloadedEvent({ noteIds }) {if (noteIds.includes(this.noteId)) {this.refresh();}diff --git a/src/public/app/widgets/shared_info.js b/src/public/app/widgets/shared_info.jsindex e6a6ad33e3..da20f419b6 100644--- a/src/public/app/widgets/shared_info.js+++ b/src/public/app/widgets/shared_info.js@@ -19,7 +19,7 @@ const TPL = `export default class SharedInfoWidget extends NoteContextAwareWidget {isEnabled() {- return super.isEnabled() && this.noteId !== '_share' && this.note.hasAncestor('_share');+ return super.isEnabled() && this.noteId !== "_share" && this.note.hasAncestor("_share");}doRender() {@@ -38,10 +38,9 @@ export default class SharedInfoWidget extends NoteContextAwareWidget {if (syncServerHost) {link = `${syncServerHost}/share/${shareId}`;this.$sharedText.text(t("shared_info.shared_publicly"));- }- else {+ } else {let host = location.host;- if (host.endsWith('/')) {+ if (host.endsWith("/")) {// seems like IE has trailing slash// https://github.com/zadam/trilium/issues/3782host = host.substr(0, host.length - 1);@@ -55,18 +54,17 @@ export default class SharedInfoWidget extends NoteContextAwareWidget {}getShareId(note) {- if (note.hasOwnedLabel('shareRoot')) {- return '';+ if (note.hasOwnedLabel("shareRoot")) {+ return "";}- return note.getOwnedLabelValue('shareAlias') || note.noteId;+ return note.getOwnedLabelValue("shareAlias") || note.noteId;}- entitiesReloadedEvent({loadResults}) {- if (loadResults.getAttributeRows().find(attr => attr.name.startsWith('_share') && attributeService.isAffecting(attr, this.note))) {+ entitiesReloadedEvent({ loadResults }) {+ if (loadResults.getAttributeRows().find((attr) => attr.name.startsWith("_share") && attributeService.isAffecting(attr, this.note))) {this.refresh();- }- else if (loadResults.getBranchRows().find(branch => branch.noteId === this.noteId)) {+ } else if (loadResults.getBranchRows().find((branch) => branch.noteId === this.noteId)) {this.refresh();}}diff --git a/src/public/app/widgets/shared_switch.js b/src/public/app/widgets/shared_switch.jsindex 2a51eddc87..7e8766ec45 100644--- a/src/public/app/widgets/shared_switch.js+++ b/src/public/app/widgets/shared_switch.js@@ -8,9 +8,7 @@ import { t } from "../services/i18n.js";export default class SharedSwitchWidget extends SwitchWidget {isEnabled() {- return super.isEnabled()- && !['root', '_share', '_hidden'].includes(this.noteId)- && !this.noteId.startsWith('_options');+ return super.isEnabled() && !["root", "_share", "_hidden"].includes(this.noteId) && !this.noteId.startsWith("_options");}doRender() {@@ -23,24 +21,24 @@ export default class SharedSwitchWidget extends SwitchWidget {this.$switchOffButton.attr("title", t("shared_switch.toggle-off-title"));this.$helpButton.attr("data-help-page", "sharing.html").show();- this.$helpButton.on('click', e => utils.openHelp($(e.target)));+ this.$helpButton.on("click", (e) => utils.openHelp($(e.target)));}async switchOn() {- await branchService.cloneNoteToParentNote(this.noteId, '_share');+ await branchService.cloneNoteToParentNote(this.noteId, "_share");syncService.syncNow(true);}async switchOff() {- const shareBranch = this.note.getParentBranches().find(b => b.parentNoteId === '_share');+ const shareBranch = this.note.getParentBranches().find((b) => b.parentNoteId === "_share");if (!shareBranch) {return;}if (this.note.getParentBranches().length === 1) {- if (!await dialogService.confirm(t("shared_switch.shared-branch"))) {+ if (!(await dialogService.confirm(t("shared_switch.shared-branch")))) {return;}}@@ -51,8 +49,8 @@ export default class SharedSwitchWidget extends SwitchWidget {}async refreshWithNote(note) {- const isShared = note.hasAncestor('_share');- const canBeUnshared = isShared && note.getParentBranches().find(b => b.parentNoteId === '_share');+ const isShared = note.hasAncestor("_share");+ const canBeUnshared = isShared && note.getParentBranches().find((b) => b.parentNoteId === "_share");const switchDisabled = isShared && !canBeUnshared;this.$switchOn.toggle(!isShared);@@ -61,15 +59,14 @@ export default class SharedSwitchWidget extends SwitchWidget {if (switchDisabled) {this.$widget.attr("title", t("shared_switch.inherited"));this.$switchOff.addClass("switch-disabled");- }- else {+ } else {this.$widget.removeAttr("title");this.$switchOff.removeClass("switch-disabled");}}- entitiesReloadedEvent({loadResults}) {- if (loadResults.getBranchRows().find(b => b.noteId === this.noteId)) {+ entitiesReloadedEvent({ loadResults }) {+ if (loadResults.getBranchRows().find((b) => b.noteId === this.noteId)) {this.refresh();}}diff --git a/src/public/app/widgets/spacer.ts b/src/public/app/widgets/spacer.tsindex 67ea42e3f0..83cf23bf84 100644--- a/src/public/app/widgets/spacer.ts+++ b/src/public/app/widgets/spacer.ts@@ -7,7 +7,6 @@ import utils from "../services/utils.js";const TPL = `<div class="spacer"></div>`;export default class SpacerWidget extends BasicWidget {-private baseSize: number;private growthFactor: number;@@ -24,16 +23,14 @@ export default class SpacerWidget extends BasicWidget {this.$widget.css("flex-grow", this.growthFactor);this.$widget.css("flex-shrink", 1000);- this.$widget.on("contextmenu", e => {+ this.$widget.on("contextmenu", (e) => {this.$widget.tooltip("hide");contextMenu.show({x: e.pageX,y: e.pageY,- items: [- {title: t("spacer.configure_launchbar"), command: "showLaunchBarSubtree", uiIcon: "bx " + (utils.isMobile() ? "bx-mobile" : "bx-sidebar")}- ],- selectMenuItemHandler: ({command}) => {+ items: [{ title: t("spacer.configure_launchbar"), command: "showLaunchBarSubtree", uiIcon: "bx " + (utils.isMobile() ? "bx-mobile" : "bx-sidebar") }],+ selectMenuItemHandler: ({ command }) => {if (command) {appContext.triggerCommand(command);}diff --git a/src/public/app/widgets/sql_result.js b/src/public/app/widgets/sql_result.jsindex f2842ff05e..185837b77a 100644--- a/src/public/app/widgets/sql_result.js+++ b/src/public/app/widgets/sql_result.js@@ -10,7 +10,7 @@ const TPL = `</style><div class="sql-query-no-rows alert alert-info" style="display: none;">- ${t('sql_result.no_rows')}+ ${t("sql_result.no_rows")}</div><div class="sql-console-result-container"></div>@@ -18,19 +18,17 @@ const TPL = `export default class SqlResultWidget extends NoteContextAwareWidget {isEnabled() {- return this.note- && this.note.mime === 'text/x-sqlite;schema=trilium'- && super.isEnabled();+ return this.note && this.note.mime === "text/x-sqlite;schema=trilium" && super.isEnabled();}doRender() {this.$widget = $(TPL);- this.$resultContainer = this.$widget.find('.sql-console-result-container');- this.$noRowsAlert = this.$widget.find('.sql-query-no-rows');+ this.$resultContainer = this.$widget.find(".sql-console-result-container");+ this.$noRowsAlert = this.$widget.find(".sql-query-no-rows");}- async sqlQueryResultsEvent({ntxId, results}) {+ async sqlQueryResultsEvent({ ntxId, results }) {if (!this.isNoteContext(ntxId)) {return;}@@ -41,11 +39,12 @@ export default class SqlResultWidget extends NoteContextAwareWidget {this.$resultContainer.empty();for (const rows of results) {- if (typeof rows === 'object' && !Array.isArray(rows)) {+ if (typeof rows === "object" && !Array.isArray(rows)) {// inserts, updates- this.$resultContainer.empty().show().append(- $("<pre>").text(JSON.stringify(rows, null, '\t'))- );+ this.$resultContainer+ .empty()+ .show()+ .append($("<pre>").text(JSON.stringify(rows, null, "\t")));continue;}diff --git a/src/public/app/widgets/sql_table_schemas.js b/src/public/app/widgets/sql_table_schemas.jsindex 61f988b7dc..e5fafb01fa 100644--- a/src/public/app/widgets/sql_table_schemas.js+++ b/src/public/app/widgets/sql_table_schemas.js@@ -34,22 +34,20 @@ const TPL = `}</style>- ${t('sql_table_schemas.tables')}:+ ${t("sql_table_schemas.tables")}:<span class="sql-table-schemas"></span></div>`;export default class SqlTableSchemasWidget extends NoteContextAwareWidget {isEnabled() {- return this.note- && this.note.mime === 'text/x-sqlite;schema=trilium'- && super.isEnabled();+ return this.note && this.note.mime === "text/x-sqlite;schema=trilium" && super.isEnabled();}doRender() {this.$widget = $(TPL);this.contentSized();- this.$sqlConsoleTableSchemas = this.$widget.find('.sql-table-schemas');+ this.$sqlConsoleTableSchemas = this.$widget.find(".sql-table-schemas");}async refreshWithNote(note) {@@ -59,7 +57,7 @@ export default class SqlTableSchemasWidget extends NoteContextAwareWidget {this.tableSchemasShown = true;- const tableSchema = await server.get('sql/schema');+ const tableSchema = await server.get("sql/schema");for (const table of tableSchema) {const $tableLink = $('<button class="btn">').text(table.name);@@ -67,19 +65,15 @@ export default class SqlTableSchemasWidget extends NoteContextAwareWidget {const $table = $('<table class="table-schema">');for (const column of table.columns) {- $table.append(- $("<tr>")- .append($("<td>").text(column.name))- .append($("<td>").text(column.type))- );+ $table.append($("<tr>").append($("<td>").text(column.name)).append($("<td>").text(column.type)));}this.$sqlConsoleTableSchemas.append($tableLink).append(" ");$tableLink.tooltip({html: true,- placement: 'bottom',- boundary: 'window',+ placement: "bottom",+ boundary: "window",title: $table[0].outerHTML,sanitize: false});diff --git a/src/public/app/widgets/switch.js b/src/public/app/widgets/switch.jsindex c59126f812..3e76cc6328 100644--- a/src/public/app/widgets/switch.js+++ b/src/public/app/widgets/switch.js@@ -102,13 +102,13 @@ export default class SwitchWidget extends NoteContextAwareWidget {this.$switchOnName = this.$widget.find(".switch-on-name");this.$switchOnButton = this.$widget.find(".switch-on-button");- this.$switchOnButton.on('click', () => this.toggle(true));+ this.$switchOnButton.on("click", () => this.toggle(true));this.$switchOff = this.$widget.find(".switch-off");this.$switchOffName = this.$widget.find(".switch-off-name");this.$switchOffButton = this.$widget.find(".switch-off-button");- this.$switchOffButton.on('click', () => this.toggle(false));+ this.$switchOffButton.on("click", () => this.toggle(false));this.$helpButton = this.$widget.find(".switch-help-button");}diff --git a/src/public/app/widgets/sync_status.js b/src/public/app/widgets/sync_status.jsindex 8fea1f1110..dc7d8da267 100644--- a/src/public/app/widgets/sync_status.js+++ b/src/public/app/widgets/sync_status.js@@ -73,7 +73,7 @@ export default class SyncStatusWidget extends BasicWidget {constructor() {super();- this.syncState = 'unknown';+ this.syncState = "unknown";this.allChangesPushed = false;this.settings = {titlePlacement: "right"@@ -84,14 +84,13 @@ export default class SyncStatusWidget extends BasicWidget {this.$widget = $(TPL);this.$widget.hide();- this.$widget.find('.sync-status-icon:not(.sync-status-in-progress)')- .on('click', () => syncService.syncNow());+ this.$widget.find(".sync-status-icon:not(.sync-status-in-progress)").on("click", () => syncService.syncNow());- ws.subscribeToMessages(message => this.processMessage(message));+ ws.subscribeToMessages((message) => this.processMessage(message));}showIcon(className) {- if (!options.get('syncServerHost')) {+ if (!options.get("syncServerHost")) {this.toggleInt(false);return;}@@ -99,41 +98,37 @@ export default class SyncStatusWidget extends BasicWidget {bootstrap.Tooltip.getOrCreateInstance(this.$widget.find(`.sync-status-${className}`), {html: true,placement: this.settings.titlePlacement,- fallbackPlacements: [ this.settings.titlePlacement ]+ fallbackPlacements: [this.settings.titlePlacement]});this.$widget.show();- this.$widget.find('.sync-status-icon').hide();+ this.$widget.find(".sync-status-icon").hide();this.$widget.find(`.sync-status-${className}`).show();}processMessage(message) {- if (message.type === 'sync-pull-in-progress') {- this.syncState = 'in-progress';+ if (message.type === "sync-pull-in-progress") {+ this.syncState = "in-progress";this.lastSyncedPush = message.lastSyncedPush;- }- else if (message.type === 'sync-push-in-progress') {- this.syncState = 'in-progress';+ } else if (message.type === "sync-push-in-progress") {+ this.syncState = "in-progress";this.lastSyncedPush = message.lastSyncedPush;- }- else if (message.type === 'sync-finished') {- this.syncState = 'connected';+ } else if (message.type === "sync-finished") {+ this.syncState = "connected";this.lastSyncedPush = message.lastSyncedPush;- }- else if (message.type === 'sync-failed') {- this.syncState = 'disconnected';+ } else if (message.type === "sync-failed") {+ this.syncState = "disconnected";this.lastSyncedPush = message.lastSyncedPush;- }- else if (message.type === 'frontend-update') {+ } else if (message.type === "frontend-update") {this.lastSyncedPush = message.data.lastSyncedPush;}this.allChangesPushed = this.lastSyncedPush === ws.getMaxKnownEntityChangeSyncId();- if (['unknown', 'in-progress'].includes(this.syncState)) {+ if (["unknown", "in-progress"].includes(this.syncState)) {this.showIcon(this.syncState);} else {- this.showIcon(`${this.syncState}-${this.allChangesPushed ? 'no-changes' : 'with-changes'}`);+ this.showIcon(`${this.syncState}-${this.allChangesPushed ? "no-changes" : "with-changes"}`);}}}diff --git a/src/public/app/widgets/tab_row.js b/src/public/app/widgets/tab_row.jsindex 41ab54c552..adbba61053 100644--- a/src/public/app/widgets/tab_row.js+++ b/src/public/app/widgets/tab_row.js@@ -13,11 +13,795 @@ import attributeService from "../services/attributes.js";* https://draggabilly.desandro.com* MIT license*/-(function(e,i){e.jQueryBridget=i(e,e.jQuery)})(window,function t(e,r){"use strict";var s=Array.prototype.slice;var i=e.console;var f=typeof i=="undefined"?function(){}:function(t){i.error(t)};function n(h,o,d){d=d||r||e.jQuery;if(!d){return}if(!o.prototype.option){o.prototype.option=function(t){if(!d.isPlainObject(t)){return}this.options=d.extend(true,this.options,t)}}d.fn[h]=function(t){if(typeof t=="string"){var e=s.call(arguments,1);return i(this,t,e)}n(this,t);return this};function i(t,r,s){var a;var u=`$().${h}("${r}")`;t.each(function(t, e){var i=d.data(e,h);if(!i){f(`${h} not initialized. Cannot call methods, i.e. ${u}`);return}var n=i[r];if(!n||r.charAt(0)=="_"){f(`${u} is not a valid method`);return}var o=n.apply(i,s);a=a===undefined?o:a});return a!==undefined?a:t}function n(t, n){t.each(function(t, e){var i=d.data(e,h);if(i){i.option(n);i._init()}else{i=new o(e,n);d.data(e,h,i)}})}a(d)}function a(t){if(!t||t&&t.bridget){return}t.bridget=n}a(r||e.jQuery);return n});-(function(t,e){"use strict";t.getSize=e()})(window,function t(){"use strict";function m(t){var e=parseFloat(t);var i=t.indexOf("%")==-1&&!isNaN(e);return i&&e}function e(){}var i=typeof console=="undefined"?e:function(t){console.error(t)};var y=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"];var b=y.length;function E(){var t={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0};for(var e=0;e<b;e++){var i=y[e];t[i]=0}return t}function _(t){var e=getComputedStyle(t);if(!e){i(`Style returned ${e}. Are you running this code in a hidden iframe on Firefox? See http://bit.ly/getsizebug1`)}return e}var n=false;var x;function P(){if(n){return}n=true;var t=document.createElement("div");t.style.width="200px";t.style.padding="1px 2px 3px 4px";t.style.borderStyle="solid";t.style.borderWidth="1px 2px 3px 4px";t.style.boxSizing="border-box";var e=document.body||document.documentElement;e.appendChild(t);var i=_(t);o.isBoxSizeOuter=x=m(i.width)==200;e.removeChild(t)}function o(t){P();if(typeof t=="string"){t=document.querySelector(t)}if(!t||typeof t!="object"||!t.nodeType){return}var e=_(t);if(e.display=="none"){return E()}var i={};i.width=t.offsetWidth;i.height=t.offsetHeight;var n=i.isBorderBox=e.boxSizing=="border-box";for(var o=0; o<b; o++){var r=y[o];var s=e[r];var a=parseFloat(s);i[r]=!isNaN(a)?a:0}var u=i.paddingLeft+i.paddingRight;var h=i.paddingTop+i.paddingBottom;var d=i.marginLeft+i.marginRight;var f=i.marginTop+i.marginBottom;var p=i.borderLeftWidth+i.borderRightWidth;var c=i.borderTopWidth+i.borderBottomWidth;var v=n&&x;var l=m(e.width);if(l!==false){i.width=l+(v?0:u+p)}var g=m(e.height);if(g!==false){i.height=g+(v?0:h+c)}i.innerWidth=i.width-(u+p);i.innerHeight=i.height-(h+c);i.outerWidth=i.width+d;i.outerHeight=i.height+f;return i}return o});(function(t, e){t.EvEmitter=e()})(typeof window!="undefined"?window:this,function(){function t(){}var e=t.prototype;e.on=function(t, e){if(!t||!e){return}var i=this._events=this._events||{};var n=i[t]=i[t]||[];if(n.indexOf(e)==-1){n.push(e)}return this};e.once=function(t, e){if(!t||!e){return}this.on(t,e);var i=this._onceEvents=this._onceEvents||{};var n=i[t]=i[t]||{};n[e]=true;return this};e.off=function(t, e){var i=this._events&&this._events[t];if(!i||!i.length){return}var n=i.indexOf(e);if(n!=-1){i.splice(n,1)}return this};e.emitEvent=function(t, e){var i=this._events&&this._events[t];if(!i||!i.length){return}i=i.slice(0);e=e||[];var n=this._onceEvents&&this._onceEvents[t];for(var o=0; o<i.length; o++){var r=i[o];var s=n&&n[r];if(s){this.off(t,r);delete n[r]}r.apply(this,e)}return this};e.allOff=function(){delete this._events;delete this._onceEvents};return t});-(function(e,i){e.Unipointer=i(e,e.EvEmitter)})(window,function t(o,e){function i(){}function n(){}var r=n.prototype=Object.create(e.prototype);r.bindStartEvent=function(t){this._bindStartEvent(t,true)};r.unbindStartEvent=function(t){this._bindStartEvent(t,false)};r._bindStartEvent=function(t,e){e=e===undefined?true:e;var i=e?"addEventListener":"removeEventListener";var n="mousedown";if(o.PointerEvent){n="pointerdown"}else if("ontouchstart"in o){n="touchstart"}t[i](n,this)};r.handleEvent=function(t){var e=`on${t.type}`;if(this[e]){this[e](t)}};r.getTouch=function(t){for(var e=0; e<t.length; e++){var i=t[e];if(i.identifier==this.pointerIdentifier){return i}}};r.onmousedown=function(t){var e=t.button;if(e&&(e!==0&&e!==1)){return}this._pointerDown(t,t)};r.ontouchstart=function(t){this._pointerDown(t,t.changedTouches[0])};r.onpointerdown=function(t){this._pointerDown(t,t)};r._pointerDown=function(t, e){if(t.button||this.isPointerDown){return}this.isPointerDown=true;this.pointerIdentifier=e.pointerId!==undefined?e.pointerId:e.identifier;this.pointerDown(t,e)};r.pointerDown=function(t, e){this._bindPostStartEvents(t);this.emitEvent("pointerDown",[t,e])};var s={mousedown:["mousemove","mouseup"],touchstart:["touchmove","touchend","touchcancel"],pointerdown:["pointermove","pointerup","pointercancel"]};r._bindPostStartEvents=function(t){if(!t){return}var e=s[t.type];e.forEach(function(t){o.addEventListener(t,this)},this);this._boundPointerEvents=e};r._unbindPostStartEvents=function(){if(!this._boundPointerEvents){return}this._boundPointerEvents.forEach(function(t){o.removeEventListener(t,this)},this);delete this._boundPointerEvents};r.onmousemove=function(t){this._pointerMove(t,t)};r.onpointermove=function(t){if(t.pointerId==this.pointerIdentifier){this._pointerMove(t,t)}};r.ontouchmove=function(t){var e=this.getTouch(t.changedTouches);if(e){this._pointerMove(t,e)}};r._pointerMove=function(t, e){this.pointerMove(t,e)};r.pointerMove=function(t, e){this.emitEvent("pointerMove",[t,e])};r.onmouseup=function(t){this._pointerUp(t,t)};r.onpointerup=function(t){if(t.pointerId==this.pointerIdentifier){this._pointerUp(t,t)}};r.ontouchend=function(t){var e=this.getTouch(t.changedTouches);if(e){this._pointerUp(t,e)}};r._pointerUp=function(t, e){this._pointerDone();this.pointerUp(t,e)};r.pointerUp=function(t, e){this.emitEvent("pointerUp",[t,e])};r._pointerDone=function(){this._pointerReset();this._unbindPostStartEvents();this.pointerDone()};r._pointerReset=function(){this.isPointerDown=false;delete this.pointerIdentifier};r.pointerDone=i;r.onpointercancel=function(t){if(t.pointerId==this.pointerIdentifier){this._pointerCancel(t,t)}};r.ontouchcancel=function(t){var e=this.getTouch(t.changedTouches);if(e){this._pointerCancel(t,e)}};r._pointerCancel=function(t, e){this._pointerDone();this.pointerCancel(t,e)};r.pointerCancel=function(t, e){this.emitEvent("pointerCancel",[t,e])};n.getPointerPoint=function(t){return{x:t.pageX,y:t.pageY}};return n});-(function(e,i){e.Unidragger=i(e,e.Unipointer)})(window,function t(r,e){function i(){}var n=i.prototype=Object.create(e.prototype);n.bindHandles=function(){this._bindHandles(true)};n.unbindHandles=function(){this._bindHandles(false)};n._bindHandles=function(t){t=t===undefined?true:t;var e=t?"addEventListener":"removeEventListener";var i=t?this._touchActionValue:"";for(var n=0;n<this.handles.length;n++){var o=this.handles[n];this._bindStartEvent(o,t);o[e]("click",this);if(r.PointerEvent){o.style.touchAction=i}}};n._touchActionValue="none";n.pointerDown=function(t,e){var i=this.okayPointerDown(t);if(!i){return}this.pointerDownPointer=e;t.preventDefault();this.pointerDownBlur();this._bindPostStartEvents(t);this.emitEvent("pointerDown",[t,e])};var o={TEXTAREA:true,INPUT:true,SELECT:true,OPTION:true};var s={radio:true,checkbox:true,button:true,submit:true,image:true,file:true};n.okayPointerDown=function(t){var e=o[t.target.nodeName];var i=s[t.target.type];var n=!e||i;if(!n){this._pointerReset()}return n};n.pointerDownBlur=function(){var t=document.activeElement;var e=t&&t.blur&&t!=document.body;if(e){t.blur()}};n.pointerMove=function(t,e){var i=this._dragPointerMove(t,e);this.emitEvent("pointerMove",[t,e,i]);this._dragMove(t,e,i)};n._dragPointerMove=function(t,e){var i={x:e.pageX-this.pointerDownPointer.pageX,y:e.pageY-this.pointerDownPointer.pageY};if(!this.isDragging&&this.hasDragStarted(i)){this._dragStart(t,e)}return i};n.hasDragStarted=function(t){return Math.abs(t.x)>3||Math.abs(t.y)>3};n.pointerUp=function(t,e){this.emitEvent("pointerUp",[t,e]);this._dragPointerUp(t,e)};n._dragPointerUp=function(t,e){if(this.isDragging){this._dragEnd(t,e)}else{this._staticClick(t,e)}};n._dragStart=function(t,e){this.isDragging=true;this.isPreventingClicks=true;this.dragStart(t,e)};n.dragStart=function(t,e){this.emitEvent("dragStart",[t,e])};n._dragMove=function(t,e,i){if(!this.isDragging){return}this.dragMove(t,e,i)};n.dragMove=function(t,e,i){t.preventDefault();this.emitEvent("dragMove",[t,e,i])};n._dragEnd=function(t,e){this.isDragging=false;setTimeout(function(){delete this.isPreventingClicks}.bind(this));this.dragEnd(t,e)};n.dragEnd=function(t,e){this.emitEvent("dragEnd",[t,e])};n.onclick=function(t){if(this.isPreventingClicks){t.preventDefault()}};n._staticClick=function(t,e){if(this.isIgnoringMouseUp&&t.type=="mouseup"){return}this.staticClick(t,e);if(t.type!="mouseup"){this.isIgnoringMouseUp=true;setTimeout(function(){delete this.isIgnoringMouseUp}.bind(this),400)}};n.staticClick=function(t,e){this.emitEvent("staticClick",[t,e])};i.getPointerPoint=e.getPointerPoint;return i});-(function(i,n){i.Draggabilly=n(i,i.getSize,i.Unidragger)})(window,function t(r,u,e){function i(t,e){for(var i in e){t[i]=e[i]}return t}function n(){}var o=r.jQuery;function s(t,e){this.element=typeof t=="string"?document.querySelector(t):t;if(o){this.$element=o(this.element)}this.options=i({},this.constructor.defaults);this.option(e);this._create()}var a=s.prototype=Object.create(e.prototype);s.defaults={};a.option=function(t){i(this.options,t)};var h={relative:true,absolute:true,fixed:true};a._create=function(){this.position={};this._getPosition();this.startPoint={x:0,y:0};this.dragPoint={x:0,y:0};this.startPosition=i({},this.position);var t=getComputedStyle(this.element);if(!h[t.position]){this.element.style.position="relative"}this.on("pointerMove",this.onPointerMove);this.on("pointerUp",this.onPointerUp);this.enable();this.setHandles()};a.setHandles=function(){this.handles=this.options.handle?this.element.querySelectorAll(this.options.handle):[this.element];this.bindHandles()};a.dispatchEvent=function(t,e,i){var n=[e].concat(i);this.emitEvent(t,n);this.dispatchJQueryEvent(t,e,i)};a.dispatchJQueryEvent=function(t,e,i){var n=r.jQuery;if(!n||!this.$element){return}var o=n.Event(e);o.type=t;this.$element.trigger(o,i)};a._getPosition=function(){var t=getComputedStyle(this.element);var e=this._getPositionCoord(t.left,"width");var i=this._getPositionCoord(t.top,"height");this.position.x=isNaN(e)?0:e;this.position.y=isNaN(i)?0:i;this._addTransformPosition(t)};a._getPositionCoord=function(t,e){if(t.indexOf("%")!=-1){var i=u(this.element.parentNode);return!i?0:parseFloat(t)/100*i[e]}return parseInt(t,10)};a._addTransformPosition=function(t){var e=t.transform;if(e.indexOf("matrix")!==0){return}var i=e.split(",");var n=e.indexOf("matrix3d")===0?12:4;var o=parseInt(i[n],10);var r=parseInt(i[n+1],10);this.position.x+=o;this.position.y+=r};a.onPointerDown=function(t,e){this.element.classList.add("is-pointer-down");this.dispatchJQueryEvent("pointerDown",t,[e])};a.pointerDown=function(t,e){var i=this.okayPointerDown(t);if(!i||!this.isEnabled){this._pointerReset();return}this.pointerDownPointer={pageX:e.pageX,pageY:e.pageY};t.preventDefault();this.pointerDownBlur();this._bindPostStartEvents(t);this.element.classList.add("is-pointer-down");this.dispatchEvent("pointerDown",t,[e])};a.dragStart=function(t,e){if(!this.isEnabled){return}this._getPosition();this.measureContainment();this.startPosition.x=this.position.x;this.startPosition.y=this.position.y;this.setLeftTop();this.dragPoint.x=0;this.dragPoint.y=0;this.element.classList.add("is-dragging");this.dispatchEvent("dragStart",t,[e]);this.animate()};a.measureContainment=function(){var t=this.getContainer();if(!t){return}var e=u(this.element);var i=u(t);var n=this.element.getBoundingClientRect();var o=t.getBoundingClientRect();var r=i.borderLeftWidth+i.borderRightWidth;var s=i.borderTopWidth+i.borderBottomWidth;var a=this.relativeStartPosition={x:n.left-(o.left+i.borderLeftWidth),y:n.top-(o.top+i.borderTopWidth)};this.containSize={width:i.width-r-a.x-e.width,height:i.height-s-a.y-e.height}};a.getContainer=function(){var t=this.options.containment;if(!t){return}var e=t instanceof HTMLElement;if(e){return t}if(typeof t=="string"){return document.querySelector(t)}return this.element.parentNode};a.onPointerMove=function(t,e,i){this.dispatchJQueryEvent("pointerMove",t,[e,i])};a.dragMove=function(t,e,i){if(!this.isEnabled){return}var n=i.x;var o=i.y;var r=this.options.grid;var s=r&&r[0];var a=r&&r[1];n=d(n,s);o=d(o,a);n=this.containDrag("x",n,s);o=this.containDrag("y",o,a);n=this.options.axis=="y"?0:n;o=this.options.axis=="x"?0:o;this.position.x=this.startPosition.x+n;this.position.y=this.startPosition.y+o;this.dragPoint.x=n;this.dragPoint.y=o;this.dispatchEvent("dragMove",t,[e,i])};function d(t,e,i){i=i||"round";return e?Math[i](t/e)*e:t}a.containDrag=function(t,e,i){if(!this.options.containment){return e}var n=t=="x"?"width":"height";var o=this.relativeStartPosition[t];var r=d(-o,i,"ceil");var s=this.containSize[n];s=d(s,i,"floor");return Math.max(r,Math.min(s,e))};a.onPointerUp=function(t,e){this.element.classList.remove("is-pointer-down");this.dispatchJQueryEvent("pointerUp",t,[e])};a.dragEnd=function(t,e){if(!this.isEnabled){return}this.element.style.transform="";this.setLeftTop();this.element.classList.remove("is-dragging");this.dispatchEvent("dragEnd",t,[e])};a.animate=function(){if(!this.isDragging){return}this.positionDrag();var e=this;requestAnimationFrame(function t(){e.animate()})};a.setLeftTop=function(){this.element.style.left=`${this.position.x}px`;this.element.style.top=`${this.position.y}px`};a.positionDrag=function(){this.element.style.transform=`translate3d( ${this.dragPoint.x}px, ${this.dragPoint.y}px, 0)`};a.staticClick=function(t, e){this.dispatchEvent("staticClick",t,[e])};a.setPosition=function(t, e){this.position.x=t;this.position.y=e;this.setLeftTop()};a.enable=function(){this.isEnabled=true};a.disable=function(){this.isEnabled=false;if(this.isDragging){this.dragEnd()}};a.destroy=function(){this.disable();this.element.style.transform="";this.element.style.left="";this.element.style.top="";this.element.style.position="";this.unbindHandles();if(this.$element){this.$element.removeData("draggabilly")}};a._init=n;if(o&&o.bridget){o.bridget("draggabilly",s)}return s});+(function (e, i) {+ e.jQueryBridget = i(e, e.jQuery);+})(window, function t(e, r) {+ "use strict";+ var s = Array.prototype.slice;+ var i = e.console;+ var f =+ typeof i == "undefined"+ ? function () {}+ : function (t) {+ i.error(t);+ };+ function n(h, o, d) {+ d = d || r || e.jQuery;+ if (!d) {+ return;+ }+ if (!o.prototype.option) {+ o.prototype.option = function (t) {+ if (!d.isPlainObject(t)) {+ return;+ }+ this.options = d.extend(true, this.options, t);+ };+ }+ d.fn[h] = function (t) {+ if (typeof t == "string") {+ var e = s.call(arguments, 1);+ return i(this, t, e);+ }+ n(this, t);+ return this;+ };+ function i(t, r, s) {+ var a;+ var u = `$().${h}("${r}")`;+ t.each(function (t, e) {+ var i = d.data(e, h);+ if (!i) {+ f(`${h} not initialized. Cannot call methods, i.e. ${u}`);+ return;+ }+ var n = i[r];+ if (!n || r.charAt(0) == "_") {+ f(`${u} is not a valid method`);+ return;+ }+ var o = n.apply(i, s);+ a = a === undefined ? o : a;+ });+ return a !== undefined ? a : t;+ }+ function n(t, n) {+ t.each(function (t, e) {+ var i = d.data(e, h);+ if (i) {+ i.option(n);+ i._init();+ } else {+ i = new o(e, n);+ d.data(e, h, i);+ }+ });+ }+ a(d);+ }+ function a(t) {+ if (!t || (t && t.bridget)) {+ return;+ }+ t.bridget = n;+ }+ a(r || e.jQuery);+ return n;+});+(function (t, e) {+ "use strict";+ t.getSize = e();+})(window, function t() {+ "use strict";+ function m(t) {+ var e = parseFloat(t);+ var i = t.indexOf("%") == -1 && !isNaN(e);+ return i && e;+ }+ function e() {}+ var i =+ typeof console == "undefined"+ ? e+ : function (t) {+ console.error(t);+ };+ var y = [+ "paddingLeft",+ "paddingRight",+ "paddingTop",+ "paddingBottom",+ "marginLeft",+ "marginRight",+ "marginTop",+ "marginBottom",+ "borderLeftWidth",+ "borderRightWidth",+ "borderTopWidth",+ "borderBottomWidth"+ ];+ var b = y.length;+ function E() {+ var t = { width: 0, height: 0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 };+ for (var e = 0; e < b; e++) {+ var i = y[e];+ t[i] = 0;+ }+ return t;+ }+ function _(t) {+ var e = getComputedStyle(t);+ if (!e) {+ i(`Style returned ${e}. Are you running this code in a hidden iframe on Firefox? See http://bit.ly/getsizebug1`);+ }+ return e;+ }+ var n = false;+ var x;+ function P() {+ if (n) {+ return;+ }+ n = true;+ var t = document.createElement("div");+ t.style.width = "200px";+ t.style.padding = "1px 2px 3px 4px";+ t.style.borderStyle = "solid";+ t.style.borderWidth = "1px 2px 3px 4px";+ t.style.boxSizing = "border-box";+ var e = document.body || document.documentElement;+ e.appendChild(t);+ var i = _(t);+ o.isBoxSizeOuter = x = m(i.width) == 200;+ e.removeChild(t);+ }+ function o(t) {+ P();+ if (typeof t == "string") {+ t = document.querySelector(t);+ }+ if (!t || typeof t != "object" || !t.nodeType) {+ return;+ }+ var e = _(t);+ if (e.display == "none") {+ return E();+ }+ var i = {};+ i.width = t.offsetWidth;+ i.height = t.offsetHeight;+ var n = (i.isBorderBox = e.boxSizing == "border-box");+ for (var o = 0; o < b; o++) {+ var r = y[o];+ var s = e[r];+ var a = parseFloat(s);+ i[r] = !isNaN(a) ? a : 0;+ }+ var u = i.paddingLeft + i.paddingRight;+ var h = i.paddingTop + i.paddingBottom;+ var d = i.marginLeft + i.marginRight;+ var f = i.marginTop + i.marginBottom;+ var p = i.borderLeftWidth + i.borderRightWidth;+ var c = i.borderTopWidth + i.borderBottomWidth;+ var v = n && x;+ var l = m(e.width);+ if (l !== false) {+ i.width = l + (v ? 0 : u + p);+ }+ var g = m(e.height);+ if (g !== false) {+ i.height = g + (v ? 0 : h + c);+ }+ i.innerWidth = i.width - (u + p);+ i.innerHeight = i.height - (h + c);+ i.outerWidth = i.width + d;+ i.outerHeight = i.height + f;+ return i;+ }+ return o;+});+(function (t, e) {+ t.EvEmitter = e();+})(typeof window != "undefined" ? window : this, function () {+ function t() {}+ var e = t.prototype;+ e.on = function (t, e) {+ if (!t || !e) {+ return;+ }+ var i = (this._events = this._events || {});+ var n = (i[t] = i[t] || []);+ if (n.indexOf(e) == -1) {+ n.push(e);+ }+ return this;+ };+ e.once = function (t, e) {+ if (!t || !e) {+ return;+ }+ this.on(t, e);+ var i = (this._onceEvents = this._onceEvents || {});+ var n = (i[t] = i[t] || {});+ n[e] = true;+ return this;+ };+ e.off = function (t, e) {+ var i = this._events && this._events[t];+ if (!i || !i.length) {+ return;+ }+ var n = i.indexOf(e);+ if (n != -1) {+ i.splice(n, 1);+ }+ return this;+ };+ e.emitEvent = function (t, e) {+ var i = this._events && this._events[t];+ if (!i || !i.length) {+ return;+ }+ i = i.slice(0);+ e = e || [];+ var n = this._onceEvents && this._onceEvents[t];+ for (var o = 0; o < i.length; o++) {+ var r = i[o];+ var s = n && n[r];+ if (s) {+ this.off(t, r);+ delete n[r];+ }+ r.apply(this, e);+ }+ return this;+ };+ e.allOff = function () {+ delete this._events;+ delete this._onceEvents;+ };+ return t;+});+(function (e, i) {+ e.Unipointer = i(e, e.EvEmitter);+})(window, function t(o, e) {+ function i() {}+ function n() {}+ var r = (n.prototype = Object.create(e.prototype));+ r.bindStartEvent = function (t) {+ this._bindStartEvent(t, true);+ };+ r.unbindStartEvent = function (t) {+ this._bindStartEvent(t, false);+ };+ r._bindStartEvent = function (t, e) {+ e = e === undefined ? true : e;+ var i = e ? "addEventListener" : "removeEventListener";+ var n = "mousedown";+ if (o.PointerEvent) {+ n = "pointerdown";+ } else if ("ontouchstart" in o) {+ n = "touchstart";+ }+ t[i](n, this);+ };+ r.handleEvent = function (t) {+ var e = `on${t.type}`;+ if (this[e]) {+ this[e](t);+ }+ };+ r.getTouch = function (t) {+ for (var e = 0; e < t.length; e++) {+ var i = t[e];+ if (i.identifier == this.pointerIdentifier) {+ return i;+ }+ }+ };+ r.onmousedown = function (t) {+ var e = t.button;+ if (e && e !== 0 && e !== 1) {+ return;+ }+ this._pointerDown(t, t);+ };+ r.ontouchstart = function (t) {+ this._pointerDown(t, t.changedTouches[0]);+ };+ r.onpointerdown = function (t) {+ this._pointerDown(t, t);+ };+ r._pointerDown = function (t, e) {+ if (t.button || this.isPointerDown) {+ return;+ }+ this.isPointerDown = true;+ this.pointerIdentifier = e.pointerId !== undefined ? e.pointerId : e.identifier;+ this.pointerDown(t, e);+ };+ r.pointerDown = function (t, e) {+ this._bindPostStartEvents(t);+ this.emitEvent("pointerDown", [t, e]);+ };+ var s = { mousedown: ["mousemove", "mouseup"], touchstart: ["touchmove", "touchend", "touchcancel"], pointerdown: ["pointermove", "pointerup", "pointercancel"] };+ r._bindPostStartEvents = function (t) {+ if (!t) {+ return;+ }+ var e = s[t.type];+ e.forEach(function (t) {+ o.addEventListener(t, this);+ }, this);+ this._boundPointerEvents = e;+ };+ r._unbindPostStartEvents = function () {+ if (!this._boundPointerEvents) {+ return;+ }+ this._boundPointerEvents.forEach(function (t) {+ o.removeEventListener(t, this);+ }, this);+ delete this._boundPointerEvents;+ };+ r.onmousemove = function (t) {+ this._pointerMove(t, t);+ };+ r.onpointermove = function (t) {+ if (t.pointerId == this.pointerIdentifier) {+ this._pointerMove(t, t);+ }+ };+ r.ontouchmove = function (t) {+ var e = this.getTouch(t.changedTouches);+ if (e) {+ this._pointerMove(t, e);+ }+ };+ r._pointerMove = function (t, e) {+ this.pointerMove(t, e);+ };+ r.pointerMove = function (t, e) {+ this.emitEvent("pointerMove", [t, e]);+ };+ r.onmouseup = function (t) {+ this._pointerUp(t, t);+ };+ r.onpointerup = function (t) {+ if (t.pointerId == this.pointerIdentifier) {+ this._pointerUp(t, t);+ }+ };+ r.ontouchend = function (t) {+ var e = this.getTouch(t.changedTouches);+ if (e) {+ this._pointerUp(t, e);+ }+ };+ r._pointerUp = function (t, e) {+ this._pointerDone();+ this.pointerUp(t, e);+ };+ r.pointerUp = function (t, e) {+ this.emitEvent("pointerUp", [t, e]);+ };+ r._pointerDone = function () {+ this._pointerReset();+ this._unbindPostStartEvents();+ this.pointerDone();+ };+ r._pointerReset = function () {+ this.isPointerDown = false;+ delete this.pointerIdentifier;+ };+ r.pointerDone = i;+ r.onpointercancel = function (t) {+ if (t.pointerId == this.pointerIdentifier) {+ this._pointerCancel(t, t);+ }+ };+ r.ontouchcancel = function (t) {+ var e = this.getTouch(t.changedTouches);+ if (e) {+ this._pointerCancel(t, e);+ }+ };+ r._pointerCancel = function (t, e) {+ this._pointerDone();+ this.pointerCancel(t, e);+ };+ r.pointerCancel = function (t, e) {+ this.emitEvent("pointerCancel", [t, e]);+ };+ n.getPointerPoint = function (t) {+ return { x: t.pageX, y: t.pageY };+ };+ return n;+});+(function (e, i) {+ e.Unidragger = i(e, e.Unipointer);+})(window, function t(r, e) {+ function i() {}+ var n = (i.prototype = Object.create(e.prototype));+ n.bindHandles = function () {+ this._bindHandles(true);+ };+ n.unbindHandles = function () {+ this._bindHandles(false);+ };+ n._bindHandles = function (t) {+ t = t === undefined ? true : t;+ var e = t ? "addEventListener" : "removeEventListener";+ var i = t ? this._touchActionValue : "";+ for (var n = 0; n < this.handles.length; n++) {+ var o = this.handles[n];+ this._bindStartEvent(o, t);+ o[e]("click", this);+ if (r.PointerEvent) {+ o.style.touchAction = i;+ }+ }+ };+ n._touchActionValue = "none";+ n.pointerDown = function (t, e) {+ var i = this.okayPointerDown(t);+ if (!i) {+ return;+ }+ this.pointerDownPointer = e;+ t.preventDefault();+ this.pointerDownBlur();+ this._bindPostStartEvents(t);+ this.emitEvent("pointerDown", [t, e]);+ };+ var o = { TEXTAREA: true, INPUT: true, SELECT: true, OPTION: true };+ var s = { radio: true, checkbox: true, button: true, submit: true, image: true, file: true };+ n.okayPointerDown = function (t) {+ var e = o[t.target.nodeName];+ var i = s[t.target.type];+ var n = !e || i;+ if (!n) {+ this._pointerReset();+ }+ return n;+ };+ n.pointerDownBlur = function () {+ var t = document.activeElement;+ var e = t && t.blur && t != document.body;+ if (e) {+ t.blur();+ }+ };+ n.pointerMove = function (t, e) {+ var i = this._dragPointerMove(t, e);+ this.emitEvent("pointerMove", [t, e, i]);+ this._dragMove(t, e, i);+ };+ n._dragPointerMove = function (t, e) {+ var i = { x: e.pageX - this.pointerDownPointer.pageX, y: e.pageY - this.pointerDownPointer.pageY };+ if (!this.isDragging && this.hasDragStarted(i)) {+ this._dragStart(t, e);+ }+ return i;+ };+ n.hasDragStarted = function (t) {+ return Math.abs(t.x) > 3 || Math.abs(t.y) > 3;+ };+ n.pointerUp = function (t, e) {+ this.emitEvent("pointerUp", [t, e]);+ this._dragPointerUp(t, e);+ };+ n._dragPointerUp = function (t, e) {+ if (this.isDragging) {+ this._dragEnd(t, e);+ } else {+ this._staticClick(t, e);+ }+ };+ n._dragStart = function (t, e) {+ this.isDragging = true;+ this.isPreventingClicks = true;+ this.dragStart(t, e);+ };+ n.dragStart = function (t, e) {+ this.emitEvent("dragStart", [t, e]);+ };+ n._dragMove = function (t, e, i) {+ if (!this.isDragging) {+ return;+ }+ this.dragMove(t, e, i);+ };+ n.dragMove = function (t, e, i) {+ t.preventDefault();+ this.emitEvent("dragMove", [t, e, i]);+ };+ n._dragEnd = function (t, e) {+ this.isDragging = false;+ setTimeout(+ function () {+ delete this.isPreventingClicks;+ }.bind(this)+ );+ this.dragEnd(t, e);+ };+ n.dragEnd = function (t, e) {+ this.emitEvent("dragEnd", [t, e]);+ };+ n.onclick = function (t) {+ if (this.isPreventingClicks) {+ t.preventDefault();+ }+ };+ n._staticClick = function (t, e) {+ if (this.isIgnoringMouseUp && t.type == "mouseup") {+ return;+ }+ this.staticClick(t, e);+ if (t.type != "mouseup") {+ this.isIgnoringMouseUp = true;+ setTimeout(+ function () {+ delete this.isIgnoringMouseUp;+ }.bind(this),+ 400+ );+ }+ };+ n.staticClick = function (t, e) {+ this.emitEvent("staticClick", [t, e]);+ };+ i.getPointerPoint = e.getPointerPoint;+ return i;+});+(function (i, n) {+ i.Draggabilly = n(i, i.getSize, i.Unidragger);+})(window, function t(r, u, e) {+ function i(t, e) {+ for (var i in e) {+ t[i] = e[i];+ }+ return t;+ }+ function n() {}+ var o = r.jQuery;+ function s(t, e) {+ this.element = typeof t == "string" ? document.querySelector(t) : t;+ if (o) {+ this.$element = o(this.element);+ }+ this.options = i({}, this.constructor.defaults);+ this.option(e);+ this._create();+ }+ var a = (s.prototype = Object.create(e.prototype));+ s.defaults = {};+ a.option = function (t) {+ i(this.options, t);+ };+ var h = { relative: true, absolute: true, fixed: true };+ a._create = function () {+ this.position = {};+ this._getPosition();+ this.startPoint = { x: 0, y: 0 };+ this.dragPoint = { x: 0, y: 0 };+ this.startPosition = i({}, this.position);+ var t = getComputedStyle(this.element);+ if (!h[t.position]) {+ this.element.style.position = "relative";+ }+ this.on("pointerMove", this.onPointerMove);+ this.on("pointerUp", this.onPointerUp);+ this.enable();+ this.setHandles();+ };+ a.setHandles = function () {+ this.handles = this.options.handle ? this.element.querySelectorAll(this.options.handle) : [this.element];+ this.bindHandles();+ };+ a.dispatchEvent = function (t, e, i) {+ var n = [e].concat(i);+ this.emitEvent(t, n);+ this.dispatchJQueryEvent(t, e, i);+ };+ a.dispatchJQueryEvent = function (t, e, i) {+ var n = r.jQuery;+ if (!n || !this.$element) {+ return;+ }+ var o = n.Event(e);+ o.type = t;+ this.$element.trigger(o, i);+ };+ a._getPosition = function () {+ var t = getComputedStyle(this.element);+ var e = this._getPositionCoord(t.left, "width");+ var i = this._getPositionCoord(t.top, "height");+ this.position.x = isNaN(e) ? 0 : e;+ this.position.y = isNaN(i) ? 0 : i;+ this._addTransformPosition(t);+ };+ a._getPositionCoord = function (t, e) {+ if (t.indexOf("%") != -1) {+ var i = u(this.element.parentNode);+ return !i ? 0 : (parseFloat(t) / 100) * i[e];+ }+ return parseInt(t, 10);+ };+ a._addTransformPosition = function (t) {+ var e = t.transform;+ if (e.indexOf("matrix") !== 0) {+ return;+ }+ var i = e.split(",");+ var n = e.indexOf("matrix3d") === 0 ? 12 : 4;+ var o = parseInt(i[n], 10);+ var r = parseInt(i[n + 1], 10);+ this.position.x += o;+ this.position.y += r;+ };+ a.onPointerDown = function (t, e) {+ this.element.classList.add("is-pointer-down");+ this.dispatchJQueryEvent("pointerDown", t, [e]);+ };+ a.pointerDown = function (t, e) {+ var i = this.okayPointerDown(t);+ if (!i || !this.isEnabled) {+ this._pointerReset();+ return;+ }+ this.pointerDownPointer = { pageX: e.pageX, pageY: e.pageY };+ t.preventDefault();+ this.pointerDownBlur();+ this._bindPostStartEvents(t);+ this.element.classList.add("is-pointer-down");+ this.dispatchEvent("pointerDown", t, [e]);+ };+ a.dragStart = function (t, e) {+ if (!this.isEnabled) {+ return;+ }+ this._getPosition();+ this.measureContainment();+ this.startPosition.x = this.position.x;+ this.startPosition.y = this.position.y;+ this.setLeftTop();+ this.dragPoint.x = 0;+ this.dragPoint.y = 0;+ this.element.classList.add("is-dragging");+ this.dispatchEvent("dragStart", t, [e]);+ this.animate();+ };+ a.measureContainment = function () {+ var t = this.getContainer();+ if (!t) {+ return;+ }+ var e = u(this.element);+ var i = u(t);+ var n = this.element.getBoundingClientRect();+ var o = t.getBoundingClientRect();+ var r = i.borderLeftWidth + i.borderRightWidth;+ var s = i.borderTopWidth + i.borderBottomWidth;+ var a = (this.relativeStartPosition = { x: n.left - (o.left + i.borderLeftWidth), y: n.top - (o.top + i.borderTopWidth) });+ this.containSize = { width: i.width - r - a.x - e.width, height: i.height - s - a.y - e.height };+ };+ a.getContainer = function () {+ var t = this.options.containment;+ if (!t) {+ return;+ }+ var e = t instanceof HTMLElement;+ if (e) {+ return t;+ }+ if (typeof t == "string") {+ return document.querySelector(t);+ }+ return this.element.parentNode;+ };+ a.onPointerMove = function (t, e, i) {+ this.dispatchJQueryEvent("pointerMove", t, [e, i]);+ };+ a.dragMove = function (t, e, i) {+ if (!this.isEnabled) {+ return;+ }+ var n = i.x;+ var o = i.y;+ var r = this.options.grid;+ var s = r && r[0];+ var a = r && r[1];+ n = d(n, s);+ o = d(o, a);+ n = this.containDrag("x", n, s);+ o = this.containDrag("y", o, a);+ n = this.options.axis == "y" ? 0 : n;+ o = this.options.axis == "x" ? 0 : o;+ this.position.x = this.startPosition.x + n;+ this.position.y = this.startPosition.y + o;+ this.dragPoint.x = n;+ this.dragPoint.y = o;+ this.dispatchEvent("dragMove", t, [e, i]);+ };+ function d(t, e, i) {+ i = i || "round";+ return e ? Math[i](t / e) * e : t;+ }+ a.containDrag = function (t, e, i) {+ if (!this.options.containment) {+ return e;+ }+ var n = t == "x" ? "width" : "height";+ var o = this.relativeStartPosition[t];+ var r = d(-o, i, "ceil");+ var s = this.containSize[n];+ s = d(s, i, "floor");+ return Math.max(r, Math.min(s, e));+ };+ a.onPointerUp = function (t, e) {+ this.element.classList.remove("is-pointer-down");+ this.dispatchJQueryEvent("pointerUp", t, [e]);+ };+ a.dragEnd = function (t, e) {+ if (!this.isEnabled) {+ return;+ }+ this.element.style.transform = "";+ this.setLeftTop();+ this.element.classList.remove("is-dragging");+ this.dispatchEvent("dragEnd", t, [e]);+ };+ a.animate = function () {+ if (!this.isDragging) {+ return;+ }+ this.positionDrag();+ var e = this;+ requestAnimationFrame(function t() {+ e.animate();+ });+ };+ a.setLeftTop = function () {+ this.element.style.left = `${this.position.x}px`;+ this.element.style.top = `${this.position.y}px`;+ };+ a.positionDrag = function () {+ this.element.style.transform = `translate3d( ${this.dragPoint.x}px, ${this.dragPoint.y}px, 0)`;+ };+ a.staticClick = function (t, e) {+ this.dispatchEvent("staticClick", t, [e]);+ };+ a.setPosition = function (t, e) {+ this.position.x = t;+ this.position.y = e;+ this.setLeftTop();+ };+ a.enable = function () {+ this.isEnabled = true;+ };+ a.disable = function () {+ this.isEnabled = false;+ if (this.isDragging) {+ this.dragEnd();+ }+ };+ a.destroy = function () {+ this.disable();+ this.element.style.transform = "";+ this.element.style.left = "";+ this.element.style.top = "";+ this.element.style.position = "";+ this.unbindHandles();+ if (this.$element) {+ this.$element.removeData("draggabilly");+ }+ };+ a._init = n;+ if (o && o.bridget) {+ o.bridget("draggabilly", s);+ }+ return s;+});const Draggabilly = window.Draggabilly;@@ -38,11 +822,11 @@ const TAB_TPL = `<div class="note-tab-drag-handle"></div><div class="note-tab-icon"></div><div class="note-tab-title"></div>- <div class="note-tab-close bx bx-x" title="${t('tab_row.close_tab')}" data-trigger-command="closeActiveTab"></div>+ <div class="note-tab-close bx bx-x" title="${t("tab_row.close_tab")}" data-trigger-command="closeActiveTab"></div></div></div>`;-const NEW_TAB_BUTTON_TPL = `<div class="note-new-tab" data-trigger-command="openNewTab" title="${t('tab_row.add_new_tab')}">+</div>`;+const NEW_TAB_BUTTON_TPL = `<div class="note-new-tab" data-trigger-command="openNewTab" title="${t("tab_row.add_new_tab")}">+</div>`;const FILLER_TPL = `<div class="tab-row-filler"></div>`;const TAB_ROW_TPL = `@@ -244,9 +1028,9 @@ const TAB_ROW_TPL = `export default class TabRowWidget extends BasicWidget {doRender() {this.$widget = $(TAB_ROW_TPL);-+const documentStyle = window.getComputedStyle(document.documentElement);- this.showNoteIcons = (documentStyle.getPropertyValue("--tab-note-icons") === "true");+ this.showNoteIcons = documentStyle.getPropertyValue("--tab-note-icons") === "true";this.draggabillies = [];@@ -258,31 +1042,31 @@ export default class TabRowWidget extends BasicWidget {this.layoutTabs();this.setVisibility();- this.$widget.on('contextmenu', '.note-tab', e => {+ this.$widget.on("contextmenu", ".note-tab", (e) => {e.preventDefault();- const ntxId = $(e.target).closest(".note-tab").attr('data-ntx-id');+ const ntxId = $(e.target).closest(".note-tab").attr("data-ntx-id");contextMenu.show({x: e.pageX,y: e.pageY,items: [- {title: t('tab_row.close'), command: "closeTab", uiIcon: "bx bx-x"},- {title: t('tab_row.close_other_tabs'), command: "closeOtherTabs", uiIcon: "bx bx-empty", enabled: appContext.tabManager.noteContexts.length !== 1},- {title: t('tab_row.close_right_tabs'), command: "closeRightTabs", uiIcon: "bx bx-empty", enabled: appContext.tabManager.noteContexts.at(-1).ntxId !== ntxId},- {title: t('tab_row.close_all_tabs'), command: "closeAllTabs", uiIcon: "bx bx-empty"},+ { title: t("tab_row.close"), command: "closeTab", uiIcon: "bx bx-x" },+ { title: t("tab_row.close_other_tabs"), command: "closeOtherTabs", uiIcon: "bx bx-empty", enabled: appContext.tabManager.noteContexts.length !== 1 },+ { title: t("tab_row.close_right_tabs"), command: "closeRightTabs", uiIcon: "bx bx-empty", enabled: appContext.tabManager.noteContexts.at(-1).ntxId !== ntxId },+ { title: t("tab_row.close_all_tabs"), command: "closeAllTabs", uiIcon: "bx bx-empty" },++ { title: "----" },- {title: "----"},+ { title: t("tab_row.reopen_last_tab"), command: "reopenLastTab", uiIcon: "bx bx-undo", enabled: appContext.tabManager.recentlyClosedTabs.length !== 0 },- {title: t('tab_row.reopen_last_tab'), command: "reopenLastTab", uiIcon: "bx bx-undo", enabled: appContext.tabManager.recentlyClosedTabs.length !== 0},+ { title: "----" },- {title: "----"},-- {title: t('tab_row.move_tab_to_new_window'), command: "moveTabToNewWindow", uiIcon: "bx bx-window-open"},- {title: t('tab_row.copy_tab_to_new_window'), command: "copyTabToNewWindow", uiIcon: "bx bx-empty"}+ { title: t("tab_row.move_tab_to_new_window"), command: "moveTabToNewWindow", uiIcon: "bx bx-window-open" },+ { title: t("tab_row.copy_tab_to_new_window"), command: "copyTabToNewWindow", uiIcon: "bx bx-empty" }],- selectMenuItemHandler: ({command}) => {- this.triggerCommand(command, {ntxId});+ selectMenuItemHandler: ({ command }) => {+ this.triggerCommand(command, { ntxId });}});});@@ -294,7 +1078,7 @@ export default class TabRowWidget extends BasicWidget {}setupEvents() {- const resizeListener = _ => {+ const resizeListener = (_) => {this.cleanUpPreviouslyDraggedTabs();this.layoutTabs();};@@ -309,11 +1093,11 @@ export default class TabRowWidget extends BasicWidget {}get tabEls() {- return Array.prototype.slice.call(this.$widget.find('.note-tab'));+ return Array.prototype.slice.call(this.$widget.find(".note-tab"));}get $tabContainer() {- return this.$widget.find('.tab-row-widget-container');+ return this.$widget.find(".tab-row-widget-container");}get tabWidths() {@@ -350,7 +1134,7 @@ export default class TabRowWidget extends BasicWidget {const tabPositions = [];let position = TAB_CONTAINER_LEFT_PADDING;- this.tabWidths.forEach(width => {+ this.tabWidths.forEach((width) => {tabPositions.push(position);position += width + MARGIN_WIDTH;});@@ -360,7 +1144,7 @@ export default class TabRowWidget extends BasicWidget {const newTabPosition = position;const fillerPosition = position + 32;- return {tabPositions, newTabPosition, fillerPosition};+ return { tabPositions, newTabPosition, fillerPosition };}layoutTabs() {@@ -370,57 +1154,57 @@ export default class TabRowWidget extends BasicWidget {const width = tabContainerWidths[i];tabEl.style.width = `${width}px`;- tabEl.removeAttribute('is-small');- tabEl.removeAttribute('is-smaller');- tabEl.removeAttribute('is-mini');+ tabEl.removeAttribute("is-small");+ tabEl.removeAttribute("is-smaller");+ tabEl.removeAttribute("is-mini");- if (width < TAB_SIZE_SMALL) tabEl.setAttribute('is-small', '');- if (width < TAB_SIZE_SMALLER) tabEl.setAttribute('is-smaller', '');- if (width < TAB_SIZE_MINI) tabEl.setAttribute('is-mini', '');+ if (width < TAB_SIZE_SMALL) tabEl.setAttribute("is-small", "");+ if (width < TAB_SIZE_SMALLER) tabEl.setAttribute("is-smaller", "");+ if (width < TAB_SIZE_MINI) tabEl.setAttribute("is-mini", "");});- let styleHTML = '';+ let styleHTML = "";- const {tabPositions, newTabPosition, fillerPosition} = this.getTabPositions();+ const { tabPositions, newTabPosition, fillerPosition } = this.getTabPositions();tabPositions.forEach((position, i) => {- styleHTML += `.note-tab:nth-child(${ i + 1 }) { transform: translate3d(${ position }px, 0, 0)} `;+ styleHTML += `.note-tab:nth-child(${i + 1}) { transform: translate3d(${position}px, 0, 0)} `;});- styleHTML += `.note-new-tab { transform: translate3d(${ newTabPosition }px, 0, 0) } `;- styleHTML += `.tab-row-filler { transform: translate3d(${ fillerPosition }px, 0, 0) } `;+ styleHTML += `.note-new-tab { transform: translate3d(${newTabPosition}px, 0, 0) } `;+ styleHTML += `.tab-row-filler { transform: translate3d(${fillerPosition}px, 0, 0) } `;this.$style.html(styleHTML);}addTab(ntxId) {- const $tab = $(TAB_TPL).attr('data-ntx-id', ntxId);+ const $tab = $(TAB_TPL).attr("data-ntx-id", ntxId);keyboardActionService.updateDisplayedShortcuts($tab);- $tab.addClass('note-tab-was-just-added');+ $tab.addClass("note-tab-was-just-added");- setTimeout(() => $tab.removeClass('note-tab-was-just-added'), 500);+ setTimeout(() => $tab.removeClass("note-tab-was-just-added"), 500);this.$newTab.before($tab);this.setVisibility();this.setTabCloseEvent($tab);- this.updateTitle($tab, t('tab_row.new_tab'));+ this.updateTitle($tab, t("tab_row.new_tab"));this.cleanUpPreviouslyDraggedTabs();this.layoutTabs();this.setupDraggabilly();}- closeActiveTabCommand({$el}) {- const ntxId = $el.closest(".note-tab").attr('data-ntx-id');+ closeActiveTabCommand({ $el }) {+ const ntxId = $el.closest(".note-tab").attr("data-ntx-id");appContext.tabManager.removeNoteContext(ntxId);}setTabCloseEvent($tab) {- $tab.on('mousedown', e => {+ $tab.on("mousedown", (e) => {if (e.which === 2) {- appContext.tabManager.removeNoteContext($tab.attr('data-ntx-id'));+ appContext.tabManager.removeNoteContext($tab.attr("data-ntx-id"));return true; // event has been handled}@@ -428,7 +1212,7 @@ export default class TabRowWidget extends BasicWidget {}get activeTabEl() {- return this.$widget.find('.note-tab[active]')[0];+ return this.$widget.find(".note-tab[active]")[0];}activeContextChangedEvent() {@@ -445,11 +1229,11 @@ export default class TabRowWidget extends BasicWidget {const tabEl = this.getTabById(activeNoteContext.ntxId)[0];const activeTabEl = this.activeTabEl;if (activeTabEl === tabEl) return;- if (activeTabEl) activeTabEl.removeAttribute('active');- if (tabEl) tabEl.setAttribute('active', '');+ if (activeTabEl) activeTabEl.removeAttribute("active");+ if (tabEl) tabEl.setAttribute("active", "");}- newNoteContextCreatedEvent({noteContext}) {+ newNoteContextCreatedEvent({ noteContext }) {if (!noteContext.mainNtxId) {this.addTab(noteContext.ntxId);}@@ -468,13 +1252,12 @@ export default class TabRowWidget extends BasicWidget {}getNtxIdsInOrder() {- return this.tabEls.map(el => el.getAttribute('data-ntx-id'));+ return this.tabEls.map((el) => el.getAttribute("data-ntx-id"));}updateTitle($tab, title) {- $tab.attr("title", title)- $tab.find('.note-tab-title')- .text(title);+ $tab.attr("title", title);+ $tab.find(".note-tab-title").text(title);}getTabById(ntxId) {@@ -482,85 +1265,85 @@ export default class TabRowWidget extends BasicWidget {}getTabId($tab) {- return $tab.attr('data-ntx-id');+ return $tab.attr("data-ntx-id");}- noteContextRemovedEvent({ntxIds}) {+ noteContextRemovedEvent({ ntxIds }) {for (const ntxId of ntxIds) {this.removeTab(ntxId);}}cleanUpPreviouslyDraggedTabs() {- this.tabEls.forEach((tabEl) => tabEl.classList.remove('note-tab-was-just-dragged'));+ this.tabEls.forEach((tabEl) => tabEl.classList.remove("note-tab-was-just-dragged"));}setupDraggabilly() {const tabEls = this.tabEls;- const {tabPositions} = this.getTabPositions();+ const { tabPositions } = this.getTabPositions();if (this.isDragging) {this.isDragging = false;- this.$widget.removeClass('tab-row-widget-is-sorting');- this.draggabillyDragging.element.classList.remove('note-tab-is-dragging');- this.draggabillyDragging.element.style.transform = '';+ this.$widget.removeClass("tab-row-widget-is-sorting");+ this.draggabillyDragging.element.classList.remove("note-tab-is-dragging");+ this.draggabillyDragging.element.style.transform = "";this.draggabillyDragging.dragEnd();this.draggabillyDragging.isDragging = false;- this.draggabillyDragging.positionDrag = _ => {}; // Prevent Draggabilly from updating tabEl.style.transform in later frames+ this.draggabillyDragging.positionDrag = (_) => {}; // Prevent Draggabilly from updating tabEl.style.transform in later framesthis.draggabillyDragging.destroy();this.draggabillyDragging = null;}- this.draggabillies.forEach(d => d.destroy());+ this.draggabillies.forEach((d) => d.destroy());tabEls.forEach((tabEl, originalIndex) => {const originalTabPositionX = tabPositions[originalIndex];const draggabilly = new Draggabilly(tabEl, {- axis: 'x',- handle: '.note-tab-drag-handle',+ axis: "x",+ handle: ".note-tab-drag-handle",containment: this.$tabContainer[0]});this.draggabillies.push(draggabilly);- draggabilly.on('pointerDown', _ => {- appContext.tabManager.activateNoteContext(tabEl.getAttribute('data-ntx-id'));+ draggabilly.on("pointerDown", (_) => {+ appContext.tabManager.activateNoteContext(tabEl.getAttribute("data-ntx-id"));});- draggabilly.on('dragStart', _ => {+ draggabilly.on("dragStart", (_) => {this.isDragging = true;this.draggabillyDragging = draggabilly;- tabEl.classList.add('note-tab-is-dragging');- this.$widget.addClass('tab-row-widget-is-sorting');+ tabEl.classList.add("note-tab-is-dragging");+ this.$widget.addClass("tab-row-widget-is-sorting");});- draggabilly.on('dragEnd', _ => {+ draggabilly.on("dragEnd", (_) => {this.isDragging = false;const finalTranslateX = parseFloat(tabEl.style.left);tabEl.style.transform = `translate3d(0, 0, 0)`;// Animate dragged tab back into its place- requestAnimationFrame(_ => {- tabEl.style.left = '0';- tabEl.style.transform = `translate3d(${ finalTranslateX }px, 0, 0)`;+ requestAnimationFrame((_) => {+ tabEl.style.left = "0";+ tabEl.style.transform = `translate3d(${finalTranslateX}px, 0, 0)`;- requestAnimationFrame(_ => {- tabEl.classList.remove('note-tab-is-dragging');- this.$widget.removeClass('tab-row-widget-is-sorting');+ requestAnimationFrame((_) => {+ tabEl.classList.remove("note-tab-is-dragging");+ this.$widget.removeClass("tab-row-widget-is-sorting");- tabEl.classList.add('note-tab-was-just-dragged');+ tabEl.classList.add("note-tab-was-just-dragged");- requestAnimationFrame(_ => {- tabEl.style.transform = '';+ requestAnimationFrame((_) => {+ tabEl.style.transform = "";this.layoutTabs();this.setupDraggabilly();- })- })- })+ });+ });+ });});- draggabilly.on('dragMove', (event, pointer, moveVector) => {+ draggabilly.on("dragMove", (event, pointer, moveVector) => {// The current index be computed within the event since it can change during the dragMoveconst tabEls = this.tabEls;const currentIndex = tabEls.indexOf(tabEl);@@ -574,7 +1357,7 @@ export default class TabRowWidget extends BasicWidget {}if (Math.abs(moveVector.y) > 100) {- this.triggerCommand('moveTabToNewWindow', {ntxId: this.getTabId($(tabEl))});+ this.triggerCommand("moveTabToNewWindow", { ntxId: this.getTabId($(tabEl)) });}});});@@ -588,7 +1371,7 @@ export default class TabRowWidget extends BasicWidget {tabEl.parentNode.insertBefore(tabEl, beforeEl);}- this.triggerEvent('tabReorder', {ntxIdsInOrder: this.getNtxIdsInOrder()});+ this.triggerEvent("tabReorder", { ntxIdsInOrder: this.getNtxIdsInOrder() });this.layoutTabs();}@@ -616,19 +1399,19 @@ export default class TabRowWidget extends BasicWidget {});return closestIndex;- };+ }- noteSwitchedAndActivatedEvent({noteContext}) {+ noteSwitchedAndActivatedEvent({ noteContext }) {this.activeContextChangedEvent();this.updateTabById(noteContext.mainNtxId || noteContext.ntxId);}- noteSwitchedEvent({noteContext}) {+ noteSwitchedEvent({ noteContext }) {this.updateTabById(noteContext.mainNtxId || noteContext.ntxId);}- noteContextReorderEvent({oldMainNtxId, newMainNtxId}) {+ noteContextReorderEvent({ oldMainNtxId, newMainNtxId }) {if (!oldMainNtxId || !newMainNtxId) {// no need to update tab rowreturn;@@ -639,7 +1422,7 @@ export default class TabRowWidget extends BasicWidget {this.updateTabById(newMainNtxId);}- contextsReopenedEvent({mainNtxId, tabPosition}) {+ contextsReopenedEvent({ mainNtxId, tabPosition }) {if (mainNtxId === undefined || tabPosition === undefined) {// no tab reopenedreturn;@@ -665,8 +1448,9 @@ export default class TabRowWidget extends BasicWidget {return;}- for (const clazz of Array.from($tab[0].classList)) { // create copy to safely iterate over while removing classes- if (clazz !== 'note-tab') {+ for (const clazz of Array.from($tab[0].classList)) {+ // create copy to safely iterate over while removing classes+ if (clazz !== "note-tab") {$tab.removeClass(clazz);}}@@ -677,22 +1461,21 @@ export default class TabRowWidget extends BasicWidget {const hoistedNote = froca.getNoteFromCache(noteContext.hoistedNoteId);if (hoistedNote) {- $tab.find('.note-tab-wrapper')- .css("--workspace-tab-background-color", hoistedNote.getWorkspaceTabBackgroundColor());+ $tab.find(".note-tab-wrapper").css("--workspace-tab-background-color", hoistedNote.getWorkspaceTabBackgroundColor());if (!this.showNoteIcons) {noteIcon = hoistedNote.getWorkspaceIconClass();}} else {- $tab.find('.note-tab-wrapper').removeAttr("style");+ $tab.find(".note-tab-wrapper").removeAttr("style");}}- const {note} = noteContext;+ const { note } = noteContext;if (!note) {- this.updateTitle($tab, t('tab_row.new_tab'));+ this.updateTitle($tab, t("tab_row.new_tab"));return;- }+ }const title = await noteContext.getNavigationTitle();this.updateTitle($tab, title);@@ -706,23 +1489,21 @@ export default class TabRowWidget extends BasicWidget {}if (noteIcon) {- $tab.find('.note-tab-icon')- .removeClass()- .addClass("note-tab-icon")- .addClass(noteIcon);+ $tab.find(".note-tab-icon").removeClass().addClass("note-tab-icon").addClass(noteIcon);}}- async entitiesReloadedEvent({loadResults}) {+ async entitiesReloadedEvent({ loadResults }) {for (const noteContext of appContext.tabManager.noteContexts) {if (!noteContext.noteId) {continue;}- if (loadResults.isNoteReloaded(noteContext.noteId) ||- loadResults.getAttributeRows().find(attr =>- ['workspace', 'workspaceIconClass', 'workspaceTabBackgroundColor'].includes(attr.name)- && attributeService.isAffecting(attr, noteContext.note))+ if (+ loadResults.isNoteReloaded(noteContext.noteId) ||+ loadResults+ .getAttributeRows()+ .find((attr) => ["workspace", "workspaceIconClass", "workspaceTabBackgroundColor"].includes(attr.name) && attributeService.isAffecting(attr, noteContext.note))) {const $tab = this.getTabById(noteContext.ntxId);@@ -739,7 +1520,7 @@ export default class TabRowWidget extends BasicWidget {}}- hoistedNoteChangedEvent({ntxId}) {+ hoistedNoteChangedEvent({ ntxId }) {const $tab = this.getTabById(ntxId);if ($tab) {diff --git a/src/public/app/widgets/template_switch.js b/src/public/app/widgets/template_switch.jsindex 16609f6204..e36494c23c 100644--- a/src/public/app/widgets/template_switch.js+++ b/src/public/app/widgets/template_switch.js@@ -6,10 +6,8 @@ import { t } from "../services/i18n.js";* Switch for the basic properties widget which allows the user to select whether the note is a template or not, which toggles the `#template` attribute.*/export default class TemplateSwitchWidget extends SwitchWidget {-isEnabled() {- return super.isEnabled()- && !this.noteId.startsWith('_options');+ return super.isEnabled() && !this.noteId.startsWith("_options");}doRender() {@@ -25,11 +23,11 @@ export default class TemplateSwitchWidget extends SwitchWidget {}async switchOn() {- await attributeService.setLabel(this.noteId, 'template');+ await attributeService.setLabel(this.noteId, "template");}async switchOff() {- for (const templateAttr of this.note.getOwnedLabels('template')) {+ for (const templateAttr of this.note.getOwnedLabels("template")) {await attributeService.removeAttributeById(this.noteId, templateAttr.attributeId);}}@@ -40,10 +38,9 @@ export default class TemplateSwitchWidget extends SwitchWidget {this.$switchOff.toggle(!!isTemplate);}- entitiesReloadedEvent({loadResults}) {- if (loadResults.getAttributeRows().find(attr => attr.type === 'label' && attr.name === "template" && attr.noteId === this.noteId)) {+ entitiesReloadedEvent({ loadResults }) {+ if (loadResults.getAttributeRows().find((attr) => attr.type === "label" && attr.name === "template" && attr.noteId === this.noteId)) {this.refresh();}}--}\ No newline at end of file+}diff --git a/src/public/app/widgets/title_bar_buttons.js b/src/public/app/widgets/title_bar_buttons.jsindex 0e1b590854..d8e389dfdf 100644--- a/src/public/app/widgets/title_bar_buttons.js+++ b/src/public/app/widgets/title_bar_buttons.js@@ -44,26 +44,26 @@ const TPL = `export default class TitleBarButtonsWidget extends BasicWidget {doRender() {- if (!utils.isElectron() || options.is('nativeTitleBarVisible')) {- return this.$widget = $('<div>');+ if (!utils.isElectron() || options.is("nativeTitleBarVisible")) {+ return (this.$widget = $("<div>"));}this.$widget = $(TPL);this.contentSized();-+const $minimizeBtn = this.$widget.find(".minimize-btn");const $maximizeBtn = this.$widget.find(".maximize-btn");const $closeBtn = this.$widget.find(".close-btn");- $minimizeBtn.on('click', () => {- $minimizeBtn.trigger('blur');- const remote = utils.dynamicRequire('@electron/remote');+ $minimizeBtn.on("click", () => {+ $minimizeBtn.trigger("blur");+ const remote = utils.dynamicRequire("@electron/remote");remote.BrowserWindow.getFocusedWindow().minimize();});- $maximizeBtn.on('click', () => {- $maximizeBtn.trigger('blur');- const remote = utils.dynamicRequire('@electron/remote');+ $maximizeBtn.on("click", () => {+ $maximizeBtn.trigger("blur");+ const remote = utils.dynamicRequire("@electron/remote");const focusedWindow = remote.BrowserWindow.getFocusedWindow();if (focusedWindow.isMaximized()) {@@ -73,9 +73,9 @@ export default class TitleBarButtonsWidget extends BasicWidget {}});- $closeBtn.on('click', () => {- $closeBtn.trigger('blur');- const remote = utils.dynamicRequire('@electron/remote');+ $closeBtn.on("click", () => {+ $closeBtn.trigger("blur");+ const remote = utils.dynamicRequire("@electron/remote");remote.BrowserWindow.getFocusedWindow().close();});}diff --git a/src/public/app/widgets/toc.js b/src/public/app/widgets/toc.jsindex 3968c11647..8d9823fd9f 100644--- a/src/public/app/widgets/toc.js+++ b/src/public/app/widgets/toc.js@@ -64,57 +64,55 @@ export default class TocWidget extends RightPanelWidget {.icon("bx-cog").title(t("toc.options")).titlePlacement("left")- .onClick(() => appContext.tabManager.openContextWithNote('_optionsTextNotes', {activate: true}))+ .onClick(() => appContext.tabManager.openContextWithNote("_optionsTextNotes", { activate: true })).class("icon-action"),new OnClickButtonWidget().icon("bx-x").titlePlacement("left")- .onClick(widget => widget.triggerCommand("closeToc"))+ .onClick((widget) => widget.triggerCommand("closeToc")).class("icon-action")];}isEnabled() {- return super.isEnabled()- && this.note.type === 'text'- && !this.noteContext.viewScope.tocTemporarilyHidden- && this.noteContext.viewScope.viewMode === 'default';+ return super.isEnabled() && this.note.type === "text" && !this.noteContext.viewScope.tocTemporarilyHidden && this.noteContext.viewScope.viewMode === "default";}async doRenderBody() {this.$body.empty().append($(TPL));- this.$toc = this.$body.find('.toc');+ this.$toc = this.$body.find(".toc");}async refreshWithNote(note) {/*The reason for adding tocPreviousVisible is to record whether the previous state of the toc is hidden or displayed,- * and then let it be displayed/hidden at the initial time. If there is no such value,- * when the right panel needs to display highlighttext but not toc, every time the note content is changed,- * toc will appear and then close immediately, because getToc(html) function will consume time*/+ * and then let it be displayed/hidden at the initial time. If there is no such value,+ * when the right panel needs to display highlighttext but not toc, every time the note content is changed,+ * toc will appear and then close immediately, because getToc(html) function will consume time*/this.toggleInt(!!this.noteContext.viewScope.tocPreviousVisible);- const tocLabel = note.getLabel('toc');+ const tocLabel = note.getLabel("toc");- if (tocLabel?.value === 'hide') {+ if (tocLabel?.value === "hide") {this.toggleInt(false);this.triggerCommand("reEvaluateRightPaneVisibility");return;}- let $toc = "", headingCount = 0;+ let $toc = "",+ headingCount = 0;// Check for type text unconditionally in case alwaysShowWidget is set- if (this.note.type === 'text') {+ if (this.note.type === "text") {const { content } = await note.getBlob();- ({$toc, headingCount} = await this.getToc(content));+ ({ $toc, headingCount } = await this.getToc(content));}this.$toc.html($toc);- if (["", "show"].includes(tocLabel?.value) || headingCount >= options.getInt('minTocHeadings')){+ if (["", "show"].includes(tocLabel?.value) || headingCount >= options.getInt("minTocHeadings")) {this.toggleInt(true);- this.noteContext.viewScope.tocPreviousVisible=true;- }else{+ this.noteContext.viewScope.tocPreviousVisible = true;+ } else {this.toggleInt(false);- this.noteContext.viewScope.tocPreviousVisible=false;+ this.noteContext.viewScope.tocPreviousVisible = false;}this.triggerCommand("reEvaluateRightPaneVisibility");@@ -142,7 +140,7 @@ export default class TocWidget extends RightPanelWidget {throwOnError: false});} catch (e) {- if (e instanceof ReferenceError && e.message.includes('katex is not defined')) {+ if (e instanceof ReferenceError && e.message.includes("katex is not defined")) {// Load KaTeX if it is not already loadedawait libraryLoader.requireLibrary(libraryLoader.KATEX);try {@@ -187,7 +185,7 @@ export default class TocWidget extends RightPanelWidget {let curLevel = 2;const $ols = [$toc];let headingCount;- for (let m = null, headingIndex = 0; ((m = headingTagsRegex.exec(html)) !== null); headingIndex++) {+ for (let m = null, headingIndex = 0; (m = headingTagsRegex.exec(html)) !== null; headingIndex++) {//// Nest/unnest whatever necessary number of ordered lists//@@ -213,8 +211,8 @@ export default class TocWidget extends RightPanelWidget {// Create the list item and set up the click callback//- const headingText = await this.replaceMathTextWithKatax(m[2])- const $li = $('<li>').html(headingText);+ const headingText = await this.replaceMathTextWithKatax(m[2]);+ const $li = $("<li>").html(headingText);$li.on("click", () => this.jumpToHeading(headingIndex));$ols[$ols.length - 1].append($li);headingCount = headingIndex;@@ -241,7 +239,7 @@ export default class TocWidget extends RightPanelWidget {const $first = $toc.children(":first");- if ($first[0].tagName !== 'OL') {+ if ($first[0].tagName !== "OL") {break;}@@ -273,24 +271,25 @@ export default class TocWidget extends RightPanelWidget {async closeTocCommand() {this.noteContext.viewScope.tocTemporarilyHidden = true;await this.refresh();- this.triggerCommand('reEvaluateRightPaneVisibility');+ this.triggerCommand("reEvaluateRightPaneVisibility");appContext.triggerEvent("reEvaluateTocWidgetVisibility", { noteId: this.noteId });}async showTocWidgetEvent({ noteId }) {if (this.noteId === noteId) {await this.refresh();- this.triggerCommand('reEvaluateRightPaneVisibility');+ this.triggerCommand("reEvaluateRightPaneVisibility");}}async entitiesReloadedEvent({ loadResults }) {if (loadResults.isNoteContentReloaded(this.noteId)) {await this.refresh();- } else if (loadResults.getAttributeRows().find(attr => attr.type === 'label'- && (attr.name.toLowerCase().includes('readonly') || attr.name === 'toc')- && attributeService.isAffecting(attr, this.note))) {-+ } else if (+ loadResults+ .getAttributeRows()+ .find((attr) => attr.type === "label" && (attr.name.toLowerCase().includes("readonly") || attr.name === "toc") && attributeService.isAffecting(attr, this.note))+ ) {await this.refresh();}}diff --git a/src/public/app/widgets/type_widgets/abstract_code_type_widget.js b/src/public/app/widgets/type_widgets/abstract_code_type_widget.jsindex 2a54e4cf08..8baae266ac 100644--- a/src/public/app/widgets/type_widgets/abstract_code_type_widget.js+++ b/src/public/app/widgets/type_widgets/abstract_code_type_widget.js@@ -5,18 +5,17 @@ import options from "../../services/options.js";/*** An abstract {@link TypeWidget} which implements the CodeMirror editor, meant to be used as a parent for* widgets requiring the editor.- *+ ** The widget handles the loading and initialization of the CodeMirror editor, as well as some common* actions.- *+ ** The derived class must:- *+ ** - Define `$editor` in the constructor.* - Call `super.doRender()` in the extended class.* - Call `this._update(note, content)` in `#doRefresh(note)`.*/export default class AbstractCodeTypeWidget extends TypeWidget {-doRender() {this.initialized = this.#initEditor();}@@ -29,20 +28,20 @@ export default class AbstractCodeTypeWidget extends TypeWidget {delete CodeMirror.keyMap.default["Alt-Right"];CodeMirror.modeURL = `${window.glob.assetPath}/node_modules/codemirror/mode/%N/%N.js`;- CodeMirror.modeInfo.find(mode=>mode.name === "JavaScript").mimes.push(...["application/javascript;env=frontend", "application/javascript;env=backend"]);- CodeMirror.modeInfo.find(mode=>mode.name === "SQLite").mimes=["text/x-sqlite", "text/x-sqlite;schema=trilium"];+ CodeMirror.modeInfo.find((mode) => mode.name === "JavaScript").mimes.push(...["application/javascript;env=frontend", "application/javascript;env=backend"]);+ CodeMirror.modeInfo.find((mode) => mode.name === "SQLite").mimes = ["text/x-sqlite", "text/x-sqlite;schema=trilium"];this.codeEditor = CodeMirror(this.$editor[0], {value: "",viewportMargin: Infinity,indentUnit: 4,matchBrackets: true,- matchTags: {bothTags: true},- highlightSelectionMatches: {showToken: false, annotateScrollbar: false},+ matchTags: { bothTags: true },+ highlightSelectionMatches: { showToken: false, annotateScrollbar: false },lineNumbers: true,// we line wrap partly also because without it horizontal scrollbar displays only when you scroll// all the way to the bottom of the note. With line wrap, there's no horizontal scrollbar so no problem- lineWrapping: options.is('codeLineWrapEnabled'),+ lineWrapping: options.is("codeLineWrapEnabled"),...this.getExtraOpts()});this.onEditorInitialized();@@ -50,8 +49,8 @@ export default class AbstractCodeTypeWidget extends TypeWidget {/*** Can be extended in derived classes to add extra options to the CodeMirror constructor. The options are appended- * at the end, so it is possible to override the default values introduced by the abstract editor as well.- *+ * at the end, so it is possible to override the default values introduced by the abstract editor as well.+ ** @returns the extra options to be passed to the CodeMirror constructor.*/getExtraOpts() {@@ -61,7 +60,7 @@ export default class AbstractCodeTypeWidget extends TypeWidget {/*** Called as soon as the CodeMirror library has been loaded and the editor was constructed. Can be extended in* derived classes to add additional functionality or to register event handlers.- *+ ** By default, it does nothing.*/onEditorInitialized() {@@ -70,7 +69,7 @@ export default class AbstractCodeTypeWidget extends TypeWidget {/*** Must be called by the derived classes in `#doRefresh(note)` in order to react to changes.- *+ ** @param {*} note the note that was changed.* @param {*} content the new content of the note.*/@@ -89,12 +88,13 @@ export default class AbstractCodeTypeWidget extends TypeWidget {this.codeEditor.setOption("mode", info.mime);CodeMirror.autoLoadMode(this.codeEditor, info.mode);- };+ }show() {this.$widget.show();- if (this.codeEditor) { // show can be called before render+ if (this.codeEditor) {+ // show can be called before renderthis.codeEditor.refresh();}}@@ -112,9 +112,8 @@ export default class AbstractCodeTypeWidget extends TypeWidget {cleanup() {if (this.codeEditor) {this.spacedUpdate.allowUpdateWithoutChange(() => {- this.codeEditor.setValue('');+ this.codeEditor.setValue("");});}}--}\ No newline at end of file+}diff --git a/src/public/app/widgets/type_widgets/abstract_text_type_widget.js b/src/public/app/widgets/type_widgets/abstract_text_type_widget.jsindex 92409eb1a1..9696b0c903 100644--- a/src/public/app/widgets/type_widgets/abstract_text_type_widget.js+++ b/src/public/app/widgets/type_widgets/abstract_text_type_widget.js@@ -7,24 +7,22 @@ import utils from "../../services/utils.js";import options from "../../services/options.js";export default class AbstractTextTypeWidget extends TypeWidget {-doRender() {super.doRender();this.refreshCodeBlockOptions();}setupImageOpening(singleClickOpens) {- this.$widget.on("dblclick", "img", e => this.openImageInCurrentTab($(e.target)));+ this.$widget.on("dblclick", "img", (e) => this.openImageInCurrentTab($(e.target)));- this.$widget.on("click", "img", e => {+ this.$widget.on("click", "img", (e) => {const isLeftClick = e.which === 1;const isMiddleClick = e.which === 2;const ctrlKey = utils.isCtrlKey(e);if ((isLeftClick && ctrlKey) || isMiddleClick) {this.openImageInNewTab($(e.target));- }- else if (isLeftClick && singleClickOpens) {+ } else if (isLeftClick && singleClickOpens) {this.openImageInCurrentTab($(e.target));}});@@ -32,11 +30,11 @@ export default class AbstractTextTypeWidget extends TypeWidget {async openImageInCurrentTab($img) {const { noteId, viewScope } = await this.parseFromImage($img);-+if (noteId) {appContext.tabManager.getActiveContext().setNote(noteId, { viewScope });} else {- window.open($img.prop("src"), '_blank');+ window.open($img.prop("src"), "_blank");}}@@ -46,7 +44,7 @@ export default class AbstractTextTypeWidget extends TypeWidget {if (noteId) {appContext.tabManager.openTabWithNoteWithHoisting(noteId, { viewScope });} else {- window.open($img.prop("src"), '_blank');+ window.open($img.prop("src"), "_blank");}}@@ -58,7 +56,7 @@ export default class AbstractTextTypeWidget extends TypeWidget {return {noteId: imageNoteMatch[1],viewScope: {}- }+ };}const attachmentMatch = imgSrc.match(/\/api\/attachments\/([A-Za-z0-9_]+)\/image\//);@@ -69,10 +67,10 @@ export default class AbstractTextTypeWidget extends TypeWidget {return {noteId: attachment.ownerId,viewScope: {- viewMode: 'attachments',+ viewMode: "attachments",attachmentId: attachmentId}- }+ };}return null;@@ -88,17 +86,11 @@ export default class AbstractTextTypeWidget extends TypeWidget {showTooltip: false});- $wrapper.empty().append(- $('<h4 class="include-note-title">')- .append($link)- );+ $wrapper.empty().append($('<h4 class="include-note-title">').append($link));- const {$renderedContent, type} = await contentRenderer.getRenderedContent(note);+ const { $renderedContent, type } = await contentRenderer.getRenderedContent(note);- $wrapper.append(- $(`<div class="include-note-content type-${type}">`)- .append($renderedContent)- );+ $wrapper.append($(`<div class="include-note-content type-${type}">`).append($renderedContent));$el.empty().append($wrapper);}@@ -121,10 +113,9 @@ export default class AbstractTextTypeWidget extends TypeWidget {this.$widget.toggleClass("word-wrap", wordWrap);}- async entitiesReloadedEvent({loadResults}) {+ async entitiesReloadedEvent({ loadResults }) {if (loadResults.isOptionReloaded("codeBlockWordWrap")) {- this.refreshCodeBlockOptions();+ this.refreshCodeBlockOptions();}}-}diff --git a/src/public/app/widgets/type_widgets/attachment_detail.js b/src/public/app/widgets/type_widgets/attachment_detail.jsindex 03d15404f5..2a797fba50 100644--- a/src/public/app/widgets/type_widgets/attachment_detail.js+++ b/src/public/app/widgets/type_widgets/attachment_detail.js@@ -38,8 +38,8 @@ export default class AttachmentDetailTypeWidget extends TypeWidget {doRender() {this.$widget = $(TPL);- this.$wrapper = this.$widget.find('.attachment-wrapper');- this.$linksWrapper = this.$widget.find('.links-wrapper');+ this.$wrapper = this.$widget.find(".attachment-wrapper");+ this.$linksWrapper = this.$widget.find(".links-wrapper");super.doRender();}@@ -48,17 +48,21 @@ export default class AttachmentDetailTypeWidget extends TypeWidget {this.$wrapper.empty();this.children = [];- const $helpButton = $('<button class="attachment-help-button" type="button" data-help-page="attachments.html" title="' + t('attachment_detail.open_help_page') + '"><span class="bx bx-help-circle"></span></button>');+ const $helpButton = $(+ '<button class="attachment-help-button" type="button" data-help-page="attachments.html" title="' ++ t("attachment_detail.open_help_page") ++ '"><span class="bx bx-help-circle"></span></button>'+ );utils.initHelpButtons($helpButton);this.$linksWrapper.empty().append(- t('attachment_detail.owning_note'),+ t("attachment_detail.owning_note"),await linkService.createLink(this.noteId),- t('attachment_detail.you_can_also_open'),+ t("attachment_detail.you_can_also_open"),await linkService.createLink(this.noteId, {- title: t('attachment_detail.list_of_all_attachments'),+ title: t("attachment_detail.list_of_all_attachments"),viewScope: {- viewMode: 'attachments'+ viewMode: "attachments"}}),$helpButton@@ -67,7 +71,7 @@ export default class AttachmentDetailTypeWidget extends TypeWidget {const attachment = await froca.getAttachment(this.attachmentId, true);if (!attachment) {- this.$wrapper.html("<strong>" + t('attachment_detail.attachment_deleted') + "</strong>");+ this.$wrapper.html("<strong>" + t("attachment_detail.attachment_deleted") + "</strong>");return;}@@ -77,8 +81,8 @@ export default class AttachmentDetailTypeWidget extends TypeWidget {this.$wrapper.append(attachmentDetailWidget.render());}- async entitiesReloadedEvent({loadResults}) {- const attachmentRow = loadResults.getAttachmentRows().find(att => att.attachmentId === this.attachmentId);+ async entitiesReloadedEvent({ loadResults }) {+ const attachmentRow = loadResults.getAttachmentRows().find((att) => att.attachmentId === this.attachmentId);if (attachmentRow?.isDeleted) {this.refresh(); // all other updates are handled within AttachmentDetailWidgetdiff --git a/src/public/app/widgets/type_widgets/attachment_list.js b/src/public/app/widgets/type_widgets/attachment_list.jsindex 72a8eded7a..09a9fea603 100644--- a/src/public/app/widgets/type_widgets/attachment_list.js+++ b/src/public/app/widgets/type_widgets/attachment_list.js@@ -33,27 +33,28 @@ export default class AttachmentListTypeWidget extends TypeWidget {doRender() {this.$widget = $(TPL);- this.$list = this.$widget.find('.attachment-list-wrapper');- this.$linksWrapper = this.$widget.find('.links-wrapper');+ this.$list = this.$widget.find(".attachment-list-wrapper");+ this.$linksWrapper = this.$widget.find(".links-wrapper");super.doRender();}async doRefresh(note) {- const $helpButton = $('<button class="attachment-help-button" type="button" data-help-page="attachments.html" title="' + t('attachment_list.open_help_page') + '"><span class="bx bx-help-circle"></span></button>');+ const $helpButton = $(+ '<button class="attachment-help-button" type="button" data-help-page="attachments.html" title="' ++ t("attachment_list.open_help_page") ++ '"><span class="bx bx-help-circle"></span></button>'+ );utils.initHelpButtons($helpButton);const noteLink = await linkService.createLink(this.noteId); // do separately to avoid race condition between empty() and .append()this.$linksWrapper.empty().append(- $('<div>').append(- t('attachment_list.owning_note'),- noteLink,- ),- $('<div>').append(+ $("<div>").append(t("attachment_list.owning_note"), noteLink),+ $("<div>").append($('<button class="btn btn-sm">')- .text(t('attachment_list.upload_attachments'))- .on('click', () => this.triggerCommand("showUploadAttachmentsDialog", {noteId: this.noteId})),+ .text(t("attachment_list.upload_attachments"))+ .on("click", () => this.triggerCommand("showUploadAttachmentsDialog", { noteId: this.noteId })),$helpButton));@@ -65,7 +66,7 @@ export default class AttachmentListTypeWidget extends TypeWidget {const attachments = await note.getAttachments();if (attachments.length === 0) {- this.$list.html('<div class="alert alert-info">' + t('attachment_list.no_attachments') + '</div>');+ this.$list.html('<div class="alert alert-info">' + t("attachment_list.no_attachments") + "</div>");return;}@@ -80,10 +81,9 @@ export default class AttachmentListTypeWidget extends TypeWidget {}}- async entitiesReloadedEvent({loadResults}) {+ async entitiesReloadedEvent({ loadResults }) {// updates and deletions are handled by the detail, for new attachments the whole list has to be refreshed- const attachmentsAdded = loadResults.getAttachmentRows()- .some(att => !this.renderedAttachmentIds.has(att.attachmentId));+ const attachmentsAdded = loadResults.getAttachmentRows().some((att) => !this.renderedAttachmentIds.has(att.attachmentId));if (attachmentsAdded) {this.refresh();diff --git a/src/public/app/widgets/type_widgets/book.js b/src/public/app/widgets/type_widgets/book.jsindex 0fa02b7294..17276c3969 100644--- a/src/public/app/widgets/type_widgets/book.js+++ b/src/public/app/widgets/type_widgets/book.js@@ -14,16 +14,18 @@ const TPL = `</style><div class="note-detail-book-empty-help alert alert-warning" style="margin: 50px; padding: 20px;">- ${t('book.no_children_help')}+ ${t("book.no_children_help")}</div></div>`;export default class BookTypeWidget extends TypeWidget {- static getType() { return "book"; }+ static getType() {+ return "book";+ }doRender() {this.$widget = $(TPL);- this.$helpNoChildren = this.$widget.find('.note-detail-book-empty-help');+ this.$helpNoChildren = this.$widget.find(".note-detail-book-empty-help");super.doRender();}diff --git a/src/public/app/widgets/type_widgets/canvas.js b/src/public/app/widgets/type_widgets/canvas.jsindex 0c3d2ffd69..bd4248d11d 100644--- a/src/public/app/widgets/type_widgets/canvas.js+++ b/src/public/app/widgets/type_widgets/canvas.js@@ -1,8 +1,8 @@-import libraryLoader from '../../services/library_loader.js';-import TypeWidget from './type_widget.js';-import utils from '../../services/utils.js';-import linkService from '../../services/link.js';-import server from '../../services/server.js';+import libraryLoader from "../../services/library_loader.js";+import TypeWidget from "./type_widget.js";+import utils from "../../services/utils.js";+import linkService from "../../services/link.js";+import server from "../../services/server.js";const TPL = `<div class="canvas-widget note-detail-canvas note-detail-printable note-detail"><style>@@ -119,7 +119,7 @@ export default class ExcalidrawTypeWidget extends TypeWidget {// these 2 variables are needed to compare the library state (all library items) after loading to the state when the library changed. So we can find attachments to be deleted.//every libraryitem is saved on its own json file in the attachments of the note.this.librarycache = [];- this.attachmentMetadata=[]+ this.attachmentMetadata = [];}static getType() {@@ -128,7 +128,7 @@ export default class ExcalidrawTypeWidget extends TypeWidget {doRender() {this.$widget = $(TPL);- this.$widget.bind('mousewheel DOMMouseScroll', event => {+ this.$widget.bind("mousewheel DOMMouseScroll", (event) => {if (event.ctrlKey) {event.preventDefault();event.stopPropagation();@@ -137,21 +137,19 @@ export default class ExcalidrawTypeWidget extends TypeWidget {});this.$widget.toggleClass("full-height", true);- this.$render = this.$widget.find('.canvas-render');+ this.$render = this.$widget.find(".canvas-render");const documentStyle = window.getComputedStyle(document.documentElement);- this.themeStyle = documentStyle.getPropertyValue('--theme-style')?.trim();-- libraryLoader- .requireLibrary(libraryLoader.EXCALIDRAW)- .then(() => {- const React = window.React;- const ReactDOM = window.ReactDOM;- const renderElement = this.$render.get(0);-- ReactDOM.unmountComponentAtNode(renderElement);- const root = ReactDOM.createRoot(renderElement);- root.render(React.createElement(() => this.createExcalidrawReactApp()));- });+ this.themeStyle = documentStyle.getPropertyValue("--theme-style")?.trim();++ libraryLoader.requireLibrary(libraryLoader.EXCALIDRAW).then(() => {+ const React = window.React;+ const ReactDOM = window.ReactDOM;+ const renderElement = this.$render.get(0);++ ReactDOM.unmountComponentAtNode(renderElement);+ const root = ReactDOM.createRoot(renderElement);+ root.render(React.createElement(() => this.createExcalidrawReactApp()));+ });return this.$widget;}@@ -195,14 +193,13 @@ export default class ExcalidrawTypeWidget extends TypeWidget {};this.excalidrawApi.updateScene(sceneData);- }- else if (blob.content) {+ } else if (blob.content) {// load saved content into excalidraw canvaslet content;try {content = blob.getJsonContent();- } catch(err) {+ } catch (err) {console.error("Error parsing content. Probably note.type changed. Starting with empty canvas", note, blob, err);content = {@@ -212,7 +209,7 @@ export default class ExcalidrawTypeWidget extends TypeWidget {};}- const {elements, files, appState = {}} = content;+ const { elements, files, appState = {} } = content;appState.theme = this.themeStyle;@@ -242,46 +239,42 @@ export default class ExcalidrawTypeWidget extends TypeWidget {}Promise.all(- (await note.getAttachmentsByRole('canvasLibraryItem'))- .map(async attachment => {- const blob = await attachment.getBlob();- return {- blob, // Save the blob for libraryItems- metadata: { // metadata to use in the cache variables for comparing old library state and new one. We delete unnecessary items later, calling the server directly- attachmentId: attachment.attachmentId,- title: attachment.title,- },- };- })- ).then(results => {+ (await note.getAttachmentsByRole("canvasLibraryItem")).map(async (attachment) => {+ const blob = await attachment.getBlob();+ return {+ blob, // Save the blob for libraryItems+ metadata: {+ // metadata to use in the cache variables for comparing old library state and new one. We delete unnecessary items later, calling the server directly+ attachmentId: attachment.attachmentId,+ title: attachment.title+ }+ };+ })+ ).then((results) => {if (note.noteId !== this.currentNoteId) {// current note changed in the course of the async operationreturn;}-+// Extract libraryItems from the blobs- const libraryItems = results- .map(result => result.blob.getJsonContentSafely())- .filter(item => !!item);-+ const libraryItems = results.map((result) => result.blob.getJsonContentSafely()).filter((item) => !!item);+// Extract metadata for each attachment- const metadata = results.map(result => result.metadata);-+ const metadata = results.map((result) => result.metadata);+// Update the library and save to independent variablesthis.excalidrawApi.updateLibrary({ libraryItems, merge: false });-+// save state of library to compare it to the new state later.this.librarycache = libraryItems;this.attachmentMetadata = metadata;});-+// Update the scenethis.excalidrawApi.updateScene(sceneData);this.excalidrawApi.addFiles(fileArray);this.excalidrawApi.history.clear();}--// set initial scene versionif (this.currentSceneVersion === this.SCENE_VERSION_INITIAL) {@@ -308,7 +301,7 @@ export default class ExcalidrawTypeWidget extends TypeWidget {elements,appState,exportPadding: 5, // 5 px padding- metadata: 'trilium-export',+ metadata: "trilium-export",files});const svgString = svg.outerHTML;@@ -332,64 +325,54 @@ export default class ExcalidrawTypeWidget extends TypeWidget {}};- const attachments = [- { role: 'image', title: 'canvas-export.svg', mime: 'image/svg+xml', content: svgString, position: 0 }- ];+ const attachments = [{ role: "image", title: "canvas-export.svg", mime: "image/svg+xml", content: svgString, position: 0 }];if (this.libraryChanged) {// this.libraryChanged is unset in dataSaved()// there's no separate method to get library items, so have to abuse this one- const libraryItems = await this.excalidrawApi.updateLibrary({merge: true});+ const libraryItems = await this.excalidrawApi.updateLibrary({ merge: true });// excalidraw saves the library as a own state. the items are saved to libraryItems. then we compare the library right now with a libraryitemcache. The cache is filled when we first load the Library into the note.//We need the cache to delete old attachments later in the server.- const libraryItemsMissmatch = this.librarycache.filter(obj1 => !libraryItems.some(obj2 => obj1.id === obj2.id));-+ const libraryItemsMissmatch = this.librarycache.filter((obj1) => !libraryItems.some((obj2) => obj1.id === obj2.id));// before we saved the metadata of the attachments in a cache. the title of the attachment is a combination of libraryitem ´s ID und it´s name.// we compare the library items in the libraryitemmissmatch variable (this one saves all libraryitems that are different to the state right now. E.g. you delete 1 item, this item is saved as mismatch)// then we combine its id and title and search the according attachmentID.-- const matchingItems = this.attachmentMetadata.filter(meta => {++ const matchingItems = this.attachmentMetadata.filter((meta) => {// Loop through the second array and check for a match- return libraryItemsMissmatch.some(item => {+ return libraryItemsMissmatch.some((item) => {// Combine the `name` and `id` from the second arrayconst combinedTitle = `${item.id}${item.name}`;return meta.title === combinedTitle;});});-- // we save the attachment ID`s in a variable and delete every attachmentID. Now the items that the user deleted will be deleted.- const attachmentIds = matchingItems.map(item => item.attachmentId);-+ // we save the attachment ID`s in a variable and delete every attachmentID. Now the items that the user deleted will be deleted.+ const attachmentIds = matchingItems.map((item) => item.attachmentId);//delete old attachments that are no longer used- for (const item of attachmentIds){-- await server.remove(`attachments/${item}`);-+ for (const item of attachmentIds) {+ await server.remove(`attachments/${item}`);}let position = 10;- // prepare data to save to server e.g. new library items.+ // prepare data to save to server e.g. new library items.for (const libraryItem of libraryItems) {-attachments.push({- role: 'canvasLibraryItem',+ role: "canvasLibraryItem",title: libraryItem.id + libraryItem.name,- mime: 'application/json',+ mime: "application/json",content: JSON.stringify(libraryItem),position: position-});-+position += 10;}-}return {@@ -448,7 +431,7 @@ export default class ExcalidrawTypeWidget extends TypeWidget {setDimensions(dimensions);const onResize = () => {- if (this.note?.type !== 'canvas') {+ if (this.note?.type !== "canvas") {return;}@@ -476,7 +459,7 @@ export default class ExcalidrawTypeWidget extends TypeWidget {event.preventDefault();return linkService.goToLinkExt(nativeEvent, link, null);- }, []);+ }, []);return React.createElement(React.Fragment,@@ -490,7 +473,9 @@ export default class ExcalidrawTypeWidget extends TypeWidget {React.createElement(Excalidraw, {// this makes sure that 1) manual theme switch button is hidden 2) theme stays as it should after opening menutheme: this.themeStyle,- excalidrawAPI: api => { this.excalidrawApi = api; },+ excalidrawAPI: (api) => {+ this.excalidrawApi = api;+ },width: dimensions.width,height: dimensions.height,onPaste: (data, event) => {@@ -526,11 +511,13 @@ export default class ExcalidrawTypeWidget extends TypeWidget {** info: sceneVersions are not incrementing. it seems to be a pseudo-random number*/- isNewSceneVersion() {+ isNewSceneVersion() {const sceneVersion = this.getSceneVersion();- return this.currentSceneVersion === this.SCENE_VERSION_INITIAL // initial scene version update- || this.currentSceneVersion !== sceneVersion; // ensure scene changed+ return (+ this.currentSceneVersion === this.SCENE_VERSION_INITIAL || // initial scene version update+ this.currentSceneVersion !== sceneVersion+ ); // ensure scene changed}getSceneVersion() {diff --git a/src/public/app/widgets/type_widgets/ckeditor/syntax_highlight.js b/src/public/app/widgets/type_widgets/ckeditor/syntax_highlight.jsindex 771b20d8c3..ab6dd562ea 100644--- a/src/public/app/widgets/type_widgets/ckeditor/syntax_highlight.js+++ b/src/public/app/widgets/type_widgets/ckeditor/syntax_highlight.js@@ -1,10 +1,10 @@/** This code is an adaptation of https://github.com/antoniotejada/Trilium-SyntaxHighlightWidget with additional improvements, such as:- *+ ** - support for selecting the language manually;* - support for determining the language automatically, if a special language is selected ("Auto-detected");* - limit for highlighting.- *+ ** TODO: Generally this class can be done directly in the CKEditor repository.*/@@ -27,22 +27,22 @@ const tag = "SyntaxHighlightWidget";const debugLevels = ["error", "warn", "info", "log", "debug"];const debugLevel = "debug";-let warn = function() {};+let warn = function () {};if (debugLevel >= debugLevels.indexOf("warn")) {warn = console.warn.bind(console, tag + ": ");}-let info = function() {};+let info = function () {};if (debugLevel >= debugLevels.indexOf("info")) {info = console.info.bind(console, tag + ": ");}-let log = function() {};+let log = function () {};if (debugLevel >= debugLevels.indexOf("log")) {log = console.log.bind(console, tag + ": ");}-let dbg = function() {};+let dbg = function () {};if (debugLevel >= debugLevels.indexOf("debug")) {dbg = console.debug.bind(console, tag + ": ");}@@ -60,42 +60,41 @@ function initTextEditor(textEditor) {let widget = this;const document = textEditor.model.document;- // Create a conversion from model to view that converts+ // Create a conversion from model to view that converts// hljs:hljsClassName:uniqueId into a span with hljsClassName// See the list of hljs class names at// https://github.com/highlightjs/highlight.js/blob/6b8c831f00c4e87ecd2189ebbd0bb3bbdde66c02/docs/css-classes-reference.rst- textEditor.conversion.for('editingDowncast').markerToHighlight( {+ textEditor.conversion.for("editingDowncast").markerToHighlight({model: "hljs",- view: ( { markerName } ) => {+ view: ({ markerName }) => {dbg("markerName " + markerName);// markerName has the pattern addMarker:cssClassName:uniqueId- const [ , cssClassName, id ] = markerName.split( ':' );+ const [, cssClassName, id] = markerName.split(":");- // The original code at+ // The original code at// https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-find-and-replace/src/findandreplaceediting.js// has this comment- // Marker removal from the view has a bug:+ // Marker removal from the view has a bug:// https://github.com/ckeditor/ckeditor5/issues/7499// A minimal option is to return a new object for each converted marker...return {- name: 'span',- classes: [ cssClassName ],+ name: "span",+ classes: [cssClassName],attributes: {// ...however, adding a unique attribute should be future-proof..- 'data-syntax-result': id- },+ "data-syntax-result": id+ }};}});-// XXX This is done at BalloonEditor.create time, so it assumes this// document is always attached to this textEditor, empirically that// seems to be the case even with two splits showing the same note,// it's not clear if CKEditor5 has apis to attach and detach// documents around- document.registerPostFixer(function(writer) {+ document.registerPostFixer(function (writer) {log("postFixer");// Postfixers are a simpler way of tracking changes than onchange// See@@ -106,7 +105,7 @@ function initTextEditor(textEditor) {for (const change of changes) {dbg("change " + JSON.stringify(change));- if ((change.type == "insert") && (change.name == "codeBlock")) {+ if (change.type == "insert" && change.name == "codeBlock") {// A new code block was insertedconst codeBlock = change.position.nodeAfter;// Even if it's a new codeblock, it needs dirtying in case@@ -115,16 +114,13 @@ function initTextEditor(textEditor) {// etc (the postfixer won't get later changes for those).log("dirtying inserted codeBlock " + JSON.stringify(codeBlock.toJSON()));dirtyCodeBlocks.add(codeBlock);-- } else if (change.type == "remove" && (change.name == "codeBlock")) {+ } else if (change.type == "remove" && change.name == "codeBlock") {// An existing codeblock was removed, do nothing. Note the// node is no longer in the editor so the codeblock cannot// be inspected here. No need to dirty the codeblock since// it has been removedlog("removing codeBlock at path " + JSON.stringify(change.position.toJSON()));-- } else if (((change.type == "remove") || (change.type == "insert")) &&- change.position.parent.is('element', 'codeBlock')) {+ } else if ((change.type == "remove" || change.type == "insert") && change.position.parent.is("element", "codeBlock")) {// Text was added or removed from the codeblock, force a// highlightconst codeBlock = change.position.parent;@@ -143,19 +139,16 @@ function initTextEditor(textEditor) {// This assumes the document is empty and a explicit call to highlight// is not necessary here. Empty documents have a single children of type// paragraph with no text- assert((document.getRoot().childCount == 1) &&- (document.getRoot().getChild(0).name == "paragraph") &&- document.getRoot().getChild(0).isEmpty);-+ assert(document.getRoot().childCount == 1 && document.getRoot().getChild(0).name == "paragraph" && document.getRoot().getChild(0).isEmpty);}/*** This implements highlighting via ephemeral markers (not stored in the- * document).+ * document).** XXX Another option would be to use formatting markers, which would have* the benefit of making it work for readonly notes. On the flip side,- * the formatting would be stored with the note and it would need a+ * the formatting would be stored with the note and it would need a* way to remove that formatting when editing back the note.*/function highlightCodeBlock(codeBlock, writer) {@@ -196,7 +189,7 @@ function highlightCodeBlock(codeBlock, writer) {if (codeBlock.childCount >= HIGHLIGHT_MAX_BLOCK_COUNT) {return;}-+// highlight.js needs the full text without HTML tags, eg for the// text// #include <stdio.h>@@ -226,12 +219,9 @@ function highlightCodeBlock(codeBlock, writer) {if (child.is("$text")) {dbg("child text " + child.data);text += child.data;-- } else if (child.is("element") &&- (child.name == "softBreak")) {+ } else if (child.is("element") && child.name == "softBreak") {dbg("softBreak");text += "\n";-} else {warn("Unkown child " + JSON.stringify(child.toJSON()));}@@ -278,21 +268,21 @@ function highlightCodeBlock(codeBlock, writer) {// needs to be dealt with belowchildText = "";}- }+ }// This parsing is made slightly simpler and faster by only// expecting <span> and </span> tags in the highlighted html- if ((html[iHtml] == "<") && (html[iHtml+1] != "/")) {+ if (html[iHtml] == "<" && html[iHtml + 1] != "/") {// new span, note they can be nested eg C preprocessor lines// are inside a hljs-meta span, hljs-title function names// inside a hljs-function span, etc- let iStartQuot = html.indexOf("\"", iHtml+1);- let iEndQuot = html.indexOf("\"", iStartQuot+1);- let className = html.slice(iStartQuot+1, iEndQuot);+ let iStartQuot = html.indexOf('"', iHtml + 1);+ let iEndQuot = html.indexOf('"', iStartQuot + 1);+ let className = html.slice(iStartQuot + 1, iEndQuot);// XXX highlight js uses scope for Python "title function_",- // etc for now just use the first style only+ // etc for now just use the first style only// See https://highlightjs.readthedocs.io/en/latest/css-classes-reference.html#a-note-on-scopes-with-sub-scopes- let iBlank = className.indexOf(" ");+ let iBlank = className.indexOf(" ");if (iBlank > 0) {className = className.slice(0, iBlank);}@@ -300,13 +290,12 @@ function highlightCodeBlock(codeBlock, writer) {iHtml = html.indexOf(">", iHtml) + 1;- // push the span+ // push the spanlet posStart = writer.createPositionAt(codeBlock, child.startOffset + iChildText);- spanStack.push({ "className" : className, "posStart": posStart});-- } else if ((html[iHtml] == "<") && (html[iHtml+1] == "/")) {+ spanStack.push({ className: className, posStart: posStart });+ } else if (html[iHtml] == "<" && html[iHtml + 1] == "/") {// Done with this span, pop the span and mark the range- iHtml = html.indexOf(">", iHtml+1) + 1;+ iHtml = html.indexOf(">", iHtml + 1) + 1;let stackTop = spanStack.pop();let posStart = stackTop.posStart;@@ -321,17 +310,13 @@ function highlightCodeBlock(codeBlock, writer) {// Wrap-around for good measure so all numbers are positive// XXX Another option is to catch the exception and retry or// go through the markers and get the largest + 1- markerCounter = (markerCounter + 1) & 0xFFFFFF;+ markerCounter = (markerCounter + 1) & 0xffffff;dbg("Found span end " + className);dbg("Adding marker " + markerName + ": " + JSON.stringify(range.toJSON()));- writer.addMarker(markerName, {"range": range, "usingOperation": false});-+ writer.addMarker(markerName, { range: range, usingOperation: false });} else {// Text, we should also have text in the children- assert(- ((iChild < codeBlock.childCount) && (iChildText < childText.length)),- "Found text in html with no corresponding child text!!!!"- );+ assert(iChild < codeBlock.childCount && iChildText < childText.length, "Found text in html with no corresponding child text!!!!");if (html[iHtml] == "&") {// highlight.js only encodes// .replace(/&/g, '&')diff --git a/src/public/app/widgets/type_widgets/content/backend_log.js b/src/public/app/widgets/type_widgets/content/backend_log.jsindex 1ae4f85f68..31b53d4f8d 100644--- a/src/public/app/widgets/type_widgets/content/backend_log.js+++ b/src/public/app/widgets/type_widgets/content/backend_log.js@@ -26,7 +26,7 @@ export default class BackendLogWidget extends AbstractCodeTypeWidget {this.$editor = this.$widget.find(".backend-log-editor");this.$refreshBackendLog = this.$widget.find(".refresh-backend-log-button");- this.$refreshBackendLog.on('click', () => this.load());+ this.$refreshBackendLog.on("click", () => this.load());}async refresh() {@@ -41,12 +41,15 @@ export default class BackendLogWidget extends AbstractCodeTypeWidget {}async load() {- const content = await server.get('backend-log');+ const content = await server.get("backend-log");await this.initialized;- this._update({- mime: "text/plain"- }, content);+ this._update(+ {+ mime: "text/plain"+ },+ content+ );this.show();this.scrollToEnd();}diff --git a/src/public/app/widgets/type_widgets/content_widget.js b/src/public/app/widgets/type_widgets/content_widget.jsindex e8c5e4829f..a7da6c4a47 100644--- a/src/public/app/widgets/type_widgets/content_widget.js+++ b/src/public/app/widgets/type_widgets/content_widget.js@@ -56,35 +56,16 @@ const TPL = `<div class="note-detail-content-widget note-detail-printable"></div>`;const CONTENT_WIDGETS = {- _optionsAppearance: [- LocalizationOptions,- ThemeOptions,- FontsOptions,- CodeBlockOptions,- ElectronIntegrationOptions,- MaxContentWidthOptions,- RibbonOptions- ],- _optionsShortcuts: [ KeyboardShortcutsOptions ],- _optionsTextNotes: [- EditorOptions,- HeadingStyleOptions,- TableOfContentsOptions,- HighlightsListOptions,- TextAutoReadOnlySizeOptions- ],- _optionsCodeNotes: [- VimKeyBindingsOptions,- WrapLinesOptions,- CodeAutoReadOnlySizeOptions,- CodeMimeTypesOptions- ],- _optionsImages: [ ImageOptions ],- _optionsSpellcheck: [ SpellcheckOptions ],- _optionsPassword: [ PasswordOptions ],- _optionsEtapi: [ EtapiOptions ],- _optionsBackup: [ BackupOptions ],- _optionsSync: [ SyncOptions ],+ _optionsAppearance: [LocalizationOptions, ThemeOptions, FontsOptions, CodeBlockOptions, ElectronIntegrationOptions, MaxContentWidthOptions, RibbonOptions],+ _optionsShortcuts: [KeyboardShortcutsOptions],+ _optionsTextNotes: [EditorOptions, HeadingStyleOptions, TableOfContentsOptions, HighlightsListOptions, TextAutoReadOnlySizeOptions],+ _optionsCodeNotes: [VimKeyBindingsOptions, WrapLinesOptions, CodeAutoReadOnlySizeOptions, CodeMimeTypesOptions],+ _optionsImages: [ImageOptions],+ _optionsSpellcheck: [SpellcheckOptions],+ _optionsPassword: [PasswordOptions],+ _optionsEtapi: [EtapiOptions],+ _optionsBackup: [BackupOptions],+ _optionsSync: [SyncOptions],_optionsOther: [SearchEngineOptions,TrayOptions,@@ -95,17 +76,14 @@ const CONTENT_WIDGETS = {NetworkConnectionsOptions,HtmlImportTagsOptions],- _optionsAdvanced: [- DatabaseIntegrityCheckOptions,- DatabaseAnonymizationOptions,- AdvancedSyncOptions,- VacuumDatabaseOptions- ],- _backendLog: [ BackendLogWidget ]+ _optionsAdvanced: [DatabaseIntegrityCheckOptions, DatabaseAnonymizationOptions, AdvancedSyncOptions, VacuumDatabaseOptions],+ _backendLog: [BackendLogWidget]};export default class ContentWidgetTypeWidget extends TypeWidget {- static getType() { return "contentWidget"; }+ static getType() {+ return "contentWidget";+ }doRender() {this.$widget = $(TPL);@@ -125,7 +103,7 @@ export default class ContentWidgetTypeWidget extends TypeWidget {for (const clazz of contentWidgets) {const widget = new clazz();- await widget.handleEvent('setNoteContext', { noteContext: this.noteContext });+ await widget.handleEvent("setNoteContext", { noteContext: this.noteContext });this.child(widget);this.$content.append(widget.render());diff --git a/src/public/app/widgets/type_widgets/doc.js b/src/public/app/widgets/type_widgets/doc.jsindex 5ca738f26e..4fd2d76f0a 100644--- a/src/public/app/widgets/type_widgets/doc.js+++ b/src/public/app/widgets/type_widgets/doc.js@@ -18,24 +18,26 @@ const TPL = `<div class="note-detail-doc note-detail-printable"></div>`;export default class DocTypeWidget extends TypeWidget {- static getType() { return "doc"; }+ static getType() {+ return "doc";+ }doRender() {this.$widget = $(TPL);- this.$content = this.$widget.find('.note-detail-doc-content');+ this.$content = this.$widget.find(".note-detail-doc-content");super.doRender();}async doRefresh(note) {- const docName = note.getLabelValue('docName');+ const docName = note.getLabelValue("docName");if (docName) {// find doc based on languageconst lng = i18next.language;this.$content.load(`${window.glob.appPath}/doc_notes/${lng}/${docName}.html`, (response, status) => {// fallback to english doc if no translation available- if (status === 'error') {+ if (status === "error") {this.$content.load(`${window.glob.appPath}/doc_notes/en/${docName}.html`);}});diff --git a/src/public/app/widgets/type_widgets/editable_code.js b/src/public/app/widgets/type_widgets/editable_code.jsindex a62f3fafbb..78a266a57a 100644--- a/src/public/app/widgets/type_widgets/editable_code.js+++ b/src/public/app/widgets/type_widgets/editable_code.js@@ -21,31 +21,33 @@ const TPL = `</div>`;export default class EditableCodeTypeWidget extends AbstractCodeTypeWidget {- static getType() { return "editableCode"; }+ static getType() {+ return "editableCode";+ }doRender() {this.$widget = $(TPL);this.contentSized();- this.$editor = this.$widget.find('.note-detail-code-editor');+ this.$editor = this.$widget.find(".note-detail-code-editor");- keyboardActionService.setupActionsForElement('code-detail', this.$widget, this);+ keyboardActionService.setupActionsForElement("code-detail", this.$widget, this);- super.doRender();+ super.doRender();}-+getExtraOpts() {return {- keyMap: options.is('vimKeymapEnabled') ? "vim": "default",+ keyMap: options.is("vimKeymapEnabled") ? "vim" : "default",lint: true,gutters: ["CodeMirror-lint-markers"],tabindex: 300,dragDrop: false, // with true the editor inlines dropped files which is not what we expect- placeholder: t('editable_code.placeholder'),+ placeholder: t("editable_code.placeholder")};}onEditorInitialized() {- this.codeEditor.on('change', () => this.spacedUpdate.scheduleUpdate());+ this.codeEditor.on("change", () => this.spacedUpdate.scheduleUpdate());}async doRefresh(note) {@@ -64,7 +66,7 @@ export default class EditableCodeTypeWidget extends AbstractCodeTypeWidget {};}- async executeWithCodeEditorEvent({resolve, ntxId}) {+ async executeWithCodeEditorEvent({ resolve, ntxId }) {if (!this.isNoteContext(ntxId)) {return;}diff --git a/src/public/app/widgets/type_widgets/editable_text.js b/src/public/app/widgets/type_widgets/editable_text.jsindex d36d4230eb..dd5096a60f 100644--- a/src/public/app/widgets/type_widgets/editable_text.js+++ b/src/public/app/widgets/type_widgets/editable_text.js@@ -1,7 +1,7 @@import { t } from "../../services/i18n.js";import libraryLoader from "../../services/library_loader.js";-import noteAutocompleteService from '../../services/note_autocomplete.js';-import mimeTypesService from '../../services/mime_types.js';+import noteAutocompleteService from "../../services/note_autocomplete.js";+import mimeTypesService from "../../services/mime_types.js";import utils from "../../services/utils.js";import keyboardActionService from "../../services/keyboard_actions.js";import froca from "../../services/froca.js";@@ -20,10 +20,10 @@ const ENABLE_INSPECTOR = false;const mentionSetup = {feeds: [{- marker: '@',- feed: queryText => noteAutocompleteService.autocompleteSourceForCKEditor(queryText),- itemRenderer: item => {- const itemElement = document.createElement('button');+ marker: "@",+ feed: (queryText) => noteAutocompleteService.autocompleteSourceForCKEditor(queryText),+ itemRenderer: (item) => {+ const itemElement = document.createElement("button");itemElement.innerHTML = `${item.highlightedNotePathTitle} `;@@ -92,12 +92,13 @@ const TPL = ``;function buildListOfLanguages() {- const userLanguages = (mimeTypesService.getMimeTypes())- .filter(mt => mt.enabled)- .map(mt => ({- language: mimeTypesService.normalizeMimeTypeForCKEditor(mt.mime),- label: mt.title- }));+ const userLanguages = mimeTypesService+ .getMimeTypes()+ .filter((mt) => mt.enabled)+ .map((mt) => ({+ language: mimeTypesService.normalizeMimeTypeForCKEditor(mt.mime),+ label: mt.title+ }));return [{@@ -115,15 +116,17 @@ function buildListOfLanguages() {* - Decoupled mode, in which the editing toolbar is actually added on the client side (in {@link ClassicEditorToolbar}), see https://ckeditor.com/docs/ckeditor5/latest/examples/framework/bottom-toolbar-editor.html for an example on how the decoupled editor works.*/export default class EditableTextTypeWidget extends AbstractTextTypeWidget {- static getType() { return "editableText"; }+ static getType() {+ return "editableText";+ }doRender() {this.$widget = $(TPL);- this.$editor = this.$widget.find('.note-detail-editable-text-editor');+ this.$editor = this.$widget.find(".note-detail-editable-text-editor");this.initialized = this.initEditor();- keyboardActionService.setupActionsForElement('text-detail', this.$widget, this);+ keyboardActionService.setupActionsForElement("text-detail", this.$widget, this);this.setupImageOpening(false);@@ -132,8 +135,8 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {async initEditor() {await libraryLoader.requireLibrary(libraryLoader.CKEDITOR);- const isClassicEditor = (options.get("textNoteEditorType") === "ckeditor-classic")- const editorClass = (isClassicEditor ? CKEditor.DecoupledEditor : CKEditor.BalloonEditor);+ const isClassicEditor = options.get("textNoteEditorType") === "ckeditor-classic";+ const editorClass = isClassicEditor ? CKEditor.DecoupledEditor : CKEditor.BalloonEditor;const codeBlockLanguages = buildListOfLanguages();@@ -159,21 +162,21 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {saveInterval: 5000});- this.watchdog.on('stateChange', () => {+ this.watchdog.on("stateChange", () => {const currentState = this.watchdog.state;- if (!['crashed', 'crashedPermanently'].includes(currentState)) {+ if (!["crashed", "crashedPermanently"].includes(currentState)) {return;}console.log(`CKEditor changed to ${currentState}`);- this.watchdog.crashes.forEach(crashInfo => console.log(crashInfo));+ this.watchdog.crashes.forEach((crashInfo) => console.log(crashInfo));- if (currentState === 'crashedPermanently') {+ if (currentState === "crashedPermanently") {dialogService.info(`Editing component keeps crashing. Please try restarting Trilium. If problem persists, consider creating a bug report.`);- this.watchdog.editor.enableReadOnlyMode('crashed-editor');+ this.watchdog.editor.enableReadOnlyMode("crashed-editor");}});@@ -236,10 +239,10 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {}}- editor.model.document.on('change:data', () => this.spacedUpdate.scheduleUpdate());+ editor.model.document.on("change:data", () => this.spacedUpdate.scheduleUpdate());if (glob.isDev && ENABLE_INSPECTOR) {- await import(/* webpackIgnore: true */'../../../libraries/ckeditor/inspector.js');+ await import(/* webpackIgnore: true */ "../../../libraries/ckeditor/inspector.js");CKEditorInspector.attach(editor);}@@ -247,14 +250,14 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {});await this.watchdog.create(this.$editor[0], {- placeholder: t('editable_text.placeholder'),+ placeholder: t("editable_text.placeholder"),mention: mentionSetup,codeBlock: {languages: codeBlockLanguages},math: {- engine: 'katex',- outputType: 'span', // or script+ engine: "katex",+ outputType: "span", // or scriptlazyLoad: async () => await libraryLoader.requireLibrary(libraryLoader.KATEX),forceOutputType: false, // forces output to use outputTypeenablePreview: true // Enable preview view@@ -269,8 +272,7 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {async doRefresh(note) {const blob = await note.getBlob();- await this.spacedUpdate.allowUpdateWithoutChange(() =>- this.watchdog.editor.setData(blob.content || ""));+ await this.spacedUpdate.allowUpdateWithoutChange(() => this.watchdog.editor.setData(blob.content || ""));}getData() {@@ -279,17 +281,17 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {// if content is only tags/whitespace (typically <p> </p>), then just make it empty,// this is important when setting a new note to codereturn {- content: utils.isHtmlEmpty(content) ? '' : content+ content: utils.isHtmlEmpty(content) ? "" : content};}focus() {- this.$editor.trigger('focus');+ this.$editor.trigger("focus");}scrollToEnd() {- this.watchdog?.editor.model.change(writer => {- writer.setSelection(writer.createPositionAt(this.watchdog?.editor.model.document.getRoot(), 'end'));+ this.watchdog?.editor.model.change((writer) => {+ writer.setSelection(writer.createPositionAt(this.watchdog?.editor.model.document.getRoot(), "end"));});this.watchdog?.editor.editing.view.focus();@@ -304,7 +306,7 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {cleanup() {if (this.watchdog?.editor) {this.spacedUpdate.allowUpdateWithoutChange(() => {- this.watchdog.editor.setData('');+ this.watchdog.editor.setData("");});}}@@ -319,22 +321,22 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {async addLinkToEditor(linkHref, linkTitle) {await this.initialized;- this.watchdog.editor.model.change(writer => {+ this.watchdog.editor.model.change((writer) => {const insertPosition = this.watchdog.editor.model.document.selection.getFirstPosition();- writer.insertText(linkTitle, {linkHref: linkHref}, insertPosition);+ writer.insertText(linkTitle, { linkHref: linkHref }, insertPosition);});}async addTextToEditor(text) {await this.initialized;- this.watchdog.editor.model.change(writer => {+ this.watchdog.editor.model.change((writer) => {const insertPosition = this.watchdog.editor.model.document.selection.getLastPosition();writer.insertText(text, insertPosition);});}- addTextToActiveEditorEvent({text}) {+ addTextToActiveEditorEvent({ text }) {if (!this.isActive()) {return;}@@ -347,13 +349,12 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {if (linkTitle) {if (this.hasSelection()) {- this.watchdog.editor.execute('link', `#${notePath}`);+ this.watchdog.editor.execute("link", `#${notePath}`);} else {await this.addLinkToEditor(`#${notePath}`, linkTitle);}- }- else {- this.watchdog.editor.execute('referenceLink', { href: '#' + notePath });+ } else {+ this.watchdog.editor.execute("referenceLink", { href: "#" + notePath });}this.watchdog.editor.editing.view.focus();@@ -367,7 +368,7 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {return !selection.isCollapsed;}- async executeWithTextEditorEvent({callback, resolve, ntxId}) {+ async executeWithTextEditorEvent({ callback, resolve, ntxId }) {if (!this.isNoteContext(ntxId)) {return;}@@ -384,12 +385,12 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {addLinkToTextCommand() {const selectedText = this.getSelectedText();- this.triggerCommand('showAddLinkDialog', {textTypeWidget: this, text: selectedText})+ this.triggerCommand("showAddLinkDialog", { textTypeWidget: this, text: selectedText });}getSelectedText() {const range = this.watchdog.editor.model.document.selection.getFirstRange();- let text = '';+ let text = "";for (const item of range.getItems()) {if (item.data) {@@ -406,9 +407,9 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {const selection = this.watchdog.editor.model.document.selection;const selectedElement = selection.getSelectedElement();- if (selectedElement?.name === 'reference') {+ if (selectedElement?.name === "reference") {// reference link- const notePath = selectedElement.getAttribute('notePath');+ const notePath = selectedElement.getAttribute("notePath");if (notePath) {await appContext.tabManager.getActiveContext().setNote(notePath);@@ -416,44 +417,46 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {}}- if (!selection.hasAttribute('linkHref')) {+ if (!selection.hasAttribute("linkHref")) {return;}- const selectedLinkUrl = selection.getAttribute('linkHref');+ const selectedLinkUrl = selection.getAttribute("linkHref");const notePath = link.getNotePathFromUrl(selectedLinkUrl);if (notePath) {await appContext.tabManager.getActiveContext().setNote(notePath);} else {- window.open(selectedLinkUrl, '_blank');+ window.open(selectedLinkUrl, "_blank");}}addIncludeNoteToTextCommand() {- this.triggerCommand("showIncludeNoteDialog", {textTypeWidget: this});+ this.triggerCommand("showIncludeNoteDialog", { textTypeWidget: this });}addIncludeNote(noteId, boxSize) {- this.watchdog.editor.model.change( writer => {+ this.watchdog.editor.model.change((writer) => {// Insert <includeNote>*</includeNote> at the current selection position// in a way that will result in creating a valid model structure- this.watchdog.editor.model.insertContent(writer.createElement('includeNote', {- noteId: noteId,- boxSize: boxSize- }));- } );+ this.watchdog.editor.model.insertContent(+ writer.createElement("includeNote", {+ noteId: noteId,+ boxSize: boxSize+ })+ );+ });}async addImage(noteId) {const note = await froca.getNote(noteId);- this.watchdog.editor.model.change( writer => {+ this.watchdog.editor.model.change((writer) => {const encodedTitle = encodeURIComponent(note.title);const src = `api/images/${note.noteId}/${encodedTitle}`;- this.watchdog.editor.execute( 'insertImage', { source: src } );- } );+ this.watchdog.editor.execute("insertImage", { source: src });+ });}async createNoteForReferenceLink(title) {@@ -469,7 +472,7 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {return resp.note.getBestNotePathString();}- async refreshIncludedNoteEvent({noteId}) {+ async refreshIncludedNoteEvent({ noteId }) {this.refreshIncludedNote(this.$editor, noteId);}}diff --git a/src/public/app/widgets/type_widgets/empty.js b/src/public/app/widgets/type_widgets/empty.jsindex abec94ab52..fa73ea5ff4 100644--- a/src/public/app/widgets/type_widgets/empty.js+++ b/src/public/app/widgets/type_widgets/empty.js@@ -1,4 +1,4 @@-import noteAutocompleteService from '../../services/note_autocomplete.js';+import noteAutocompleteService from "../../services/note_autocomplete.js";import TypeWidget from "./type_widget.js";import appContext from "../../components/app_context.js";import searchService from "../../services/search.js";@@ -49,16 +49,18 @@ const TPL = `<div class="workspace-notes"></div><div class="form-group empty-tab-search">- <label>${t('empty.open_note_instruction')}</label>+ <label>${t("empty.open_note_instruction")}</label><div class="input-group mt-1">- <input class="form-control note-autocomplete" placeholder="${t('empty.search_placeholder')}">+ <input class="form-control note-autocomplete" placeholder="${t("empty.search_placeholder")}"></div></div><div class="note-detail-empty-results"></div></div>`;export default class EmptyTypeWidget extends TypeWidget {- static getType() { return "empty"; }+ static getType() {+ return "empty";+ }doRender() {// FIXME: this might be optimized - cleaned up after use since it's always used only for new tab@@ -67,13 +69,14 @@ export default class EmptyTypeWidget extends TypeWidget {this.$autoComplete = this.$widget.find(".note-autocomplete");this.$results = this.$widget.find(".note-detail-empty-results");- noteAutocompleteService.initNoteAutocomplete(this.$autoComplete, {- hideGoToSelectedNoteButton: true,- allowCreatingNotes: true,- allowJumpToSearchNotes: true,- container: this.$results- })- .on('autocomplete:noteselected', function(event, suggestion, dataset) {+ noteAutocompleteService+ .initNoteAutocomplete(this.$autoComplete, {+ hideGoToSelectedNoteButton: true,+ allowCreatingNotes: true,+ allowJumpToSearchNotes: true,+ container: this.$results+ })+ .on("autocomplete:noteselected", function (event, suggestion, dataset) {if (!suggestion.notePath) {return false;}@@ -81,14 +84,14 @@ export default class EmptyTypeWidget extends TypeWidget {appContext.tabManager.getActiveContext().setNote(suggestion.notePath);});- this.$workspaceNotes = this.$widget.find('.workspace-notes');+ this.$workspaceNotes = this.$widget.find(".workspace-notes");noteAutocompleteService.showRecentNotes(this.$autoComplete);super.doRender();}async doRefresh(note) {- const workspaceNotes = await searchService.searchForNotes('#workspace #!template');+ const workspaceNotes = await searchService.searchForNotes("#workspace #!template");this.$workspaceNotes.empty();@@ -97,13 +100,11 @@ export default class EmptyTypeWidget extends TypeWidget {$('<div class="workspace-note">').append($("<div>").addClass(`${workspaceNote.getIcon()} workspace-icon`)).append($("<div>").text(workspaceNote.title))- .attr("title", t('empty.enter_workspace', { title: workspaceNote.title }))- .on('click', () => this.triggerCommand('hoistNote', {noteId: workspaceNote.noteId}))+ .attr("title", t("empty.enter_workspace", { title: workspaceNote.title }))+ .on("click", () => this.triggerCommand("hoistNote", { noteId: workspaceNote.noteId })));}- this.$autoComplete- .trigger('focus')- .trigger('select');+ this.$autoComplete.trigger("focus").trigger("select");}}diff --git a/src/public/app/widgets/type_widgets/file.js b/src/public/app/widgets/type_widgets/file.jsindex 6785517134..5454b7a8f7 100644--- a/src/public/app/widgets/type_widgets/file.js+++ b/src/public/app/widgets/type_widgets/file.js@@ -26,7 +26,7 @@ const TPL = `<pre class="file-preview-content"></pre><div class="file-preview-not-available alert alert-info">- ${t('file.file_preview_not_available')}+ ${t("file.file_preview_not_available")}</div><iframe class="pdf-preview" style="width: 100%; height: 100%; flex-grow: 100;"></iframe>@@ -37,7 +37,9 @@ const TPL = `</div>`;export default class FileTypeWidget extends TypeWidget {- static getType() { return "file"; }+ static getType() {+ return "file";+ }doRender() {this.$widget = $(TPL);@@ -56,7 +58,7 @@ export default class FileTypeWidget extends TypeWidget {const blob = await this.note.getBlob();this.$previewContent.empty().hide();- this.$pdfPreview.attr('src', '').empty().hide();+ this.$pdfPreview.attr("src", "").empty().hide();this.$previewNotAvailable.hide();this.$videoPreview.hide();this.$audioPreview.hide();@@ -64,30 +66,26 @@ export default class FileTypeWidget extends TypeWidget {if (blob.content) {this.$previewContent.show().scrollTop(0);this.$previewContent.text(blob.content);- }- else if (note.mime === 'application/pdf') {+ } else if (note.mime === "application/pdf") {this.$pdfPreview.show().attr("src", openService.getUrlForDownload(`api/notes/${this.noteId}/open`));- }- else if (note.mime.startsWith('video/')) {+ } else if (note.mime.startsWith("video/")) {this.$videoPreview.show().attr("src", openService.getUrlForDownload(`api/notes/${this.noteId}/open-partial`)).attr("type", this.note.mime).css("width", this.$widget.width());- }- else if (note.mime.startsWith('audio/')) {+ } else if (note.mime.startsWith("audio/")) {this.$audioPreview.show().attr("src", openService.getUrlForDownload(`api/notes/${this.noteId}/open-partial`)).attr("type", this.note.mime).css("width", this.$widget.width());- }- else {+ } else {this.$previewNotAvailable.show();}}- async entitiesReloadedEvent({loadResults}) {+ async entitiesReloadedEvent({ loadResults }) {if (loadResults.isNoteReloaded(this.noteId)) {this.refresh();}diff --git a/src/public/app/widgets/type_widgets/image.js b/src/public/app/widgets/type_widgets/image.jsindex 184023b034..208c1c1ad8 100644--- a/src/public/app/widgets/type_widgets/image.js+++ b/src/public/app/widgets/type_widgets/image.js@@ -39,13 +39,14 @@ const TPL = `</div>`;class ImageTypeWidget extends TypeWidget {- static getType() { return "image"; }+ static getType() {+ return "image";+ }doRender() {this.$widget = $(TPL);- this.$imageWrapper = this.$widget.find('.note-detail-image-wrapper');- this.$imageView = this.$widget.find('.note-detail-image-view')- .attr("id", `image-view-${utils.randomString(10)}`);+ this.$imageWrapper = this.$widget.find(".note-detail-image-wrapper");+ this.$imageView = this.$widget.find(".note-detail-image-view").attr("id", `image-view-${utils.randomString(10)}`);libraryLoader.requireLibrary(libraryLoader.WHEEL_ZOOM).then(() => {WZoom.create(`#${this.$imageView.attr("id")}`, {@@ -64,7 +65,7 @@ class ImageTypeWidget extends TypeWidget {this.$imageView.prop("src", utils.createImageSrcUrl(note));}- copyImageReferenceToClipboardEvent({ntxId}) {+ copyImageReferenceToClipboardEvent({ ntxId }) {if (!this.isNoteContext(ntxId)) {return;}@@ -72,11 +73,11 @@ class ImageTypeWidget extends TypeWidget {imageService.copyImageReferenceToClipboard(this.$imageWrapper);}- async entitiesReloadedEvent({loadResults}) {+ async entitiesReloadedEvent({ loadResults }) {if (loadResults.isNoteReloaded(this.noteId)) {this.refresh();}}}-export default ImageTypeWidget+export default ImageTypeWidget;diff --git a/src/public/app/widgets/type_widgets/mind_map.js b/src/public/app/widgets/type_widgets/mind_map.jsindex 1baa9235e9..551a108d65 100644--- a/src/public/app/widgets/type_widgets/mind_map.js+++ b/src/public/app/widgets/type_widgets/mind_map.js@@ -137,16 +137,18 @@ const TPL = ``;export default class MindMapWidget extends TypeWidget {- static getType() { return "mindMap"; }+ static getType() {+ return "mindMap";+ }doRender() {this.$widget = $(TPL);- this.$content = this.$widget.find(".mind-map-container");+ this.$content = this.$widget.find(".mind-map-container");this.$content.on("keydown", (e) => {/** Some global shortcuts interfere with the default shortcuts of the mind map,* as defined here: https://mind-elixir.com/docs/guides/shortcuts- */+ */if (e.key === "F1") {e.stopPropagation();}@@ -158,7 +160,7 @@ export default class MindMapWidget extends TypeWidget {}});- super.doRender();+ super.doRender();}async doRefresh(note) {@@ -170,19 +172,19 @@ export default class MindMapWidget extends TypeWidget {if (!window.MindElixir) {await libraryLoader.requireLibrary(libraryLoader.MIND_ELIXIR);}-+this.#initLibrary();- await this.#loadData(note);+ await this.#loadData(note);}cleanup() {this.triggeredByUserOperation = false;}-+async #loadData(note) {- const blob = await note.getBlob();+ const blob = await note.getBlob();const content = blob.getJsonContent() || MindElixir.new();-+this.mind.refresh(content);this.mind.toCenter();}@@ -202,7 +204,7 @@ export default class MindMapWidget extends TypeWidget {this.spacedUpdate.scheduleUpdate();}});-+// If the note is displayed directly after a refresh, the scroll ends up at (0,0), making it difficult for the user to see.// Adding an arbitrary wait until the element is attached to the DOM seems to do the trick for now.setTimeout(() => {@@ -216,7 +218,7 @@ export default class MindMapWidget extends TypeWidget {return;}- const svgContent = await this.renderSvg();+ const svgContent = await this.renderSvg();return {content: mind.getDataString(),attachments: [@@ -235,13 +237,13 @@ export default class MindMapWidget extends TypeWidget {return await this.mind.exportSvg().text();}- async entitiesReloadedEvent({loadResults}) {+ async entitiesReloadedEvent({ loadResults }) {if (loadResults.isNoteReloaded(this.noteId)) {this.refresh();}}- async exportSvgEvent({ntxId}) {+ async exportSvgEvent({ ntxId }) {if (!this.isNoteContext(ntxId) || this.note.type !== "mindMap") {return;}@@ -249,5 +251,4 @@ export default class MindMapWidget extends TypeWidget {const svg = await this.renderSvg();utils.downloadSvg(this.note.title, svg);}--}\ No newline at end of file+}diff --git a/src/public/app/widgets/type_widgets/none.js b/src/public/app/widgets/type_widgets/none.jsindex a844608351..da1d32abc4 100644--- a/src/public/app/widgets/type_widgets/none.js+++ b/src/public/app/widgets/type_widgets/none.js@@ -3,7 +3,9 @@ import TypeWidget from "./type_widget.js";const TPL = `<div class="note-detail-none note-detail-printable"></div>`;export default class NoneTypeWidget extends TypeWidget {- static getType() { return "none"; }+ static getType() {+ return "none";+ }doRender() {this.$widget = $(TPL);diff --git a/src/public/app/widgets/type_widgets/note_map.js b/src/public/app/widgets/type_widgets/note_map.jsindex 895d2ea7b7..dea9a9f00d 100644--- a/src/public/app/widgets/type_widgets/note_map.js+++ b/src/public/app/widgets/type_widgets/note_map.js@@ -4,12 +4,14 @@ import NoteMapWidget from "../note_map.js";const TPL = `<div class="note-detail-note-map note-detail-printable"></div>`;export default class NoteMapTypeWidget extends TypeWidget {- static getType() { return "noteMap"; }+ static getType() {+ return "noteMap";+ }constructor() {super();- this.noteMapWidget = new NoteMapWidget('type');+ this.noteMapWidget = new NoteMapWidget("type");this.child(this.noteMapWidget);}diff --git a/src/public/app/widgets/type_widgets/options/advanced/database_anonymization.js b/src/public/app/widgets/type_widgets/options/advanced/database_anonymization.jsindex dd59a8b185..e47f40b397 100644--- a/src/public/app/widgets/type_widgets/options/advanced/database_anonymization.js+++ b/src/public/app/widgets/type_widgets/options/advanced/database_anonymization.js@@ -38,30 +38,28 @@ export default class DatabaseAnonymizationOptions extends OptionsWidget {this.$widget = $(TPL);this.$anonymizeFullButton = this.$widget.find(".anonymize-full-button");this.$anonymizeLightButton = this.$widget.find(".anonymize-light-button");- this.$anonymizeFullButton.on('click', async () => {+ this.$anonymizeFullButton.on("click", async () => {toastService.showMessage(t("database_anonymization.creating_fully_anonymized_database"));- const resp = await server.post('database/anonymize/full');+ const resp = await server.post("database/anonymize/full");if (!resp.success) {toastService.showError(t("database_anonymization.error_creating_anonymized_database"));- }- else {+ } else {toastService.showMessage(t("database_anonymization.successfully_created_fully_anonymized_database", { anonymizedFilePath: resp.anonymizedFilePath }), 10000);}this.refresh();});- this.$anonymizeLightButton.on('click', async () => {+ this.$anonymizeLightButton.on("click", async () => {toastService.showMessage(t("database_anonymization.creating_lightly_anonymized_database"));- const resp = await server.post('database/anonymize/light');+ const resp = await server.post("database/anonymize/light");if (!resp.success) {toastService.showError(t("database_anonymization.error_creating_anonymized_database"));- }- else {+ } else {toastService.showMessage(t("database_anonymization.successfully_created_lightly_anonymized_database", { anonymizedFilePath: resp.anonymizedFilePath }), 10000);}@@ -72,14 +70,14 @@ export default class DatabaseAnonymizationOptions extends OptionsWidget {}optionsLoaded(options) {- server.get("database/anonymized-databases").then(anonymizedDatabases => {+ server.get("database/anonymized-databases").then((anonymizedDatabases) => {this.$existingAnonymizedDatabases.empty();if (!anonymizedDatabases.length) {- anonymizedDatabases = [{filePath: t("database_anonymization.no_anonymized_database_yet")}];+ anonymizedDatabases = [{ filePath: t("database_anonymization.no_anonymized_database_yet") }];}- for (const {filePath} of anonymizedDatabases) {+ for (const { filePath } of anonymizedDatabases) {this.$existingAnonymizedDatabases.append($("<li>").text(filePath));}});diff --git a/src/public/app/widgets/type_widgets/options/advanced/database_integrity_check.js b/src/public/app/widgets/type_widgets/options/advanced/database_integrity_check.jsindex 7dd29cfc4d..48b6927ae3 100644--- a/src/public/app/widgets/type_widgets/options/advanced/database_integrity_check.js+++ b/src/public/app/widgets/type_widgets/options/advanced/database_integrity_check.js@@ -18,24 +18,23 @@ export default class DatabaseIntegrityCheckOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$checkIntegrityButton = this.$widget.find(".check-integrity-button");- this.$checkIntegrityButton.on('click', async () => {+ this.$checkIntegrityButton.on("click", async () => {toastService.showMessage(t("database_integrity_check.checking_integrity"));- const {results} = await server.get('database/check-integrity');+ const { results } = await server.get("database/check-integrity");if (results.length === 1 && results[0].integrity_check === "ok") {toastService.showMessage(t("database_integrity_check.integrity_check_succeeded"));- }- else {+ } else {toastService.showMessage(t("database_integrity_check.integrity_check_failed", { results: JSON.stringify(results, null, 2) }), 15000);}});this.$findAndFixConsistencyIssuesButton = this.$widget.find(".find-and-fix-consistency-issues-button");- this.$findAndFixConsistencyIssuesButton.on('click', async () => {+ this.$findAndFixConsistencyIssuesButton.on("click", async () => {toastService.showMessage(t("consistency_checks.finding_and_fixing_message"));- await server.post('database/find-and-fix-consistency-issues');+ await server.post("database/find-and-fix-consistency-issues");toastService.showMessage(t("consistency_checks.issues_fixed_message"));});diff --git a/src/public/app/widgets/type_widgets/options/advanced/sync.js b/src/public/app/widgets/type_widgets/options/advanced/sync.jsindex e4bc32b5d3..472ff8dbd6 100644--- a/src/public/app/widgets/type_widgets/options/advanced/sync.js+++ b/src/public/app/widgets/type_widgets/options/advanced/sync.js@@ -16,22 +16,20 @@ export default class AdvancedSyncOptions extends OptionsWidget {this.$widget = $(TPL);this.$forceFullSyncButton = this.$widget.find(".force-full-sync-button");this.$fillEntityChangesButton = this.$widget.find(".fill-entity-changes-button");- this.$forceFullSyncButton.on('click', async () => {- await server.post('sync/force-full-sync');+ this.$forceFullSyncButton.on("click", async () => {+ await server.post("sync/force-full-sync");toastService.showMessage(t("sync.full_sync_triggered"));});- this.$fillEntityChangesButton.on('click', async () => {+ this.$fillEntityChangesButton.on("click", async () => {toastService.showMessage(t("sync.filling_entity_changes"));- await server.post('sync/fill-entity-changes');+ await server.post("sync/fill-entity-changes");toastService.showMessage(t("sync.sync_rows_filled_successfully"));});}- async optionsLoaded(options) {-- }+ async optionsLoaded(options) {}}diff --git a/src/public/app/widgets/type_widgets/options/advanced/vacuum_database.js b/src/public/app/widgets/type_widgets/options/advanced/vacuum_database.jsindex 622e8ab1b9..19c4a21a8d 100644--- a/src/public/app/widgets/type_widgets/options/advanced/vacuum_database.js+++ b/src/public/app/widgets/type_widgets/options/advanced/vacuum_database.js@@ -16,10 +16,10 @@ export default class VacuumDatabaseOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$vacuumDatabaseButton = this.$widget.find(".vacuum-database-button");- this.$vacuumDatabaseButton.on('click', async () => {+ this.$vacuumDatabaseButton.on("click", async () => {toastService.showMessage(t("vacuum_database.vacuuming_database"));- await server.post('database/vacuum-database');+ await server.post("database/vacuum-database");toastService.showMessage(t("vacuum_database.database_vacuumed"));});diff --git a/src/public/app/widgets/type_widgets/options/appearance/code_block.js b/src/public/app/widgets/type_widgets/options/appearance/code_block.jsindex e619b2e5c5..3b999edd57 100644--- a/src/public/app/widgets/type_widgets/options/appearance/code_block.js+++ b/src/public/app/widgets/type_widgets/options/appearance/code_block.js@@ -18,7 +18,7 @@ function greet(times) {console.log("Hello World!");}}-`+`;const TPL = `<div class="options-section">@@ -77,14 +77,12 @@ export default class CodeBlockOptions extends OptionsWidget {#setupPreview(shouldEnableSyntaxHighlight) {const text = SAMPLE_CODE;if (shouldEnableSyntaxHighlight) {- library_loader- .requireLibrary(library_loader.HIGHLIGHT_JS)- .then(() => {- const highlightedText = hljs.highlight(text, {- language: SAMPLE_LANGUAGE- });- this.$sampleEl.html(highlightedText.value);+ library_loader.requireLibrary(library_loader.HIGHLIGHT_JS).then(() => {+ const highlightedText = hljs.highlight(text, {+ language: SAMPLE_LANGUAGE});+ this.$sampleEl.html(highlightedText.value);+ });} else {this.$sampleEl.text(text);}@@ -94,13 +92,11 @@ export default class CodeBlockOptions extends OptionsWidget {const themeGroups = await server.get("options/codeblock-themes");this.$themeSelect.empty();- for (const [ key, themes ] of Object.entries(themeGroups)) {- const $group = (key ? $("<optgroup>").attr("label", key) : null);+ for (const [key, themes] of Object.entries(themeGroups)) {+ const $group = key ? $("<optgroup>").attr("label", key) : null;for (const theme of themes) {- const option = $("<option>")- .attr("value", theme.val)- .text(theme.title);+ const option = $("<option>").attr("value", theme.val).text(theme.title);if ($group) {$group.append(option);diff --git a/src/public/app/widgets/type_widgets/options/appearance/electron_integration.js b/src/public/app/widgets/type_widgets/options/appearance/electron_integration.jsindex 78806e845e..d9007a50c2 100644--- a/src/public/app/widgets/type_widgets/options/appearance/electron_integration.js+++ b/src/public/app/widgets/type_widgets/options/appearance/electron_integration.js@@ -40,7 +40,9 @@ export default class ElectronIntegrationOptions extends OptionsWidget {this.$widget = $(TPL);this.$zoomFactorSelect = this.$widget.find(".zoom-factor-select");- this.$zoomFactorSelect.on('change', () => { appContext.triggerCommand('setZoomFactorAndSave', {zoomFactor: this.$zoomFactorSelect.val()}); });+ this.$zoomFactorSelect.on("change", () => {+ appContext.triggerCommand("setZoomFactorAndSave", { zoomFactor: this.$zoomFactorSelect.val() });+ });this.$nativeTitleBar = this.$widget.find("input.native-title-bar");this.$nativeTitleBar.on("change", () => this.updateCheckboxOption("nativeTitleBarVisible", this.$nativeTitleBar));@@ -50,12 +52,12 @@ export default class ElectronIntegrationOptions extends OptionsWidget {const restartAppButton = this.$widget.find(".restart-app-button");restartAppButton.on("click", () => {- const app = utils.dynamicRequire('@electron/remote').app;+ const app = utils.dynamicRequire("@electron/remote").app;app.relaunch();app.exit();});}-+isEnabled() {return utils.isElectron();}diff --git a/src/public/app/widgets/type_widgets/options/appearance/fonts.ts b/src/public/app/widgets/type_widgets/options/appearance/fonts.tsindex be828c2a42..0cbcd32ab3 100644--- a/src/public/app/widgets/type_widgets/options/appearance/fonts.ts+++ b/src/public/app/widgets/type_widgets/options/appearance/fonts.ts@@ -26,22 +26,11 @@ const FONT_FAMILIES: FontGroup[] = [},{title: t("fonts.sans-serif-system-fonts"),- items: [- { value: "Arial" },- { value: "Verdana" },- { value: "Helvetica" },- { value: "Tahoma" },- { value: "Trebuchet MS" },- { value: "Microsoft YaHei" },- ]+ items: [{ value: "Arial" }, { value: "Verdana" }, { value: "Helvetica" }, { value: "Tahoma" }, { value: "Trebuchet MS" }, { value: "Microsoft YaHei" }]},{title: t("fonts.serif-system-fonts"),- items: [- { value: "Times New Roman" },- { value: "Georgia" },- { value: "Garamond" },- ]+ items: [{ value: "Times New Roman" }, { value: "Georgia" }, { value: "Garamond" }]},{title: t("fonts.monospace-system-fonts"),@@ -52,16 +41,12 @@ const FONT_FAMILIES: FontGroup[] = [{ value: "American Typewriter" },{ value: "Andalé Mono" },{ value: "Lucida Console" },- { value: "Monaco" },+ { value: "Monaco" }]},{title: t("fonts.handwriting-system-fonts"),- items: [- { value: "Bradley Hand" },- { value: "Luminari" },- { value: "Comic Sans MS" }- ]+ items: [{ value: "Bradley Hand" }, { value: "Luminari" }, { value: "Comic Sans MS" }]}];@@ -152,7 +137,6 @@ const TPL = `</div>`;export default class FontsOptions extends OptionsWidget {-private $mainFontSize!: JQuery<HTMLElement>;private $mainFontFamily!: JQuery<HTMLElement>;private $treeFontSize!: JQuery<HTMLElement>;@@ -187,7 +171,7 @@ export default class FontsOptions extends OptionsWidget {}async optionsLoaded(options: OptionMap) {- this._isEnabled = (options.overrideThemeFonts === 'true');+ this._isEnabled = options.overrideThemeFonts === "true";this.toggleInt(this._isEnabled);if (!this._isEnabled) {return;@@ -205,17 +189,11 @@ export default class FontsOptions extends OptionsWidget {this.$monospaceFontSize.val(options.monospaceFontSize);this.fillFontFamilyOptions(this.$monospaceFontFamily, options.monospaceFontFamily);- const optionsToSave: OptionNames[] = [- 'mainFontFamily', 'mainFontSize',- 'treeFontFamily', 'treeFontSize',- 'detailFontFamily', 'detailFontSize',- 'monospaceFontFamily', 'monospaceFontSize'- ];+ const optionsToSave: OptionNames[] = ["mainFontFamily", "mainFontSize", "treeFontFamily", "treeFontSize", "detailFontFamily", "detailFontSize", "monospaceFontFamily", "monospaceFontSize"];for (const optionName of optionsToSave) {const $el = (this as any)[`$${optionName}`];- $el.on('change', () =>- this.updateOption(optionName, $el.val()));+ $el.on("change", () => this.updateOption(optionName, $el.val()));}}@@ -223,18 +201,18 @@ export default class FontsOptions extends OptionsWidget {$select.empty();for (const { title, items } of Object.values(FONT_FAMILIES)) {- const $group = ($("<optgroup>")- .attr("label", title));-- for (const {value, label} of items) {- $group.append($("<option>")- .attr("value", value)- .prop("selected", value === currentValue)- .text(label ?? value));+ const $group = $("<optgroup>").attr("label", title);++ for (const { value, label } of items) {+ $group.append(+ $("<option>")+ .attr("value", value)+ .prop("selected", value === currentValue)+ .text(label ?? value)+ );}$select.append($group);}-}}diff --git a/src/public/app/widgets/type_widgets/options/appearance/i18n.js b/src/public/app/widgets/type_widgets/options/appearance/i18n.jsindex 002b1278d2..c60318dd10 100644--- a/src/public/app/widgets/type_widgets/options/appearance/i18n.js+++ b/src/public/app/widgets/type_widgets/options/appearance/i18n.js@@ -27,9 +27,9 @@ const TPL = `export default class LocalizationOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);-+this.$localeSelect = this.$widget.find(".locale-select");- this.$localeSelect.on("change", async() => {+ this.$localeSelect.on("change", async () => {const newLocale = this.$localeSelect.val();await server.put(`options/locale/${newLocale}`);utils.reloadFrontendApp("locale change");@@ -46,12 +46,10 @@ export default class LocalizationOptions extends OptionsWidget {this.$localeSelect.empty();for (const locale of availableLocales) {- this.$localeSelect.append($("<option>")- .attr("value", locale.id)- .text(locale.name));+ this.$localeSelect.append($("<option>").attr("value", locale.id).text(locale.name));}this.$localeSelect.val(options.locale);this.$firstDayOfWeek.val(options.firstDayOfWeek);}-}\ No newline at end of file+}diff --git a/src/public/app/widgets/type_widgets/options/appearance/max_content_width.js b/src/public/app/widgets/type_widgets/options/appearance/max_content_width.jsindex ee6d0f6311..658d4babe7 100644--- a/src/public/app/widgets/type_widgets/options/appearance/max_content_width.js+++ b/src/public/app/widgets/type_widgets/options/appearance/max_content_width.js@@ -29,8 +29,7 @@ export default class MaxContentWidthOptions extends OptionsWidget {this.$maxContentWidth = this.$widget.find(".max-content-width");- this.$maxContentWidth.on('change', async () =>- this.updateOption('maxContentWidth', this.$maxContentWidth.val()))+ this.$maxContentWidth.on("change", async () => this.updateOption("maxContentWidth", this.$maxContentWidth.val()));this.$widget.find(".reload-frontend-button").on("click", () => utils.reloadFrontendApp(t("max_content_width.reload_description")));}diff --git a/src/public/app/widgets/type_widgets/options/appearance/ribbon.js b/src/public/app/widgets/type_widgets/options/appearance/ribbon.jsindex ce17fd53c8..4f80dbf4b8 100644--- a/src/public/app/widgets/type_widgets/options/appearance/ribbon.js+++ b/src/public/app/widgets/type_widgets/options/appearance/ribbon.js@@ -3,15 +3,15 @@ import OptionsWidget from "../options_widget.js";const TPL = `<div class="options-section">- <h4>${t('ribbon.widgets')}</h4>+ <h4>${t("ribbon.widgets")}</h4><label><input type="checkbox" class="promoted-attributes-open-in-ribbon form-check-input">- ${t('ribbon.promoted_attributes_message')}+ ${t("ribbon.promoted_attributes_message")}</label><label><input type="checkbox" class="edited-notes-open-in-ribbon form-check-input">- ${t('ribbon.edited_notes_message')}+ ${t("ribbon.edited_notes_message")}</label></div>`;@@ -20,12 +20,10 @@ export default class RibbonOptions extends OptionsWidget {this.$widget = $(TPL);this.$promotedAttributesOpenInRibbon = this.$widget.find(".promoted-attributes-open-in-ribbon");- this.$promotedAttributesOpenInRibbon.on('change', () =>- this.updateCheckboxOption('promotedAttributesOpenInRibbon', this.$promotedAttributesOpenInRibbon));+ this.$promotedAttributesOpenInRibbon.on("change", () => this.updateCheckboxOption("promotedAttributesOpenInRibbon", this.$promotedAttributesOpenInRibbon));this.$editedNotesOpenInRibbon = this.$widget.find(".edited-notes-open-in-ribbon");- this.$editedNotesOpenInRibbon.on('change', () =>- this.updateCheckboxOption('editedNotesOpenInRibbon', this.$editedNotesOpenInRibbon));+ this.$editedNotesOpenInRibbon.on("change", () => this.updateCheckboxOption("editedNotesOpenInRibbon", this.$editedNotesOpenInRibbon));}async optionsLoaded(options) {diff --git a/src/public/app/widgets/type_widgets/options/appearance/theme.js b/src/public/app/widgets/type_widgets/options/appearance/theme.jsindex 730fcad97f..4e9330dd00 100644--- a/src/public/app/widgets/type_widgets/options/appearance/theme.js+++ b/src/public/app/widgets/type_widgets/options/appearance/theme.js@@ -55,7 +55,7 @@ export default class ThemeOptions extends OptionsWidget {utils.reloadFrontendApp("layout orientation change");});- this.$themeSelect.on('change', async () => {+ this.$themeSelect.on("change", async () => {const newTheme = this.$themeSelect.val();await server.put(`options/theme/${newTheme}`);@@ -63,33 +63,29 @@ export default class ThemeOptions extends OptionsWidget {utils.reloadFrontendApp("theme change");});- this.$overrideThemeFonts.on('change', () => this.updateCheckboxOption('overrideThemeFonts', this.$overrideThemeFonts));+ this.$overrideThemeFonts.on("change", () => this.updateCheckboxOption("overrideThemeFonts", this.$overrideThemeFonts));}async optionsLoaded(options) {const themes = [- { val: 'next', title: t("theme.triliumnext") },- { val: 'next-light', title: t("theme.triliumnext-light") },- { val: 'next-dark', title: t("theme.triliumnext-dark") },- { val: 'auto', title: t('theme.auto_theme') },- { val: 'light', title: t('theme.light_theme') },- { val: 'dark', title: t('theme.dark_theme') }- ].concat(await server.get('options/user-themes'));+ { val: "next", title: t("theme.triliumnext") },+ { val: "next-light", title: t("theme.triliumnext-light") },+ { val: "next-dark", title: t("theme.triliumnext-dark") },+ { val: "auto", title: t("theme.auto_theme") },+ { val: "light", title: t("theme.light_theme") },+ { val: "dark", title: t("theme.dark_theme") }+ ].concat(await server.get("options/user-themes"));this.$themeSelect.empty();for (const theme of themes) {- this.$themeSelect.append($("<option>")- .attr("value", theme.val)- .attr("data-note-id", theme.noteId)- .text(theme.title));+ this.$themeSelect.append($("<option>").attr("value", theme.val).attr("data-note-id", theme.noteId).text(theme.title));}this.$themeSelect.val(options.theme);this.setCheckboxState(this.$overrideThemeFonts, options.overrideThemeFonts);- this.$widget.find(`input[name="layout-orientation"][value="${options.layoutOrientation}"]`)- .prop("checked", "true");+ this.$widget.find(`input[name="layout-orientation"][value="${options.layoutOrientation}"]`).prop("checked", "true");}}diff --git a/src/public/app/widgets/type_widgets/options/backup.js b/src/public/app/widgets/type_widgets/options/backup.jsindex 067950f73c..9ced52b3a4 100644--- a/src/public/app/widgets/type_widgets/options/backup.js+++ b/src/public/app/widgets/type_widgets/options/backup.js@@ -1,4 +1,4 @@-import { formatDateTime } from "../../../utils/formatters.js"+import { formatDateTime } from "../../../utils/formatters.js";import { t } from "../../../services/i18n.js";import OptionsWidget from "./options_widget.js";import server from "../../../services/server.js";@@ -6,42 +6,42 @@ import toastService from "../../../services/toast.js";const TPL = `<div class="options-section">- <h4>${t('backup.automatic_backup')}</h4>+ <h4>${t("backup.automatic_backup")}</h4>- <p>${t('backup.automatic_backup_description')}</p>+ <p>${t("backup.automatic_backup_description")}</p><ul style="list-style: none"><li><label><input type="checkbox" class="daily-backup-enabled form-check-input">- ${t('backup.enable_daily_backup')}+ ${t("backup.enable_daily_backup")}</label></li><li><label><input type="checkbox" class="weekly-backup-enabled form-check-input">- ${t('backup.enable_weekly_backup')}+ ${t("backup.enable_weekly_backup")}</label></li><li><label><input type="checkbox" class="monthly-backup-enabled form-check-input">- ${t('backup.enable_monthly_backup')}+ ${t("backup.enable_monthly_backup")}</label></li></ul>- <p>${t('backup.backup_recommendation')}</p>+ <p>${t("backup.backup_recommendation")}</p></div><div class="options-section">- <h4>${t('backup.backup_now')}</h4>+ <h4>${t("backup.backup_now")}</h4>- <button class="backup-database-button btn">${t('backup.backup_database_now')}</button>+ <button class="backup-database-button btn">${t("backup.backup_database_now")}</button></div><div class="options-section">- <h4>${t('backup.existing_backups')}</h4>+ <h4>${t("backup.existing_backups")}</h4><table class="table table-stripped"><colgroup>@@ -67,10 +67,10 @@ export default class BackupOptions extends OptionsWidget {this.$backupDatabaseButton = this.$widget.find(".backup-database-button");- this.$backupDatabaseButton.on('click', async () => {- const {backupFile} = await server.post('database/backup-database');+ this.$backupDatabaseButton.on("click", async () => {+ const { backupFile } = await server.post("database/backup-database");- toastService.showMessage(t('backup.database_backed_up_to', { backupFilePath: backupFile}), 10000);+ toastService.showMessage(t("backup.database_backed_up_to", { backupFilePath: backupFile }), 10000);this.refresh();});@@ -79,14 +79,11 @@ export default class BackupOptions extends OptionsWidget {this.$weeklyBackupEnabled = this.$widget.find(".weekly-backup-enabled");this.$monthlyBackupEnabled = this.$widget.find(".monthly-backup-enabled");- this.$dailyBackupEnabled.on('change', () =>- this.updateCheckboxOption('dailyBackupEnabled', this.$dailyBackupEnabled));+ this.$dailyBackupEnabled.on("change", () => this.updateCheckboxOption("dailyBackupEnabled", this.$dailyBackupEnabled));- this.$weeklyBackupEnabled.on('change', () =>- this.updateCheckboxOption('weeklyBackupEnabled', this.$weeklyBackupEnabled));+ this.$weeklyBackupEnabled.on("change", () => this.updateCheckboxOption("weeklyBackupEnabled", this.$weeklyBackupEnabled));- this.$monthlyBackupEnabled.on('change', () =>- this.updateCheckboxOption('monthlyBackupEnabled', this.$monthlyBackupEnabled));+ this.$monthlyBackupEnabled.on("change", () => this.updateCheckboxOption("monthlyBackupEnabled", this.$monthlyBackupEnabled));this.$existingBackupList = this.$widget.find(".existing-backup-list-items");}@@ -96,15 +93,17 @@ export default class BackupOptions extends OptionsWidget {this.setCheckboxState(this.$weeklyBackupEnabled, options.weeklyBackupEnabled);this.setCheckboxState(this.$monthlyBackupEnabled, options.monthlyBackupEnabled);- server.get("database/backups").then(backupFiles => {+ server.get("database/backups").then((backupFiles) => {this.$existingBackupList.empty();if (!backupFiles.length) {- this.$existingBackupList.append($(`+ this.$existingBackupList.append(+ $(`<tr>- <td class="empty-table-placeholder" colspan="2">${t('backup.no_backup_yet')}</td>+ <td class="empty-table-placeholder" colspan="2">${t("backup.no_backup_yet")}</td></tr>- `));+ `)+ );return;}@@ -116,13 +115,15 @@ export default class BackupOptions extends OptionsWidget {return 0;});- for (const {filePath, mtime} of backupFiles) {- this.$existingBackupList.append($(`+ for (const { filePath, mtime } of backupFiles) {+ this.$existingBackupList.append(+ $(`<tr>- <td>${(mtime) ? formatDateTime(mtime) : "-"}</td>+ <td>${mtime ? formatDateTime(mtime) : "-"}</td><td>${filePath}</td></tr>- `));+ `)+ );}});}diff --git a/src/public/app/widgets/type_widgets/options/code_notes/code_auto_read_only_size.js b/src/public/app/widgets/type_widgets/options/code_notes/code_auto_read_only_size.jsindex 3d52af3e43..6772419d5a 100644--- a/src/public/app/widgets/type_widgets/options/code_notes/code_auto_read_only_size.js+++ b/src/public/app/widgets/type_widgets/options/code_notes/code_auto_read_only_size.js@@ -3,12 +3,12 @@ import OptionsWidget from "../options_widget.js";const TPL = `<div class="options-section">- <h4>${t('code_auto_read_only_size.title')}</h4>+ <h4>${t("code_auto_read_only_size.title")}</h4>- <p>${t('code_auto_read_only_size.description')}</p>+ <p>${t("code_auto_read_only_size.description")}</p><div class="form-group">- <label for="auto-readonly-size-code">${t('code_auto_read_only_size.label')}</label>+ <label for="auto-readonly-size-code">${t("code_auto_read_only_size.label")}</label><input id="auto-readonly-size-code" class="auto-readonly-size-code form-control options-number-input" type="number" min="0"></div></div>`;@@ -17,8 +17,7 @@ export default class CodeAutoReadOnlySizeOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$autoReadonlySizeCode = this.$widget.find(".auto-readonly-size-code");- this.$autoReadonlySizeCode.on('change', () =>- this.updateOption('autoReadonlySizeCode', this.$autoReadonlySizeCode.val()));+ this.$autoReadonlySizeCode.on("change", () => this.updateOption("autoReadonlySizeCode", this.$autoReadonlySizeCode.val()));}async optionsLoaded(options) {diff --git a/src/public/app/widgets/type_widgets/options/code_notes/code_mime_types.js b/src/public/app/widgets/type_widgets/options/code_notes/code_mime_types.jsindex 300dee9b7f..17dcf17f1c 100644--- a/src/public/app/widgets/type_widgets/options/code_notes/code_mime_types.js+++ b/src/public/app/widgets/type_widgets/options/code_notes/code_mime_types.js@@ -4,7 +4,7 @@ import mimeTypesService from "../../../../services/mime_types.js";const TPL = `<div class="options-section">- <h4>${t('code_mime_types.title')}</h4>+ <h4>${t("code_mime_types.title")}</h4><ul class="options-mime-types" style="list-style-type: none;"></ul></div>@@ -34,18 +34,12 @@ function groupMimeTypesAlphabetically(ungroupedMimeTypes) {}function buildSelectionForMimeType(mimeType) {- const id = "code-mime-type-" + (idCtr++);- return ($("<li>")- .append($('<input type="checkbox" class="form-check-input">')- .attr("id", id)- .attr("data-mime-type", mimeType.mime)- .prop("checked", mimeType.enabled))- .on('change', () => this.save())+ const id = "code-mime-type-" + idCtr++;+ return $("<li>")+ .append($('<input type="checkbox" class="form-check-input">').attr("id", id).attr("data-mime-type", mimeType.mime).prop("checked", mimeType.enabled))+ .on("change", () => this.save()).append(" ")- .append($('<label>')- .attr("for", id)- .text(mimeType.title))- );+ .append($("<label>").attr("for", id).text(mimeType.title));}export default class CodeMimeTypesOptions extends OptionsWidget {@@ -63,10 +57,10 @@ export default class CodeMimeTypesOptions extends OptionsWidget {// Plain text is displayed at the top intentionally.this.$mimeTypes.append(buildSelectionForMimeType.call(this, plainTextMimeType));-- for (const [ initial, mimeTypes ] of Object.entries(groupedMimeTypes)) {++ for (const [initial, mimeTypes] of Object.entries(groupedMimeTypes)) {const $section = $("<section>");- $section.append($("<h5>").text(initial));+ $section.append($("<h5>").text(initial));for (const mimeType of mimeTypes) {$section.append(buildSelectionForMimeType.call(this, mimeType));@@ -79,10 +73,9 @@ export default class CodeMimeTypesOptions extends OptionsWidget {async save() {const enabledMimeTypes = [];- this.$mimeTypes.find("input:checked").each(- (i, el) => enabledMimeTypes.push(this.$widget.find(el).attr("data-mime-type")));+ this.$mimeTypes.find("input:checked").each((i, el) => enabledMimeTypes.push(this.$widget.find(el).attr("data-mime-type")));- await this.updateOption('codeNotesMimeTypes', JSON.stringify(enabledMimeTypes));+ await this.updateOption("codeNotesMimeTypes", JSON.stringify(enabledMimeTypes));mimeTypesService.loadMimeTypes();}diff --git a/src/public/app/widgets/type_widgets/options/code_notes/vim_key_bindings.js b/src/public/app/widgets/type_widgets/options/code_notes/vim_key_bindings.jsindex a1065c51ac..5cbe367ce7 100644--- a/src/public/app/widgets/type_widgets/options/code_notes/vim_key_bindings.js+++ b/src/public/app/widgets/type_widgets/options/code_notes/vim_key_bindings.js@@ -3,10 +3,10 @@ import { t } from "../../../../services/i18n.js";const TPL = `<div class="options-section">- <h4>${t('vim_key_bindings.use_vim_keybindings_in_code_notes')}</h4>+ <h4>${t("vim_key_bindings.use_vim_keybindings_in_code_notes")}</h4><label><input type="checkbox" class="vim-keymap-enabled form-check-input">- ${t('vim_key_bindings.enable_vim_keybindings')}+ ${t("vim_key_bindings.enable_vim_keybindings")}</label></div>`;@@ -14,8 +14,7 @@ export default class VimKeyBindingsOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$vimKeymapEnabled = this.$widget.find(".vim-keymap-enabled");- this.$vimKeymapEnabled.on('change', () =>- this.updateCheckboxOption('vimKeymapEnabled', this.$vimKeymapEnabled));+ this.$vimKeymapEnabled.on("change", () => this.updateCheckboxOption("vimKeymapEnabled", this.$vimKeymapEnabled));}async optionsLoaded(options) {diff --git a/src/public/app/widgets/type_widgets/options/code_notes/wrap_lines.js b/src/public/app/widgets/type_widgets/options/code_notes/wrap_lines.jsindex 73c5eb85ba..fe0559a652 100644--- a/src/public/app/widgets/type_widgets/options/code_notes/wrap_lines.js+++ b/src/public/app/widgets/type_widgets/options/code_notes/wrap_lines.js@@ -14,8 +14,7 @@ export default class WrapLinesOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$codeLineWrapEnabled = this.$widget.find(".line-wrap-enabled");- this.$codeLineWrapEnabled.on('change', () =>- this.updateCheckboxOption('codeLineWrapEnabled', this.$codeLineWrapEnabled));+ this.$codeLineWrapEnabled.on("change", () => this.updateCheckboxOption("codeLineWrapEnabled", this.$codeLineWrapEnabled));}async optionsLoaded(options) {diff --git a/src/public/app/widgets/type_widgets/options/etapi.js b/src/public/app/widgets/type_widgets/options/etapi.jsindex b2d939743e..356d842309 100644--- a/src/public/app/widgets/type_widgets/options/etapi.js+++ b/src/public/app/widgets/type_widgets/options/etapi.js@@ -1,4 +1,4 @@-import { formatDateTime } from "../../../utils/formatters.js"+import { formatDateTime } from "../../../utils/formatters.js";import { t } from "../../../services/i18n.js";import dialogService from "../../../services/dialog.js";import OptionsWidget from "./options_widget.js";@@ -66,7 +66,7 @@ export default class EtapiOptions extends OptionsWidget {return;}- const {authToken} = await server.post('etapi-tokens', {tokenName});+ const { authToken } = await server.post("etapi-tokens", { tokenName });await dialogService.prompt({title: t("etapi.token_created_title"),@@ -84,7 +84,7 @@ export default class EtapiOptions extends OptionsWidget {const $noTokensYet = this.$widget.find(".no-tokens-yet");const $tokensTable = this.$widget.find(".tokens-table");- const tokens = await server.get('etapi-tokens');+ const tokens = await server.get("etapi-tokens");$noTokensYet.toggle(tokens.length === 0);$tokensTable.toggle(tokens.length > 0);@@ -97,12 +97,12 @@ export default class EtapiOptions extends OptionsWidget {$("<tr>").append($("<td>").text(token.name)).append($("<td>").text(formatDateTime(token.utcDateCreated)))- .append($("<td>").append(- $(`<span class="bx bx-pen token-table-button" title="${t("etapi.rename_token")}"></span>`)- .on("click", () => this.renameToken(token.etapiTokenId, token.name)),- $(`<span class="bx bx-trash token-table-button" title="${t("etapi.delete_token")}"></span>`)- .on("click", () => this.deleteToken(token.etapiTokenId, token.name))- ))+ .append(+ $("<td>").append(+ $(`<span class="bx bx-pen token-table-button" title="${t("etapi.rename_token")}"></span>`).on("click", () => this.renameToken(token.etapiTokenId, token.name)),+ $(`<span class="bx bx-trash token-table-button" title="${t("etapi.delete_token")}"></span>`).on("click", () => this.deleteToken(token.etapiTokenId, token.name))+ )+ ));}}@@ -118,13 +118,13 @@ export default class EtapiOptions extends OptionsWidget {return;}- await server.patch(`etapi-tokens/${etapiTokenId}`, {name: tokenName});+ await server.patch(`etapi-tokens/${etapiTokenId}`, { name: tokenName });this.refreshTokens();}async deleteToken(etapiTokenId, name) {- if (!await dialogService.confirm(t("etapi.delete_token_confirmation", { name }))) {+ if (!(await dialogService.confirm(t("etapi.delete_token_confirmation", { name })))) {return;}diff --git a/src/public/app/widgets/type_widgets/options/images/images.js b/src/public/app/widgets/type_widgets/options/images/images.jsindex 2642461a4f..758298b56d 100644--- a/src/public/app/widgets/type_widgets/options/images/images.js+++ b/src/public/app/widgets/type_widgets/options/images/images.js@@ -47,22 +47,19 @@ export default class ImageOptions extends OptionsWidget {this.$imageMaxWidthHeight = this.$widget.find(".image-max-width-height");this.$imageJpegQuality = this.$widget.find(".image-jpeg-quality");- this.$imageMaxWidthHeight.on('change', () =>- this.updateOption('imageMaxWidthHeight', this.$imageMaxWidthHeight.val()));+ this.$imageMaxWidthHeight.on("change", () => this.updateOption("imageMaxWidthHeight", this.$imageMaxWidthHeight.val()));- this.$imageJpegQuality.on('change', () =>- this.updateOption('imageJpegQuality', this.$imageJpegQuality.val().trim() || "75"));+ this.$imageJpegQuality.on("change", () => this.updateOption("imageJpegQuality", this.$imageJpegQuality.val().trim() || "75"));this.$downloadImagesAutomatically = this.$widget.find(".download-images-automatically");- this.$downloadImagesAutomatically.on("change", () =>- this.updateCheckboxOption('downloadImagesAutomatically', this.$downloadImagesAutomatically));+ this.$downloadImagesAutomatically.on("change", () => this.updateCheckboxOption("downloadImagesAutomatically", this.$downloadImagesAutomatically));this.$enableImageCompression = this.$widget.find(".image-compresion-enabled");this.$imageCompressionWrapper = this.$widget.find(".image-compression-enabled-wraper");this.$enableImageCompression.on("change", () => {- this.updateCheckboxOption('compressImages', this.$enableImageCompression);+ this.updateCheckboxOption("compressImages", this.$enableImageCompression);this.setImageCompression();});}diff --git a/src/public/app/widgets/type_widgets/options/options_widget.ts b/src/public/app/widgets/type_widgets/options/options_widget.tsindex 77d84d6ef8..77d52bb693 100644--- a/src/public/app/widgets/type_widgets/options/options_widget.ts+++ b/src/public/app/widgets/type_widgets/options/options_widget.ts@@ -6,9 +6,7 @@ import server from "../../../services/server.js";import toastService from "../../../services/toast.js";import NoteContextAwareWidget from "../../note_context_aware_widget.js";-export default class OptionsWidget extends NoteContextAwareWidget- implements EventListener<"entitiesReloaded">-{+export default class OptionsWidget extends NoteContextAwareWidget implements EventListener<"entitiesReloaded"> {constructor() {super();@@ -22,7 +20,7 @@ export default class OptionsWidget extends NoteContextAwareWidget}async updateMultipleOptions(opts: Partial<OptionMap>) {- await server.put('options', opts);+ await server.put("options", opts);this.showUpdateNotification();}@@ -40,11 +38,11 @@ export default class OptionsWidget extends NoteContextAwareWidgetasync updateCheckboxOption<T extends FilterOptionsByType<boolean>>(name: T, $checkbox: JQuery<HTMLElement>) {const isChecked = $checkbox.prop("checked");- return await this.updateOption(name, isChecked ? 'true' : 'false');+ return await this.updateOption(name, isChecked ? "true" : "false");}setCheckboxState($checkbox: JQuery<HTMLElement>, optionValue: string) {- $checkbox.prop('checked', optionValue === 'true');+ $checkbox.prop("checked", optionValue === "true");}optionsLoaded(options: OptionMap) {}@@ -64,14 +62,14 @@ export default class OptionsWidget extends NoteContextAwareWidget}async refreshWithNote(note: FNote | null | undefined) {- const options = await server.get<OptionMap>('options');+ const options = await server.get<OptionMap>("options");if (options) {this.optionsLoaded(options);}}- async entitiesReloadedEvent({loadResults}: EventData<"entitiesReloaded">) {+ async entitiesReloadedEvent({ loadResults }: EventData<"entitiesReloaded">) {if (loadResults.getOptionNames().length > 0) {this.refresh();}diff --git a/src/public/app/widgets/type_widgets/options/other/attachment_erasure_timeout.js b/src/public/app/widgets/type_widgets/options/other/attachment_erasure_timeout.jsindex acac8c90f9..671f7d6440 100644--- a/src/public/app/widgets/type_widgets/options/other/attachment_erasure_timeout.js+++ b/src/public/app/widgets/type_widgets/options/other/attachment_erasure_timeout.js@@ -23,11 +23,11 @@ export default class AttachmentErasureTimeoutOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$eraseUnusedAttachmentsAfterTimeInSeconds = this.$widget.find(".erase-unused-attachments-after-time-in-seconds");- this.$eraseUnusedAttachmentsAfterTimeInSeconds.on('change', () => this.updateOption('eraseUnusedAttachmentsAfterSeconds', this.$eraseUnusedAttachmentsAfterTimeInSeconds.val()));+ this.$eraseUnusedAttachmentsAfterTimeInSeconds.on("change", () => this.updateOption("eraseUnusedAttachmentsAfterSeconds", this.$eraseUnusedAttachmentsAfterTimeInSeconds.val()));this.$eraseUnusedAttachmentsNowButton = this.$widget.find(".erase-unused-attachments-now-button");- this.$eraseUnusedAttachmentsNowButton.on('click', () => {- server.post('notes/erase-unused-attachments-now').then(() => {+ this.$eraseUnusedAttachmentsNowButton.on("click", () => {+ server.post("notes/erase-unused-attachments-now").then(() => {toastService.showMessage(t("attachment_erasure_timeout.unused_attachments_erased"));});});diff --git a/src/public/app/widgets/type_widgets/options/other/html_import_tags.js b/src/public/app/widgets/type_widgets/options/other/html_import_tags.jsindex 709615676b..efc3eb84f1 100644--- a/src/public/app/widgets/type_widgets/options/other/html_import_tags.js+++ b/src/public/app/widgets/type_widgets/options/other/html_import_tags.js@@ -3,17 +3,101 @@ import { t } from "../../../../services/i18n.js";// TODO: Deduplicate with src/services/html_sanitizer once there is a commons project between client and server.export const DEFAULT_ALLOWED_TAGS = [- 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol',- 'li', 'b', 'i', 'strong', 'em', 'strike', 's', 'del', 'abbr', 'code', 'hr', 'br', 'div',- 'table', 'thead', 'caption', 'tbody', 'tfoot', 'tr', 'th', 'td', 'pre', 'section', 'img',- 'figure', 'figcaption', 'span', 'label', 'input', 'details', 'summary', 'address', 'aside', 'footer',- 'header', 'hgroup', 'main', 'nav', 'dl', 'dt', 'menu', 'bdi', 'bdo', 'dfn', 'kbd', 'mark', 'q', 'time',- 'var', 'wbr', 'area', 'map', 'track', 'video', 'audio', 'picture', 'del', 'ins',- 'en-media', // for ENEX import+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "blockquote",+ "p",+ "a",+ "ul",+ "ol",+ "li",+ "b",+ "i",+ "strong",+ "em",+ "strike",+ "s",+ "del",+ "abbr",+ "code",+ "hr",+ "br",+ "div",+ "table",+ "thead",+ "caption",+ "tbody",+ "tfoot",+ "tr",+ "th",+ "td",+ "pre",+ "section",+ "img",+ "figure",+ "figcaption",+ "span",+ "label",+ "input",+ "details",+ "summary",+ "address",+ "aside",+ "footer",+ "header",+ "hgroup",+ "main",+ "nav",+ "dl",+ "dt",+ "menu",+ "bdi",+ "bdo",+ "dfn",+ "kbd",+ "mark",+ "q",+ "time",+ "var",+ "wbr",+ "area",+ "map",+ "track",+ "video",+ "audio",+ "picture",+ "del",+ "ins",+ "en-media", // for ENEX import// Additional tags (https://github.com/TriliumNext/Notes/issues/567)- 'acronym', 'article', 'big', 'button', 'cite', 'col', 'colgroup', 'data', 'dd',- 'fieldset', 'form', 'legend', 'meter', 'noscript', 'option', 'progress', 'rp',- 'samp', 'small', 'sub', 'sup', 'template', 'textarea', 'tt'+ "acronym",+ "article",+ "big",+ "button",+ "cite",+ "col",+ "colgroup",+ "data",+ "dd",+ "fieldset",+ "form",+ "legend",+ "meter",+ "noscript",+ "option",+ "progress",+ "rp",+ "samp",+ "small",+ "sub",+ "sup",+ "template",+ "textarea",+ "tt"];const TPL = `@@ -37,12 +121,12 @@ export default class HtmlImportTagsOptions extends OptionsWidget {this.$widget = $(TPL);this.contentSized();- this.$allowedTags = this.$widget.find('.allowed-html-tags');- this.$resetButton = this.$widget.find('.reset-to-default');-- this.$allowedTags.on('change', () => this.saveTags());- this.$resetButton.on('click', () => this.resetToDefault());-+ this.$allowedTags = this.$widget.find(".allowed-html-tags");+ this.$resetButton = this.$widget.find(".reset-to-default");++ this.$allowedTags.on("change", () => this.saveTags());+ this.$resetButton.on("click", () => this.resetToDefault());+// Load initial tagsthis.refresh();}@@ -51,30 +135,30 @@ export default class HtmlImportTagsOptions extends OptionsWidget {try {if (options.allowedHtmlTags) {const tags = JSON.parse(options.allowedHtmlTags);- this.$allowedTags.val(tags.join(' '));+ this.$allowedTags.val(tags.join(" "));} else {// If no tags are set, show the defaults- this.$allowedTags.val(DEFAULT_ALLOWED_TAGS.join(' '));+ this.$allowedTags.val(DEFAULT_ALLOWED_TAGS.join(" "));}- }- catch (e) {- console.error('Could not load HTML tags:', e);+ } catch (e) {+ console.error("Could not load HTML tags:", e);// On error, show the defaults- this.$allowedTags.val(DEFAULT_ALLOWED_TAGS.join(' '));+ this.$allowedTags.val(DEFAULT_ALLOWED_TAGS.join(" "));}}async saveTags() {const tagsText = this.$allowedTags.val();- const tags = tagsText.split(/[\n,\s]+/) // Split on newlines, commas, or spaces- .map(tag => tag.trim())- .filter(tag => tag.length > 0);-- await this.updateOption('allowedHtmlTags', JSON.stringify(tags));+ const tags = tagsText+ .split(/[\n,\s]+/) // Split on newlines, commas, or spaces+ .map((tag) => tag.trim())+ .filter((tag) => tag.length > 0);++ await this.updateOption("allowedHtmlTags", JSON.stringify(tags));}async resetToDefault() {- this.$allowedTags.val(DEFAULT_ALLOWED_TAGS.join('\n')); // Use actual newline+ this.$allowedTags.val(DEFAULT_ALLOWED_TAGS.join("\n")); // Use actual newlineawait this.saveTags();}}diff --git a/src/public/app/widgets/type_widgets/options/other/network_connections.js b/src/public/app/widgets/type_widgets/options/other/network_connections.jsindex 061f9425c9..33eb5189b9 100644--- a/src/public/app/widgets/type_widgets/options/other/network_connections.js+++ b/src/public/app/widgets/type_widgets/options/other/network_connections.js@@ -15,8 +15,7 @@ export default class NetworkConnectionsOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$checkForUpdates = this.$widget.find(".check-for-updates");- this.$checkForUpdates.on("change", () =>- this.updateCheckboxOption('checkForUpdates', this.$checkForUpdates));+ this.$checkForUpdates.on("change", () => this.updateCheckboxOption("checkForUpdates", this.$checkForUpdates));}async optionsLoaded(options) {diff --git a/src/public/app/widgets/type_widgets/options/other/note_erasure_timeout.js b/src/public/app/widgets/type_widgets/options/other/note_erasure_timeout.jsindex 6733b8535b..f81735e9c4 100644--- a/src/public/app/widgets/type_widgets/options/other/note_erasure_timeout.js+++ b/src/public/app/widgets/type_widgets/options/other/note_erasure_timeout.js@@ -23,11 +23,11 @@ export default class NoteErasureTimeoutOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$eraseEntitiesAfterTimeInSeconds = this.$widget.find(".erase-entities-after-time-in-seconds");- this.$eraseEntitiesAfterTimeInSeconds.on('change', () => this.updateOption('eraseEntitiesAfterTimeInSeconds', this.$eraseEntitiesAfterTimeInSeconds.val()));+ this.$eraseEntitiesAfterTimeInSeconds.on("change", () => this.updateOption("eraseEntitiesAfterTimeInSeconds", this.$eraseEntitiesAfterTimeInSeconds.val()));this.$eraseDeletedNotesButton = this.$widget.find(".erase-deleted-notes-now-button");- this.$eraseDeletedNotesButton.on('click', () => {- server.post('notes/erase-deleted-notes-now').then(() => {+ this.$eraseDeletedNotesButton.on("click", () => {+ server.post("notes/erase-deleted-notes-now").then(() => {toastService.showMessage(t("note_erasure_timeout.deleted_notes_erased"));});});diff --git a/src/public/app/widgets/type_widgets/options/other/revision_snapshots_limit.js b/src/public/app/widgets/type_widgets/options/other/revision_snapshots_limit.jsindex 58cb409ac5..76c09ac43d 100644--- a/src/public/app/widgets/type_widgets/options/other/revision_snapshots_limit.js+++ b/src/public/app/widgets/type_widgets/options/other/revision_snapshots_limit.js@@ -15,22 +15,22 @@ const TPL = `</div><button class="erase-excess-revision-snapshots-now-button btn btn-sm" style="padding: 0 10px">- ${t('revisions_snapshot_limit.erase_excess_revision_snapshots')}</button>+ ${t("revisions_snapshot_limit.erase_excess_revision_snapshots")}</button></div>`;export default class RevisionSnapshotsLimitOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$revisionSnapshotsNumberLimit = this.$widget.find(".revision-snapshot-number-limit");- this.$revisionSnapshotsNumberLimit.on('change', () => {+ this.$revisionSnapshotsNumberLimit.on("change", () => {let revisionSnapshotNumberLimit = this.$revisionSnapshotsNumberLimit.val();if (!isNaN(revisionSnapshotNumberLimit) && revisionSnapshotNumberLimit >= -1) {- this.updateOption('revisionSnapshotNumberLimit', revisionSnapshotNumberLimit)- }+ this.updateOption("revisionSnapshotNumberLimit", revisionSnapshotNumberLimit);+ }});this.$eraseExcessRevisionSnapshotsButton = this.$widget.find(".erase-excess-revision-snapshots-now-button");- this.$eraseExcessRevisionSnapshotsButton.on('click', () => {- server.post('revisions/erase-all-excess-revisions').then(() => {+ this.$eraseExcessRevisionSnapshotsButton.on("click", () => {+ server.post("revisions/erase-all-excess-revisions").then(() => {toastService.showMessage(t("revisions_snapshot_limit.erase_excess_revision_snapshots_prompt"));});});diff --git a/src/public/app/widgets/type_widgets/options/other/revisions_snapshot_interval.js b/src/public/app/widgets/type_widgets/options/other/revisions_snapshot_interval.jsindex d0758c9e7f..f3285eb397 100644--- a/src/public/app/widgets/type_widgets/options/other/revisions_snapshot_interval.js+++ b/src/public/app/widgets/type_widgets/options/other/revisions_snapshot_interval.js@@ -17,8 +17,7 @@ export default class RevisionsSnapshotIntervalOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$revisionsTimeInterval = this.$widget.find(".revision-snapshot-time-interval-in-seconds");- this.$revisionsTimeInterval.on('change', () =>- this.updateOption('revisionSnapshotTimeInterval', this.$revisionsTimeInterval.val()));+ this.$revisionsTimeInterval.on("change", () => this.updateOption("revisionSnapshotTimeInterval", this.$revisionsTimeInterval.val()));}async optionsLoaded(options) {diff --git a/src/public/app/widgets/type_widgets/options/other/search_engine.js b/src/public/app/widgets/type_widgets/options/other/search_engine.jsindex c2974b97b5..bdbfd7b152 100644--- a/src/public/app/widgets/type_widgets/options/other/search_engine.js+++ b/src/public/app/widgets/type_widgets/options/other/search_engine.js@@ -36,11 +36,11 @@ const TPL = `</div>`;const SEARCH_ENGINES = {- "Bing": "https://www.bing.com/search?q={keyword}",- "Baidu": "https://www.baidu.com/s?wd={keyword}",- "DuckDuckGo": "https://duckduckgo.com/?q={keyword}",- "Google": "https://www.google.com/search?q={keyword}",-}+ Bing: "https://www.bing.com/search?q={keyword}",+ Baidu: "https://www.baidu.com/s?wd={keyword}",+ DuckDuckGo: "https://duckduckgo.com/?q={keyword}",+ Google: "https://www.google.com/search?q={keyword}"+};export default class SearchEngineOptions extends OptionsWidget {isEnabled() {@@ -55,16 +55,16 @@ export default class SearchEngineOptions extends OptionsWidget {this.$customSearchEngineName = this.$widget.find(".custom-search-engine-name");this.$customSearchEngineUrl = this.$widget.find(".custom-search-engine-url");- this.$predefinedSearchEngineSelect.on('change', () => {+ this.$predefinedSearchEngineSelect.on("change", () => {const predefinedSearchEngine = this.$predefinedSearchEngineSelect.val();this.$customSearchEngineName[0].value = predefinedSearchEngine;this.$customSearchEngineUrl[0].value = SEARCH_ENGINES[predefinedSearchEngine];});- this.$form.on('submit', () => {+ this.$form.on("submit", () => {this.updateMultipleOptions({- 'customSearchEngineName': this.$customSearchEngineName.val(),- 'customSearchEngineUrl': this.$customSearchEngineUrl.val()+ customSearchEngineName: this.$customSearchEngineName.val(),+ customSearchEngineUrl: this.$customSearchEngineUrl.val()});});}diff --git a/src/public/app/widgets/type_widgets/options/other/tray.js b/src/public/app/widgets/type_widgets/options/other/tray.jsindex ac7f91eb96..10255ac188 100644--- a/src/public/app/widgets/type_widgets/options/other/tray.js+++ b/src/public/app/widgets/type_widgets/options/other/tray.js@@ -16,8 +16,7 @@ export default class TrayOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$trayEnabled = this.$widget.find(".tray-enabled");- this.$trayEnabled.on('change', () =>- this.updateOption('disableTray', !this.$trayEnabled.is(":checked") ? "true" : "false"));+ this.$trayEnabled.on("change", () => this.updateOption("disableTray", !this.$trayEnabled.is(":checked") ? "true" : "false"));}isEnabled() {@@ -25,6 +24,6 @@ export default class TrayOptions extends OptionsWidget {}async optionsLoaded(options) {- this.$trayEnabled.prop("checked", options.disableTray !== 'true');+ this.$trayEnabled.prop("checked", options.disableTray !== "true");}}diff --git a/src/public/app/widgets/type_widgets/options/password.js b/src/public/app/widgets/type_widgets/options/password.jsindex 29a7353525..0f6cb1e91c 100644--- a/src/public/app/widgets/type_widgets/options/password.js+++ b/src/public/app/widgets/type_widgets/options/password.js@@ -59,22 +59,21 @@ export default class PasswordOptions extends OptionsWidget {if (confirm(t("password.reset_confirmation"))) {await server.post("password/reset?really=yesIReallyWantToResetPasswordAndLoseAccessToMyProtectedNotes");- const options = await server.get('options');+ const options = await server.get("options");this.optionsLoaded(options);toastService.showError(t("password.reset_success_message"));}});- this.$changePasswordForm.on('submit', () => this.save());+ this.$changePasswordForm.on("submit", () => this.save());this.$protectedSessionTimeout = this.$widget.find(".protected-session-timeout-in-seconds");- this.$protectedSessionTimeout.on('change', () =>- this.updateOption('protectedSessionTimeout', this.$protectedSessionTimeout.val()));+ this.$protectedSessionTimeout.on("change", () => this.updateOption("protectedSessionTimeout", this.$protectedSessionTimeout.val()));}optionsLoaded(options) {- const isPasswordSet = options.isPasswordSet === 'true';+ const isPasswordSet = options.isPasswordSet === "true";this.$widget.find(".old-password-form-group").toggle(isPasswordSet);this.$passwordHeading.text(isPasswordSet ? t("password.change_password_heading") : t("password.set_password_heading"));@@ -87,29 +86,30 @@ export default class PasswordOptions extends OptionsWidget {const newPassword1 = this.$newPassword1.val();const newPassword2 = this.$newPassword2.val();- this.$oldPassword.val('');- this.$newPassword1.val('');- this.$newPassword2.val('');+ this.$oldPassword.val("");+ this.$newPassword1.val("");+ this.$newPassword2.val("");if (newPassword1 !== newPassword2) {toastService.showError(t("password.password_mismatch"));return false;}- server.post('password/change', {- 'current_password': oldPassword,- 'new_password': newPassword1- }).then(result => {- if (result.success) {- toastService.showError(t("password.password_changed_success"));-- // password changed so current protected session is invalid and needs to be cleared- protectedSessionHolder.resetProtectedSession();- }- else {- toastService.showError(result.message);- }- });+ server+ .post("password/change", {+ current_password: oldPassword,+ new_password: newPassword1+ })+ .then((result) => {+ if (result.success) {+ toastService.showError(t("password.password_changed_success"));++ // password changed so current protected session is invalid and needs to be cleared+ protectedSessionHolder.resetProtectedSession();+ } else {+ toastService.showError(result.message);+ }+ });return false;}diff --git a/src/public/app/widgets/type_widgets/options/shortcuts.js b/src/public/app/widgets/type_widgets/options/shortcuts.jsindex 7f261ea88c..f453859f1f 100644--- a/src/public/app/widgets/type_widgets/options/shortcuts.js+++ b/src/public/app/widgets/type_widgets/options/shortcuts.js@@ -26,25 +26,25 @@ const TPL = `}</style>- <h4>${t('shortcuts.keyboard_shortcuts')}</h4>+ <h4>${t("shortcuts.keyboard_shortcuts")}</h4><p>- ${t('shortcuts.multiple_shortcuts')}- ${t('shortcuts.electron_documentation')}+ ${t("shortcuts.multiple_shortcuts")}+ ${t("shortcuts.electron_documentation")}</p><div class="form-group">- <input type="text" class="keyboard-shortcut-filter form-control" placeholder="${t('shortcuts.type_text_to_filter')}">+ <input type="text" class="keyboard-shortcut-filter form-control" placeholder="${t("shortcuts.type_text_to_filter")}"></div><div class="shortcuts-table-container"><table class="keyboard-shortcut-table" cellpadding="10"><thead><tr class="text-nowrap">- <th>${t('shortcuts.action_name')}</th>- <th>${t('shortcuts.shortcuts')}</th>- <th>${t('shortcuts.default_shortcuts')}</th>- <th>${t('shortcuts.description')}</th>+ <th>${t("shortcuts.action_name")}</th>+ <th>${t("shortcuts.shortcuts")}</th>+ <th>${t("shortcuts.default_shortcuts")}</th>+ <th>${t("shortcuts.description")}</th></tr></thead><tbody></tbody>@@ -52,9 +52,9 @@ const TPL = `</div><div class="shortcuts-options-buttons">- <button class="options-keyboard-shortcuts-reload-app btn btn-primary">${t('shortcuts.reload_app')}</button>+ <button class="options-keyboard-shortcuts-reload-app btn btn-primary">${t("shortcuts.reload_app")}</button>- <button class="options-keyboard-shortcuts-set-all-to-default btn">${t('shortcuts.set_all_to_default')}</button>+ <button class="options-keyboard-shortcuts-set-all-to-default btn">${t("shortcuts.set_all_to_default")}</button></div></div>`;@@ -68,25 +68,22 @@ export default class KeyboardShortcutsOptions extends OptionsWidget {const $table = this.$widget.find(".keyboard-shortcut-table tbody");- server.get('keyboard-actions').then(actions => {+ server.get("keyboard-actions").then((actions) => {globActions = actions;for (const action of actions) {const $tr = $("<tr>");if (action.separator) {- $tr.append(- $('<td colspan="4">')- .attr("style","background-color: var(--accented-background-color); font-weight: bold;")- .text(action.separator)- )+ $tr.append($('<td colspan="4">').attr("style", "background-color: var(--accented-background-color); font-weight: bold;").text(action.separator));} else if (action.defaultShortcuts) {$tr.append($("<td>").text(action.actionName))- .append($("<td>").append(+ .append(+ $("<td>").append($(`<input type="text" class="form-control">`).val(action.effectiveShortcuts.join(", "))- .attr('data-keyboard-action-name', action.actionName)- .attr('data-default-keyboard-shortcuts', action.defaultShortcuts.join(", "))+ .attr("data-keyboard-action-name", action.actionName)+ .attr("data-default-keyboard-shortcuts", action.defaultShortcuts.join(", ")))).append($("<td>").text(action.defaultShortcuts.join(", ")))@@ -97,39 +94,38 @@ export default class KeyboardShortcutsOptions extends OptionsWidget {}});- $table.on('change', 'input.form-control', e => {+ $table.on("change", "input.form-control", (e) => {const $input = this.$widget.find(e.target);- const actionName = $input.attr('data-keyboard-action-name');- const shortcuts = $input.val()- .replace('+,', "+Comma")+ const actionName = $input.attr("data-keyboard-action-name");+ const shortcuts = $input+ .val()+ .replace("+,", "+Comma").split(",")- .map(shortcut => shortcut.replace("+Comma", "+,"))- .filter(shortcut => !!shortcut);+ .map((shortcut) => shortcut.replace("+Comma", "+,"))+ .filter((shortcut) => !!shortcut);const optionName = `keyboardShortcuts${actionName.substr(0, 1).toUpperCase()}${actionName.substr(1)}`;this.updateOption(optionName, JSON.stringify(shortcuts));});- this.$widget.find(".options-keyboard-shortcuts-set-all-to-default").on('click', async () => {- if (!await dialogService.confirm(t('shortcuts.confirm_reset'))) {+ this.$widget.find(".options-keyboard-shortcuts-set-all-to-default").on("click", async () => {+ if (!(await dialogService.confirm(t("shortcuts.confirm_reset")))) {return;}- $table.find('input.form-control').each((_index, el) => {- const defaultShortcuts = this.$widget.find(el).attr('data-default-keyboard-shortcuts');+ $table.find("input.form-control").each((_index, el) => {+ const defaultShortcuts = this.$widget.find(el).attr("data-default-keyboard-shortcuts");if (this.$widget.find(el).val() !== defaultShortcuts) {- this.$widget.find(el)- .val(defaultShortcuts)- .trigger('change');+ this.$widget.find(el).val(defaultShortcuts).trigger("change");}});});const $filter = this.$widget.find(".keyboard-shortcut-filter");- $filter.on('keyup', () => {+ $filter.on("keyup", () => {const filter = $filter.val().trim().toLowerCase();$table.find("tr").each((i, el) => {@@ -138,26 +134,30 @@ export default class KeyboardShortcutsOptions extends OptionsWidget {return;}- const actionName = this.$widget.find(el).find('input').attr('data-keyboard-action-name');+ const actionName = this.$widget.find(el).find("input").attr("data-keyboard-action-name");if (!actionName) {this.$widget.find(el).hide();return;}- const action = globActions.find(act => act.actionName === actionName);+ const action = globActions.find((act) => act.actionName === actionName);if (!action) {this.$widget.find(el).hide();return;}- this.$widget.find(el).toggle(!!(- action.actionName.toLowerCase().includes(filter)- || action.defaultShortcuts.some(shortcut => shortcut.toLowerCase().includes(filter))- || action.effectiveShortcuts.some(shortcut => shortcut.toLowerCase().includes(filter))- || (action.description && action.description.toLowerCase().includes(filter))- ));+ this.$widget+ .find(el)+ .toggle(+ !!(+ action.actionName.toLowerCase().includes(filter) ||+ action.defaultShortcuts.some((shortcut) => shortcut.toLowerCase().includes(filter)) ||+ action.effectiveShortcuts.some((shortcut) => shortcut.toLowerCase().includes(filter)) ||+ (action.description && action.description.toLowerCase().includes(filter))+ )+ );});});}diff --git a/src/public/app/widgets/type_widgets/options/spellcheck.js b/src/public/app/widgets/type_widgets/options/spellcheck.jsindex 3014b5d2ce..86d684e6d7 100644--- a/src/public/app/widgets/type_widgets/options/spellcheck.js+++ b/src/public/app/widgets/type_widgets/options/spellcheck.js@@ -4,33 +4,33 @@ import { t } from "../../../services/i18n.js";const TPL_WEB = `<div class="options-section">- <h4>${t('spellcheck.title')}</h4>+ <h4>${t("spellcheck.title")}</h4>- <p>${t('spellcheck.description')}</p>+ <p>${t("spellcheck.description")}</p></div>`;const TPL_ELECTRON = `<div class="options-section">- <h4>${t('spellcheck.title')}</h4>+ <h4>${t("spellcheck.title")}</h4><p>${t("spellcheck.restart-required")}</p><label><input type="checkbox" class="spell-check-enabled">- ${t('spellcheck.enable')}+ ${t("spellcheck.enable")}</label><br/><div class="form-group">- <label for="spell-check-language-code">${t('spellcheck.language_code_label')}</label>- <input id="spell-check-language-code" type="text" class="spell-check-language-code form-control" placeholder="${t('spellcheck.language_code_placeholder')}">+ <label for="spell-check-language-code">${t("spellcheck.language_code_label")}</label>+ <input id="spell-check-language-code" type="text" class="spell-check-language-code form-control" placeholder="${t("spellcheck.language_code_placeholder")}"></div>- <p>${t('spellcheck.multiple_languages_info')}</p>+ <p>${t("spellcheck.multiple_languages_info")}</p>- <p><strong>${t('spellcheck.available_language_codes_label')} </strong> <span class="available-language-codes"></span></p>+ <p><strong>${t("spellcheck.available_language_codes_label")} </strong> <span class="available-language-codes"></span></p></div>`;export default class SpellcheckOptions extends OptionsWidget {@@ -41,18 +41,16 @@ export default class SpellcheckOptions extends OptionsWidget {this.$spellCheckEnabled = this.$widget.find(".spell-check-enabled");this.$spellCheckLanguageCode = this.$widget.find(".spell-check-language-code");- this.$spellCheckEnabled.on('change', () =>- this.updateCheckboxOption('spellCheckEnabled', this.$spellCheckEnabled));+ this.$spellCheckEnabled.on("change", () => this.updateCheckboxOption("spellCheckEnabled", this.$spellCheckEnabled));- this.$spellCheckLanguageCode.on('change', () =>- this.updateOption('spellCheckLanguageCode', this.$spellCheckLanguageCode.val()));+ this.$spellCheckLanguageCode.on("change", () => this.updateOption("spellCheckLanguageCode", this.$spellCheckLanguageCode.val()));this.$availableLanguageCodes = this.$widget.find(".available-language-codes");if (utils.isElectron()) {- const { webContents } = utils.dynamicRequire('@electron/remote').getCurrentWindow();+ const { webContents } = utils.dynamicRequire("@electron/remote").getCurrentWindow();- this.$availableLanguageCodes.text(webContents.session.availableSpellCheckerLanguages.join(', '));+ this.$availableLanguageCodes.text(webContents.session.availableSpellCheckerLanguages.join(", "));}}diff --git a/src/public/app/widgets/type_widgets/options/sync.js b/src/public/app/widgets/type_widgets/options/sync.jsindex ad99c4ead2..0e69f3d9fd 100644--- a/src/public/app/widgets/type_widgets/options/sync.js+++ b/src/public/app/widgets/type_widgets/options/sync.js@@ -5,41 +5,41 @@ import { t } from "../../../services/i18n.js";const TPL = `<div class="options-section">- <h4 style="margin-top: 0px;">${t('sync_2.config_title')}</h4>+ <h4 style="margin-top: 0px;">${t("sync_2.config_title")}</h4><form class="sync-setup-form"><div class="form-group">- <label for="sync-server-host" >${t('sync_2.server_address')}</label>+ <label for="sync-server-host" >${t("sync_2.server_address")}</label><input id="sync-server-host" class="sync-server-host form-control" placeholder="https://<host>:<port>"></div><div class="form-group">- <label for="sync-server-timeout" >${t('sync_2.timeout')}</label>+ <label for="sync-server-timeout" >${t("sync_2.timeout")}</label><input id="sync-server-timeout" class="sync-server-timeout form-control" min="1" max="10000000" type="number" style="text-align: left;"></div><div class="form-group">- <label for="sync-proxy form-control" >${t('sync_2.proxy_label')}</label>+ <label for="sync-proxy form-control" >${t("sync_2.proxy_label")}</label><input id="sync-proxy form-control" class="sync-proxy form-control" placeholder="https://<host>:<port>">- <p><strong>${t('sync_2.note')}:</strong> ${t('sync_2.note_description')}</p>- <p>${t('sync_2.special_value_description')}</p>+ <p><strong>${t("sync_2.note")}:</strong> ${t("sync_2.note_description")}</p>+ <p>${t("sync_2.special_value_description")}</p></div><div style="display: flex; justify-content: space-between;">- <button class="btn btn-primary">${t('sync_2.save')}</button>+ <button class="btn btn-primary">${t("sync_2.save")}</button>- <button class="btn" type="button" data-help-page="synchronization.html">${t('sync_2.help')}</button>+ <button class="btn" type="button" data-help-page="synchronization.html">${t("sync_2.help")}</button></div></form></div><div class="options-section">- <h4>${t('sync_2.test_title')}</h4>+ <h4>${t("sync_2.test_title")}</h4>- <p>${t('sync_2.test_description')}</p>+ <p>${t("sync_2.test_description")}</p>- <button class="test-sync-button btn">${t('sync_2.test_button')}</button>+ <button class="test-sync-button btn">${t("sync_2.test_button")}</button></div>`;export default class SyncOptions extends OptionsWidget {@@ -52,15 +52,15 @@ export default class SyncOptions extends OptionsWidget {this.$syncProxy = this.$widget.find(".sync-proxy");this.$testSyncButton = this.$widget.find(".test-sync-button");- this.$form.on('submit', () => this.save());+ this.$form.on("submit", () => this.save());- this.$testSyncButton.on('click', async () => {- const result = await server.post('sync/test');+ this.$testSyncButton.on("click", async () => {+ const result = await server.post("sync/test");if (result.success) {toastService.showMessage(result.message);} else {- toastService.showError(t('sync_2.handshake_failed', { message: result.message }));+ toastService.showError(t("sync_2.handshake_failed", { message: result.message }));}});}@@ -73,9 +73,9 @@ export default class SyncOptions extends OptionsWidget {save() {this.updateMultipleOptions({- 'syncServerHost': this.$syncServerHost.val(),- 'syncServerTimeout': this.$syncServerTimeout.val(),- 'syncProxy': this.$syncProxy.val()+ syncServerHost: this.$syncServerHost.val(),+ syncServerTimeout: this.$syncServerTimeout.val(),+ syncProxy: this.$syncProxy.val()});return false;diff --git a/src/public/app/widgets/type_widgets/options/text_notes/editor.js b/src/public/app/widgets/type_widgets/options/text_notes/editor.jsindex 9271d19775..84cdb047c6 100644--- a/src/public/app/widgets/type_widgets/options/text_notes/editor.js+++ b/src/public/app/widgets/type_widgets/options/text_notes/editor.js@@ -42,19 +42,18 @@ export default class EditorOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$body = $("body");- this.$widget.find(`input[name="editor-type"]`).on('change', async () => {+ this.$widget.find(`input[name="editor-type"]`).on("change", async () => {const newEditorType = this.$widget.find(`input[name="editor-type"]:checked`).val();- await this.updateOption('textNoteEditorType', newEditorType);+ await this.updateOption("textNoteEditorType", newEditorType);utils.reloadFrontendApp("editor type change");});-+this.$multilineToolbarCheckbox = this.$widget.find('input[name="multiline-toolbar"]');this.$multilineToolbarCheckbox.on("change", () => this.updateCheckboxOption("textNoteEditorMultilineToolbar", this.$multilineToolbarCheckbox));}async optionsLoaded(options) {- this.$widget.find(`input[name="editor-type"][value="${options.textNoteEditorType}"]`)- .prop("checked", "true");+ this.$widget.find(`input[name="editor-type"][value="${options.textNoteEditorType}"]`).prop("checked", "true");this.setCheckboxState(this.$multilineToolbarCheckbox, options.textNoteEditorMultilineToolbar);}}diff --git a/src/public/app/widgets/type_widgets/options/text_notes/heading_style.js b/src/public/app/widgets/type_widgets/options/text_notes/heading_style.jsindex cfc2edf7fa..a2ad013a4b 100644--- a/src/public/app/widgets/type_widgets/options/text_notes/heading_style.js+++ b/src/public/app/widgets/type_widgets/options/text_notes/heading_style.js@@ -17,12 +17,12 @@ export default class HeadingStyleOptions extends OptionsWidget {this.$widget = $(TPL);this.$body = $("body");this.$headingStyle = this.$widget.find(".heading-style");- this.$headingStyle.on('change', () => {+ this.$headingStyle.on("change", () => {const newHeadingStyle = this.$headingStyle.val();this.toggleBodyClass("heading-style-", newHeadingStyle);- this.updateOption('headingStyle', newHeadingStyle);+ this.updateOption("headingStyle", newHeadingStyle);});}@@ -31,7 +31,8 @@ export default class HeadingStyleOptions extends OptionsWidget {}toggleBodyClass(prefix, value) {- for (const clazz of Array.from(this.$body[0].classList)) { // create copy to safely iterate over while removing classes+ for (const clazz of Array.from(this.$body[0].classList)) {+ // create copy to safely iterate over while removing classesif (clazz.startsWith(prefix)) {this.$body.removeClass(clazz);}diff --git a/src/public/app/widgets/type_widgets/options/text_notes/highlights_list.js b/src/public/app/widgets/type_widgets/options/text_notes/highlights_list.jsindex 3cd4c6d1fa..532aca4e50 100644--- a/src/public/app/widgets/type_widgets/options/text_notes/highlights_list.js+++ b/src/public/app/widgets/type_widgets/options/text_notes/highlights_list.js@@ -28,11 +28,14 @@ export default class HighlightsListOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$hlt = this.$widget.find("input.highlights-list-check");- this.$hlt.on('change', () => {- const hltVals = this.$widget.find('input.highlights-list-check[type="checkbox"]:checked').map(function () {- return this.value;- }).get();- this.updateOption('highlightsList', JSON.stringify(hltVals));+ this.$hlt.on("change", () => {+ const hltVals = this.$widget+ .find('input.highlights-list-check[type="checkbox"]:checked')+ .map(function () {+ return this.value;+ })+ .get();+ this.updateOption("highlightsList", JSON.stringify(hltVals));});}diff --git a/src/public/app/widgets/type_widgets/options/text_notes/table_of_contents.js b/src/public/app/widgets/type_widgets/options/text_notes/table_of_contents.jsindex 6a73b7bea3..dd9cc4a885 100644--- a/src/public/app/widgets/type_widgets/options/text_notes/table_of_contents.js+++ b/src/public/app/widgets/type_widgets/options/text_notes/table_of_contents.js@@ -20,8 +20,7 @@ export default class TableOfContentsOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$minTocHeadings = this.$widget.find(".min-toc-headings");- this.$minTocHeadings.on('change', () =>- this.updateOption('minTocHeadings', this.$minTocHeadings.val()));+ this.$minTocHeadings.on("change", () => this.updateOption("minTocHeadings", this.$minTocHeadings.val()));}async optionsLoaded(options) {diff --git a/src/public/app/widgets/type_widgets/options/text_notes/text_auto_read_only_size.js b/src/public/app/widgets/type_widgets/options/text_notes/text_auto_read_only_size.jsindex b1570ec706..b620bbdaae 100644--- a/src/public/app/widgets/type_widgets/options/text_notes/text_auto_read_only_size.js+++ b/src/public/app/widgets/type_widgets/options/text_notes/text_auto_read_only_size.js@@ -17,8 +17,7 @@ export default class TextAutoReadOnlySizeOptions extends OptionsWidget {doRender() {this.$widget = $(TPL);this.$autoReadonlySizeText = this.$widget.find(".auto-readonly-size-text");- this.$autoReadonlySizeText.on('change', () =>- this.updateOption('autoReadonlySizeText', this.$autoReadonlySizeText.val()));+ this.$autoReadonlySizeText.on("change", () => this.updateOption("autoReadonlySizeText", this.$autoReadonlySizeText.val()));}async optionsLoaded(options) {diff --git a/src/public/app/widgets/type_widgets/protected_session.js b/src/public/app/widgets/type_widgets/protected_session.jsindex 6b752d7a23..6209460122 100644--- a/src/public/app/widgets/type_widgets/protected_session.js+++ b/src/public/app/widgets/type_widgets/protected_session.js@@ -1,4 +1,4 @@-import protectedSessionService from '../../services/protected_session.js';+import protectedSessionService from "../../services/protected_session.js";import TypeWidget from "./type_widget.js";import { t } from "../../services/i18n.js";@@ -13,23 +13,25 @@ const TPL = `<form class="protected-session-password-form"><div class="form-group">- <label for="protected-session-password-in-detail">${t('protected_session.enter_password_instruction')}</label>+ <label for="protected-session-password-in-detail">${t("protected_session.enter_password_instruction")}</label><input class="protected-session-password-in-detail form-control protected-session-password" type="password"></div>- <button class="btn btn-primary">${t('protected_session.start_session_button')}</button>+ <button class="btn btn-primary">${t("protected_session.start_session_button")}</button></form></div>`;export default class ProtectedSessionTypeWidget extends TypeWidget {- static getType() { return "protectedSession"; }+ static getType() {+ return "protectedSession";+ }doRender() {this.$widget = $(TPL);this.$passwordForm = this.$widget.find(".protected-session-password-form");this.$passwordInput = this.$widget.find(".protected-session-password");- this.$passwordForm.on('submit', () => {+ this.$passwordForm.on("submit", () => {const password = this.$passwordInput.val();this.$passwordInput.val("");diff --git a/src/public/app/widgets/type_widgets/read_only_code.js b/src/public/app/widgets/type_widgets/read_only_code.jsindex 6a45259dd3..f96b5a760a 100644--- a/src/public/app/widgets/type_widgets/read_only_code.js+++ b/src/public/app/widgets/type_widgets/read_only_code.js@@ -17,20 +17,22 @@ const TPL = `</div>`;export default class ReadOnlyCodeTypeWidget extends AbstractCodeTypeWidget {- static getType() { return "readOnlyCode"; }+ static getType() {+ return "readOnlyCode";+ }doRender() {this.$widget = $(TPL);this.contentSized();- this.$editor = this.$widget.find('.note-detail-readonly-code-content');+ this.$editor = this.$widget.find(".note-detail-readonly-code-content");super.doRender();}async doRefresh(note) {- let {content} = await this.note.getBlob();+ let { content } = await this.note.getBlob();- if (note.type === 'text' && this.noteContext?.viewScope?.viewMode === 'source') {+ if (note.type === "text" && this.noteContext?.viewScope?.viewMode === "source") {content = this.format(content);}@@ -44,7 +46,7 @@ export default class ReadOnlyCodeTypeWidget extends AbstractCodeTypeWidget {};}- async executeWithContentElementEvent({resolve, ntxId}) {+ async executeWithContentElementEvent({ resolve, ntxId }) {if (!this.isNoteContext(ntxId)) {return;}@@ -55,43 +57,48 @@ export default class ReadOnlyCodeTypeWidget extends AbstractCodeTypeWidget {}format(html) {- let indent = '\n';- const tab = '\t';+ let indent = "\n";+ const tab = "\t";let i = 0;let pre = [];html = html- .replace(new RegExp('<pre>((.|\\t|\\n|\\r)+)?</pre>'), function (x) {- pre.push({indent: '', tag: x});- return '<--TEMPPRE' + i++ + '/-->'+ .replace(new RegExp("<pre>((.|\\t|\\n|\\r)+)?</pre>"), function (x) {+ pre.push({ indent: "", tag: x });+ return "<--TEMPPRE" + i++ + "/-->";})- .replace(new RegExp('<[^<>]+>[^<]?', 'g'), function (x) {+ .replace(new RegExp("<[^<>]+>[^<]?", "g"), function (x) {let ret;let tag = /<\/?([^\s/>]+)/.exec(x)[1];- let p = new RegExp('<--TEMPPRE(\\d+)/-->').exec(x);+ let p = new RegExp("<--TEMPPRE(\\d+)/-->").exec(x);if (p) {pre[p[1]].indent = indent;}- if (['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr'].indexOf(tag) >= 0) { // self closing tag+ if (["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "menuitem", "meta", "param", "source", "track", "wbr"].indexOf(tag) >= 0) {+ // self closing tagret = indent + x;} else {- if (x.indexOf('</') < 0) { //open tag- if (x.charAt(x.length - 1) !== '>') ret = indent + x.substr(0, x.length - 1) + indent + tab + x.substr(x.length - 1, x.length); else ret = indent + x;+ if (x.indexOf("</") < 0) {+ //open tag+ if (x.charAt(x.length - 1) !== ">") ret = indent + x.substr(0, x.length - 1) + indent + tab + x.substr(x.length - 1, x.length);+ else ret = indent + x;!p && (indent += tab);- } else {//close tag+ } else {+ //close tagindent = indent.substr(0, indent.length - 1);- if (x.charAt(x.length - 1) !== '>') ret = indent + x.substr(0, x.length - 1) + indent + x.substr(x.length - 1, x.length); else ret = indent + x;+ if (x.charAt(x.length - 1) !== ">") ret = indent + x.substr(0, x.length - 1) + indent + x.substr(x.length - 1, x.length);+ else ret = indent + x;}}return ret;});- for (i = pre.length; i--;) {- html = html.replace('<--TEMPPRE' + i + '/-->', pre[i].tag.replace('<pre>', '<pre>\n').replace('</pre>', pre[i].indent + '</pre>'));+ for (i = pre.length; i--; ) {+ html = html.replace("<--TEMPPRE" + i + "/-->", pre[i].tag.replace("<pre>", "<pre>\n").replace("</pre>", pre[i].indent + "</pre>"));}- return html.charAt(0) === '\n' ? html.substr(1, html.length - 1) : html;+ return html.charAt(0) === "\n" ? html.substr(1, html.length - 1) : html;}}diff --git a/src/public/app/widgets/type_widgets/read_only_text.js b/src/public/app/widgets/type_widgets/read_only_text.jsindex 54fa592bc6..b1e08a269e 100644--- a/src/public/app/widgets/type_widgets/read_only_text.js+++ b/src/public/app/widgets/type_widgets/read_only_text.js@@ -71,12 +71,14 @@ const TPL = ``;export default class ReadOnlyTextTypeWidget extends AbstractTextTypeWidget {- static getType() { return "readOnlyText"; }+ static getType() {+ return "readOnlyText";+ }doRender() {this.$widget = $(TPL);- this.$content = this.$widget.find('.note-detail-readonly-text-content');+ this.$content = this.$widget.find(".note-detail-readonly-text-content");this.setupImageOpening(true);@@ -84,7 +86,7 @@ export default class ReadOnlyTextTypeWidget extends AbstractTextTypeWidget {}cleanup() {- this.$content.html('');+ this.$content.html("");}async doRefresh(note) {@@ -102,15 +104,15 @@ export default class ReadOnlyTextTypeWidget extends AbstractTextTypeWidget {});this.$content.find("section").each(async (_, el) => {- const noteId = $(el).attr('data-note-id');+ const noteId = $(el).attr("data-note-id");this.loadIncludedNote(noteId, $(el));});- if (this.$content.find('span.math-tex').length > 0) {+ if (this.$content.find("span.math-tex").length > 0) {await libraryLoader.requireLibrary(libraryLoader.KATEX);- renderMathInElement(this.$content[0], {trust: true});+ renderMathInElement(this.$content[0], { trust: true });}await this.#applyInlineMermaid();@@ -133,11 +135,11 @@ export default class ReadOnlyTextTypeWidget extends AbstractTextTypeWidget {mermaid.init(getMermaidConfig(), this.$content.find(".mermaid-diagram"));}- async refreshIncludedNoteEvent({noteId}) {+ async refreshIncludedNoteEvent({ noteId }) {this.refreshIncludedNote(this.$content, noteId);}- async executeWithContentElementEvent({resolve, ntxId}) {+ async executeWithContentElementEvent({ resolve, ntxId }) {if (!this.isNoteContext(ntxId)) {return;}diff --git a/src/public/app/widgets/type_widgets/relation_map.js b/src/public/app/widgets/type_widgets/relation_map.jsindex c1511f8bd0..9dbeb2d453 100644--- a/src/public/app/widgets/type_widgets/relation_map.js+++ b/src/public/app/widgets/type_widgets/relation_map.js@@ -12,57 +12,75 @@ import dialogService from "../../services/dialog.js";import { t } from "../../services/i18n.js";const uniDirectionalOverlays = [- [ "Arrow", {- location: 1,- id: "arrow",- length: 14,- foldback: 0.8- } ],- [ "Label", { label: "", id: "label", cssClass: "connection-label" }]+ [+ "Arrow",+ {+ location: 1,+ id: "arrow",+ length: 14,+ foldback: 0.8+ }+ ],+ ["Label", { label: "", id: "label", cssClass: "connection-label" }]];const biDirectionalOverlays = [- [ "Arrow", {- location: 1,- id: "arrow",- length: 14,- foldback: 0.8- } ],- [ "Label", { label: "", id: "label", cssClass: "connection-label" }],- [ "Arrow", {- location: 0,- id: "arrow2",- length: 14,- direction: -1,- foldback: 0.8- } ]+ [+ "Arrow",+ {+ location: 1,+ id: "arrow",+ length: 14,+ foldback: 0.8+ }+ ],+ ["Label", { label: "", id: "label", cssClass: "connection-label" }],+ [+ "Arrow",+ {+ location: 0,+ id: "arrow2",+ length: 14,+ direction: -1,+ foldback: 0.8+ }+ ]];const inverseRelationsOverlays = [- [ "Arrow", {- location: 1,- id: "arrow",- length: 14,- foldback: 0.8- } ],- [ "Label", { label: "", location: 0.2, id: "label-source", cssClass: "connection-label" }],- [ "Label", { label: "", location: 0.8, id: "label-target", cssClass: "connection-label" }],- [ "Arrow", {- location: 0,- id: "arrow2",- length: 14,- direction: -1,- foldback: 0.8- } ]+ [+ "Arrow",+ {+ location: 1,+ id: "arrow",+ length: 14,+ foldback: 0.8+ }+ ],+ ["Label", { label: "", location: 0.2, id: "label-source", cssClass: "connection-label" }],+ ["Label", { label: "", location: 0.8, id: "label-target", cssClass: "connection-label" }],+ [+ "Arrow",+ {+ location: 0,+ id: "arrow2",+ length: 14,+ direction: -1,+ foldback: 0.8+ }+ ]];const linkOverlays = [- [ "Arrow", {- location: 1,- id: "arrow",- length: 14,- foldback: 0.8- } ]+ [+ "Arrow",+ {+ location: 1,+ id: "arrow",+ length: 14,+ foldback: 0.8+ }+ ]];const TPL = `@@ -75,7 +93,9 @@ const TPL = `let containerCounter = 1;export default class RelationMapTypeWidget extends TypeWidget {- static getType() { return "relationMap"; }+ static getType() {+ return "relationMap";+ }doRender() {this.$widget = $(TPL);@@ -87,10 +107,10 @@ export default class RelationMapTypeWidget extends TypeWidget {this.relations = null;this.pzInstance = null;- this.$relationMapWrapper = this.$widget.find('.relation-map-wrapper');- this.$relationMapWrapper.on('click', event => {+ this.$relationMapWrapper = this.$widget.find(".relation-map-wrapper");+ this.$relationMapWrapper.on("click", (event) => {if (this.clipboard) {- let {x, y} = this.getMousePosition(event);+ let { x, y } = this.getMousePosition(event);// modifying position so that the cursor is on the top-center of the boxx -= 80;@@ -108,8 +128,8 @@ export default class RelationMapTypeWidget extends TypeWidget {return true;});- this.$relationMapContainer.attr("id", "relation-map-container-" + (containerCounter++));- this.$relationMapContainer.on("contextmenu", ".note-box", e => {+ this.$relationMapContainer.attr("id", "relation-map-container-" + containerCounter++);+ this.$relationMapContainer.on("contextmenu", ".note-box", (e) => {contextMenu.show({x: e.pageX,y: e.pageY,@@ -118,7 +138,7 @@ export default class RelationMapTypeWidget extends TypeWidget {{ title: t("relation_map.remove_note"), command: "remove", uiIcon: "bx bx-trash" },{ title: t("relation_map.edit_title"), command: "editTitle", uiIcon: "bx bx-pencil" }],- selectMenuItemHandler: ({command}) => this.contextMenuHandler(command, e.target)+ selectMenuItemHandler: ({ command }) => this.contextMenuHandler(command, e.target)});return false; // blocks default browser right click menu@@ -126,10 +146,10 @@ export default class RelationMapTypeWidget extends TypeWidget {this.clipboard = null;- this.$widget.on("drop", ev => this.dropNoteOntoRelationMapHandler(ev));- this.$widget.on("dragover", ev => ev.preventDefault());+ this.$widget.on("drop", (ev) => this.dropNoteOntoRelationMapHandler(ev));+ this.$widget.on("dragover", (ev) => ev.preventDefault());- this.initialized = new Promise(async res => {+ this.initialized = new Promise(async (res) => {await libraryLoader.requireLibrary(libraryLoader.RELATION_MAP);jsPlumb.ready(res);@@ -145,8 +165,7 @@ export default class RelationMapTypeWidget extends TypeWidget {if (command === "openInNewTab") {appContext.tabManager.openTabWithNoteWithHoisting(noteId);- }- else if (command === "remove") {+ } else if (command === "remove") {const result = await dialogService.confirmDeleteNoteBoxWithNote($title.text());if (!result.confirmed) {@@ -161,13 +180,12 @@ export default class RelationMapTypeWidget extends TypeWidget {await server.remove(`notes/${noteId}?taskId=${taskId}&last=true`);}- this.mapData.notes = this.mapData.notes.filter(note => note.noteId !== noteId);+ this.mapData.notes = this.mapData.notes.filter((note) => note.noteId !== noteId);- this.relations = this.relations.filter(relation => relation.sourceNoteId !== noteId && relation.targetNoteId !== noteId);+ this.relations = this.relations.filter((relation) => relation.sourceNoteId !== noteId && relation.targetNoteId !== noteId);this.saveData();- }- else if (command === "editTitle") {+ } else if (command === "editTitle") {const title = await dialogService.prompt({title: t("relation_map.rename_note"),message: t("relation_map.enter_new_title"),@@ -237,29 +255,31 @@ export default class RelationMapTypeWidget extends TypeWidget {}async loadNotesAndRelations() {- const noteIds = this.mapData.notes.map(note => note.noteId);- const data = await server.post("relation-map", {noteIds, relationMapNoteId: this.noteId});+ const noteIds = this.mapData.notes.map((note) => note.noteId);+ const data = await server.post("relation-map", { noteIds, relationMapNoteId: this.noteId });this.relations = [];for (const relation of data.relations) {- const match = this.relations.find(rel =>- rel.name === data.inverseRelations[relation.name]- && ((rel.sourceNoteId === relation.sourceNoteId && rel.targetNoteId === relation.targetNoteId)- || (rel.sourceNoteId === relation.targetNoteId && rel.targetNoteId === relation.sourceNoteId)));+ const match = this.relations.find(+ (rel) =>+ rel.name === data.inverseRelations[relation.name] &&+ ((rel.sourceNoteId === relation.sourceNoteId && rel.targetNoteId === relation.targetNoteId) ||+ (rel.sourceNoteId === relation.targetNoteId && rel.targetNoteId === relation.sourceNoteId))+ );if (match) {- match.type = relation.type = relation.name === data.inverseRelations[relation.name] ? 'biDirectional' : 'inverse';+ match.type = relation.type = relation.name === data.inverseRelations[relation.name] ? "biDirectional" : "inverse";relation.render = false; // don't render second relation} else {- relation.type = 'uniDirectional';+ relation.type = "uniDirectional";relation.render = true;}this.relations.push(relation);}- this.mapData.notes = this.mapData.notes.filter(note => note.noteId in data.noteTitles);+ this.mapData.notes = this.mapData.notes.filter((note) => note.noteId in data.noteTitles);this.jsPlumbInstance.batch(async () => {this.clearMap();@@ -283,11 +303,10 @@ export default class RelationMapTypeWidget extends TypeWidget {connection.id = relation.attributeId;- if (relation.type === 'inverse') {+ if (relation.type === "inverse") {connection.getOverlay("label-source").setLabel(relation.name);connection.getOverlay("label-target").setLabel(data.inverseRelations[relation.name]);- }- else {+ } else {connection.getOverlay("label").setLabel(relation.name);}@@ -305,14 +324,15 @@ export default class RelationMapTypeWidget extends TypeWidget {maxZoom: 2,minZoom: 0.3,smoothScroll: false,- filterKey: function(e, dx, dy, dz) {+ filterKey: function (e, dx, dy, dz) {// if ALT is pressed, then panzoom should bubble the event up// this is to preserve ALT-LEFT, ALT-RIGHT navigation workingreturn e.altKey;}});- this.pzInstance.on('transform', () => { // gets triggered on any transform change+ this.pzInstance.on("transform", () => {+ // gets triggered on any transform changethis.jsPlumbInstance.setZoom(this.getZoom());this.saveCurrentTransform();@@ -322,8 +342,7 @@ export default class RelationMapTypeWidget extends TypeWidget {this.pzInstance.zoomTo(0, 0, this.mapData.transform.scale);this.pzInstance.moveTo(this.mapData.transform.x, this.mapData.transform.y);- }- else {+ } else {// set to initial coordinatesthis.pzInstance.moveTo(0, 0);}@@ -351,7 +370,7 @@ export default class RelationMapTypeWidget extends TypeWidget {}}- initJsPlumbInstance () {+ initJsPlumbInstance() {if (this.jsPlumbInstance) {this.cleanup();@@ -359,20 +378,20 @@ export default class RelationMapTypeWidget extends TypeWidget {}this.jsPlumbInstance = jsPlumb.getInstance({- Endpoint: ["Dot", {radius: 2}],+ Endpoint: ["Dot", { radius: 2 }],Connector: "StateMachine",ConnectionOverlays: uniDirectionalOverlays,HoverPaintStyle: { stroke: "#777", strokeWidth: 1 },Container: this.$relationMapContainer.attr("id")});- this.jsPlumbInstance.registerConnectionType("uniDirectional", { anchor:"Continuous", connector:"StateMachine", overlays: uniDirectionalOverlays });+ this.jsPlumbInstance.registerConnectionType("uniDirectional", { anchor: "Continuous", connector: "StateMachine", overlays: uniDirectionalOverlays });- this.jsPlumbInstance.registerConnectionType("biDirectional", { anchor:"Continuous", connector:"StateMachine", overlays: biDirectionalOverlays });+ this.jsPlumbInstance.registerConnectionType("biDirectional", { anchor: "Continuous", connector: "StateMachine", overlays: biDirectionalOverlays });- this.jsPlumbInstance.registerConnectionType("inverse", { anchor:"Continuous", connector:"StateMachine", overlays: inverseRelationsOverlays });+ this.jsPlumbInstance.registerConnectionType("inverse", { anchor: "Continuous", connector: "StateMachine", overlays: inverseRelationsOverlays });- this.jsPlumbInstance.registerConnectionType("link", { anchor:"Continuous", connector:"StateMachine", overlays: linkOverlays });+ this.jsPlumbInstance.registerConnectionType("link", { anchor: "Continuous", connector: "StateMachine", overlays: linkOverlays });this.jsPlumbInstance.bind("connection", (info, originalEvent) => this.connectionCreatedHandler(info, originalEvent));}@@ -385,28 +404,27 @@ export default class RelationMapTypeWidget extends TypeWidget {// don't create context menu if it's a link since there's nothing to do with link from relation map// (don't open browser menu either)event.preventDefault();- }- else {+ } else {event.preventDefault();event.stopPropagation();contextMenu.show({x: event.pageX,y: event.pageY,- items: [{title: t("relation_map.remove_relation"), command: "remove", uiIcon: "bx bx-trash"}],- selectMenuItemHandler: async ({command}) => {- if (command === 'remove') {- if (!await dialogService.confirm(t("relation_map.confirm_remove_relation"))) {+ items: [{ title: t("relation_map.remove_relation"), command: "remove", uiIcon: "bx bx-trash" }],+ selectMenuItemHandler: async ({ command }) => {+ if (command === "remove") {+ if (!(await dialogService.confirm(t("relation_map.confirm_remove_relation")))) {return;}- const relation = this.relations.find(rel => rel.attributeId === connection.id);+ const relation = this.relations.find((rel) => rel.attributeId === connection.id);await server.remove(`notes/${relation.sourceNoteId}/relations/${relation.name}/to/${relation.targetNoteId}`);this.jsPlumbInstance.deleteConnection(connection);- this.relations = this.relations.filter(relation => relation.attributeId !== connection.id);+ this.relations = this.relations.filter((relation) => relation.attributeId !== connection.id);}}});@@ -421,7 +439,7 @@ export default class RelationMapTypeWidget extends TypeWidget {let name = await dialogService.prompt({message: t("relation_map.specify_new_relation_name"),shown: ({ $answer }) => {- $answer.on('keyup', () => {+ $answer.on("keyup", () => {// invalid characters are simply ignored (from user perspective they are not even entered)const attrName = utils.filterAttributeName($answer.val());@@ -447,13 +465,10 @@ export default class RelationMapTypeWidget extends TypeWidget {const targetNoteId = this.idToNoteId(connection.target.id);const sourceNoteId = this.idToNoteId(connection.source.id);- const relationExists = this.relations.some(rel =>- rel.targetNoteId === targetNoteId- && rel.sourceNoteId === sourceNoteId- && rel.name === name);+ const relationExists = this.relations.some((rel) => rel.targetNoteId === targetNoteId && rel.sourceNoteId === sourceNoteId && rel.name === name);if (relationExists) {- await dialogService.info(t("relation_map.connection_exists", {name}));+ await dialogService.info(t("relation_map.connection_exists", { name }));this.jsPlumbInstance.deleteConnection(connection);@@ -470,8 +485,8 @@ export default class RelationMapTypeWidget extends TypeWidget {}async createNoteBox(noteId, title, x, y) {- const $link = await linkService.createLink(noteId, {title});- $link.mousedown(e => linkService.goToLink(e));+ const $link = await linkService.createLink(noteId, { title });+ $link.mousedown((e) => linkService.goToLink(e));const note = await froca.getNote(noteId);@@ -487,15 +502,15 @@ export default class RelationMapTypeWidget extends TypeWidget {this.jsPlumbInstance.getContainer().appendChild($noteBox[0]);this.jsPlumbInstance.draggable($noteBox[0], {- start: params => {},- drag: params => {},- stop: params => {+ start: (params) => {},+ drag: (params) => {},+ stop: (params) => {const noteId = this.idToNoteId(params.el.id);- const note = this.mapData.notes.find(note => note.noteId === noteId);+ const note = this.mapData.notes.find((note) => note.noteId === noteId);if (!note) {- logError(t("relation_map.note_not_found", {noteId}));+ logError(t("relation_map.note_not_found", { noteId }));return;}@@ -510,8 +525,8 @@ export default class RelationMapTypeWidget extends TypeWidget {anchor: "Continuous",connectorStyle: { stroke: "#000", strokeWidth: 1 },connectionType: "basic",- extract:{- "action": "the-action"+ extract: {+ action: "the-action"}});@@ -525,16 +540,16 @@ export default class RelationMapTypeWidget extends TypeWidget {getZoom() {const matrixRegex = /matrix\((-?\d*\.?\d+),\s*0,\s*0,\s*-?\d*\.?\d+,\s*-?\d*\.?\d+,\s*-?\d*\.?\d+\)/;- const transform = this.$relationMapContainer.css('transform');+ const transform = this.$relationMapContainer.css("transform");- if (transform === 'none') {+ if (transform === "none") {return 1;}const matches = transform.match(matrixRegex);if (!matches) {- throw new Error(t("relation_map.cannot_match_transform", {transform}));+ throw new Error(t("relation_map.cannot_match_transform", { transform }));}return matches[1];@@ -545,23 +560,22 @@ export default class RelationMapTypeWidget extends TypeWidget {const notes = JSON.parse(ev.originalEvent.dataTransfer.getData("text"));- let {x, y} = this.getMousePosition(ev);+ let { x, y } = this.getMousePosition(ev);for (const note of notes) {- const exists = this.mapData.notes.some(n => n.noteId === note.noteId);+ const exists = this.mapData.notes.some((n) => n.noteId === note.noteId);if (exists) {- toastService.showError(t("relation_map.note_already_in_diagram", {title: note.title}));+ toastService.showError(t("relation_map.note_already_in_diagram", { title: note.title }));continue;}- this.mapData.notes.push({noteId: note.noteId, x, y});+ this.mapData.notes.push({ noteId: note.noteId, x, y });if (x > 1000) {y += 100;x = 0;- }- else {+ } else {x += 200;}}@@ -588,7 +602,7 @@ export default class RelationMapTypeWidget extends TypeWidget {};}- async relationMapCreateChildNoteEvent({ntxId}) {+ async relationMapCreateChildNoteEvent({ ntxId }) {if (!this.isNoteContext(ntxId)) {return;}@@ -599,10 +613,10 @@ export default class RelationMapTypeWidget extends TypeWidget {return;}- const {note} = await server.post(`notes/${this.noteId}/children?target=into`, {+ const { note } = await server.post(`notes/${this.noteId}/children?target=into`, {title,- content: '',- type: 'text'+ content: "",+ type: "text"});toastService.showMessage(t("relation_map.click_on_canvas_to_place_new_note"));@@ -610,7 +624,7 @@ export default class RelationMapTypeWidget extends TypeWidget {this.clipboard = { noteId: note.noteId, title };}- relationMapResetPanZoomEvent({ntxId}) {+ relationMapResetPanZoomEvent({ ntxId }) {if (!this.isNoteContext(ntxId)) {return;}@@ -620,7 +634,7 @@ export default class RelationMapTypeWidget extends TypeWidget {this.pzInstance.moveTo(0, 0);}- relationMapResetZoomInEvent({ntxId}) {+ relationMapResetZoomInEvent({ ntxId }) {if (!this.isNoteContext(ntxId)) {return;}@@ -628,7 +642,7 @@ export default class RelationMapTypeWidget extends TypeWidget {this.pzInstance.zoomTo(0, 0, 1.2);}- relationMapResetZoomOutEvent({ntxId}) {+ relationMapResetZoomOutEvent({ ntxId }) {if (!this.isNoteContext(ntxId)) {return;}diff --git a/src/public/app/widgets/type_widgets/render.js b/src/public/app/widgets/type_widgets/render.jsindex 91e699414a..27772c74ce 100644--- a/src/public/app/widgets/type_widgets/render.js+++ b/src/public/app/widgets/type_widgets/render.js@@ -20,12 +20,14 @@ const TPL = `</div>`;export default class RenderTypeWidget extends TypeWidget {- static getType() { return "render"; }+ static getType() {+ return "render";+ }doRender() {this.$widget = $(TPL);- this.$noteDetailRenderHelp = this.$widget.find('.note-detail-render-help');- this.$noteDetailRenderContent = this.$widget.find('.note-detail-render-content');+ this.$noteDetailRenderHelp = this.$widget.find(".note-detail-render-help");+ this.$noteDetailRenderContent = this.$widget.find(".note-detail-render-content");super.doRender();}@@ -51,7 +53,7 @@ export default class RenderTypeWidget extends TypeWidget {}}- async executeWithContentElementEvent({resolve, ntxId}) {+ async executeWithContentElementEvent({ resolve, ntxId }) {if (!this.isNoteContext(ntxId)) {return;}diff --git a/src/public/app/widgets/type_widgets/type_widget.js b/src/public/app/widgets/type_widgets/type_widget.jsindex de328906f4..3591c7821c 100644--- a/src/public/app/widgets/type_widgets/type_widget.js+++ b/src/public/app/widgets/type_widgets/type_widget.js@@ -22,13 +22,12 @@ export default class TypeWidget extends NoteContextAwareWidget {this.toggleInt(false);this.cleanup();- }- else {+ } else {this.toggleInt(true);await this.doRefresh(this.note);- this.triggerEvent('noteDetailRefreshed', {ntxId: this.noteContext.ntxId});+ this.triggerEvent("noteDetailRefreshed", { ntxId: this.noteContext.ntxId });}}@@ -41,7 +40,7 @@ export default class TypeWidget extends NoteContextAwareWidget {focus() {}- async readOnlyTemporarilyDisabledEvent({noteContext}) {+ async readOnlyTemporarilyDisabledEvent({ noteContext }) {if (this.isNoteContext(noteContext.ntxId)) {await this.refresh();@@ -51,14 +50,12 @@ export default class TypeWidget extends NoteContextAwareWidget {// events should be propagated manually to the children widgetshandleEventInChildren(name, data) {- if (['activeContextChanged', 'setNoteContext'].includes(name)) {+ if (["activeContextChanged", "setNoteContext"].includes(name)) {// won't trigger .refresh();- return super.handleEventInChildren('setNoteContext', data);- }- else if (name === 'entitiesReloaded') {+ return super.handleEventInChildren("setNoteContext", data);+ } else if (name === "entitiesReloaded") {return super.handleEventInChildren(name, data);- }- else {+ } else {return Promise.resolve();}}diff --git a/src/public/app/widgets/type_widgets/web_view.js b/src/public/app/widgets/type_widgets/web_view.jsindex 717392d268..5bfa74f053 100644--- a/src/public/app/widgets/type_widgets/web_view.js+++ b/src/public/app/widgets/type_widgets/web_view.js@@ -20,14 +20,16 @@ const TPL = `</div>`;export default class WebViewTypeWidget extends TypeWidget {- static getType() { return "webView"; }+ static getType() {+ return "webView";+ }doRender() {this.$widget = $(TPL);- this.$noteDetailWebViewHelp = this.$widget.find('.note-detail-web-view-help');- this.$noteDetailWebViewContent = this.$widget.find('.note-detail-web-view-content');+ this.$noteDetailWebViewHelp = this.$widget.find(".note-detail-web-view-help");+ this.$noteDetailWebViewContent = this.$widget.find(".note-detail-web-view-content");- window.addEventListener('resize', () => this.setDimensions(), false);+ window.addEventListener("resize", () => this.setDimensions(), false);super.doRender();}@@ -37,12 +39,10 @@ export default class WebViewTypeWidget extends TypeWidget {this.$noteDetailWebViewHelp.hide();this.$noteDetailWebViewContent.hide();- const webViewSrc = this.note.getLabelValue('webViewSrc');+ const webViewSrc = this.note.getLabelValue("webViewSrc");if (webViewSrc) {- this.$noteDetailWebViewContent- .show()- .attr("src", webViewSrc);+ this.$noteDetailWebViewContent.show().attr("src", webViewSrc);} else {this.$noteDetailWebViewContent.hide();this.$noteDetailWebViewHelp.show();@@ -60,13 +60,11 @@ export default class WebViewTypeWidget extends TypeWidget {setDimensions() {const $parent = this.$widget;- this.$noteDetailWebViewContent- .height($parent.height())- .width($parent.width());+ this.$noteDetailWebViewContent.height($parent.height()).width($parent.width());}- entitiesReloadedEvent({loadResults}) {- if (loadResults.getAttributeRows().find(attr => attr.name === 'webViewSrc' && attributeService.isAffecting(attr, this.noteContext.note))) {+ entitiesReloadedEvent({ loadResults }) {+ if (loadResults.getAttributeRows().find((attr) => attr.name === "webViewSrc" && attributeService.isAffecting(attr, this.noteContext.note))) {this.refresh();}}diff --git a/src/public/app/widgets/watched_file_update_status.js b/src/public/app/widgets/watched_file_update_status.jsindex 1747723d53..6f3ee4e3dc 100644--- a/src/public/app/widgets/watched_file_update_status.js+++ b/src/public/app/widgets/watched_file_update_status.js@@ -12,7 +12,7 @@ const TPL = `}</style>- <p>${t("watched_file_update_status.file_last_modified", { count: '' })}</p>+ <p>${t("watched_file_update_status.file_last_modified", { count: "" })}</p><div style="display: flex; flex-direction: row; justify-content: space-evenly;"><button class="btn btn-sm file-upload-button">${t("watched_file_update_status.upload_modified_file")}</button>@@ -47,7 +47,7 @@ export default class WatchedFileUpdateStatusWidget extends NoteContextAwareWidge});this.$ignoreThisChangeButton = this.$widget.find(".ignore-this-change-button");- this.$ignoreThisChangeButton.on('click', () => {+ this.$ignoreThisChangeButton.on("click", () => {const { entityType, entityId } = this.getEntity();fileWatcher.ignoreModification(entityType, entityId);@@ -70,20 +70,21 @@ export default class WatchedFileUpdateStatusWidget extends NoteContextAwareWidgeconst { viewScope } = this.noteContext;- if (viewScope.viewMode === 'attachments' && viewScope.attachmentId) {+ if (viewScope.viewMode === "attachments" && viewScope.attachmentId) {return {- entityType: 'attachments',+ entityType: "attachments",entityId: viewScope.attachmentId};} else {return {- entityType: 'notes',+ entityType: "notes",entityId: this.noteId};}}- openedFileUpdatedEvent(data) {console.log(data);+ openedFileUpdatedEvent(data) {+ console.log(data);const { entityType, entityId } = this.getEntity();if (data.entityType === entityType && data.entityId === entityId) {diff --git a/src/public/manifest.webmanifest b/src/public/manifest.webmanifestindex 75d0d225d0..b2cbca184c 100644--- a/src/public/manifest.webmanifest+++ b/src/public/manifest.webmanifest@@ -1,17 +1,17 @@{- "name": "Trilium Notes",- "short_name": "Trilium",- "description": "Trilium Notes is a hierarchical note taking application with focus on building large personal knowledge bases.",- "theme_color": "#333333",- "background_color": "#1F1F1F",- "display": "standalone",- "scope": "/",- "start_url": "/",- "icons": [- {- "src": "icon.png",- "sizes": "512x512",- "type": "image/png"- }- ]+ "name": "Trilium Notes",+ "short_name": "Trilium",+ "description": "Trilium Notes is a hierarchical note taking application with focus on building large personal knowledge bases.",+ "theme_color": "#333333",+ "background_color": "#1F1F1F",+ "display": "standalone",+ "scope": "/",+ "start_url": "/",+ "icons": [+ {+ "src": "icon.png",+ "sizes": "512x512",+ "type": "image/png"+ }+ ]}diff --git a/src/public/stylesheets/calendar.css b/src/public/stylesheets/calendar.cssindex 1a54afed76..49de32f525 100644--- a/src/public/stylesheets/calendar.css+++ b/src/public/stylesheets/calendar.css@@ -1,113 +1,115 @@-.calendar-dropdown-widget *, .calendar-dropdown-widget *:before, .calendar-dropdown-widget *:after {- box-sizing: border-box;+.calendar-dropdown-widget *,+.calendar-dropdown-widget *:before,+.calendar-dropdown-widget *:after {+ box-sizing: border-box;}.calendar-dropdown-widget {- margin: 0 auto;- overflow: hidden;- width: 100%;+ margin: 0 auto;+ overflow: hidden;+ width: 100%;}.calendar-dropdown-widget .calendar-btn {- -moz-user-select: none;- -ms-user-select: none;- user-select: none;- -webkit-appearance: button;- appearance: none;- background: none;- border: 0;- color: inherit;- cursor: pointer;- font-size: x-large;- line-height: normal;- min-width: 27px;- outline: none;- overflow: visible;- padding: 0;- text-align: center;+ -moz-user-select: none;+ -ms-user-select: none;+ user-select: none;+ -webkit-appearance: button;+ appearance: none;+ background: none;+ border: 0;+ color: inherit;+ cursor: pointer;+ font-size: x-large;+ line-height: normal;+ min-width: 27px;+ outline: none;+ overflow: visible;+ padding: 0;+ text-align: center;}.calendar-dropdown-widget .calendar-header {- align-items: center;- display: flex;- padding: 0 0.5rem 0.5rem 0.5rem;+ align-items: center;+ display: flex;+ padding: 0 0.5rem 0.5rem 0.5rem;}.calendar-dropdown-widget .calendar-header > div {- display: flex;- justify-content: center;- flex-grow: 1;+ display: flex;+ justify-content: center;+ flex-grow: 1;}.calendar-dropdown-widget .calendar-header select {- cursor: pointer;+ cursor: pointer;}.calendar-dropdown-widget .calendar-header input,.calendar-dropdown-widget .calendar-header select {- appearance: none;- text-align: center;- border: 0;- border-bottom: 1px solid var(--button-border-color);- background-color: var(--menu-background-color) !important;- outline: 0;+ appearance: none;+ text-align: center;+ border: 0;+ border-bottom: 1px solid var(--button-border-color);+ background-color: var(--menu-background-color) !important;+ outline: 0;}.calendar-dropdown-widget .calendar-week {- display: flex;- flex-wrap: wrap;+ display: flex;+ flex-wrap: wrap;}.calendar-dropdown-widget .calendar-week span {- flex-direction: column;- flex: 0 0 14.28%;- font-size: 1rem;- font-weight: bold;- max-width: 14.28%;- padding-top: 5px;- padding-bottom: 5px;- text-align: center;+ flex-direction: column;+ flex: 0 0 14.28%;+ font-size: 1rem;+ font-weight: bold;+ max-width: 14.28%;+ padding-top: 5px;+ padding-bottom: 5px;+ text-align: center;}.calendar-dropdown-widget .calendar-body {- display: flex;- flex-wrap: wrap;+ display: flex;+ flex-wrap: wrap;}.calendar-dropdown-widget .calendar-date {- align-items: center;- color: var(--main-text-color);- background-color: var(--main-background-color);- display: flex;- flex-direction: column;- flex: 0 0 14.28%;- max-width: 14.28%;- padding: 0.4rem 0;- font-size: 120%;+ align-items: center;+ color: var(--main-text-color);+ background-color: var(--main-background-color);+ display: flex;+ flex-direction: column;+ flex: 0 0 14.28%;+ max-width: 14.28%;+ padding: 0.4rem 0;+ font-size: 120%;}.calendar-dropdown-widget .calendar-date:hover {- color: var(--hover-item-text-color);- background-color: var(--hover-item-background-color);+ color: var(--hover-item-text-color);+ background-color: var(--hover-item-background-color);}.calendar-dropdown-widget .calendar-date-active {- background-color: var(--active-item-background-color);- color: var(--active-item-text-color);+ background-color: var(--active-item-background-color);+ color: var(--active-item-text-color);}.calendar-dropdown-widget .calendar-date-today {- font-weight: bold;+ font-weight: bold;}.calendar-dropdown-widget a {- text-decoration: none;+ text-decoration: none;}.calendar-dropdown-widget .calendar-date-exists {- text-decoration: underline !important;+ text-decoration: underline !important;}.calendar-dropdown-widget .calendar-date:not(.calendar-date-active) {- cursor: pointer;+ cursor: pointer;}diff --git a/src/public/stylesheets/print.css b/src/public/stylesheets/print.cssindex 655b367efd..cf3595d37d 100644--- a/src/public/stylesheets/print.css+++ b/src/public/stylesheets/print.css@@ -1,12 +1,11 @@-@media print-{+@media print {html body {/* https://github.com/zadam/trilium/issues/3202 */color: black;}- .no-print, .no-print *- {+ .no-print,+ .no-print * {display: none !important;}@@ -15,15 +14,15 @@}.table thead th,- .table td, .table th {+ .table td,+ .table th {/* Fix center vertical alignment of table cells */vertical-align: middle;}pre {box-shadow: unset !important;- border: .75pt solid gray !important;+ border: 0.75pt solid gray !important;border-radius: 2pt !important;}-}diff --git a/src/public/stylesheets/relation_map.css b/src/public/stylesheets/relation_map.cssindex c78767de4b..7213da78f0 100644--- a/src/public/stylesheets/relation_map.css+++ b/src/public/stylesheets/relation_map.css@@ -43,7 +43,9 @@font-weight: 600;}-.note-detail-relation-map .connection-label.jtk-hover, .jtk-source-hover, .jtk-target-hover {+.note-detail-relation-map .connection-label.jtk-hover,+.jtk-source-hover,+.jtk-target-hover {background-color: var(--more-accented-background-color);}@@ -76,7 +78,10 @@border: 2px solid orange;}-.note-detail-relation-map path, .note-detail-relation-map .jtk-endpoint { cursor:pointer; }+.note-detail-relation-map path,+.note-detail-relation-map .jtk-endpoint {+ cursor: pointer;+}.note-detail-relation-map .ui-contextmenu {z-index: 100;diff --git a/src/public/stylesheets/share.css b/src/public/stylesheets/share.cssindex 8fb245d783..213853dbe0 100644--- a/src/public/stylesheets/share.css+++ b/src/public/stylesheets/share.css@@ -1,5 +1,5 @@body {- font-family: 'Lucida Grande', 'Lucida Sans Unicode', arial, sans-serif;+ font-family: "Lucida Grande", "Lucida Sans Unicode", arial, sans-serif;line-height: 1.5;}@@ -173,32 +173,32 @@ iframe.pdf-view {border-radius: 2px;counter-reset: footnote-counter;margin: 1em 0;- padding: 10px+ padding: 10px;}.ck-content .footnote-item {counter-increment: footnote-counter;display: flex;list-style: none;- margin-left: .5em+ margin-left: 0.5em;}.ck-content .footnote-item:target .footnote-content {background: #eee;}-.ck-content .footnote-item>* {- vertical-align: text-top+.ck-content .footnote-item > * {+ vertical-align: text-top;}.ck-content .footnote-back-link {- margin-right: .1em;+ margin-right: 0.1em;position: relative;- top: -.2em+ top: -0.2em;}-.ck-content .footnotes .footnote-back-link>sup {- margin-right: 0+.ck-content .footnotes .footnote-back-link > sup {+ margin-right: 0;}.ck-content .footnote-item:before {@@ -206,7 +206,7 @@ iframe.pdf-view {display: inline-block;min-width: fit-content;position: relative;- right: .2em;+ right: 0.2em;text-align: right;}@@ -214,10 +214,10 @@ iframe.pdf-view {border-radius: 2px;display: inline-block;flex-grow: 1;- padding: 0 .3em;- width: 95%+ padding: 0 0.3em;+ width: 95%;}.ck-content .ck-content-widget.footnote-section .ck-content-widget__type-around__button_after {- display: none-}\ No newline at end of file+ display: none;+}diff --git a/src/public/stylesheets/style.css b/src/public/stylesheets/style.cssindex a57feaf911..f2f928ee8d 100644--- a/src/public/stylesheets/style.css+++ b/src/public/stylesheets/style.css@@ -12,7 +12,7 @@@font-face {font-family: JetBrainsLight;- src: url(../fonts/JetBrainsMono-Light.woff2) format('woff');+ src: url(../fonts/JetBrainsMono-Light.woff2) format("woff");}.table {@@ -65,7 +65,7 @@ body.mobile #root-widget {}body.desktop #root-widget.horizontal-layout {- padding-top: env(safe-area-inset-top);+ padding-top: env(safe-area-inset-top);background-color: var(--launcher-pane-background-color);}@@ -79,7 +79,9 @@ a {text-decoration: none;}-a, a:visited, a:hover {+a,+a:visited,+a:hover {color: var(--link-color);}@@ -106,7 +108,9 @@ textarea,}.form-select {- background: var(--input-background-color) url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='%23ffffff' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/></svg>") right .75rem center/15px 20px no-repeat;+ background: var(--input-background-color)+ url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='%23ffffff' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/></svg>")+ right 0.75rem center/15px 20px no-repeat;}/* Restore default apperance */@@ -149,7 +153,10 @@ input::placeholder,contain: size;}-code, kbd, pre, samp {+code,+kbd,+pre,+samp {font-family: var(--monospace-font-family) !important;}@@ -251,7 +258,8 @@ div.ui-tooltip {}/* Allow to use <kbd> elements inside the title to define shortcut hints. */-.ui-menu kbd, button kbd {+.ui-menu kbd,+button kbd {color: var(--muted-text-color);border: none;background-color: transparent;@@ -274,14 +282,15 @@ div.ui-tooltip {@keyframes dropdown-menu-opening {from {opacity: 0;- } to {+ }+ to {opacity: 1;}}-.dropdown-menu {+.dropdown-menu {color: var(--menu-text-color) !important;- font-size: inherit;+ font-size: inherit;background-color: var(--menu-background-color) !important;}@@ -291,7 +300,7 @@ body.desktop .dropdown-menu {animation: dropdown-menu-opening 100ms ease-in;}-@supports(animation-fill-mode: forwards) {+@supports (animation-fill-mode: forwards) {/* Delay the opening of submenus */body.desktop .dropdown-submenu .dropdown-menu {opacity: 0;@@ -305,7 +314,7 @@ body.desktop .dropdown-menu {}.dropend .dropdown-toggle::after {- margin-left: .5em;+ margin-left: 0.5em;color: var(--muted-text-color);}@@ -317,24 +326,27 @@ body.desktop .dropdown-menu {.dropdown-menu .disabled .disabled-tooltip {pointer-events: all;margin-left: 8px;- font-size: .5em;+ font-size: 0.5em;color: var(--disabled-tooltip-icon-color);cursor: help;- opacity: .75;+ opacity: 0.75;}.dropdown-menu .disabled .disabled-tooltip:hover {opacity: 1;}-.dropdown-menu a:hover:not(.disabled), .dropdown-item:hover:not(.disabled, .dropdown-item-container) {+.dropdown-menu a:hover:not(.disabled),+.dropdown-item:hover:not(.disabled, .dropdown-item-container) {color: var(--hover-item-text-color) !important;background-color: var(--hover-item-background-color) !important;border-color: var(--hover-item-border-color) !important;cursor: pointer;}-.dropdown-item-container, .dropdown-item-container:hover, .dropdown-item-container:active {+.dropdown-item-container,+.dropdown-item-container:hover,+.dropdown-item-container:active {background: transparent;cursor: default;}@@ -354,16 +366,19 @@ body.desktop .dropdown-menu {padding-bottom: 0;}-.dropdown-item, .dropdown-header {+.dropdown-item,+.dropdown-header {color: var(--menu-text-color) !important;border: 1px solid transparent !important;}-.dropdown-item.disabled, .dropdown-item.disabled kbd {+.dropdown-item.disabled,+.dropdown-item.disabled kbd {color: #aaa !important;}-.dropdown-item.active, .dropdown-item:focus {+.dropdown-item.active,+.dropdown-item:focus {color: var(--active-item-text-color) !important;background-color: var(--active-item-background-color) !important;border-color: var(--active-item-border-color) !important;@@ -389,7 +404,7 @@ body .CodeMirror {}.cm-matchhighlight {- background-color: #eeeeee+ background-color: #eeeeee;}.CodeMirror pre.CodeMirror-placeholder {@@ -420,7 +435,8 @@ body .CodeMirror {border-color: var(--hover-item-border-color);}-button.btn, button.btn-sm {+button.btn,+button.btn-sm {font-size: inherit;}@@ -434,7 +450,8 @@ button.btn, button.btn-sm {color: var(--primary-button-text-color);}-.btn:not(:disabled):not(.disabled):active, .btn:not(:disabled):not(.disabled).active {+.btn:not(:disabled):not(.disabled):active,+.btn:not(:disabled):not(.disabled).active {border-color: var(--primary-button-text-color);background-color: var(--active-item-background-color);color: var(--active-item-text-color);@@ -478,11 +495,14 @@ pre:not(.CodeMirror-line):not(.hljs) {cursor: pointer;}-.show-recent-notes-button, .input-clearer-button, .go-to-selected-note-button {+.show-recent-notes-button,+.input-clearer-button,+.go-to-selected-note-button {padding-top: 8px;}-.show-recent-notes-button, .full-text-search-button {+.show-recent-notes-button,+.full-text-search-button {cursor: pointer;font-size: 1.3em;padding-left: 5px;@@ -512,7 +532,8 @@ pre:not(.CodeMirror-line):not(.hljs) {padding-right: 3px;}-.go-to-selected-note-button.disabled, .go-to-selected-note-button.disabled:hover {+.go-to-selected-note-button.disabled,+.go-to-selected-note-button.disabled:hover {cursor: inherit;color: var(--button-disabled-text-color) !important;background-color: var(--button-disabled-background-color) !important;@@ -528,7 +549,8 @@ table.promoted-attributes-in-tooltip {margin: auto;}-table.promoted-attributes-in-tooltip td, table.promoted-attributes-in-tooltip th {+table.promoted-attributes-in-tooltip td,+table.promoted-attributes-in-tooltip th {padding: 10px;}@@ -551,66 +573,82 @@ table.promoted-attributes-in-tooltip td, table.promoted-attributes-in-tooltip thpointer-events: none;}-.bs-tooltip-bottom .tooltip-arrow::before { border-bottom-color: var(--main-border-color) !important; }-.bs-tooltip-top .tooltip-arrow::before { border-top-color: var(--main-border-color) !important; }-.bs-tooltip-left .tooltip-arrow::before { border-left-color: var(--main-border-color) !important; }-.bs-tooltip-right .tooltip-arrow::before { border-right-color: var(--main-border-color) !important; }+.bs-tooltip-bottom .tooltip-arrow::before {+ border-bottom-color: var(--main-border-color) !important;+}+.bs-tooltip-top .tooltip-arrow::before {+ border-top-color: var(--main-border-color) !important;+}+.bs-tooltip-left .tooltip-arrow::before {+ border-left-color: var(--main-border-color) !important;+}+.bs-tooltip-right .tooltip-arrow::before {+ border-right-color: var(--main-border-color) !important;+}-.bs-tooltip-bottom .tooltip-arrow::after { border-bottom-color: var(--tooltip-background-color) !important; }-.bs-tooltip-top .tooltip-arrow::after { border-top-color: var(--tooltip-background-color) !important; }-.bs-tooltip-left .tooltip-arrow::after { border-left-color: var(--tooltip-background-color) !important; }-.bs-tooltip-right .tooltip-arrow::after { border-right-color: var(--tooltip-background-color) !important; }+.bs-tooltip-bottom .tooltip-arrow::after {+ border-bottom-color: var(--tooltip-background-color) !important;+}+.bs-tooltip-top .tooltip-arrow::after {+ border-top-color: var(--tooltip-background-color) !important;+}+.bs-tooltip-left .tooltip-arrow::after {+ border-left-color: var(--tooltip-background-color) !important;+}+.bs-tooltip-right .tooltip-arrow::after {+ border-right-color: var(--tooltip-background-color) !important;+}-.bs-tooltip-auto[data-popper-placement^='left'] .tooltip-arrow::before,+.bs-tooltip-auto[data-popper-placement^="left"] .tooltip-arrow::before,.bs-tooltip-left .tooltip-arrow::before {left: -1px;border-width: 0.4rem 0 0.4rem 0.4rem;border-left-color: var(--main-border-color) !important;}-.bs-tooltip-auto[data-popper-placement^='bottom'] .tooltip-arrow::before,+.bs-tooltip-auto[data-popper-placement^="bottom"] .tooltip-arrow::before,.bs-tooltip-bottom .tooltip-arrow::before {bottom: -1px;border-width: 0 0.4rem 0.4rem;border-bottom-color: var(--main-border-color) !important;}-.bs-tooltip-auto[data-popper-placement^='right'] .tooltip-arrow::before,+.bs-tooltip-auto[data-popper-placement^="right"] .tooltip-arrow::before,.bs-tooltip-right .tooltip-arrow::before {right: -1px;border-width: 0.4rem 0.4rem 0.4rem 0;border-right-color: var(--main-border-color) !important;}-.bs-tooltip-auto[data-popper-placement^='top'] .tooltip-arrow::before,+.bs-tooltip-auto[data-popper-placement^="top"] .tooltip-arrow::before,.bs-tooltip-top .tooltip-arrow::before {top: -1px;border-width: 0.4rem 0.4rem 0;border-top-color: var(--main-border-color) !important;}-.bs-tooltip-auto[data-popper-placement^='left'] .tooltip-arrow::after,+.bs-tooltip-auto[data-popper-placement^="left"] .tooltip-arrow::after,.bs-tooltip-left .tooltip-arrow::after {left: -1px;border-width: 0.4rem 0 0.4rem 0.4rem;border-left-color: var(--tooltip-background-color) !important;}-.bs-tooltip-auto[data-popper-placement^='bottom'] .tooltip-arrow::after,+.bs-tooltip-auto[data-popper-placement^="bottom"] .tooltip-arrow::after,.bs-tooltip-bottom .tooltip-arrow::after {bottom: -1px;border-width: 0 0.4rem 0.4rem;border-bottom-color: var(--tooltip-background-color) !important;}-.bs-tooltip-auto[data-popper-placement^='right'] .tooltip-arrow::after,+.bs-tooltip-auto[data-popper-placement^="right"] .tooltip-arrow::after,.bs-tooltip-right .tooltip-arrow::after {right: -1px;border-width: 0.4rem 0.4rem 0.4rem 0;border-right-color: var(--tooltip-background-color) !important;}-.bs-tooltip-auto[data-popper-placement^='top'] .tooltip-arrow::after,+.bs-tooltip-auto[data-popper-placement^="top"] .tooltip-arrow::after,.bs-tooltip-top .tooltip-arrow::after {top: -1px;border-width: 0.4rem 0.4rem 0;@@ -688,7 +726,8 @@ table.promoted-attributes-in-tooltip td, table.promoted-attributes-in-tooltip thoverflow: auto;}-.algolia-autocomplete .aa-input, .algolia-autocomplete .aa-hint {+.algolia-autocomplete .aa-input,+.algolia-autocomplete .aa-hint {width: 100%;}@@ -784,7 +823,7 @@ div[data-notify="container"] {}.ck-editor__is-empty.ck-content.ck-editor__editable::before {- content: 'You can start writing note here ...';+ content: "You can start writing note here ...";position: absolute;display: block;@@ -819,28 +858,28 @@ div[data-notify="container"] {border-radius: 2px;counter-reset: footnote-counter;margin: 1em 0;- padding: 10px+ padding: 10px;}.ck-content .footnote-item {counter-increment: footnote-counter;display: flex;list-style: none;- margin-left: .5em+ margin-left: 0.5em;}-.ck-content .footnote-item>* {- vertical-align: text-top+.ck-content .footnote-item > * {+ vertical-align: text-top;}.ck-content .footnote-back-link {- margin-right: .1em;+ margin-right: 0.1em;position: relative;- top: -.2em+ top: -0.2em;}-.ck-content .footnotes .footnote-back-link>sup {- margin-right: 0+.ck-content .footnotes .footnote-back-link > sup {+ margin-right: 0;}.ck-content .footnote-item:before {@@ -848,7 +887,7 @@ div[data-notify="container"] {display: inline-block;min-width: fit-content;position: relative;- right: .2em;+ right: 0.2em;text-align: right;}@@ -856,15 +895,15 @@ div[data-notify="container"] {border-radius: 2px;display: inline-block;flex-grow: 1;- padding: 0 .3em;- width: 95%+ padding: 0 0.3em;+ width: 95%;}.ck-content .ck-content-widget.footnote-section .ck-content-widget__type-around__button_after {- display: none+ display: none;}-#options-dialog input[type=number] {+#options-dialog input[type="number"] {text-align: right;}@@ -879,9 +918,8 @@ div[data-notify="container"] {padding: 2px;}---a.external:not(.no-arrow):after, a[href^="http://"]:not(.no-arrow):after, a[href^="https://"]:not(.no-arrow):after {+a.external:not(.no-arrow):after, a[href^="http://"]:not(.no-arrow):after, a[href^="https://"]:not(.no-arrow):after+{font-size: smaller;content: "\2197";vertical-align: top;@@ -898,8 +936,6 @@ a.external:not(.no-arrow):after, a[href^="http://"]:not(.no-arrow):after, a[hrefdisplay: inline-block;}--.note-detail-empty {margin: 50px;}@@ -951,12 +987,11 @@ a.external:not(.no-arrow):after, a[href^="http://"]:not(.no-arrow):after, a[hrefvertical-align: baseline !important;}-.side-checkbox {display: flex;align-items: end;- padding-top: .375rem;- padding-bottom: .375rem;+ padding-top: 0.375rem;+ padding-bottom: 0.375rem;line-height: 1.5;}@@ -977,30 +1012,31 @@ a.external:not(.no-arrow):after, a[href^="http://"]:not(.no-arrow):after, a[hrefdisplay: flex; /* see https://github.com/zadam/trilium/issues/1590 */}-.include-note.ck-placeholder::before { /* remove placeholder in otherwise empty note */- content: '' !important;+.include-note.ck-placeholder::before {+ /* remove placeholder in otherwise empty note */+ content: "" !important;}/* Using data- attribute to support both CKEditor and readonly view */-.include-note[data-box-size=small] .include-note-content {+.include-note[data-box-size="small"] .include-note-content {max-height: 10em;overflow: auto;}-.include-note[data-box-size=small] .include-note-content.type-pdf {+.include-note[data-box-size="small"] .include-note-content.type-pdf {height: 10em; /* PDF is rendered in iframe and must be sized absolutely */}-.include-note[data-box-size=medium] .include-note-content {+.include-note[data-box-size="medium"] .include-note-content {max-height: 20em;overflow: auto;}-.include-note[data-box-size=medium] .include-note-content.type-pdf .rendered-content {+.include-note[data-box-size="medium"] .include-note-content.type-pdf .rendered-content {height: 20em; /* PDF is rendered in iframe and must be sized absolutely */}-.include-note[data-box-size=full] .include-note-content.type-pdf .rendered-content {+.include-note[data-box-size="full"] .include-note-content.type-pdf .rendered-content {height: 50em; /* PDF is rendered in iframe and it's not possible to put full height so at least a large height */}@@ -1013,7 +1049,8 @@ a.external:not(.no-arrow):after, a[href^="http://"]:not(.no-arrow):after, a[hrefwidth: auto;}-.alert-warning, .alert-info {+.alert-warning,+.alert-info {color: var(--main-text-color) !important;background-color: transparent !important;border-color: var(--main-border-color) !important;@@ -1077,7 +1114,8 @@ body.mobile .dropdown-submenu > .dropdown-menu {margin-top: 0 !important;}-#context-menu-container, #context-menu-container .dropdown-menu {+#context-menu-container,+#context-menu-container .dropdown-menu {padding: 3px 0 0;z-index: 2000;}@@ -1144,7 +1182,8 @@ body:not(.mobile) #launcher-pane.horizontal .dropdown-submenu > .dropdown-menu {border-bottom: 1px dotted;}-.hidden-int, .hidden-ext {+.hidden-int,+.hidden-ext {display: none !important;}@@ -1260,19 +1299,19 @@ body.mobile #launcher-pane .dropdown-menu.show {#mobile-sidebar-container {position: fixed;top: 0;- left: 0;- right: 0;- bottom: 0;+ left: 0;+ right: 0;+ bottom: 0;z-index: 1000;transition: background-color 250ms ease-in-out;visibility: hidden;background: rgba(0, 0, 0, 0.4);}-+#mobile-sidebar-container.show {- visibility: visible;+ visibility: visible;}-+#mobile-sidebar-wrapper {position: absolute;top: 0;@@ -1284,7 +1323,7 @@ body.mobile #launcher-pane .dropdown-menu.show {background: var(--main-background-color);z-index: 2000;}-+#mobile-sidebar-container.show #mobile-sidebar-wrapper {transform: translateX(0);}diff --git a/src/public/stylesheets/theme-dark.css b/src/public/stylesheets/theme-dark.cssindex a80a2df1d1..cfabe2f156 100644--- a/src/public/stylesheets/theme-dark.css+++ b/src/public/stylesheets/theme-dark.css@@ -17,11 +17,10 @@--main-text-color: #ccc;--main-border-color: #aaa;--dropdown-border-color: #555;- --dropdown-shadow-opacity: .4;+ --dropdown-shadow-opacity: 0.4;--dropdown-item-icon-destructive-color: #de6e5b;--disabled-tooltip-icon-color: #7fd2ef;---accented-background-color: #555;--more-accented-background-color: #777;@@ -56,10 +55,10 @@--modal-backdrop-color: #444;--left-pane-background-color: #1f1f1f;- --left-pane-text-color: #AAAAAA;+ --left-pane-text-color: #aaaaaa;--launcher-pane-background-color: #1f1f1f;- --launcher-pane-text-color: #AAAAAA;+ --launcher-pane-text-color: #aaaaaa;--active-tab-background-color: #666;--active-tab-hover-background-color: #737373;diff --git a/src/public/stylesheets/theme-light.css b/src/public/stylesheets/theme-light.cssindex 3bf9810bef..70e81885f8 100644--- a/src/public/stylesheets/theme-light.css+++ b/src/public/stylesheets/theme-light.css@@ -21,7 +21,7 @@ html {--main-text-color: black;--main-border-color: #ccc;--dropdown-border-color: #ccc;- --dropdown-shadow-opacity: .2;+ --dropdown-shadow-opacity: 0.2;--dropdown-item-icon-destructive-color: #ec5138;--disabled-tooltip-icon-color: #004382;@@ -58,10 +58,10 @@ html {--modal-background-color: white;--modal-backdrop-color: black;- --left-pane-background-color: #F3F3F3;+ --left-pane-background-color: #f3f3f3;--left-pane-text-color: #333;- --launcher-pane-background-color: #F3F3F3;+ --launcher-pane-background-color: #f3f3f3;--launcher-pane-text-color: #333;--active-tab-background-color: #ddd;diff --git a/src/public/stylesheets/theme-next-dark.css b/src/public/stylesheets/theme-next-dark.cssindex 872af89167..dd7f1ee77b 100644--- a/src/public/stylesheets/theme-next-dark.css+++ b/src/public/stylesheets/theme-next-dark.css@@ -13,11 +13,10 @@--main-border-color: #454545;--subtle-border-color: #313131;--dropdown-border-color: #292929;- --dropdown-shadow-opacity: .6;+ --dropdown-shadow-opacity: 0.6;--dropdown-item-icon-destructive-color: #de6e5b;--disabled-tooltip-icon-color: #7fd2ef;---accented-background-color: #555;--button-background-color: transparent;@@ -46,19 +45,18 @@--new-tab-button-background: #fff0;--new-tab-button-color: #ffffff96;- --new-tab-button-shadow: 2px 2px 4px rgba(0, 0, 0, .4);+ --new-tab-button-shadow: 2px 2px 4px rgba(0, 0, 0, 0.4);--new-tab-button-hover-background: #fff3;--new-tab-button-hover-color: white;--menu-text-color: #e3e3e3;--menu-background-color: #222222d9;--menu-item-icon-color: #8c8c8c;- --menu-item-disabled-opacity: .5;+ --menu-item-disabled-opacity: 0.5;--menu-item-keyboard-shortcut-color: #ffffff8f;--menu-item-arrow-color: #ffffffa3;--menu-item-delimiter-color: #ffffff1c;---modal-background-color: #333;--modal-backdrop-color: #444;@@ -71,16 +69,16 @@--left-pane-collapsed-border-color: #0009;--left-pane-background-color: #1f1f1f;- --left-pane-text-color: #AAAAAA;+ --left-pane-text-color: #aaaaaa;--left-pane-item-hover-background: #ffffff0d;--left-pane-item-selected-background: #ffffff25;--left-pane-item-selected-color: #dfdfdf;- --left-pane-item-selected-shadow: 1px 1px 2px rgba(0, 0, 0, .6);+ --left-pane-item-selected-shadow: 1px 1px 2px rgba(0, 0, 0, 0.6);--left-pane-item-action-button-background: #ffffff73;--left-pane-item-action-button-color: black;--left-pane-item-action-button-hover-background: #ffffffad;- --left-pane-item-action-button-hover-shadow: 2px 2px 3px rgba(0, 0, 0, .15);- --left-pane-item-selected-action-button-hover-shadow: 2px 2px 10px rgba(0, 0, 0, .25);+ --left-pane-item-action-button-hover-shadow: 2px 2px 3px rgba(0, 0, 0, 0.15);+ --left-pane-item-selected-action-button-hover-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25);--launcher-pane-background-color: #1a1a1a;--launcher-pane-horizontal-background-color: #282828;@@ -88,7 +86,7 @@--launcher-pane-text-color: #909090;--launcher-pane-button-hover-color: #ffffff;--launcher-pane-button-hover-background: #ffffff1c;- --launcher-pane-button-hover-shadow: 4px 4px 4px rgba(0, 0, 0, .2);+ --launcher-pane-button-hover-shadow: 4px 4px 4px rgba(0, 0, 0, 0.2);--protected-session-active-icon-color: #8edd8e;--sync-status-error-pulse-color: #f47871;@@ -104,8 +102,8 @@--active-tab-background-color: #ffffff1c;--active-tab-hover-background-color: var(--active-tab-background-color);--active-tab-text-color: #ffffffcd;- --active-tab-shadow: 3px 3px 6px rgba(0, 0, 0, .2), -1px -1px 3px rgba(0, 0, 0, .4);- --active-tab-dragging-shadow: var(--active-tab-shadow), 0 0 20px rgba(0, 0, 0, .4);+ --active-tab-shadow: 3px 3px 6px rgba(0, 0, 0, 0.2), -1px -1px 3px rgba(0, 0, 0, 0.4);+ --active-tab-dragging-shadow: var(--active-tab-shadow), 0 0 20px rgba(0, 0, 0, 0.4);--inactive-tab-background-color: transparent;--inactive-tab-hover-background-color: #ffffff0f;@@ -146,11 +144,11 @@--help-background-color: var(--menu-background-color);--help-card-background: var(--card-background-color);- --help-card-shadow: 2px 2px 2px rgba(0, 0, 0, .2);+ --help-card-shadow: 2px 2px 2px rgba(0, 0, 0, 0.2);--help-card-heading-color: #959595;--help-kbd-shortcut-color: white;--help-kbd-shortcut-background: #676767;- --help-kbd-shortcut-shadow: 1px 1px 2px rgba(0, 0, 0, .7);+ --help-kbd-shortcut-shadow: 1px 1px 2px rgba(0, 0, 0, 0.7);--help-code-color: inherit;--help-code-background: #565656;}diff --git a/src/public/stylesheets/theme-next-light.css b/src/public/stylesheets/theme-next-light.cssindex 108b797ed1..0bed73460d 100644--- a/src/public/stylesheets/theme-next-light.css+++ b/src/public/stylesheets/theme-next-light.css@@ -13,7 +13,7 @@--main-border-color: #dbdbdb;--subtle-border-color: rgba(0, 0, 0, 0.1);--dropdown-border-color: #ccc;- --dropdown-shadow-opacity: .2;+ --dropdown-shadow-opacity: 0.2;--dropdown-item-icon-destructive-color: #ec5138;--disabled-tooltip-icon-color: #004382;@@ -46,7 +46,7 @@--menu-text-color: #272727;--menu-background-color: #ffffffd9;--menu-item-icon-color: #727272;- --menu-item-disabled-opacity: .5;+ --menu-item-disabled-opacity: 0.5;--menu-item-keyboard-shortcut-color: #666666a8;--menu-item-arrow-color: #00000080;--menu-item-delimiter-color: #00000030;@@ -67,12 +67,12 @@--left-pane-item-hover-background: #eaeaea;--left-pane-item-selected-background: white;--left-pane-item-selected-color: black;- --left-pane-item-selected-shadow: 1px 1px 2px rgba(0, 0, 0, .2);+ --left-pane-item-selected-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);--left-pane-item-action-button-background: #d7d7d7;--left-pane-item-action-button-color: inherit;--left-pane-item-action-button-hover-background: white;- --left-pane-item-action-button-hover-shadow: 2px 2px 3px rgba(0, 0, 0, .15);- --left-pane-item-selected-action-button-hover-shadow: 2px 2px 10px rgba(0, 0, 0, .25);+ --left-pane-item-action-button-hover-shadow: 2px 2px 3px rgba(0, 0, 0, 0.15);+ --left-pane-item-selected-action-button-hover-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25);--launcher-pane-background-color: #e8e8e8;--launcher-pane-horizontal-background-color: #fafafa;@@ -80,7 +80,7 @@--launcher-pane-text-color: #000000bd;--launcher-pane-button-hover-color: black;--launcher-pane-button-hover-background: white;- --launcher-pane-button-hover-shadow: 4px 4px 4px rgba(0, 0, 0, .075);+ --launcher-pane-button-hover-shadow: 4px 4px 4px rgba(0, 0, 0, 0.075);--protected-session-active-icon-color: #16b516;--sync-status-error-pulse-color: #ff5528;@@ -96,8 +96,8 @@--active-tab-background-color: white;--active-tab-hover-background-color: var(--active-tab-background-color);--active-tab-text-color: black;- --active-tab-shadow: 3px 3px 6px rgba(0, 0, 0, .1), -1px -1px 3px rgba(0, 0, 0, .05);- --active-tab-dragging-shadow: var(--active-tab-shadow), 0 0 20px rgba(0, 0, 0, .1);+ --active-tab-shadow: 3px 3px 6px rgba(0, 0, 0, 0.1), -1px -1px 3px rgba(0, 0, 0, 0.05);+ --active-tab-dragging-shadow: var(--active-tab-shadow), 0 0 20px rgba(0, 0, 0, 0.1);--inactive-tab-background-color: transparent;--inactive-tab-hover-background-color: #00000016;@@ -105,7 +105,7 @@--new-tab-button-background: #d8d8d8;--new-tab-button-color: #3a3a3a;- --new-tab-button-shadow: 2px 2px 4px rgba(0, 0, 0, .2);+ --new-tab-button-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);--new-tab-button-hover-background: white;--new-tab-button-hover-color: black;@@ -141,15 +141,15 @@--tooltip-background-color: rgba(255, 255, 255, 0.85);--tooltip-foreground-color: #000000ba;- --tooltip-shadow-color: rgba(0, 0, 0, .15);+ --tooltip-shadow-color: rgba(0, 0, 0, 0.15);--help-background-color: #fffc;--help-card-background: var(--card-background-color);- --help-card-shadow: 2px 2px 2px rgba(0, 0, 0, .10);+ --help-card-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1);--help-card-heading-color: #797979;--help-kbd-shortcut-color: #3f3f3f;--help-kbd-shortcut-background: white;- --help-kbd-shortcut-shadow: 1px 1px 2px rgba(0, 0, 0, .3);+ --help-kbd-shortcut-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);--help-code-color: black;--help-code-background: #d7d5d5;- }+}diff --git a/src/public/stylesheets/theme-next/base.css b/src/public/stylesheets/theme-next/base.cssindex b9aa3c6191..8b6d0d9db2 100644--- a/src/public/stylesheets/theme-next/base.css+++ b/src/public/stylesheets/theme-next/base.css@@ -25,7 +25,7 @@--launcher-pane-size: 58px;--launcher-pane-horizontal-size: 54px;- --launcher-pane-horizontal-icon-size: 20px;+ --launcher-pane-horizontal-icon-size: 20px;--launcher-pane-button-margin: 6px;--launcher-pane-button-gap: 3px;@@ -43,7 +43,7 @@--center-pane-border-radius: 10px;--menu-padding-size: 8px;- --menu-item-icon-vert-offset: 0;+ --menu-item-icon-vert-offset: 0;--more-accented-background-color: var(--card-background-hover-color);@@ -52,11 +52,11 @@--timeline-item-top-padding: 4px;--timeline-item-bottom-padding: 8px;--timeline-bullet-size: 10px;- --timeline-bullet-vertical-pos: .75em;+ --timeline-bullet-vertical-pos: 0.75em;--timeline-connector-size: 4px;--help-backdrop-blur: 10px;/* Theme capabilities */--tab-note-icons: true;-}\ No newline at end of file+}diff --git a/src/public/stylesheets/theme-next/notes/text.css b/src/public/stylesheets/theme-next/notes/text.cssindex eee5a07339..baaf207c92 100644--- a/src/public/stylesheets/theme-next/notes/text.css+++ b/src/public/stylesheets/theme-next/notes/text.css@@ -6,14 +6,14 @@* Code Blocks*/- .attachment-content-wrapper pre,- .ck-content pre,- .ck-mermaid__editing-view {+.attachment-content-wrapper pre,+.ck-content pre,+.ck-mermaid__editing-view {border: 0;border-radius: 6px;box-shadow: var(--code-block-box-shadow);padding: 0 !important;- margin-top: 2px !important;+ margin-top: 2px !important;}.ck-content pre {@@ -26,10 +26,10 @@ html .note-detail-editable-text :not(figure, .include-note, hr):first-child {}.ck.ck-editor__editable pre[data-language]::after {- --ck-color-code-block-label-background: rgba(128, 128, 128, .5);+ --ck-color-code-block-label-background: rgba(128, 128, 128, 0.5);border-radius: 0 0 5px 5px;padding: 0px 10px;- letter-spacing: .5px;+ letter-spacing: 0.5px;font-weight: bold;}@@ -51,7 +51,8 @@ html .note-detail-editable-text :not(figure, .include-note, hr):first-child {background: gray !important;}-.ck-content pre code::-webkit-scrollbar-track, ::-webkit-scrollbar-thumb {+.ck-content pre code::-webkit-scrollbar-track,+::-webkit-scrollbar-thumb {cursor: default;}@@ -84,7 +85,7 @@ html .note-detail-editable-text :not(figure, .include-note, hr):first-child {.ck-content blockquote:after {content: "”";- right: 0.35em;+ right: 0.35em;}.ck-content h2,@@ -121,4 +122,4 @@ html .note-detail-editable-text :not(figure, .include-note, hr):first-child {.ck-content .footnote-section {border: 0 !important;border-top: 1px solid var(--main-border-color) !important;-}\ No newline at end of file+}diff --git a/src/public/stylesheets/theme-next/settings.css b/src/public/stylesheets/theme-next/settings.cssindex ed1d021fcf..e2f1b7467e 100644--- a/src/public/stylesheets/theme-next/settings.css+++ b/src/public/stylesheets/theme-next/settings.css@@ -1,13 +1,13 @@/** Settings*/- :root {+:root {--options-card-padding: 17px;--options-title-font-size: 1rem;--options-title-offset: 13px;}-.options-section {+.options-section {border-radius: 12px;border: 1px solid var(--card-border-color) !important;box-shadow: var(--card-box-shadow);@@ -70,4 +70,4 @@margin: 0;padding: 0;margin-bottom: 1em;-}\ No newline at end of file+}diff --git a/src/public/stylesheets/theme-next/shell.css b/src/public/stylesheets/theme-next/shell.cssindex 9d41b0a176..3abfd4c538 100644--- a/src/public/stylesheets/theme-next/shell.css+++ b/src/public/stylesheets/theme-next/shell.css@@ -2,10 +2,11 @@* USER INTERFACE*/- @keyframes fade-in {+@keyframes fade-in {from {opacity: 0;- } to {+ }+ to {opacity: 1;}}@@ -46,7 +47,7 @@ body.background-effects.platform-win32 {--tab-background-color: transparent;--new-tab-button-background: transparent;--active-tab-background-color: var(--launcher-pane-background-color);- --background-material: tabbed;+ --background-material: tabbed;}@media (prefers-color-scheme: dark) {@@ -66,7 +67,7 @@ body.background-effects.platform-win32.layout-vertical {body.background-effects.platform-win32,body.background-effects.platform-win32 #root-widget,body.background-effects.platform-win32 #launcher-pane .launcher-button {- background: transparent !important;+ background: transparent !important;}body.background-effects.platform-win32.layout-horizontal #horizontal-main-container,@@ -111,8 +112,8 @@ body.layout-horizontal > .horizontal {}#launcher-pane.horizontal {- height: var(--launcher-pane-size) !important;- align-items: center;+ height: var(--launcher-pane-size) !important;+ align-items: center;}@media (max-width: 991px) {@@ -139,12 +140,13 @@ body.layout-horizontal > .horizontal {margin: var(--launcher-pane-button-gap) var(--launcher-pane-button-margin);}-#launcher-pane .launcher-button {+#launcher-pane .launcher-button {padding: 0 !important;border-radius: 8px;- transition: background-color 300ms ease-out,- color 300ms ease-out,- box-shadow 300ms ease-out;+ transition:+ background-color 300ms ease-out,+ color 300ms ease-out,+ box-shadow 300ms ease-out;cursor: default;}@@ -165,9 +167,10 @@ body.layout-horizontal > .horizontal {background: var(--launcher-pane-button-hover-background) !important;color: var(--launcher-pane-button-hover-color);box-shadow: var(--launcher-pane-button-hover-shadow);- transition: background-color 100ms ease-in,- color 80ms ease-in,- box-shadow 100ms ease-in;+ transition:+ background-color 100ms ease-in,+ color 80ms ease-in,+ box-shadow 100ms ease-in;}#launcher-pane div.launcher-button {@@ -204,8 +207,9 @@ body.layout-horizontal > .horizontal {@keyframes sync-status-pulse {from {- color: currentColor- } to {+ color: currentColor;+ }+ to {color: var(--pulse-color);}}@@ -229,15 +233,16 @@ body.layout-horizontal > .horizontal {.tooltip .tooltip-inner {padding: 6px 10px !important;- box-shadow: -1px -1px 2px var(--tooltip-shadow-color),- 2px 2px 8px var(--tooltip-shadow-color) !important;+ box-shadow:+ -1px -1px 2px var(--tooltip-shadow-color),+ 2px 2px 8px var(--tooltip-shadow-color) !important;border: unset !important;border-radius: 6px;backdrop-filter: blur(5px);color: var(--tooltip-foreground-color) !important;}- /*+/** Search Box*/@@ -311,7 +316,7 @@ div.quick-search .search-button {}div.quick-search .search-button:active {- transform: scale(.85);+ transform: scale(0.85);}div.quick-search:focus-within:has(input:not(:placeholder-shown)) .search-button {@@ -322,7 +327,7 @@ div.quick-search:focus-within:has(input:not(:placeholder-shown)) .search-button}html body .quick-search:focus-within .search-button:hover,-div.quick-search .search-button.show {+div.quick-search .search-button.show {/* Hover state */background: var(--left-pane-item-action-button-hover-background) !important;color: var(--left-pane-item-action-button-color) !important;@@ -338,7 +343,6 @@ div.quick-search .search-button.show {padding: 8px 12px !important;}-/* Note icon */.quick-search .dropdown-menu .dropdown-item > .bx {position: relative;@@ -355,12 +359,11 @@ div.quick-search .search-button.show {text-decoration: underline;}-/* Note path */.quick-search .dropdown-menu small {display: block;- opacity: .5;- font-size: .75em;+ opacity: 0.5;+ font-size: 0.75em;overflow: hidden;}@@ -405,7 +408,8 @@ div.quick-search .search-button.show {@keyframes left-pane-item-select {from {opacity: 0;- } to {+ }+ to {opacity: 1;}}@@ -435,7 +439,7 @@ div.quick-search .search-button.show {right: 0;font-size: 14px;content: "\eb4a";- font-family: "boxicons";+ font-family: "boxicons";transform: translateX(25%);background: var(--left-pane-background-color);border-radius: 50%;@@ -460,7 +464,7 @@ body.mobile .fancytree-node > span {}#left-pane .fancytree-expander {- opacity: .65;+ opacity: 0.65;transition: opacity 150ms ease-in;}@@ -474,7 +478,7 @@ body.mobile .fancytree-node > span {}#left-pane span .fancytree-title {- margin-top: -5px;+ margin-top: -5px;}#left-pane span.fancytree-active .fancytree-title {@@ -486,7 +490,7 @@ body.mobile .fancytree-node > span {}#left-pane span.fancytree-node.shared .fancytree-title::after {- opacity: .5;+ opacity: 0.5;}#left-pane .tree-item-button {@@ -495,15 +499,17 @@ body.mobile .fancytree-node > span {border-radius: 50%;background: var(--left-pane-item-action-button-background);color: var(--left-pane-item-action-button-color);- transition: background-color 200ms ease-out,- box-shadow 200ms ease-out;+ transition:+ background-color 200ms ease-out,+ box-shadow 200ms ease-out;}#left-pane .tree-item-button:hover {background: var(--left-pane-item-action-button-hover-background);box-shadow: var(--left-pane-item-action-button-hover-shadow);- transition: background-color 100ms ease-in,- box-shadow 100ms ease-in;+ transition:+ background-color 100ms ease-in,+ box-shadow 100ms ease-in;}#left-pane span.fancytree-node.fancytree-active .tree-item-button:hover {@@ -527,9 +533,10 @@ body.mobile .fancytree-node > span {padding: var(--tree-actions-toolbar-padding-size);padding-right: var(--tree-actions-toolbar-collapsed-width);background: transparent;- transition: max-width 400ms ease-out,- background-color 400ms ease-out,- border-color 400ms ease-out;+ transition:+ max-width 400ms ease-out,+ background-color 400ms ease-out,+ border-color 400ms ease-out;}/* Toolbar container (expanded state) */@@ -605,7 +612,7 @@ body.mobile .fancytree-node > span {}#left-pane .tree-settings-popup h4 {- margin-bottom: .75em;+ margin-bottom: 0.75em;font-size: 1.5em;line-height: 1;}@@ -654,7 +661,7 @@ body.layout-horizontal .tab-row-container .note-tab[active] {overflow: visible !important;}-body.layout-horizontal .tab-row-container .note-tab[active]:before {+body.layout-horizontal .tab-row-container .note-tab[active]:before {content: "";position: absolute;bottom: 0;@@ -665,7 +672,7 @@ body.layout-horizontal .tab-row-container .note-tab[active]:before {border-bottom: 1px solid var(--launcher-pane-horizontal-border-color);}-body.layout-horizontal .tab-row-container .note-tab[active]:after {+body.layout-horizontal .tab-row-container .note-tab[active]:after {content: "";position: absolute;bottom: 0;@@ -684,11 +691,11 @@ body.layout-vertical.electron.platform-darwin .tab-row-container {.tab-row-widget-container {margin-top: calc((var(--tab-bar-height) - var(--tab-height)) / 2);- height: var(--tab-height) !important;+ height: var(--tab-height) !important;}body.layout-horizontal .tab-row-container {- padding-top: calc((var(--tab-bar-height) - var(--tab-height)));+ padding-top: calc((var(--tab-bar-height) - var(--tab-height)));}body.layout-horizontal .tab-row-widget-container {@@ -714,8 +721,9 @@ body.desktop #root-widget.horizontal-layout {.tab-row-widget .note-tab .note-tab-wrapper {height: var(--tab-height) !important;- transition: background 75ms ease-in,- box-shadow 75ms ease-in;+ transition:+ background 75ms ease-in,+ box-shadow 75ms ease-in;}.tab-row-widget .note-tab .note-tab-wrapper:hover {@@ -728,7 +736,7 @@ body.desktop #root-widget.horizontal-layout {body.layout-horizontal .tab-row-widget .note-tab .note-tab-wrapper {border-bottom-left-radius: 0;- border-bottom-right-radius: 0;+ border-bottom-right-radius: 0;}.note-tab .note-tab-wrapper {@@ -754,15 +762,16 @@ body.layout-horizontal .tab-row-widget .note-tab .note-tab-wrapper {}.tab-row-widget-is-sorting .note-tab[active] .note-tab-wrapper {- transform: scale(.85);+ transform: scale(0.85);box-shadow: var(--active-tab-dragging-shadow) !important;}.tab-row-widget .note-tab[active] .note-tab-wrapper {box-shadow: var(--active-tab-shadow);font-weight: unset !important;- transition: background 150ms ease-out,- box-shadow 300ms ease-out;+ transition:+ background 150ms ease-out,+ box-shadow 300ms ease-out;}.tab-row-widget-is-sorting .note-tab-drag-handle {@@ -773,9 +782,9 @@ body.layout-horizontal .tab-row-widget .note-tab .note-tab-wrapper {display: flex;justify-content: center;align-items: center;- transition: background-color 75ms ease-out,- color 75ms ease-out;-+ transition:+ background-color 75ms ease-out,+ color 75ms ease-out;}.tab-row-widget .note-tab-close:hover {@@ -804,17 +813,19 @@ body.layout-horizontal .tab-row-widget .note-tab .note-tab-wrapper {height: var(--new-tab-button-size);background: var(--new-tab-button-background);border-radius: 50%;- transition: background-color 200ms ease-out,- box-shadow 200ms ease-out,- transform 300ms ease-in;+ transition:+ background-color 200ms ease-out,+ box-shadow 200ms ease-out,+ transform 300ms ease-in;will-change: transform;}.tab-row-widget .note-new-tab:hover::before {background: var(--new-tab-button-hover-background);box-shadow: var(--new-tab-button-shadow);- transition: background-color 100ms ease-in,- box-shadow 100ms ease-in;+ transition:+ background-color 100ms ease-in,+ box-shadow 100ms ease-in;}.tab-row-widget .note-new-tab::after {@@ -829,21 +840,22 @@ body.layout-horizontal .tab-row-widget .note-tab .note-tab-wrapper {align-items: center;justify-content: center;font-family: boxicons;- font-size: calc(var(--new-tab-button-size) * .75);+ font-size: calc(var(--new-tab-button-size) * 0.75);color: var(--new-tab-button-color);- transition: color 300ms ease-out,- transform 300ms ease-in;+ transition:+ color 300ms ease-out,+ transform 300ms ease-in;will-change: transform;}.tab-row-widget .note-new-tab:hover::after {color: var(--new-tab-button-hover-color);- transition: color 100ms ease-in,+ transition: color 100ms ease-in;}.tab-row-widget .note-new-tab:active:before,.tab-row-widget .note-new-tab:active:after {- transform: scale(.85);+ transform: scale(0.85);transition: transform 75ms ease-out;}@@ -856,8 +868,8 @@ body.layout-horizontal .tab-row-widget .note-tab .note-tab-wrapper {*/#center-pane {- padding-top: 2px;- background: var(--main-background-color);+ padding-top: 2px;+ background: var(--main-background-color);}.vertical-layout #center-pane {@@ -892,8 +904,9 @@ body.mobile .note-title {padding: 2px 8px;border-radius: 4px;text-align: unset;- transition: background-color 150ms ease-in,- color 150ms ease-in;+ transition:+ background-color 150ms ease-in,+ color 150ms ease-in;}#right-pane .highlights-list li {@@ -911,8 +924,7 @@ body.mobile .note-title {background: var(--right-pane-item-hover-background);color: var(--right-pane-item-hover-color);font-weight: normal;- transition: background-color 300ms ease-out- color 300ms ease-out;+ transition: background-color 300ms ease-out color 300ms ease-out;}#right-pane .toc li:active,@@ -928,7 +940,7 @@ body.mobile .note-title {.dropdown-menu {border-radius: var(--dropdown-border-radius);padding: var(--menu-padding-size) !important;- font-size: .90rem !important;+ font-size: 0.9rem !important;}body.mobile .dropdown-menu {@@ -1074,8 +1086,8 @@ body.mobile .dropdown-menu .dropdown-item.submenu-open .dropdown-toggle::after {.calendar-dropdown-widget .calendar-header input[type="number"]::-webkit-outer-spin-button,.calendar-dropdown-widget .calendar-header input[type="number"]::-webkit-inner-spin-button {- -webkit-appearance: none;- margin: 0;+ -webkit-appearance: none;+ margin: 0;}.calendar-dropdown-widget .calendar-header input,@@ -1093,13 +1105,13 @@ body.mobile .dropdown-menu .dropdown-item.submenu-open .dropdown-toggle::after {}.calendar-dropdown-widget .calendar-week span {- font-size: .85em;+ font-size: 0.85em;font-weight: 500;color: var(--calendar-weekday-labels-color);}.calendar-dropdown-widget .calendar-body {- font-size: .9em;+ font-size: 0.9em;}.calendar-dropdown-widget .calendar-body a {@@ -1142,25 +1154,24 @@ body .calendar-dropdown-widget .calendar-body a:hover {.note-tooltip-content {padding: 8px;- }+}.note-tooltip-content .note-title-with-path {display: flex;flex-direction: column-reverse;border-bottom: 2px solid currentColor;padding-bottom: 6px;-}.note-tooltip-content .note-path {display: block;color: var(--muted-text-color);- font-size: .75em;+ font-size: 0.75em;}.note-tooltip-content .note-tooltip-attributes {margin-top: -4px;- font-size: .75em;+ font-size: 0.75em;}.note-tooltip-content .rendered-content {@@ -1212,7 +1223,7 @@ body .calendar-dropdown-widget .calendar-body a:hover {.jump-to-note-dialog .input-group:focus-within {border-color: var(--quick-search-focus-border);background: var(--quick-search-focus-background);- color: var(--quick-search-focus-color)+ color: var(--quick-search-focus-color);}/* Search box input */@@ -1232,7 +1243,7 @@ body .calendar-dropdown-widget .calendar-body a:hover {}.jump-to-note-dialog .input-group button:last-child {- padding-right: .75em;+ padding-right: 0.75em;}.jump-to-note-dialog .input-clearer-button {@@ -1253,7 +1264,7 @@ body .calendar-dropdown-widget .calendar-body a:hover {}/* Selected list item */-.jump-to-note-dialog .aa-suggestions div.aa-cursor {+.jump-to-note-dialog .aa-suggestions div.aa-cursor {background: var(--hover-item-background-color);color: var(--hover-item-text-color);}@@ -1306,7 +1317,6 @@ body .calendar-dropdown-widget .calendar-body a:hover {content: "" !important;}-.recent-changes-content ul li:not(.deleted-note):hover {border-radius: 8px;background: var(--hover-item-background-color);@@ -1315,7 +1325,7 @@ body .calendar-dropdown-widget .calendar-body a:hover {.recent-changes-content ul li .note-path {color: var(--muted-text-color);- font-size: .75em;+ font-size: 0.75em;}/* Item time */@@ -1346,12 +1356,11 @@ body .calendar-dropdown-widget .calendar-body a:hover {text-decoration: line-through;}-/* Item path */.recent-changes-content ul li > span:nth-child(2) small {display: block;line-height: 1;- opacity: .75;+ opacity: 0.75;}/* Timeline connector */@@ -1383,7 +1392,7 @@ body .calendar-dropdown-widget .calendar-body a:hover {}/* The last item of the timeline */-.recent-changes-content > div:last-child li:last-child {+.recent-changes-content > div:last-child li:last-child {--connector-bottom: 50%;}@@ -1408,7 +1417,7 @@ body .calendar-dropdown-widget .calendar-body a:hover {/** Note list*/- .note-list .note-book-card {+.note-list .note-book-card {--note-list-horizontal-padding: 22px;--note-list-vertical-padding: 15px;background-color: var(--card-background-color);@@ -1444,11 +1453,11 @@ body .calendar-dropdown-widget .calendar-body a:hover {}.note-list-wrapper .note-book-card .note-book-header .note-icon {- font-size: 17px;+ font-size: 17px;vertical-align: text-bottom;}-.note-list-wrapper .note-book-card .note-book-header .note-book-title {+.note-list-wrapper .note-book-card .note-book-header .note-book-title {font-size: 1em;color: var(--active-item-text-color);vertical-align: middle;@@ -1484,7 +1493,7 @@ body .calendar-dropdown-widget .calendar-body a:hover {.note-list-wrapper .note-book-card .note-book-content h5,.note-list-wrapper .note-book-card .note-book-content h6 {font-size: 1rem;- color: var(--active-item-text-color);+ color: var(--active-item-text-color);}.note-list-wrapper .note-book-card .note-book-content p:last-child {@@ -1544,9 +1553,9 @@ body .calendar-dropdown-widget .calendar-body a:hover {/* Replace the path delimiters with arrows */display: inline-block;content: "\ed3b";- padding: 0 .25em;+ padding: 0 0.25em;font-family: boxicons;- opacity: .75;+ opacity: 0.75;transform: translateY(4%);}@@ -1557,7 +1566,7 @@ body .calendar-dropdown-widget .calendar-body a:hover {}.search-result-widget-content .note-path {- opacity: .75;+ opacity: 0.75;font-weight: normal;}@@ -1601,7 +1610,7 @@ body .calendar-dropdown-widget .calendar-body a:hover {.help-dialog .card-body h6 {font-size: 15px;- padding-bottom: .5em;+ padding-bottom: 0.5em;}/* Help card item */@@ -1611,7 +1620,7 @@ body .calendar-dropdown-widget .calendar-body a:hover {}.help-dialog .help-cards li + li {- margin-top: .4em;+ margin-top: 0.4em;}/* Keyboard shortcut */@@ -1624,7 +1633,7 @@ body .calendar-dropdown-widget .calendar-body a:hover {background: var(--help-kbd-shortcut-background);color: var(--help-kbd-shortcut-color);font-weight: 500;- letter-spacing: .5pt;+ letter-spacing: 0.5pt;}.help-dialog .help-cards kbd:first-child {@@ -1637,4 +1646,4 @@ body .calendar-dropdown-widget .calendar-body a:hover {background: var(--help-code-background);padding: 0 8px;color: var(--help-code-color);-}\ No newline at end of file+}diff --git a/src/public/stylesheets/tree.css b/src/public/stylesheets/tree.cssindex 7e8f035612..b6bcff2eee 100644--- a/src/public/stylesheets/tree.css+++ b/src/public/stylesheets/tree.css@@ -51,7 +51,7 @@ span.fancytree-node.fancytree-hide {}.fancytree-node:not(.fancytree-loading) .fancytree-expander:before {- font-family: 'boxicons' !important;+ font-family: "boxicons" !important;content: "\ea50"; /* lookup code for "chevron-right" in boxicons.css */speak: none;font-size: x-large;@@ -104,15 +104,23 @@ ul.fancytree-container li {}.fancytree-node.fancytree-expanded .fancytree-expander:before {- font-family: 'boxicons' !important;+ font-family: "boxicons" !important;content: "\ea4a"; /* lookup code for "chevron-down" in boxicons.css */}/** some common text styling for cssClass label */-span.fancytree-node.underline .fancytree-title { text-decoration: underline; }-span.fancytree-node.dotted .fancytree-title { text-decoration: dotted; }-span.fancytree-node.bold .fancytree-title { font-weight: bold; }-span.fancytree-node.muted { opacity: 0.6; }+span.fancytree-node.underline .fancytree-title {+ text-decoration: underline;+}+span.fancytree-node.dotted .fancytree-title {+ text-decoration: dotted;+}+span.fancytree-node.bold .fancytree-title {+ font-weight: bold;+}+span.fancytree-node.muted {+ opacity: 0.6;+}/** following will hide ancestors of hoisted (filtered) note */.fancytree-submatch:not(.fancytree-match) {@@ -138,19 +146,19 @@ span.fancytree-node.protected > span.fancytree-custom-icon {}span.fancytree-node.multiple-parents.shared .fancytree-title::after {- font-family: 'boxicons' !important;+ font-family: "boxicons" !important;font-size: smaller;content: " \eb3d \ec03";}span.fancytree-node.multiple-parents .fancytree-title::after {- font-family: 'boxicons' !important;+ font-family: "boxicons" !important;font-size: smaller;content: " \eb3d"; /* lookup code for "link-alt" in boxicons.css */}span.fancytree-node.shared .fancytree-title::after {- font-family: 'boxicons' !important;+ font-family: "boxicons" !important;font-size: smaller;content: " \ec03"; /* lookup code for "share-alt" in boxicons.css */}@@ -200,7 +208,8 @@ span.fancytree-node:hover {border: 1px solid var(--main-border-color);}-.fancytree-title:hover, span.fancytree-node:hover .fancytree-title {+.fancytree-title:hover,+span.fancytree-node:hover .fancytree-title {border: 0;}@@ -243,7 +252,8 @@ span.fancytree-node:hover .add-note-button {border: 1px solid var(--main-border-color);}-#fancytree-drop-marker.fancytree-drop-after, #fancytree-drop-marker.fancytree-drop-before {+#fancytree-drop-marker.fancytree-drop-after,+#fancytree-drop-marker.fancytree-drop-before {width: 100px;/* marker is by default position: relative which doesn't make sense */position: absolute !important;diff --git a/src/public/translations/cn/translation.json b/src/public/translations/cn/translation.jsonindex 78280f5297..1d844f21d2 100644--- a/src/public/translations/cn/translation.json+++ b/src/public/translations/cn/translation.json@@ -186,10 +186,10 @@"description": "配置在导入笔记时应保留的 HTML 标签。不在此列表中的标签将在导入过程中被移除。一些标签(例如 'script')为了安全性会始终被移除。","placeholder": "输入 HTML 标签,每行一个","reset_button": "重置为默认列表"- },- "import-status": "导入状态",- "in-progress": "导入进行中:{{progress}}",- "successful": "导入成功完成。"+ },+ "import-status": "导入状态",+ "in-progress": "导入进行中:{{progress}}",+ "successful": "导入成功完成。"},"include_note": {"dialog_title": "包含笔记",@@ -1090,7 +1090,7 @@"layout-horizontal-title": "水平","layout-vertical-description": "启动栏位于左侧(默认)","layout-horizontal-description": "启动栏位于标签栏下方,标签栏现在是全宽的。"- },+ },"zoom_factor": {"title": "缩放系数(仅桌面客户端有效)","description": "缩放也可以通过 CTRL+- 和 CTRL+= 快捷键进行控制。"diff --git a/src/public/translations/tw/translation.json b/src/public/translations/tw/translation.jsonindex f75e418da2..e80761cb25 100644--- a/src/public/translations/tw/translation.json+++ b/src/public/translations/tw/translation.json@@ -1068,7 +1068,7 @@"layout-horizontal-title": "水平","layout-vertical-description": "啓動欄位於左側(默認)","layout-horizontal-description": "啓動欄位於標籤欄下方,標籤欄現在是全寬的。"- },+ },"zoom_factor": {"title": "縮放系數(僅桌面客戶端有效)","description": "縮放也可以通過 CTRL+- 和 CTRL+= 快捷鍵進行控制。"diff --git a/src/routes/api/attachments.ts b/src/routes/api/attachments.tsindex d56bd1bbbe..b5f54fce04 100644--- a/src/routes/api/attachments.ts+++ b/src/routes/api/attachments.ts@@ -2,46 +2,46 @@ import becca from "../../becca/becca.js";import blobService from "../../services/blob.js";import ValidationError from "../../errors/validation_error.js";import imageService from "../../services/image.js";-import { Request } from 'express';+import { Request } from "express";function getAttachmentBlob(req: Request) {- const preview = req.query.preview === 'true';+ const preview = req.query.preview === "true";- return blobService.getBlobPojo('attachments', req.params.attachmentId, { preview });+ return blobService.getBlobPojo("attachments", req.params.attachmentId, { preview });}function getAttachments(req: Request) {const note = becca.getNoteOrThrow(req.params.noteId);- return note.getAttachments({includeContentLength: true});+ return note.getAttachments({ includeContentLength: true });}function getAttachment(req: Request) {- const {attachmentId} = req.params;+ const { attachmentId } = req.params;- return becca.getAttachmentOrThrow(attachmentId, {includeContentLength: true});+ return becca.getAttachmentOrThrow(attachmentId, { includeContentLength: true });}function getAllAttachments(req: Request) {- const {attachmentId} = req.params;+ const { attachmentId } = req.params;// one particular attachment is requested, but return all note's attachmentsconst attachment = becca.getAttachmentOrThrow(attachmentId);- return attachment.getNote()?.getAttachments({includeContentLength: true}) || [];+ return attachment.getNote()?.getAttachments({ includeContentLength: true }) || [];}function saveAttachment(req: Request) {- const {noteId} = req.params;- const {attachmentId, role, mime, title, content} = req.body;- const {matchBy} = req.query as any;+ const { noteId } = req.params;+ const { attachmentId, role, mime, title, content } = req.body;+ const { matchBy } = req.query as any;const note = becca.getNoteOrThrow(noteId);- note.saveAttachment({attachmentId, role, mime, title, content}, matchBy);+ note.saveAttachment({ attachmentId, role, mime, title, content }, matchBy);}function uploadAttachment(req: Request) {- const {noteId} = req.params;- const {file} = req as any;+ const { noteId } = req.params;+ const { file } = req as any;const note = becca.getNoteOrThrow(noteId);let url;@@ -51,7 +51,7 @@ function uploadAttachment(req: Request) {url = `api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}`;} else {const attachment = note.saveAttachment({- role: 'file',+ role: "file",mime: file.mimetype,title: file.originalname,content: file.buffer@@ -67,8 +67,8 @@ function uploadAttachment(req: Request) {}function renameAttachment(req: Request) {- const {title} = req.body;- const {attachmentId} = req.params;+ const { title } = req.body;+ const { attachmentId } = req.params;const attachment = becca.getAttachmentOrThrow(attachmentId);@@ -81,7 +81,7 @@ function renameAttachment(req: Request) {}function deleteAttachment(req: Request) {- const {attachmentId} = req.params;+ const { attachmentId } = req.params;const attachment = becca.getAttachment(attachmentId);@@ -91,7 +91,7 @@ function deleteAttachment(req: Request) {}function convertAttachmentToNote(req: Request) {- const {attachmentId} = req.params;+ const { attachmentId } = req.params;const attachment = becca.getAttachmentOrThrow(attachmentId);return attachment.convertToNote();diff --git a/src/routes/api/attributes.ts b/src/routes/api/attributes.tsindex b31afecf41..647e1a2067 100644--- a/src/routes/api/attributes.ts+++ b/src/routes/api/attributes.ts@@ -6,7 +6,7 @@ import attributeService from "../../services/attributes.js";import BAttribute from "../../becca/entities/battribute.js";import becca from "../../becca/becca.js";import ValidationError from "../../errors/validation_error.js";-import { Request } from 'express';+import { Request } from "express";function getEffectiveNoteAttributes(req: Request) {const note = becca.getNote(req.params.noteId);@@ -26,13 +26,10 @@ function updateNoteAttribute(req: Request) {throw new ValidationError(`Attribute '${body.attributeId}' is not owned by ${noteId}`);}- if (body.type !== attribute.type- || body.name !== attribute.name- || (body.type === 'relation' && body.value !== attribute.value)) {-+ if (body.type !== attribute.type || body.name !== attribute.name || (body.type === "relation" && body.value !== attribute.value)) {let newAttribute;- if (body.type !== 'relation' || !!body.value.trim()) {+ if (body.type !== "relation" || !!body.value.trim()) {newAttribute = attribute.createClone(body.type, body.name, body.value);newAttribute.save();}@@ -43,9 +40,8 @@ function updateNoteAttribute(req: Request) {attributeId: newAttribute ? newAttribute.attributeId : null};}- }- else {- if (body.type === 'relation' && !body.value?.trim()) {+ } else {+ if (body.type === "relation" && !body.value?.trim()) {return {};}@@ -56,10 +52,9 @@ function updateNoteAttribute(req: Request) {});}- if (attribute.type === 'label' || body.value.trim()) {+ if (attribute.type === "label" || body.value.trim()) {attribute.value = body.value;- }- else {+ } else {// relations should never have empty targetattribute.markAsDeleted();}@@ -85,7 +80,7 @@ function setNoteAttribute(req: Request) {attr.value = body.value;attr.save();} else {- const params = {...body};+ const params = { ...body };params.noteId = noteId; // noteId must be set before calling constructor for proper initializationnew BAttribute(params).save();@@ -96,7 +91,7 @@ function addNoteAttribute(req: Request) {const noteId = req.params.noteId;const body = req.body;- new BAttribute({...body, noteId}).save();+ new BAttribute({ ...body, noteId }).save();}function deleteNoteAttribute(req: Request) {@@ -132,14 +127,10 @@ function updateNoteAttributes(req: Request) {const value = incAttr.value || "";- const perfectMatchAttr = existingAttrs.find(attr =>- attr.type === incAttr.type &&- attr.name === incAttr.name &&- attr.isInheritable === incAttr.isInheritable &&- attr.value === value);+ const perfectMatchAttr = existingAttrs.find((attr) => attr.type === incAttr.type && attr.name === incAttr.name && attr.isInheritable === incAttr.isInheritable && attr.value === value);if (perfectMatchAttr) {- existingAttrs = existingAttrs.filter(attr => attr.attributeId !== perfectMatchAttr.attributeId);+ existingAttrs = existingAttrs.filter((attr) => attr.attributeId !== perfectMatchAttr.attributeId);if (perfectMatchAttr.position !== position) {perfectMatchAttr.position = position;@@ -149,7 +140,7 @@ function updateNoteAttributes(req: Request) {continue; // nothing to update}- if (incAttr.type === 'relation') {+ if (incAttr.type === "relation") {const targetNote = becca.getNote(incAttr.value);if (!targetNote) {@@ -158,17 +149,14 @@ function updateNoteAttributes(req: Request) {}}- const matchedAttr = existingAttrs.find(attr =>- attr.type === incAttr.type &&- attr.name === incAttr.name &&- attr.isInheritable === incAttr.isInheritable);+ const matchedAttr = existingAttrs.find((attr) => attr.type === incAttr.type && attr.name === incAttr.name && attr.isInheritable === incAttr.isInheritable);if (matchedAttr) {matchedAttr.value = incAttr.value;matchedAttr.position = position;matchedAttr.save();- existingAttrs = existingAttrs.filter(attr => attr.attributeId !== matchedAttr.attributeId);+ existingAttrs = existingAttrs.filter((attr) => attr.attributeId !== matchedAttr.attributeId);continue;}@@ -208,14 +196,18 @@ function createRelation(req: Request) {const targetNoteId = req.params.targetNoteId;const name = req.params.name;- const attributeId = sql.getValue<string>(`SELECT attributeId FROM attributes WHERE isDeleted = 0 AND noteId = ? AND type = 'relation' AND name = ? AND value = ?`, [sourceNoteId, name, targetNoteId]);+ const attributeId = sql.getValue<string>(`SELECT attributeId FROM attributes WHERE isDeleted = 0 AND noteId = ? AND type = 'relation' AND name = ? AND value = ?`, [+ sourceNoteId,+ name,+ targetNoteId+ ]);let attribute = becca.getAttribute(attributeId);if (!attribute) {attribute = new BAttribute({noteId: sourceNoteId,name: name,- type: 'relation',+ type: "relation",value: targetNoteId}).save();}@@ -228,7 +220,11 @@ function deleteRelation(req: Request) {const targetNoteId = req.params.targetNoteId;const name = req.params.name;- const attributeId = sql.getValue<string | null>(`SELECT attributeId FROM attributes WHERE isDeleted = 0 AND noteId = ? AND type = 'relation' AND name = ? AND value = ?`, [sourceNoteId, name, targetNoteId]);+ const attributeId = sql.getValue<string | null>(`SELECT attributeId FROM attributes WHERE isDeleted = 0 AND noteId = ? AND type = 'relation' AND name = ? AND value = ?`, [+ sourceNoteId,+ name,+ targetNoteId+ ]);if (attributeId) {const attribute = becca.getAttribute(attributeId);diff --git a/src/routes/api/autocomplete.ts b/src/routes/api/autocomplete.tsindex 1ec55bfb6c..012065c5d1 100644--- a/src/routes/api/autocomplete.ts+++ b/src/routes/api/autocomplete.ts@@ -6,7 +6,7 @@ import log from "../../services/log.js";import utils from "../../services/utils.js";import cls from "../../services/cls.js";import becca from "../../becca/becca.js";-import { Request } from 'express';+import { Request } from "express";import ValidationError from "../../errors/validation_error.js";function getAutocomplete(req: Request) {@@ -16,7 +16,7 @@ function getAutocomplete(req: Request) {const query = (req.query.query || "").trim();const fastSearch = String(req.query.fastSearch).toLowerCase() === "false" ? false : true;- const activeNoteId = req.query.activeNoteId || 'none';+ const activeNoteId = req.query.activeNoteId || "none";let results;@@ -24,8 +24,7 @@ function getAutocomplete(req: Request) {if (query.length === 0 && typeof activeNoteId === "string") {results = getRecentNotes(activeNoteId);- }- else {+ } else {results = searchService.searchNotesForAutocomplete(query, fastSearch);}@@ -39,16 +38,17 @@ function getAutocomplete(req: Request) {}function getRecentNotes(activeNoteId: string) {- let extraCondition = '';+ let extraCondition = "";const params = [activeNoteId];const hoistedNoteId = cls.getHoistedNoteId();- if (hoistedNoteId !== 'root') {+ if (hoistedNoteId !== "root") {extraCondition = `AND recent_notes.notePath LIKE ?`;params.push(`%${hoistedNoteId}%`);}- const recentNotes = becca.getRecentNotesFromQuery(`+ const recentNotes = becca.getRecentNotesFromQuery(+ `SELECTrecent_notes.*FROM@@ -60,10 +60,12 @@ function getRecentNotes(activeNoteId: string) {${extraCondition}ORDER BYutcDateCreated DESC- LIMIT 200`, params);+ LIMIT 200`,+ params+ );- return recentNotes.map(rn => {- const notePathArray = rn.notePath.split('/');+ return recentNotes.map((rn) => {+ const notePathArray = rn.notePath.split("/");const noteTitle = beccaService.getNoteTitle(notePathArray[notePathArray.length - 1]);const notePathTitle = beccaService.getNoteTitleForPath(notePathArray);diff --git a/src/routes/api/backend_log.ts b/src/routes/api/backend_log.tsindex 6e3af2a8ea..f578862429 100644--- a/src/routes/api/backend_log.ts+++ b/src/routes/api/backend_log.ts@@ -9,9 +9,8 @@ function getBackendLog() {const file = `${LOG_DIR}/trilium-${dateUtils.localNowDate()}.log`;try {- return fs.readFileSync(file, 'utf8');- }- catch (e) {+ return fs.readFileSync(file, "utf8");+ } catch (e) {// most probably the log file does not exist yet - https://github.com/zadam/trilium/issues/1977return "";}diff --git a/src/routes/api/branches.ts b/src/routes/api/branches.tsindex 11141fbe8b..a80805db05 100644--- a/src/routes/api/branches.ts+++ b/src/routes/api/branches.ts@@ -11,7 +11,7 @@ import branchService from "../../services/branches.js";import log from "../../services/log.js";import ValidationError from "../../errors/validation_error.js";import eventService from "../../services/events.js";-import { Request } from 'express';+import { Request } from "express";/*** Code in this file deals with moving and cloning branches. The relationship between note and parent note is unique@@ -19,7 +19,7 @@ import { Request } from 'express';*/function moveBranchToParent(req: Request) {- const {branchId, parentBranchId} = req.params;+ const { branchId, parentBranchId } = req.params;const branchToMove = becca.getBranch(branchId);const targetParentBranch = becca.getBranch(parentBranchId);@@ -32,7 +32,7 @@ function moveBranchToParent(req: Request) {}function moveBranchBeforeNote(req: Request) {- const {branchId, beforeBranchId} = req.params;+ const { branchId, beforeBranchId } = req.params;const branchToMove = becca.getBranchOrThrow(branchId);const beforeBranch = becca.getBranchOrThrow(beforeBranchId);@@ -48,8 +48,7 @@ function moveBranchBeforeNote(req: Request) {// we don't change utcDateModified, so other changes are prioritized in case of conflict// also we would have to sync all those modified branches otherwise hash checks would fail- sql.execute("UPDATE branches SET notePosition = notePosition + 10 WHERE parentNoteId = ? AND notePosition >= ? AND isDeleted = 0",- [beforeBranch.parentNoteId, originalBeforeNotePosition]);+ sql.execute("UPDATE branches SET notePosition = notePosition + 10 WHERE parentNoteId = ? AND notePosition >= ? AND isDeleted = 0", [beforeBranch.parentNoteId, originalBeforeNotePosition]);// also need to update becca positionsconst parentNote = becca.getNoteOrThrow(beforeBranch.parentNoteId);@@ -63,8 +62,7 @@ function moveBranchBeforeNote(req: Request) {if (branchToMove.parentNoteId === beforeBranch.parentNoteId) {branchToMove.notePosition = originalBeforeNotePosition;branchToMove.save();- }- else {+ } else {const newBranch = branchToMove.createClone(beforeBranch.parentNoteId, originalBeforeNotePosition);newBranch.save();@@ -82,7 +80,7 @@ function moveBranchBeforeNote(req: Request) {}function moveBranchAfterNote(req: Request) {- const {branchId, afterBranchId} = req.params;+ const { branchId, afterBranchId } = req.params;const branchToMove = becca.getBranchOrThrow(branchId);const afterNote = becca.getBranchOrThrow(afterBranchId);@@ -97,8 +95,7 @@ function moveBranchAfterNote(req: Request) {// we don't change utcDateModified, so other changes are prioritized in case of conflict// also we would have to sync all those modified branches otherwise hash checks would fail- sql.execute("UPDATE branches SET notePosition = notePosition + 10 WHERE parentNoteId = ? AND notePosition > ? AND isDeleted = 0",- [afterNote.parentNoteId, originalAfterNotePosition]);+ sql.execute("UPDATE branches SET notePosition = notePosition + 10 WHERE parentNoteId = ? AND notePosition > ? AND isDeleted = 0", [afterNote.parentNoteId, originalAfterNotePosition]);// also need to update becca positionsconst parentNote = becca.getNoteOrThrow(afterNote.parentNoteId);@@ -114,8 +111,7 @@ function moveBranchAfterNote(req: Request) {if (branchToMove.parentNoteId === afterNote.parentNoteId) {branchToMove.notePosition = movedNotePosition;branchToMove.save();- }- else {+ } else {const newBranch = branchToMove.createClone(afterNote.parentNoteId, movedNotePosition);newBranch.save();@@ -133,10 +129,10 @@ function moveBranchAfterNote(req: Request) {}function setExpanded(req: Request) {- const {branchId} = req.params;+ const { branchId } = req.params;const expanded = parseInt(req.params.expanded);- if (branchId !== 'none_root') {+ if (branchId !== "none_root") {sql.execute("UPDATE branches SET isExpanded = ? WHERE branchId = ?", [expanded, branchId]);// we don't sync expanded label// also this does not trigger updates to the frontend, this would trigger too many reloads@@ -148,17 +144,18 @@ function setExpanded(req: Request) {}eventService.emit(eventService.ENTITY_CHANGED, {- entityName: 'branches',+ entityName: "branches",entity: branch});}}function setExpandedForSubtree(req: Request) {- const {branchId} = req.params;+ const { branchId } = req.params;const expanded = parseInt(req.params.expanded);- let branchIds = sql.getColumn<string>(`+ let branchIds = sql.getColumn<string>(+ `WITH RECURSIVEtree(branchId, noteId) AS (SELECT branchId, noteId FROM branches WHERE branchId = ?@@ -167,10 +164,12 @@ function setExpandedForSubtree(req: Request) {JOIN tree ON branches.parentNoteId = tree.noteIdWHERE branches.isDeleted = 0)- SELECT branchId FROM tree`, [branchId]);+ SELECT branchId FROM tree`,+ [branchId]+ );// root is always expanded- branchIds = branchIds.filter(branchId => branchId !== 'none_root');+ branchIds = branchIds.filter((branchId) => branchId !== "none_root");sql.executeMany(`UPDATE branches SET isExpanded = ${expanded} WHERE branchId IN (???)`, branchIds);@@ -188,11 +187,11 @@ function setExpandedForSubtree(req: Request) {}function deleteBranch(req: Request) {- const last = req.query.last === 'true';- const eraseNotes = req.query.eraseNotes === 'true';+ const last = req.query.last === "true";+ const eraseNotes = req.query.eraseNotes === "true";const branch = becca.getBranchOrThrow(req.params.branchId);- const taskContext = TaskContext.getInstance(req.query.taskId as string, 'deleteNotes');+ const taskContext = TaskContext.getInstance(req.query.taskId as string, "deleteNotes");const deleteId = utils.randomString(10);let noteDeleted;diff --git a/src/routes/api/bulk_action.ts b/src/routes/api/bulk_action.tsindex 799d05952e..4688b5c43a 100644--- a/src/routes/api/bulk_action.ts+++ b/src/routes/api/bulk_action.ts@@ -1,19 +1,19 @@-import { Request } from 'express';+import { Request } from "express";import becca from "../../becca/becca.js";import bulkActionService from "../../services/bulk_actions.js";function execute(req: Request) {- const {noteIds, includeDescendants} = req.body;+ const { noteIds, includeDescendants } = req.body;const affectedNoteIds = getAffectedNoteIds(noteIds, includeDescendants);- const bulkActionNote = becca.getNoteOrThrow('_bulkAction');+ const bulkActionNote = becca.getNoteOrThrow("_bulkAction");bulkActionService.executeActions(bulkActionNote, affectedNoteIds);}function getAffectedNoteCount(req: Request) {- const {noteIds, includeDescendants} = req.body;+ const { noteIds, includeDescendants } = req.body;const affectedNoteIds = getAffectedNoteIds(noteIds, includeDescendants);diff --git a/src/routes/api/clipper.ts b/src/routes/api/clipper.tsindex ae181742cf..98b7d3d44b 100644--- a/src/routes/api/clipper.ts+++ b/src/routes/api/clipper.ts@@ -30,8 +30,8 @@ function addClipping(req: Request) {// if a note under the clipperInbox has the same 'pageUrl' attribute,// add the content to that note and clone it under today's inbox// otherwise just create a new note under today's inbox- let {title, content, pageUrl, images} = req.body;- const clipType = 'clippings';+ let { title, content, pageUrl, images } = req.body;+ const clipType = "clippings";const clipperInbox = getClipperInboxNote();@@ -42,13 +42,13 @@ function addClipping(req: Request) {clippingNote = noteService.createNewNote({parentNoteId: clipperInbox.noteId,title: title,- content: '',- type: 'text'+ content: "",+ type: "text"}).note;- clippingNote.setLabel('clipType', 'clippings');- clippingNote.setLabel('pageUrl', pageUrl);- clippingNote.setLabel('iconClass', 'bx bx-globe');+ clippingNote.setLabel("clipType", "clippings");+ clippingNote.setLabel("pageUrl", pageUrl);+ clippingNote.setLabel("iconClass", "bx bx-globe");}const rewrittenContent = processContent(images, clippingNote, content);@@ -76,20 +76,21 @@ function findClippingNote(clipperInboxNote: BNote, pageUrl: string, clipType: st}const notes = clipperInboxNote.searchNotesInSubtree(- attributeFormatter.formatAttrForSearch({- type: 'label',- name: "pageUrl",- value: pageUrl- }, true)+ attributeFormatter.formatAttrForSearch(+ {+ type: "label",+ name: "pageUrl",+ value: pageUrl+ },+ true+ ));- return clipType- ? notes.find(note => note.getOwnedLabelValue('clipType') === clipType)- : notes[0];+ return clipType ? notes.find((note) => note.getOwnedLabelValue("clipType") === clipType) : notes[0];}function getClipperInboxNote() {- let clipperInbox = attributeService.getNoteWithLabel('clipperInbox');+ let clipperInbox = attributeService.getNoteWithLabel("clipperInbox");if (!clipperInbox) {clipperInbox = dateNoteService.getDayNote(dateUtils.localNowDate());@@ -99,7 +100,7 @@ function getClipperInboxNote() {}function createNote(req: Request) {- let {title, content, pageUrl, images, clipType, labels} = req.body;+ let { title, content, pageUrl, images, clipType, labels } = req.body;if (!title || !title.trim()) {title = `Clipped note from ${pageUrl}`;@@ -115,17 +116,17 @@ function createNote(req: Request) {note = noteService.createNewNote({parentNoteId: clipperInbox.noteId,title,- content: '',- type: 'text'+ content: "",+ type: "text"}).note;- note.setLabel('clipType', clipType);+ note.setLabel("clipType", clipType);if (pageUrl) {pageUrl = htmlSanitizer.sanitizeUrl(pageUrl);- note.setLabel('pageUrl', pageUrl);- note.setLabel('iconClass', 'bx bx-globe');+ note.setLabel("pageUrl", pageUrl);+ note.setLabel("iconClass", "bx bx-globe");}}@@ -155,19 +156,17 @@ function processContent(images: Image[], note: BNote, content: string) {let rewrittenContent = htmlSanitizer.sanitize(content);if (images) {- for (const {src, dataUrl, imageId} of images) {+ for (const { src, dataUrl, imageId } of images) {const filename = path.basename(src);if (!dataUrl || !dataUrl.startsWith("data:image")) {- const excerpt = dataUrl- ? dataUrl.substr(0, Math.min(100, dataUrl.length))- : "null";+ const excerpt = dataUrl ? dataUrl.substr(0, Math.min(100, dataUrl.length)) : "null";log.info(`Image could not be recognized as data URL: ${excerpt}`);continue;}- const buffer = Buffer.from(dataUrl.split(",")[1], 'base64');+ const buffer = Buffer.from(dataUrl.split(",")[1], "base64");const attachment = imageService.saveImageToAttachment(note.noteId, buffer, filename, true);@@ -198,18 +197,17 @@ function processContent(images: Image[], note: BNote, content: string) {function openNote(req: Request) {if (utils.isElectron()) {ws.sendMessageToAllClients({- type: 'openNote',+ type: "openNote",noteId: req.params.noteId});return {- result: 'ok'+ result: "ok"};- }- else {+ } else {return {- result: 'open-in-browser'- }+ result: "open-in-browser"+ };}}@@ -217,16 +215,16 @@ function handshake() {return {appName: "trilium",protocolVersion: appInfo.clipperProtocolVersion- }+ };}-function findNotesByUrl(req: Request){+function findNotesByUrl(req: Request) {let pageUrl = req.params.noteUrl;const clipperInbox = getClipperInboxNote();let foundPage = findClippingNote(clipperInbox, pageUrl, null);return {noteId: foundPage ? foundPage.noteId : null- }+ };}export default {diff --git a/src/routes/api/cloning.ts b/src/routes/api/cloning.tsindex 73de813cb3..c000575dce 100644--- a/src/routes/api/cloning.ts+++ b/src/routes/api/cloning.ts@@ -1,32 +1,32 @@"use strict";-import { Request } from 'express';+import { Request } from "express";import cloningService from "../../services/cloning.js";function cloneNoteToBranch(req: Request) {- const {noteId, parentBranchId} = req.params;- const {prefix} = req.body;+ const { noteId, parentBranchId } = req.params;+ const { prefix } = req.body;return cloningService.cloneNoteToBranch(noteId, parentBranchId, prefix);}function cloneNoteToParentNote(req: Request) {- const {noteId, parentNoteId} = req.params;- const {prefix} = req.body;+ const { noteId, parentNoteId } = req.params;+ const { prefix } = req.body;return cloningService.cloneNoteToParentNote(noteId, parentNoteId, prefix);}function cloneNoteAfter(req: Request) {- const {noteId, afterBranchId} = req.params;+ const { noteId, afterBranchId } = req.params;return cloningService.cloneNoteAfter(noteId, afterBranchId);}function toggleNoteInParent(req: Request) {- const {noteId, parentNoteId, present} = req.params;+ const { noteId, parentNoteId, present } = req.params;- return cloningService.toggleNoteInParent(present === 'true', noteId, parentNoteId);+ return cloningService.toggleNoteInParent(present === "true", noteId, parentNoteId);}export default {diff --git a/src/routes/api/database.ts b/src/routes/api/database.tsindex 6b66575c2b..2329a88635 100644--- a/src/routes/api/database.ts+++ b/src/routes/api/database.ts@@ -5,7 +5,7 @@ import log from "../../services/log.js";import backupService from "../../services/backup.js";import anonymizationService from "../../services/anonymization.js";import consistencyChecksService from "../../services/consistency_checks.js";-import { Request } from 'express';+import { Request } from "express";import ValidationError from "../../errors/validation_error.js";import sql_init from "../../services/sql_init.js";import becca_loader from "../../becca/becca_loader.js";diff --git a/src/routes/api/etapi_tokens.ts b/src/routes/api/etapi_tokens.tsindex 82cb470e88..ffcdb6c614 100644--- a/src/routes/api/etapi_tokens.ts+++ b/src/routes/api/etapi_tokens.ts@@ -1,10 +1,10 @@-import { Request } from 'express';+import { Request } from "express";import etapiTokenService from "../../services/etapi_tokens.js";function getTokens() {const tokens = etapiTokenService.getTokens();- tokens.sort((a, b) => a.utcDateCreated < b.utcDateCreated ? -1 : 1);+ tokens.sort((a, b) => (a.utcDateCreated < b.utcDateCreated ? -1 : 1));return tokens;}diff --git a/src/routes/api/export.ts b/src/routes/api/export.tsindex f654487af2..c99b5396fb 100644--- a/src/routes/api/export.ts+++ b/src/routes/api/export.ts@@ -7,51 +7,43 @@ import becca from "../../becca/becca.js";import TaskContext from "../../services/task_context.js";import log from "../../services/log.js";import NotFoundError from "../../errors/not_found_error.js";-import { Request, Response } from 'express';+import { Request, Response } from "express";import ValidationError from "../../errors/validation_error.js";function exportBranch(req: Request, res: Response) {- const {branchId, type, format, version, taskId} = req.params;+ const { branchId, type, format, version, taskId } = req.params;const branch = becca.getBranch(branchId);if (!branch) {const message = `Cannot export branch '${branchId}' since it does not exist.`;log.error(message);- res.setHeader("Content-Type", "text/plain")- .status(500)- .send(message);+ res.setHeader("Content-Type", "text/plain").status(500).send(message);return;}- const taskContext = new TaskContext(taskId, 'export');+ const taskContext = new TaskContext(taskId, "export");try {- if (type === 'subtree' && (format === 'html' || format === 'markdown')) {+ if (type === "subtree" && (format === "html" || format === "markdown")) {zipExportService.exportToZip(taskContext, branch, format, res);- }- else if (type === 'single') {+ } else if (type === "single") {if (format !== "html" && format !== "markdown") {throw new ValidationError("Invalid export type.");}singleExportService.exportSingleNote(taskContext, branch, format, res);- }- else if (format === 'opml') {+ } else if (format === "opml") {opmlExportService.exportToOpml(taskContext, branch, version, res);- }- else {+ } else {throw new NotFoundError(`Unrecognized export format '${format}'`);}- }- catch (e: any) {+ } catch (e: any) {const message = `Export failed with following error: '${e.message}'. More details might be in the logs.`;taskContext.reportError(message);log.error(message + e.stack);- res.setHeader("Content-Type", "text/plain")- .status(500)- .send(message);+ res.setHeader("Content-Type", "text/plain").status(500).send(message);}}diff --git a/src/routes/api/files.ts b/src/routes/api/files.tsindex 2eb3ee37b8..67db64317e 100644--- a/src/routes/api/files.ts+++ b/src/routes/api/files.ts@@ -6,12 +6,12 @@ import log from "../../services/log.js";import noteService from "../../services/notes.js";import tmp from "tmp";import fs from "fs";-import { Readable } from 'stream';+import { Readable } from "stream";import chokidar from "chokidar";import ws from "../../services/ws.js";import becca from "../../becca/becca.js";import ValidationError from "../../errors/validation_error.js";-import { Request, Response } from 'express';+import { Request, Response } from "express";import BNote from "../../becca/entities/bnote.js";import BAttachment from "../../becca/entities/battachment.js";@@ -33,7 +33,7 @@ function updateFile(req: Request) {note.setContent(file.buffer);- note.setLabel('originalFileName', file.originalname);+ note.setLabel("originalFileName", file.originalname);noteService.asyncPostProcessContent(note, file.buffer);@@ -55,7 +55,7 @@ function updateAttachment(req: Request) {attachment.getNote().saveRevision();attachment.mime = file.mimetype.toLowerCase();- attachment.setContent(file.buffer, {forceSave: true});+ attachment.setContent(file.buffer, { forceSave: true });return {uploaded: true@@ -70,11 +70,11 @@ function downloadData(noteOrAttachment: BNote | BAttachment, res: Response, contif (contentDisposition) {const fileName = noteOrAttachment.getFileName();- res.setHeader('Content-Disposition', utils.getContentDisposition(fileName));+ res.setHeader("Content-Disposition", utils.getContentDisposition(fileName));}res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");- res.setHeader('Content-Type', noteOrAttachment.mime);+ res.setHeader("Content-Type", noteOrAttachment.mime);res.send(noteOrAttachment.getContent());}@@ -83,9 +83,7 @@ function downloadNoteInt(noteId: string, res: Response, contentDisposition = truconst note = becca.getNote(noteId);if (!note) {- return res.setHeader("Content-Type", "text/plain")- .status(404)- .send(`Note '${noteId}' doesn't exist.`);+ return res.setHeader("Content-Type", "text/plain").status(404).send(`Note '${noteId}' doesn't exist.`);}return downloadData(note, res, contentDisposition);@@ -95,9 +93,7 @@ function downloadAttachmentInt(attachmentId: string, res: Response, contentDispoconst attachment = becca.getAttachment(attachmentId);if (!attachment) {- return res.setHeader("Content-Type", "text/plain")- .status(404)- .send(`Attachment '${attachmentId}' doesn't exist.`);+ return res.setHeader("Content-Type", "text/plain").status(404).send(`Attachment '${attachmentId}' doesn't exist.`);}return downloadData(attachment, res, contentDisposition);@@ -125,21 +121,21 @@ function attachmentContentProvider(req: Request) {async function streamContent(content: string | Buffer, fileName: string, mimeType: string) {if (typeof content === "string") {- content = Buffer.from(content, 'utf8');+ content = Buffer.from(content, "utf8");}const totalSize = content.byteLength;- const getStream = (range: { start: number, end: number }) => {+ const getStream = (range: { start: number; end: number }) => {if (!range) {// Request if for complete content.return Readable.from(content);}// Partial content request.- const {start, end} = range;+ const { start, end } = range;return Readable.from(content.slice(start, end + 1));- }+ };return {fileName,@@ -154,7 +150,7 @@ function saveNoteToTmpDir(req: Request) {const fileName = note.getFileName();const content = note.getContent();- return saveToTmpDir(fileName, content, 'notes', note.noteId);+ return saveToTmpDir(fileName, content, "notes", note.noteId);}function saveAttachmentToTmpDir(req: Request) {@@ -165,7 +161,7 @@ function saveAttachmentToTmpDir(req: Request) {if (!attachment.attachmentId) {throw new ValidationError("Missing attachment ID.");}- return saveToTmpDir(fileName, content, 'attachments', attachment.attachmentId);+ return saveToTmpDir(fileName, content, "attachments", attachment.attachmentId);}const createdTemporaryFiles = new Set<string>();@@ -186,9 +182,9 @@ function saveToTmpDir(fileName: string, content: string | Buffer, entityType: stlog.info(`Saved temporary file ${tmpObj.name}`);if (utils.isElectron()) {- chokidar.watch(tmpObj.name).on('change', (path, stats) => {+ chokidar.watch(tmpObj.name).on("change", (path, stats) => {ws.sendMessageToAllClients({- type: 'openedFileUpdated',+ type: "openedFileUpdated",entityType: entityType,entityId: entityId,lastModifiedMs: stats?.atimeMs,@@ -204,7 +200,7 @@ function saveToTmpDir(fileName: string, content: string | Buffer, entityType: stfunction uploadModifiedFileToNote(req: Request) {const noteId = req.params.noteId;- const {filePath} = req.body;+ const { filePath } = req.body;if (!createdTemporaryFiles.has(filePath)) {throw new ValidationError(`File '${filePath}' is not a temporary file.`);@@ -226,8 +222,8 @@ function uploadModifiedFileToNote(req: Request) {}function uploadModifiedFileToAttachment(req: Request) {- const {attachmentId} = req.params;- const {filePath} = req.body;+ const { attachmentId } = req.params;+ const { filePath } = req.body;const attachment = becca.getAttachmentOrThrow(attachmentId);diff --git a/src/routes/api/fonts.ts b/src/routes/api/fonts.tsindex d62ecb2256..38a784354f 100644--- a/src/routes/api/fonts.ts+++ b/src/routes/api/fonts.ts@@ -1,10 +1,11 @@-import { Request, Response } from 'express';+import { Request, Response } from "express";import optionService from "../../services/options.js";-import { OptionMap } from '../../services/options_interface.js';+import { OptionMap } from "../../services/options_interface.js";const SYSTEM_SANS_SERIF = ["system-ui",- "-apple-system", "BlinkMacSystemFont",+ "-apple-system",+ "BlinkMacSystemFont","Segoe UI","Cantarell","Ubuntu",@@ -12,25 +13,17 @@ const SYSTEM_SANS_SERIF = ["Helvetica","Arial","sans-serif",- "Apple Color Emoji", "Segoe UI Emoji"+ "Apple Color Emoji",+ "Segoe UI Emoji"].join(",");-const SYSTEM_MONOSPACE = [- "ui-monospace",- "SFMono-Regular", "SF Mono",- "Consolas",- "Source Code Pro",- "Ubuntu Mono",- "Menlo",- "Liberation Mono",- "monospace"-].join(",");+const SYSTEM_MONOSPACE = ["ui-monospace", "SFMono-Regular", "SF Mono", "Consolas", "Source Code Pro", "Ubuntu Mono", "Menlo", "Liberation Mono", "monospace"].join(",");function getFontCss(req: Request, res: Response) {- res.setHeader('Content-Type', 'text/css');+ res.setHeader("Content-Type", "text/css");- if (!optionService.getOptionBool('overrideThemeFonts')) {- res.send('');+ if (!optionService.getOptionBool("overrideThemeFonts")) {+ res.send("");return;}@@ -38,10 +31,10 @@ function getFontCss(req: Request, res: Response) {const optionsMap = optionService.getOptionMap();// using body to be more specific than themes' :root- let style = 'body {';+ let style = "body {";style += getFontFamily(optionsMap);style += getFontSize(optionsMap);- style += '}';+ style += "}";res.send(style);}@@ -67,19 +60,19 @@ function getFontFamily({ mainFontFamily, treeFontFamily, detailFontFamily, monos}// Apply the font override if not using theme fonts.- if (mainFontFamily !== 'theme') {+ if (mainFontFamily !== "theme") {style += `--main-font-family: ${mainFontFamily};`;}- if (treeFontFamily !== 'theme') {+ if (treeFontFamily !== "theme") {style += `--tree-font-family: ${treeFontFamily};`;}- if (detailFontFamily !== 'theme') {+ if (detailFontFamily !== "theme") {style += `--detail-font-family: ${detailFontFamily};`;}- if (monospaceFontFamily !== 'theme') {+ if (monospaceFontFamily !== "theme") {style += `--monospace-font-family: ${monospaceFontFamily};`;}diff --git a/src/routes/api/image.ts b/src/routes/api/image.tsindex 5c8bd417e3..4712e9a340 100644--- a/src/routes/api/image.ts+++ b/src/routes/api/image.ts@@ -3,7 +3,7 @@import imageService from "../../services/image.js";import becca from "../../becca/becca.js";import fs from "fs";-import { Request, Response } from 'express';+import { Request, Response } from "express";import BNote from "../../becca/entities/bnote.js";import BRevision from "../../becca/entities/brevision.js";import { RESOURCE_DIR } from "../../services/resource_dir.js";@@ -22,27 +22,27 @@ function returnImageFromRevision(req: Request, res: Response) {function returnImageInt(image: BNote | BRevision | null, res: Response) {if (!image) {- res.set('Content-Type', 'image/png');+ res.set("Content-Type", "image/png");return res.send(fs.readFileSync(`${RESOURCE_DIR}/db/image-deleted.png`));- } else if (![ "image", "canvas", "mermaid", "mindMap" ].includes(image.type)) {+ } else if (!["image", "canvas", "mermaid", "mindMap"].includes(image.type)) {return res.sendStatus(400);}- if (image.type === 'canvas') {- renderSvgAttachment(image, res, 'canvas-export.svg');- } else if (image.type === 'mermaid') {- renderSvgAttachment(image, res, 'mermaid-export.svg');+ if (image.type === "canvas") {+ renderSvgAttachment(image, res, "canvas-export.svg");+ } else if (image.type === "mermaid") {+ renderSvgAttachment(image, res, "mermaid-export.svg");} else if (image.type === "mindMap") {- renderSvgAttachment(image, res, 'mindmap-export.svg');+ renderSvgAttachment(image, res, "mindmap-export.svg");} else {- res.set('Content-Type', image.mime);+ res.set("Content-Type", image.mime);res.set("Cache-Control", "no-cache, no-store, must-revalidate");res.send(image.getContent());}}function renderSvgAttachment(image: BNote | BRevision, res: Response, attachmentName: string) {- let svg: string | Buffer = '<svg/>'+ let svg: string | Buffer = "<svg/>";const attachment = image.getAttachmentByTitle(attachmentName);if (attachment) {@@ -56,34 +56,31 @@ function renderSvgAttachment(image: BNote | BRevision, res: Response, attachment}}- res.set('Content-Type', "image/svg+xml");+ res.set("Content-Type", "image/svg+xml");res.set("Cache-Control", "no-cache, no-store, must-revalidate");res.send(svg);}-function returnAttachedImage(req: Request, res: Response) {const attachment = becca.getAttachment(req.params.attachmentId);if (!attachment) {- res.set('Content-Type', 'image/png');+ res.set("Content-Type", "image/png");return res.send(fs.readFileSync(`${RESOURCE_DIR}/db/image-deleted.png`));}if (!["image"].includes(attachment.role)) {- return res.setHeader("Content-Type", "text/plain")- .status(400)- .send(`Attachment '${attachment.attachmentId}' has role '${attachment.role}', but 'image' was expected.`);+ return res.setHeader("Content-Type", "text/plain").status(400).send(`Attachment '${attachment.attachmentId}' has role '${attachment.role}', but 'image' was expected.`);}- res.set('Content-Type', attachment.mime);+ res.set("Content-Type", attachment.mime);res.set("Cache-Control", "no-cache, no-store, must-revalidate");res.send(attachment.getContent());}function updateImage(req: Request) {- const {noteId} = req.params;- const {file} = req;+ const { noteId } = req.params;+ const { file } = req;const note = becca.getNoteOrThrow(noteId);diff --git a/src/routes/api/import.ts b/src/routes/api/import.tsindex d811cc045a..5e65fb58e1 100644--- a/src/routes/api/import.ts+++ b/src/routes/api/import.ts@@ -11,7 +11,7 @@ import beccaLoader from "../../becca/becca_loader.js";import log from "../../services/log.js";import TaskContext from "../../services/task_context.js";import ValidationError from "../../errors/validation_error.js";-import { Request } from 'express';+import { Request } from "express";import BNote from "../../becca/entities/bnote.js";async function importNotesToBranch(req: Request) {@@ -19,12 +19,12 @@ async function importNotesToBranch(req: Request) {const { taskId, last } = req.body;const options = {- safeImport: req.body.safeImport !== 'false',- shrinkImages: req.body.shrinkImages !== 'false',- textImportedAsText: req.body.textImportedAsText !== 'false',- codeImportedAsCode: req.body.codeImportedAsCode !== 'false',- explodeArchives: req.body.explodeArchives !== 'false',- replaceUnderscoresWithSpaces: req.body.replaceUnderscoresWithSpaces !== 'false'+ safeImport: req.body.safeImport !== "false",+ shrinkImages: req.body.shrinkImages !== "false",+ textImportedAsText: req.body.textImportedAsText !== "false",+ codeImportedAsCode: req.body.codeImportedAsCode !== "false",+ explodeArchives: req.body.explodeArchives !== "false",+ replaceUnderscoresWithSpaces: req.body.replaceUnderscoresWithSpaces !== "false"};const file = req.file;@@ -46,19 +46,19 @@ async function importNotesToBranch(req: Request) {let note: BNote | null; // typically root of the import - client can show it after finishing the import- const taskContext = TaskContext.getInstance(taskId, 'importNotes', options);+ const taskContext = TaskContext.getInstance(taskId, "importNotes", options);try {- if (extension === '.zip' && options.explodeArchives && typeof file.buffer !== "string") {+ if (extension === ".zip" && options.explodeArchives && typeof file.buffer !== "string") {note = await zipImportService.importZip(taskContext, file.buffer, parentNote);- } else if (extension === '.opml' && options.explodeArchives) {+ } else if (extension === ".opml" && options.explodeArchives) {const importResult = await opmlImportService.importOpml(taskContext, file.buffer, parentNote);if (!Array.isArray(importResult)) {note = importResult;} else {return importResult;}- } else if (extension === '.enex' && options.explodeArchives) {+ } else if (extension === ".enex" && options.explodeArchives) {const importResult = await enexImportService.importEnex(taskContext, file, parentNote);if (!Array.isArray(importResult)) {note = importResult;@@ -68,8 +68,7 @@ async function importNotesToBranch(req: Request) {} else {note = await singleImportService.importSingleFile(taskContext, file, parentNote);}- }- catch (e: any) {+ } catch (e: any) {const message = `Import failed with following error: '${e.message}'. More details might be in the logs.`;taskContext.reportError(message);@@ -84,10 +83,14 @@ async function importNotesToBranch(req: Request) {if (last === "true") {// small timeout to avoid race condition (the message is received before the transaction is committed)- setTimeout(() => taskContext.taskSucceeded({- parentNoteId: parentNoteId,- importedNoteId: note?.noteId- }), 1000);+ setTimeout(+ () =>+ taskContext.taskSucceeded({+ parentNoteId: parentNoteId,+ importedNoteId: note?.noteId+ }),+ 1000+ );}// import has deactivated note events so becca is not updated, instead we force it to reload@@ -101,7 +104,7 @@ async function importAttachmentsToNote(req: Request) {const { taskId, last } = req.body;const options = {- shrinkImages: req.body.shrinkImages !== 'false',+ shrinkImages: req.body.shrinkImages !== "false"};const file = req.file;@@ -111,14 +114,13 @@ async function importAttachmentsToNote(req: Request) {}const parentNote = becca.getNoteOrThrow(parentNoteId);- const taskContext = TaskContext.getInstance(taskId, 'importAttachment', options);+ const taskContext = TaskContext.getInstance(taskId, "importAttachment", options);// unlike in note import, we let the events run, because a huge number of attachments is not likelytry {await singleImportService.importAttachment(taskContext, file, parentNote);- }- catch (e: any) {+ } catch (e: any) {const message = `Import failed with following error: '${e.message}'. More details might be in the logs.`;taskContext.reportError(message);@@ -129,9 +131,13 @@ async function importAttachmentsToNote(req: Request) {if (last === "true") {// small timeout to avoid race condition (the message is received before the transaction is committed)- setTimeout(() => taskContext.taskSucceeded({- parentNoteId: parentNoteId- }), 1000);+ setTimeout(+ () =>+ taskContext.taskSucceeded({+ parentNoteId: parentNoteId+ }),+ 1000+ );}}diff --git a/src/routes/api/keys.ts b/src/routes/api/keys.tsindex cd49c5c477..aded839e21 100644--- a/src/routes/api/keys.ts+++ b/src/routes/api/keys.ts@@ -8,10 +8,10 @@ function getKeyboardActions() {}function getShortcutsForNotes() {- const labels = becca.findAttributes('label', 'keyboardShortcut');+ const labels = becca.findAttributes("label", "keyboardShortcut");// launchers have different handling- return labels.filter(attr => becca.getNote(attr.noteId)?.type !== 'launcher');+ return labels.filter((attr) => becca.getNote(attr.noteId)?.type !== "launcher");}export default {diff --git a/src/routes/api/login.ts b/src/routes/api/login.tsindex 23b029bcec..598136fbe8 100644--- a/src/routes/api/login.ts+++ b/src/routes/api/login.ts@@ -12,7 +12,7 @@ import sqlInit from "../../services/sql_init.js";import sql from "../../services/sql.js";import ws from "../../services/ws.js";import etapiTokenService from "../../services/etapi_tokens.js";-import { Request } from 'express';+import { Request } from "express";function loginSync(req: Request) {if (!sqlInit.schemaExists()) {@@ -27,16 +27,19 @@ function loginSync(req: Request) {// login token is valid for 5 minutesif (Math.abs(timestamp.getTime() - now.getTime()) > 5 * 60 * 1000) {- return [401, { message: 'Auth request time is out of sync, please check that both client and server have correct time. The difference between clocks has to be smaller than 5 minutes.' }];+ return [401, { message: "Auth request time is out of sync, please check that both client and server have correct time. The difference between clocks has to be smaller than 5 minutes." }];}const syncVersion = req.body.syncVersion;if (syncVersion !== appInfo.syncVersion) {- return [400, { message: `Non-matching sync versions, local is version ${appInfo.syncVersion}, remote is ${syncVersion}. It is recommended to run same version of Trilium on both sides of sync.` }];+ return [+ 400,+ { message: `Non-matching sync versions, local is version ${appInfo.syncVersion}, remote is ${syncVersion}. It is recommended to run same version of Trilium on both sides of sync.` }+ ];}- const documentSecret = options.getOption('documentSecret');+ const documentSecret = options.getOption("documentSecret");const expectedHash = utils.hmac(documentSecret, timestampStr);const givenHash = req.body.hash;@@ -68,14 +71,14 @@ function loginToProtectedSession(req: Request) {return {success: false,message: "Unable to obtain data key."- }+ };}protectedSessionService.setDataKey(decryptedDataKey);eventService.emit(eventService.ENTER_PROTECTED_SESSION);- ws.sendMessageToAllClients({ type: 'protectedSessionLogin' });+ ws.sendMessageToAllClients({ type: "protectedSessionLogin" });return {success: true@@ -87,7 +90,7 @@ function logoutFromProtectedSession() {eventService.emit(eventService.LEAVE_PROTECTED_SESSION);- ws.sendMessageToAllClients({ type: 'protectedSessionLogout' });+ ws.sendMessageToAllClients({ type: "protectedSessionLogout" });}function touchProtectedSession() {@@ -104,7 +107,7 @@ function token(req: Request) {// for backwards compatibility with Sender which does not send the nameconst tokenName = req.body.tokenName || "Trilium Sender / Web Clipper";- const {authToken} = etapiTokenService.createToken(tokenName);+ const { authToken } = etapiTokenService.createToken(tokenName);return { token: authToken };}diff --git a/src/routes/api/note_map.ts b/src/routes/api/note_map.tsindex 4c4590e909..2b2b43eec0 100644--- a/src/routes/api/note_map.ts+++ b/src/routes/api/note_map.ts@@ -4,11 +4,11 @@ import becca from "../../becca/becca.js";import { JSDOM } from "jsdom";import BNote from "../../becca/entities/bnote.js";import BAttribute from "../../becca/entities/battribute.js";-import { Request } from 'express';+import { Request } from "express";function buildDescendantCountMap(noteIdsToCount: string[]) {if (!Array.isArray(noteIdsToCount)) {- throw new Error('noteIdsToCount: type error');+ throw new Error("noteIdsToCount: type error");}const noteIdToCountMap = Object.create(null);@@ -20,9 +20,9 @@ function buildDescendantCountMap(noteIdsToCount: string[]) {return;}- const hiddenImageNoteIds = note.getRelations('imageLink').map(rel => rel.value);- const childNoteIds = note.children.map(child => child.noteId);- const nonHiddenNoteIds = childNoteIds.filter(childNoteId => !hiddenImageNoteIds.includes(childNoteId));+ const hiddenImageNoteIds = note.getRelations("imageLink").map((rel) => rel.value);+ const childNoteIds = note.children.map((child) => child.noteId);+ const nonHiddenNoteIds = childNoteIds.filter((childNoteId) => !hiddenImageNoteIds.includes(childNoteId));noteIdToCountMap[noteId] = nonHiddenNoteIds.length;@@ -47,7 +47,7 @@ function getNeighbors(note: BNote, depth: number): string[] {const retNoteIds = [];function isIgnoredRelation(relation: BAttribute) {- return ['relationMapLink', 'template', 'inherit', 'image', 'ancestor'].includes(relation.name);+ return ["relationMapLink", "template", "inherit", "image", "ancestor"].includes(relation.name);}// forward links@@ -58,7 +58,7 @@ function getNeighbors(note: BNote, depth: number): string[] {const targetNote = relation.getTargetNote();- if (!targetNote || targetNote.isLabelTruthy('excludeFromNoteMap')) {+ if (!targetNote || targetNote.isLabelTruthy("excludeFromNoteMap")) {continue;}@@ -77,7 +77,7 @@ function getNeighbors(note: BNote, depth: number): string[] {const sourceNote = relation.getNote();- if (!sourceNote || sourceNote.isLabelTruthy('excludeFromNoteMap')) {+ if (!sourceNote || sourceNote.isLabelTruthy("excludeFromNoteMap")) {continue;}@@ -96,10 +96,10 @@ function getLinkMap(req: Request) {// if the map root itself has "excludeFromNoteMap" attribute (journal typically) then there wouldn't be anything// to display, so we'll just ignore it- const ignoreExcludeFromNoteMap = mapRootNote.isLabelTruthy('excludeFromNoteMap');+ const ignoreExcludeFromNoteMap = mapRootNote.isLabelTruthy("excludeFromNoteMap");let unfilteredNotes;- if (mapRootNote.type === 'search') {+ if (mapRootNote.type === "search") {// for search notes, we want to consider the direct search results only without the descendantsunfilteredNotes = mapRootNote.getSearchResultNotes();} else {@@ -110,13 +110,9 @@ function getLinkMap(req: Request) {}).notes;}- const noteIds = new Set(- unfilteredNotes- .filter(note => ignoreExcludeFromNoteMap || !note.isLabelTruthy('excludeFromNoteMap'))- .map(note => note.noteId)- );+ const noteIds = new Set(unfilteredNotes.filter((note) => ignoreExcludeFromNoteMap || !note.isLabelTruthy("excludeFromNoteMap")).map((note) => note.noteId));- if (mapRootNote.type === 'search') {+ if (mapRootNote.type === "search") {noteIds.delete(mapRootNote.noteId);}@@ -124,44 +120,37 @@ function getLinkMap(req: Request) {noteIds.add(noteId);}- const noteIdsArray = Array.from(noteIds)+ const noteIdsArray = Array.from(noteIds);- const notes = noteIdsArray.map(noteId => {+ const notes = noteIdsArray.map((noteId) => {const note = becca.getNoteOrThrow(noteId);- return [- note.noteId,- note.getTitleOrProtected(),- note.type,- note.getLabelValue('color')- ];+ return [note.noteId, note.getTitleOrProtected(), note.type, note.getLabelValue("color")];});- const links = Object.values(becca.attributes).filter(rel => {- if (rel.type !== 'relation' || rel.name === 'relationMapLink' || rel.name === 'template' || rel.name === 'inherit') {- return false;- }- else if (!noteIds.has(rel.noteId) || !noteIds.has(rel.value)) {- return false;- }- else if (rel.name === 'imageLink') {- const parentNote = becca.getNote(rel.noteId);- if (!parentNote) {+ const links = Object.values(becca.attributes)+ .filter((rel) => {+ if (rel.type !== "relation" || rel.name === "relationMapLink" || rel.name === "template" || rel.name === "inherit") {return false;- }+ } else if (!noteIds.has(rel.noteId) || !noteIds.has(rel.value)) {+ return false;+ } else if (rel.name === "imageLink") {+ const parentNote = becca.getNote(rel.noteId);+ if (!parentNote) {+ return false;+ }- return !parentNote.getChildNotes().find(childNote => childNote.noteId === rel.value);- }- else {- return true;- }- })- .map(rel => ({- id: `${rel.noteId}-${rel.name}-${rel.value}`,- sourceNoteId: rel.noteId,- targetNoteId: rel.value,- name: rel.name- }));+ return !parentNote.getChildNotes().find((childNote) => childNote.noteId === rel.value);+ } else {+ return true;+ }+ })+ .map((rel) => ({+ id: `${rel.noteId}-${rel.name}-${rel.value}`,+ sourceNoteId: rel.noteId,+ targetNoteId: rel.value,+ name: rel.name+ }));return {notes: notes,@@ -174,7 +163,7 @@ function getTreeMap(req: Request) {const mapRootNote = becca.getNoteOrThrow(req.params.noteId);// if the map root itself has "excludeFromNoteMap" (journal typically) then there wouldn't be anything to display,// so we'll just ignore it- const ignoreExcludeFromNoteMap = mapRootNote.isLabelTruthy('excludeFromNoteMap');+ const ignoreExcludeFromNoteMap = mapRootNote.isLabelTruthy("excludeFromNoteMap");const subtree = mapRootNote.getSubtree({includeArchived: false,resolveSearch: true,@@ -182,33 +171,28 @@ function getTreeMap(req: Request) {});const notes = subtree.notes- .filter(note => ignoreExcludeFromNoteMap || !note.isLabelTruthy('excludeFromNoteMap'))- .filter(note => {- if (note.type !== 'image' || note.getChildNotes().length > 0) {+ .filter((note) => ignoreExcludeFromNoteMap || !note.isLabelTruthy("excludeFromNoteMap"))+ .filter((note) => {+ if (note.type !== "image" || note.getChildNotes().length > 0) {return true;}- const imageLinkRelation = note.getTargetRelations().find(rel => rel.name === 'imageLink');+ const imageLinkRelation = note.getTargetRelations().find((rel) => rel.name === "imageLink");if (!imageLinkRelation) {return true;}- return !note.getParentNotes().find(parentNote => parentNote.noteId === imageLinkRelation.noteId);+ return !note.getParentNotes().find((parentNote) => parentNote.noteId === imageLinkRelation.noteId);})- .map(note => [- note.noteId,- note.getTitleOrProtected(),- note.type,- note.getLabelValue('color')- ]);+ .map((note) => [note.noteId, note.getTitleOrProtected(), note.type, note.getLabelValue("color")]);const noteIds = new Set<string>();notes.forEach(([noteId]) => noteId && noteIds.add(noteId));const links = [];- for (const {parentNoteId, childNoteId} of subtree.relationships) {+ for (const { parentNoteId, childNoteId } of subtree.relationships) {if (!noteIds.has(parentNoteId) || !noteIds.has(childNoteId)) {continue;}@@ -230,10 +214,10 @@ function getTreeMap(req: Request) {};}-function updateDescendantCountMapForSearch(noteIdToDescendantCountMap: Record<string, number>, relationships: { parentNoteId: string, childNoteId: string }[]) {- for (const {parentNoteId, childNoteId} of relationships) {+function updateDescendantCountMapForSearch(noteIdToDescendantCountMap: Record<string, number>, relationships: { parentNoteId: string; childNoteId: string }[]) {+ for (const { parentNoteId, childNoteId } of relationships) {const parentNote = becca.notes[parentNoteId];- if (!parentNote || parentNote.type !== 'search') {+ if (!parentNote || parentNote.type !== "search") {continue;}@@ -243,14 +227,14 @@ function updateDescendantCountMapForSearch(noteIdToDescendantCountMap: Record<st}function removeImages(document: Document) {- const images = document.getElementsByTagName('img');+ const images = document.getElementsByTagName("img");while (images && images.length > 0) {images[0]?.parentNode?.removeChild(images[0]);}}const EXCERPT_CHAR_LIMIT = 200;-type ElementOrText = (Element | Text);+type ElementOrText = Element | Text;function findExcerpts(sourceNote: BNote, referencedNoteId: string) {const html = sourceNote.getContent();@@ -271,7 +255,7 @@ function findExcerpts(sourceNote: BNote, referencedNoteId: string) {let centerEl: HTMLElement = linkEl;- while (centerEl.tagName !== 'BODY' && centerEl.parentElement && (centerEl.parentElement?.textContent?.length || 0) <= EXCERPT_CHAR_LIMIT) {+ while (centerEl.tagName !== "BODY" && centerEl.parentElement && (centerEl.parentElement?.textContent?.length || 0) <= EXCERPT_CHAR_LIMIT) {centerEl = centerEl.parentElement;}@@ -328,7 +312,7 @@ function findExcerpts(sourceNote: BNote, referencedNoteId: string) {}}- const excerptWrapper = document.createElement('div');+ const excerptWrapper = document.createElement("div");excerptWrapper.classList.add("ck-content");excerptWrapper.classList.add("backlink-excerpt");@@ -342,13 +326,16 @@ function findExcerpts(sourceNote: BNote, referencedNoteId: string) {}function getFilteredBacklinks(note: BNote) {- return note.getTargetRelations()- // search notes have "ancestor" relations which are not interesting- .filter(relation => !!relation.getNote() && relation.getNote().type !== 'search');+ return (+ note+ .getTargetRelations()+ // search notes have "ancestor" relations which are not interesting+ .filter((relation) => !!relation.getNote() && relation.getNote().type !== "search")+ );}function getBacklinkCount(req: Request) {- const {noteId} = req.params;+ const { noteId } = req.params;const note = becca.getNoteOrThrow(noteId);@@ -358,15 +345,15 @@ function getBacklinkCount(req: Request) {}function getBacklinks(req: Request) {- const {noteId} = req.params;+ const { noteId } = req.params;const note = becca.getNoteOrThrow(noteId);let backlinksWithExcerptCount = 0;- return getFilteredBacklinks(note).map(backlink => {+ return getFilteredBacklinks(note).map((backlink) => {const sourceNote = backlink.note;- if (sourceNote.type !== 'text' || backlinksWithExcerptCount > 50) {+ if (sourceNote.type !== "text" || backlinksWithExcerptCount > 50) {return {noteId: sourceNote.noteId,relationName: backlink.namediff --git a/src/routes/api/notes.ts b/src/routes/api/notes.tsindex 7f3c02124a..622acfc77c 100644--- a/src/routes/api/notes.ts+++ b/src/routes/api/notes.ts@@ -10,16 +10,16 @@ import TaskContext from "../../services/task_context.js";import becca from "../../becca/becca.js";import ValidationError from "../../errors/validation_error.js";import blobService from "../../services/blob.js";-import { Request } from 'express';+import { Request } from "express";import BBranch from "../../becca/entities/bbranch.js";-import { AttributeRow } from '../../becca/entities/rows.js';+import { AttributeRow } from "../../becca/entities/rows.js";function getNote(req: Request) {return becca.getNoteOrThrow(req.params.noteId);}function getNoteBlob(req: Request) {- return blobService.getBlobPojo('notes', req.params.noteId);+ return blobService.getBlobPojo("notes", req.params.noteId);}function getNoteMetadata(req: Request) {@@ -29,7 +29,7 @@ function getNoteMetadata(req: Request) {dateCreated: note.dateCreated,utcDateCreated: note.utcDateCreated,dateModified: note.dateModified,- utcDateModified: note.utcDateModified,+ utcDateModified: note.utcDateModified};}@@ -56,8 +56,8 @@ function createNote(req: Request) {}function updateNoteData(req: Request) {- const {content, attachments} = req.body;- const {noteId} = req.params;+ const { content, attachments } = req.body;+ const { noteId } = req.params;return noteService.updateNoteData(noteId, content, attachments);}@@ -65,8 +65,8 @@ function updateNoteData(req: Request) {function deleteNote(req: Request) {const noteId = req.params.noteId;const taskId = req.query.taskId;- const eraseNotes = req.query.eraseNotes === 'true';- const last = req.query.last === 'true';+ const eraseNotes = req.query.eraseNotes === "true";+ const last = req.query.last === "true";// note how deleteId is separate from taskId - single taskId produces separate deleteId for each "top level" deleted noteconst deleteId = utils.randomString(10);@@ -76,7 +76,7 @@ function deleteNote(req: Request) {if (typeof taskId !== "string") {throw new ValidationError("Missing or incorrect type for task ID.");}- const taskContext = TaskContext.getInstance(taskId, 'deleteNotes');+ const taskContext = TaskContext.getInstance(taskId, "deleteNotes");note.deleteNote(deleteId, taskContext);@@ -90,7 +90,7 @@ function deleteNote(req: Request) {}function undeleteNote(req: Request) {- const taskContext = TaskContext.getInstance(utils.randomString(10), 'undeleteNotes');+ const taskContext = TaskContext.getInstance(utils.randomString(10), "undeleteNotes");noteService.undeleteNote(req.params.noteId, taskContext);@@ -99,11 +99,11 @@ function undeleteNote(req: Request) {function sortChildNotes(req: Request) {const noteId = req.params.noteId;- const {sortBy, sortDirection, foldersFirst, sortNatural, sortLocale} = req.body;+ const { sortBy, sortDirection, foldersFirst, sortNatural, sortLocale } = req.body;log.info(`Sorting '${noteId}' children with ${sortBy} ${sortDirection}, foldersFirst=${foldersFirst}, sortNatural=${sortNatural}, sortLocale=${sortLocale}`);- const reverse = sortDirection === 'desc';+ const reverse = sortDirection === "desc";treeService.sortNotes(noteId, sortBy, reverse, foldersFirst, sortNatural, sortLocale);}@@ -114,7 +114,7 @@ function protectNote(req: Request) {const protect = !!parseInt(req.params.isProtected);const includingSubTree = !!parseInt(req.query?.subtree as string);- const taskContext = new TaskContext(utils.randomString(10), 'protectNotes', {protect});+ const taskContext = new TaskContext(utils.randomString(10), "protectNotes", { protect });noteService.protectNoteRecursively(note, protect, includingSubTree, taskContext);@@ -123,8 +123,8 @@ function protectNote(req: Request) {function setNoteTypeMime(req: Request) {// can't use [] destructuring because req.params is not iterable- const {noteId} = req.params;- const {type, mime} = req.body;+ const { noteId } = req.params;+ const { type, mime } = req.body;const note = becca.getNoteOrThrow(noteId);note.type = type;@@ -160,7 +160,7 @@ function changeTitle(req: Request) {}function duplicateSubtree(req: Request) {- const {noteId, parentNoteId} = req.params;+ const { noteId, parentNoteId } = req.params;return noteService.duplicateSubtree(noteId, parentNoteId);}@@ -174,7 +174,7 @@ function eraseUnusedAttachmentsNow() {}function getDeleteNotesPreview(req: Request) {- const {branchIdsToDelete, deleteAllClones} = req.body;+ const { branchIdsToDelete, deleteAllClones } = req.body;const noteIdsToBeDeleted = new Set<string>();const strongBranchCountToDelete: Record<string, number> = {}; // noteId => count@@ -216,12 +216,16 @@ function getDeleteNotesPreview(req: Request) {sql.fillParamList(noteIdsToBeDeleted);// FIXME: No need to do this in database, can be done with becca data- brokenRelations = sql.getRows<AttributeRow>(`+ brokenRelations = sql+ .getRows<AttributeRow>(+ `SELECT attr.noteId, attr.name, attr.valueFROM attributes attrJOIN param_list ON param_list.paramId = attr.valueWHERE attr.isDeleted = 0- AND attr.type = 'relation'`).filter(attr => attr.noteId && !noteIdsToBeDeleted.has(attr.noteId));+ AND attr.type = 'relation'`+ )+ .filter((attr) => attr.noteId && !noteIdsToBeDeleted.has(attr.noteId));}return {@@ -231,7 +235,7 @@ function getDeleteNotesPreview(req: Request) {}function forceSaveRevision(req: Request) {- const {noteId} = req.params;+ const { noteId } = req.params;const note = becca.getNoteOrThrow(noteId);if (!note.isContentAvailable()) {@@ -242,7 +246,7 @@ function forceSaveRevision(req: Request) {}function convertNoteToAttachment(req: Request) {- const {noteId} = req.params;+ const { noteId } = req.params;const note = becca.getNoteOrThrow(noteId);return {diff --git a/src/routes/api/options.ts b/src/routes/api/options.tsindex cf3038561f..87e0f47bad 100644--- a/src/routes/api/options.ts+++ b/src/routes/api/options.ts@@ -4,74 +4,74 @@ import optionService from "../../services/options.js";import log from "../../services/log.js";import searchService from "../../services/search/services/search.js";import ValidationError from "../../errors/validation_error.js";-import { Request } from 'express';+import { Request } from "express";import { changeLanguage } from "../../services/i18n.js";import { listSyntaxHighlightingThemes } from "../../services/code_block_theme.js";import type { OptionNames } from "../../services/options_interface.js";// options allowed to be updated directly in the Options dialogconst ALLOWED_OPTIONS = new Set([- 'eraseEntitiesAfterTimeInSeconds',- 'protectedSessionTimeout',- 'revisionSnapshotTimeInterval',- 'revisionSnapshotNumberLimit',- 'zoomFactor',- 'theme',- 'codeBlockTheme',+ "eraseEntitiesAfterTimeInSeconds",+ "protectedSessionTimeout",+ "revisionSnapshotTimeInterval",+ "revisionSnapshotNumberLimit",+ "zoomFactor",+ "theme",+ "codeBlockTheme","codeBlockWordWrap",- 'syncServerHost',- 'syncServerTimeout',- 'syncProxy',- 'hoistedNoteId',- 'mainFontSize',- 'mainFontFamily',- 'treeFontSize',- 'treeFontFamily',- 'detailFontSize',- 'detailFontFamily',- 'monospaceFontSize',- 'monospaceFontFamily',- 'openNoteContexts',- 'vimKeymapEnabled',- 'codeLineWrapEnabled',- 'codeNotesMimeTypes',- 'spellCheckEnabled',- 'spellCheckLanguageCode',- 'imageMaxWidthHeight',- 'imageJpegQuality',- 'leftPaneWidth',- 'rightPaneWidth',- 'leftPaneVisible',- 'rightPaneVisible',- 'nativeTitleBarVisible',- 'headingStyle',- 'autoCollapseNoteTree',- 'autoReadonlySizeText',- 'autoReadonlySizeCode',- 'overrideThemeFonts',- 'dailyBackupEnabled',- 'weeklyBackupEnabled',- 'monthlyBackupEnabled',- 'maxContentWidth',- 'compressImages',- 'downloadImagesAutomatically',- 'minTocHeadings',- 'highlightsList',- 'checkForUpdates',- 'disableTray',- 'eraseUnusedAttachmentsAfterSeconds',- 'disableTray',- 'customSearchEngineName',- 'customSearchEngineUrl',- 'promotedAttributesOpenInRibbon',- 'editedNotesOpenInRibbon',- 'locale',- 'firstDayOfWeek',- 'textNoteEditorType',- 'textNoteEditorMultilineToolbar',- 'layoutOrientation',- 'backgroundEffects',- 'allowedHtmlTags' // Allow configuring HTML import tags+ "syncServerHost",+ "syncServerTimeout",+ "syncProxy",+ "hoistedNoteId",+ "mainFontSize",+ "mainFontFamily",+ "treeFontSize",+ "treeFontFamily",+ "detailFontSize",+ "detailFontFamily",+ "monospaceFontSize",+ "monospaceFontFamily",+ "openNoteContexts",+ "vimKeymapEnabled",+ "codeLineWrapEnabled",+ "codeNotesMimeTypes",+ "spellCheckEnabled",+ "spellCheckLanguageCode",+ "imageMaxWidthHeight",+ "imageJpegQuality",+ "leftPaneWidth",+ "rightPaneWidth",+ "leftPaneVisible",+ "rightPaneVisible",+ "nativeTitleBarVisible",+ "headingStyle",+ "autoCollapseNoteTree",+ "autoReadonlySizeText",+ "autoReadonlySizeCode",+ "overrideThemeFonts",+ "dailyBackupEnabled",+ "weeklyBackupEnabled",+ "monthlyBackupEnabled",+ "maxContentWidth",+ "compressImages",+ "downloadImagesAutomatically",+ "minTocHeadings",+ "highlightsList",+ "checkForUpdates",+ "disableTray",+ "eraseUnusedAttachmentsAfterSeconds",+ "disableTray",+ "customSearchEngineName",+ "customSearchEngineUrl",+ "promotedAttributesOpenInRibbon",+ "editedNotesOpenInRibbon",+ "locale",+ "firstDayOfWeek",+ "textNoteEditorType",+ "textNoteEditorMultilineToolbar",+ "layoutOrientation",+ "backgroundEffects",+ "allowedHtmlTags" // Allow configuring HTML import tags]);function getOptions() {@@ -84,13 +84,13 @@ function getOptions() {}}- resultMap['isPasswordSet'] = optionMap['passwordVerificationHash'] ? 'true' : 'false';+ resultMap["isPasswordSet"] = optionMap["passwordVerificationHash"] ? "true" : "false";return resultMap;}function updateOption(req: Request) {- const {name, value} = req.params;+ const { name, value } = req.params;if (!update(name, value)) {throw new ValidationError("not allowed option to change");@@ -112,7 +112,7 @@ function update(name: string, value: string) {return false;}- if (name !== 'openNoteContexts') {+ if (name !== "openNoteContexts") {log.info(`Updating option '${name}' to '${value}'`);}@@ -127,14 +127,14 @@ function update(name: string, value: string) {}function getUserThemes() {- const notes = searchService.searchNotes("#appTheme", {ignoreHoistedNote: true});+ const notes = searchService.searchNotes("#appTheme", { ignoreHoistedNote: true });const ret = [];for (const note of notes) {- let value = note.getOwnedLabelValue('appTheme');+ let value = note.getOwnedLabelValue("appTheme");if (!value) {- value = note.title.toLowerCase().replace(/[^a-z0-9]/gi, '-');+ value = note.title.toLowerCase().replace(/[^a-z0-9]/gi, "-");}ret.push({@@ -155,41 +155,38 @@ function getSupportedLocales() {// TODO: Currently hardcoded, needs to read the list of available languages.return [{- "id": "en",- "name": "English"+ id: "en",+ name: "English"},{- "id": "de",- "name": "Deutsch"+ id: "de",+ name: "Deutsch"},{- "id": "es",- "name": "Español"+ id: "es",+ name: "Español"},{- "id": "fr",- "name": "Français"+ id: "fr",+ name: "Français"},{- "id": "cn",- "name": "简体中文"+ id: "cn",+ name: "简体中文"},{- "id": "tw",- "name": "繁體中文"+ id: "tw",+ name: "繁體中文"},{- "id": "ro",- "name": "Română"+ id: "ro",+ name: "Română"}];}function isAllowed(name: string) {- return ALLOWED_OPTIONS.has(name)- || name.startsWith("keyboardShortcuts")- || name.endsWith("Collapsed")- || name.startsWith("hideArchivedNotes");+ return ALLOWED_OPTIONS.has(name) || name.startsWith("keyboardShortcuts") || name.endsWith("Collapsed") || name.startsWith("hideArchivedNotes");}export default {diff --git a/src/routes/api/other.ts b/src/routes/api/other.tsindex c09b5d62d9..38fbbc280a 100644--- a/src/routes/api/other.ts+++ b/src/routes/api/other.ts@@ -6,7 +6,7 @@ import markdownService from "../../services/import/markdown.js";function getIconUsage() {const iconClassToCountMap: Record<string, number> = {};- for (const {value: iconClass, noteId} of becca.findAttributes('label', 'iconClass')) {+ for (const { value: iconClass, noteId } of becca.findAttributes("label", "iconClass")) {if (noteId.startsWith("_")) {continue; // ignore icons of "system" notes since they were not set by the user}@@ -16,7 +16,7 @@ function getIconUsage() {}for (const clazz of iconClass.trim().split(/\s+/)) {- if (clazz === 'bx') {+ if (clazz === "bx") {continue;}@@ -31,7 +31,7 @@ function renderMarkdown(req: Request) {const { markdownContent } = req.body;return {- htmlContent: markdownService.renderToHtml(markdownContent, '')+ htmlContent: markdownService.renderToHtml(markdownContent, "")};}diff --git a/src/routes/api/password.ts b/src/routes/api/password.tsindex 03721ea3e5..18f89b4930 100644--- a/src/routes/api/password.ts+++ b/src/routes/api/password.ts@@ -2,13 +2,12 @@import passwordService from "../../services/encryption/password.js";import ValidationError from "../../errors/validation_error.js";-import { Request } from 'express';+import { Request } from "express";function changePassword(req: Request) {if (passwordService.isPasswordSet()) {return passwordService.changePassword(req.body.current_password, req.body.new_password);- }- else {+ } else {return passwordService.setPassword(req.body.new_password);}}diff --git a/src/routes/api/recent_changes.ts b/src/routes/api/recent_changes.tsindex 8cf0a37c0d..4c0de24aea 100644--- a/src/routes/api/recent_changes.ts+++ b/src/routes/api/recent_changes.ts@@ -4,15 +4,15 @@ import sql from "../../services/sql.js";import protectedSessionService from "../../services/protected_session.js";import noteService from "../../services/notes.js";import becca from "../../becca/becca.js";-import { Request } from 'express';-import { RevisionRow } from '../../becca/entities/rows.js';+import { Request } from "express";+import { RevisionRow } from "../../becca/entities/rows.js";interface RecentChangeRow {noteId: string;current_isDeleted: boolean;current_deleteId: string;current_title: string;- current_isProtected: boolean,+ current_isProtected: boolean;title: string;utcDate: string;date: string;@@ -20,7 +20,7 @@ interface RecentChangeRow {}function getRecentChanges(req: Request) {- const {ancestorNoteId} = req.params;+ const { ancestorNoteId } = req.params;let recentChanges = [];@@ -42,7 +42,7 @@ function getRecentChanges(req: Request) {const note = becca.getNote(revisionRow.noteId);// for deleted notes, the becca note is null, and it's not possible to (easily) determine if it belongs to a subtree- if (ancestorNoteId === 'root' || note?.hasAncestor(ancestorNoteId)) {+ if (ancestorNoteId === "root" || note?.hasAncestor(ancestorNoteId)) {recentChanges.push(revisionRow);}}@@ -78,12 +78,12 @@ function getRecentChanges(req: Request) {const note = becca.getNote(noteRow.noteId);// for deleted notes, the becca note is null, and it's not possible to (easily) determine if it belongs to a subtree- if (ancestorNoteId === 'root' || note?.hasAncestor(ancestorNoteId)) {+ if (ancestorNoteId === "root" || note?.hasAncestor(ancestorNoteId)) {recentChanges.push(noteRow);}}- recentChanges.sort((a, b) => a.utcDate > b.utcDate ? -1 : 1);+ recentChanges.sort((a, b) => (a.utcDate > b.utcDate ? -1 : 1));recentChanges = recentChanges.slice(0, Math.min(500, recentChanges.length));@@ -92,8 +92,7 @@ function getRecentChanges(req: Request) {if (protectedSessionService.isProtectedSessionAvailable()) {change.title = protectedSessionService.decryptString(change.title) || "[protected]";change.current_title = protectedSessionService.decryptString(change.current_title) || "[protected]";- }- else {+ } else {change.title = change.current_title = "[protected]";}}diff --git a/src/routes/api/recent_notes.ts b/src/routes/api/recent_notes.tsindex 72a49f520c..2ac0216fca 100644--- a/src/routes/api/recent_notes.ts+++ b/src/routes/api/recent_notes.ts@@ -3,7 +3,7 @@import BRecentNote from "../../becca/entities/brecent_note.js";import sql from "../../services/sql.js";import dateUtils from "../../services/date_utils.js";-import { Request } from 'express';+import { Request } from "express";function addRecentNote(req: Request) {new BRecentNote({diff --git a/src/routes/api/relation-map.ts b/src/routes/api/relation-map.tsindex d24164899e..b83e5e89be 100644--- a/src/routes/api/relation-map.ts+++ b/src/routes/api/relation-map.ts@@ -1,20 +1,20 @@-import { Request } from 'express';+import { Request } from "express";import becca from "../../becca/becca.js";import sql from "../../services/sql.js";interface ResponseData {noteTitles: Record<string, string>;relations: {- attributeId: string,- sourceNoteId: string,- targetNoteId: string,- name: string+ attributeId: string;+ sourceNoteId: string;+ targetNoteId: string;+ name: string;}[];inverseRelations: Record<string, string>;}function getRelationMap(req: Request) {- const {relationMapNoteId, noteIds} = req.body;+ const { relationMapNoteId, noteIds } = req.body;const resp: ResponseData = {// noteId => title@@ -22,7 +22,7 @@ function getRelationMap(req: Request) {relations: [],// relation name => inverse relation nameinverseRelations: {- 'internalLink': 'internalLink'+ internalLink: "internalLink"}};@@ -30,19 +30,15 @@ function getRelationMap(req: Request) {return resp;}- const questionMarks = noteIds.map(noteId => '?').join(',');+ const questionMarks = noteIds.map((noteId) => "?").join(",");const relationMapNote = becca.getNoteOrThrow(relationMapNoteId);- const displayRelationsVal = relationMapNote.getLabelValue('displayRelations');- const displayRelations = !displayRelationsVal ? [] : displayRelationsVal- .split(",")- .map(token => token.trim());+ const displayRelationsVal = relationMapNote.getLabelValue("displayRelations");+ const displayRelations = !displayRelationsVal ? [] : displayRelationsVal.split(",").map((token) => token.trim());- const hideRelationsVal = relationMapNote.getLabelValue('hideRelations');- const hideRelations = !hideRelationsVal ? [] : hideRelationsVal- .split(",")- .map(token => token.trim());+ const hideRelationsVal = relationMapNote.getLabelValue("hideRelations");+ const hideRelations = !hideRelationsVal ? [] : hideRelationsVal.split(",").map((token) => token.trim());const foundNoteIds = sql.getColumn<string>(`SELECT noteId FROM notes WHERE isDeleted = 0 AND noteId IN (${questionMarks})`, noteIds);const notes = becca.getNotes(foundNoteIds);@@ -50,18 +46,19 @@ function getRelationMap(req: Request) {for (const note of notes) {resp.noteTitles[note.noteId] = note.title;- resp.relations = resp.relations.concat(note.getRelations()- .filter(relation => !relation.isAutoLink() || displayRelations.includes(relation.name))- .filter(relation => displayRelations.length > 0- ? displayRelations.includes(relation.name)- : !hideRelations.includes(relation.name))- .filter(relation => noteIds.includes(relation.value))- .map(relation => ({- attributeId: relation.attributeId,- sourceNoteId: relation.noteId,- targetNoteId: relation.value,- name: relation.name- })));+ resp.relations = resp.relations.concat(+ note+ .getRelations()+ .filter((relation) => !relation.isAutoLink() || displayRelations.includes(relation.name))+ .filter((relation) => (displayRelations.length > 0 ? displayRelations.includes(relation.name) : !hideRelations.includes(relation.name)))+ .filter((relation) => noteIds.includes(relation.value))+ .map((relation) => ({+ attributeId: relation.attributeId,+ sourceNoteId: relation.noteId,+ targetNoteId: relation.value,+ name: relation.name+ }))+ );for (const relationDefinition of note.getRelationDefinitions()) {const def = relationDefinition.getDefinition();diff --git a/src/routes/api/revisions.ts b/src/routes/api/revisions.tsindex 9dfb8824e3..39ea76a729 100644--- a/src/routes/api/revisions.ts+++ b/src/routes/api/revisions.ts@@ -9,10 +9,10 @@ import path from "path";import becca from "../../becca/becca.js";import blobService from "../../services/blob.js";import eraseService from "../../services/erase.js";-import { Request, Response } from 'express';+import { Request, Response } from "express";import BRevision from "../../becca/entities/brevision.js";import BNote from "../../becca/entities/bnote.js";-import { NotePojo } from '../../becca/becca-interface.js';+import { NotePojo } from "../../becca/becca-interface.js";interface NotePath {noteId: string;@@ -27,34 +27,36 @@ interface NotePojoWithNotePath extends NotePojo {}function getRevisionBlob(req: Request) {- const preview = req.query.preview === 'true';+ const preview = req.query.preview === "true";- return blobService.getBlobPojo('revisions', req.params.revisionId, { preview });+ return blobService.getBlobPojo("revisions", req.params.revisionId, { preview });}function getRevisions(req: Request) {- return becca.getRevisionsFromQuery(`+ return becca.getRevisionsFromQuery(+ `SELECT revisions.*,LENGTH(blobs.content) AS contentLengthFROM revisionsJOIN blobs ON revisions.blobId = blobs.blobIdWHERE revisions.noteId = ?- ORDER BY revisions.utcDateCreated DESC`, [req.params.noteId]);+ ORDER BY revisions.utcDateCreated DESC`,+ [req.params.noteId]+ );}function getRevision(req: Request) {const revision = becca.getRevisionOrThrow(req.params.revisionId);- if (revision.type === 'file') {+ if (revision.type === "file") {if (revision.hasStringContent()) {revision.content = (revision.getContent() as string).substr(0, 10000);}- }- else {+ } else {revision.content = revision.getContent();- if (revision.content && revision.type === 'image') {- revision.content = revision.content.toString('base64');+ if (revision.content && revision.type === "image") {+ revision.content = revision.content.toString("base64");}}@@ -71,13 +73,12 @@ function getRevisionFilename(revision: BRevision) {const extension = path.extname(filename);const date = revision.dateCreated.substr(0, 19)- .replace(' ', '_')- .replace(/[^0-9_]/g, '');+ .replace(" ", "_")+ .replace(/[^0-9_]/g, "");if (extension) {filename = `${filename.substr(0, filename.length - extension.length)}-${date}${extension}`;- }- else {+ } else {filename += `-${date}`;}@@ -88,22 +89,19 @@ function downloadRevision(req: Request, res: Response) {const revision = becca.getRevisionOrThrow(req.params.revisionId);if (!revision.isContentAvailable()) {- return res.setHeader("Content-Type", "text/plain")- .status(401)- .send("Protected session not available");+ return res.setHeader("Content-Type", "text/plain").status(401).send("Protected session not available");}const filename = getRevisionFilename(revision);- res.setHeader('Content-Disposition', utils.getContentDisposition(filename));- res.setHeader('Content-Type', revision.mime);+ res.setHeader("Content-Disposition", utils.getContentDisposition(filename));+ res.setHeader("Content-Type", revision.mime);res.send(revision.getContent());}function eraseAllRevisions(req: Request) {- const revisionIdsToErase = sql.getColumn<string>('SELECT revisionId FROM revisions WHERE noteId = ?',- [req.params.noteId]);+ const revisionIdsToErase = sql.getColumn<string>("SELECT revisionId FROM revisions WHERE noteId = ?", [req.params.noteId]);eraseService.eraseRevisions(revisionIdsToErase);}@@ -114,8 +112,8 @@ function eraseRevision(req: Request) {function eraseAllExcessRevisions() {let allNoteIds = sql.getRows("SELECT noteId FROM notes WHERE SUBSTRING(noteId, 1, 1) != '_'") as { noteId: string }[];- allNoteIds.forEach(row => {- becca.getNote(row.noteId)?.eraseExcessRevisionSnapshots()+ allNoteIds.forEach((row) => {+ becca.getNote(row.noteId)?.eraseExcessRevisionSnapshots();});}@@ -154,7 +152,8 @@ function restoreRevision(req: Request) {}function getEditedNotesOnDate(req: Request) {- const noteIds = sql.getColumn<string>(`+ const noteIds = sql.getColumn<string>(+ `SELECT notes.*FROM notesWHERE noteId IN (@@ -166,17 +165,19 @@ function getEditedNotesOnDate(req: Request) {WHERE revisions.dateLastEdited LIKE :date)ORDER BY isDeleted- LIMIT 50`, {date: `${req.params.date}%`});+ LIMIT 50`,+ { date: `${req.params.date}%` }+ );let notes = becca.getNotes(noteIds, true);// Narrow down the results if a note is hoisted, similar to "Jump to note".const hoistedNoteId = cls.getHoistedNoteId();- if (hoistedNoteId !== 'root') {- notes = notes.filter(note => note.hasAncestor(hoistedNoteId));+ if (hoistedNoteId !== "root") {+ notes = notes.filter((note) => note.hasAncestor(hoistedNoteId));}- return notes.map(note => {+ return notes.map((note) => {const notePath = getNotePathData(note);const notePojo: NotePojoWithNotePath = note.getPojo();@@ -184,7 +185,6 @@ function getEditedNotesOnDate(req: Request) {return notePojo;});-}function getNotePathData(note: BNote): NotePath | undefined {@@ -196,9 +196,8 @@ function getNotePathData(note: BNote): NotePath | undefined {let branchId;if (note.isRoot()) {- branchId = 'none_root';- }- else {+ branchId = "none_root";+ } else {const parentNote = note.parents[0];branchId = becca.getBranchFromChildAndParent(note.noteId, parentNote.noteId)?.branchId;}@@ -208,7 +207,7 @@ function getNotePathData(note: BNote): NotePath | undefined {branchId: branchId,title: noteTitle,notePath: retPath,- path: retPath.join('/')+ path: retPath.join("/")};}}diff --git a/src/routes/api/script.ts b/src/routes/api/script.tsindex 92aa9fc248..916a017cfe 100644--- a/src/routes/api/script.ts+++ b/src/routes/api/script.ts@@ -5,7 +5,7 @@ import attributeService from "../../services/attributes.js";import becca from "../../becca/becca.js";import syncService from "../../services/sync.js";import sql from "../../services/sql.js";-import { Request } from 'express';+import { Request } from "express";interface ScriptBody {script: string;@@ -22,28 +22,18 @@ interface ScriptBody {// this and does result.then().async function exec(req: Request) {try {- const body = (req.body as ScriptBody);+ const body = req.body as ScriptBody;- const execute = (body: ScriptBody) => scriptService.executeScript(- body.script,- body.params,- body.startNoteId,- body.currentNoteId,- body.originEntityName,- body.originEntityId- );+ const execute = (body: ScriptBody) => scriptService.executeScript(body.script, body.params, body.startNoteId, body.currentNoteId, body.originEntityName, body.originEntityId);- const result = body.transactional- ? sql.transactional(() => execute(body))- : await execute(body);+ const result = body.transactional ? sql.transactional(() => execute(body)) : await execute(body);return {success: true,executionResult: result,maxEntityChangeId: syncService.getMaxEntityChangeId()};- }- catch (e: any) {+ } catch (e: any) {return { success: false, error: e.message };}}@@ -76,12 +66,10 @@ function getStartupBundles(req: Request) {if (!process.env.TRILIUM_SAFE_MODE) {if (req.query.mobile === "true") {return getBundlesWithLabel("run", "mobileStartup");- }- else {+ } else {return getBundlesWithLabel("run", "frontendStartup");}- }- else {+ } else {return [];}}@@ -89,8 +77,7 @@ function getStartupBundles(req: Request) {function getWidgetBundles() {if (!process.env.TRILIUM_SAFE_MODE) {return getBundlesWithLabel("widget");- }- else {+ } else {return [];}}@@ -101,8 +88,8 @@ function getRelationBundles(req: Request) {const relationName = req.params.relationName;const attributes = note.getAttributes();- const filtered = attributes.filter(attr => attr.type === 'relation' && attr.name === relationName);- const targetNoteIds = filtered.map(relation => relation.value);+ const filtered = attributes.filter((attr) => attr.type === "relation" && attr.name === relationName);+ const targetNoteIds = filtered.map((relation) => relation.value);const uniqueNoteIds = Array.from(new Set(targetNoteIds));const bundles = [];@@ -110,7 +97,7 @@ function getRelationBundles(req: Request) {for (const noteId of uniqueNoteIds) {const note = becca.getNoteOrThrow(noteId);- if (!note.isJavaScript() || note.getScriptEnv() !== 'frontend') {+ if (!note.isJavaScript() || note.getScriptEnv() !== "frontend") {continue;}diff --git a/src/routes/api/search.ts b/src/routes/api/search.tsindex fbfe747669..d5d500161e 100644--- a/src/routes/api/search.ts+++ b/src/routes/api/search.ts@@ -19,7 +19,7 @@ function searchFromNote(req: Request): SearchNoteResult {return EMPTY_RESULT;}- if (note.type !== 'search') {+ if (note.type !== "search") {throw new ValidationError(`Note '${req.params.noteId}' is not a search note.`);}@@ -34,17 +34,17 @@ function searchAndExecute(req: Request) {return [];}- if (note.type !== 'search') {+ if (note.type !== "search") {throw new ValidationError(`Note '${req.params.noteId}' is not a search note.`);}- const {searchResultNoteIds} = searchService.searchFromNote(note);+ const { searchResultNoteIds } = searchService.searchFromNote(note);bulkActionService.executeActions(note, searchResultNoteIds);}function quickSearch(req: Request) {- const {searchString} = req.params;+ const { searchString } = req.params;const searchContext = new SearchContext({fastSearch: false,@@ -52,8 +52,7 @@ function quickSearch(req: Request) {fuzzyAttributeSearch: false});- const resultNoteIds = searchService.findResultsWithQuery(searchString, searchContext)- .map(sr => sr.noteId);+ const resultNoteIds = searchService.findResultsWithQuery(searchString, searchContext).map((sr) => sr.noteId);return {searchResultNoteIds: resultNoteIds,@@ -62,7 +61,7 @@ function quickSearch(req: Request) {}function search(req: Request) {- const {searchString} = req.params;+ const { searchString } = req.params;const searchContext = new SearchContext({fastSearch: false,@@ -71,8 +70,7 @@ function search(req: Request) {ignoreHoistedNote: true});- return searchService.findResultsWithQuery(searchString, searchContext)- .map(sr => sr.noteId);+ return searchService.findResultsWithQuery(searchString, searchContext).map((sr) => sr.noteId);}function getRelatedNotes(req: Request) {@@ -102,7 +100,7 @@ function getRelatedNotes(req: Request) {break;}- if (results.find(res => res.noteId === record.noteId)) {+ if (results.find((res) => res.noteId === record.noteId)) {continue;}@@ -116,14 +114,14 @@ function getRelatedNotes(req: Request) {}function searchTemplates() {- const query = cls.getHoistedNoteId() === 'root'- ? '#template'- : '#template OR #workspaceTemplate';-- return searchService.searchNotes(query, {- includeArchivedNotes: true,- ignoreHoistedNote: false- }).map(note => note.noteId);+ const query = cls.getHoistedNoteId() === "root" ? "#template" : "#template OR #workspaceTemplate";++ return searchService+ .searchNotes(query, {+ includeArchivedNotes: true,+ ignoreHoistedNote: false+ })+ .map((note) => note.noteId);}export default {diff --git a/src/routes/api/sender.ts b/src/routes/api/sender.tsindex 705cac25e8..d772989838 100644--- a/src/routes/api/sender.ts+++ b/src/routes/api/sender.ts@@ -5,7 +5,7 @@ import imageService from "../../services/image.js";import noteService from "../../services/notes.js";import sanitizeAttributeName from "../../services/sanitize_attribute_name.js";import specialNotesService from "../../services/special_notes.js";-import { Request } from 'express';+import { Request } from "express";async function uploadImage(req: Request) {const file = req.file;@@ -34,11 +34,11 @@ async function uploadImage(req: Request) {return [400, "Invalid local date"];}- const parentNote = specialNotesService.getInboxNote(req.headers['x-local-date']);+ const parentNote = specialNotesService.getInboxNote(req.headers["x-local-date"]);const { note, noteId } = imageService.saveImage(parentNote.noteId, file.buffer, originalName, true);- const labelsStr = req.headers['x-labels'];+ const labelsStr = req.headers["x-labels"];if (labelsStr?.trim()) {const labels = JSON.parse(labelsStr);@@ -60,15 +60,15 @@ function saveNote(req: Request) {return [400, "Invalid local date"];}- const parentNote = specialNotesService.getInboxNote(req.headers['x-local-date']);+ const parentNote = specialNotesService.getInboxNote(req.headers["x-local-date"]);const { note, branch } = noteService.createNewNote({parentNoteId: parentNote.noteId,title: req.body.title,content: req.body.content,isProtected: false,- type: 'text',- mime: 'text/html'+ type: "text",+ mime: "text/html"});if (req.body.labels) {diff --git a/src/routes/api/setup.ts b/src/routes/api/setup.tsindex a4a473a3ed..863247381f 100644--- a/src/routes/api/setup.ts+++ b/src/routes/api/setup.ts@@ -4,7 +4,7 @@ import sqlInit from "../../services/sql_init.js";import setupService from "../../services/setup.js";import log from "../../services/log.js";import appInfo from "../../services/app_info.js";-import { Request } from 'express';+import { Request } from "express";function getStatus() {return {@@ -32,9 +32,12 @@ function saveSyncSeed(req: Request) {log.error(message);- return [400, {- error: message- }]+ return [+ 400,+ {+ error: message+ }+ ];}log.info("Saved sync seed.");diff --git a/src/routes/api/special_notes.ts b/src/routes/api/special_notes.tsindex 5d9dc2514c..282adbc833 100644--- a/src/routes/api/special_notes.ts+++ b/src/routes/api/special_notes.ts@@ -5,7 +5,7 @@ import sql from "../../services/sql.js";import cls from "../../services/cls.js";import specialNotesService from "../../services/special_notes.js";import becca from "../../becca/becca.js";-import { Request } from 'express';+import { Request } from "express";function getInboxNote(req: Request) {return specialNotesService.getInboxNote(req.params.date);diff --git a/src/routes/api/sql.ts b/src/routes/api/sql.tsindex 703a38065f..6e9ead1e42 100644--- a/src/routes/api/sql.ts+++ b/src/routes/api/sql.ts@@ -2,7 +2,7 @@import sql from "../../services/sql.js";import becca from "../../becca/becca.js";-import { Request } from 'express';+import { Request } from "express";import ValidationError from "../../errors/validation_error.js";function getSchema() {@@ -35,9 +35,9 @@ function execute(req: Request) {for (let query of queries) {query = query.trim();- while (query.startsWith('-- ')) {+ while (query.startsWith("-- ")) {// Query starts with one or more SQL comments, discard these before we execute.- const pivot = query.indexOf('\n');+ const pivot = query.indexOf("\n");query = pivot > 0 ? query.substr(pivot + 1).trim() : "";}@@ -45,10 +45,9 @@ function execute(req: Request) {continue;}- if (query.toLowerCase().startsWith('select') || query.toLowerCase().startsWith('with')) {+ if (query.toLowerCase().startsWith("select") || query.toLowerCase().startsWith("with")) {results.push(sql.getRows(query));- }- else {+ } else {results.push(sql.execute(query));}}@@ -57,8 +56,7 @@ function execute(req: Request) {success: true,results};- }- catch (e: any) {+ } catch (e: any) {return {success: false,error: e.messagediff --git a/src/routes/api/stats.ts b/src/routes/api/stats.tsindex 769fe1c4b8..21fd728e0d 100644--- a/src/routes/api/stats.ts+++ b/src/routes/api/stats.ts@@ -1,11 +1,12 @@import sql from "../../services/sql.js";import becca from "../../becca/becca.js";-import { Request } from 'express';+import { Request } from "express";function getNoteSize(req: Request) {- const {noteId} = req.params;+ const { noteId } = req.params;- const blobSizes = sql.getMap<string, number>(`+ const blobSizes = sql.getMap<string, number>(+ `SELECT blobs.blobId, LENGTH(content)FROM blobsLEFT JOIN notes ON notes.blobId = blobs.blobId AND notes.noteId = ? AND notes.isDeleted = 0@@ -13,7 +14,9 @@ function getNoteSize(req: Request) {LEFT JOIN revisions ON revisions.blobId = blobs.blobId AND revisions.noteId = ?WHERE notes.noteId IS NOT NULLOR attachments.attachmentId IS NOT NULL- OR revisions.revisionId IS NOT NULL`, [noteId, noteId, noteId]);+ OR revisions.revisionId IS NOT NULL`,+ [noteId, noteId, noteId]+ );const noteSize = Object.values(blobSizes).reduce((acc, blobSize) => acc + blobSize, 0);diff --git a/src/routes/api/sync.ts b/src/routes/api/sync.tsindex 2f4766b295..704c6fbed4 100644--- a/src/routes/api/sync.ts+++ b/src/routes/api/sync.ts@@ -11,8 +11,8 @@ import log from "../../services/log.js";import syncOptions from "../../services/sync_options.js";import utils from "../../services/utils.js";import ws from "../../services/ws.js";-import { Request } from 'express';-import { EntityChange } from '../../services/entity_changes_interface.js';+import { Request } from "express";+import { EntityChange } from "../../services/entity_changes_interface.js";import ValidationError from "../../errors/validation_error.js";import consistencyChecksService from "../../services/consistency_checks.js";import { t } from "i18next";@@ -30,8 +30,7 @@ async function testSync() {syncService.sync();return { success: true, message: t("test_sync.successful") };- }- catch (e: any) {+ } catch (e: any) {return {success: false,message: e.message@@ -46,7 +45,7 @@ function getStats() {}const stats = {- initialized: sql.getValue("SELECT value FROM options WHERE name = 'initialized'") === 'true',+ initialized: sql.getValue("SELECT value FROM options WHERE name = 'initialized'") === "true",outstandingPullCount: syncService.getOutstandingPullCount()};@@ -58,7 +57,7 @@ function getStats() {function checkSync() {return {entityHashes: contentHashService.getEntityHashes(),- maxEntityChangeId: sql.getValue('SELECT COALESCE(MAX(id), 0) FROM entity_changes WHERE isSynced = 1')+ maxEntityChangeId: sql.getValue("SELECT COALESCE(MAX(id), 0) FROM entity_changes WHERE isSynced = 1")};}@@ -78,8 +77,8 @@ function fillEntityChanges() {}function forceFullSync() {- optionService.setOption('lastSyncedPull', 0);- optionService.setOption('lastSyncedPush', 0);+ optionService.setOption("lastSyncedPull", 0);+ optionService.setOption("lastSyncedPush", 0);log.info("Forcing full sync.");@@ -99,19 +98,22 @@ function getChanged(req: Request) {let filteredEntityChanges: EntityChange[] = [];do {- const entityChanges: EntityChange[] = sql.getRows<EntityChange>(`+ const entityChanges: EntityChange[] = sql.getRows<EntityChange>(+ `SELECT *FROM entity_changesWHERE isSynced = 1AND id > ?ORDER BY id- LIMIT 1000`, [lastEntityChangeId]);+ LIMIT 1000`,+ [lastEntityChangeId]+ );if (entityChanges.length === 0) {break;}- filteredEntityChanges = entityChanges.filter(ec => ec.instanceId !== clientInstanceId);+ filteredEntityChanges = entityChanges.filter((ec) => ec.instanceId !== clientInstanceId);if (filteredEntityChanges.length === 0) {lastEntityChangeId = entityChanges[entityChanges.length - 1].id;@@ -129,28 +131,34 @@ function getChanged(req: Request) {return {entityChanges: entityChangeRecords,lastEntityChangeId,- outstandingPullCount: sql.getValue(`+ outstandingPullCount: sql.getValue(+ `SELECT COUNT(id)FROM entity_changesWHERE isSynced = 1AND instanceId != ?- AND id > ?`, [clientInstanceId, lastEntityChangeId])+ AND id > ?`,+ [clientInstanceId, lastEntityChangeId]+ )};}-const partialRequests: Record<string, {- createdAt: number,- payload: string-}> = {};+const partialRequests: Record<+ string,+ {+ createdAt: number;+ payload: string;+ }+> = {};function update(req: Request) {let { body } = req;- const pageCount = parseInt(req.get('pageCount') as string);- const pageIndex = parseInt(req.get('pageIndex') as string);+ const pageCount = parseInt(req.get("pageCount") as string);+ const pageIndex = parseInt(req.get("pageIndex") as string);if (pageCount !== 1) {- const requestId = req.get('requestId');+ const requestId = req.get("requestId");if (!requestId) {throw new Error("Missing request ID.");}@@ -158,7 +166,7 @@ function update(req: Request) {if (pageIndex === 0) {partialRequests[requestId] = {createdAt: Date.now(),- payload: ''+ payload: ""};}@@ -172,8 +180,7 @@ function update(req: Request) {if (pageIndex !== pageCount - 1) {return;- }- else {+ } else {body = JSON.parse(partialRequests[requestId].payload);delete partialRequests[requestId];}diff --git a/src/routes/api/tree.ts b/src/routes/api/tree.tsindex f519ea4f8b..f404ff7b72 100644--- a/src/routes/api/tree.ts+++ b/src/routes/api/tree.ts@@ -3,7 +3,7 @@import becca from "../../becca/becca.js";import log from "../../services/log.js";import NotFoundError from "../../errors/not_found_error.js";-import { Request } from 'express';+import { Request } from "express";import BNote from "../../becca/entities/bnote.js";function getNotesAndBranchesAndAttributes(_noteIds: string[] | Set<string>) {@@ -37,7 +37,7 @@ function getNotesAndBranchesAndAttributes(_noteIds: string[] | Set<string>) {for (const attr of note.ownedAttributes) {collectedAttributeIds.add(attr.attributeId);- if (attr.type === 'relation' && ['template', 'inherit'].includes(attr.name) && attr.targetNote) {+ if (attr.type === "relation" && ["template", "inherit"].includes(attr.name) && attr.targetNote) {collectEntityIds(attr.targetNote);}}@@ -70,13 +70,13 @@ function getNotesAndBranchesAndAttributes(_noteIds: string[] | Set<string>) {const branches = [];- if (noteIds.has('root')) {+ if (noteIds.has("root")) {branches.push({- branchId: 'none_root',- noteId: 'root',- parentNoteId: 'none',+ branchId: "none_root",+ noteId: "root",+ parentNoteId: "none",notePosition: 0,- prefix: '',+ prefix: "",isExpanded: true});}@@ -128,7 +128,7 @@ function getNotesAndBranchesAndAttributes(_noteIds: string[] | Set<string>) {}function getTree(req: Request) {- const subTreeNoteId = typeof req.query.subTreeNoteId === "string" ? req.query.subTreeNoteId : 'root';+ const subTreeNoteId = typeof req.query.subTreeNoteId === "string" ? req.query.subTreeNoteId : "root";const collectedNoteIds = new Set<string>([subTreeNoteId]);function collect(parentNote: BNote) {diff --git a/src/routes/assets.ts b/src/routes/assets.tsindex fab3d61397..e5dccaf20a 100644--- a/src/routes/assets.ts+++ b/src/routes/assets.ts@@ -8,7 +8,7 @@ import serveStatic from "serve-static";const persistentCacheStatic = (root: string, options?: serveStatic.ServeStaticOptions<express.Response<any, Record<string, any>>>) => {if (!env.isDev()) {options = {- maxAge: '1y',+ maxAge: "1y",...options};}@@ -16,107 +16,99 @@ const persistentCacheStatic = (root: string, options?: serveStatic.ServeStaticOp};async function register(app: express.Application) {- const srcRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+ const srcRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");if (env.isDev()) {- const webpack = (await import("webpack")).default;- const webpackMiddleware = (await import("webpack-dev-middleware")).default;- const productionConfig = (await import("../../webpack.config.js")).default;-- const frontendCompiler = webpack({- mode: "development",- entry: productionConfig.entry,- module: productionConfig.module,- resolve: productionConfig.resolve,- devtool: productionConfig.devtool,- target: productionConfig.target- });-- app.use(`/${assetPath}/app`, webpackMiddleware(frontendCompiler));+ const webpack = (await import("webpack")).default;+ const webpackMiddleware = (await import("webpack-dev-middleware")).default;+ const productionConfig = (await import("../../webpack.config.js")).default;++ const frontendCompiler = webpack({+ mode: "development",+ entry: productionConfig.entry,+ module: productionConfig.module,+ resolve: productionConfig.resolve,+ devtool: productionConfig.devtool,+ target: productionConfig.target+ });++ app.use(`/${assetPath}/app`, webpackMiddleware(frontendCompiler));} else {- app.use(`/${assetPath}/app`, persistentCacheStatic(path.join(srcRoot, 'public/app')));+ app.use(`/${assetPath}/app`, persistentCacheStatic(path.join(srcRoot, "public/app")));}- app.use(`/${assetPath}/app-dist`, persistentCacheStatic(path.join(srcRoot, 'public/app-dist')));- app.use(`/${assetPath}/fonts`, persistentCacheStatic(path.join(srcRoot, 'public/fonts')));- app.use(`/assets/vX/fonts`, express.static(path.join(srcRoot, 'public/fonts')));- app.use(`/${assetPath}/images`, persistentCacheStatic(path.join(srcRoot, '..', 'images')));- app.use(`/assets/vX/images`, express.static(path.join(srcRoot, '..', 'images')));- app.use(`/${assetPath}/stylesheets`, persistentCacheStatic(path.join(srcRoot, 'public/stylesheets')));- app.use(`/assets/vX/stylesheets`, express.static(path.join(srcRoot, 'public/stylesheets')));- app.use(`/${assetPath}/libraries`, persistentCacheStatic(path.join(srcRoot, '..', 'libraries')));- app.use(`/assets/vX/libraries`, express.static(path.join(srcRoot, '..', 'libraries')));+ app.use(`/${assetPath}/app-dist`, persistentCacheStatic(path.join(srcRoot, "public/app-dist")));+ app.use(`/${assetPath}/fonts`, persistentCacheStatic(path.join(srcRoot, "public/fonts")));+ app.use(`/assets/vX/fonts`, express.static(path.join(srcRoot, "public/fonts")));+ app.use(`/${assetPath}/images`, persistentCacheStatic(path.join(srcRoot, "..", "images")));+ app.use(`/assets/vX/images`, express.static(path.join(srcRoot, "..", "images")));+ app.use(`/${assetPath}/stylesheets`, persistentCacheStatic(path.join(srcRoot, "public/stylesheets")));+ app.use(`/assets/vX/stylesheets`, express.static(path.join(srcRoot, "public/stylesheets")));+ app.use(`/${assetPath}/libraries`, persistentCacheStatic(path.join(srcRoot, "..", "libraries")));+ app.use(`/assets/vX/libraries`, express.static(path.join(srcRoot, "..", "libraries")));// excalidraw-view mode in shared notes- app.use(`/${assetPath}/node_modules/react/umd/react.production.min.js`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/react/umd/react.production.min.js')));- app.use(`/${assetPath}/node_modules/react/umd/react.development.js`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/react/umd/react.development.js')));- app.use(`/${assetPath}/node_modules/react-dom/umd/react-dom.production.min.js`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/react-dom/umd/react-dom.production.min.js')));- app.use(`/${assetPath}/node_modules/react-dom/umd/react-dom.development.js`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/react-dom/umd/react-dom.development.js')));+ app.use(`/${assetPath}/node_modules/react/umd/react.production.min.js`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/react/umd/react.production.min.js")));+ app.use(`/${assetPath}/node_modules/react/umd/react.development.js`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/react/umd/react.development.js")));+ app.use(`/${assetPath}/node_modules/react-dom/umd/react-dom.production.min.js`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/react-dom/umd/react-dom.production.min.js")));+ app.use(`/${assetPath}/node_modules/react-dom/umd/react-dom.development.js`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/react-dom/umd/react-dom.development.js")));// expose the whole dist folder since complete assets are needed in edit and share- app.use(`/node_modules/@excalidraw/excalidraw/dist/`, express.static(path.join(srcRoot, '..', 'node_modules/@excalidraw/excalidraw/dist/')));- app.use(`/${assetPath}/node_modules/@excalidraw/excalidraw/dist/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/@excalidraw/excalidraw/dist/')));+ app.use(`/node_modules/@excalidraw/excalidraw/dist/`, express.static(path.join(srcRoot, "..", "node_modules/@excalidraw/excalidraw/dist/")));+ app.use(`/${assetPath}/node_modules/@excalidraw/excalidraw/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/@excalidraw/excalidraw/dist/")));// KaTeX- app.use(- `/${assetPath}/node_modules/katex/dist/katex.min.js`,- persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/katex/dist/katex.min.js')));- app.use(- `/${assetPath}/node_modules/katex/dist/contrib/mhchem.min.js`,- persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/katex/dist/contrib/mhchem.min.js')));- app.use(- `/${assetPath}/node_modules/katex/dist/contrib/auto-render.min.js`,- persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/katex/dist/contrib/auto-render.min.js')));+ app.use(`/${assetPath}/node_modules/katex/dist/katex.min.js`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/katex/dist/katex.min.js")));+ app.use(`/${assetPath}/node_modules/katex/dist/contrib/mhchem.min.js`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/katex/dist/contrib/mhchem.min.js")));+ app.use(`/${assetPath}/node_modules/katex/dist/contrib/auto-render.min.js`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/katex/dist/contrib/auto-render.min.js")));// expose the whole dist folder- app.use(`/node_modules/katex/dist/`,- express.static(path.join(srcRoot, '..', 'node_modules/katex/dist/')));- app.use(`/${assetPath}/node_modules/katex/dist/`,- persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/katex/dist/')));+ app.use(`/node_modules/katex/dist/`, express.static(path.join(srcRoot, "..", "node_modules/katex/dist/")));+ app.use(`/${assetPath}/node_modules/katex/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/katex/dist/")));- app.use(`/${assetPath}/node_modules/dayjs/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/dayjs/')));- app.use(`/${assetPath}/node_modules/force-graph/dist/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/force-graph/dist/')));+ app.use(`/${assetPath}/node_modules/dayjs/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/dayjs/")));+ app.use(`/${assetPath}/node_modules/force-graph/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/force-graph/dist/")));- app.use(`/${assetPath}/node_modules/boxicons/css/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/boxicons/css/')));- app.use(`/${assetPath}/node_modules/boxicons/fonts/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/boxicons/fonts/')));+ app.use(`/${assetPath}/node_modules/boxicons/css/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/boxicons/css/")));+ app.use(`/${assetPath}/node_modules/boxicons/fonts/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/boxicons/fonts/")));- app.use(`/${assetPath}/node_modules/mermaid/dist/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/mermaid/dist/')));+ app.use(`/${assetPath}/node_modules/mermaid/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/mermaid/dist/")));- app.use(`/${assetPath}/node_modules/jquery/dist/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/jquery/dist/')));+ app.use(`/${assetPath}/node_modules/jquery/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/jquery/dist/")));- app.use(`/${assetPath}/node_modules/jquery-hotkeys/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/jquery-hotkeys/')));+ app.use(`/${assetPath}/node_modules/jquery-hotkeys/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/jquery-hotkeys/")));- app.use(`/${assetPath}/node_modules/print-this/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/print-this/')));+ app.use(`/${assetPath}/node_modules/print-this/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/print-this/")));- app.use(`/${assetPath}/node_modules/split.js/dist/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/split.js/dist/')));+ app.use(`/${assetPath}/node_modules/split.js/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/split.js/dist/")));- app.use(`/${assetPath}/node_modules/panzoom/dist/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/panzoom/dist/')));+ app.use(`/${assetPath}/node_modules/panzoom/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/panzoom/dist/")));// i18n- app.use(`/${assetPath}/node_modules/i18next/`, persistentCacheStatic(path.join(srcRoot, "..", 'node_modules/i18next/')));- app.use(`/${assetPath}/node_modules/i18next-http-backend/`, persistentCacheStatic(path.join(srcRoot, "..", 'node_modules/i18next-http-backend/')));+ app.use(`/${assetPath}/node_modules/i18next/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/i18next/")));+ app.use(`/${assetPath}/node_modules/i18next-http-backend/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/i18next-http-backend/")));app.use(`/${assetPath}/translations/`, persistentCacheStatic(path.join(srcRoot, "public", "translations/")));- app.use(`/${assetPath}/node_modules/eslint/bin/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/eslint/bin/')));+ app.use(`/${assetPath}/node_modules/eslint/bin/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/eslint/bin/")));- app.use(`/${assetPath}/node_modules/jsplumb/dist/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/jsplumb/dist/')));+ app.use(`/${assetPath}/node_modules/jsplumb/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/jsplumb/dist/")));- app.use(`/${assetPath}/node_modules/vanilla-js-wheel-zoom/dist/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/vanilla-js-wheel-zoom/dist/')));+ app.use(`/${assetPath}/node_modules/vanilla-js-wheel-zoom/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/vanilla-js-wheel-zoom/dist/")));- app.use(`/${assetPath}/node_modules/mark.js/dist/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/mark.js/dist/')));+ app.use(`/${assetPath}/node_modules/mark.js/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/mark.js/dist/")));// Deprecated, https://www.npmjs.com/package/autocomplete.js?activeTab=readme- app.use(`/${assetPath}/node_modules/autocomplete.js/dist/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/autocomplete.js/dist/')));+ app.use(`/${assetPath}/node_modules/autocomplete.js/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/autocomplete.js/dist/")));- app.use(`/${assetPath}/node_modules/knockout/build/output/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/knockout/build/output/')));+ app.use(`/${assetPath}/node_modules/knockout/build/output/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/knockout/build/output/")));- app.use(`/${assetPath}/node_modules/normalize.css/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/normalize.css/')));+ app.use(`/${assetPath}/node_modules/normalize.css/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/normalize.css/")));- app.use(`/${assetPath}/node_modules/jquery.fancytree/dist/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/jquery.fancytree/dist/')));+ app.use(`/${assetPath}/node_modules/jquery.fancytree/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/jquery.fancytree/dist/")));- app.use(`/${assetPath}/node_modules/bootstrap/dist/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/bootstrap/dist/')));+ app.use(`/${assetPath}/node_modules/bootstrap/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/bootstrap/dist/")));// CodeMirror- app.use(`/${assetPath}/node_modules/codemirror/lib/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/codemirror/lib/')));- app.use(`/${assetPath}/node_modules/codemirror/addon/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/codemirror/addon/')));- app.use(`/${assetPath}/node_modules/codemirror/mode/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/codemirror/mode/')));- app.use(`/${assetPath}/node_modules/codemirror/keymap/`, persistentCacheStatic(path.join(srcRoot, '..', 'node_modules/codemirror/keymap/')));+ app.use(`/${assetPath}/node_modules/codemirror/lib/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/codemirror/lib/")));+ app.use(`/${assetPath}/node_modules/codemirror/addon/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/codemirror/addon/")));+ app.use(`/${assetPath}/node_modules/codemirror/mode/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/codemirror/mode/")));+ app.use(`/${assetPath}/node_modules/codemirror/keymap/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/codemirror/keymap/")));app.use(`/${assetPath}/node_modules/mind-elixir/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/mind-elixir/dist/")));app.use(`/${assetPath}/node_modules/@mind-elixir/node-menu/dist/`, persistentCacheStatic(path.join(srcRoot, "..", "node_modules/@mind-elixir/node-menu/dist/")));diff --git a/src/routes/custom.ts b/src/routes/custom.tsindex a2e2f900ac..3d6ff93d33 100644--- a/src/routes/custom.ts+++ b/src/routes/custom.ts@@ -4,7 +4,7 @@ import scriptService from "../services/script.js";import cls from "../services/cls.js";import sql from "../services/sql.js";import becca from "../becca/becca.js";-import { Request, Response, Router } from 'express';+import { Request, Response, Router } from "express";function handleRequest(req: Request, res: Response) {// express puts content after first slash into 0 index element@@ -13,7 +13,7 @@ function handleRequest(req: Request, res: Response) {const attributeIds = sql.getColumn<string>("SELECT attributeId FROM attributes WHERE isDeleted = 0 AND type = 'label' AND name IN ('customRequestHandler', 'customResourceProvider')");- const attrs = attributeIds.map(attrId => becca.getAttribute(attrId));+ const attrs = attributeIds.map((attrId) => becca.getAttribute(attrId));for (const attr of attrs) {if (!attr?.value.trim()) {@@ -25,8 +25,7 @@ function handleRequest(req: Request, res: Response) {try {match = path.match(regex);- }- catch (e: any) {+ } catch (e: any) {log.error(`Testing path for label '${attr.attributeId}', regex '${attr.value}' failed with error: ${e.message}, stack: ${e.stack}`);continue;}@@ -35,7 +34,7 @@ function handleRequest(req: Request, res: Response) {continue;}- if (attr.name === 'customRequestHandler') {+ if (attr.name === "customRequestHandler") {const note = attr.getNote();log.info(`Handling custom request '${path}' with note '${note.noteId}'`);@@ -46,19 +45,14 @@ function handleRequest(req: Request, res: Response) {req,res});- }- catch (e: any) {+ } catch (e: any) {log.error(`Custom handler '${note.noteId}' failed with: ${e.message}, ${e.stack}`);- res.setHeader("Content-Type", "text/plain")- .status(500)- .send(e.message);+ res.setHeader("Content-Type", "text/plain").status(500).send(e.message);}- }- else if (attr.name === 'customResourceProvider') {+ } else if (attr.name === "customResourceProvider") {fileService.downloadNoteInt(attr.noteId, res);- }- else {+ } else {throw new Error(`Unrecognized attribute name '${attr.name}'`);}@@ -68,15 +62,13 @@ function handleRequest(req: Request, res: Response) {const message = `No handler matched for custom '${path}' request.`;log.info(message);- res.setHeader("Content-Type", "text/plain")- .status(404)- .send(message);+ res.setHeader("Content-Type", "text/plain").status(404).send(message);}function register(router: Router) {// explicitly no CSRF middleware since it's meant to allow integration from external services- router.all('/custom/:path*', (req: Request, res: Response, next) => {+ router.all("/custom/:path*", (req: Request, res: Response, next) => {cls.namespace.bindEmitter(req);cls.namespace.bindEmitter(res);diff --git a/src/routes/electron.ts b/src/routes/electron.tsindex 358c49e318..186ff98ad1 100644--- a/src/routes/electron.ts+++ b/src/routes/electron.ts@@ -11,7 +11,7 @@ interface Response {}function init(app: Application) {- ipcMain.on('server-request', (event, arg) => {+ ipcMain.on("server-request", (event, arg) => {const req = {url: arg.url,method: arg.method,@@ -26,7 +26,7 @@ function init(app: Application) {const res: Response = {statusCode: 200,- getHeader: name => respHeaders[name],+ getHeader: (name) => respHeaders[name],setHeader: (name, value) => {respHeaders[name] = value.toString();return res;@@ -35,12 +35,12 @@ function init(app: Application) {respHeaders[name] = value.toString();return res;},- status: statusCode => {+ status: (statusCode) => {res.statusCode = statusCode;return res;},- send: obj => {- event.sender.send('server-response', {+ send: (obj) => {+ event.sender.send("server-response", {url: arg.url,method: arg.method,requestId: arg.requestId,diff --git a/src/routes/error_handlers.ts b/src/routes/error_handlers.tsindex f121d31a6d..eb1aa0f919 100644--- a/src/routes/error_handlers.ts+++ b/src/routes/error_handlers.ts@@ -1,15 +1,15 @@-import { Application, NextFunction, Request, Response } from 'express';+import { Application, NextFunction, Request, Response } from "express";import log from "../services/log.js";function register(app: Application) {app.use((err: any, req: Request, res: Response, next: NextFunction) => {- if (err.code !== 'EBADCSRFTOKEN') {+ if (err.code !== "EBADCSRFTOKEN") {return next(err);}- log.error(`Invalid CSRF token: ${req.headers['x-csrf-token']}, secret: ${req.cookies['_csrf']}`);+ log.error(`Invalid CSRF token: ${req.headers["x-csrf-token"]}, secret: ${req.cookies["_csrf"]}`);- err = new Error('Invalid CSRF token');+ err = new Error("Invalid CSRF token");err.status = 403;next(err);});diff --git a/src/routes/index.ts b/src/routes/index.tsindex e9cde473a8..70758c2e9f 100644--- a/src/routes/index.ts+++ b/src/routes/index.ts@@ -11,18 +11,16 @@ import protectedSessionService from "../services/protected_session.js";import packageJson from "../../package.json" with { type: "json" };import assetPath from "../services/asset_path.js";import appPath from "../services/app_path.js";-import { Request, Response } from 'express';+import { Request, Response } from "express";import BNote from "../becca/entities/bnote.js";function index(req: Request, res: Response) {const options = optionService.getOptionMap();- const view = (!utils.isElectron() && req.cookies['trilium-device'] === 'mobile')- ? 'mobile'- : 'desktop';+ const view = !utils.isElectron() && req.cookies["trilium-device"] === "mobile" ? "mobile" : "desktop";const csrfToken = req.csrfToken();- log.info(`Generated CSRF token ${csrfToken} with secret ${res.getHeader('set-cookie')}`);+ log.info(`Generated CSRF token ${csrfToken} with secret ${res.getHeader("set-cookie")}`);// We force the page to not be cached since on mobile the CSRF token can be// broken when closing the browser and coming back in to the page.@@ -30,7 +28,7 @@ function index(req: Request, res: Response) {res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");const theme = options.theme;- const themeNote = attributeService.getNoteWithLabel('appTheme', theme);+ const themeNote = attributeService.getNoteWithLabel("appTheme", theme);const isElectron = utils.isElectron();res.render(view, {@@ -42,8 +40,8 @@ function index(req: Request, res: Response) {layoutOrientation: options.layoutOrientation,platform: process.platform,isElectron,- hasNativeTitleBar: (isElectron && options.nativeTitleBarVisible === "true"),- hasBackgroundEffects: (isElectron && options.backgroundEffects === "true"),+ hasNativeTitleBar: isElectron && options.nativeTitleBarVisible === "true",+ hasBackgroundEffects: isElectron && options.backgroundEffects === "true",mainFontSize: parseInt(options.mainFontSize),treeFontSize: parseInt(options.treeFontSize),detailFontSize: parseInt(options.detailFontSize),@@ -52,7 +50,7 @@ function index(req: Request, res: Response) {instanceName: config.General ? config.General.instanceName : null,appCssNoteIds: getAppCssNoteIds(),isDev: env.isDev(),- isMainWindow: (view === "mobile") ? true : !req.query.extraWindow,+ isMainWindow: view === "mobile" ? true : !req.query.extraWindow,isProtectedSessionAvailable: protectedSessionService.isProtectedSessionAvailable(),maxContentWidth: Math.max(640, parseInt(options.maxContentWidth)),triliumVersion: packageJson.version,@@ -62,12 +60,12 @@ function index(req: Request, res: Response) {}function getThemeCssUrl(theme: string, themeNote: BNote | null) {- if (theme === 'auto') {+ if (theme === "auto") {return `${assetPath}/stylesheets/theme.css`;- } else if (theme === 'light') {+ } else if (theme === "light") {// light theme is always loaded as baselinereturn false;- } else if (theme === 'dark') {+ } else if (theme === "dark") {return `${assetPath}/stylesheets/theme-dark.css`;} else if (theme === "next") {return `${assetPath}/stylesheets/theme-next.css`;@@ -84,7 +82,7 @@ function getThemeCssUrl(theme: string, themeNote: BNote | null) {}function getAppCssNoteIds() {- return attributeService.getNotesWithLabel('appCss').map(note => note.noteId);+ return attributeService.getNotesWithLabel("appCss").map((note) => note.noteId);}export default {diff --git a/src/routes/login.ts b/src/routes/login.tsindex 4af0abda3c..26a8e42806 100644--- a/src/routes/login.ts+++ b/src/routes/login.ts@@ -8,10 +8,10 @@ import passwordService from "../services/encryption/password.js";import assetPath from "../services/asset_path.js";import appPath from "../services/app_path.js";import ValidationError from "../errors/validation_error.js";-import { Request, Response } from 'express';+import { Request, Response } from "express";function loginPage(req: Request, res: Response) {- res.render('login', {+ res.render("login", {failedAuth: false,assetPath: assetPath,appPath: appPath@@ -19,7 +19,7 @@ function loginPage(req: Request, res: Response) {}function setPasswordPage(req: Request, res: Response) {- res.render('set_password', {+ res.render("set_password", {error: false,assetPath: assetPath,appPath: appPath@@ -31,7 +31,7 @@ function setPassword(req: Request, res: Response) {throw new ValidationError("Password has been already set");}- let {password1, password2} = req.body;+ let { password1, password2 } = req.body;password1 = password1.trim();password2 = password2.trim();@@ -44,7 +44,7 @@ function setPassword(req: Request, res: Response) {}if (error) {- res.render('set_password', {+ res.render("set_password", {error,assetPath: assetPath});@@ -53,7 +53,7 @@ function setPassword(req: Request, res: Response) {passwordService.setPassword(password1);- res.redirect('login');+ res.redirect("login");}function login(req: Request, res: Response) {@@ -64,20 +64,19 @@ function login(req: Request, res: Response) {req.session.regenerate(() => {if (rememberMe) {- req.session.cookie.maxAge = 21 * 24 * 3600000; // 3 weeks+ req.session.cookie.maxAge = 21 * 24 * 3600000; // 3 weeks} else {req.session.cookie.expires = null;}req.session.loggedIn = true;- res.redirect('.');+ res.redirect(".");});- }- else {+ } else {// note that logged IP address is usually meaningless since the traffic should come from a reverse proxylog.info(`WARNING: Wrong password from ${req.ip}, rejecting.`);- res.status(401).render('login', {+ res.status(401).render("login", {failedAuth: true,assetPath: assetPath});@@ -85,7 +84,7 @@ function login(req: Request, res: Response) {}function verifyPassword(guessedPassword: string) {- const hashed_password = utils.fromBase64(optionService.getOption('passwordVerificationHash'));+ const hashed_password = utils.fromBase64(optionService.getOption("passwordVerificationHash"));const guess_hashed = myScryptService.getVerificationHash(guessedPassword);@@ -96,9 +95,8 @@ function logout(req: Request, res: Response) {req.session.regenerate(() => {req.session.loggedIn = false;- res.redirect('login');+ res.redirect("login");});-}export default {diff --git a/src/routes/routes.ts b/src/routes/routes.tsindex ac26999f62..81cec2c6d5 100644--- a/src/routes/routes.ts+++ b/src/routes/routes.ts@@ -73,12 +73,16 @@ import etapiBackupRoute from "../etapi/backup.js";const csrfMiddleware = csurf({cookie: {- path: "" // empty, so cookie is valid only for the current path+ path: "" // empty, so cookie is valid only for the current path}});const MAX_ALLOWED_FILE_SIZE_MB = 250;-const GET = 'get', PST = 'post', PUT = 'put', PATCH = 'patch', DEL = 'delete';+const GET = "get",+ PST = "post",+ PUT = "put",+ PATCH = "patch",+ DEL = "delete";export type ApiResultHandler = (req: express.Request, res: express.Response, result: unknown) => number;export type ApiRequestHandler = (req: express.Request, res: express.Response, next: express.NextFunction) => unknown;@@ -90,21 +94,18 @@ const uploadMiddleware = createUploadMiddleware();const uploadMiddlewareWithErrorHandling = function (req: express.Request, res: express.Response, next: express.NextFunction) {uploadMiddleware(req, res, function (err) {- if (err?.code === 'LIMIT_FILE_SIZE') {- res.setHeader("Content-Type", "text/plain")- .status(400)- .send(`Cannot upload file because it excceeded max allowed file size of ${MAX_ALLOWED_FILE_SIZE_MB} MiB`);- }- else {+ if (err?.code === "LIMIT_FILE_SIZE") {+ res.setHeader("Content-Type", "text/plain").status(400).send(`Cannot upload file because it excceeded max allowed file size of ${MAX_ALLOWED_FILE_SIZE_MB} MiB`);+ } else {next();}});};function register(app: express.Application) {- route(GET, '/', [auth.checkAuth, csrfMiddleware], indexRoute.index);- route(GET, '/login', [auth.checkAppInitialized, auth.checkPasswordSet], loginRoute.loginPage);- route(GET, '/set-password', [auth.checkAppInitialized, auth.checkPasswordNotSet], loginRoute.setPasswordPage);+ route(GET, "/", [auth.checkAuth, csrfMiddleware], indexRoute.index);+ route(GET, "/login", [auth.checkAppInitialized, auth.checkPasswordSet], loginRoute.loginPage);+ route(GET, "/set-password", [auth.checkAppInitialized, auth.checkPasswordNotSet], loginRoute.setPasswordPage);const loginRateLimiter = rateLimit({windowMs: 15 * 60 * 1000, // 15 minutes@@ -112,244 +113,253 @@ function register(app: express.Application) {skipSuccessfulRequests: true // successful auth to rate-limited ETAPI routes isn't counted. However, successful auth to /login is still counted!});- route(PST, '/login', [loginRateLimiter], loginRoute.login);- route(PST, '/logout', [csrfMiddleware, auth.checkAuth], loginRoute.logout);- route(PST, '/set-password', [auth.checkAppInitialized, auth.checkPasswordNotSet], loginRoute.setPassword);- route(GET, '/setup', [], setupRoute.setupPage);-- apiRoute(GET, '/api/tree', treeApiRoute.getTree);- apiRoute(PST, '/api/tree/load', treeApiRoute.load);-- apiRoute(GET, '/api/notes/:noteId', notesApiRoute.getNote);- apiRoute(GET, '/api/notes/:noteId/blob', notesApiRoute.getNoteBlob);- apiRoute(GET, '/api/notes/:noteId/metadata', notesApiRoute.getNoteMetadata);- apiRoute(PUT, '/api/notes/:noteId/data', notesApiRoute.updateNoteData);- apiRoute(DEL, '/api/notes/:noteId', notesApiRoute.deleteNote);- apiRoute(PUT, '/api/notes/:noteId/undelete', notesApiRoute.undeleteNote);- apiRoute(PST, '/api/notes/:noteId/revision', notesApiRoute.forceSaveRevision);- apiRoute(PST, '/api/notes/:parentNoteId/children', notesApiRoute.createNote);- apiRoute(PUT, '/api/notes/:noteId/sort-children', notesApiRoute.sortChildNotes);- apiRoute(PUT, '/api/notes/:noteId/protect/:isProtected', notesApiRoute.protectNote);- apiRoute(PUT, '/api/notes/:noteId/type', notesApiRoute.setNoteTypeMime);- apiRoute(PUT, '/api/notes/:noteId/title', notesApiRoute.changeTitle);- apiRoute(PST, '/api/notes/:noteId/duplicate/:parentNoteId', notesApiRoute.duplicateSubtree);- apiRoute(PUT, '/api/notes/:noteId/clone-to-branch/:parentBranchId', cloningApiRoute.cloneNoteToBranch);- apiRoute(PUT, '/api/notes/:noteId/toggle-in-parent/:parentNoteId/:present', cloningApiRoute.toggleNoteInParent);- apiRoute(PUT, '/api/notes/:noteId/clone-to-note/:parentNoteId', cloningApiRoute.cloneNoteToParentNote);- apiRoute(PUT, '/api/notes/:noteId/clone-after/:afterBranchId', cloningApiRoute.cloneNoteAfter);- route(PUT, '/api/notes/:noteId/file', [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware],- filesRoute.updateFile, apiResultHandler);- route(GET, '/api/notes/:noteId/open', [auth.checkApiAuthOrElectron], filesRoute.openFile);- route(GET, '/api/notes/:noteId/open-partial', [auth.checkApiAuthOrElectron],+ route(PST, "/login", [loginRateLimiter], loginRoute.login);+ route(PST, "/logout", [csrfMiddleware, auth.checkAuth], loginRoute.logout);+ route(PST, "/set-password", [auth.checkAppInitialized, auth.checkPasswordNotSet], loginRoute.setPassword);+ route(GET, "/setup", [], setupRoute.setupPage);++ apiRoute(GET, "/api/tree", treeApiRoute.getTree);+ apiRoute(PST, "/api/tree/load", treeApiRoute.load);++ apiRoute(GET, "/api/notes/:noteId", notesApiRoute.getNote);+ apiRoute(GET, "/api/notes/:noteId/blob", notesApiRoute.getNoteBlob);+ apiRoute(GET, "/api/notes/:noteId/metadata", notesApiRoute.getNoteMetadata);+ apiRoute(PUT, "/api/notes/:noteId/data", notesApiRoute.updateNoteData);+ apiRoute(DEL, "/api/notes/:noteId", notesApiRoute.deleteNote);+ apiRoute(PUT, "/api/notes/:noteId/undelete", notesApiRoute.undeleteNote);+ apiRoute(PST, "/api/notes/:noteId/revision", notesApiRoute.forceSaveRevision);+ apiRoute(PST, "/api/notes/:parentNoteId/children", notesApiRoute.createNote);+ apiRoute(PUT, "/api/notes/:noteId/sort-children", notesApiRoute.sortChildNotes);+ apiRoute(PUT, "/api/notes/:noteId/protect/:isProtected", notesApiRoute.protectNote);+ apiRoute(PUT, "/api/notes/:noteId/type", notesApiRoute.setNoteTypeMime);+ apiRoute(PUT, "/api/notes/:noteId/title", notesApiRoute.changeTitle);+ apiRoute(PST, "/api/notes/:noteId/duplicate/:parentNoteId", notesApiRoute.duplicateSubtree);+ apiRoute(PUT, "/api/notes/:noteId/clone-to-branch/:parentBranchId", cloningApiRoute.cloneNoteToBranch);+ apiRoute(PUT, "/api/notes/:noteId/toggle-in-parent/:parentNoteId/:present", cloningApiRoute.toggleNoteInParent);+ apiRoute(PUT, "/api/notes/:noteId/clone-to-note/:parentNoteId", cloningApiRoute.cloneNoteToParentNote);+ apiRoute(PUT, "/api/notes/:noteId/clone-after/:afterBranchId", cloningApiRoute.cloneNoteAfter);+ route(PUT, "/api/notes/:noteId/file", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], filesRoute.updateFile, apiResultHandler);+ route(GET, "/api/notes/:noteId/open", [auth.checkApiAuthOrElectron], filesRoute.openFile);+ route(+ GET,+ "/api/notes/:noteId/open-partial",+ [auth.checkApiAuthOrElectron],createPartialContentHandler(filesRoute.fileContentProvider, {- debug: (string, extra) => { console.log(string, extra); }- }));- route(GET, '/api/notes/:noteId/download', [auth.checkApiAuthOrElectron], filesRoute.downloadFile);+ debug: (string, extra) => {+ console.log(string, extra);+ }+ })+ );+ route(GET, "/api/notes/:noteId/download", [auth.checkApiAuthOrElectron], filesRoute.downloadFile);// this "hacky" path is used for easier referencing of CSS resources- route(GET, '/api/notes/download/:noteId', [auth.checkApiAuthOrElectron], filesRoute.downloadFile);- apiRoute(PST, '/api/notes/:noteId/save-to-tmp-dir', filesRoute.saveNoteToTmpDir);- apiRoute(PST, '/api/notes/:noteId/upload-modified-file', filesRoute.uploadModifiedFileToNote);- apiRoute(PST, '/api/notes/:noteId/convert-to-attachment', notesApiRoute.convertNoteToAttachment);-- apiRoute(PUT, '/api/branches/:branchId/move-to/:parentBranchId', branchesApiRoute.moveBranchToParent);- apiRoute(PUT, '/api/branches/:branchId/move-before/:beforeBranchId', branchesApiRoute.moveBranchBeforeNote);- apiRoute(PUT, '/api/branches/:branchId/move-after/:afterBranchId', branchesApiRoute.moveBranchAfterNote);- apiRoute(PUT, '/api/branches/:branchId/expanded/:expanded', branchesApiRoute.setExpanded);- apiRoute(PUT, '/api/branches/:branchId/expanded-subtree/:expanded', branchesApiRoute.setExpandedForSubtree);- apiRoute(DEL, '/api/branches/:branchId', branchesApiRoute.deleteBranch);- apiRoute(PUT, '/api/branches/:branchId/set-prefix', branchesApiRoute.setPrefix);-- apiRoute(GET, '/api/notes/:noteId/attachments', attachmentsApiRoute.getAttachments);- apiRoute(PST, '/api/notes/:noteId/attachments', attachmentsApiRoute.saveAttachment);- route(PST, '/api/notes/:noteId/attachments/upload', [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], attachmentsApiRoute.uploadAttachment, apiResultHandler);- apiRoute(GET, '/api/attachments/:attachmentId', attachmentsApiRoute.getAttachment);- apiRoute(GET, '/api/attachments/:attachmentId/all', attachmentsApiRoute.getAllAttachments);- apiRoute(PST, '/api/attachments/:attachmentId/convert-to-note', attachmentsApiRoute.convertAttachmentToNote);- apiRoute(DEL, '/api/attachments/:attachmentId', attachmentsApiRoute.deleteAttachment);- apiRoute(PUT, '/api/attachments/:attachmentId/rename', attachmentsApiRoute.renameAttachment);- apiRoute(GET, '/api/attachments/:attachmentId/blob', attachmentsApiRoute.getAttachmentBlob);- route(GET, '/api/attachments/:attachmentId/image/:filename', [auth.checkApiAuthOrElectron], imageRoute.returnAttachedImage);- route(GET, '/api/attachments/:attachmentId/open', [auth.checkApiAuthOrElectron], filesRoute.openAttachment);- route(GET, '/api/attachments/:attachmentId/open-partial', [auth.checkApiAuthOrElectron],+ route(GET, "/api/notes/download/:noteId", [auth.checkApiAuthOrElectron], filesRoute.downloadFile);+ apiRoute(PST, "/api/notes/:noteId/save-to-tmp-dir", filesRoute.saveNoteToTmpDir);+ apiRoute(PST, "/api/notes/:noteId/upload-modified-file", filesRoute.uploadModifiedFileToNote);+ apiRoute(PST, "/api/notes/:noteId/convert-to-attachment", notesApiRoute.convertNoteToAttachment);++ apiRoute(PUT, "/api/branches/:branchId/move-to/:parentBranchId", branchesApiRoute.moveBranchToParent);+ apiRoute(PUT, "/api/branches/:branchId/move-before/:beforeBranchId", branchesApiRoute.moveBranchBeforeNote);+ apiRoute(PUT, "/api/branches/:branchId/move-after/:afterBranchId", branchesApiRoute.moveBranchAfterNote);+ apiRoute(PUT, "/api/branches/:branchId/expanded/:expanded", branchesApiRoute.setExpanded);+ apiRoute(PUT, "/api/branches/:branchId/expanded-subtree/:expanded", branchesApiRoute.setExpandedForSubtree);+ apiRoute(DEL, "/api/branches/:branchId", branchesApiRoute.deleteBranch);+ apiRoute(PUT, "/api/branches/:branchId/set-prefix", branchesApiRoute.setPrefix);++ apiRoute(GET, "/api/notes/:noteId/attachments", attachmentsApiRoute.getAttachments);+ apiRoute(PST, "/api/notes/:noteId/attachments", attachmentsApiRoute.saveAttachment);+ route(PST, "/api/notes/:noteId/attachments/upload", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], attachmentsApiRoute.uploadAttachment, apiResultHandler);+ apiRoute(GET, "/api/attachments/:attachmentId", attachmentsApiRoute.getAttachment);+ apiRoute(GET, "/api/attachments/:attachmentId/all", attachmentsApiRoute.getAllAttachments);+ apiRoute(PST, "/api/attachments/:attachmentId/convert-to-note", attachmentsApiRoute.convertAttachmentToNote);+ apiRoute(DEL, "/api/attachments/:attachmentId", attachmentsApiRoute.deleteAttachment);+ apiRoute(PUT, "/api/attachments/:attachmentId/rename", attachmentsApiRoute.renameAttachment);+ apiRoute(GET, "/api/attachments/:attachmentId/blob", attachmentsApiRoute.getAttachmentBlob);+ route(GET, "/api/attachments/:attachmentId/image/:filename", [auth.checkApiAuthOrElectron], imageRoute.returnAttachedImage);+ route(GET, "/api/attachments/:attachmentId/open", [auth.checkApiAuthOrElectron], filesRoute.openAttachment);+ route(+ GET,+ "/api/attachments/:attachmentId/open-partial",+ [auth.checkApiAuthOrElectron],createPartialContentHandler(filesRoute.attachmentContentProvider, {- debug: (string, extra) => { console.log(string, extra); }- }));- route(GET, '/api/attachments/:attachmentId/download', [auth.checkApiAuthOrElectron], filesRoute.downloadAttachment);+ debug: (string, extra) => {+ console.log(string, extra);+ }+ })+ );+ route(GET, "/api/attachments/:attachmentId/download", [auth.checkApiAuthOrElectron], filesRoute.downloadAttachment);// this "hacky" path is used for easier referencing of CSS resources- route(GET, '/api/attachments/download/:attachmentId', [auth.checkApiAuthOrElectron], filesRoute.downloadAttachment);- apiRoute(PST, '/api/attachments/:attachmentId/save-to-tmp-dir', filesRoute.saveAttachmentToTmpDir);- apiRoute(PST, '/api/attachments/:attachmentId/upload-modified-file', filesRoute.uploadModifiedFileToAttachment);- route(PUT, '/api/attachments/:attachmentId/file', [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware],- filesRoute.updateAttachment, apiResultHandler);-- apiRoute(GET, '/api/notes/:noteId/revisions', revisionsApiRoute.getRevisions);- apiRoute(DEL, '/api/notes/:noteId/revisions', revisionsApiRoute.eraseAllRevisions);- apiRoute(PST, '/api/revisions/erase-all-excess-revisions', revisionsApiRoute.eraseAllExcessRevisions);- apiRoute(GET, '/api/revisions/:revisionId', revisionsApiRoute.getRevision);- apiRoute(GET, '/api/revisions/:revisionId/blob', revisionsApiRoute.getRevisionBlob);- apiRoute(DEL, '/api/revisions/:revisionId', revisionsApiRoute.eraseRevision);- apiRoute(PST, '/api/revisions/:revisionId/restore', revisionsApiRoute.restoreRevision);- route(GET, '/api/revisions/:revisionId/image/:filename', [auth.checkApiAuthOrElectron], imageRoute.returnImageFromRevision);-- route(GET, '/api/revisions/:revisionId/download', [auth.checkApiAuthOrElectron], revisionsApiRoute.downloadRevision);--- route(GET, '/api/branches/:branchId/export/:type/:format/:version/:taskId', [auth.checkApiAuthOrElectron], exportRoute.exportBranch);- route(PST, '/api/notes/:parentNoteId/notes-import', [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importNotesToBranch, apiResultHandler);- route(PST, '/api/notes/:parentNoteId/attachments-import', [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importAttachmentsToNote, apiResultHandler);-- apiRoute(GET, '/api/notes/:noteId/attributes', attributesRoute.getEffectiveNoteAttributes);- apiRoute(PST, '/api/notes/:noteId/attributes', attributesRoute.addNoteAttribute);- apiRoute(PUT, '/api/notes/:noteId/attributes', attributesRoute.updateNoteAttributes);- apiRoute(PUT, '/api/notes/:noteId/attribute', attributesRoute.updateNoteAttribute);- apiRoute(PUT, '/api/notes/:noteId/set-attribute', attributesRoute.setNoteAttribute);- apiRoute(PUT, '/api/notes/:noteId/relations/:name/to/:targetNoteId', attributesRoute.createRelation);- apiRoute(DEL, '/api/notes/:noteId/relations/:name/to/:targetNoteId', attributesRoute.deleteRelation);- apiRoute(DEL, '/api/notes/:noteId/attributes/:attributeId', attributesRoute.deleteNoteAttribute);- apiRoute(GET, '/api/attribute-names', attributesRoute.getAttributeNames);- apiRoute(GET, '/api/attribute-values/:attributeName', attributesRoute.getValuesForAttribute);+ route(GET, "/api/attachments/download/:attachmentId", [auth.checkApiAuthOrElectron], filesRoute.downloadAttachment);+ apiRoute(PST, "/api/attachments/:attachmentId/save-to-tmp-dir", filesRoute.saveAttachmentToTmpDir);+ apiRoute(PST, "/api/attachments/:attachmentId/upload-modified-file", filesRoute.uploadModifiedFileToAttachment);+ route(PUT, "/api/attachments/:attachmentId/file", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], filesRoute.updateAttachment, apiResultHandler);++ apiRoute(GET, "/api/notes/:noteId/revisions", revisionsApiRoute.getRevisions);+ apiRoute(DEL, "/api/notes/:noteId/revisions", revisionsApiRoute.eraseAllRevisions);+ apiRoute(PST, "/api/revisions/erase-all-excess-revisions", revisionsApiRoute.eraseAllExcessRevisions);+ apiRoute(GET, "/api/revisions/:revisionId", revisionsApiRoute.getRevision);+ apiRoute(GET, "/api/revisions/:revisionId/blob", revisionsApiRoute.getRevisionBlob);+ apiRoute(DEL, "/api/revisions/:revisionId", revisionsApiRoute.eraseRevision);+ apiRoute(PST, "/api/revisions/:revisionId/restore", revisionsApiRoute.restoreRevision);+ route(GET, "/api/revisions/:revisionId/image/:filename", [auth.checkApiAuthOrElectron], imageRoute.returnImageFromRevision);++ route(GET, "/api/revisions/:revisionId/download", [auth.checkApiAuthOrElectron], revisionsApiRoute.downloadRevision);++ route(GET, "/api/branches/:branchId/export/:type/:format/:version/:taskId", [auth.checkApiAuthOrElectron], exportRoute.exportBranch);+ route(PST, "/api/notes/:parentNoteId/notes-import", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importNotesToBranch, apiResultHandler);+ route(PST, "/api/notes/:parentNoteId/attachments-import", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], importRoute.importAttachmentsToNote, apiResultHandler);++ apiRoute(GET, "/api/notes/:noteId/attributes", attributesRoute.getEffectiveNoteAttributes);+ apiRoute(PST, "/api/notes/:noteId/attributes", attributesRoute.addNoteAttribute);+ apiRoute(PUT, "/api/notes/:noteId/attributes", attributesRoute.updateNoteAttributes);+ apiRoute(PUT, "/api/notes/:noteId/attribute", attributesRoute.updateNoteAttribute);+ apiRoute(PUT, "/api/notes/:noteId/set-attribute", attributesRoute.setNoteAttribute);+ apiRoute(PUT, "/api/notes/:noteId/relations/:name/to/:targetNoteId", attributesRoute.createRelation);+ apiRoute(DEL, "/api/notes/:noteId/relations/:name/to/:targetNoteId", attributesRoute.deleteRelation);+ apiRoute(DEL, "/api/notes/:noteId/attributes/:attributeId", attributesRoute.deleteNoteAttribute);+ apiRoute(GET, "/api/attribute-names", attributesRoute.getAttributeNames);+ apiRoute(GET, "/api/attribute-values/:attributeName", attributesRoute.getValuesForAttribute);// :filename is not used by trilium, but instead used for "save as" to assign a human-readable filename- route(GET, '/api/images/:noteId/:filename', [auth.checkApiAuthOrElectron], imageRoute.returnImageFromNote);- route(PUT, '/api/images/:noteId', [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], imageRoute.updateImage, apiResultHandler);+ route(GET, "/api/images/:noteId/:filename", [auth.checkApiAuthOrElectron], imageRoute.returnImageFromNote);+ route(PUT, "/api/images/:noteId", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], imageRoute.updateImage, apiResultHandler);- apiRoute(GET, '/api/options', optionsApiRoute.getOptions);+ apiRoute(GET, "/api/options", optionsApiRoute.getOptions);// FIXME: possibly change to sending value in the body to avoid host of HTTP server issues with slashes- apiRoute(PUT, '/api/options/:name/:value*', optionsApiRoute.updateOption);- apiRoute(PUT, '/api/options', optionsApiRoute.updateOptions);- apiRoute(GET, '/api/options/user-themes', optionsApiRoute.getUserThemes);- apiRoute(GET, '/api/options/codeblock-themes', optionsApiRoute.getSyntaxHighlightingThemes);- apiRoute(GET, '/api/options/locales', optionsApiRoute.getSupportedLocales);-- apiRoute(PST, '/api/password/change', passwordApiRoute.changePassword);- apiRoute(PST, '/api/password/reset', passwordApiRoute.resetPassword);-- apiRoute(PST, '/api/sync/test', syncApiRoute.testSync);- apiRoute(PST, '/api/sync/now', syncApiRoute.syncNow);- apiRoute(PST, '/api/sync/fill-entity-changes', syncApiRoute.fillEntityChanges);- apiRoute(PST, '/api/sync/force-full-sync', syncApiRoute.forceFullSync);- route(GET, '/api/sync/check', [auth.checkApiAuth], syncApiRoute.checkSync, apiResultHandler);- route(GET, '/api/sync/changed', [auth.checkApiAuth], syncApiRoute.getChanged, apiResultHandler);- route(PUT, '/api/sync/update', [auth.checkApiAuth], syncApiRoute.update, apiResultHandler);- route(PST, '/api/sync/finished', [auth.checkApiAuth], syncApiRoute.syncFinished, apiResultHandler);- route(PST, '/api/sync/check-entity-changes', [auth.checkApiAuth], syncApiRoute.checkEntityChanges, apiResultHandler);- route(PST, '/api/sync/queue-sector/:entityName/:sector', [auth.checkApiAuth], syncApiRoute.queueSector, apiResultHandler);- route(GET, '/api/sync/stats', [], syncApiRoute.getStats, apiResultHandler);-- apiRoute(PST, '/api/recent-notes', recentNotesRoute.addRecentNote);- apiRoute(GET, '/api/app-info', appInfoRoute.getAppInfo);+ apiRoute(PUT, "/api/options/:name/:value*", optionsApiRoute.updateOption);+ apiRoute(PUT, "/api/options", optionsApiRoute.updateOptions);+ apiRoute(GET, "/api/options/user-themes", optionsApiRoute.getUserThemes);+ apiRoute(GET, "/api/options/codeblock-themes", optionsApiRoute.getSyntaxHighlightingThemes);+ apiRoute(GET, "/api/options/locales", optionsApiRoute.getSupportedLocales);++ apiRoute(PST, "/api/password/change", passwordApiRoute.changePassword);+ apiRoute(PST, "/api/password/reset", passwordApiRoute.resetPassword);++ apiRoute(PST, "/api/sync/test", syncApiRoute.testSync);+ apiRoute(PST, "/api/sync/now", syncApiRoute.syncNow);+ apiRoute(PST, "/api/sync/fill-entity-changes", syncApiRoute.fillEntityChanges);+ apiRoute(PST, "/api/sync/force-full-sync", syncApiRoute.forceFullSync);+ route(GET, "/api/sync/check", [auth.checkApiAuth], syncApiRoute.checkSync, apiResultHandler);+ route(GET, "/api/sync/changed", [auth.checkApiAuth], syncApiRoute.getChanged, apiResultHandler);+ route(PUT, "/api/sync/update", [auth.checkApiAuth], syncApiRoute.update, apiResultHandler);+ route(PST, "/api/sync/finished", [auth.checkApiAuth], syncApiRoute.syncFinished, apiResultHandler);+ route(PST, "/api/sync/check-entity-changes", [auth.checkApiAuth], syncApiRoute.checkEntityChanges, apiResultHandler);+ route(PST, "/api/sync/queue-sector/:entityName/:sector", [auth.checkApiAuth], syncApiRoute.queueSector, apiResultHandler);+ route(GET, "/api/sync/stats", [], syncApiRoute.getStats, apiResultHandler);++ apiRoute(PST, "/api/recent-notes", recentNotesRoute.addRecentNote);+ apiRoute(GET, "/api/app-info", appInfoRoute.getAppInfo);// docker health check- route(GET, '/api/health-check', [], () => ({ "status": "ok" }), apiResultHandler);+ route(GET, "/api/health-check", [], () => ({ status: "ok" }), apiResultHandler);// group of the services below are meant to be executed from the outside- route(GET, '/api/setup/status', [], setupApiRoute.getStatus, apiResultHandler);- route(PST, '/api/setup/new-document', [auth.checkAppNotInitialized], setupApiRoute.setupNewDocument, apiResultHandler, false);- route(PST, '/api/setup/sync-from-server', [auth.checkAppNotInitialized], setupApiRoute.setupSyncFromServer, apiResultHandler, false);- route(GET, '/api/setup/sync-seed', [auth.checkCredentials], setupApiRoute.getSyncSeed, apiResultHandler);- route(PST, '/api/setup/sync-seed', [auth.checkAppNotInitialized], setupApiRoute.saveSyncSeed, apiResultHandler, false);-- apiRoute(GET, '/api/autocomplete', autocompleteApiRoute.getAutocomplete);- apiRoute(GET, '/api/quick-search/:searchString', searchRoute.quickSearch);- apiRoute(GET, '/api/search-note/:noteId', searchRoute.searchFromNote);- apiRoute(PST, '/api/search-and-execute-note/:noteId', searchRoute.searchAndExecute);- apiRoute(PST, '/api/search-related', searchRoute.getRelatedNotes);- apiRoute(GET, '/api/search/:searchString', searchRoute.search);- apiRoute(GET, '/api/search-templates', searchRoute.searchTemplates);-- apiRoute(PST, '/api/bulk-action/execute', bulkActionRoute.execute);- apiRoute(PST, '/api/bulk-action/affected-notes', bulkActionRoute.getAffectedNoteCount);-- route(PST, '/api/login/sync', [], loginApiRoute.loginSync, apiResultHandler);+ route(GET, "/api/setup/status", [], setupApiRoute.getStatus, apiResultHandler);+ route(PST, "/api/setup/new-document", [auth.checkAppNotInitialized], setupApiRoute.setupNewDocument, apiResultHandler, false);+ route(PST, "/api/setup/sync-from-server", [auth.checkAppNotInitialized], setupApiRoute.setupSyncFromServer, apiResultHandler, false);+ route(GET, "/api/setup/sync-seed", [auth.checkCredentials], setupApiRoute.getSyncSeed, apiResultHandler);+ route(PST, "/api/setup/sync-seed", [auth.checkAppNotInitialized], setupApiRoute.saveSyncSeed, apiResultHandler, false);++ apiRoute(GET, "/api/autocomplete", autocompleteApiRoute.getAutocomplete);+ apiRoute(GET, "/api/quick-search/:searchString", searchRoute.quickSearch);+ apiRoute(GET, "/api/search-note/:noteId", searchRoute.searchFromNote);+ apiRoute(PST, "/api/search-and-execute-note/:noteId", searchRoute.searchAndExecute);+ apiRoute(PST, "/api/search-related", searchRoute.getRelatedNotes);+ apiRoute(GET, "/api/search/:searchString", searchRoute.search);+ apiRoute(GET, "/api/search-templates", searchRoute.searchTemplates);++ apiRoute(PST, "/api/bulk-action/execute", bulkActionRoute.execute);+ apiRoute(PST, "/api/bulk-action/affected-notes", bulkActionRoute.getAffectedNoteCount);++ route(PST, "/api/login/sync", [], loginApiRoute.loginSync, apiResultHandler);// this is for entering protected mode so user has to be already logged-in (that's the reason we don't require username)- apiRoute(PST, '/api/login/protected', loginApiRoute.loginToProtectedSession);- apiRoute(PST, '/api/login/protected/touch', loginApiRoute.touchProtectedSession);- apiRoute(PST, '/api/logout/protected', loginApiRoute.logoutFromProtectedSession);+ apiRoute(PST, "/api/login/protected", loginApiRoute.loginToProtectedSession);+ apiRoute(PST, "/api/login/protected/touch", loginApiRoute.touchProtectedSession);+ apiRoute(PST, "/api/logout/protected", loginApiRoute.logoutFromProtectedSession);- route(PST, '/api/login/token', [loginRateLimiter], loginApiRoute.token, apiResultHandler);+ route(PST, "/api/login/token", [loginRateLimiter], loginApiRoute.token, apiResultHandler);- apiRoute(GET, '/api/etapi-tokens', etapiTokensApiRoutes.getTokens);- apiRoute(PST, '/api/etapi-tokens', etapiTokensApiRoutes.createToken);- apiRoute(PATCH, '/api/etapi-tokens/:etapiTokenId', etapiTokensApiRoutes.patchToken);- apiRoute(DEL, '/api/etapi-tokens/:etapiTokenId', etapiTokensApiRoutes.deleteToken);+ apiRoute(GET, "/api/etapi-tokens", etapiTokensApiRoutes.getTokens);+ apiRoute(PST, "/api/etapi-tokens", etapiTokensApiRoutes.createToken);+ apiRoute(PATCH, "/api/etapi-tokens/:etapiTokenId", etapiTokensApiRoutes.patchToken);+ apiRoute(DEL, "/api/etapi-tokens/:etapiTokenId", etapiTokensApiRoutes.deleteToken);// in case of local electron, local calls are allowed unauthenticated, for server they need authconst clipperMiddleware = utils.isElectron() ? [] : [auth.checkEtapiToken];- route(GET, '/api/clipper/handshake', clipperMiddleware, clipperRoute.handshake, apiResultHandler);- route(PST, '/api/clipper/clippings', clipperMiddleware, clipperRoute.addClipping, apiResultHandler);- route(PST, '/api/clipper/notes', clipperMiddleware, clipperRoute.createNote, apiResultHandler);- route(PST, '/api/clipper/open/:noteId', clipperMiddleware, clipperRoute.openNote, apiResultHandler);- route(GET, '/api/clipper/notes-by-url/:noteUrl', clipperMiddleware, clipperRoute.findNotesByUrl, apiResultHandler);-- apiRoute(GET, '/api/special-notes/inbox/:date', specialNotesRoute.getInboxNote);- apiRoute(GET, '/api/special-notes/days/:date', specialNotesRoute.getDayNote);- apiRoute(GET, '/api/special-notes/weeks/:date', specialNotesRoute.getWeekNote);- apiRoute(GET, '/api/special-notes/months/:month', specialNotesRoute.getMonthNote);- apiRoute(GET, '/api/special-notes/years/:year', specialNotesRoute.getYearNote);- apiRoute(GET, '/api/special-notes/notes-for-month/:month', specialNotesRoute.getDayNotesForMonth);- apiRoute(PST, '/api/special-notes/sql-console', specialNotesRoute.createSqlConsole);- apiRoute(PST, '/api/special-notes/save-sql-console', specialNotesRoute.saveSqlConsole);- apiRoute(PST, '/api/special-notes/search-note', specialNotesRoute.createSearchNote);- apiRoute(PST, '/api/special-notes/save-search-note', specialNotesRoute.saveSearchNote);- apiRoute(PST, '/api/special-notes/launchers/:noteId/reset', specialNotesRoute.resetLauncher);- apiRoute(PST, '/api/special-notes/launchers/:parentNoteId/:launcherType', specialNotesRoute.createLauncher);- apiRoute(PUT, '/api/special-notes/api-script-launcher', specialNotesRoute.createOrUpdateScriptLauncherFromApi);-- apiRoute(GET, '/api/sql/schema', sqlRoute.getSchema);- apiRoute(PST, '/api/sql/execute/:noteId', sqlRoute.execute);- route(PST, '/api/database/anonymize/:type', [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.anonymize, apiResultHandler, false);- apiRoute(GET, '/api/database/anonymized-databases', databaseRoute.getExistingAnonymizedDatabases);+ route(GET, "/api/clipper/handshake", clipperMiddleware, clipperRoute.handshake, apiResultHandler);+ route(PST, "/api/clipper/clippings", clipperMiddleware, clipperRoute.addClipping, apiResultHandler);+ route(PST, "/api/clipper/notes", clipperMiddleware, clipperRoute.createNote, apiResultHandler);+ route(PST, "/api/clipper/open/:noteId", clipperMiddleware, clipperRoute.openNote, apiResultHandler);+ route(GET, "/api/clipper/notes-by-url/:noteUrl", clipperMiddleware, clipperRoute.findNotesByUrl, apiResultHandler);++ apiRoute(GET, "/api/special-notes/inbox/:date", specialNotesRoute.getInboxNote);+ apiRoute(GET, "/api/special-notes/days/:date", specialNotesRoute.getDayNote);+ apiRoute(GET, "/api/special-notes/weeks/:date", specialNotesRoute.getWeekNote);+ apiRoute(GET, "/api/special-notes/months/:month", specialNotesRoute.getMonthNote);+ apiRoute(GET, "/api/special-notes/years/:year", specialNotesRoute.getYearNote);+ apiRoute(GET, "/api/special-notes/notes-for-month/:month", specialNotesRoute.getDayNotesForMonth);+ apiRoute(PST, "/api/special-notes/sql-console", specialNotesRoute.createSqlConsole);+ apiRoute(PST, "/api/special-notes/save-sql-console", specialNotesRoute.saveSqlConsole);+ apiRoute(PST, "/api/special-notes/search-note", specialNotesRoute.createSearchNote);+ apiRoute(PST, "/api/special-notes/save-search-note", specialNotesRoute.saveSearchNote);+ apiRoute(PST, "/api/special-notes/launchers/:noteId/reset", specialNotesRoute.resetLauncher);+ apiRoute(PST, "/api/special-notes/launchers/:parentNoteId/:launcherType", specialNotesRoute.createLauncher);+ apiRoute(PUT, "/api/special-notes/api-script-launcher", specialNotesRoute.createOrUpdateScriptLauncherFromApi);++ apiRoute(GET, "/api/sql/schema", sqlRoute.getSchema);+ apiRoute(PST, "/api/sql/execute/:noteId", sqlRoute.execute);+ route(PST, "/api/database/anonymize/:type", [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.anonymize, apiResultHandler, false);+ apiRoute(GET, "/api/database/anonymized-databases", databaseRoute.getExistingAnonymizedDatabases);if (process.env.TRILIUM_INTEGRATION_TEST === "memory") {- route(PST, '/api/database/rebuild/', [auth.checkApiAuthOrElectron], databaseRoute.rebuildIntegrationTestDatabase, apiResultHandler, false);+ route(PST, "/api/database/rebuild/", [auth.checkApiAuthOrElectron], databaseRoute.rebuildIntegrationTestDatabase, apiResultHandler, false);}// backup requires execution outside of transaction- route(PST, '/api/database/backup-database', [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.backupDatabase, apiResultHandler, false);- apiRoute(GET, '/api/database/backups', databaseRoute.getExistingBackups);+ route(PST, "/api/database/backup-database", [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.backupDatabase, apiResultHandler, false);+ apiRoute(GET, "/api/database/backups", databaseRoute.getExistingBackups);// VACUUM requires execution outside of transaction- route(PST, '/api/database/vacuum-database', [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.vacuumDatabase, apiResultHandler, false);+ route(PST, "/api/database/vacuum-database", [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.vacuumDatabase, apiResultHandler, false);- route(PST, '/api/database/find-and-fix-consistency-issues', [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.findAndFixConsistencyIssues, apiResultHandler, false);+ route(PST, "/api/database/find-and-fix-consistency-issues", [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.findAndFixConsistencyIssues, apiResultHandler, false);- apiRoute(GET, '/api/database/check-integrity', databaseRoute.checkIntegrity);+ apiRoute(GET, "/api/database/check-integrity", databaseRoute.checkIntegrity);- route(PST, '/api/script/exec', [auth.checkApiAuth, csrfMiddleware], scriptRoute.exec, apiResultHandler, false);+ route(PST, "/api/script/exec", [auth.checkApiAuth, csrfMiddleware], scriptRoute.exec, apiResultHandler, false);- apiRoute(PST, '/api/script/run/:noteId', scriptRoute.run);- apiRoute(GET, '/api/script/startup', scriptRoute.getStartupBundles);- apiRoute(GET, '/api/script/widgets', scriptRoute.getWidgetBundles);- apiRoute(PST, '/api/script/bundle/:noteId', scriptRoute.getBundle);- apiRoute(GET, '/api/script/relation/:noteId/:relationName', scriptRoute.getRelationBundles);+ apiRoute(PST, "/api/script/run/:noteId", scriptRoute.run);+ apiRoute(GET, "/api/script/startup", scriptRoute.getStartupBundles);+ apiRoute(GET, "/api/script/widgets", scriptRoute.getWidgetBundles);+ apiRoute(PST, "/api/script/bundle/:noteId", scriptRoute.getBundle);+ apiRoute(GET, "/api/script/relation/:noteId/:relationName", scriptRoute.getRelationBundles);// no CSRF since this is called from android app- route(PST, '/api/sender/login', [loginRateLimiter], loginApiRoute.token, apiResultHandler);- route(PST, '/api/sender/image', [auth.checkEtapiToken, uploadMiddlewareWithErrorHandling], senderRoute.uploadImage, apiResultHandler);- route(PST, '/api/sender/note', [auth.checkEtapiToken], senderRoute.saveNote, apiResultHandler);-- apiRoute(GET, '/api/keyboard-actions', keysRoute.getKeyboardActions);- apiRoute(GET, '/api/keyboard-shortcuts-for-notes', keysRoute.getShortcutsForNotes);-- apiRoute(PST, '/api/relation-map', relationMapApiRoute.getRelationMap);- apiRoute(PST, '/api/notes/erase-deleted-notes-now', notesApiRoute.eraseDeletedNotesNow);- apiRoute(PST, '/api/notes/erase-unused-attachments-now', notesApiRoute.eraseUnusedAttachmentsNow);- apiRoute(GET, '/api/similar-notes/:noteId', similarNotesRoute.getSimilarNotes);- apiRoute(GET, '/api/backend-log', backendLogRoute.getBackendLog);- apiRoute(GET, '/api/stats/note-size/:noteId', statsRoute.getNoteSize);- apiRoute(GET, '/api/stats/subtree-size/:noteId', statsRoute.getSubtreeSize);- apiRoute(PST, '/api/delete-notes-preview', notesApiRoute.getDeleteNotesPreview);- route(GET, '/api/fonts', [auth.checkApiAuthOrElectron], fontsRoute.getFontCss);- apiRoute(GET, '/api/other/icon-usage', otherRoute.getIconUsage);- apiRoute(PST, '/api/other/render-markdown', otherRoute.renderMarkdown);- apiRoute(GET, '/api/recent-changes/:ancestorNoteId', recentChangesApiRoute.getRecentChanges);- apiRoute(GET, '/api/edited-notes/:date', revisionsApiRoute.getEditedNotesOnDate);-- apiRoute(PST, '/api/note-map/:noteId/tree', noteMapRoute.getTreeMap);- apiRoute(PST, '/api/note-map/:noteId/link', noteMapRoute.getLinkMap);- apiRoute(GET, '/api/note-map/:noteId/backlink-count', noteMapRoute.getBacklinkCount);- apiRoute(GET, '/api/note-map/:noteId/backlinks', noteMapRoute.getBacklinks);+ route(PST, "/api/sender/login", [loginRateLimiter], loginApiRoute.token, apiResultHandler);+ route(PST, "/api/sender/image", [auth.checkEtapiToken, uploadMiddlewareWithErrorHandling], senderRoute.uploadImage, apiResultHandler);+ route(PST, "/api/sender/note", [auth.checkEtapiToken], senderRoute.saveNote, apiResultHandler);++ apiRoute(GET, "/api/keyboard-actions", keysRoute.getKeyboardActions);+ apiRoute(GET, "/api/keyboard-shortcuts-for-notes", keysRoute.getShortcutsForNotes);++ apiRoute(PST, "/api/relation-map", relationMapApiRoute.getRelationMap);+ apiRoute(PST, "/api/notes/erase-deleted-notes-now", notesApiRoute.eraseDeletedNotesNow);+ apiRoute(PST, "/api/notes/erase-unused-attachments-now", notesApiRoute.eraseUnusedAttachmentsNow);+ apiRoute(GET, "/api/similar-notes/:noteId", similarNotesRoute.getSimilarNotes);+ apiRoute(GET, "/api/backend-log", backendLogRoute.getBackendLog);+ apiRoute(GET, "/api/stats/note-size/:noteId", statsRoute.getNoteSize);+ apiRoute(GET, "/api/stats/subtree-size/:noteId", statsRoute.getSubtreeSize);+ apiRoute(PST, "/api/delete-notes-preview", notesApiRoute.getDeleteNotesPreview);+ route(GET, "/api/fonts", [auth.checkApiAuthOrElectron], fontsRoute.getFontCss);+ apiRoute(GET, "/api/other/icon-usage", otherRoute.getIconUsage);+ apiRoute(PST, "/api/other/render-markdown", otherRoute.renderMarkdown);+ apiRoute(GET, "/api/recent-changes/:ancestorNoteId", recentChangesApiRoute.getRecentChanges);+ apiRoute(GET, "/api/edited-notes/:date", revisionsApiRoute.getEditedNotesOnDate);++ apiRoute(PST, "/api/note-map/:noteId/tree", noteMapRoute.getTreeMap);+ apiRoute(PST, "/api/note-map/:noteId/link", noteMapRoute.getLinkMap);+ apiRoute(GET, "/api/note-map/:noteId/backlink-count", noteMapRoute.getBacklinkCount);+ apiRoute(GET, "/api/note-map/:noteId/backlinks", noteMapRoute.getBacklinks);shareRoutes.register(router);@@ -363,22 +373,20 @@ function register(app: express.Application) {etapiSpecRoute.register(router);etapiBackupRoute.register(router);- app.use('', router);+ app.use("", router);}/** Handling common patterns. If entity is not caught, serialization to JSON will fail */function convertEntitiesToPojo(result: unknown) {if (result instanceof AbstractBeccaEntity) {result = result.getPojo();- }- else if (Array.isArray(result)) {+ } else if (Array.isArray(result)) {for (const idx in result) {if (result[idx] instanceof AbstractBeccaEntity) {result[idx] = result[idx].getPojo();}}- }- else if (result && typeof result === "object") {+ } else if (result && typeof result === "object") {if ("note" in result && result.note instanceof AbstractBeccaEntity) {result.note = result.note.getPojo();}@@ -388,7 +396,8 @@ function convertEntitiesToPojo(result: unknown) {}}- if (result && typeof result === "object" && "executionResult" in result) { // from runOnBackend()+ if (result && typeof result === "object" && "executionResult" in result) {+ // from runOnBackend()result.executionResult = convertEntitiesToPojo(result.executionResult);}@@ -396,7 +405,7 @@ function convertEntitiesToPojo(result: unknown) {}function apiResultHandler(req: express.Request, res: express.Response, result: unknown) {- res.setHeader('trilium-max-entity-change-id', entityChangesService.getMaxEntityChangeId());+ res.setHeader("trilium-max-entity-change-id", entityChangesService.getMaxEntityChangeId());result = convertEntitiesToPojo(result);@@ -409,17 +418,15 @@ function apiResultHandler(req: express.Request, res: express.Response, result: u}return send(res, statusCode, response);- }- else if (result === undefined) {+ } else if (result === undefined) {return send(res, 204, "");- }- else {+ } else {return send(res, 200, result);}}function send(res: express.Response, statusCode: number, response: unknown) {- if (typeof response === 'string') {+ if (typeof response === "string") {if (statusCode >= 400) {res.setHeader("Content-Type", "text/plain");}@@ -427,8 +434,7 @@ function send(res: express.Response, statusCode: number, response: unknown) {res.status(statusCode).send(response);return response.length;- }- else {+ } else {const json = JSON.stringify(response);res.setHeader("Content-Type", "application/json");@@ -451,9 +457,9 @@ function route(method: HttpMethod, path: string, middleware: express.Handler[],cls.namespace.bindEmitter(res);const result = cls.init(() => {- cls.set('componentId', req.headers['trilium-component-id']);- cls.set('localNowDateTime', req.headers['trilium-local-now-datetime']);- cls.set('hoistedNoteId', req.headers['trilium-hoisted-note-id'] || 'root');+ cls.set("componentId", req.headers["trilium-component-id"]);+ cls.set("localNowDateTime", req.headers["trilium-local-now-datetime"]);+ cls.set("hoistedNoteId", req.headers["trilium-hoisted-note-id"] || "root");const cb = () => routeHandler(req, res, next);@@ -464,15 +470,13 @@ function route(method: HttpMethod, path: string, middleware: express.Handler[],return;}- if (result?.then) { // promise- result- .then((promiseResult: unknown) => handleResponse(resultHandler, req, res, promiseResult, start))- .catch((e: any) => handleException(e, method, path, res));+ if (result?.then) {+ // promise+ result.then((promiseResult: unknown) => handleResponse(resultHandler, req, res, promiseResult, start)).catch((e: any) => handleException(e, method, path, res));} else {- handleResponse(resultHandler, req, res, result, start)+ handleResponse(resultHandler, req, res, result, start);}- }- catch (e) {+ } catch (e) {handleException(e, method, path, res);}});@@ -488,20 +492,17 @@ function handleException(e: any, method: HttpMethod, path: string, res: express.log.error(`${method} ${path} threw exception: '${e.message}', stack: ${e.stack}`);if (e instanceof ValidationError) {- res.status(400)- .json({- message: e.message- });+ res.status(400).json({+ message: e.message+ });} else if (e instanceof NotFoundError) {- res.status(404)- .json({- message: e.message- });+ res.status(404).json({+ message: e.message+ });} else {- res.status(500)- .json({- message: e.message- });+ res.status(500).json({+ message: e.message+ });}}@@ -521,7 +522,7 @@ function createUploadMiddleware() {};}- return multer(multerOptions).single('upload');+ return multer(multerOptions).single("upload");}export default {diff --git a/src/routes/session_parser.ts b/src/routes/session_parser.tsindex ee99181529..90f4151212 100644--- a/src/routes/session_parser.ts+++ b/src/routes/session_parser.ts@@ -13,7 +13,7 @@ const sessionParser = session({httpOnly: true,maxAge: 24 * 60 * 60 * 1000 // in milliseconds},- name: 'trilium.sid',+ name: "trilium.sid",store: new FileStore({ttl: 30 * 24 * 3600,path: `${dataDir.TRILIUM_DATA_DIR}/sessions`diff --git a/src/routes/setup.ts b/src/routes/setup.tsindex d2ade1d88a..15fd0b4701 100644--- a/src/routes/setup.ts+++ b/src/routes/setup.ts@@ -5,14 +5,14 @@ import setupService from "../services/setup.js";import utils from "../services/utils.js";import assetPath from "../services/asset_path.js";import appPath from "../services/app_path.js";-import { Request, Response } from 'express';+import { Request, Response } from "express";function setupPage(req: Request, res: Response) {if (sqlInit.isDbInitialized()) {if (utils.isElectron()) {handleElectronRedirect();} else {- res.redirect('.');+ res.redirect(".");}return;@@ -27,7 +27,7 @@ function setupPage(req: Request, res: Response) {setupService.triggerSync();}- res.render('setup', {+ res.render("setup", {syncInProgress: syncInProgress,assetPath: assetPath,appPath: appPathdiff --git a/src/services/anonymization.ts b/src/services/anonymization.tsindex 81eb26be49..2d855130f9 100644--- a/src/services/anonymization.ts+++ b/src/services/anonymization.ts@@ -9,9 +9,9 @@ import path from "path";function getFullAnonymizationScript() {// we want to delete all non-builtin attributes because they can contain sensitive names and values// on the other hand builtin/system attrs should not contain any sensitive info- const builtinAttrNames = BUILTIN_ATTRIBUTES- .filter(attr => !["shareCredentials", "shareAlias"].includes(attr.name))- .map(attr => `'${attr.name}'`).join(', ');+ const builtinAttrNames = BUILTIN_ATTRIBUTES.filter((attr) => !["shareCredentials", "shareAlias"].includes(attr.name))+ .map((attr) => `'${attr.name}'`)+ .join(", ");const anonymizeScript = `UPDATE etapi_tokens SET tokenHash = 'API token hash value';@@ -49,7 +49,7 @@ function getLightAnonymizationScript() {}async function createAnonymizedCopy(type: "full" | "light") {- if (!['full', 'light'].includes(type)) {+ if (!["full", "light"].includes(type)) {throw new Error(`Unrecognized anonymization type '${type}'`);}@@ -63,9 +63,7 @@ async function createAnonymizedCopy(type: "full" | "light") {const db = new Database(anonymizedFile);- const anonymizationScript = type === 'light'- ? getLightAnonymizationScript()- : getFullAnonymizationScript();+ const anonymizationScript = type === "light" ? getLightAnonymizationScript() : getFullAnonymizationScript();db.exec(anonymizationScript);@@ -82,9 +80,10 @@ function getExistingAnonymizedDatabases() {return [];}- return fs.readdirSync(dataDir.ANONYMIZED_DB_DIR)- .filter(fileName => fileName.includes("anonymized"))- .map(fileName => ({+ return fs+ .readdirSync(dataDir.ANONYMIZED_DB_DIR)+ .filter((fileName) => fileName.includes("anonymized"))+ .map((fileName) => ({fileName: fileName,filePath: path.resolve(dataDir.ANONYMIZED_DB_DIR, fileName)}));@@ -94,4 +93,4 @@ export default {getFullAnonymizationScript,createAnonymizedCopy,getExistingAnonymizedDatabases-}+};diff --git a/src/services/api-interface.ts b/src/services/api-interface.tsindex 14432eb439..908e8dc0c6 100644--- a/src/services/api-interface.ts+++ b/src/services/api-interface.ts@@ -13,5 +13,5 @@ export interface SetupStatusResponse {*/export interface SetupSyncSeedResponse {syncVersion: number;- options: OptionRow[]+ options: OptionRow[];}diff --git a/src/services/app_icon.ts b/src/services/app_icon.tsindex ef2b5d355c..a03a9a9374 100644--- a/src/services/app_icon.ts+++ b/src/services/app_icon.ts@@ -23,9 +23,7 @@ Terminal=false* We overwrite this file during every run as it might have been updated.*/function installLocalAppIcon() {- if (!isElectron()- || ["win32", "darwin"].includes(os.platform())- || (config.General && config.General.noDesktopIcon)) {+ if (!isElectron() || ["win32", "darwin"].includes(os.platform()) || (config.General && config.General.noDesktopIcon)) {return;}@@ -35,7 +33,7 @@ function installLocalAppIcon() {return;}- const desktopDir = path.resolve(os.homedir(), '.local/share/applications');+ const desktopDir = path.resolve(os.homedir(), ".local/share/applications");fs.stat(desktopDir, function (err, stats) {if (err) {@@ -56,9 +54,7 @@ function installLocalAppIcon() {}function getDesktopFileContent() {- return template- .replace("#APP_ROOT_DIR#", escapePath(resourceDir.ELECTRON_APP_ROOT_DIR))- .replace("#EXE_PATH#", escapePath(getExePath()));+ return template.replace("#APP_ROOT_DIR#", escapePath(resourceDir.ELECTRON_APP_ROOT_DIR)).replace("#EXE_PATH#", escapePath(getExePath()));}function escapePath(path: string) {@@ -66,7 +62,7 @@ function escapePath(path: string) {}function getExePath() {- return path.resolve(resourceDir.ELECTRON_APP_ROOT_DIR, 'trilium');+ return path.resolve(resourceDir.ELECTRON_APP_ROOT_DIR, "trilium");}export default {diff --git a/src/services/app_path.ts b/src/services/app_path.tsindex 6d5e02231d..f4ae316c34 100644--- a/src/services/app_path.ts+++ b/src/services/app_path.ts@@ -1,6 +1,4 @@import assetPath from "./asset_path.js";import env from "./env.js";-export default env.isDev()- ? assetPath + "/app"- : assetPath + "/app-dist";+export default env.isDev() ? assetPath + "/app" : assetPath + "/app-dist";diff --git a/src/services/attribute_formatter.ts b/src/services/attribute_formatter.tsindex 31112be368..fa0d75838e 100644--- a/src/services/attribute_formatter.ts+++ b/src/services/attribute_formatter.ts@@ -3,26 +3,24 @@import { AttributeRow } from "../becca/entities/rows.js";function formatAttrForSearch(attr: AttributeRow, searchWithValue: boolean) {- let searchStr = '';+ let searchStr = "";- if (attr.type === 'label') {- searchStr += '#';- }- else if (attr.type === 'relation') {- searchStr += '~';- }- else {+ if (attr.type === "label") {+ searchStr += "#";+ } else if (attr.type === "relation") {+ searchStr += "~";+ } else {throw new Error(`Unrecognized attribute type ${JSON.stringify(attr)}`);}searchStr += attr.name;if (searchWithValue && attr.value) {- if (attr.type === 'relation') {+ if (attr.type === "relation") {searchStr += ".noteId";}- searchStr += '=';+ searchStr += "=";searchStr += formatValue(attr.value);}@@ -32,17 +30,13 @@ function formatAttrForSearch(attr: AttributeRow, searchWithValue: boolean) {function formatValue(val: string) {if (!/[^\w]/.test(val)) {return val;- }- else if (!val.includes('"')) {+ } else if (!val.includes('"')) {return `"${val}"`;- }- else if (!val.includes("'")) {+ } else if (!val.includes("'")) {return `'${val}'`;- }- else if (!val.includes("`")) {+ } else if (!val.includes("`")) {return `\`${val}\``;- }- else {+ } else {return `"${val.replace(/"/g, '\\"')}"`;}}diff --git a/src/services/attributes.ts b/src/services/attributes.tsindex eff0f4697f..69de8d8640 100644--- a/src/services/attributes.ts+++ b/src/services/attributes.ts@@ -7,12 +7,12 @@ import BAttribute from "../becca/entities/battribute.js";import attributeFormatter from "./attribute_formatter.js";import BUILTIN_ATTRIBUTES from "./builtin_attributes.js";import BNote from "../becca/entities/bnote.js";-import { AttributeRow } from '../becca/entities/rows.js';+import { AttributeRow } from "../becca/entities/rows.js";-const ATTRIBUTE_TYPES = new Set(['label', 'relation']);+const ATTRIBUTE_TYPES = new Set(["label", "relation"]);function getNotesWithLabel(name: string, value?: string): BNote[] {- const query = attributeFormatter.formatAttrForSearch({type: 'label', name, value}, value !== undefined);+ const query = attributeFormatter.formatAttrForSearch({ type: "label", name, value }, value !== undefined);return searchService.searchNotes(query, {includeArchivedNotes: true,ignoreHoistedNote: true@@ -22,7 +22,7 @@ function getNotesWithLabel(name: string, value?: string): BNote[] {// TODO: should be in search servicefunction getNoteWithLabel(name: string, value?: string): BNote | null {// optimized version (~20 times faster) without using normal search, useful for e.g., finding date notes- const attrs = becca.findAttributes('label', name);+ const attrs = becca.findAttributes("label", name);if (value === undefined) {return attrs[0]?.getNote();@@ -42,7 +42,7 @@ function getNoteWithLabel(name: string, value?: string): BNote | null {function createLabel(noteId: string, name: string, value: string = "") {return createAttribute({noteId: noteId,- type: 'label',+ type: "label",name: name,value: value});@@ -51,7 +51,7 @@ function createLabel(noteId: string, name: string, value: string = "") {function createRelation(noteId: string, name: string, targetNoteId: string) {return createAttribute({noteId: noteId,- type: 'relation',+ type: "relation",name: name,value: targetNoteId});@@ -69,7 +69,9 @@ function getAttributeNames(type: string, nameLike: string) {FROM attributesWHERE isDeleted = 0AND type = ?- AND name LIKE ?`, [type, `%${nameLike}%`]);+ AND name LIKE ?`,+ [type, `%${nameLike}%`]+ );for (const attr of BUILTIN_ATTRIBUTES) {if (attr.type === type && attr.name.toLowerCase().includes(nameLike) && !names.includes(attr.name)) {@@ -77,12 +79,7 @@ function getAttributeNames(type: string, nameLike: string) {}}- names = names.filter(name => ![- 'internalLink',- 'imageLink',- 'includeNoteLink',- 'relationMapLink'- ].includes(name));+ names = names.filter((name) => !["internalLink", "imageLink", "includeNoteLink", "relationMapLink"].includes(name));names.sort((a, b) => {const aPrefix = a.toLowerCase().startsWith(nameLike);@@ -103,11 +100,7 @@ function isAttributeType(type: string): boolean {}function isAttributeDangerous(type: string, name: string): boolean {- return BUILTIN_ATTRIBUTES.some(attr =>- attr.type === type &&- attr.name.toLowerCase() === name.trim().toLowerCase() &&- attr.isDangerous- );+ return BUILTIN_ATTRIBUTES.some((attr) => attr.type === type && attr.name.toLowerCase() === name.trim().toLowerCase() && attr.isDangerous);}export default {diff --git a/src/services/auth.ts b/src/services/auth.tsindex 015c7eae09..a7a729a6e3 100644--- a/src/services/auth.ts+++ b/src/services/auth.ts@@ -7,18 +7,16 @@ import { isElectron } from "./utils.js";import passwordEncryptionService from "./encryption/password_encryption.js";import config from "./config.js";import passwordService from "./encryption/password.js";-import type { NextFunction, Request, Response } from 'express';+import type { NextFunction, Request, Response } from "express";const noAuthentication = config.General && config.General.noAuthentication === true;function checkAuth(req: Request, res: Response, next: NextFunction) {if (!sqlInit.isDbInitialized()) {res.redirect("setup");- }- else if (!req.session.loggedIn && !isElectron() && !noAuthentication) {+ } else if (!req.session.loggedIn && !isElectron() && !noAuthentication) {res.redirect("login");- }- else {+ } else {next();}}@@ -28,8 +26,7 @@ function checkAuth(req: Request, res: Response, next: NextFunction) {function checkApiAuthOrElectron(req: Request, res: Response, next: NextFunction) {if (!req.session.loggedIn && !isElectron() && !noAuthentication) {reject(req, res, "Logged in session not found");- }- else {+ } else {next();}}@@ -37,8 +34,7 @@ function checkApiAuthOrElectron(req: Request, res: Response, next: NextFunction)function checkApiAuth(req: Request, res: Response, next: NextFunction) {if (!req.session.loggedIn && !noAuthentication) {reject(req, res, "Logged in session not found");- }- else {+ } else {next();}}@@ -46,8 +42,7 @@ function checkApiAuth(req: Request, res: Response, next: NextFunction) {function checkAppInitialized(req: Request, res: Response, next: NextFunction) {if (!sqlInit.isDbInitialized()) {res.redirect("setup");- }- else {+ } else {next();}}@@ -71,8 +66,7 @@ function checkPasswordNotSet(req: Request, res: Response, next: NextFunction) {function checkAppNotInitialized(req: Request, res: Response, next: NextFunction) {if (sqlInit.isDbInitialized()) {reject(req, res, "App already initialized.");- }- else {+ } else {next();}}@@ -80,8 +74,7 @@ function checkAppNotInitialized(req: Request, res: Response, next: NextFunction)function checkEtapiToken(req: Request, res: Response, next: NextFunction) {if (etapiTokenService.isValidAuthHeader(req.headers.authorization)) {next();- }- else {+ } else {reject(req, res, "Token not found");}}@@ -89,45 +82,34 @@ function checkEtapiToken(req: Request, res: Response, next: NextFunction) {function reject(req: Request, res: Response, message: string) {log.info(`${req.method} ${req.path} rejected with 401 ${message}`);- res.setHeader("Content-Type", "text/plain")- .status(401)- .send(message);+ res.setHeader("Content-Type", "text/plain").status(401).send(message);}function checkCredentials(req: Request, res: Response, next: NextFunction) {if (!sqlInit.isDbInitialized()) {- res.setHeader("Content-Type", "text/plain")- .status(400)- .send('Database is not initialized yet.');+ res.setHeader("Content-Type", "text/plain").status(400).send("Database is not initialized yet.");return;}if (!passwordService.isPasswordSet()) {- res.setHeader("Content-Type", "text/plain")- .status(400)- .send('Password has not been set yet. Please set a password and repeat the action');+ res.setHeader("Content-Type", "text/plain").status(400).send("Password has not been set yet. Please set a password and repeat the action");return;}- const header = req.headers['trilium-cred'] || '';+ const header = req.headers["trilium-cred"] || "";if (typeof header !== "string") {- res.setHeader("Content-Type", "text/plain")- .status(400)- .send('Invalid data type for trilium-cred.');+ res.setHeader("Content-Type", "text/plain").status(400).send("Invalid data type for trilium-cred.");return;}- const auth = Buffer.from(header, 'base64').toString();- const colonIndex = auth.indexOf(':');+ const auth = Buffer.from(header, "base64").toString();+ const colonIndex = auth.indexOf(":");const password = colonIndex === -1 ? "" : auth.substr(colonIndex + 1);// username is ignoredif (!passwordEncryptionService.verifyPassword(password)) {- res.setHeader("Content-Type", "text/plain")- .status(401)- .send('Incorrect password');- }- else {+ res.setHeader("Content-Type", "text/plain").status(401).send("Incorrect password");+ } else {next();}}diff --git a/src/services/backend_script_api.ts b/src/services/backend_script_api.tsindex 20e68faf80..a5655caf4d 100644--- a/src/services/backend_script_api.ts+++ b/src/services/backend_script_api.ts@@ -9,7 +9,7 @@ import config from "./config.js";import axios from "axios";import dayjs from "dayjs";import xml2js from "xml2js";-import * as cheerio from 'cheerio';+import * as cheerio from "cheerio";import cloningService from "./cloning.js";import appInfo from "./app_info.js";import searchService from "./search/services/search.js";@@ -31,11 +31,10 @@ import BAttachment from "../becca/entities/battachment.js";import BRevision from "../becca/entities/brevision.js";import BEtapiToken from "../becca/entities/betapi_token.js";import BOption from "../becca/entities/boption.js";-import { AttributeRow } from '../becca/entities/rows.js';-import Becca from '../becca/becca-interface.js';-import { NoteParams } from './note-interface.js';-import { ApiParams } from './backend_script_api_interface.js';-+import { AttributeRow } from "../becca/entities/rows.js";+import Becca from "../becca/becca-interface.js";+import { NoteParams } from "./note-interface.js";+import { ApiParams } from "./backend_script_api_interface.js";/*** A whole number@@ -61,51 +60,51 @@ interface NoteAndBranch {interface Api {/**- * Note where the script started executing (entrypoint).- * As an analogy, in C this would be the file which contains the main() function of the current process.- */+ * Note where the script started executing (entrypoint).+ * As an analogy, in C this would be the file which contains the main() function of the current process.+ */startNote?: BNote | null;/**- * Note where the script is currently executing. This comes into play when your script is spread in multiple code- * notes, the script starts in "startNote", but then through function calls may jump into another note (currentNote).- * A similar concept in C would be __FILE__- * Don't mix this up with the concept of active note.- */+ * Note where the script is currently executing. This comes into play when your script is spread in multiple code+ * notes, the script starts in "startNote", but then through function calls may jump into another note (currentNote).+ * A similar concept in C would be __FILE__+ * Don't mix this up with the concept of active note.+ */currentNote: BNote;/**- * Entity whose event triggered this execution- */+ * Entity whose event triggered this execution+ */originEntity?: AbstractBeccaEntity<any> | null;/**- * Axios library for HTTP requests. See {@link https://axios-http.com} for documentation- * @deprecated use native (browser compatible) fetch() instead- */+ * Axios library for HTTP requests. See {@link https://axios-http.com} for documentation+ * @deprecated use native (browser compatible) fetch() instead+ */axios: typeof axios;/**- * day.js library for date manipulation. See {@link https://day.js.org} for documentation- */+ * day.js library for date manipulation. See {@link https://day.js.org} for documentation+ */dayjs: typeof dayjs;/**- * xml2js library for XML parsing. See {@link https://github.com/Leonidas-from-XIV/node-xml2js} for documentation- */+ * xml2js library for XML parsing. See {@link https://github.com/Leonidas-from-XIV/node-xml2js} for documentation+ */xml2js: typeof xml2js;/**- * cheerio library for HTML parsing and manipulation. See {@link https://cheerio.js.org} for documentation- */+ * cheerio library for HTML parsing and manipulation. See {@link https://cheerio.js.org} for documentation+ */cheerio: typeof cheerio;/**- * Instance name identifies particular Trilium instance. It can be useful for scripts- * if some action needs to happen on only one specific instance.- */+ * Instance name identifies particular Trilium instance. It can be useful for scripts+ * if some action needs to happen on only one specific instance.+ */getInstanceName(): string | null;getNote(noteId: string): BNote | null;@@ -120,208 +119,224 @@ interface Api {getAttribute(attributeId: string): BAttribute | null;/**- * This is a powerful search method - you can search by attributes and their values, e.g.:- * "#dateModified =* MONTH AND #log". See {@link https://triliumnext.github.io/Docs/Wiki/search.html} for full documentation for all options- */+ * This is a powerful search method - you can search by attributes and their values, e.g.:+ * "#dateModified =* MONTH AND #log". See {@link https://triliumnext.github.io/Docs/Wiki/search.html} for full documentation for all options+ */searchForNotes(query: string, searchParams: SearchParams): BNote[];/**- * This is a powerful search method - you can search by attributes and their values, e.g.:- * "#dateModified =* MONTH AND #log". See {@link https://triliumnext.github.io/Docs/Wiki/search.html} for full documentation for all options- */+ * This is a powerful search method - you can search by attributes and their values, e.g.:+ * "#dateModified =* MONTH AND #log". See {@link https://triliumnext.github.io/Docs/Wiki/search.html} for full documentation for all options+ */searchForNote(query: string, searchParams: SearchParams): BNote | null;/**- * Retrieves notes with given label name & value- *- * @param name - attribute name- * @param value - attribute value- */+ * Retrieves notes with given label name & value+ *+ * @param name - attribute name+ * @param value - attribute value+ */getNotesWithLabel(name: string, value?: string): BNote[];/**- * Retrieves first note with given label name & value- *- * @param name - attribute name- * @param value - attribute value- */+ * Retrieves first note with given label name & value+ *+ * @param name - attribute name+ * @param value - attribute value+ */getNoteWithLabel(name: string, value?: string): BNote | null;/**- * If there's no branch between note and parent note, create one. Otherwise, do nothing. Returns the new or existing branch.- *- * @param prefix - if branch is created between note and parent note, set this prefix- */- ensureNoteIsPresentInParent(noteId: string, parentNoteId: string, prefix: string): {- branch: BBranch | null+ * If there's no branch between note and parent note, create one. Otherwise, do nothing. Returns the new or existing branch.+ *+ * @param prefix - if branch is created between note and parent note, set this prefix+ */+ ensureNoteIsPresentInParent(+ noteId: string,+ parentNoteId: string,+ prefix: string+ ): {+ branch: BBranch | null;};/**- * If there's a branch between note and parent note, remove it. Otherwise, do nothing.- */+ * If there's a branch between note and parent note, remove it. Otherwise, do nothing.+ */ensureNoteIsAbsentFromParent(noteId: string, parentNoteId: string): void;/**- * Based on the value, either create or remove branch between note and parent note.- *- * @param present - true if we want the branch to exist, false if we want it gone- * @param prefix - if branch is created between note and parent note, set this prefix- */+ * Based on the value, either create or remove branch between note and parent note.+ *+ * @param present - true if we want the branch to exist, false if we want it gone+ * @param prefix - if branch is created between note and parent note, set this prefix+ */toggleNoteInParent(present: true, noteId: string, parentNoteId: string, prefix: string): void;/**- * Create text note. See also createNewNote() for more options.- */+ * Create text note. See also createNewNote() for more options.+ */createTextNote(parentNoteId: string, title: string, content: string): NoteAndBranch;/**- * Create data note - data in this context means object serializable to JSON. Created note will be of type 'code' and- * JSON MIME type. See also createNewNote() for more options.- */+ * Create data note - data in this context means object serializable to JSON. Created note will be of type 'code' and+ * JSON MIME type. See also createNewNote() for more options.+ */createDataNote(parentNoteId: string, title: string, content: {}): NoteAndBranch;/**- * @returns object contains newly created entities note and branch- */+ * @returns object contains newly created entities note and branch+ */createNewNote(params: NoteParams): NoteAndBranch;/**- * @deprecated please use createTextNote() with similar API for simpler use cases or createNewNote() for more complex needs- * @param parentNoteId - create new note under this parent- * @returns object contains newly created entities note and branch- */- createNote(parentNoteId: string, title: string, content: string, extraOptions: Omit<NoteParams, "title" | "content" | "type" | "parentNoteId"> & {- /** should the note be JSON */- json?: boolean;- attributes?: AttributeRow[]- }): NoteAndBranch;+ * @deprecated please use createTextNote() with similar API for simpler use cases or createNewNote() for more complex needs+ * @param parentNoteId - create new note under this parent+ * @returns object contains newly created entities note and branch+ */+ createNote(+ parentNoteId: string,+ title: string,+ content: string,+ extraOptions: Omit<NoteParams, "title" | "content" | "type" | "parentNoteId"> & {+ /** should the note be JSON */+ json?: boolean;+ attributes?: AttributeRow[];+ }+ ): NoteAndBranch;logMessages: Record<string, string[]>;logSpacedUpdates: Record<string, SpacedUpdate>;/**- * Log given message to trilium logs and log pane in UI- */+ * Log given message to trilium logs and log pane in UI+ */log(message: string): void;/**- * Returns root note of the calendar.- */+ * Returns root note of the calendar.+ */getRootCalendarNote(): BNote | null;/**- * Returns day note for given date. If such note doesn't exist, it is created.- *- * @method- * @param date in YYYY-MM-DD format- * @param rootNote - specify calendar root note, normally leave empty to use the default calendar- */+ * Returns day note for given date. If such note doesn't exist, it is created.+ *+ * @method+ * @param date in YYYY-MM-DD format+ * @param rootNote - specify calendar root note, normally leave empty to use the default calendar+ */getDayNote(date: string, rootNote?: BNote): BNote | null;/**- * Returns today's day note. If such note doesn't exist, it is created.- *- * @param rootNote specify calendar root note, normally leave empty to use the default calendar- */+ * Returns today's day note. If such note doesn't exist, it is created.+ *+ * @param rootNote specify calendar root note, normally leave empty to use the default calendar+ */getTodayNote(rootNote?: BNote): BNote | null;/**- * Returns note for the first date of the week of the given date.- *- * @param date in YYYY-MM-DD format- * @param rootNote - specify calendar root note, normally leave empty to use the default calendar- */- getWeekNote(date: string, options: {- // TODO: Deduplicate type with date_notes.ts once ES modules are added.- /** either "monday" (default) or "sunday" */- startOfTheWeek: "monday" | "sunday";- }, rootNote: BNote): BNote | null;-- /**- * Returns month note for given date. If such a note doesn't exist, it is created.- *- * @param date in YYYY-MM format- * @param rootNote - specify calendar root note, normally leave empty to use the default calendar- */+ * Returns note for the first date of the week of the given date.+ *+ * @param date in YYYY-MM-DD format+ * @param rootNote - specify calendar root note, normally leave empty to use the default calendar+ */+ getWeekNote(+ date: string,+ options: {+ // TODO: Deduplicate type with date_notes.ts once ES modules are added.+ /** either "monday" (default) or "sunday" */+ startOfTheWeek: "monday" | "sunday";+ },+ rootNote: BNote+ ): BNote | null;++ /**+ * Returns month note for given date. If such a note doesn't exist, it is created.+ *+ * @param date in YYYY-MM format+ * @param rootNote - specify calendar root note, normally leave empty to use the default calendar+ */getMonthNote(date: string, rootNote: BNote): BNote | null;/**- * Returns year note for given year. If such a note doesn't exist, it is created.- *- * @param year in YYYY format- * @param rootNote - specify calendar root note, normally leave empty to use the default calendar- */+ * Returns year note for given year. If such a note doesn't exist, it is created.+ *+ * @param year in YYYY format+ * @param rootNote - specify calendar root note, normally leave empty to use the default calendar+ */getYearNote(year: string, rootNote?: BNote): BNote | null;/**- * Sort child notes of a given note.- */- sortNotes(parentNoteId: string, sortConfig: {- /** 'title', 'dateCreated', 'dateModified' or a label name- * See {@link https://triliumnext.github.io/Docs/Wiki/sorting.html} for details. */- sortBy?: string;- reverse?: boolean;- foldersFirst?: boolean;- }): void;-- /**- * This method finds note by its noteId and prefix and either sets it to the given parentNoteId- * or removes the branch (if parentNoteId is not given).- *- * This method looks similar to toggleNoteInParent() but differs because we're looking up branch by prefix.- *- * @deprecated this method is pretty confusing and serves specialized purpose only- */+ * Sort child notes of a given note.+ */+ sortNotes(+ parentNoteId: string,+ sortConfig: {+ /** 'title', 'dateCreated', 'dateModified' or a label name+ * See {@link https://triliumnext.github.io/Docs/Wiki/sorting.html} for details. */+ sortBy?: string;+ reverse?: boolean;+ foldersFirst?: boolean;+ }+ ): void;++ /**+ * This method finds note by its noteId and prefix and either sets it to the given parentNoteId+ * or removes the branch (if parentNoteId is not given).+ *+ * This method looks similar to toggleNoteInParent() but differs because we're looking up branch by prefix.+ *+ * @deprecated this method is pretty confusing and serves specialized purpose only+ */setNoteToParent(noteId: string, prefix: string, parentNoteId: string | null): void;/**- * This functions wraps code which is supposed to be running in transaction. If transaction already- * exists, then we'll use that transaction.- *- * @param func- * @returns result of func callback- */+ * This functions wraps code which is supposed to be running in transaction. If transaction already+ * exists, then we'll use that transaction.+ *+ * @param func+ * @returns result of func callback+ */transactional(func: () => void): any;/**- * Return randomly generated string of given length. This random string generation is NOT cryptographically secure.- *- * @param length of the string- * @returns random string- */+ * Return randomly generated string of given length. This random string generation is NOT cryptographically secure.+ *+ * @param length of the string+ * @returns random string+ */randomString(length: number): string;/**- * @param to escape- * @returns escaped string- */+ * @param to escape+ * @returns escaped string+ */escapeHtml(string: string): string;/**- * @param string to unescape- * @returns unescaped string- */+ * @param string to unescape+ * @returns unescaped string+ */unescapeHtml(string: string): string;/**- * sql- * @type {module:sql}- */+ * sql+ * @type {module:sql}+ */sql: any;getAppInfo(): typeof appInfo;/**- * Creates a new launcher to the launchbar. If the launcher (id) already exists, it will be updated.- */+ * Creates a new launcher to the launchbar. If the launcher (id) already exists, it will be updated.+ */createOrUpdateLauncher(opts: {/** id of the launcher, only alphanumeric at least 6 characters long */id: string;/** one of- * - "note" - activating the launcher will navigate to the target note (specified in targetNoteId param)- * - "script" - activating the launcher will execute the script (specified in scriptNoteId param)- * - "customWidget" - the launcher will be rendered with a custom widget (specified in widgetNoteId param)- */+ * - "note" - activating the launcher will navigate to the target note (specified in targetNoteId param)+ * - "script" - activating the launcher will execute the script (specified in scriptNoteId param)+ * - "customWidget" - the launcher will be rendered with a custom widget (specified in widgetNoteId param)+ */type: "note" | "script" | "customWidget";title: string;/** if true, will be created in the "Visible launchers", otherwise in "Available launchers" */@@ -339,44 +354,44 @@ interface Api {}): { note: BNote };/**- * @param format - either 'html' or 'markdown'- */+ * @param format - either 'html' or 'markdown'+ */exportSubtreeToZipFile(noteId: string, format: "markdown" | "html", zipFilePath: string): Promise<void>;/**- * Executes given anonymous function on the frontend(s).- * Internally, this serializes the anonymous function into string and sends it to frontend(s) via WebSocket.- * Note that there can be multiple connected frontend instances (e.g. in different tabs). In such case, all- * instances execute the given function.- *- * @param script - script to be executed on the frontend- * @param params - list of parameters to the anonymous function to be sent to frontend- * @returns no return value is provided.- */+ * Executes given anonymous function on the frontend(s).+ * Internally, this serializes the anonymous function into string and sends it to frontend(s) via WebSocket.+ * Note that there can be multiple connected frontend instances (e.g. in different tabs). In such case, all+ * instances execute the given function.+ *+ * @param script - script to be executed on the frontend+ * @param params - list of parameters to the anonymous function to be sent to frontend+ * @returns no return value is provided.+ */runOnFrontend(script: () => void | string, params: []): void;/**- * Sync process can make data intermittently inconsistent. Scripts which require strong data consistency- * can use this function to wait for a possible sync process to finish and prevent new sync process from starting- * while it is running.- *- * Because this is an async process, the inner callback doesn't have automatic transaction handling, so in case- * you need to make some DB changes, you need to surround your call with api.transactional(...)- *- * @param callback - function to be executed while sync process is not running- * @returns resolves once the callback is finished (callback is awaited)- */+ * Sync process can make data intermittently inconsistent. Scripts which require strong data consistency+ * can use this function to wait for a possible sync process to finish and prevent new sync process from starting+ * while it is running.+ *+ * Because this is an async process, the inner callback doesn't have automatic transaction handling, so in case+ * you need to make some DB changes, you need to surround your call with api.transactional(...)+ *+ * @param callback - function to be executed while sync process is not running+ * @returns resolves once the callback is finished (callback is awaited)+ */runOutsideOfSync(callback: () => void): Promise<void>;/**- * @param backupName - If the backupName is e.g. "now", then the backup will be written to "backup-now.db" file- * @returns resolves once the backup is finished- */+ * @param backupName - If the backupName is e.g. "now", then the backup will be written to "backup-now.db" file+ * @returns resolves once the backup is finished+ */backupNow(backupName: string): Promise<string>;/**- * This object contains "at your risk" and "no BC guarantees" objects for advanced use cases.- */+ * This object contains "at your risk" and "no BC guarantees" objects for advanced use cases.+ */__private: {/** provides access to the backend in-memory object graph, see {@link Becca} */becca: Becca;@@ -405,17 +420,17 @@ function BackendScriptApi(this: Api, currentNote: BNote, apiParams: ApiParams) {this.dayjs = dayjs;this.xml2js = xml2js;this.cheerio = cheerio;- this.getInstanceName = () => config.General ? config.General.instanceName : null;- this.getNote = noteId => becca.getNote(noteId);- this.getBranch = branchId => becca.getBranch(branchId);- this.getAttribute = attributeId => becca.getAttribute(attributeId);- this.getAttachment = attachmentId => becca.getAttachment(attachmentId);- this.getRevision = revisionId => becca.getRevision(revisionId);- this.getEtapiToken = etapiTokenId => becca.getEtapiToken(etapiTokenId);+ this.getInstanceName = () => (config.General ? config.General.instanceName : null);+ this.getNote = (noteId) => becca.getNote(noteId);+ this.getBranch = (branchId) => becca.getBranch(branchId);+ this.getAttribute = (attributeId) => becca.getAttribute(attributeId);+ this.getAttachment = (attachmentId) => becca.getAttachment(attachmentId);+ this.getRevision = (revisionId) => becca.getRevision(revisionId);+ this.getEtapiToken = (etapiTokenId) => becca.getEtapiToken(etapiTokenId);this.getEtapiTokens = () => becca.getEtapiTokens();- this.getOption = optionName => becca.getOption(optionName);+ this.getOption = (optionName) => becca.getOption(optionName);this.getOptions = () => optionsService.getOptions();- this.getAttribute = attributeId => becca.getAttribute(attributeId);+ this.getAttribute = (attributeId) => becca.getAttribute(attributeId);this.searchForNotes = (query, searchParams = {}) => {if (searchParams.includeArchivedNotes === undefined) {@@ -426,13 +441,11 @@ function BackendScriptApi(this: Api, currentNote: BNote, apiParams: ApiParams) {searchParams.ignoreHoistedNote = true;}- const noteIds = searchService.findResultsWithQuery(query, new SearchContext(searchParams))- .map(sr => sr.noteId);+ const noteIds = searchService.findResultsWithQuery(query, new SearchContext(searchParams)).map((sr) => sr.noteId);return becca.getNotes(noteIds);};-this.searchForNote = (query, searchParams = {}) => {const notes = this.searchForNotes(query, searchParams);@@ -444,20 +457,22 @@ function BackendScriptApi(this: Api, currentNote: BNote, apiParams: ApiParams) {this.ensureNoteIsPresentInParent = cloningService.ensureNoteIsPresentInParent;this.ensureNoteIsAbsentFromParent = cloningService.ensureNoteIsAbsentFromParent;this.toggleNoteInParent = cloningService.toggleNoteInParent;- this.createTextNote = (parentNoteId, title, content = '') => noteService.createNewNote({- parentNoteId,- title,- content,- type: 'text'- });-- this.createDataNote = (parentNoteId, title, content = {}) => noteService.createNewNote({- parentNoteId,- title,- content: JSON.stringify(content, null, '\t'),- type: 'code',- mime: 'application/json'- });+ this.createTextNote = (parentNoteId, title, content = "") =>+ noteService.createNewNote({+ parentNoteId,+ title,+ content,+ type: "text"+ });++ this.createDataNote = (parentNoteId, title, content = {}) =>+ noteService.createNewNote({+ parentNoteId,+ title,+ content: JSON.stringify(content, null, "\t"),+ type: "code",+ mime: "application/json"+ });this.createNewNote = noteService.createNewNote;@@ -476,15 +491,14 @@ function BackendScriptApi(this: Api, currentNote: BNote, apiParams: ApiParams) {};// code note type can be inherited, otherwise "text" is the default- extraOptions.type = parentNote.type === 'code' ? 'code' : 'text';- extraOptions.mime = parentNote.type === 'code' ? parentNote.mime : 'text/html';+ extraOptions.type = parentNote.type === "code" ? "code" : "text";+ extraOptions.mime = parentNote.type === "code" ? parentNote.mime : "text/html";if (_extraOptions.json) {- extraOptions.content = JSON.stringify(content || {}, null, '\t');- extraOptions.type = 'code';- extraOptions.mime = 'application/json';- }- else {+ extraOptions.content = JSON.stringify(content || {}, null, "\t");+ extraOptions.type = "code";+ extraOptions.mime = "application/json";+ } else {extraOptions.content = content;}@@ -508,7 +522,7 @@ function BackendScriptApi(this: Api, currentNote: BNote, apiParams: ApiParams) {this.logMessages = {};this.logSpacedUpdates = {};- this.log = message => {+ this.log = (message) => {log.info(message);if (!this.startNote) {@@ -518,16 +532,18 @@ function BackendScriptApi(this: Api, currentNote: BNote, apiParams: ApiParams) {const { noteId } = this.startNote;this.logMessages[noteId] = this.logMessages[noteId] || [];- this.logSpacedUpdates[noteId] = this.logSpacedUpdates[noteId] || new SpacedUpdate(() => {- const messages = this.logMessages[noteId];- this.logMessages[noteId] = [];-- ws.sendMessageToAllClients({- type: 'api-log-messages',- noteId,- messages- });- }, 100);+ this.logSpacedUpdates[noteId] =+ this.logSpacedUpdates[noteId] ||+ new SpacedUpdate(() => {+ const messages = this.logMessages[noteId];+ this.logMessages[noteId] = [];++ ws.sendMessageToAllClients({+ type: "api-log-messages",+ noteId,+ messages+ });+ }, 100);this.logMessages[noteId].push(message);this.logSpacedUpdates[noteId].scheduleUpdate();@@ -540,12 +556,7 @@ function BackendScriptApi(this: Api, currentNote: BNote, apiParams: ApiParams) {this.getMonthNote = dateNoteService.getMonthNote;this.getYearNote = dateNoteService.getYearNote;- this.sortNotes = (parentNoteId, sortConfig = {}) => treeService.sortNotes(- parentNoteId,- sortConfig.sortBy || "title",- !!sortConfig.reverse,- !!sortConfig.foldersFirst- );+ this.sortNotes = (parentNoteId, sortConfig = {}) => treeService.sortNotes(parentNoteId, sortConfig.sortBy || "title", !!sortConfig.reverse, !!sortConfig.foldersFirst);this.setNoteToParent = treeService.setNoteToParent;this.transactional = sql.transactional;@@ -555,26 +566,41 @@ function BackendScriptApi(this: Api, currentNote: BNote, apiParams: ApiParams) {this.sql = sql;this.getAppInfo = () => appInfo;+ this.createOrUpdateLauncher = (opts) => {+ if (!opts.id) {+ throw new Error("ID is a mandatory parameter for api.createOrUpdateLauncher(opts)");+ }+ if (!opts.id.match(/[a-z0-9]{6,1000}/i)) {+ throw new Error(`ID must be an alphanumeric string at least 6 characters long.`);+ }+ if (!opts.type) {+ throw new Error("Launcher Type is a mandatory parameter for api.createOrUpdateLauncher(opts)");+ }+ if (!["note", "script", "customWidget"].includes(opts.type)) {+ throw new Error(`Given launcher type '${opts.type}'`);+ }+ if (!opts.title?.trim()) {+ throw new Error("Title is a mandatory parameter for api.createOrUpdateLauncher(opts)");+ }+ if (opts.type === "note" && !opts.targetNoteId) {+ throw new Error("targetNoteId is mandatory for launchers of type 'note'");+ }+ if (opts.type === "script" && !opts.scriptNoteId) {+ throw new Error("scriptNoteId is mandatory for launchers of type 'script'");+ }+ if (opts.type === "customWidget" && !opts.widgetNoteId) {+ throw new Error("widgetNoteId is mandatory for launchers of type 'customWidget'");+ }- this.createOrUpdateLauncher = opts => {- if (!opts.id) { throw new Error("ID is a mandatory parameter for api.createOrUpdateLauncher(opts)"); }- if (!opts.id.match(/[a-z0-9]{6,1000}/i)) { throw new Error(`ID must be an alphanumeric string at least 6 characters long.`); }- if (!opts.type) { throw new Error("Launcher Type is a mandatory parameter for api.createOrUpdateLauncher(opts)"); }- if (!["note", "script", "customWidget"].includes(opts.type)) { throw new Error(`Given launcher type '${opts.type}'`); }- if (!opts.title?.trim()) { throw new Error("Title is a mandatory parameter for api.createOrUpdateLauncher(opts)"); }- if (opts.type === 'note' && !opts.targetNoteId) { throw new Error("targetNoteId is mandatory for launchers of type 'note'"); }- if (opts.type === 'script' && !opts.scriptNoteId) { throw new Error("scriptNoteId is mandatory for launchers of type 'script'"); }- if (opts.type === 'customWidget' && !opts.widgetNoteId) { throw new Error("widgetNoteId is mandatory for launchers of type 'customWidget'"); }-- const parentNoteId = opts.isVisible ? '_lbVisibleLaunchers' : '_lbAvailableLaunchers';- const noteId = 'al_' + opts.id;+ const parentNoteId = opts.isVisible ? "_lbVisibleLaunchers" : "_lbAvailableLaunchers";+ const noteId = "al_" + opts.id;const launcherNote =becca.getNote(noteId) ||specialNotesService.createLauncher({noteId: noteId,parentNoteId: parentNoteId,- launcherType: opts.type,+ launcherType: opts.type}).note;if (launcherNote.title !== opts.title) {@@ -590,26 +616,26 @@ function BackendScriptApi(this: Api, currentNote: BNote, apiParams: ApiParams) {}}- if (opts.type === 'note') {- launcherNote.setRelation('target', opts.targetNoteId);- } else if (opts.type === 'script') {- launcherNote.setRelation('script', opts.scriptNoteId);- } else if (opts.type === 'customWidget') {- launcherNote.setRelation('widget', opts.widgetNoteId);+ if (opts.type === "note") {+ launcherNote.setRelation("target", opts.targetNoteId);+ } else if (opts.type === "script") {+ launcherNote.setRelation("script", opts.scriptNoteId);+ } else if (opts.type === "customWidget") {+ launcherNote.setRelation("widget", opts.widgetNoteId);} else {throw new Error(`Unrecognized launcher type '${opts.type}'`);}if (opts.keyboardShortcut) {- launcherNote.setLabel('keyboardShortcut', opts.keyboardShortcut);+ launcherNote.setLabel("keyboardShortcut", opts.keyboardShortcut);} else {- launcherNote.removeLabel('keyboardShortcut');+ launcherNote.removeLabel("keyboardShortcut");}if (opts.icon) {- launcherNote.setLabel('iconClass', `bx ${opts.icon}`);+ launcherNote.setLabel("iconClass", `bx ${opts.icon}`);} else {- launcherNote.removeLabel('iconClass');+ launcherNote.removeLabel("iconClass");}return { note: launcherNote };@@ -626,7 +652,7 @@ function BackendScriptApi(this: Api, currentNote: BNote, apiParams: ApiParams) {}ws.sendMessageToAllClients({- type: 'execute-script',+ type: "execute-script",script: script,params: prepareParams(params),startNoteId: this.startNote?.noteId,@@ -640,11 +666,10 @@ function BackendScriptApi(this: Api, currentNote: BNote, apiParams: ApiParams) {return params;}- return params.map(p => {+ return params.map((p) => {if (typeof p === "function") {return `!@#Function: ${p.toString()}`;- }- else {+ } else {return p;}});@@ -656,9 +681,9 @@ function BackendScriptApi(this: Api, currentNote: BNote, apiParams: ApiParams) {this.__private = {becca- }+ };}export default BackendScriptApi as any as {- new (currentNote: BNote, apiParams: ApiParams): Api+ new (currentNote: BNote, apiParams: ApiParams): Api;};diff --git a/src/services/backend_script_api_interface.ts b/src/services/backend_script_api_interface.tsindex 9ea6f57215..6c0525a1ef 100644--- a/src/services/backend_script_api_interface.ts+++ b/src/services/backend_script_api_interface.ts@@ -5,7 +5,7 @@ import BNote from "../becca/entities/bnote.js";export interface ApiParams {startNote?: BNote | null;originEntity?: AbstractBeccaEntity<any> | null;- pathParams?: string[],- req?: Request,- res?: Response+ pathParams?: string[];+ req?: Request;+ res?: Response;}diff --git a/src/services/backup.ts b/src/services/backup.tsindex b5e2737144..8e9851602c 100644--- a/src/services/backup.ts+++ b/src/services/backup.ts@@ -11,30 +11,31 @@ import sql from "./sql.js";import path from "path";import type { OptionNames } from "./options_interface.js";-type BackupType = ("daily" | "weekly" | "monthly");+type BackupType = "daily" | "weekly" | "monthly";function getExistingBackups() {if (!fs.existsSync(dataDir.BACKUP_DIR)) {return [];}- return fs.readdirSync(dataDir.BACKUP_DIR)- .filter(fileName => fileName.includes("backup"))- .map(fileName => {+ return fs+ .readdirSync(dataDir.BACKUP_DIR)+ .filter((fileName) => fileName.includes("backup"))+ .map((fileName) => {const filePath = path.resolve(dataDir.BACKUP_DIR, fileName);- const stat = fs.statSync(filePath)+ const stat = fs.statSync(filePath);- return {fileName, filePath, mtime: stat.mtime};+ return { fileName, filePath, mtime: stat.mtime };});}function regularBackup() {cls.init(() => {- periodBackup('lastDailyBackupDate', 'daily', 24 * 3600);+ periodBackup("lastDailyBackupDate", "daily", 24 * 3600);- periodBackup('lastWeeklyBackupDate', 'weekly', 7 * 24 * 3600);+ periodBackup("lastWeeklyBackupDate", "weekly", 7 * 24 * 3600);- periodBackup('lastMonthlyBackupDate', 'monthly', 30 * 24 * 3600);+ periodBackup("lastMonthlyBackupDate", "monthly", 30 * 24 * 3600);});}diff --git a/src/services/blob.ts b/src/services/blob.tsindex 0040da189a..c4684c2ae5 100644--- a/src/services/blob.ts+++ b/src/services/blob.ts@@ -50,7 +50,7 @@ function processContent(content: Buffer | string | null, isProtected: boolean, i}}-function calculateContentHash({blobId, content}: Blob) {+function calculateContentHash({ blobId, content }: Blob) {return hash(`${blobId}|${content.toString()}`);}diff --git a/src/services/branches.ts b/src/services/branches.tsindex 88454c4ab6..6665903bf8 100644--- a/src/services/branches.ts+++ b/src/services/branches.ts@@ -4,7 +4,7 @@ import BBranch from "../becca/entities/bbranch.js";function moveBranchToNote(branchToMove: BBranch, targetParentNoteId: string) {if (branchToMove.parentNoteId === targetParentNoteId) {- return {success: true}; // no-op+ return { success: true }; // no-op}const validationResult = treeService.validateParentChild(targetParentNoteId, branchToMove.noteId, branchToMove.branchId);@@ -13,7 +13,7 @@ function moveBranchToNote(branchToMove: BBranch, targetParentNoteId: string) {return [200, validationResult];}- const maxNotePos = sql.getValue<number | null>('SELECT MAX(notePosition) FROM branches WHERE parentNoteId = ? AND isDeleted = 0', [targetParentNoteId]);+ const maxNotePos = sql.getValue<number | null>("SELECT MAX(notePosition) FROM branches WHERE parentNoteId = ? AND isDeleted = 0", [targetParentNoteId]);const newNotePos = !maxNotePos ? 0 : maxNotePos + 10;const newBranch = branchToMove.createClone(targetParentNoteId, newNotePos);diff --git a/src/services/builtin_attributes.ts b/src/services/builtin_attributes.tsindex 2c40204c5c..30c0b6ce5a 100644--- a/src/services/builtin_attributes.ts+++ b/src/services/builtin_attributes.ts@@ -1,99 +1,99 @@export default [// label names- { type: 'label', name: 'inbox' },- { type: 'label', name: 'disableVersioning' },- { type: 'label', name: 'calendarRoot' },- { type: 'label', name: 'archived' },- { type: 'label', name: 'excludeFromExport' },- { type: 'label', name: 'disableInclusion' },- { type: 'label', name: 'appCss' },- { type: 'label', name: 'appTheme' },- { type: 'label', name: 'appThemeBase' },- { type: 'label', name: 'hidePromotedAttributes' },- { type: 'label', name: 'readOnly' },- { type: 'label', name: 'autoReadOnlyDisabled' },- { type: 'label', name: 'cssClass' },- { type: 'label', name: 'iconClass' },- { type: 'label', name: 'keyboardShortcut' },- { type: 'label', name: 'run', isDangerous: true },- { type: 'label', name: 'runOnInstance', isDangerous: false },- { type: 'label', name: 'runAtHour', isDangerous: false },- { type: 'label', name: 'customRequestHandler', isDangerous: true },- { type: 'label', name: 'customResourceProvider', isDangerous: true },- { type: 'label', name: 'widget', isDangerous: true },- { type: 'label', name: 'noteInfoWidgetDisabled' },- { type: 'label', name: 'linkMapWidgetDisabled' },- { type: 'label', name: 'revisionsWidgetDisabled' },- { type: 'label', name: 'whatLinksHereWidgetDisabled' },- { type: 'label', name: 'similarNotesWidgetDisabled' },- { type: 'label', name: 'workspace' },- { type: 'label', name: 'workspaceIconClass' },- { type: 'label', name: 'workspaceTabBackgroundColor' },- { type: 'label', name: 'workspaceCalendarRoot' },- { type: 'label', name: 'workspaceTemplate' },- { type: 'label', name: 'searchHome' },- { type: 'label', name: 'workspaceInbox' },- { type: 'label', name: 'workspaceSearchHome' },- { type: 'label', name: 'sqlConsoleHome' },- { type: 'label', name: 'datePattern' },- { type: 'label', name: 'pageSize' },- { type: 'label', name: 'viewType' },- { type: 'label', name: 'mapRootNoteId' },- { type: 'label', name: 'bookmarkFolder' },- { type: 'label', name: 'sorted' },- { type: 'label', name: 'sortDirection' },- { type: 'label', name: 'sortFoldersFirst' },- { type: 'label', name: 'sortNatural' },- { type: 'label', name: 'sortLocale' },- { type: 'label', name: 'top' },- { type: 'label', name: 'bottom' },- { type: 'label', name: 'fullContentWidth' },- { type: 'label', name: 'shareHiddenFromTree' },- { type: 'label', name: 'shareExternalLink' },- { type: 'label', name: 'shareAlias' },- { type: 'label', name: 'shareOmitDefaultCss' },- { type: 'label', name: 'shareRoot' },- { type: 'label', name: 'shareDescription' },- { type: 'label', name: 'shareRaw' },- { type: 'label', name: 'shareDisallowRobotIndexing' },- { type: 'label', name: 'shareCredentials' },- { type: 'label', name: 'shareIndex' },- { type: 'label', name: 'displayRelations' },- { type: 'label', name: 'hideRelations' },- { type: 'label', name: 'titleTemplate', isDangerous: true },- { type: 'label', name: 'template' },- { type: 'label', name: 'toc' },- { type: 'label', name: 'color' },- { type: 'label', name: 'keepCurrentHoisting'},- { type: 'label', name: 'executeButton'},- { type: 'label', name: 'executeDescription'},- { type: 'label', name: 'newNotesOnTop'},- { type: 'label', name: 'clipperInbox'},- { type: 'label', name: 'webViewSrc', isDangerous: true },- { type: 'label', name: 'hideHighlightWidget' },+ { type: "label", name: "inbox" },+ { type: "label", name: "disableVersioning" },+ { type: "label", name: "calendarRoot" },+ { type: "label", name: "archived" },+ { type: "label", name: "excludeFromExport" },+ { type: "label", name: "disableInclusion" },+ { type: "label", name: "appCss" },+ { type: "label", name: "appTheme" },+ { type: "label", name: "appThemeBase" },+ { type: "label", name: "hidePromotedAttributes" },+ { type: "label", name: "readOnly" },+ { type: "label", name: "autoReadOnlyDisabled" },+ { type: "label", name: "cssClass" },+ { type: "label", name: "iconClass" },+ { type: "label", name: "keyboardShortcut" },+ { type: "label", name: "run", isDangerous: true },+ { type: "label", name: "runOnInstance", isDangerous: false },+ { type: "label", name: "runAtHour", isDangerous: false },+ { type: "label", name: "customRequestHandler", isDangerous: true },+ { type: "label", name: "customResourceProvider", isDangerous: true },+ { type: "label", name: "widget", isDangerous: true },+ { type: "label", name: "noteInfoWidgetDisabled" },+ { type: "label", name: "linkMapWidgetDisabled" },+ { type: "label", name: "revisionsWidgetDisabled" },+ { type: "label", name: "whatLinksHereWidgetDisabled" },+ { type: "label", name: "similarNotesWidgetDisabled" },+ { type: "label", name: "workspace" },+ { type: "label", name: "workspaceIconClass" },+ { type: "label", name: "workspaceTabBackgroundColor" },+ { type: "label", name: "workspaceCalendarRoot" },+ { type: "label", name: "workspaceTemplate" },+ { type: "label", name: "searchHome" },+ { type: "label", name: "workspaceInbox" },+ { type: "label", name: "workspaceSearchHome" },+ { type: "label", name: "sqlConsoleHome" },+ { type: "label", name: "datePattern" },+ { type: "label", name: "pageSize" },+ { type: "label", name: "viewType" },+ { type: "label", name: "mapRootNoteId" },+ { type: "label", name: "bookmarkFolder" },+ { type: "label", name: "sorted" },+ { type: "label", name: "sortDirection" },+ { type: "label", name: "sortFoldersFirst" },+ { type: "label", name: "sortNatural" },+ { type: "label", name: "sortLocale" },+ { type: "label", name: "top" },+ { type: "label", name: "bottom" },+ { type: "label", name: "fullContentWidth" },+ { type: "label", name: "shareHiddenFromTree" },+ { type: "label", name: "shareExternalLink" },+ { type: "label", name: "shareAlias" },+ { type: "label", name: "shareOmitDefaultCss" },+ { type: "label", name: "shareRoot" },+ { type: "label", name: "shareDescription" },+ { type: "label", name: "shareRaw" },+ { type: "label", name: "shareDisallowRobotIndexing" },+ { type: "label", name: "shareCredentials" },+ { type: "label", name: "shareIndex" },+ { type: "label", name: "displayRelations" },+ { type: "label", name: "hideRelations" },+ { type: "label", name: "titleTemplate", isDangerous: true },+ { type: "label", name: "template" },+ { type: "label", name: "toc" },+ { type: "label", name: "color" },+ { type: "label", name: "keepCurrentHoisting" },+ { type: "label", name: "executeButton" },+ { type: "label", name: "executeDescription" },+ { type: "label", name: "newNotesOnTop" },+ { type: "label", name: "clipperInbox" },+ { type: "label", name: "webViewSrc", isDangerous: true },+ { type: "label", name: "hideHighlightWidget" },// relation names- { type: 'relation', name: 'internalLink' },- { type: 'relation', name: 'imageLink' },- { type: 'relation', name: 'relationMapLink' },- { type: 'relation', name: 'includeMapLink' },- { type: 'relation', name: 'runOnNoteCreation', isDangerous: true },- { type: 'relation', name: 'runOnNoteTitleChange', isDangerous: true },- { type: 'relation', name: 'runOnNoteChange', isDangerous: true },- { type: 'relation', name: 'runOnNoteContentChange', isDangerous: true },- { type: 'relation', name: 'runOnNoteDeletion', isDangerous: true },- { type: 'relation', name: 'runOnBranchCreation', isDangerous: true },- { type: 'relation', name: 'runOnBranchChange', isDangerous: true },- { type: 'relation', name: 'runOnBranchDeletion', isDangerous: true },- { type: 'relation', name: 'runOnChildNoteCreation', isDangerous: true },- { type: 'relation', name: 'runOnAttributeCreation', isDangerous: true },- { type: 'relation', name: 'runOnAttributeChange', isDangerous: true },- { type: 'relation', name: 'template' },- { type: 'relation', name: 'inherit' },- { type: 'relation', name: 'widget', isDangerous: true },- { type: 'relation', name: 'renderNote', isDangerous: true },- { type: 'relation', name: 'shareCss' },- { type: 'relation', name: 'shareJs' },- { type: 'relation', name: 'shareTemplate' },- { type: 'relation', name: 'shareFavicon' },+ { type: "relation", name: "internalLink" },+ { type: "relation", name: "imageLink" },+ { type: "relation", name: "relationMapLink" },+ { type: "relation", name: "includeMapLink" },+ { type: "relation", name: "runOnNoteCreation", isDangerous: true },+ { type: "relation", name: "runOnNoteTitleChange", isDangerous: true },+ { type: "relation", name: "runOnNoteChange", isDangerous: true },+ { type: "relation", name: "runOnNoteContentChange", isDangerous: true },+ { type: "relation", name: "runOnNoteDeletion", isDangerous: true },+ { type: "relation", name: "runOnBranchCreation", isDangerous: true },+ { type: "relation", name: "runOnBranchChange", isDangerous: true },+ { type: "relation", name: "runOnBranchDeletion", isDangerous: true },+ { type: "relation", name: "runOnChildNoteCreation", isDangerous: true },+ { type: "relation", name: "runOnAttributeCreation", isDangerous: true },+ { type: "relation", name: "runOnAttributeChange", isDangerous: true },+ { type: "relation", name: "template" },+ { type: "relation", name: "inherit" },+ { type: "relation", name: "widget", isDangerous: true },+ { type: "relation", name: "renderNote", isDangerous: true },+ { type: "relation", name: "shareCss" },+ { type: "relation", name: "shareJs" },+ { type: "relation", name: "shareTemplate" },+ { type: "relation", name: "shareFavicon" }];diff --git a/src/services/bulk_actions.ts b/src/services/bulk_actions.tsindex eb99f5f2be..3e9b06b4e9 100644--- a/src/services/bulk_actions.ts+++ b/src/services/bulk_actions.ts@@ -12,7 +12,6 @@ interface Action {oldLabelName: string;newLabelName: string;-relationName: string;oldRelationName: string;newRelationName: string;@@ -37,8 +36,9 @@ const ACTION_HANDLERS: Record<string, ActionHandler> = {note.deleteNote(deleteId);},deleteRevisions: (action, note) => {- const revisionIds = note.getRevisions()- .map(rev => rev.revisionId)+ const revisionIds = note+ .getRevisions()+ .map((rev) => rev.revisionId).filter((rev) => !!rev) as string[];eraseService.eraseRevisions(revisionIds);},@@ -66,7 +66,7 @@ const ACTION_HANDLERS: Record<string, ActionHandler> = {renameLabel: (action, note) => {for (const label of note.getOwnedLabels(action.oldLabelName)) {// attribute name is immutable, renaming means delete old + create new- const newLabel = label.createClone('label', action.newLabelName, label.value);+ const newLabel = label.createClone("label", action.newLabelName, label.value);newLabel.save();label.markAsDeleted();@@ -75,7 +75,7 @@ const ACTION_HANDLERS: Record<string, ActionHandler> = {renameRelation: (action, note) => {for (const relation of note.getOwnedRelations(action.oldRelationName)) {// attribute name is immutable, renaming means delete old + create new- const newRelation = relation.createClone('relation', action.newRelationName, relation.value);+ const newRelation = relation.createClone("relation", action.newRelationName, relation.value);newRelation.save();relation.markAsDeleted();@@ -106,8 +106,7 @@ const ACTION_HANDLERS: Record<string, ActionHandler> = {if (note.getParentBranches().length > 1) {res = cloningService.cloneNoteToParentNote(note.noteId, action.targetParentNoteId);- }- else {+ } else {res = branchService.moveBranchToNote(note.getParentBranches()[0], action.targetParentNoteId);}@@ -117,7 +116,7 @@ const ACTION_HANDLERS: Record<string, ActionHandler> = {},executeScript: (action, note) => {if (!action.script || !action.script.trim()) {- log.info("Ignoring executeScript since the script is empty.")+ log.info("Ignoring executeScript since the script is empty.");return;}@@ -129,8 +128,9 @@ const ACTION_HANDLERS: Record<string, ActionHandler> = {};function getActions(note: BNote) {- return note.getLabels('action')- .map(actionLabel => {+ return note+ .getLabels("action")+ .map((actionLabel) => {let action;try {@@ -147,7 +147,7 @@ function getActions(note: BNote) {return action;})- .filter(a => !!a);+ .filter((a) => !!a);}function executeActions(note: BNote, searchResultNoteIds: string[] | Set<string>) {diff --git a/src/services/cloning.ts b/src/services/cloning.tsindex 6f35e671fa..4166d8a11f 100644--- a/src/services/cloning.ts+++ b/src/services/cloning.ts@@ -1,11 +1,11 @@"use strict";-import sql from './sql.js';-import eventChangesService from './entity_changes.js';-import treeService from './tree.js';-import BBranch from '../becca/entities/bbranch.js';-import becca from '../becca/becca.js';-import log from './log.js';+import sql from "./sql.js";+import eventChangesService from "./entity_changes.js";+import treeService from "./tree.js";+import BBranch from "../becca/entities/bbranch.js";+import becca from "../becca/becca.js";+import log from "./log.js";export interface CloneResponse {success: boolean;@@ -16,15 +16,15 @@ export interface CloneResponse {function cloneNoteToParentNote(noteId: string, parentNoteId: string, prefix: string | null = null): CloneResponse {if (!(noteId in becca.notes) || !(parentNoteId in becca.notes)) {- return { success: false, message: 'Note cannot be cloned because either the cloned note or the intended parent is deleted.' };+ return { success: false, message: "Note cannot be cloned because either the cloned note or the intended parent is deleted." };}const parentNote = becca.getNote(parentNoteId);if (!parentNote) {- return { success: false, message: 'Note cannot be cloned because the parent note could not be found.' };+ return { success: false, message: "Note cannot be cloned because the parent note could not be found." };}- if (parentNote.type === 'search') {+ if (parentNote.type === "search") {return {success: false,message: "Can't clone into a search note"@@ -80,7 +80,7 @@ function ensureNoteIsPresentInParent(noteId: string, parentNoteId: string, prefiif (!parentNote) {return { branch: null, success: false, message: "Can't find parent note." };}- if (parentNote.type === 'search') {+ if (parentNote.type === "search") {return { branch: null, success: false, message: "Can't clone into a search note" };}@@ -125,14 +125,13 @@ function ensureNoteIsAbsentFromParent(noteId: string, parentNoteId: string) {function toggleNoteInParent(present: boolean, noteId: string, parentNoteId: string, prefix?: string) {if (present) {return ensureNoteIsPresentInParent(noteId, parentNoteId, prefix);- }- else {+ } else {return ensureNoteIsAbsentFromParent(noteId, parentNoteId);}}function cloneNoteAfter(noteId: string, afterBranchId: string) {- if (['_hidden', 'root'].includes(noteId)) {+ if (["_hidden", "root"].includes(noteId)) {return { success: false, message: `Cloning the note '${noteId}' is forbidden.` };}@@ -142,8 +141,8 @@ function cloneNoteAfter(noteId: string, afterBranchId: string) {return { success: false, message: `Branch '${afterBranchId}' does not exist.` };}- if (afterBranch.noteId === '_hidden') {- return { success: false, message: 'Cannot clone after the hidden branch.' };+ if (afterBranch.noteId === "_hidden") {+ return { success: false, message: "Cannot clone after the hidden branch." };}const afterNote = becca.getBranch(afterBranchId);@@ -156,7 +155,7 @@ function cloneNoteAfter(noteId: string, afterBranchId: string) {const parentNote = becca.getNote(afterNote.parentNoteId);- if (!parentNote || parentNote.type === 'search') {+ if (!parentNote || parentNote.type === "search") {return {success: false,message: "Can't clone into a search note"@@ -171,8 +170,7 @@ function cloneNoteAfter(noteId: string, afterBranchId: string) {// we don't change utcDateModified, so other changes are prioritized in case of conflict// also we would have to sync all those modified branches otherwise hash checks would fail- sql.execute("UPDATE branches SET notePosition = notePosition + 10 WHERE parentNoteId = ? AND notePosition > ? AND isDeleted = 0",- [afterNote.parentNoteId, afterNote.notePosition]);+ sql.execute("UPDATE branches SET notePosition = notePosition + 10 WHERE parentNoteId = ? AND notePosition > ? AND isDeleted = 0", [afterNote.parentNoteId, afterNote.notePosition]);eventChangesService.putNoteReorderingEntityChange(afterNote.parentNoteId);diff --git a/src/services/cls.ts b/src/services/cls.tsindex dbc527f4d9..b07e1026a2 100644--- a/src/services/cls.ts+++ b/src/services/cls.ts@@ -1,5 +1,5 @@import clsHooked from "cls-hooked";-import { EntityChange } from './entity_changes_interface.js';+import { EntityChange } from "./entity_changes_interface.js";const namespace = clsHooked.createNamespace("trilium");type Callback = (...args: any[]) => any;@@ -12,11 +12,10 @@ function wrap(callback: Callback) {return () => {try {init(callback);- }- catch (e: any) {+ } catch (e: any) {console.log(`Error occurred: ${e.message}: ${e.stack}`);}- }+ };}function get(key: string) {@@ -28,64 +27,64 @@ function set(key: string, value: any) {}function getHoistedNoteId() {- return namespace.get('hoistedNoteId') || 'root';+ return namespace.get("hoistedNoteId") || "root";}function getComponentId() {- return namespace.get('componentId');+ return namespace.get("componentId");}function getLocalNowDateTime() {- return namespace.get('localNowDateTime');+ return namespace.get("localNowDateTime");}function disableEntityEvents() {- namespace.set('disableEntityEvents', true);+ namespace.set("disableEntityEvents", true);}function enableEntityEvents() {- namespace.set('disableEntityEvents', false);+ namespace.set("disableEntityEvents", false);}function isEntityEventsDisabled() {- return !!namespace.get('disableEntityEvents');+ return !!namespace.get("disableEntityEvents");}function setMigrationRunning(running: boolean) {- namespace.set('migrationRunning', !!running);+ namespace.set("migrationRunning", !!running);}function isMigrationRunning() {- return !!namespace.get('migrationRunning');+ return !!namespace.get("migrationRunning");}function disableSlowQueryLogging(disable: boolean) {- namespace.set('disableSlowQueryLogging', disable);+ namespace.set("disableSlowQueryLogging", disable);}function isSlowQueryLoggingDisabled() {- return !!namespace.get('disableSlowQueryLogging');+ return !!namespace.get("disableSlowQueryLogging");}function getAndClearEntityChangeIds() {- const entityChangeIds = namespace.get('entityChangeIds') || [];+ const entityChangeIds = namespace.get("entityChangeIds") || [];- namespace.set('entityChangeIds', []);+ namespace.set("entityChangeIds", []);return entityChangeIds;}function putEntityChange(entityChange: EntityChange) {- if (namespace.get('ignoreEntityChangeIds')) {+ if (namespace.get("ignoreEntityChangeIds")) {return;}- const entityChangeIds = namespace.get('entityChangeIds') || [];+ const entityChangeIds = namespace.get("entityChangeIds") || [];// store only ID since the record can be modified (e.g., in erase)entityChangeIds.push(entityChange.id);- namespace.set('entityChangeIds', entityChangeIds);+ namespace.set("entityChangeIds", entityChangeIds);}function reset() {@@ -93,7 +92,7 @@ function reset() {}function ignoreEntityChangeIds() {- namespace.set('ignoreEntityChangeIds', true);+ namespace.set("ignoreEntityChangeIds", true);}export default {diff --git a/src/services/code_block_theme.ts b/src/services/code_block_theme.tsindex 92b3bb1928..e56dc8ee44 100644--- a/src/services/code_block_theme.ts+++ b/src/services/code_block_theme.ts@@ -5,7 +5,7 @@*/import fs from "fs";-import themeNames from "./code_block_theme_names.json" with { type: "json" }+import themeNames from "./code_block_theme_names.json" with { type: "json" };import { t } from "i18next";import { join } from "path";import { isElectron, getResourceDir } from "./utils.js";@@ -42,7 +42,7 @@ export function listSyntaxHighlightingThemes() {}],...groupThemesByLightOrDark(systemThemes)- }+ };}function getStylesDirectory() {@@ -62,7 +62,8 @@ function getStylesDirectory() {* @returns the list of themes.*/function readThemesFromFileSystem(path: string): ColorTheme[] {- return fs.readdirSync(path)+ return fs+ .readdirSync(path).filter((el) => el.endsWith(".min.css")).map((name) => {const nameWithoutExtension = name.replace(".min.css", "");diff --git a/src/services/code_block_theme_names.json b/src/services/code_block_theme_names.jsonindex f1095e321c..0981092f2b 100644--- a/src/services/code_block_theme_names.json+++ b/src/services/code_block_theme_names.json@@ -1,75 +1,75 @@{- "1c light": "1C (Light)",- "a11y dark": "a11y (Dark)",- "a11y light": "a11y (Light)",- "agate": "Agate (Dark)",- "an old hope": "An Old Hope (Dark)",- "androidstudio": "Android Studio (Dark)",- "arduino light": "Arduino (Light)",- "arta": "Arta (Dark)",- "ascetic": "Ascetic (Light)",- "atom one dark reasonable": "Atom One with ReasonML support (Dark)",- "atom one dark": "Atom One (Dark)",- "atom one light": "Atom One (Light)",- "brown paper": "Brown Paper (Light)",- "codepen embed": "CodePen Embed (Dark)",- "color brewer": "Color Brewer (Light)",- "dark": "Dark",- "default": "Original highlight.js Theme (Light)",- "devibeans": "devibeans (Dark)",- "docco": "Docco (Light)",- "far": "FAR (Dark)",- "felipec": "FelipeC (Dark)",- "foundation": "Foundation 4 Docs (Light)",- "github dark dimmed": "GitHub Dimmed (Dark)",- "github dark": "GitHub (Dark)",- "github": "GitHub (Light)",- "gml": "GML (Dark)",- "googlecode": "Google Code (Light)",- "gradient dark": "Gradient (Dark)",- "gradient light": "Gradient (Light)",- "grayscale": "Grayscale (Light)",- "hybrid": "hybrid (Dark)",- "idea": "Idea (Light)",- "intellij light": "IntelliJ (Light)",- "ir black": "IR Black (Dark)",- "isbl editor dark": "ISBL Editor (Dark)",- "isbl editor light": "ISBL Editor (Light)",- "kimbie dark": "Kimbie (Dark)",- "kimbie light": "Kimbie (Light)",- "lightfair": "Lightfair (Light)",- "lioshi": "Lioshi (Dark)",- "magula": "Magula (Light)",- "mono blue": "Mono Blue (Light)",- "monokai sublime": "Monokai Sublime (Dark)",- "monokai": "Monokai (Dark)",- "night owl": "Night Owl (Dark)",- "nnfx dark": "NNFX (Dark)",- "nnfx light": "NNFX (Light)",- "nord": "Nord (Dark)",- "obsidian": "Obsidian (Dark)",- "panda syntax dark": "Panda (Dark)",- "panda syntax light": "Panda (Light)",- "paraiso dark": "Paraiso (Dark)",- "paraiso light": "Paraiso (Light)",- "pojoaque": "Pojoaque (Dark)",- "purebasic": "PureBasic (Light)",- "qtcreator dark": "Qt Creator (Dark)",- "qtcreator light": "Qt Creator (Light)",- "rainbow": "Rainbow (Dark)",- "routeros": "RouterOS Script (Light)",- "school book": "School Book (Light)",- "shades of purple": "Shades of Purple (Dark)",- "srcery": "Srcery (Dark)",- "stackoverflow dark": "Stack Overflow (Dark)",- "stackoverflow light": "Stack Overflow (Light)",- "sunburst": "Sunburst (Dark)",- "tokyo night dark": "Tokyo Night (Dark)",- "tokyo night light": "Tokyo Night (Light)",- "tomorrow night blue": "Tomorrow Night Blue (Dark)",- "tomorrow night bright": "Tomorrow Night Bright (Dark)",- "vs": "Visual Studio (Light)",- "vs2015": "Visual Studio 2015 (Dark)",- "xcode": "Xcode (Light)",- "xt256": "xt256 (Dark)"+ "1c light": "1C (Light)",+ "a11y dark": "a11y (Dark)",+ "a11y light": "a11y (Light)",+ "agate": "Agate (Dark)",+ "an old hope": "An Old Hope (Dark)",+ "androidstudio": "Android Studio (Dark)",+ "arduino light": "Arduino (Light)",+ "arta": "Arta (Dark)",+ "ascetic": "Ascetic (Light)",+ "atom one dark reasonable": "Atom One with ReasonML support (Dark)",+ "atom one dark": "Atom One (Dark)",+ "atom one light": "Atom One (Light)",+ "brown paper": "Brown Paper (Light)",+ "codepen embed": "CodePen Embed (Dark)",+ "color brewer": "Color Brewer (Light)",+ "dark": "Dark",+ "default": "Original highlight.js Theme (Light)",+ "devibeans": "devibeans (Dark)",+ "docco": "Docco (Light)",+ "far": "FAR (Dark)",+ "felipec": "FelipeC (Dark)",+ "foundation": "Foundation 4 Docs (Light)",+ "github dark dimmed": "GitHub Dimmed (Dark)",+ "github dark": "GitHub (Dark)",+ "github": "GitHub (Light)",+ "gml": "GML (Dark)",+ "googlecode": "Google Code (Light)",+ "gradient dark": "Gradient (Dark)",+ "gradient light": "Gradient (Light)",+ "grayscale": "Grayscale (Light)",+ "hybrid": "hybrid (Dark)",+ "idea": "Idea (Light)",+ "intellij light": "IntelliJ (Light)",+ "ir black": "IR Black (Dark)",+ "isbl editor dark": "ISBL Editor (Dark)",+ "isbl editor light": "ISBL Editor (Light)",+ "kimbie dark": "Kimbie (Dark)",+ "kimbie light": "Kimbie (Light)",+ "lightfair": "Lightfair (Light)",+ "lioshi": "Lioshi (Dark)",+ "magula": "Magula (Light)",+ "mono blue": "Mono Blue (Light)",+ "monokai sublime": "Monokai Sublime (Dark)",+ "monokai": "Monokai (Dark)",+ "night owl": "Night Owl (Dark)",+ "nnfx dark": "NNFX (Dark)",+ "nnfx light": "NNFX (Light)",+ "nord": "Nord (Dark)",+ "obsidian": "Obsidian (Dark)",+ "panda syntax dark": "Panda (Dark)",+ "panda syntax light": "Panda (Light)",+ "paraiso dark": "Paraiso (Dark)",+ "paraiso light": "Paraiso (Light)",+ "pojoaque": "Pojoaque (Dark)",+ "purebasic": "PureBasic (Light)",+ "qtcreator dark": "Qt Creator (Dark)",+ "qtcreator light": "Qt Creator (Light)",+ "rainbow": "Rainbow (Dark)",+ "routeros": "RouterOS Script (Light)",+ "school book": "School Book (Light)",+ "shades of purple": "Shades of Purple (Dark)",+ "srcery": "Srcery (Dark)",+ "stackoverflow dark": "Stack Overflow (Dark)",+ "stackoverflow light": "Stack Overflow (Light)",+ "sunburst": "Sunburst (Dark)",+ "tokyo night dark": "Tokyo Night (Dark)",+ "tokyo night light": "Tokyo Night (Light)",+ "tomorrow night blue": "Tomorrow Night Blue (Dark)",+ "tomorrow night bright": "Tomorrow Night Bright (Dark)",+ "vs": "Visual Studio (Light)",+ "vs2015": "Visual Studio 2015 (Dark)",+ "xcode": "Xcode (Light)",+ "xt256": "xt256 (Dark)"}diff --git a/src/services/config.ts b/src/services/config.tsindex a5469efb50..43ecc39dab 100644--- a/src/services/config.ts+++ b/src/services/config.ts@@ -9,11 +9,11 @@ import resourceDir from "./resource_dir.js";const configSampleFilePath = path.resolve(resourceDir.RESOURCE_DIR, "config-sample.ini");if (!fs.existsSync(dataDir.CONFIG_INI_PATH)) {- const configSample = fs.readFileSync(configSampleFilePath).toString('utf8');+ const configSample = fs.readFileSync(configSampleFilePath).toString("utf8");fs.writeFileSync(dataDir.CONFIG_INI_PATH, configSample);}-const config = ini.parse(fs.readFileSync(dataDir.CONFIG_INI_PATH, 'utf-8'));+const config = ini.parse(fs.readFileSync(dataDir.CONFIG_INI_PATH, "utf-8"));export default config;diff --git a/src/services/consistency_checks.ts b/src/services/consistency_checks.tsindex fa1cec21d0..743765af03 100644--- a/src/services/consistency_checks.ts+++ b/src/services/consistency_checks.ts@@ -14,21 +14,20 @@ import { hash as getHash, hashedBlobId, randomString } from "../services/utils.jimport eraseService from "../services/erase.js";import sanitizeAttributeName from "./sanitize_attribute_name.js";import noteTypesService from "../services/note_types.js";-import { BranchRow } from '../becca/entities/rows.js';-import { EntityChange } from './entity_changes_interface.js';+import { BranchRow } from "../becca/entities/rows.js";+import { EntityChange } from "./entity_changes_interface.js";import becca_loader from "../becca/becca_loader.js";const noteTypes = noteTypesService.getNoteTypeNames();class ConsistencyChecks {-private autoFix: boolean;private unrecoveredConsistencyErrors: boolean;private fixedIssues: boolean;private reloadNeeded: boolean;/**- * @param autoFix - automatically fix all encountered problems. False is only for debugging during development (fail fast)- */+ * @param autoFix - automatically fix all encountered problems. False is only for debugging during development (fail fast)+ */constructor(autoFix: boolean) {this.autoFix = autoFix;this.unrecoveredConsistencyErrors = false;@@ -71,7 +70,7 @@ class ConsistencyChecks {/** @returns true if cycle was found and we should try again */const checkTreeCycle = (noteId: string, path: string[]) => {- if (noteId === 'root') {+ if (noteId === "root") {return false;}@@ -80,13 +79,12 @@ class ConsistencyChecks {if (this.autoFix) {const branch = becca.getBranchFromChildAndParent(noteId, parentNoteId);if (branch) {- branch.markAsDeleted('cycle-autofix');+ branch.markAsDeleted("cycle-autofix");logFix(`Branch '${branch.branchId}' between child '${noteId}' and parent '${parentNoteId}' has been deleted since it was causing a tree cycle.`);}return true;- }- else {+ } else {logError(`Tree cycle detected at parent-child relationship: '${parentNoteId}' - '${noteId}', whole path: '${path}'`);this.unrecoveredConsistencyErrors = true;@@ -135,13 +133,14 @@ class ConsistencyChecks {}findBrokenReferenceIssues() {- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT branchId, branches.noteIdFROM branchesLEFT JOIN notes USING (noteId)WHERE branches.isDeleted = 0AND notes.noteId IS NULL`,- ({branchId, noteId}) => {+ ({ branchId, noteId }) => {if (this.autoFix) {const branch = becca.getBranch(branchId);if (!branch) {@@ -155,16 +154,18 @@ class ConsistencyChecks {} else {logError(`Branch '${branchId}' references missing note '${noteId}'`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT branchId, branches.parentNoteId AS parentNoteIdFROM branchesLEFT JOIN notes ON notes.noteId = branches.parentNoteIdWHERE branches.isDeleted = 0AND branches.noteId != 'root'AND notes.noteId IS NULL`,- ({branchId, parentNoteId}) => {+ ({ branchId, parentNoteId }) => {if (this.autoFix) {// Delete the old branch and recreate it with root as parent.const oldBranch = becca.getBranch(branchId);@@ -184,9 +185,9 @@ class ConsistencyChecks {if (note.getParentBranches().length === 0) {const newBranch = new BBranch({- parentNoteId: 'root',+ parentNoteId: "root",noteId: noteId,- prefix: 'recovered'+ prefix: "recovered"}).save();message += `${newBranch.branchId} was created in the root instead.`;@@ -200,15 +201,17 @@ class ConsistencyChecks {} else {logError(`Branch '${branchId}' references missing parent note '${parentNoteId}'`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT attributeId, attributes.noteIdFROM attributesLEFT JOIN notes USING (noteId)WHERE attributes.isDeleted = 0AND notes.noteId IS NULL`,- ({attributeId, noteId}) => {+ ({ attributeId, noteId }) => {if (this.autoFix) {const attribute = becca.getAttribute(attributeId);if (!attribute) {@@ -222,16 +225,18 @@ class ConsistencyChecks {} else {logError(`Attribute '${attributeId}' references missing source note '${noteId}'`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT attributeId, attributes.value AS noteIdFROM attributesLEFT JOIN notes ON notes.noteId = attributes.valueWHERE attributes.isDeleted = 0AND attributes.type = 'relation'AND notes.noteId IS NULL`,- ({attributeId, noteId}) => {+ ({ attributeId, noteId }) => {if (this.autoFix) {const attribute = becca.getAttribute(attributeId);if (!attribute) {@@ -241,13 +246,15 @@ class ConsistencyChecks {this.reloadNeeded = true;- logFix(`Relation '${attributeId}' has been deleted since it references missing note '${noteId}'`)+ logFix(`Relation '${attributeId}' has been deleted since it references missing note '${noteId}'`);} else {- logError(`Relation '${attributeId}' references missing note '${noteId}'`)+ logError(`Relation '${attributeId}' references missing note '${noteId}'`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT attachmentId, attachments.ownerId AS noteIdFROM attachmentsWHERE attachments.ownerId NOT IN (@@ -256,7 +263,7 @@ class ConsistencyChecks {SELECT revisionId FROM revisions)AND attachments.isDeleted = 0`,- ({attachmentId, ownerId}) => {+ ({ attachmentId, ownerId }) => {if (this.autoFix) {const attachment = becca.getAttachment(attachmentId);if (!attachment) {@@ -270,7 +277,8 @@ class ConsistencyChecks {} else {logError(`Attachment '${attachmentId}' references missing note/revision '${ownerId}'`);}- });+ }+ );}findExistencyIssues() {@@ -280,14 +288,15 @@ class ConsistencyChecks {// the order here is important - first we might need to delete inconsistent branches, and after that// another check might create missing branch- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT branchId,noteIdFROM branchesJOIN notes USING (noteId)WHERE notes.isDeleted = 1AND branches.isDeleted = 0`,- ({branchId, noteId}) => {+ ({ branchId, noteId }) => {if (this.autoFix) {const branch = becca.getBranch(branchId);if (!branch) return;@@ -297,57 +306,65 @@ class ConsistencyChecks {logFix(`Branch '${branchId}' has been deleted since the associated note '${noteId}' is deleted.`);} else {- logError(`Branch '${branchId}' is not deleted even though the associated note '${noteId}' is deleted.`)+ logError(`Branch '${branchId}' is not deleted even though the associated note '${noteId}' is deleted.`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT branchId,parentNoteIdFROM branchesJOIN notes AS parentNote ON parentNote.noteId = branches.parentNoteIdWHERE parentNote.isDeleted = 1AND branches.isDeleted = 0- `, ({branchId, parentNoteId}) => {- if (this.autoFix) {- const branch = becca.getBranch(branchId);- if (!branch) {- return;- }- branch.markAsDeleted();+ `,+ ({ branchId, parentNoteId }) => {+ if (this.autoFix) {+ const branch = becca.getBranch(branchId);+ if (!branch) {+ return;+ }+ branch.markAsDeleted();- this.reloadNeeded = true;+ this.reloadNeeded = true;- logFix(`Branch '${branchId}' has been deleted since the associated parent note '${parentNoteId}' is deleted.`);- } else {- logError(`Branch '${branchId}' is not deleted even though the associated parent note '${parentNoteId}' is deleted.`)+ logFix(`Branch '${branchId}' has been deleted since the associated parent note '${parentNoteId}' is deleted.`);+ } else {+ logError(`Branch '${branchId}' is not deleted even though the associated parent note '${parentNoteId}' is deleted.`);+ }}- });+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT DISTINCT notes.noteIdFROM notesLEFT JOIN branches ON notes.noteId = branches.noteId AND branches.isDeleted = 0WHERE notes.isDeleted = 0AND branches.branchId IS NULL- `, ({noteId}) => {- if (this.autoFix) {- const branch = new BBranch({- parentNoteId: 'root',- noteId: noteId,- prefix: 'recovered'- }).save();+ `,+ ({ noteId }) => {+ if (this.autoFix) {+ const branch = new BBranch({+ parentNoteId: "root",+ noteId: noteId,+ prefix: "recovered"+ }).save();- this.reloadNeeded = true;+ this.reloadNeeded = true;- logFix(`Created missing branch '${branch.branchId}' for note '${noteId}'`);- } else {- logError(`No undeleted branch found for note '${noteId}'`);+ logFix(`Created missing branch '${branch.branchId}' for note '${noteId}'`);+ } else {+ logError(`No undeleted branch found for note '${noteId}'`);+ }}- });+ );// there should be a unique relationship between note and its parent- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT noteId,parentNoteIdFROM branches@@ -355,17 +372,19 @@ class ConsistencyChecks {GROUP BY branches.parentNoteId,branches.noteIdHAVING COUNT(1) > 1`,- ({noteId, parentNoteId}) => {+ ({ noteId, parentNoteId }) => {if (this.autoFix) {const branchIds = sql.getColumn<string>(- `SELECT branchId+ `SELECT branchIdFROM branchesWHERE noteId = ?and parentNoteId = ?and isDeleted = 0- ORDER BY utcDateModified`, [noteId, parentNoteId]);+ ORDER BY utcDateModified`,+ [noteId, parentNoteId]+ );- const branches = branchIds.map(branchId => becca.getBranch(branchId));+ const branches = branchIds.map((branchId) => becca.getBranch(branchId));// it's not necessarily "original" branch, it's just the only one which will surviveconst origBranch = branches[0];@@ -389,16 +408,18 @@ class ConsistencyChecks {} else {logError(`Duplicate branches for note '${noteId}' and parent '${parentNoteId}'`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT attachmentId,attachments.ownerId AS noteIdFROM attachmentsJOIN notes ON notes.noteId = attachments.ownerIdWHERE notes.isDeleted = 1AND attachments.isDeleted = 0`,- ({attachmentId, noteId}) => {+ ({ attachmentId, noteId }) => {if (this.autoFix) {const attachment = becca.getAttachment(attachmentId);if (!attachment) return;@@ -408,41 +429,45 @@ class ConsistencyChecks {logFix(`Attachment '${attachmentId}' has been deleted since the associated note '${noteId}' is deleted.`);} else {- logError(`Attachment '${attachmentId}' is not deleted even though the associated note '${noteId}' is deleted.`)+ logError(`Attachment '${attachmentId}' is not deleted even though the associated note '${noteId}' is deleted.`);}- });+ }+ );}findLogicIssues() {- const noteTypesStr = noteTypes.map(nt => `'${nt}'`).join(", ");+ const noteTypesStr = noteTypes.map((nt) => `'${nt}'`).join(", ");- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT noteId, typeFROM notesWHERE isDeleted = 0AND type NOT IN (${noteTypesStr})`,- ({noteId, type}) => {+ ({ noteId, type }) => {if (this.autoFix) {const note = becca.getNote(noteId);if (!note) return;- note.type = 'file'; // file is a safe option to recover notes if the type is not known+ note.type = "file"; // file is a safe option to recover notes if the type is not knownnote.save();this.reloadNeeded = true;- logFix(`Note '${noteId}' type has been change to file since it had invalid type '${type}'`)+ logFix(`Note '${noteId}' type has been change to file since it had invalid type '${type}'`);} else {logError(`Note '${noteId}' has invalid type '${type}'`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT notes.noteId, notes.isProtected, notes.type, notes.mimeFROM notesLEFT JOIN blobs USING (blobId)WHERE blobs.blobId IS NULLAND notes.isDeleted = 0`,- ({noteId, isProtected, type, mime}) => {+ ({ noteId, isProtected, type, mime }) => {if (this.autoFix) {// it might be possible that the blob is not available only because of the interrupted// sync, and it will come later. It's therefore important to guarantee that this artificial@@ -469,7 +494,7 @@ class ConsistencyChecks {const hash = getHash(randomString(10));entityChangesService.putEntityChange({- entityName: 'blobs',+ entityName: "blobs",entityId: blobId,hash: hash,isErased: false,@@ -486,19 +511,21 @@ class ConsistencyChecks {} else {logError(`Note '${noteId}' content row does not exist`);}- });+ }+ );if (sqlInit.getDbSize() < 500000) {// querying for "content IS NULL" is expensive since content is not indexed. See e.g. https://github.com/zadam/trilium/issues/2887- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT notes.noteId, notes.type, notes.mimeFROM notesJOIN blobs USING (blobId)WHERE isDeleted = 0AND isProtected = 0AND content IS NULL`,- ({noteId, type, mime}) => {+ ({ noteId, type, mime }) => {if (this.autoFix) {const note = becca.getNote(noteId);const blankContent = getBlankContent(false, type, mime);@@ -514,15 +541,17 @@ class ConsistencyChecks {} else {logError(`Note '${noteId}' content is null even though it is not deleted`);}- });+ }+ );}- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT revisions.revisionId, blobs.blobIdFROM revisionsLEFT JOIN blobs USING (blobId)WHERE blobs.blobId IS NULL`,- ({revisionId, blobId}) => {+ ({ revisionId, blobId }) => {if (this.autoFix) {eraseService.eraseRevisions([revisionId]);@@ -532,14 +561,16 @@ class ConsistencyChecks {} else {logError(`Note revision '${revisionId}' blob '${blobId}' does not exist`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT attachments.attachmentId, blobs.blobIdFROM attachmentsLEFT JOIN blobs USING (blobId)WHERE blobs.blobId IS NULL`,- ({attachmentId, blobId}) => {+ ({ attachmentId, blobId }) => {if (this.autoFix) {eraseService.eraseAttachments([attachmentId]);@@ -549,24 +580,29 @@ class ConsistencyChecks {} else {logError(`Attachment '${attachmentId}' blob '${blobId}' does not exist`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT parentNoteIdFROM branchesJOIN notes ON notes.noteId = branches.parentNoteIdWHERE notes.isDeleted = 0AND notes.type == 'search'AND branches.isDeleted = 0`,- ({parentNoteId}) => {+ ({ parentNoteId }) => {if (this.autoFix) {- const branchIds = sql.getColumn<string>(`+ const branchIds = sql.getColumn<string>(+ `SELECT branchIdFROM branchesWHERE isDeleted = 0- AND parentNoteId = ?`, [parentNoteId]);+ AND parentNoteId = ?`,+ [parentNoteId]+ );- const branches = branchIds.map(branchId => becca.getBranch(branchId));+ const branches = branchIds.map((branchId) => becca.getBranch(branchId));for (const branch of branches) {if (!branch) continue;@@ -576,27 +612,29 @@ class ConsistencyChecks {// create a replacement branch in root parentnew BBranch({- parentNoteId: 'root',+ parentNoteId: "root",noteId: branch.noteId,- prefix: 'recovered'+ prefix: "recovered"}).save();- logFix(`Note '${branch.noteId}' has been moved to root since it was a child of a search note '${parentNoteId}'`)+ logFix(`Note '${branch.noteId}' has been moved to root since it was a child of a search note '${parentNoteId}'`);}this.reloadNeeded = true;} else {logError(`Search note '${parentNoteId}' has children`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT attributeIdFROM attributesWHERE isDeleted = 0AND type = 'relation'AND value = ''`,- ({attributeId}) => {+ ({ attributeId }) => {if (this.autoFix) {const relation = becca.getAttribute(attributeId);if (!relation) return;@@ -608,20 +646,22 @@ class ConsistencyChecks {} else {logError(`Relation '${attributeId}' has empty target.`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT attributeId,typeFROM attributesWHERE isDeleted = 0AND type != 'label'AND type != 'relation'`,- ({attributeId, type}) => {+ ({ attributeId, type }) => {if (this.autoFix) {const attribute = becca.getAttribute(attributeId);if (!attribute) return;- attribute.type = 'label';+ attribute.type = "label";attribute.save();this.reloadNeeded = true;@@ -630,16 +670,18 @@ class ConsistencyChecks {} else {logError(`Attribute '${attributeId}' has invalid type '${type}'`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT attributeId,attributes.noteIdFROM attributesJOIN notes ON attributes.noteId = notes.noteIdWHERE attributes.isDeleted = 0AND notes.isDeleted = 1`,- ({attributeId, noteId}) => {+ ({ attributeId, noteId }) => {if (this.autoFix) {const attribute = becca.getAttribute(attributeId);if (!attribute) return;@@ -651,9 +693,11 @@ class ConsistencyChecks {} else {logError(`Attribute '${attributeId}' is not deleted even though owning note '${noteId}' is deleted.`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT attributeId,attributes.value AS targetNoteIdFROM attributes@@ -661,7 +705,7 @@ class ConsistencyChecks {WHERE attributes.type = 'relation'AND attributes.isDeleted = 0AND notes.isDeleted = 1`,- ({attributeId, targetNoteId}) => {+ ({ attributeId, targetNoteId }) => {if (this.autoFix) {const attribute = becca.getAttribute(attributeId);if (!attribute) return;@@ -673,16 +717,18 @@ class ConsistencyChecks {} else {logError(`Attribute '${attributeId}' is not deleted even though target note '${targetNoteId}' is deleted.`);}- });+ }+ );}runEntityChangeChecks(entityName: string, key: string) {- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT ${key} as entityIdFROM ${entityName}LEFT JOIN entity_changes ec ON ec.entityName = '${entityName}' AND ec.entityId = ${entityName}.${key}WHERE ec.id IS NULL`,- ({entityId}) => {+ ({ entityId }) => {const entityRow = sql.getRow<EntityChange>(`SELECT * FROM ${entityName} WHERE ${key} = ?`, [entityId]);if (this.autoFix) {@@ -692,16 +738,18 @@ class ConsistencyChecks {hash: randomString(10), // doesn't matter, will force sync, but that's OKisErased: false,utcDateChanged: entityRow.utcDateModified || entityRow.utcDateCreated,- isSynced: entityName !== 'options' || entityRow.isSynced+ isSynced: entityName !== "options" || entityRow.isSynced});logFix(`Created missing entity change for entityName '${entityName}', entityId '${entityId}'`);} else {logError(`Missing entity change for entityName '${entityName}', entityId '${entityId}'`);}- });+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT id, entityIdFROM entity_changesLEFT JOIN ${entityName} ON entityId = ${entityName}.${key}@@ -709,24 +757,26 @@ class ConsistencyChecks {entity_changes.isErased = 0AND entity_changes.entityName = '${entityName}'AND ${entityName}.${key} IS NULL`,- ({id, entityId}) => {- if (this.autoFix) {- sql.execute("DELETE FROM entity_changes WHERE entityName = ? AND entityId = ?", [entityName, entityId]);+ ({ id, entityId }) => {+ if (this.autoFix) {+ sql.execute("DELETE FROM entity_changes WHERE entityName = ? AND entityId = ?", [entityName, entityId]);- logFix(`Deleted extra entity change id '${id}', entityName '${entityName}', entityId '${entityId}'`);- } else {- logError(`Unrecognized entity change id '${id}', entityName '${entityName}', entityId '${entityId}'`);- }- });+ logFix(`Deleted extra entity change id '${id}', entityName '${entityName}', entityId '${entityId}'`);+ } else {+ logError(`Unrecognized entity change id '${id}', entityName '${entityName}', entityId '${entityId}'`);+ }+ }+ );- this.findAndFixIssues(`+ this.findAndFixIssues(+ `SELECT id, entityIdFROM entity_changesJOIN ${entityName} ON entityId = ${entityName}.${key}WHEREentity_changes.isErased = 1AND entity_changes.entityName = '${entityName}'`,- ({id, entityId}) => {+ ({ id, entityId }) => {if (this.autoFix) {sql.execute(`DELETE FROM ${entityName} WHERE ${key} = ?`, [entityId]);@@ -736,7 +786,8 @@ class ConsistencyChecks {} else {logError(`Entity change id '${id}' has entityName '${entityName}', entityId '${entityId}' as erased, but it's not.`);}- });+ }+ );}findEntityChangeIssues() {@@ -763,14 +814,13 @@ class ConsistencyChecks {// - renaming the attribute would break the invariant that single attribute never changes the name// - deleting the old attribute and creating new will create duplicates across synchronized cluster (specifically in the initial migration)// But in general, we assume there won't be many such problems- sql.execute('UPDATE attributes SET name = ? WHERE name = ?', [fixedName, origName]);+ sql.execute("UPDATE attributes SET name = ? WHERE name = ?", [fixedName, origName]);this.fixedIssues = true;this.reloadNeeded = true;logFix(`Renamed incorrectly named attributes '${origName}' to '${fixedName}'`);- }- else {+ } else {this.unrecoveredConsistencyErrors = true;logFix(`There are incorrectly named attributes '${origName}'`);@@ -790,8 +840,7 @@ class ConsistencyChecks {this.fixedIssues = true;logFix(`Fixed incorrect lastSyncedPush - was ${lastSyncedPush}, needs to be at maximum ${maxEntityChangeId}`);- }- else {+ } else {this.unrecoveredConsistencyErrors = true;logFix(`Incorrect lastSyncedPush - is ${lastSyncedPush}, needs to be at maximum ${maxEntityChangeId}`);@@ -839,9 +888,9 @@ class ConsistencyChecks {return `${tableName}: ${count}`;}- const tables = [ "notes", "revisions", "attachments", "branches", "attributes", "etapi_tokens", "blobs" ];+ const tables = ["notes", "revisions", "attachments", "branches", "attributes", "etapi_tokens", "blobs"];- log.info(`Table counts: ${tables.map(tableName => getTableRowCount(tableName)).join(", ")}`);+ log.info(`Table counts: ${tables.map((tableName) => getTableRowCount(tableName)).join(", ")}`);}async runChecks() {@@ -860,12 +909,9 @@ class ConsistencyChecks {if (this.unrecoveredConsistencyErrors) {log.info(`Consistency checks failed (took ${elapsedTimeMs}ms)`);- ws.sendMessageToAllClients({type: 'consistency-checks-failed'});+ ws.sendMessageToAllClients({ type: "consistency-checks-failed" });} else {- log.info(`All consistency checks passed ` +- (this.fixedIssues ? "after some fixes" : "with no errors detected") +- ` (took ${elapsedTimeMs}ms)`- );+ log.info(`All consistency checks passed ` + (this.fixedIssues ? "after some fixes" : "with no errors detected") + ` (took ${elapsedTimeMs}ms)`);}}}@@ -875,11 +921,11 @@ function getBlankContent(isProtected: boolean, type: string, mime: string) {return null; // this is wrong for protected non-erased notes, but we cannot create a valid value without a password}- if (mime === 'application/json') {- return '{}';+ if (mime === "application/json") {+ return "{}";}- return ''; // empty string might be a wrong choice for some note types, but it's the best guess+ return ""; // empty string might be a wrong choice for some note types, but it's the best guess}function logFix(message: string) {@@ -891,7 +937,7 @@ function logError(message: string) {}function runPeriodicChecks() {- const autoFix = optionsService.getOptionBool('autoFixConsistencyIssues');+ const autoFix = optionsService.getOptionBool("autoFixConsistencyIssues");const consistencyChecks = new ConsistencyChecks(autoFix);consistencyChecks.runChecks();diff --git a/src/services/content_hash.ts b/src/services/content_hash.tsindex 41dc9282a0..0247bd3352 100644--- a/src/services/content_hash.ts+++ b/src/services/content_hash.ts@@ -14,9 +14,9 @@ function getEntityHashes() {const startTime = new Date();// we know this is slow and the total content hash calculation time is logged- type HashRow = [ string, string, string, boolean ];- const hashRows = sql.disableSlowQueryLogging(- () => sql.getRawRows<HashRow>(`+ type HashRow = [string, string, string, boolean];+ const hashRows = sql.disableSlowQueryLogging(() =>+ sql.getRawRows<HashRow>(`SELECT entityName,entityId,hash,@@ -28,12 +28,12 @@ function getEntityHashes() {// sorting is faster in memory// sorting by entityId is enough, hashes will be segmented by entityName later on anyway- hashRows.sort((a, b) => a[1] < b[1] ? -1 : 1);+ hashRows.sort((a, b) => (a[1] < b[1] ? -1 : 1));const hashMap: Record<string, SectorHash> = {};for (const [entityName, entityId, hash, isErased] of hashRows) {- const entityHashMap = hashMap[entityName] = hashMap[entityName] || {};+ const entityHashMap = (hashMap[entityName] = hashMap[entityName] || {});const sector = entityId[0];diff --git a/src/services/data_dir.ts b/src/services/data_dir.tsindex 7009b918f5..b87b00d321 100644--- a/src/services/data_dir.ts+++ b/src/services/data_dir.ts@@ -15,13 +15,11 @@ import path from "path";function getAppDataDir() {let appDataDir = os.homedir(); // fallback if OS is not recognized- if (os.platform() === 'win32' && process.env.APPDATA) {+ if (os.platform() === "win32" && process.env.APPDATA) {appDataDir = process.env.APPDATA;- }- else if (os.platform() === 'linux') {+ } else if (os.platform() === "linux") {appDataDir = `${os.homedir()}/.local/share`;- }- else if (os.platform() === 'darwin') {+ } else if (os.platform() === "darwin") {appDataDir = `${os.homedir()}/Library/Application Support`;}@@ -33,7 +31,7 @@ function getAppDataDir() {return appDataDir;}-const DIR_NAME = 'trilium-data';+const DIR_NAME = "trilium-data";function getTriliumDataDir() {if (process.env.TRILIUM_DATA_DIR) {diff --git a/src/services/date_notes.ts b/src/services/date_notes.tsindex 3f355f4291..e6659b3fdb 100644--- a/src/services/date_notes.ts+++ b/src/services/date_notes.ts@@ -11,17 +11,26 @@ import hoistedNoteService from "./hoisted_note.js";import BNote from "../becca/entities/bnote.js";import { t } from "i18next";-const CALENDAR_ROOT_LABEL = 'calendarRoot';-const YEAR_LABEL = 'yearNote';-const MONTH_LABEL = 'monthNote';-const DATE_LABEL = 'dateNote';+const CALENDAR_ROOT_LABEL = "calendarRoot";+const YEAR_LABEL = "yearNote";+const MONTH_LABEL = "monthNote";+const DATE_LABEL = "dateNote";-const WEEKDAY_TRANSLATION_IDS = [- "weekdays.sunday", "weekdays.monday", "weekdays.tuesday", "weekdays.wednesday", "weekdays.thursday", "weekdays.friday", "weekdays.saturday", "weekdays.sunday"-];+const WEEKDAY_TRANSLATION_IDS = ["weekdays.sunday", "weekdays.monday", "weekdays.tuesday", "weekdays.wednesday", "weekdays.thursday", "weekdays.friday", "weekdays.saturday", "weekdays.sunday"];const MONTH_TRANSLATION_IDS = [- "months.january", "months.february", "months.march", "months.april", "months.may", "months.june", "months.july", "months.august", "months.september", "months.october", "months.november", "months.december"+ "months.january",+ "months.february",+ "months.march",+ "months.april",+ "months.may",+ "months.june",+ "months.july",+ "months.august",+ "months.september",+ "months.october",+ "months.november",+ "months.december"];type StartOfWeek = "monday" | "sunday";@@ -30,9 +39,9 @@ function createNote(parentNote: BNote, noteTitle: string) {return noteService.createNewNote({parentNoteId: parentNote.noteId,title: noteTitle,- content: '',+ content: "",isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),- type: 'text'+ type: "text"}).note;}@@ -42,7 +51,7 @@ function getRootCalendarNote(): BNote {const workspaceNote = hoistedNoteService.getWorkspaceNote();if (!workspaceNote || !workspaceNote.isRoot()) {- rootNote = searchService.findFirstNoteWithQuery('#workspaceCalendarRoot', new SearchContext({ignoreHoistedNote: false}));+ rootNote = searchService.findFirstNoteWithQuery("#workspaceCalendarRoot", new SearchContext({ ignoreHoistedNote: false }));}if (!rootNote) {@@ -52,16 +61,16 @@ function getRootCalendarNote(): BNote {if (!rootNote) {sql.transactional(() => {rootNote = noteService.createNewNote({- parentNoteId: 'root',- title: 'Calendar',- target: 'into',+ parentNoteId: "root",+ title: "Calendar",+ target: "into",isProtected: false,- type: 'text',- content: ''+ type: "text",+ content: ""}).note;attributeService.createLabel(rootNote.noteId, CALENDAR_ROOT_LABEL);- attributeService.createLabel(rootNote.noteId, 'sorted');+ attributeService.createLabel(rootNote.noteId, "sorted");});}@@ -73,8 +82,7 @@ function getYearNote(dateStr: string, _rootNote: BNote | null = null): BNote {const yearStr = dateStr.trim().substr(0, 4);- let yearNote = searchService.findFirstNoteWithQuery(`#${YEAR_LABEL}="${yearStr}"`,- new SearchContext({ancestorNoteId: rootNote.noteId}));+ let yearNote = searchService.findFirstNoteWithQuery(`#${YEAR_LABEL}="${yearStr}"`, new SearchContext({ ancestorNoteId: rootNote.noteId }));if (yearNote) {return yearNote;@@ -84,12 +92,12 @@ function getYearNote(dateStr: string, _rootNote: BNote | null = null): BNote {yearNote = createNote(rootNote, yearStr);attributeService.createLabel(yearNote.noteId, YEAR_LABEL, yearStr);- attributeService.createLabel(yearNote.noteId, 'sorted');+ attributeService.createLabel(yearNote.noteId, "sorted");- const yearTemplateAttr = rootNote.getOwnedAttribute('relation', 'yearTemplate');+ const yearTemplateAttr = rootNote.getOwnedAttribute("relation", "yearTemplate");if (yearTemplateAttr) {- attributeService.createRelation(yearNote.noteId, 'template', yearTemplateAttr.value);+ attributeService.createRelation(yearNote.noteId, "template", yearTemplateAttr.value);}});@@ -101,8 +109,8 @@ function getMonthNoteTitle(rootNote: BNote, monthNumber: string, dateObj: Date)const monthName = t(MONTH_TRANSLATION_IDS[dateObj.getMonth()]);return pattern- .replace(/{shortMonth3}/g, monthName.slice(0,3))- .replace(/{shortMonth4}/g, monthName.slice(0,4))+ .replace(/{shortMonth3}/g, monthName.slice(0, 3))+ .replace(/{shortMonth4}/g, monthName.slice(0, 4)).replace(/{monthNumberPadded}/g, monthNumber).replace(/{month}/g, monthName);}@@ -113,8 +121,7 @@ function getMonthNote(dateStr: string, _rootNote: BNote | null = null): BNote {const monthStr = dateStr.substr(0, 7);const monthNumber = dateStr.substr(5, 2);- let monthNote = searchService.findFirstNoteWithQuery(`#${MONTH_LABEL}="${monthStr}"`,- new SearchContext({ancestorNoteId: rootNote.noteId}));+ let monthNote = searchService.findFirstNoteWithQuery(`#${MONTH_LABEL}="${monthStr}"`, new SearchContext({ ancestorNoteId: rootNote.noteId }));if (monthNote) {return monthNote;@@ -130,12 +137,12 @@ function getMonthNote(dateStr: string, _rootNote: BNote | null = null): BNote {monthNote = createNote(yearNote, noteTitle);attributeService.createLabel(monthNote.noteId, MONTH_LABEL, monthStr);- attributeService.createLabel(monthNote.noteId, 'sorted');+ attributeService.createLabel(monthNote.noteId, "sorted");- const monthTemplateAttr = rootNote.getOwnedAttribute('relation', 'monthTemplate');+ const monthTemplateAttr = rootNote.getOwnedAttribute("relation", "monthTemplate");if (monthTemplateAttr) {- attributeService.createRelation(monthNote.noteId, 'template', monthTemplateAttr.value);+ attributeService.createRelation(monthNote.noteId, "template", monthTemplateAttr.value);}});@@ -168,8 +175,7 @@ function getDayNote(dateStr: string, _rootNote: BNote | null = null): BNote {dateStr = dateStr.trim().substr(0, 10);- let dateNote = searchService.findFirstNoteWithQuery(`#${DATE_LABEL}="${dateStr}"`,- new SearchContext({ancestorNoteId: rootNote.noteId}));+ let dateNote = searchService.findFirstNoteWithQuery(`#${DATE_LABEL}="${dateStr}"`, new SearchContext({ ancestorNoteId: rootNote.noteId }));if (dateNote) {return dateNote;@@ -187,10 +193,10 @@ function getDayNote(dateStr: string, _rootNote: BNote | null = null): BNote {attributeService.createLabel(dateNote.noteId, DATE_LABEL, dateStr.substr(0, 10));- const dateTemplateAttr = rootNote.getOwnedAttribute('relation', 'dateTemplate');+ const dateTemplateAttr = rootNote.getOwnedAttribute("relation", "dateTemplate");if (dateTemplateAttr) {- attributeService.createRelation(dateNote.noteId, 'template', dateTemplateAttr.value);+ attributeService.createRelation(dateNote.noteId, "template", dateTemplateAttr.value);}});@@ -205,13 +211,11 @@ function getStartOfTheWeek(date: Date, startOfTheWeek: StartOfWeek) {const day = date.getDay();let diff;- if (startOfTheWeek === 'monday') {+ if (startOfTheWeek === "monday") {diff = date.getDate() - day + (day === 0 ? -6 : 1); // adjust when day is sunday- }- else if (startOfTheWeek === 'sunday') {+ } else if (startOfTheWeek === "sunday") {diff = date.getDate() - day;- }- else {+ } else {throw new Error(`Unrecognized start of the week ${startOfTheWeek}`);}@@ -219,7 +223,7 @@ function getStartOfTheWeek(date: Date, startOfTheWeek: StartOfWeek) {}interface WeekNoteOpts {- startOfTheWeek?: StartOfWeek+ startOfTheWeek?: StartOfWeek;}function getWeekNote(dateStr: string, options: WeekNoteOpts = {}, rootNote: BNote | null = null) {diff --git a/src/services/date_utils.ts b/src/services/date_utils.tsindex 7c882e55e7..33f0ff1979 100644--- a/src/services/date_utils.ts+++ b/src/services/date_utils.ts@@ -1,8 +1,8 @@import dayjs from "dayjs";import cls from "./cls.js";-const LOCAL_DATETIME_FORMAT = 'YYYY-MM-DD HH:mm:ss.SSSZZ';-const UTC_DATETIME_FORMAT = 'YYYY-MM-DD HH:mm:ssZ';+const LOCAL_DATETIME_FORMAT = "YYYY-MM-DD HH:mm:ss.SSSZZ";+const UTC_DATETIME_FORMAT = "YYYY-MM-DD HH:mm:ssZ";function utcNowDateTime() {return utcDateTimeStr(new Date());@@ -12,8 +12,7 @@ function utcNowDateTime() {// so we'd prefer client timezone to be used to record local dates. For this reason, requests from clients contain// "trilium-local-now-datetime" header which is then stored in CLSfunction localNowDateTime() {- return cls.getLocalNowDateTime()- || dayjs().format(LOCAL_DATETIME_FORMAT)+ return cls.getLocalNowDateTime() || dayjs().format(LOCAL_DATETIME_FORMAT);}function localNowDate() {@@ -21,8 +20,7 @@ function localNowDate() {if (clsDateTime) {return clsDateTime.substr(0, 10);- }- else {+ } else {const date = new Date();return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;@@ -34,11 +32,11 @@ function pad(num: number) {}function utcDateStr(date: Date) {- return date.toISOString().split('T')[0];+ return date.toISOString().split("T")[0];}function utcDateTimeStr(date: Date) {- return date.toISOString().replace('T', ' ');+ return date.toISOString().replace("T", " ");}/**@@ -48,8 +46,7 @@ function utcDateTimeStr(date: Date) {function parseDateTime(str: string) {try {return new Date(Date.parse(str));- }- catch (e: any) {+ } catch (e: any) {throw new Error(`Can't parse date from '${str}': ${e.stack}`);}}@@ -62,7 +59,7 @@ function parseLocalDate(str: string) {}function getDateTimeForFile() {- return new Date().toISOString().substr(0, 19).replace(/:/g, '');+ return new Date().toISOString().substr(0, 19).replace(/:/g, "");}function validateLocalDateTime(str: string | null | undefined) {@@ -74,7 +71,6 @@ function validateLocalDateTime(str: string | null | undefined) {return `Invalid local date time format in '${str}'. Correct format shoud follow example: '2023-08-21 23:38:51.110+0200'`;}-if (!dayjs(str, LOCAL_DATETIME_FORMAT)) {return `Date '${str}' appears to be in the correct format, but cannot be parsed. It likely represents an invalid date.`;}@@ -89,7 +85,6 @@ function validateUtcDateTime(str: string | undefined) {return `Invalid UTC date time format in '${str}'. Correct format shoud follow example: '2023-08-21 23:38:51.110Z'`;}-if (!dayjs(str, UTC_DATETIME_FORMAT)) {return `Date '${str}' appears to be in the correct format, but cannot be parsed. It likely represents an invalid date.`;}diff --git a/src/services/encryption/data_encryption.ts b/src/services/encryption/data_encryption.tsindex 2088db6bf2..285462d898 100644--- a/src/services/encryption/data_encryption.ts+++ b/src/services/encryption/data_encryption.ts@@ -14,14 +14,13 @@ function arraysIdentical(a: any[] | Buffer, b: any[] | Buffer) {function shaArray(content: crypto.BinaryLike) {// we use this as a simple checksum and don't rely on its security, so SHA-1 is good enough- return crypto.createHash('sha1').update(content).digest();+ return crypto.createHash("sha1").update(content).digest();}function pad(data: Buffer): Buffer {if (data.length > 16) {data = data.slice(0, 16);- }- else if (data.length < 16) {+ } else if (data.length < 16) {const zeros = Array(16 - data.length).fill(0);data = Buffer.concat([data, Buffer.from(zeros)]);@@ -38,7 +37,7 @@ function encrypt(key: Buffer, plainText: Buffer | string) {const plainTextBuffer = Buffer.from(plainText);const iv = crypto.randomBytes(16);- const cipher = crypto.createCipheriv('aes-128-cbc', pad(key), pad(iv));+ const cipher = crypto.createCipheriv("aes-128-cbc", pad(key), pad(iv));const digest = shaArray(plainTextBuffer).slice(0, 4);@@ -48,7 +47,7 @@ function encrypt(key: Buffer, plainText: Buffer | string) {const encryptedDataWithIv = Buffer.concat([iv, encryptedData]);- return encryptedDataWithIv.toString('base64');+ return encryptedDataWithIv.toString("base64");}function decrypt(key: Buffer, cipherText: string | Buffer): Buffer | false | null {@@ -61,7 +60,7 @@ function decrypt(key: Buffer, cipherText: string | Buffer): Buffer | false | nul}try {- const cipherTextBufferWithIv = Buffer.from(cipherText.toString(), 'base64');+ const cipherTextBufferWithIv = Buffer.from(cipherText.toString(), "base64");// old encrypted data can have IV of length 13, see some details here: https://github.com/zadam/trilium/issues/3017const ivLength = cipherTextBufferWithIv.length % 16 === 0 ? 16 : 13;@@ -70,7 +69,7 @@ function decrypt(key: Buffer, cipherText: string | Buffer): Buffer | false | nulconst cipherTextBuffer = cipherTextBufferWithIv.slice(ivLength);- const decipher = crypto.createDecipheriv('aes-128-cbc', pad(key), pad(iv));+ const decipher = crypto.createDecipheriv("aes-128-cbc", pad(key), pad(iv));const decryptedBytes = Buffer.concat([decipher.update(cipherTextBuffer), decipher.final()]);@@ -84,15 +83,13 @@ function decrypt(key: Buffer, cipherText: string | Buffer): Buffer | false | nul}return payload;- }- catch (e: any) {+ } catch (e: any) {// recovery from https://github.com/zadam/trilium/issues/510if (e.message?.includes("WRONG_FINAL_BLOCK_LENGTH") || e.message?.includes("wrong final block length")) {log.info("Caught WRONG_FINAL_BLOCK_LENGTH, returning cipherText instead");return Buffer.from(cipherText);- }- else {+ } else {throw e;}}@@ -109,7 +106,7 @@ function decryptString(dataKey: Buffer, cipherText: string) {throw new Error("Could not decrypt string.");}- return buffer.toString('utf-8');+ return buffer.toString("utf-8");}export default {diff --git a/src/services/encryption/my_scrypt.ts b/src/services/encryption/my_scrypt.tsindex 658f4f2301..ec8adc18cd 100644--- a/src/services/encryption/my_scrypt.ts+++ b/src/services/encryption/my_scrypt.ts@@ -4,20 +4,19 @@ import optionService from "../options.js";import crypto from "crypto";function getVerificationHash(password: crypto.BinaryLike) {- const salt = optionService.getOption('passwordVerificationSalt');+ const salt = optionService.getOption("passwordVerificationSalt");return getScryptHash(password, salt);}function getPasswordDerivedKey(password: crypto.BinaryLike) {- const salt = optionService.getOption('passwordDerivedKeySalt');+ const salt = optionService.getOption("passwordDerivedKeySalt");return getScryptHash(password, salt);}function getScryptHash(password: crypto.BinaryLike, salt: crypto.BinaryLike) {- const hashed = crypto.scryptSync(password, salt, 32,- {N: 16384, r:8, p:1});+ const hashed = crypto.scryptSync(password, salt, 32, { N: 16384, r: 8, p: 1 });return hashed;}diff --git a/src/services/encryption/password.ts b/src/services/encryption/password.tsindex fe6da16906..bbfe9577b0 100644--- a/src/services/encryption/password.ts+++ b/src/services/encryption/password.ts@@ -25,8 +25,8 @@ function changePassword(currentPassword: string, newPassword: string) {sql.transactional(() => {const decryptedDataKey = passwordEncryptionService.getDataKey(currentPassword);- optionService.setOption('passwordVerificationSalt', randomSecureToken(32));- optionService.setOption('passwordDerivedKeySalt', randomSecureToken(32));+ optionService.setOption("passwordVerificationSalt", randomSecureToken(32));+ optionService.setOption("passwordDerivedKeySalt", randomSecureToken(32));const newPasswordVerificationKey = toBase64(myScryptService.getVerificationHash(newPassword));@@ -35,7 +35,7 @@ function changePassword(currentPassword: string, newPassword: string) {passwordEncryptionService.setDataKey(newPassword, decryptedDataKey);}- optionService.setOption('passwordVerificationHash', newPasswordVerificationKey);+ optionService.setOption("passwordVerificationHash", newPasswordVerificationKey);});return {@@ -48,14 +48,14 @@ function setPassword(password: string) {throw new Error("Password is set already. Either change it or perform 'reset password' first.");}- optionService.createOption('passwordVerificationSalt', randomSecureToken(32), true);- optionService.createOption('passwordDerivedKeySalt', randomSecureToken(32), true);+ optionService.createOption("passwordVerificationSalt", randomSecureToken(32), true);+ optionService.createOption("passwordDerivedKeySalt", randomSecureToken(32), true);const passwordVerificationKey = toBase64(myScryptService.getVerificationHash(password));- optionService.createOption('passwordVerificationHash', passwordVerificationKey, true);+ optionService.createOption("passwordVerificationHash", passwordVerificationKey, true);// passwordEncryptionService expects these options to already exist- optionService.createOption('encryptedDataKey', '', true);+ optionService.createOption("encryptedDataKey", "", true);passwordEncryptionService.setDataKey(password, randomSecureToken(16));@@ -67,10 +67,10 @@ function setPassword(password: string) {function resetPassword() {// user forgot the password,sql.transactional(() => {- optionService.setOption('passwordVerificationSalt', '');- optionService.setOption('passwordDerivedKeySalt', '');- optionService.setOption('encryptedDataKey', '');- optionService.setOption('passwordVerificationHash', '');+ optionService.setOption("passwordVerificationSalt", "");+ optionService.setOption("passwordDerivedKeySalt", "");+ optionService.setOption("encryptedDataKey", "");+ optionService.setOption("passwordVerificationHash", "");});return {diff --git a/src/services/encryption/password_encryption.ts b/src/services/encryption/password_encryption.tsindex fd82698717..931ab9c86a 100644--- a/src/services/encryption/password_encryption.ts+++ b/src/services/encryption/password_encryption.ts@@ -6,7 +6,7 @@ import dataEncryptionService from "./data_encryption.js";function verifyPassword(password: string) {const givenPasswordHash = toBase64(myScryptService.getVerificationHash(password));- const dbPasswordHash = optionService.getOptionOrNull('passwordVerificationHash');+ const dbPasswordHash = optionService.getOptionOrNull("passwordVerificationHash");if (!dbPasswordHash) {return false;@@ -20,13 +20,13 @@ function setDataKey(password: string, plainTextDataKey: string | Buffer) {const newEncryptedDataKey = dataEncryptionService.encrypt(passwordDerivedKey, plainTextDataKey);- optionService.setOption('encryptedDataKey', newEncryptedDataKey);+ optionService.setOption("encryptedDataKey", newEncryptedDataKey);}function getDataKey(password: string) {const passwordDerivedKey = myScryptService.getPasswordDerivedKey(password);- const encryptedDataKey = optionService.getOption('encryptedDataKey');+ const encryptedDataKey = optionService.getOption("encryptedDataKey");const decryptedDataKey = dataEncryptionService.decrypt(passwordDerivedKey, encryptedDataKey);diff --git a/src/services/entity_changes.ts b/src/services/entity_changes.tsindex e15eff4de7..4f7a3fe3f9 100644--- a/src/services/entity_changes.ts+++ b/src/services/entity_changes.ts@@ -6,26 +6,26 @@ import { randomString } from "./utils.js";import instanceId from "./instance_id.js";import becca from "../becca/becca.js";import blobService from "../services/blob.js";-import { EntityChange } from './entity_changes_interface.js';+import { EntityChange } from "./entity_changes_interface.js";import type { Blob } from "./blob-interface.js";import eventService from "./events.js";let maxEntityChangeId = 0;function putEntityChangeWithInstanceId(origEntityChange: EntityChange, instanceId: string) {- const ec = {...origEntityChange, instanceId};+ const ec = { ...origEntityChange, instanceId };putEntityChange(ec);}function putEntityChangeWithForcedChange(origEntityChange: EntityChange) {- const ec = {...origEntityChange, changeId: null};+ const ec = { ...origEntityChange, changeId: null };putEntityChange(ec);}function putEntityChange(origEntityChange: EntityChange) {- const ec = {...origEntityChange};+ const ec = { ...origEntityChange };delete ec.id;@@ -50,7 +50,7 @@ function putNoteReorderingEntityChange(parentNoteId: string, componentId?: strinputEntityChange({entityName: "note_reordering",entityId: parentNoteId,- hash: 'N/A',+ hash: "N/A",isErased: false,utcDateChanged: dateUtils.utcNowDateTime(),isSynced: true,@@ -59,7 +59,7 @@ function putNoteReorderingEntityChange(parentNoteId: string, componentId?: strin});eventService.emit(eventService.ENTITY_CHANGED, {- entityName: 'note_reordering',+ entityName: "note_reordering",entity: sql.getMap(`SELECT branchId, notePosition FROM branches WHERE isDeleted = 0 AND parentNoteId = ?`, [parentNoteId])});}@@ -78,10 +78,10 @@ function addEntityChangesForSector(entityName: string, sector: string) {let entitiesInserted = entityChanges.length;sql.transactional(() => {- if (entityName === 'blobs') {- entitiesInserted += addEntityChangesForDependingEntity(sector, 'notes', 'noteId');- entitiesInserted += addEntityChangesForDependingEntity(sector, 'attachments', 'attachmentId');- entitiesInserted += addEntityChangesForDependingEntity(sector, 'revisions', 'revisionId');+ if (entityName === "blobs") {+ entitiesInserted += addEntityChangesForDependingEntity(sector, "notes", "noteId");+ entitiesInserted += addEntityChangesForDependingEntity(sector, "attachments", "attachmentId");+ entitiesInserted += addEntityChangesForDependingEntity(sector, "revisions", "revisionId");}for (const ec of entityChanges) {@@ -94,12 +94,15 @@ function addEntityChangesForSector(entityName: string, sector: string) {function addEntityChangesForDependingEntity(sector: string, tableName: string, primaryKeyColumn: string) {// problem in blobs might be caused by problem in entity referencing the blob- const dependingEntityChanges = sql.getRows<EntityChange>(`+ const dependingEntityChanges = sql.getRows<EntityChange>(+ `SELECT dep_change.*FROM entity_changes orig_sectorJOIN ${tableName} ON ${tableName}.blobId = orig_sector.entityIdJOIN entity_changes dep_change ON dep_change.entityName = '${tableName}' AND dep_change.entityId = ${tableName}.${primaryKeyColumn}- WHERE orig_sector.entityName = 'blobs' AND SUBSTR(orig_sector.entityId, 1, 1) = ?`, [sector]);+ WHERE orig_sector.entityName = 'blobs' AND SUBSTR(orig_sector.entityId, 1, 1) = ?`,+ [sector]+ );for (const ec of dependingEntityChanges) {putEntityChangeWithForcedChange(ec);@@ -118,7 +121,7 @@ function cleanupEntityChangesForMissingEntities(entityName: string, entityPrimarAND entityId NOT IN (SELECT ${entityPrimaryKey} FROM ${entityName})`);}-function fillEntityChanges(entityName: string, entityPrimaryKey: string, condition = '') {+function fillEntityChanges(entityName: string, entityPrimaryKey: string, condition = "") {cleanupEntityChangesForMissingEntities(entityName, entityPrimaryKey);sql.transactional(() => {@@ -142,7 +145,7 @@ function fillEntityChanges(entityName: string, entityPrimaryKey: string, conditiisErased: false};- if (entityName === 'blobs') {+ if (entityName === "blobs") {const blob = sql.getRow<Blob>("SELECT blobId, content, utcDateModified FROM blobs WHERE blobId = ?", [entityId]);ec.hash = blobService.calculateContentHash(blob);ec.utcDateChanged = blob.utcDateModified;@@ -153,7 +156,7 @@ function fillEntityChanges(entityName: string, entityPrimaryKey: string, conditiif (entity) {ec.hash = entity.generateHash();ec.utcDateChanged = entity.getUtcDateChanged() || dateUtils.utcNowDateTime();- ec.isSynced = entityName !== 'options' || !!entity.isSynced;+ ec.isSynced = entityName !== "options" || !!entity.isSynced;} else {// entity might be null (not present in becca) when it's deleted// this will produce different hash value than when entity is being deleted since then@@ -184,7 +187,7 @@ function fillAllEntityChanges() {fillEntityChanges("blobs", "blobId");fillEntityChanges("attributes", "attributeId");fillEntityChanges("etapi_tokens", "etapiTokenId");- fillEntityChanges("options", "name", 'WHERE isSynced = 1');+ fillEntityChanges("options", "name", "WHERE isSynced = 1");});}diff --git a/src/services/env.ts b/src/services/env.tsindex 5a7e45f35b..08737bb2db 100644--- a/src/services/env.ts+++ b/src/services/env.ts@@ -1,5 +1,5 @@function isDev() {- return !!(process.env.TRILIUM_ENV && process.env.TRILIUM_ENV === 'dev');+ return !!(process.env.TRILIUM_ENV && process.env.TRILIUM_ENV === "dev");}export default {diff --git a/src/services/erase.ts b/src/services/erase.tsindex d026757007..806c5232b7 100644--- a/src/services/erase.ts+++ b/src/services/erase.ts@@ -16,18 +16,15 @@ function eraseNotes(noteIdsToErase: string[]) {setEntityChangesAsErased(sql.getManyRows(`SELECT * FROM entity_changes WHERE entityName = 'notes' AND entityId IN (???)`, noteIdsToErase));// we also need to erase all "dependent" entities of the erased notes- const branchIdsToErase = sql.getManyRows<{ branchId: string }>(`SELECT branchId FROM branches WHERE noteId IN (???)`, noteIdsToErase)- .map(row => row.branchId);+ const branchIdsToErase = sql.getManyRows<{ branchId: string }>(`SELECT branchId FROM branches WHERE noteId IN (???)`, noteIdsToErase).map((row) => row.branchId);eraseBranches(branchIdsToErase);- const attributeIdsToErase = sql.getManyRows<{ attributeId: string }>(`SELECT attributeId FROM attributes WHERE noteId IN (???)`, noteIdsToErase)- .map(row => row.attributeId);+ const attributeIdsToErase = sql.getManyRows<{ attributeId: string }>(`SELECT attributeId FROM attributes WHERE noteId IN (???)`, noteIdsToErase).map((row) => row.attributeId);eraseAttributes(attributeIdsToErase);- const revisionIdsToErase = sql.getManyRows<{ revisionId: string }>(`SELECT revisionId FROM revisions WHERE noteId IN (???)`, noteIdsToErase)- .map(row => row.revisionId);+ const revisionIdsToErase = sql.getManyRows<{ revisionId: string }>(`SELECT revisionId FROM revisions WHERE noteId IN (???)`, noteIdsToErase).map((row) => row.revisionId);eraseRevisions(revisionIdsToErase);@@ -120,7 +117,7 @@ function eraseDeletedEntities(eraseEntitiesAfterTimeInSeconds: number | null = n// this is important also so that the erased entity changes are sent to the connected clientssql.transactional(() => {if (eraseEntitiesAfterTimeInSeconds === null) {- eraseEntitiesAfterTimeInSeconds = optionService.getOptionInt('eraseEntitiesAfterTimeInSeconds');+ eraseEntitiesAfterTimeInSeconds = optionService.getOptionInt("eraseEntitiesAfterTimeInSeconds");}const cutoffDate = new Date(Date.now() - eraseEntitiesAfterTimeInSeconds * 1000);@@ -167,11 +164,11 @@ function eraseUnusedAttachmentsNow() {function eraseScheduledAttachments(eraseUnusedAttachmentsAfterSeconds: number | null = null) {if (eraseUnusedAttachmentsAfterSeconds === null) {- eraseUnusedAttachmentsAfterSeconds = optionService.getOptionInt('eraseUnusedAttachmentsAfterSeconds');+ eraseUnusedAttachmentsAfterSeconds = optionService.getOptionInt("eraseUnusedAttachmentsAfterSeconds");}- const cutOffDate = dateUtils.utcDateTimeStr(new Date(Date.now() - (eraseUnusedAttachmentsAfterSeconds * 1000)));- const attachmentIdsToErase = sql.getColumn<string>('SELECT attachmentId FROM attachments WHERE utcDateScheduledForErasureSince < ?', [cutOffDate]);+ const cutOffDate = dateUtils.utcDateTimeStr(new Date(Date.now() - eraseUnusedAttachmentsAfterSeconds * 1000));+ const attachmentIdsToErase = sql.getColumn<string>("SELECT attachmentId FROM attachments WHERE utcDateScheduledForErasureSince < ?", [cutOffDate]);eraseAttachments(attachmentIdsToErase);}@@ -179,11 +176,23 @@ function eraseScheduledAttachments(eraseUnusedAttachmentsAfterSeconds: number |export function startScheduledCleanup() {sqlInit.dbReady.then(() => {// first cleanup kickoff 5 minutes after startup- setTimeout(cls.wrap(() => eraseDeletedEntities()), 5 * 60 * 1000);- setTimeout(cls.wrap(() => eraseScheduledAttachments()), 6 * 60 * 1000);-- setInterval(cls.wrap(() => eraseDeletedEntities()), 4 * 3600 * 1000);- setInterval(cls.wrap(() => eraseScheduledAttachments()), 3600 * 1000);+ setTimeout(+ cls.wrap(() => eraseDeletedEntities()),+ 5 * 60 * 1000+ );+ setTimeout(+ cls.wrap(() => eraseScheduledAttachments()),+ 6 * 60 * 1000+ );++ setInterval(+ cls.wrap(() => eraseDeletedEntities()),+ 4 * 3600 * 1000+ );+ setInterval(+ cls.wrap(() => eraseScheduledAttachments()),+ 3600 * 1000+ );});}@@ -193,5 +202,5 @@ export default {eraseNotesWithDeleteId,eraseUnusedBlobs,eraseAttachments,- eraseRevisions,+ eraseRevisions};diff --git a/src/services/etapi_tokens.ts b/src/services/etapi_tokens.tsindex af20af55fa..93d916a60c 100644--- a/src/services/etapi_tokens.ts+++ b/src/services/etapi_tokens.ts@@ -8,7 +8,7 @@ function getTokens() {}function getTokenHash(token: crypto.BinaryLike) {- return crypto.createHash('sha256').update(token).digest('base64');+ return crypto.createHash("sha256").update(token).digest("base64");}function createToken(tokenName: string) {@@ -52,14 +52,12 @@ function parseAuthToken(auth: string | undefined) {if (chunks.length === 1) {return { token: auth }; // legacy format without etapiTokenId- }- else if (chunks.length === 2) {+ } else if (chunks.length === 2) {return {etapiTokenId: chunks[0],token: chunks[1]- }- }- else {+ };+ } else {return null; // wrong format}}@@ -81,8 +79,7 @@ function isValidAuthHeader(auth: string | undefined) {}return etapiToken.tokenHash === authTokenHash;- }- else {+ } else {for (const etapiToken of becca.getEtapiTokens()) {if (etapiToken.tokenHash === authTokenHash) {return true;diff --git a/src/services/events.ts b/src/services/events.tsindex 1a7ed9eb87..2b24a58261 100644--- a/src/services/events.ts+++ b/src/services/events.ts@@ -21,7 +21,7 @@ const eventListeners: Record<string, EventListener[]> = {};*/function subscribe(eventTypes: EventType, listener: EventListener) {if (!Array.isArray(eventTypes)) {- eventTypes = [ eventTypes ];+ eventTypes = [eventTypes];}for (const eventType of eventTypes) {@@ -32,7 +32,7 @@ function subscribe(eventTypes: EventType, listener: EventListener) {function subscribeBeccaLoader(eventTypes: EventType, listener: EventListener) {if (!Array.isArray(eventTypes)) {- eventTypes = [ eventTypes ];+ eventTypes = [eventTypes];}for (const eventType of eventTypes) {@@ -50,8 +50,7 @@ function emit(eventType: string, data?: any) {for (const listener of listeners) {try {listener(data);- }- catch (e: any) {+ } catch (e: any) {log.error(`Listener threw error: ${e.message}, stack: ${e.stack}`);// we won't stop execution because of listener}diff --git a/src/services/export/md.ts b/src/services/export/md.tsindex ece07d0435..0ee0753bb8 100644--- a/src/services/export/md.ts+++ b/src/services/export/md.ts@@ -6,36 +6,27 @@ import turndownPluginGfm from "joplin-turndown-plugin-gfm";let instance: TurndownService | null = null;const fencedCodeBlockFilter: TurndownService.Rule = {- filter: function (node, options) {- return (- options.codeBlockStyle === 'fenced' &&- node.nodeName === 'PRE' &&- node.firstChild !== null &&- node.firstChild.nodeName === 'CODE'- )- },-- replacement: function (content, node, options) {- if (!node.firstChild || !("getAttribute" in node.firstChild) || typeof node.firstChild.getAttribute !== "function") {- return content;- }+ filter: function (node, options) {+ return options.codeBlockStyle === "fenced" && node.nodeName === "PRE" && node.firstChild !== null && node.firstChild.nodeName === "CODE";+ },++ replacement: function (content, node, options) {+ if (!node.firstChild || !("getAttribute" in node.firstChild) || typeof node.firstChild.getAttribute !== "function") {+ return content;+ }- const className = node.firstChild.getAttribute('class') || ''- const language = rewriteLanguageTag((className.match(/language-(\S+)/) || [null, ''])[1]);+ const className = node.firstChild.getAttribute("class") || "";+ const language = rewriteLanguageTag((className.match(/language-(\S+)/) || [null, ""])[1]);- return (- '\n\n' + options.fence + language + '\n' +- node.firstChild.textContent +- '\n' + options.fence + '\n\n'- )- }+ return "\n\n" + options.fence + language + "\n" + node.firstChild.textContent + "\n" + options.fence + "\n\n";+ }};function toMarkdown(content: string) {if (instance === null) {- instance = new TurndownService({ codeBlockStyle: 'fenced' });+ instance = new TurndownService({ codeBlockStyle: "fenced" });// Filter is heavily based on: https://github.com/mixmark-io/turndown/issues/274#issuecomment-458730974- instance.addRule('fencedCodeBlock', fencedCodeBlockFilter);+ instance.addRule("fencedCodeBlock", fencedCodeBlockFilter);instance.use(turndownPluginGfm.gfm);}@@ -44,16 +35,14 @@ function toMarkdown(content: string) {function rewriteLanguageTag(source: string) {if (!source) {- return source;+ return source;}if (source === "text-x-trilium-auto") {return "";}- return source- .split("-")- .at(-1);+ return source.split("-").at(-1);}export default {diff --git a/src/services/export/opml.ts b/src/services/export/opml.tsindex b4e4c7f6e0..1467160163 100644--- a/src/services/export/opml.ts+++ b/src/services/export/opml.ts@@ -4,10 +4,10 @@ import { getContentDisposition, stripTags } from "../utils.js";import becca from "../../becca/becca.js";import TaskContext from "../task_context.js";import BBranch from "../../becca/entities/bbranch.js";-import { Response } from 'express';+import { Response } from "express";function exportToOpml(taskContext: TaskContext, branch: BBranch, version: string, res: Response) {- if (!['1.0', '2.0'].includes(version)) {+ if (!["1.0", "2.0"].includes(version)) {throw new Error(`Unrecognized OPML version ${version}`);}@@ -17,30 +17,32 @@ function exportToOpml(taskContext: TaskContext, branch: BBranch, version: stringfunction exportNoteInner(branchId: string) {const branch = becca.getBranch(branchId);- if (!branch) { throw new Error("Unable to find branch."); }+ if (!branch) {+ throw new Error("Unable to find branch.");+ }const note = branch.getNote();- if (!note) { throw new Error("Unable to find note."); }+ if (!note) {+ throw new Error("Unable to find note.");+ }- if (note.hasOwnedLabel('excludeFromExport')) {+ if (note.hasOwnedLabel("excludeFromExport")) {return;}- const title = `${branch.prefix ? (`${branch.prefix} - `) : ''}${note.title}`;+ const title = `${branch.prefix ? `${branch.prefix} - ` : ""}${note.title}`;if (opmlVersion === 1) {const preparedTitle = escapeXmlAttribute(title);- const preparedContent = note.hasStringContent() ? prepareText(note.getContent() as string) : '';+ const preparedContent = note.hasStringContent() ? prepareText(note.getContent() as string) : "";res.write(`<outline title="${preparedTitle}" text="${preparedContent}">\n`);- }- else if (opmlVersion === 2) {+ } else if (opmlVersion === 2) {const preparedTitle = escapeXmlAttribute(title);- const preparedContent = note.hasStringContent() ? escapeXmlAttribute(note.getContent() as string) : '';+ const preparedContent = note.hasStringContent() ? escapeXmlAttribute(note.getContent() as string) : "";res.write(`<outline text="${preparedTitle}" _note="${preparedContent}">\n`);- }- else {+ } else {throw new Error(`Unrecognized OPML version ${opmlVersion}`);}@@ -52,14 +54,13 @@ function exportToOpml(taskContext: TaskContext, branch: BBranch, version: string}}- res.write('</outline>');+ res.write("</outline>");}+ const filename = `${branch.prefix ? `${branch.prefix} - ` : ""}${note.title}.opml`;- const filename = `${branch.prefix ? (`${branch.prefix} - `) : ''}${note.title}.opml`;-- res.setHeader('Content-Disposition', getContentDisposition(filename));- res.setHeader('Content-Type', 'text/x-opml');+ res.setHeader("Content-Disposition", getContentDisposition(filename));+ res.setHeader("Content-Type", "text/x-opml");res.write(`<?xml version="1.0" encoding="UTF-8"?><opml version="${version}">@@ -80,22 +81,17 @@ function exportToOpml(taskContext: TaskContext, branch: BBranch, version: string}function prepareText(text: string) {- const newLines = text.replace(/(<p[^>]*>|<br\s*\/?>)/g, '\n')- .replace(/ /g, ' '); // nbsp isn't in XML standard (only HTML)+ const newLines = text.replace(/(<p[^>]*>|<br\s*\/?>)/g, "\n").replace(/ /g, " "); // nbsp isn't in XML standard (only HTML)const stripped = stripTags(newLines);const escaped = escapeXmlAttribute(stripped);- return escaped.replace(/\n/g, ' ');+ return escaped.replace(/\n/g, " ");}function escapeXmlAttribute(text: string) {- return text.replace(/&/g, '&')- .replace(/</g, '<')- .replace(/>/g, '>')- .replace(/"/g, '"')- .replace(/'/g, ''');+ return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");}export default {diff --git a/src/services/export/single.ts b/src/services/export/single.tsindex 7abb99fad3..713e42a00f 100644--- a/src/services/export/single.ts+++ b/src/services/export/single.ts@@ -7,16 +7,16 @@ import mdService from "./md.js";import becca from "../../becca/becca.js";import TaskContext from "../task_context.js";import BBranch from "../../becca/entities/bbranch.js";-import { Response } from 'express';+import { Response } from "express";function exportSingleNote(taskContext: TaskContext, branch: BBranch, format: "html" | "markdown", res: Response) {const note = branch.getNote();- if (note.type === 'image' || note.type === 'file') {+ if (note.type === "image" || note.type === "file") {return [400, `Note type '${note.type}' cannot be exported as single file.`];}- if (format !== 'html' && format !== 'markdown') {+ if (format !== "html" && format !== "markdown") {return [400, `Unrecognized format '${format}'`];}@@ -27,42 +27,37 @@ function exportSingleNote(taskContext: TaskContext, branch: BBranch, format: "htthrow new Error("Unsupported content type for export.");}- if (note.type === 'text') {- if (format === 'html') {+ if (note.type === "text") {+ if (format === "html") {content = inlineAttachments(content);if (!content.toLowerCase().includes("<html")) {content = `<html><head><meta charset="utf-8"></head><body>${content}</body></html>`;}- payload = content.length < 100_000- ? html.prettyPrint(content, {indent_size: 2})- : content;+ payload = content.length < 100_000 ? html.prettyPrint(content, { indent_size: 2 }) : content;- extension = 'html';- mime = 'text/html';- }- else if (format === 'markdown') {+ extension = "html";+ mime = "text/html";+ } else if (format === "markdown") {payload = mdService.toMarkdown(content);- extension = 'md';- mime = 'text/x-markdown'+ extension = "md";+ mime = "text/x-markdown";}- }- else if (note.type === 'code') {+ } else if (note.type === "code") {payload = content;- extension = mimeTypes.extension(note.mime) || 'code';+ extension = mimeTypes.extension(note.mime) || "code";mime = note.mime;- }- else if (note.type === 'relationMap' || note.type === 'canvas' || note.type === 'search') {+ } else if (note.type === "relationMap" || note.type === "canvas" || note.type === "search") {payload = content;- extension = 'json';- mime = 'application/json';+ extension = "json";+ mime = "application/json";}const fileName = `${note.title}.${extension}`;- res.setHeader('Content-Disposition', getContentDisposition(fileName));- res.setHeader('Content-Type', `${mime}; charset=UTF-8`);+ res.setHeader("Content-Disposition", getContentDisposition(fileName));+ res.setHeader("Content-Type", `${mime}; charset=UTF-8`);res.send(payload);@@ -73,7 +68,7 @@ function exportSingleNote(taskContext: TaskContext, branch: BBranch, format: "htfunction inlineAttachments(content: string) {content = content.replace(/src="[^"]*api\/images\/([a-zA-Z0-9_]+)\/?[^"]+"/g, (match, noteId) => {const note = becca.getNote(noteId);- if (!note || !note.mime.startsWith('image/')) {+ if (!note || !note.mime.startsWith("image/")) {return match;}@@ -82,7 +77,7 @@ function inlineAttachments(content: string) {return match;}- const base64Content = imageContent.toString('base64');+ const base64Content = imageContent.toString("base64");const srcValue = `data:${note.mime};base64,${base64Content}`;return `src="${srcValue}"`;@@ -90,7 +85,7 @@ function inlineAttachments(content: string) {content = content.replace(/src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image\/?[^"]+"/g, (match, attachmentId) => {const attachment = becca.getAttachment(attachmentId);- if (!attachment || !attachment.mime.startsWith('image/')) {+ if (!attachment || !attachment.mime.startsWith("image/")) {return match;}@@ -99,7 +94,7 @@ function inlineAttachments(content: string) {return match;}- const base64Content = attachmentContent.toString('base64');+ const base64Content = attachmentContent.toString("base64");const srcValue = `data:${attachment.mime};base64,${base64Content}`;return `src="${srcValue}"`;@@ -116,7 +111,7 @@ function inlineAttachments(content: string) {return match;}- const base64Content = attachmentContent.toString('base64');+ const base64Content = attachmentContent.toString("base64");const hrefValue = `data:${attachment.mime};base64,${base64Content}`;return `href="${hrefValue}" download="${escapeHtml(attachment.title)}"`;diff --git a/src/services/export/zip.ts b/src/services/export/zip.tsindex 1c31c2cae8..26e73fea46 100644--- a/src/services/export/zip.ts+++ b/src/services/export/zip.ts@@ -19,15 +19,15 @@ import NoteMeta from "../meta/note_meta.js";import AttachmentMeta from "../meta/attachment_meta.js";import AttributeMeta from "../meta/attribute_meta.js";import BBranch from "../../becca/entities/bbranch.js";-import { Response } from 'express';+import { Response } from "express";import { RESOURCE_DIR } from "../resource_dir.js";async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "html" | "markdown", res: Response | fs.WriteStream, setHeaders = true) {- if (!['html', 'markdown'].includes(format)) {+ if (!["html", "markdown"].includes(format)) {throw new ValidationError(`Only 'html' and 'markdown' allowed as export format, '${format}' given`);}- const archive = archiver('zip', {+ const archive = archiver("zip", {zlib: { level: 9 } // Sets the compression level.});@@ -44,12 +44,10 @@ async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "hindex = existingFileNames[lcFileName]++;newName = `${index}_${lcFileName}`;- }- while (newName in existingFileNames);+ } while (newName in existingFileNames);return `${index}_${fileName}`;- }- else {+ } else {existingFileNames[lcFileName] = 1;return fileName;@@ -63,7 +61,7 @@ async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "hif (fileName.length > 30) {// We use regex to match the extension to preserve multiple dots in extensions (e.g. .tar.gz).let match = fileName.match(/(\.[a-zA-Z0-9_.!#-]+)$/);- let ext = match ? match[0] : '';+ let ext = match ? match[0] : "";// Crop the extension if extension length exceeds 30const croppedExt = ext.slice(-30);// Crop the file name section and append the cropped extension@@ -75,26 +73,22 @@ async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "h// the following two are handled specifically since we always want to have these extensions no matter the automatic detection// and/or existing detected extensions in the note name- if (type === 'text' && format === 'markdown') {- newExtension = 'md';- }- else if (type === 'text' && format === 'html') {- newExtension = 'html';- }- else if (mime === 'application/x-javascript' || mime === 'text/javascript') {- newExtension = 'js';- }- else if (type === 'canvas' || mime === 'application/json') {- newExtension = 'json';- }- else if (existingExtension.length > 0) { // if the page already has an extension, then we'll just keep it+ if (type === "text" && format === "markdown") {+ newExtension = "md";+ } else if (type === "text" && format === "html") {+ newExtension = "html";+ } else if (mime === "application/x-javascript" || mime === "text/javascript") {+ newExtension = "js";+ } else if (type === "canvas" || mime === "application/json") {+ newExtension = "json";+ } else if (existingExtension.length > 0) {+ // if the page already has an extension, then we'll just keep itnewExtension = null;- }- else {+ } else {if (mime?.toLowerCase()?.trim() === "image/jpg") {- newExtension = 'jpg';+ newExtension = "jpg";} else if (mime?.toLowerCase()?.trim() === "text/mermaid") {- newExtension = 'txt';+ newExtension = "txt";} else {newExtension = mimeTypes.extension(mime) || "dat";}@@ -111,23 +105,26 @@ async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "hfunction createNoteMeta(branch: BBranch, parentMeta: Partial<NoteMeta>, existingFileNames: Record<string, number>): NoteMeta | null {const note = branch.getNote();- if (note.hasOwnedLabel('excludeFromExport')) {+ if (note.hasOwnedLabel("excludeFromExport")) {return null;}const title = note.getTitleOrProtected();- const completeTitle = branch.prefix ? (`${branch.prefix} - ${title}`) : title;+ const completeTitle = branch.prefix ? `${branch.prefix} - ${title}` : title;let baseFileName = sanitize(completeTitle);- if (baseFileName.length > 200) { // the actual limit is 256 bytes(!) but let's be conservative+ if (baseFileName.length > 200) {+ // the actual limit is 256 bytes(!) but let's be conservativebaseFileName = baseFileName.substr(0, 200);}- if (!parentMeta.notePath) { throw new Error("Missing parent note path."); }+ if (!parentMeta.notePath) {+ throw new Error("Missing parent note path.");+ }const notePath = parentMeta.notePath.concat([note.noteId]);if (note.noteId in noteIdToMeta) {- const fileName = getUniqueFilename(existingFileNames, `${baseFileName}.clone.${format === 'html' ? 'html' : 'md'}`);+ const fileName = getUniqueFilename(existingFileNames, `${baseFileName}.clone.${format === "html" ? "html" : "md"}`);const meta: NoteMeta = {isClone: true,@@ -136,7 +133,7 @@ async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "htitle: note.getTitleOrProtected(),prefix: branch.prefix,dataFileName: fileName,- type: 'text', // export will have text description+ type: "text", // export will have text descriptionformat: format};return meta;@@ -152,7 +149,7 @@ async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "hmeta.isExpanded = branch.isExpanded;meta.type = note.type;meta.mime = note.mime;- meta.attributes = note.getOwnedAttributes().map(attribute => {+ meta.attributes = note.getOwnedAttributes().map((attribute) => {const attrMeta: AttributeMeta = {type: attribute.type,name: attribute.name,@@ -166,7 +163,7 @@ async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "htaskContext.increaseProgressCount();- if (note.type === 'text') {+ if (note.type === "text") {meta.format = format;}@@ -174,8 +171,7 @@ async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "h// sort children for having a stable / reproducible export formatnote.sortChildren();- const childBranches = note.getChildBranches()- .filter(branch => branch?.noteId !== '_hidden');+ const childBranches = note.getChildBranches().filter((branch) => branch?.noteId !== "_hidden");const available = !note.isProtected || protectedSessionService.isProtectedSessionAvailable();@@ -185,23 +181,17 @@ async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "h}const attachments = note.getAttachments();- meta.attachments = attachments- .map(attachment => {- const attMeta: AttachmentMeta = {- attachmentId: attachment.attachmentId,- title: attachment.title,- role: attachment.role,- mime: attachment.mime,- position: attachment.position,- dataFileName: getDataFileName(- null,- attachment.mime,- baseFileName + "_" + attachment.title,- existingFileNames- )- };- return attMeta;- });+ meta.attachments = attachments.map((attachment) => {+ const attMeta: AttachmentMeta = {+ attachmentId: attachment.attachmentId,+ title: attachment.title,+ role: attachment.role,+ mime: attachment.mime,+ position: attachment.position,+ dataFileName: getDataFileName(null, attachment.mime, baseFileName + "_" + attachment.title, existingFileNames)+ };+ return attMeta;+ });if (childBranches.length > 0) {meta.dirFileName = getUniqueFilename(existingFileNames, baseFileName);@@ -211,7 +201,9 @@ async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "hconst childExistingNames = {};for (const childBranch of childBranches) {- if (!childBranch) { continue; }+ if (!childBranch) {+ continue;+ }const note = createNoteMeta(childBranch, meta as NoteMeta, childExistingNames);@@ -288,7 +280,7 @@ async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "hfunction findAttachment(targetAttachmentId: string) {let url;- const attachmentMeta = (noteMeta.attachments || []).find(attMeta => attMeta.attachmentId === targetAttachmentId);+ const attachmentMeta = (noteMeta.attachments || []).find((attMeta) => attMeta.attachmentId === targetAttachmentId);if (attachmentMeta) {// easy job here, because attachment will be in the same directory as the note's data file.url = attachmentMeta.dataFileName;@@ -300,15 +292,17 @@ async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "h}function prepareContent(title: string, content: string | Buffer, noteMeta: NoteMeta): string | Buffer {- if (['html', 'markdown'].includes(noteMeta?.format || "")) {+ if (["html", "markdown"].includes(noteMeta?.format || "")) {content = content.toString();content = rewriteLinks(content, noteMeta);}- if (noteMeta.format === 'html' && typeof content === "string") {+ if (noteMeta.format === "html" && typeof content === "string") {if (!content.substr(0, 100).toLowerCase().includes("<html")) {- if (!noteMeta?.notePath?.length) { throw new Error("Missing note path."); }+ if (!noteMeta?.notePath?.length) {+ throw new Error("Missing note path.");+ }const cssUrl = `${"../".repeat(noteMeta.notePath.length - 1)}style.css`;const htmlTitle = escapeHtml(title);@@ -332,10 +326,8 @@ async function exportToZip(taskContext: TaskContext, branch: BBranch, format: "h</html>`;}- return content.length < 100_000- ? html.prettyPrint(content, {indent_size: 2})- : content;- } else if (noteMeta.format === 'markdown' && typeof content === "string") {+ return content.length < 100_000 ? html.prettyPrint(content, { indent_size: 2 }) : content;+ } else if (noteMeta.format === "markdown" && typeof content === "string") {let markdownContent = mdService.toMarkdown(content);if (markdownContent.trim().length > 0 && !markdownContent.startsWith("# ")) {@@ -369,8 +361,12 @@ ${markdownContent}`;}const note = becca.getNote(noteMeta.noteId);- if (!note) { throw new Error("Unable to find note."); }- if (!note.utcDateModified) { throw new Error("Unable to find modification date."); }+ if (!note) {+ throw new Error("Unable to find note.");+ }+ if (!note.utcDateModified) {+ throw new Error("Unable to find modification date.");+ }if (noteMeta.dataFileName) {const content = prepareContent(noteMeta.title, note.getContent(), noteMeta);@@ -384,7 +380,9 @@ ${markdownContent}`;taskContext.increaseProgressCount();for (const attachmentMeta of noteMeta.attachments || []) {- if (!attachmentMeta.attachmentId) { continue; }+ if (!attachmentMeta.attachmentId) {+ continue;+ }const attachment = note.getAttachmentById(attachmentMeta.attachmentId);const content = attachment.getContent();@@ -399,7 +397,7 @@ ${markdownContent}`;const directoryPath = filePathPrefix + noteMeta.dirFileName;// create directory- archive.append('', { name: `${directoryPath}/`, date: dateUtils.parseDateTime(note.utcDateModified) });+ archive.append("", { name: `${directoryPath}/`, date: dateUtils.parseDateTime(note.utcDateModified) });for (const childMeta of noteMeta.children || []) {saveNote(childMeta, `${directoryPath}/`);@@ -409,27 +407,26 @@ ${markdownContent}`;function saveNavigation(rootMeta: NoteMeta, navigationMeta: NoteMeta) {function saveNavigationInner(meta: NoteMeta) {- let html = '<li>';+ let html = "<li>";- const escapedTitle = escapeHtml(`${meta.prefix ? `${meta.prefix} - ` : ''}${meta.title}`);+ const escapedTitle = escapeHtml(`${meta.prefix ? `${meta.prefix} - ` : ""}${meta.title}`);if (meta.dataFileName && meta.noteId) {const targetUrl = getNoteTargetUrl(meta.noteId, rootMeta);html += `<a href="${targetUrl}" target="detail">${escapedTitle}</a>`;- }- else {+ } else {html += escapedTitle;}if (meta.children && meta.children.length > 0) {- html += '<ul>';+ html += "<ul>";for (const child of meta.children) {html += saveNavigationInner(child);}- html += '</ul>'+ html += "</ul>";}return `${html}</li>`;@@ -444,9 +441,7 @@ ${markdownContent}`;<ul>${saveNavigationInner(rootMeta)}</ul></body></html>`;- const prettyHtml = fullHtml.length < 100_000- ? html.prettyPrint(fullHtml, {indent_size: 2})- : fullHtml;+ const prettyHtml = fullHtml.length < 100_000 ? html.prettyPrint(fullHtml, { indent_size: 2 }) : fullHtml;archive.append(prettyHtml, { name: navigationMeta.dataFileName });}@@ -462,8 +457,7 @@ ${markdownContent}`;if (curMeta.children && curMeta.children.length > 0) {curMeta = curMeta.children[0];- }- else {+ } else {break;}}@@ -489,20 +483,20 @@ ${markdownContent}`;archive.append(cssContent, { name: cssMeta.dataFileName });}- const existingFileNames: Record<string, number> = format === 'html' ? {'navigation': 0, 'index': 1} : {};+ const existingFileNames: Record<string, number> = format === "html" ? { navigation: 0, index: 1 } : {};const rootMeta = createNoteMeta(branch, { notePath: [] }, existingFileNames);const metaFile = {formatVersion: 2,appVersion: packageInfo.version,- files: [ rootMeta ]+ files: [rootMeta]};let navigationMeta: NoteMeta | null = null;let indexMeta: NoteMeta | null = null;let cssMeta: NoteMeta | null = null;- if (format === 'html') {+ if (format === "html") {navigationMeta = {noImport: true,dataFileName: "navigation.html"@@ -527,12 +521,12 @@ ${markdownContent}`;for (const noteMeta of Object.values(noteIdToMeta)) {// filter out relations which are not inside this export- noteMeta.attributes = (noteMeta.attributes || []).filter(attr => {- if (attr.type !== 'relation') {+ noteMeta.attributes = (noteMeta.attributes || []).filter((attr) => {+ if (attr.type !== "relation") {return true;} else if (attr.value in noteIdToMeta) {return true;- } else if (attr.value === 'root' || attr.value?.startsWith("_")) {+ } else if (attr.value === "root" || attr.value?.startsWith("_")) {// relations to "named" noteIds can be preservedreturn true;} else {@@ -541,20 +535,21 @@ ${markdownContent}`;});}- if (!rootMeta) { // corner case of disabled export for exported note+ if (!rootMeta) {+ // corner case of disabled export for exported noteif ("sendStatus" in res) {res.sendStatus(400);}return;}- const metaFileJson = JSON.stringify(metaFile, null, '\t');+ const metaFileJson = JSON.stringify(metaFile, null, "\t");archive.append(metaFileJson, { name: "!!!meta.json" });- saveNote(rootMeta, '');+ saveNote(rootMeta, "");- if (format === 'html') {+ if (format === "html") {if (!navigationMeta || !indexMeta || !cssMeta) {throw new Error("Missing meta.");}@@ -568,8 +563,8 @@ ${markdownContent}`;const zipFileName = `${branch.prefix ? `${branch.prefix} - ` : ""}${note.getTitleOrProtected()}.zip`;if (setHeaders && "setHeader" in res) {- res.setHeader('Content-Disposition', getContentDisposition(zipFileName));- res.setHeader('Content-Type', 'application/zip');+ res.setHeader("Content-Disposition", getContentDisposition(zipFileName));+ res.setHeader("Content-Type", "application/zip");}archive.pipe(res);@@ -580,7 +575,7 @@ ${markdownContent}`;async function exportToZipFile(noteId: string, format: "markdown" | "html", zipFilePath: string) {const fileOutputStream = fs.createWriteStream(zipFilePath);- const taskContext = new TaskContext('no-progress-reporting');+ const taskContext = new TaskContext("no-progress-reporting");const note = becca.getNote(noteId);diff --git a/src/services/handlers.ts b/src/services/handlers.tsindex 5799249239..31e6fa01d1 100644--- a/src/services/handlers.ts+++ b/src/services/handlers.ts@@ -8,7 +8,7 @@ import hiddenSubtreeService from "./hidden_subtree.js";import oneTimeTimer from "./one_time_timer.js";import BNote from "../becca/entities/bnote.js";import AbstractBeccaEntity from "../becca/entities/abstract_becca_entity.js";-import { DefinitionObject } from './promoted_attribute_definition_interface.js';+import { DefinitionObject } from "./promoted_attribute_definition_interface.js";type Handler = (definition: DefinitionObject, note: BNote, targetNote: BNote) => void;@@ -19,9 +19,10 @@ function runAttachedRelations(note: BNote, relationName: string, originEntity: A// the same script note can get here with multiple ways, but execute only onceconst notesToRun = new Set(- note.getRelations(relationName)- .map(relation => relation.getTargetNote())- .filter(note => !!note) as BNote[]+ note+ .getRelations(relationName)+ .map((relation) => relation.getTargetNote())+ .filter((note) => !!note) as BNote[]);for (const noteToRun of notesToRun) {@@ -29,8 +30,8 @@ function runAttachedRelations(note: BNote, relationName: string, originEntity: A}}-eventService.subscribe(eventService.NOTE_TITLE_CHANGED, note => {- runAttachedRelations(note, 'runOnNoteTitleChange', note);+eventService.subscribe(eventService.NOTE_TITLE_CHANGED, (note) => {+ runAttachedRelations(note, "runOnNoteTitleChange", note);if (!note.isRoot()) {const noteFromCache = becca.notes[note.noteId];@@ -48,23 +49,22 @@ eventService.subscribe(eventService.NOTE_TITLE_CHANGED, note => {});eventService.subscribe([eventService.ENTITY_CHANGED, eventService.ENTITY_DELETED], ({ entityName, entity }) => {- if (entityName === 'attributes') {- runAttachedRelations(entity.getNote(), 'runOnAttributeChange', entity);+ if (entityName === "attributes") {+ runAttachedRelations(entity.getNote(), "runOnAttributeChange", entity);- if (entity.type === 'label' && ['sorted', 'sortDirection', 'sortFoldersFirst', 'sortNatural', 'sortLocale'].includes(entity.name)) {+ if (entity.type === "label" && ["sorted", "sortDirection", "sortFoldersFirst", "sortNatural", "sortLocale"].includes(entity.name)) {handleSortedAttribute(entity);- } else if (entity.type === 'label') {+ } else if (entity.type === "label") {handleMaybeSortingLabel(entity);}- }- else if (entityName === 'notes') {+ } else if (entityName === "notes") {// ENTITY_DELETED won't trigger anything since all branches/attributes are already deleted at this point- runAttachedRelations(entity, 'runOnNoteChange', entity);+ runAttachedRelations(entity, "runOnNoteChange", entity);}});eventService.subscribe(eventService.ENTITY_CHANGED, ({ entityName, entity }) => {- if (entityName === 'branches') {+ if (entityName === "branches") {const parentNote = becca.getNote(entity.parentNoteId);if (parentNote?.hasLabel("sorted")) {@@ -74,20 +74,20 @@ eventService.subscribe(eventService.ENTITY_CHANGED, ({ entityName, entity }) =>const childNote = becca.getNote(entity.noteId);if (childNote) {- runAttachedRelations(childNote, 'runOnBranchChange', entity);+ runAttachedRelations(childNote, "runOnBranchChange", entity);}}});eventService.subscribe(eventService.NOTE_CONTENT_CHANGE, ({ entity }) => {- runAttachedRelations(entity, 'runOnNoteContentChange', entity);+ runAttachedRelations(entity, "runOnNoteContentChange", entity);});eventService.subscribe(eventService.ENTITY_CREATED, ({ entityName, entity }) => {- if (entityName === 'attributes') {- runAttachedRelations(entity.getNote(), 'runOnAttributeCreation', entity);+ if (entityName === "attributes") {+ runAttachedRelations(entity.getNote(), "runOnAttributeCreation", entity);- if (entity.type === 'relation' && entity.name === 'template') {+ if (entity.type === "relation" && entity.name === "template") {const note = becca.getNote(entity.noteId);if (!note) {return;@@ -101,12 +101,13 @@ eventService.subscribe(eventService.ENTITY_CREATED, ({ entityName, entity }) =>const content = note.getContent();- if (["text", "code"].includes(note.type)- && typeof content === "string"+ if (+ ["text", "code"].includes(note.type) &&+ 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()) {-+ (!content || content.trim().length === 0) &&+ templateNote.hasStringContent()+ ) {const templateNoteContent = templateNote.getContent();if (templateNoteContent) {@@ -123,32 +124,28 @@ eventService.subscribe(eventService.ENTITY_CREATED, ({ entityName, entity }) =>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)) {+ } else if (entity.type === "label" && ["sorted", "sortDirection", "sortFoldersFirst", "sortNatural", "sortLocale"].includes(entity.name)) {handleSortedAttribute(entity);- }- else if (entity.type === 'label') {+ } else if (entity.type === "label") {handleMaybeSortingLabel(entity);}- }- else if (entityName === 'branches') {- runAttachedRelations(entity.getNote(), 'runOnBranchCreation', 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);+ } else if (entityName === "notes") {+ runAttachedRelations(entity, "runOnNoteCreation", entity);}});eventService.subscribe(eventService.CHILD_NOTE_CREATED, ({ parentNote, childNote }) => {- runAttachedRelations(parentNote, 'runOnChildNoteCreation', childNote);+ runAttachedRelations(parentNote, "runOnChildNoteCreation", childNote);});function processInverseRelations(entityName: string, entity: BAttribute, handler: Handler) {- if (entityName === 'attributes' && entity.type === 'relation') {+ if (entityName === "attributes" && entity.type === "relation") {const note = entity.getNote();const relDefinitions = note.getLabels(`relation:${entity.name}`);@@ -194,9 +191,11 @@ function handleMaybeSortingLabel(entity: BAttribute) {continue;}- if (sorted.includes(entity.name) // hacky check if this label is used in the sort- || entity.name === "top"- || entity.name === "bottom") {+ 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);}}@@ -207,13 +206,12 @@ 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);+ const hasInverseAttribute = targetNote.getRelations(definition.inverseRelation).some((attr) => attr.value === note.noteId);if (!hasInverseAttribute) {new BAttribute({noteId: targetNote.noteId,- type: 'relation',+ type: "relation",name: definition.inverseRelation || "",value: note.noteId,isInheritable: entity.isInheritable@@ -237,15 +235,14 @@ eventService.subscribe(eventService.ENTITY_DELETED, ({ entityName, entity }) =>}});- if (entityName === 'branches') {- runAttachedRelations(entity.getNote(), 'runOnBranchDeletion', entity);+ if (entityName === "branches") {+ runAttachedRelations(entity.getNote(), "runOnBranchDeletion", entity);}- if (entityName === 'notes' && entity.noteId.startsWith("_")) {+ 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());+ oneTimeTimer.scheduleExecution("hidden-subtree-check", 1000, () => hiddenSubtreeService.checkHiddenSubtree());}});diff --git a/src/services/hidden_subtree.ts b/src/services/hidden_subtree.tsindex 71afab079d..677f820100 100644--- a/src/services/hidden_subtree.ts+++ b/src/services/hidden_subtree.ts@@ -20,7 +20,7 @@ interface Attribute {type: AttributeType;name: string;isInheritable?: boolean;- value?: string+ value?: string;}interface Item {@@ -58,253 +58,292 @@ let hiddenSubtreeDefinition: Item;function buildHiddenSubtreeDefinition(): Item {return {- id: '_hidden',+ id: "_hidden",title: t("hidden-subtree.root-title"),- type: 'doc',- icon: 'bx bx-hide',+ type: "doc",+ icon: "bx bx-hide",// we want to keep the hidden subtree always last, otherwise there will be problems with e.g., keyboard navigation// over tree when it's in the middlenotePosition: 999_999_999,attributes: [- { type: 'label', name: 'excludeFromNoteMap', isInheritable: true },- { type: 'label', name: 'docName', value: 'hidden' }+ { type: "label", name: "excludeFromNoteMap", isInheritable: true },+ { type: "label", name: "docName", value: "hidden" }],children: [{- id: '_search',+ id: "_search",title: t("hidden-subtree.search-history-title"),- type: 'doc'+ type: "doc"},{- id: '_globalNoteMap',+ id: "_globalNoteMap",title: t("hidden-subtree.note-map-title"),- type: 'noteMap',+ type: "noteMap",attributes: [- { type: 'label', name: 'mapRootNoteId', value: 'hoisted' },- { type: 'label', name: 'keepCurrentHoisting' }+ { type: "label", name: "mapRootNoteId", value: "hoisted" },+ { type: "label", name: "keepCurrentHoisting" }]},{- id: '_sqlConsole',+ id: "_sqlConsole",title: t("hidden-subtree.sql-console-history-title"),- type: 'doc',- icon: 'bx-data'+ type: "doc",+ icon: "bx-data"},{- id: '_share',+ id: "_share",title: t("hidden-subtree.shared-notes-title"),- type: 'doc',- attributes: [ { type: 'label', name: 'docName', value: 'share' } ]+ type: "doc",+ attributes: [{ type: "label", name: "docName", value: "share" }]},{- id: '_bulkAction',+ id: "_bulkAction",title: t("hidden-subtree.bulk-action-title"),- type: 'doc',+ type: "doc"},{- id: '_backendLog',+ id: "_backendLog",title: t("hidden-subtree.backend-log-title"),- type: 'contentWidget',- icon: 'bx-terminal',+ type: "contentWidget",+ icon: "bx-terminal",attributes: [- { type: 'label', name: 'keepCurrentHoisting' },- { type: 'label', name: 'fullContentWidth' }+ { type: "label", name: "keepCurrentHoisting" },+ { type: "label", name: "fullContentWidth" }]},{// place for user scripts hidden stuff (scripts should not create notes directly under hidden root)- id: '_userHidden',+ id: "_userHidden",title: t("hidden-subtree.user-hidden-title"),- type: 'doc',- attributes: [ { type: 'label', name: 'docName', value: 'user_hidden' } ]+ type: "doc",+ attributes: [{ type: "label", name: "docName", value: "user_hidden" }]},{id: LBTPL_ROOT,title: t("hidden-subtree.launch-bar-templates-title"),- type: 'doc',+ type: "doc",children: [{id: LBTPL_BASE,title: t("hidden-subtree.base-abstract-launcher-title"),- type: 'doc'+ type: "doc"},{id: LBTPL_COMMAND,title: t("hidden-subtree.command-launcher-title"),- type: 'doc',+ type: "doc",attributes: [- { type: 'relation', name: 'template', value: LBTPL_BASE },- { type: 'label', name: 'launcherType', value: 'command' },- { type: 'label', name: 'docName', value: 'launchbar_command_launcher' }+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "command" },+ { type: "label", name: "docName", value: "launchbar_command_launcher" }]},{id: LBTPL_NOTE_LAUNCHER,title: t("hidden-subtree.note-launcher-title"),- type: 'doc',+ type: "doc",attributes: [- { type: 'relation', name: 'template', value: LBTPL_BASE },- { type: 'label', name: 'launcherType', value: 'note' },- { type: 'label', name: 'relation:target', value: 'promoted' },- { type: 'label', name: 'relation:hoistedNote', value: 'promoted' },- { type: 'label', name: 'label:keyboardShortcut', value: 'promoted,text' },- { type: 'label', name: 'docName', value: 'launchbar_note_launcher' }+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "note" },+ { type: "label", name: "relation:target", value: "promoted" },+ { type: "label", name: "relation:hoistedNote", value: "promoted" },+ { type: "label", name: "label:keyboardShortcut", value: "promoted,text" },+ { type: "label", name: "docName", value: "launchbar_note_launcher" }]},{id: LBTPL_SCRIPT,title: t("hidden-subtree.script-launcher-title"),- type: 'doc',+ type: "doc",attributes: [- { type: 'relation', name: 'template', value: LBTPL_BASE },- { type: 'label', name: 'launcherType', value: 'script' },- { type: 'label', name: 'relation:script', value: 'promoted' },- { type: 'label', name: 'label:keyboardShortcut', value: 'promoted,text' },- { type: 'label', name: 'docName', value: 'launchbar_script_launcher' }+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "script" },+ { type: "label", name: "relation:script", value: "promoted" },+ { type: "label", name: "label:keyboardShortcut", value: "promoted,text" },+ { type: "label", name: "docName", value: "launchbar_script_launcher" }]},{id: LBTPL_BUILTIN_WIDGET,title: t("hidden-subtree.built-in-widget-title"),- type: 'doc',+ type: "doc",attributes: [- { type: 'relation', name: 'template', value: LBTPL_BASE },- { type: 'label', name: 'launcherType', value: 'builtinWidget' }+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "builtinWidget" }]},{id: LBTPL_SPACER,title: t("hidden-subtree.spacer-title"),- type: 'doc',- icon: 'bx-move-vertical',+ type: "doc",+ icon: "bx-move-vertical",attributes: [- { type: 'relation', name: 'template', value: LBTPL_BUILTIN_WIDGET },- { type: 'label', name: 'builtinWidget', value: 'spacer' },- { type: 'label', name: 'label:baseSize', value: 'promoted,number' },- { type: 'label', name: 'label:growthFactor', value: 'promoted,number' },- { type: 'label', name: 'docName', value: 'launchbar_spacer' }+ { type: "relation", name: "template", value: LBTPL_BUILTIN_WIDGET },+ { type: "label", name: "builtinWidget", value: "spacer" },+ { type: "label", name: "label:baseSize", value: "promoted,number" },+ { type: "label", name: "label:growthFactor", value: "promoted,number" },+ { type: "label", name: "docName", value: "launchbar_spacer" }]},{id: LBTPL_CUSTOM_WIDGET,title: t("hidden-subtree.custom-widget-title"),- type: 'doc',+ type: "doc",attributes: [- { type: 'relation', name: 'template', value: LBTPL_BASE },- { type: 'label', name: 'launcherType', value: 'customWidget' },- { type: 'label', name: 'relation:widget', value: 'promoted' },- { type: 'label', name: 'docName', value: 'launchbar_widget_launcher' }+ { type: "relation", name: "template", value: LBTPL_BASE },+ { type: "label", name: "launcherType", value: "customWidget" },+ { type: "label", name: "relation:widget", value: "promoted" },+ { type: "label", name: "docName", value: "launchbar_widget_launcher" }]- },+ }]},{- id: '_lbRoot',+ id: "_lbRoot",title: t("hidden-subtree.launch-bar-title"),- type: 'doc',- icon: 'bx-sidebar',+ type: "doc",+ icon: "bx-sidebar",isExpanded: true,- attributes: [ { type: 'label', name: 'docName', value: 'launchbar_intro' } ],+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],children: [{- id: '_lbAvailableLaunchers',+ id: "_lbAvailableLaunchers",title: t("hidden-subtree.available-launchers-title"),- type: 'doc',- icon: 'bx-hide',+ type: "doc",+ icon: "bx-hide",isExpanded: true,- attributes: [ { type: 'label', name: 'docName', value: 'launchbar_intro' } ],+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],children: [- { id: '_lbBackInHistory', title: t("hidden-subtree.go-to-previous-note-title"), type: 'launcher', builtinWidget: 'backInHistoryButton', icon: 'bx bxs-chevron-left',- attributes: [ { type: 'label', name: 'docName', value: 'launchbar_history_navigation' } ]},- { id: '_lbForwardInHistory', title: t("hidden-subtree.go-to-next-note-title"), type: 'launcher', builtinWidget: 'forwardInHistoryButton', icon: 'bx bxs-chevron-right',- attributes: [ { type: 'label', name: 'docName', value: 'launchbar_history_navigation' } ]},- { id: '_lbBackendLog', title: t("hidden-subtree.backend-log-title"), type: 'launcher', targetNoteId: '_backendLog', icon: 'bx bx-terminal' },+ {+ id: "_lbBackInHistory",+ title: t("hidden-subtree.go-to-previous-note-title"),+ type: "launcher",+ builtinWidget: "backInHistoryButton",+ icon: "bx bxs-chevron-left",+ attributes: [{ type: "label", name: "docName", value: "launchbar_history_navigation" }]+ },+ {+ id: "_lbForwardInHistory",+ title: t("hidden-subtree.go-to-next-note-title"),+ type: "launcher",+ builtinWidget: "forwardInHistoryButton",+ icon: "bx bxs-chevron-right",+ attributes: [{ type: "label", name: "docName", value: "launchbar_history_navigation" }]+ },+ { id: "_lbBackendLog", title: t("hidden-subtree.backend-log-title"), type: "launcher", targetNoteId: "_backendLog", icon: "bx bx-terminal" }]},{- id: '_lbVisibleLaunchers',+ id: "_lbVisibleLaunchers",title: t("hidden-subtree.visible-launchers-title"),- type: 'doc',- icon: 'bx-show',+ type: "doc",+ icon: "bx-show",isExpanded: true,- attributes: [ { type: 'label', name: 'docName', value: 'launchbar_intro' } ],+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],children: [- { id: '_lbNewNote', title: t("hidden-subtree.new-note-title"), type: 'launcher', command: 'createNoteIntoInbox', icon: 'bx bx-file-blank' },- { id: '_lbSearch', title: t("hidden-subtree.search-notes-title"), type: 'launcher', command: 'searchNotes', icon: 'bx bx-search', attributes: [- { type: 'label', name: 'desktopOnly' }- ] },- { id: '_lbJumpTo', title: t("hidden-subtree.jump-to-note-title"), type: 'launcher', command: 'jumpToNote', icon: 'bx bx-send', attributes: [- { type: 'label', name: 'desktopOnly' }- ] },- { id: '_lbNoteMap', title: t("hidden-subtree.note-map-title"), type: 'launcher', targetNoteId: '_globalNoteMap', icon: 'bx bxs-network-chart' },- { id: '_lbCalendar', title: t("hidden-subtree.calendar-title"), type: 'launcher', builtinWidget: 'calendar', icon: 'bx bx-calendar' },- { id: '_lbRecentChanges', title: t("hidden-subtree.recent-changes-title"), type: 'launcher', command: 'showRecentChanges', icon: 'bx bx-history', attributes: [- { type: 'label', name: 'desktopOnly' }- ] },- { id: '_lbSpacer1', title: t("hidden-subtree.spacer-title"), type: 'launcher', builtinWidget: 'spacer', baseSize: "50", growthFactor: "0" },- { id: '_lbBookmarks', title: t("hidden-subtree.bookmarks-title"), type: 'launcher', builtinWidget: 'bookmarks', icon: 'bx bx-bookmark' },- { id: '_lbToday', title: t("hidden-subtree.open-today-journal-note-title"), type: 'launcher', builtinWidget: 'todayInJournal', icon: 'bx bx-calendar-star' },- { id: '_lbSpacer2', title: t("hidden-subtree.spacer-title"), type: 'launcher', builtinWidget: 'spacer', baseSize: "0", growthFactor: "1" },- { id: '_lbQuickSearch', title: t("hidden-subtree.quick-search-title"), type: "launcher", builtinWidget: "quickSearch", icon: "bx bx-rectangle" },- { id: '_lbProtectedSession', title: t("hidden-subtree.protected-session-title"), type: 'launcher', builtinWidget: 'protectedSession', icon: 'bx bx bx-shield-quarter' },- { id: '_lbSyncStatus', title: t("hidden-subtree.sync-status-title"), type: 'launcher', builtinWidget: 'syncStatus', icon: 'bx bx-wifi' },- { id: '_lbSettings', title: t("hidden-subtree.settings-title"), type: 'launcher', command: 'showOptions', icon: 'bx bx-cog' }+ { id: "_lbNewNote", title: t("hidden-subtree.new-note-title"), type: "launcher", command: "createNoteIntoInbox", icon: "bx bx-file-blank" },+ {+ id: "_lbSearch",+ title: t("hidden-subtree.search-notes-title"),+ type: "launcher",+ command: "searchNotes",+ icon: "bx bx-search",+ attributes: [{ type: "label", name: "desktopOnly" }]+ },+ {+ id: "_lbJumpTo",+ title: t("hidden-subtree.jump-to-note-title"),+ type: "launcher",+ command: "jumpToNote",+ icon: "bx bx-send",+ attributes: [{ type: "label", name: "desktopOnly" }]+ },+ { id: "_lbNoteMap", title: t("hidden-subtree.note-map-title"), type: "launcher", targetNoteId: "_globalNoteMap", icon: "bx bxs-network-chart" },+ { id: "_lbCalendar", title: t("hidden-subtree.calendar-title"), type: "launcher", builtinWidget: "calendar", icon: "bx bx-calendar" },+ {+ id: "_lbRecentChanges",+ title: t("hidden-subtree.recent-changes-title"),+ type: "launcher",+ command: "showRecentChanges",+ icon: "bx bx-history",+ attributes: [{ type: "label", name: "desktopOnly" }]+ },+ { id: "_lbSpacer1", title: t("hidden-subtree.spacer-title"), type: "launcher", builtinWidget: "spacer", baseSize: "50", growthFactor: "0" },+ { id: "_lbBookmarks", title: t("hidden-subtree.bookmarks-title"), type: "launcher", builtinWidget: "bookmarks", icon: "bx bx-bookmark" },+ { id: "_lbToday", title: t("hidden-subtree.open-today-journal-note-title"), type: "launcher", builtinWidget: "todayInJournal", icon: "bx bx-calendar-star" },+ { id: "_lbSpacer2", title: t("hidden-subtree.spacer-title"), type: "launcher", builtinWidget: "spacer", baseSize: "0", growthFactor: "1" },+ { id: "_lbQuickSearch", title: t("hidden-subtree.quick-search-title"), type: "launcher", builtinWidget: "quickSearch", icon: "bx bx-rectangle" },+ { id: "_lbProtectedSession", title: t("hidden-subtree.protected-session-title"), type: "launcher", builtinWidget: "protectedSession", icon: "bx bx bx-shield-quarter" },+ { id: "_lbSyncStatus", title: t("hidden-subtree.sync-status-title"), type: "launcher", builtinWidget: "syncStatus", icon: "bx bx-wifi" },+ { id: "_lbSettings", title: t("hidden-subtree.settings-title"), type: "launcher", command: "showOptions", icon: "bx bx-cog" }]}]},{- id: '_lbMobileRoot',+ id: "_lbMobileRoot",title: "Mobile Launch Bar",type: "doc",icon: "bx-mobile",isExpanded: true,- attributes: [ { type: 'label', name: 'docName', value: 'launchbar_intro' } ],+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],children: [{id: "_lbMobileAvailableLaunchers",title: t("hidden-subtree.available-launchers-title"),- type: 'doc',- icon: 'bx-hide',+ type: "doc",+ icon: "bx-hide",isExpanded: true,- attributes: [ { type: 'label', name: 'docName', value: 'launchbar_intro' } ],+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],children: []},{id: "_lbMobileVisibleLaunchers",title: t("hidden-subtree.visible-launchers-title"),- type: 'doc',- icon: 'bx-show',+ type: "doc",+ icon: "bx-show",isExpanded: true,- attributes: [ { type: 'label', name: 'docName', value: 'launchbar_intro' } ],+ attributes: [{ type: "label", name: "docName", value: "launchbar_intro" }],children: [- { id: '_lbMobileBackInHistory', title: t("hidden-subtree.go-to-previous-note-title"), type: 'launcher', builtinWidget: 'backInHistoryButton', icon: 'bx bxs-chevron-left',- attributes: [ { type: 'label', name: 'docName', value: 'launchbar_history_navigation' } ]},- { id: '_lbMobileForwardInHistory', title: t("hidden-subtree.go-to-next-note-title"), type: 'launcher', builtinWidget: 'forwardInHistoryButton', icon: 'bx bxs-chevron-right',- attributes: [ { type: 'label', name: 'docName', value: 'launchbar_history_navigation' } ]},- { id: '_lbMobileJumpTo', title: t("hidden-subtree.jump-to-note-title"), type: 'launcher', command: 'jumpToNote', icon: 'bx bx-plus-circle' }+ {+ id: "_lbMobileBackInHistory",+ title: t("hidden-subtree.go-to-previous-note-title"),+ type: "launcher",+ builtinWidget: "backInHistoryButton",+ icon: "bx bxs-chevron-left",+ attributes: [{ type: "label", name: "docName", value: "launchbar_history_navigation" }]+ },+ {+ id: "_lbMobileForwardInHistory",+ title: t("hidden-subtree.go-to-next-note-title"),+ type: "launcher",+ builtinWidget: "forwardInHistoryButton",+ icon: "bx bxs-chevron-right",+ attributes: [{ type: "label", name: "docName", value: "launchbar_history_navigation" }]+ },+ { id: "_lbMobileJumpTo", title: t("hidden-subtree.jump-to-note-title"), type: "launcher", command: "jumpToNote", icon: "bx bx-plus-circle" }]}]},{- id: '_options',+ id: "_options",title: t("hidden-subtree.options-title"),- type: 'book',- icon: 'bx-cog',+ type: "book",+ icon: "bx-cog",children: [- { id: '_optionsAppearance', title: t("hidden-subtree.appearance-title"), type: 'contentWidget', icon: 'bx-layout' },- { id: '_optionsShortcuts', title: t("hidden-subtree.shortcuts-title"), type: 'contentWidget', icon: 'bxs-keyboard' },- { id: '_optionsTextNotes', title: t("hidden-subtree.text-notes"), type: 'contentWidget', icon: 'bx-text' },- { id: '_optionsCodeNotes', title: t("hidden-subtree.code-notes-title"), type: 'contentWidget', icon: 'bx-code' },- { id: '_optionsImages', title: t("hidden-subtree.images-title"), type: 'contentWidget', icon: 'bx-image' },- { id: '_optionsSpellcheck', title: t("hidden-subtree.spellcheck-title"), type: 'contentWidget', icon: 'bx-check-double' },- { id: '_optionsPassword', title: t("hidden-subtree.password-title"), type: 'contentWidget', icon: 'bx-lock' },- { id: '_optionsEtapi', title: t("hidden-subtree.etapi-title"), type: 'contentWidget', icon: 'bx-extension' },- { id: '_optionsBackup', title: t("hidden-subtree.backup-title"), type: 'contentWidget', icon: 'bx-data' },- { id: '_optionsSync', title: t("hidden-subtree.sync-title"), type: 'contentWidget', icon: 'bx-wifi' },- { id: '_optionsOther', title: t("hidden-subtree.other"), type: 'contentWidget', icon: 'bx-dots-horizontal' },- { id: '_optionsAdvanced', title: t("hidden-subtree.advanced-title"), type: 'contentWidget' }+ { id: "_optionsAppearance", title: t("hidden-subtree.appearance-title"), type: "contentWidget", icon: "bx-layout" },+ { id: "_optionsShortcuts", title: t("hidden-subtree.shortcuts-title"), type: "contentWidget", icon: "bxs-keyboard" },+ { id: "_optionsTextNotes", title: t("hidden-subtree.text-notes"), type: "contentWidget", icon: "bx-text" },+ { id: "_optionsCodeNotes", title: t("hidden-subtree.code-notes-title"), type: "contentWidget", icon: "bx-code" },+ { id: "_optionsImages", title: t("hidden-subtree.images-title"), type: "contentWidget", icon: "bx-image" },+ { id: "_optionsSpellcheck", title: t("hidden-subtree.spellcheck-title"), type: "contentWidget", icon: "bx-check-double" },+ { id: "_optionsPassword", title: t("hidden-subtree.password-title"), type: "contentWidget", icon: "bx-lock" },+ { id: "_optionsEtapi", title: t("hidden-subtree.etapi-title"), type: "contentWidget", icon: "bx-extension" },+ { id: "_optionsBackup", title: t("hidden-subtree.backup-title"), type: "contentWidget", icon: "bx-data" },+ { id: "_optionsSync", title: t("hidden-subtree.sync-title"), type: "contentWidget", icon: "bx-wifi" },+ { id: "_optionsOther", title: t("hidden-subtree.other"), type: "contentWidget", icon: "bx-dots-horizontal" },+ { id: "_optionsAdvanced", title: t("hidden-subtree.advanced-title"), type: "contentWidget" }]}]@@ -326,7 +365,7 @@ function checkHiddenSubtree(force = false, extraOpts: CheckHiddenExtraOpts = {})hiddenSubtreeDefinition = buildHiddenSubtreeDefinition();}- checkHiddenSubtreeRecursively('root', hiddenSubtreeDefinition, extraOpts);+ checkHiddenSubtreeRecursively("root", hiddenSubtreeDefinition, extraOpts);}function checkHiddenSubtreeRecursively(parentNoteId: string, item: Item, extraOpts: CheckHiddenExtraOpts = {}) {@@ -334,7 +373,7 @@ function checkHiddenSubtreeRecursively(parentNoteId: string, item: Item, extraOpthrow new Error(`Item does not contain mandatory properties: ${JSON.stringify(item)}`);}- if (item.id.charAt(0) !== '_') {+ if (item.id.charAt(0) !== "_") {throw new Error(`ID has to start with underscore, given '${item.id}'`);}@@ -342,41 +381,41 @@ function checkHiddenSubtreeRecursively(parentNoteId: string, item: Item, extraOplet branch;if (!note) {- ({note, branch} = noteService.createNewNote({+ ({ note, branch } = noteService.createNewNote({noteId: item.id,title: item.title,type: item.type,parentNoteId: parentNoteId,- content: '',+ content: "",ignoreForbiddenParents: true}));} else {- branch = note.getParentBranches().find(branch => branch.parentNoteId === parentNoteId);+ branch = note.getParentBranches().find((branch) => branch.parentNoteId === parentNoteId);}const attrs = [...(item.attributes || [])];if (item.icon) {- attrs.push({ type: 'label', name: 'iconClass', value: `bx ${item.icon}` });+ attrs.push({ type: "label", name: "iconClass", value: `bx ${item.icon}` });}- if (item.type === 'launcher') {+ if (item.type === "launcher") {if (item.command) {- attrs.push({ type: 'relation', name: 'template', value: LBTPL_COMMAND });- attrs.push({ type: 'label', name: 'command', value: item.command });+ attrs.push({ type: "relation", name: "template", value: LBTPL_COMMAND });+ attrs.push({ type: "label", name: "command", value: item.command });} else if (item.builtinWidget) {- if (item.builtinWidget === 'spacer') {- attrs.push({ type: 'relation', name: 'template', value: LBTPL_SPACER });- attrs.push({ type: 'label', name: 'baseSize', value: item.baseSize });- attrs.push({ type: 'label', name: 'growthFactor', value: item.growthFactor });+ if (item.builtinWidget === "spacer") {+ attrs.push({ type: "relation", name: "template", value: LBTPL_SPACER });+ attrs.push({ type: "label", name: "baseSize", value: item.baseSize });+ attrs.push({ type: "label", name: "growthFactor", value: item.growthFactor });} else {- attrs.push({ type: 'relation', name: 'template', value: LBTPL_BUILTIN_WIDGET });+ attrs.push({ type: "relation", name: "template", value: LBTPL_BUILTIN_WIDGET });}- attrs.push({ type: 'label', name: 'builtinWidget', value: item.builtinWidget });+ attrs.push({ type: "label", name: "builtinWidget", value: item.builtinWidget });} else if (item.targetNoteId) {- attrs.push({ type: 'relation', name: 'template', value: LBTPL_NOTE_LAUNCHER });- attrs.push({ type: 'relation', name: 'target', value: item.targetNoteId });+ attrs.push({ type: "relation", name: "template", value: LBTPL_NOTE_LAUNCHER });+ attrs.push({ type: "relation", name: "target", value: item.targetNoteId });} else {throw new Error(`No action defined for launcher ${JSON.stringify(item)}`);}@@ -410,7 +449,7 @@ function checkHiddenSubtreeRecursively(parentNoteId: string, item: Item, extraOpfor (const attr of attrs) {const attrId = note.noteId + "_" + attr.type.charAt(0) + attr.name;- if (!note.getAttributes().find(attr => attr.attributeId === attrId)) {+ if (!note.getAttributes().find((attr) => attr.attributeId === attrId)) {new BAttribute({attributeId: attrId,noteId: note.noteId,diff --git a/src/services/hoisted_note.ts b/src/services/hoisted_note.tsindex 798889c460..ba68263fc8 100644--- a/src/services/hoisted_note.ts+++ b/src/services/hoisted_note.ts@@ -8,9 +8,9 @@ function getHoistedNoteId() {function isHoistedInHiddenSubtree() {const hoistedNoteId = getHoistedNoteId();- if (hoistedNoteId === 'root') {+ if (hoistedNoteId === "root") {return false;- } else if (hoistedNoteId === '_hidden') {+ } else if (hoistedNoteId === "_hidden") {return true;}@@ -26,7 +26,7 @@ function isHoistedInHiddenSubtree() {function getWorkspaceNote() {const hoistedNote = becca.getNote(cls.getHoistedNoteId());- if (hoistedNote && (hoistedNote.isRoot() || hoistedNote.hasLabel('workspace'))) {+ if (hoistedNote && (hoistedNote.isRoot() || hoistedNote.hasLabel("workspace"))) {return hoistedNote;} else {return becca.getRoot();diff --git a/src/services/host.ts b/src/services/host.tsindex fe5302bf21..eee470e084 100644--- a/src/services/host.ts+++ b/src/services/host.ts@@ -7,7 +7,7 @@ function getHost() {return envHost;}- return config['Network']['host'] || '0.0.0.0';+ return config["Network"]["host"] || "0.0.0.0";}export default getHost();diff --git a/src/services/html_sanitizer.ts b/src/services/html_sanitizer.tsindex 6847300979..40f9734c98 100644--- a/src/services/html_sanitizer.ts+++ b/src/services/html_sanitizer.ts@@ -4,17 +4,101 @@ import optionService from "./options.js";// Default list of allowed HTML tagsexport const DEFAULT_ALLOWED_TAGS = [- 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol',- 'li', 'b', 'i', 'strong', 'em', 'strike', 's', 'del', 'abbr', 'code', 'hr', 'br', 'div',- 'table', 'thead', 'caption', 'tbody', 'tfoot', 'tr', 'th', 'td', 'pre', 'section', 'img',- 'figure', 'figcaption', 'span', 'label', 'input', 'details', 'summary', 'address', 'aside', 'footer',- 'header', 'hgroup', 'main', 'nav', 'dl', 'dt', 'menu', 'bdi', 'bdo', 'dfn', 'kbd', 'mark', 'q', 'time',- 'var', 'wbr', 'area', 'map', 'track', 'video', 'audio', 'picture', 'del', 'ins',- 'en-media', // for ENEX import+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "blockquote",+ "p",+ "a",+ "ul",+ "ol",+ "li",+ "b",+ "i",+ "strong",+ "em",+ "strike",+ "s",+ "del",+ "abbr",+ "code",+ "hr",+ "br",+ "div",+ "table",+ "thead",+ "caption",+ "tbody",+ "tfoot",+ "tr",+ "th",+ "td",+ "pre",+ "section",+ "img",+ "figure",+ "figcaption",+ "span",+ "label",+ "input",+ "details",+ "summary",+ "address",+ "aside",+ "footer",+ "header",+ "hgroup",+ "main",+ "nav",+ "dl",+ "dt",+ "menu",+ "bdi",+ "bdo",+ "dfn",+ "kbd",+ "mark",+ "q",+ "time",+ "var",+ "wbr",+ "area",+ "map",+ "track",+ "video",+ "audio",+ "picture",+ "del",+ "ins",+ "en-media", // for ENEX import// Additional tags (https://github.com/TriliumNext/Notes/issues/567)- 'acronym', 'article', 'big', 'button', 'cite', 'col', 'colgroup', 'data', 'dd',- 'fieldset', 'form', 'legend', 'meter', 'noscript', 'option', 'progress', 'rp',- 'samp', 'small', 'sub', 'sup', 'template', 'textarea', 'tt'+ "acronym",+ "article",+ "big",+ "button",+ "cite",+ "col",+ "colgroup",+ "data",+ "dd",+ "fieldset",+ "form",+ "legend",+ "meter",+ "noscript",+ "option",+ "progress",+ "rp",+ "samp",+ "small",+ "sub",+ "sup",+ "template",+ "textarea",+ "tt"] as const;// intended mainly as protection against XSS via import@@ -33,8 +117,7 @@ function sanitize(dirtyHtml: string) {for (let i = 1; i < 6; ++i) {if (lowercasedHtml.includes(`<h${i}`)) {transformTags[`h${i}`] = `h${i + 1}`;- }- else {+ } else {break;}}@@ -42,7 +125,7 @@ function sanitize(dirtyHtml: string) {// Get allowed tags from options, with fallback to default list if option not yet setlet allowedTags;try {- allowedTags = JSON.parse(optionService.getOption('allowedHtmlTags'));+ allowedTags = JSON.parse(optionService.getOption("allowedHtmlTags"));} catch (e) {// Fallback to default list if option doesn't exist or is invalidallowedTags = DEFAULT_ALLOWED_TAGS;@@ -52,19 +135,60 @@ function sanitize(dirtyHtml: string) {return sanitizeHtml(dirtyHtml, {allowedTags,allowedAttributes: {- "*": [ 'class', 'style', 'title', 'src', 'href', 'hash', 'disabled', 'align', 'alt', 'center', 'data-*' ],- "input": [ "type", "checked" ]+ "*": ["class", "style", "title", "src", "href", "hash", "disabled", "align", "alt", "center", "data-*"],+ input: ["type", "checked"]},// Be consistent with `allowedSchemes` in `src\public\app\services\link.js`allowedSchemes: [- 'http', 'https', 'ftp', 'ftps', 'mailto', 'data', 'evernote', 'file', 'facetime', 'gemini', 'git',- 'gopher', 'imap', 'irc', 'irc6', 'jabber', 'jar', 'lastfm', 'ldap', 'ldaps', 'magnet', 'message',- 'mumble', 'nfs', 'onenote', 'pop', 'rmi', 's3', 'sftp', 'skype', 'sms', 'spotify', 'steam', 'svn', 'udp',- 'view-source', 'vlc', 'vnc', 'ws', 'wss', 'xmpp', 'jdbc', 'slack', 'tel', 'smb', 'zotero', 'geo'- ],- nonTextTags: [- 'head'+ "http",+ "https",+ "ftp",+ "ftps",+ "mailto",+ "data",+ "evernote",+ "file",+ "facetime",+ "gemini",+ "git",+ "gopher",+ "imap",+ "irc",+ "irc6",+ "jabber",+ "jar",+ "lastfm",+ "ldap",+ "ldaps",+ "magnet",+ "message",+ "mumble",+ "nfs",+ "onenote",+ "pop",+ "rmi",+ "s3",+ "sftp",+ "skype",+ "sms",+ "spotify",+ "steam",+ "svn",+ "udp",+ "view-source",+ "vlc",+ "vnc",+ "ws",+ "wss",+ "xmpp",+ "jdbc",+ "slack",+ "tel",+ "smb",+ "zotero",+ "geo"],+ nonTextTags: ["head"],transformTags});}diff --git a/src/services/i18n.ts b/src/services/i18n.tsindex 98342ae0d6..4f659cb309 100644--- a/src/services/i18n.ts+++ b/src/services/i18n.ts@@ -7,34 +7,34 @@ import { getResourceDir } from "./utils.js";import hidden_subtree from "./hidden_subtree.js";export async function initializeTranslations() {- const resourceDir = getResourceDir();+ const resourceDir = getResourceDir();- // Initialize translations- await i18next.use(Backend).init({- lng: getCurrentLanguage(),- fallbackLng: "en",- ns: "server",- backend: {- loadPath: join(resourceDir, "translations/{{lng}}/{{ns}}.json")- }- });+ // Initialize translations+ await i18next.use(Backend).init({+ lng: getCurrentLanguage(),+ fallbackLng: "en",+ ns: "server",+ backend: {+ loadPath: join(resourceDir, "translations/{{lng}}/{{ns}}.json")+ }+ });}function getCurrentLanguage() {- let language;- if (sql_init.isDbInitialized()) {- language = options.getOptionOrNull("locale");- }+ let language;+ if (sql_init.isDbInitialized()) {+ language = options.getOptionOrNull("locale");+ }- if (!language) {- console.info("Language option not found, falling back to en.");- language = "en";- }+ if (!language) {+ console.info("Language option not found, falling back to en.");+ language = "en";+ }- return language;+ return language;}export async function changeLanguage(locale: string) {- await i18next.changeLanguage(locale);- hidden_subtree.checkHiddenSubtree(true, { restoreNames: true });+ await i18next.changeLanguage(locale);+ hidden_subtree.checkHiddenSubtree(true, { restoreNames: true });}diff --git a/src/services/image.ts b/src/services/image.tsindex 12ba420c3d..387fcaec54 100644--- a/src/services/image.ts+++ b/src/services/image.ts@@ -19,8 +19,7 @@ async function processImage(uploadBuffer: Buffer, originalName: string, shrinkImif (!origImageFormat || !["jpg", "png"].includes(origImageFormat.ext)) {shrinkImageSwitch = false;- }- else if (isAnimated(uploadBuffer)) {+ } else if (isAnimated(uploadBuffer)) {// recompression of animated images will make them staticshrinkImageSwitch = false;}@@ -34,7 +33,7 @@ async function processImage(uploadBuffer: Buffer, originalName: string, shrinkIm} else {finalImageBuffer = uploadBuffer;imageFormat = origImageFormat || {- ext: 'dat'+ ext: "dat"};}@@ -46,17 +45,16 @@ async function processImage(uploadBuffer: Buffer, originalName: string, shrinkImasync function getImageType(buffer: Buffer) {if (isSvg(buffer.toString())) {- return { ext: 'svg' }- }- else {- return await imageType(buffer) || { ext: "jpg" }; // optimistic JPG default+ return { ext: "svg" };+ } else {+ return (await imageType(buffer)) || { ext: "jpg" }; // optimistic JPG default}}function getImageMimeFromExtension(ext: string) {ext = ext.toLowerCase();- return `image/${ext === 'svg' ? 'svg+xml' : ext}`;+ return `image/${ext === "svg" ? "svg+xml" : ext}`;}function updateImage(noteId: string, uploadBuffer: Buffer, originalName: string) {@@ -65,14 +63,16 @@ function updateImage(noteId: string, uploadBuffer: Buffer, originalName: string)originalName = htmlSanitizer.sanitize(originalName);const note = becca.getNote(noteId);- if (!note) { throw new Error("Unable to find note."); }+ if (!note) {+ throw new Error("Unable to find note.");+ }note.saveRevision();- note.setLabel('originalFileName', originalName);+ note.setLabel("originalFileName", originalName);// resizing images asynchronously since JIMP does not support sync operation- processImage(uploadBuffer, originalName, true).then(({buffer, imageFormat}) => {+ processImage(uploadBuffer, originalName, true).then(({ buffer, imageFormat }) => {sql.transactional(() => {note.mime = getImageMimeFromExtension(imageFormat.ext);note.save();@@ -92,28 +92,30 @@ function saveImage(parentNoteId: string, uploadBuffer: Buffer, originalName: strconst fileName = sanitizeFilename(originalName);const parentNote = becca.getNote(parentNoteId);- if (!parentNote) { throw new Error("Unable to find parent note."); }+ if (!parentNote) {+ throw new Error("Unable to find parent note.");+ }- const {note} = noteService.createNewNote({+ const { note } = noteService.createNewNote({parentNoteId,title: fileName,- type: 'image',- mime: 'unknown',- content: '',+ type: "image",+ mime: "unknown",+ content: "",isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()});- note.addLabel('originalFileName', originalName);+ note.addLabel("originalFileName", originalName);// resizing images asynchronously since JIMP does not support sync operation- processImage(uploadBuffer, originalName, shrinkImageSwitch).then(({buffer, imageFormat}) => {+ processImage(uploadBuffer, originalName, shrinkImageSwitch).then(({ buffer, imageFormat }) => {sql.transactional(() => {note.mime = getImageMimeFromExtension(imageFormat.ext);if (!originalName.includes(".")) {originalName += `.${imageFormat.ext}`;- note.setLabel('originalFileName', originalName);+ note.setLabel("originalFileName", originalName);note.title = sanitizeFilename(originalName);}@@ -141,8 +143,8 @@ function saveImageToAttachment(noteId: string, uploadBuffer: Buffer, originalNamconst note = becca.getNoteOrThrow(noteId);let attachment = note.saveAttachment({- role: 'image',- mime: 'unknown',+ role: "image",+ mime: "unknown",title: fileName});@@ -157,10 +159,12 @@ function saveImageToAttachment(noteId: string, uploadBuffer: Buffer, originalNam}, 5000);// resizing images asynchronously since JIMP does not support sync operation- processImage(uploadBuffer, originalName, !!shrinkImageSwitch).then(({buffer, imageFormat}) => {+ processImage(uploadBuffer, originalName, !!shrinkImageSwitch).then(({ buffer, imageFormat }) => {sql.transactional(() => {// re-read, might be changed in the meantime- if (!attachment.attachmentId) { throw new Error("Missing attachment ID."); }+ if (!attachment.attachmentId) {+ throw new Error("Missing attachment ID.");+ }attachment = becca.getAttachmentOrThrow(attachment.attachmentId);attachment.mime = getImageMimeFromExtension(imageFormat.ext);@@ -178,7 +182,7 @@ function saveImageToAttachment(noteId: string, uploadBuffer: Buffer, originalNam}async function shrinkImage(buffer: Buffer, originalName: string) {- let jpegQuality = optionService.getOptionInt('imageJpegQuality', 0);+ let jpegQuality = optionService.getOptionInt("imageJpegQuality", 0);if (jpegQuality < 10 || jpegQuality > 100) {jpegQuality = 75;@@ -187,8 +191,7 @@ async function shrinkImage(buffer: Buffer, originalName: string) {let finalImageBuffer;try {finalImageBuffer = await resize(buffer, jpegQuality);- }- catch (e: any) {+ } catch (e: any) {log.error(`Failed to resize image '${originalName}', stack: ${e.stack}`);finalImageBuffer = buffer;@@ -204,7 +207,7 @@ async function shrinkImage(buffer: Buffer, originalName: string) {}async function resize(buffer: Buffer, quality: number) {- const imageMaxWidthHeight = optionService.getOptionInt('imageMaxWidthHeight');+ const imageMaxWidthHeight = optionService.getOptionInt("imageMaxWidthHeight");const start = Date.now();@@ -212,13 +215,12 @@ async function resize(buffer: Buffer, quality: number) {if (image.bitmap.width > image.bitmap.height && image.bitmap.width > imageMaxWidthHeight) {image.resize({ w: imageMaxWidthHeight });- }- else if (image.bitmap.height > imageMaxWidthHeight) {+ } else if (image.bitmap.height > imageMaxWidthHeight) {image.resize({ h: imageMaxWidthHeight });}// when converting PNG to JPG, we lose the alpha channel, this is replaced by white to match Trilium white background- image.background = 0xFFFFFFFF;+ image.background = 0xffffffff;const resultBuffer = await image.getBuffer("image/jpeg", { quality });diff --git a/src/services/import/enex.ts b/src/services/import/enex.tsindex f0805b2fcc..f7557351f5 100644--- a/src/services/import/enex.ts+++ b/src/services/import/enex.ts@@ -1,6 +1,6 @@import sax from "sax";import stream from "stream";-import { Throttle } from 'stream-throttle';+import { Throttle } from "stream-throttle";import log from "../log.js";import { md5, escapeHtml, fromBase64 } from "../utils.js";import sql from "../sql.js";@@ -23,8 +23,7 @@ function parseDate(text: string) {text = text.replace(/[-:]/g, "");// insert - and : to convert it to trilium format- text = text.substr(0, 4) + "-" + text.substr(4, 2) + "-" + text.substr(6, 2)- + " " + text.substr(9, 2) + ":" + text.substr(11, 2) + ":" + text.substr(13, 2) + ".000Z";+ text = text.substr(0, 4) + "-" + text.substr(4, 2) + "-" + text.substr(6, 2) + " " + text.substr(9, 2) + ":" + text.substr(11, 2) + ":" + text.substr(13, 2) + ".000Z";return text;}@@ -50,7 +49,7 @@ interface Note {noteId: string;blobId: string;content: string;- resources: Resource[]+ resources: Resource[];}let note: Partial<Note> = {};@@ -59,28 +58,26 @@ let resource: Resource;function importEnex(taskContext: TaskContext, file: File, parentNote: BNote): Promise<BNote> {const saxStream = sax.createStream(true);- const rootNoteTitle = file.originalname.toLowerCase().endsWith(".enex")- ? file.originalname.substr(0, file.originalname.length - 5)- : file.originalname;+ const rootNoteTitle = file.originalname.toLowerCase().endsWith(".enex") ? file.originalname.substr(0, file.originalname.length - 5) : file.originalname;// root note is new note into all ENEX/notebook's notes will be importedconst rootNote = noteService.createNewNote({parentNoteId: parentNote.noteId,title: rootNoteTitle,content: "",- type: 'text',- mime: 'text/html',- isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),+ type: "text",+ mime: "text/html",+ isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()}).note;function extractContent(content: string) {- const openingNoteIndex = content.indexOf('<en-note>');+ const openingNoteIndex = content.indexOf("<en-note>");if (openingNoteIndex !== -1) {content = content.substr(openingNoteIndex + 9);}- const closingNoteIndex = content.lastIndexOf('</en-note>');+ const closingNoteIndex = content.lastIndexOf("</en-note>");if (closingNoteIndex !== -1) {content = content.substr(0, closingNoteIndex);@@ -109,15 +106,20 @@ function importEnex(taskContext: TaskContext, file: File, parentNote: BNote): Pr// Replace OneNote converted checkboxes with unicode ballot box based// on known hash of checkboxes for regular, p1, and p2 checkboxes- content = content.replace(/<en-media alt="To Do( priority [12])?" hash="(74de5d3d1286f01bac98d32a09f601d9|4a19d3041585e11643e808d68dd3e72f|8e17580123099ac6515c3634b1f6f9a1)"( type="[a-z\/]*"| width="\d+"| height="\d+")*\/>/g, "\u2610 ");- content = content.replace(/<en-media alt="To Do( priority [12])?" hash="(5069b775461e471a47ce04ace6e1c6ae|7912ee9cec35fc3dba49edb63a9ed158|3a05f4f006a6eaf2627dae5ed8b8013b)"( type="[a-z\/]*"| width="\d+"| height="\d+")*\/>/g, "\u2611 ");+ content = content.replace(+ /<en-media alt="To Do( priority [12])?" hash="(74de5d3d1286f01bac98d32a09f601d9|4a19d3041585e11643e808d68dd3e72f|8e17580123099ac6515c3634b1f6f9a1)"( type="[a-z\/]*"| width="\d+"| height="\d+")*\/>/g,+ "\u2610 "+ );+ content = content.replace(+ /<en-media alt="To Do( priority [12])?" hash="(5069b775461e471a47ce04ace6e1c6ae|7912ee9cec35fc3dba49edb63a9ed158|3a05f4f006a6eaf2627dae5ed8b8013b)"( type="[a-z\/]*"| width="\d+"| height="\d+")*\/>/g,+ "\u2611 "+ );content = htmlSanitizer.sanitize(content);return content;}-const path: string[] = [];function getCurrentTag() {@@ -132,7 +134,7 @@ function importEnex(taskContext: TaskContext, file: File, parentNote: BNote): Pr}}- saxStream.on("error", e => {+ saxStream.on("error", (e) => {// unhandled errors will throw, since this is a proper node event emitter.log.error(`error when parsing ENEX file: ${e}`);// clear the error@@ -140,92 +142,86 @@ function importEnex(taskContext: TaskContext, file: File, parentNote: BNote): PrsaxStream._parser.resume();});- saxStream.on("text", text => {+ saxStream.on("text", (text) => {const currentTag = getCurrentTag();const previousTag = getPreviousTag();- if (previousTag === 'note-attributes') {+ if (previousTag === "note-attributes") {let labelName = currentTag;- if (labelName === 'source-url') {- labelName = 'pageUrl';+ if (labelName === "source-url") {+ labelName = "pageUrl";}labelName = sanitizeAttributeName(labelName || "");if (note.attributes) {note.attributes.push({- type: 'label',+ type: "label",name: labelName,value: text});}- }- else if (previousTag === 'resource-attributes') {- if (currentTag === 'file-name') {+ } else if (previousTag === "resource-attributes") {+ if (currentTag === "file-name") {resource.attributes.push({- type: 'label',- name: 'originalFileName',+ type: "label",+ name: "originalFileName",value: text});resource.title = text;- }- else if (currentTag === 'source-url') {+ } else if (currentTag === "source-url") {resource.attributes.push({- type: 'label',- name: 'pageUrl',+ type: "label",+ name: "pageUrl",value: text});}- }- else if (previousTag === 'resource') {- if (currentTag === 'data') {- text = text.replace(/\s/g, '');+ } else if (previousTag === "resource") {+ if (currentTag === "data") {+ text = text.replace(/\s/g, "");// resource can be chunked into multiple events: https://github.com/zadam/trilium/issues/3424// it would probably make sense to do this in a more global way since it can in theory affect any field,// not just dataresource.content = (resource.content || "") + text;- }- else if (currentTag === 'mime') {+ } else if (currentTag === "mime") {resource.mime = text.toLowerCase();}- }- else if (previousTag === 'note') {- if (currentTag === 'title') {+ } else if (previousTag === "note") {+ if (currentTag === "title") {note.title = text;- } else if (currentTag === 'created') {+ } else if (currentTag === "created") {note.utcDateCreated = parseDate(text);- } else if (currentTag === 'updated') {+ } else if (currentTag === "updated") {note.utcDateModified = parseDate(text);- } else if (currentTag === 'tag' && note.attributes) {+ } else if (currentTag === "tag" && note.attributes) {note.attributes.push({- type: 'label',+ type: "label",name: sanitizeAttributeName(text),- value: ''- })+ value: ""+ });}// unknown tags are just ignored}});- saxStream.on("attribute", attr => {+ saxStream.on("attribute", (attr) => {// an attribute. attr has "name" and "value"});- saxStream.on("opentag", tag => {+ saxStream.on("opentag", (tag) => {path.push(tag.name);- if (tag.name === 'note') {+ if (tag.name === "note") {note = {content: "",// it's an array, not a key-value object because we don't know if attributes can be duplicatedattributes: [],resources: []};- }- else if (tag.name === 'resource') {+ } else if (tag.name === "resource") {resource = {title: "resource",attributes: []@@ -239,25 +235,29 @@ function importEnex(taskContext: TaskContext, file: File, parentNote: BNote): Prfunction updateDates(note: BNote, utcDateCreated?: string, utcDateModified?: string) {// it's difficult to force custom dateCreated and dateModified to Note entity, so we do it post-creation with SQL- sql.execute(`+ sql.execute(+ `UPDATE notesSET dateCreated = ?,utcDateCreated = ?,dateModified = ?,utcDateModified = ?WHERE noteId = ?`,- [utcDateCreated, utcDateCreated, utcDateModified, utcDateModified, note.noteId]);+ [utcDateCreated, utcDateCreated, utcDateModified, utcDateModified, note.noteId]+ );- sql.execute(`+ sql.execute(+ `UPDATE blobsSET utcDateModified = ?WHERE blobId = ?`,- [utcDateModified, note.blobId]);+ [utcDateModified, note.blobId]+ );}function saveNote() {// make a copy because stream continues with the next call and note gets overwritten- let {title, content, attributes, resources, utcDateCreated, utcDateModified} = note;+ let { title, content, attributes, resources, utcDateCreated, utcDateModified } = note;if (!title || !content) {throw new Error("Missing title or content for note.");@@ -270,9 +270,9 @@ function importEnex(taskContext: TaskContext, file: File, parentNote: BNote): Prtitle,content,utcDateCreated,- type: 'text',- mime: 'text/html',- isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),+ type: "text",+ mime: "text/html",+ isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()}).note;for (const attr of attributes || []) {@@ -297,16 +297,20 @@ function importEnex(taskContext: TaskContext, file: File, parentNote: BNote): Prconst hash = md5(resource.content);// skip all checked/unchecked checkboxes from OneNote- if (['74de5d3d1286f01bac98d32a09f601d9',- '4a19d3041585e11643e808d68dd3e72f',- '8e17580123099ac6515c3634b1f6f9a1',- '5069b775461e471a47ce04ace6e1c6ae',- '7912ee9cec35fc3dba49edb63a9ed158',- '3a05f4f006a6eaf2627dae5ed8b8013b'].includes(hash)) {+ if (+ [+ "74de5d3d1286f01bac98d32a09f601d9",+ "4a19d3041585e11643e808d68dd3e72f",+ "8e17580123099ac6515c3634b1f6f9a1",+ "5069b775461e471a47ce04ace6e1c6ae",+ "7912ee9cec35fc3dba49edb63a9ed158",+ "3a05f4f006a6eaf2627dae5ed8b8013b"+ ].includes(hash)+ ) {continue;}- const mediaRegex = new RegExp(`<en-media [^>]*hash="${hash}"[^>]*>`, 'g');+ const mediaRegex = new RegExp(`<en-media [^>]*hash="${hash}"[^>]*>`, "g");resource.mime = resource.mime || "application/octet-stream";@@ -319,9 +323,9 @@ function importEnex(taskContext: TaskContext, file: File, parentNote: BNote): PrparentNoteId: noteEntity.noteId,title: resource.title,content: resource.content,- type: 'file',+ type: "file",mime: resource.mime,- isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),+ isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()}).note;for (const attr of resource.attributes) {@@ -337,11 +341,9 @@ function importEnex(taskContext: TaskContext, file: File, parentNote: BNote): Prcontent = (content || "").replace(mediaRegex, resourceLink);};- if (resource.mime && resource.mime.startsWith('image/')) {+ if (resource.mime && resource.mime.startsWith("image/")) {try {- const originalName = (resource.title && resource.title !== 'resource')- ? resource.title- : `image.${resource.mime.substr(6)}`; // default if real name is not present+ const originalName = resource.title && resource.title !== "resource" ? resource.title : `image.${resource.mime.substr(6)}`; // default if real name is not presentconst attachment = imageService.saveImageToAttachment(noteEntity.noteId, resource.content, originalName, !!taskContext.data?.shrinkImages);@@ -375,10 +377,10 @@ function importEnex(taskContext: TaskContext, file: File, parentNote: BNote): PrupdateDates(noteEntity, utcDateCreated, utcDateModified);}- saxStream.on("closetag", tag => {+ saxStream.on("closetag", (tag) => {path.pop();- if (tag === 'note') {+ if (tag === "note") {saveNote();}});@@ -387,7 +389,7 @@ function importEnex(taskContext: TaskContext, file: File, parentNote: BNote): Pr//console.log("opencdata");});- saxStream.on("cdata", text => {+ saxStream.on("cdata", (text) => {note.content += text;});@@ -395,8 +397,7 @@ function importEnex(taskContext: TaskContext, file: File, parentNote: BNote): Pr//console.log("closecdata");});- return new Promise((resolve, reject) =>- {+ return new Promise((resolve, reject) => {// resolve only when we parse the whole document AND saving of all notes have been finishedsaxStream.on("end", () => resolve(rootNote));@@ -405,7 +406,7 @@ function importEnex(taskContext: TaskContext, file: File, parentNote: BNote): PrbufferStream// rate limiting to improve responsiveness during / after import- .pipe(new Throttle({rate: 500000}))+ .pipe(new Throttle({ rate: 500000 })).pipe(saxStream);});}diff --git a/src/services/import/mime.ts b/src/services/import/mime.tsindex 55119e4ca1..14e9f5d489 100644--- a/src/services/import/mime.ts+++ b/src/services/import/mime.ts@@ -2,46 +2,46 @@import mimeTypes from "mime-types";import path from "path";-import { TaskData } from '../task_context_interface.js';+import { TaskData } from "../task_context_interface.js";const CODE_MIME_TYPES: Record<string, boolean | string> = {- 'text/plain': true,- 'text/x-csrc': true,- 'text/x-c++src': true,- 'text/x-csharp': true,- 'text/x-clojure': true,- 'text/css': true,- 'text/x-dockerfile': true,- 'text/x-erlang': true,- 'text/x-feature': true,- 'text/x-go': true,- 'text/x-groovy': true,- 'text/x-haskell': true,- 'text/html': true,- 'message/http': true,- 'text/x-java': true,- 'application/javascript': 'application/javascript;env=frontend',- 'application/x-javascript': 'application/javascript;env=frontend',- 'application/json': true,- 'text/x-kotlin': true,- 'text/x-stex': true,- 'text/x-lua': true,+ "text/plain": true,+ "text/x-csrc": true,+ "text/x-c++src": true,+ "text/x-csharp": true,+ "text/x-clojure": true,+ "text/css": true,+ "text/x-dockerfile": true,+ "text/x-erlang": true,+ "text/x-feature": true,+ "text/x-go": true,+ "text/x-groovy": true,+ "text/x-haskell": true,+ "text/html": true,+ "message/http": true,+ "text/x-java": true,+ "application/javascript": "application/javascript;env=frontend",+ "application/x-javascript": "application/javascript;env=frontend",+ "application/json": true,+ "text/x-kotlin": true,+ "text/x-stex": true,+ "text/x-lua": true,// possibly later migrate to text/markdown as primary MIME- 'text/markdown': 'text/x-markdown',- 'text/x-markdown': true,- 'text/x-objectivec': true,- 'text/x-pascal': true,- 'text/x-perl': true,- 'text/x-php': true,- 'text/x-python': true,- 'text/x-ruby': true,- 'text/x-rustsrc': true,- 'text/x-scala': true,- 'text/x-sh': true,- 'text/x-sql': true,- 'text/x-swift': true,- 'text/xml': true,- 'text/x-yaml': true+ "text/markdown": "text/x-markdown",+ "text/x-markdown": true,+ "text/x-objectivec": true,+ "text/x-pascal": true,+ "text/x-perl": true,+ "text/x-php": true,+ "text/x-python": true,+ "text/x-ruby": true,+ "text/x-rustsrc": true,+ "text/x-scala": true,+ "text/x-sh": true,+ "text/x-sql": true,+ "text/x-swift": true,+ "text/xml": true,+ "text/x-yaml": true};// extensions missing in mime-db@@ -67,7 +67,7 @@ const EXTENSION_TO_MIME: Record<string, string> = {/** @returns false if MIME is not detected */function getMime(fileName: string) {- if (fileName.toLowerCase() === 'dockerfile') {+ if (fileName.toLowerCase() === "dockerfile") {return "text/x-dockerfile";}@@ -81,24 +81,21 @@ function getMime(fileName: string) {}function getType(options: TaskData, mime: string) {- mime = mime ? mime.toLowerCase() : '';+ mime = mime ? mime.toLowerCase() : "";- if (options.textImportedAsText && (mime === 'text/html' || ['text/markdown', 'text/x-markdown'].includes(mime))) {- return 'text';- }- else if (options.codeImportedAsCode && mime in CODE_MIME_TYPES) {- return 'code';- }- else if (mime.startsWith("image/")) {- return 'image';- }- else {- return 'file';+ if (options.textImportedAsText && (mime === "text/html" || ["text/markdown", "text/x-markdown"].includes(mime))) {+ return "text";+ } else if (options.codeImportedAsCode && mime in CODE_MIME_TYPES) {+ return "code";+ } else if (mime.startsWith("image/")) {+ return "image";+ } else {+ return "file";}}function normalizeMimeType(mime: string) {- mime = mime ? mime.toLowerCase() : '';+ mime = mime ? mime.toLowerCase() : "";const mappedMime = CODE_MIME_TYPES[mime];if (mappedMime === true) {diff --git a/src/services/import/opml.ts b/src/services/import/opml.tsindex 32a633746b..dc7496951e 100644--- a/src/services/import/opml.ts+++ b/src/services/import/opml.ts@@ -14,9 +14,9 @@ interface OpmlXml {interface OpmlBody {$: {- version: string- }- body: OpmlOutline[]+ version: string;+ };+ body: OpmlOutline[];}interface OpmlOutline {@@ -29,19 +29,17 @@ interface OpmlOutline {}async function importOpml(taskContext: TaskContext, fileBuffer: string | Buffer, parentNote: BNote) {- const xml = await new Promise<OpmlXml>(function(resolve, reject)- {+ const xml = await new Promise<OpmlXml>(function (resolve, reject) {parseString(fileBuffer, function (err: any, result: OpmlXml) {if (err) {reject(err);- }- else {+ } else {resolve(result);}});});- if (!['1.0', '1.1', '2.0'].includes(xml.opml.$.version)) {+ if (!["1.0", "1.1", "2.0"].includes(xml.opml.$.version)) {return [400, `Unsupported OPML version ${xml.opml.$.version}, 1.0, 1.1 or 2.0 expected instead.`];}@@ -57,30 +55,28 @@ async function importOpml(taskContext: TaskContext, fileBuffer: string | Buffer,if (!title || !title.trim()) {// https://github.com/zadam/trilium/issues/1862title = outline.$.text;- content = '';+ content = "";}- }- else if (opmlVersion === 2) {+ } else if (opmlVersion === 2) {title = outline.$.text;content = outline.$._note; // _note is already HTML- }- else {+ } else {throw new Error(`Unrecognized OPML version ${opmlVersion}`);}content = htmlSanitizer.sanitize(content || "");- const {note} = noteService.createNewNote({+ const { note } = noteService.createNewNote({parentNoteId,title,content,- type: 'text',+ type: "text",isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()});taskContext.increaseProgressCount();- for (const childOutline of (outline.outline || [])) {+ for (const childOutline of outline.outline || []) {importOutline(childOutline, note.noteId);}@@ -102,10 +98,10 @@ async function importOpml(taskContext: TaskContext, fileBuffer: string | Buffer,function toHtml(text: string) {if (!text) {- return '';+ return "";}- return `<p>${text.replace(/(?:\r\n|\r|\n)/g, '</p><p>')}</p>`;+ return `<p>${text.replace(/(?:\r\n|\r|\n)/g, "</p><p>")}</p>`;}export default {diff --git a/src/services/import/single.ts b/src/services/import/single.tsindex 3791b6ea12..0b6f1401e3 100644--- a/src/services/import/single.ts+++ b/src/services/import/single.ts@@ -17,16 +17,16 @@ function importSingleFile(taskContext: TaskContext, file: File, parentNote: BNotconst mime = mimeService.getMime(file.originalname) || file.mimetype;if (taskContext?.data?.textImportedAsText) {- if (mime === 'text/html') {+ if (mime === "text/html") {return importHtml(taskContext, file, parentNote);- } else if (['text/markdown', 'text/x-markdown'].includes(mime)) {+ } else if (["text/markdown", "text/x-markdown"].includes(mime)) {return importMarkdown(taskContext, file, parentNote);- } else if (mime === 'text/plain') {+ } else if (mime === "text/plain") {return importPlainText(taskContext, file, parentNote);}}- if (taskContext?.data?.codeImportedAsCode && mimeService.getType(taskContext.data, mime) === 'code') {+ if (taskContext?.data?.codeImportedAsCode && mimeService.getType(taskContext.data, mime) === "code") {return importCodeNote(taskContext, file, parentNote);}@@ -41,7 +41,7 @@ function importImage(file: File, parentNote: BNote, taskContext: TaskContext) {if (typeof file.buffer === "string") {throw new Error("Invalid file content for image.");}- const {note} = imageService.saveImage(parentNote.noteId, file.buffer, file.originalname, !!taskContext.data?.shrinkImages);+ const { note } = imageService.saveImage(parentNote.noteId, file.buffer, file.originalname, !!taskContext.data?.shrinkImages);taskContext.increaseProgressCount();@@ -51,12 +51,12 @@ function importImage(file: File, parentNote: BNote, taskContext: TaskContext) {function importFile(taskContext: TaskContext, file: File, parentNote: BNote) {const originalName = file.originalname;- const {note} = noteService.createNewNote({+ const { note } = noteService.createNewNote({parentNoteId: parentNote.noteId,title: originalName,content: file.buffer,isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),- type: 'file',+ type: "file",mime: mimeService.getMime(originalName) || file.mimetype});@@ -77,7 +77,7 @@ function importCodeNote(taskContext: TaskContext, file: File, parentNote: BNote)parentNoteId: parentNote.noteId,title,content,- type: 'code',+ type: "code",mime: mime,isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()});@@ -92,13 +92,13 @@ function importPlainText(taskContext: TaskContext, file: File, parentNote: BNoteconst plainTextContent = file.buffer.toString("utf-8");const htmlContent = convertTextToHtml(plainTextContent);- const {note} = noteService.createNewNote({+ const { note } = noteService.createNewNote({parentNoteId: parentNote.noteId,title,content: htmlContent,- type: 'text',- mime: 'text/html',- isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),+ type: "text",+ mime: "text/html",+ isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()});taskContext.increaseProgressCount();@@ -108,9 +108,7 @@ function importPlainText(taskContext: TaskContext, file: File, parentNote: BNotefunction convertTextToHtml(text: string) {// 1: Plain Text Search- text = text.replace(/&/g, "&").- replace(/</g, "<").- replace(/>/g, ">");+ text = text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");// 2: Line Breakstext = text.replace(/\r\n?|\n/g, "<br>");@@ -134,13 +132,13 @@ function importMarkdown(taskContext: TaskContext, file: File, parentNote: BNote)htmlContent = htmlSanitizer.sanitize(htmlContent);}- const {note} = noteService.createNewNote({+ const { note } = noteService.createNewNote({parentNoteId: parentNote.noteId,title,content: htmlContent,- type: 'text',- mime: 'text/html',- isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),+ type: "text",+ mime: "text/html",+ isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()});taskContext.increaseProgressCount();@@ -162,14 +160,13 @@ function importHtml(taskContext: TaskContext, file: File, parentNote: BNote) {content = htmlSanitizer.sanitize(content);}-- const {note} = noteService.createNewNote({+ const { note } = noteService.createNewNote({parentNoteId: parentNote.noteId,title,content,- type: 'text',- mime: 'text/html',- isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),+ type: "text",+ mime: "text/html",+ isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()});taskContext.increaseProgressCount();@@ -188,7 +185,7 @@ function importAttachment(taskContext: TaskContext, file: File, parentNote: BNotparentNote.saveAttachment({title: file.originalname,content: file.buffer,- role: 'file',+ role: "file",mime: mime});diff --git a/src/services/import/zip.ts b/src/services/import/zip.tsindex aa5a5822d3..8d5bb91052 100644--- a/src/services/import/zip.ts+++ b/src/services/import/zip.ts@@ -19,11 +19,11 @@ import TaskContext from "../task_context.js";import BNote from "../../becca/entities/bnote.js";import NoteMeta from "../meta/note_meta.js";import AttributeMeta from "../meta/attribute_meta.js";-import { Stream } from 'stream';-import { ALLOWED_NOTE_TYPES, NoteType } from '../../becca/entities/rows.js';+import { Stream } from "stream";+import { ALLOWED_NOTE_TYPES, NoteType } from "../../becca/entities/rows.js";interface MetaFile {- files: NoteMeta[]+ files: NoteMeta[];}async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRootNote: BNote): Promise<BNote> {@@ -34,7 +34,7 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRooconst attributes: AttributeMeta[] = [];// path => noteId, used only when meta file is not available/** path => noteId | attachmentId */- const createdPaths: Record<string, string> = { '/': importRootNote.noteId, '\\': importRootNote.noteId };+ const createdPaths: Record<string, string> = { "/": importRootNote.noteId, "\\": importRootNote.noteId };let metaFile: MetaFile | null = null;let firstNote: BNote | null = null;const createdNoteIds = new Set<string>();@@ -45,7 +45,7 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRooreturn "empty_note_id";}- if (origNoteId === 'root' || origNoteId.startsWith("_")) {+ if (origNoteId === "root" || origNoteId.startsWith("_")) {// these "named" noteIds don't differ between Trilium instancesreturn origNoteId;}@@ -108,7 +108,7 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRooparent = cursor;if (parent.children) {- cursor = parent.children.find(file => file.dataFileName === segment || file.dirFileName === segment);+ cursor = parent.children.find((file) => file.dataFileName === segment || file.dirFileName === segment);}if (!cursor) {@@ -128,11 +128,10 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRooif (parentNoteMeta?.noteId) {parentNoteId = parentNoteMeta.isImportRoot ? importRootNote.noteId : getNewNoteId(parentNoteMeta.noteId);- }- else {+ } else {const parentPath = path.dirname(filePath);- if (parentPath === '.') {+ if (parentPath === ".") {parentNoteId = importRootNote.noteId;} else if (parentPath in createdPaths) {parentNoteId = createdPaths[parentPath];@@ -180,12 +179,11 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRoofor (const attr of noteMeta.attributes || []) {attr.noteId = note.noteId;- if (attr.type === 'label-definition') {- attr.type = 'label';+ if (attr.type === "label-definition") {+ attr.type = "label";attr.name = `label:${attr.name}`;- }- else if (attr.type === 'relation-definition') {- attr.type = 'label';+ } else if (attr.type === "relation-definition") {+ attr.type = "label";attr.name = `relation:${attr.name}`;}@@ -194,12 +192,12 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRoocontinue;}- if (attr.type === 'relation' && ['internalLink', 'imageLink', 'relationMapLink', 'includeNoteLink'].includes(attr.name)) {+ if (attr.type === "relation" && ["internalLink", "imageLink", "relationMapLink", "includeNoteLink"].includes(attr.name)) {// these relations are created automatically and as such don't need to be duplicated in the importcontinue;}- if (attr.type === 'relation') {+ if (attr.type === "relation") {attr.value = getNewNoteId(attr.value);}@@ -232,17 +230,17 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRoothrow new Error("Missing parent note ID.");}- const {note} = noteService.createNewNote({+ const { note } = noteService.createNewNote({parentNoteId: parentNoteId,title: noteTitle || "",- content: '',+ content: "",noteId: noteId,type: resolveNoteType(noteMeta?.type),- mime: noteMeta ? noteMeta.mime : 'text/html',- prefix: noteMeta?.prefix || '',+ mime: noteMeta ? noteMeta.mime : "text/html",+ prefix: noteMeta?.prefix || "",isExpanded: !!noteMeta?.isExpanded,- notePosition: (noteMeta && firstNote) ? noteMeta.notePosition : undefined,- isProtected: importRootNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),+ notePosition: noteMeta && firstNote ? noteMeta.notePosition : undefined,+ isProtected: importRootNote.isProtected && protectedSessionService.isProtectedSessionAvailable()});createdNoteIds.add(note.noteId);@@ -267,11 +265,11 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRoourl = url.substr(3);}- if (absUrl === '.') {- absUrl = '';+ if (absUrl === ".") {+ absUrl = "";}- absUrl += `${absUrl.length > 0 ? '/' : ''}${url}`;+ absUrl += `${absUrl.length > 0 ? "/" : ""}${url}`;const { noteMeta, attachmentMeta } = getMeta(absUrl);@@ -280,7 +278,8 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRooattachmentId: getNewAttachmentId(attachmentMeta.attachmentId),noteId: getNewNoteId(noteMeta.noteId)};- } else { // don't check for noteMeta since it's not mandatory for notes+ } else {+ // don't check for noteMeta since it's not mandatory for notesreturn {noteId: getNoteId(noteMeta, absUrl)};@@ -345,8 +344,10 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRooreturn `href="${url}"`;}- if (url.startsWith('#') // already a note path (probably)- || isUrlAbsolute(url)) {+ if (+ url.startsWith("#") || // already a note path (probably)+ isUrlAbsolute(url)+ ) {return match;}@@ -362,8 +363,7 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRoo});if (noteMeta) {- const includeNoteLinks = (noteMeta.attributes || [])- .filter(attr => attr.type === 'relation' && attr.name === 'includeNoteLink');+ const includeNoteLinks = (noteMeta.attributes || []).filter((attr) => attr.type === "relation" && attr.name === "includeNoteLink");for (const link of includeNoteLinks) {// no need to escape the regexp find string since it's a noteId which doesn't contain any special characters@@ -377,31 +377,25 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRoo}function removeTriliumTags(content: string) {- const tagsToRemove = [- '<h1 data-trilium-h1>([^<]*)<\/h1>',- '<title data-trilium-title>([^<]*)<\/title>'- ]+ const tagsToRemove = ["<h1 data-trilium-h1>([^<]*)<\/h1>", "<title data-trilium-title>([^<]*)<\/title>"];for (const tag of tagsToRemove) {let re = new RegExp(tag, "gi");- content = content.replace(re, '');+ content = content.replace(re, "");}return content;}function processNoteContent(noteMeta: NoteMeta | undefined, type: string, mime: string, content: string | Buffer, noteTitle: string, filePath: string) {- if ((noteMeta?.format === 'markdown'- || (!noteMeta && taskContext.data?.textImportedAsText && ['text/markdown', 'text/x-markdown'].includes(mime)))- && typeof content === "string") {+ if ((noteMeta?.format === "markdown" || (!noteMeta && taskContext.data?.textImportedAsText && ["text/markdown", "text/x-markdown"].includes(mime))) && typeof content === "string") {content = markdownService.renderToHtml(content, noteTitle);}- if (type === 'text' && typeof content === "string") {+ if (type === "text" && typeof content === "string") {content = processTextNoteContent(content, noteTitle, filePath, noteMeta);}- if (type === 'relationMap' && noteMeta && typeof content === "string") {- const relationMapLinks = (noteMeta.attributes || [])- .filter(attr => attr.type === 'relation' && attr.name === 'relationMapLink');+ if (type === "relationMap" && noteMeta && typeof content === "string") {+ const relationMapLinks = (noteMeta.attributes || []).filter((attr) => attr.type === "relation" && attr.name === "relationMapLink");// this will replace relation map linksfor (const link of relationMapLinks) {@@ -462,7 +456,7 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRoothrow new Error("Unable to resolve mime type.");}- if (type !== 'file' && type !== 'image') {+ if (type !== "file" && type !== "image") {content = content.toString("utf-8");}@@ -496,21 +490,20 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRoonotePosition: noteMeta?.notePosition}).save();}- }- else {- ({note} = noteService.createNewNote({+ } else {+ ({ note } = noteService.createNewNote({parentNoteId: parentNoteId,title: noteTitle || "",content: content,noteId,type,mime,- prefix: noteMeta?.prefix || '',+ prefix: noteMeta?.prefix || "",isExpanded: !!noteMeta?.isExpanded,// root notePosition should be ignored since it relates to the original document// now import root should be placed after existing notes into new parent- notePosition: (noteMeta && firstNote) ? noteMeta.notePosition : undefined,- isProtected: isProtected,+ notePosition: noteMeta && firstNote ? noteMeta.notePosition : undefined,+ isProtected: isProtected}));createdNoteIds.add(note.noteId);@@ -520,11 +513,11 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRoofirstNote = firstNote || note;}- if (!noteMeta && (type === 'file' || type === 'image')) {+ if (!noteMeta && (type === "file" || type === "image")) {attributes.push({noteId,- type: 'label',- name: 'originalFileName',+ type: "label",+ name: "originalFileName",value: path.basename(filePath)});}@@ -535,7 +528,7 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRooawait readZipFile(fileBuffer, async (zipfile: yauzl.ZipFile, entry: yauzl.Entry) => {const filePath = normalizeFilePath(entry.fileName);- if (filePath === '!!!meta.json') {+ if (filePath === "!!!meta.json") {const content = await readContent(zipfile, entry);metaFile = JSON.parse(content.toString("utf-8"));@@ -549,8 +542,7 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRooif (/\/$/.test(entry.fileName)) {saveDirectory(filePath);- }- else if (filePath !== '!!!meta.json') {+ } else if (filePath !== "!!!meta.json") {const content = await readContent(zipfile, entry);saveNote(filePath, content);@@ -568,7 +560,7 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRooif (!metaFile) {// if there's no meta file, then the notes are created based on the order in that zip file but that// is usually quite random, so we sort the notes in the way they would appear in the file manager- treeService.sortNotes(noteId, 'title', false, true);+ treeService.sortNotes(noteId, "title", false, true);}taskContext.increaseProgressCount();@@ -577,10 +569,9 @@ async function importZip(taskContext: TaskContext, fileBuffer: Buffer, importRoo// we're saving attributes and links only now so that all relation and link target notes// are already in the database (we don't want to have "broken" relations, not even transitionally)for (const attr of attributes) {- if (attr.type !== 'relation' || attr.value in becca.notes) {+ if (attr.type !== "relation" || attr.value in becca.notes) {new BAttribute(attr).save();- }- else {+ } else {log.info(`Relation not imported since the target note doesn't exist: ${JSON.stringify(attr)}`);}}@@ -609,14 +600,14 @@ function normalizeFilePath(filePath: string): string {function streamToBuffer(stream: Stream): Promise<Buffer> {const chunks: Uint8Array[] = [];- stream.on('data', chunk => chunks.push(chunk));+ stream.on("data", (chunk) => chunks.push(chunk));- return new Promise((res, rej) => stream.on('end', () => res(Buffer.concat(chunks))));+ return new Promise((res, rej) => stream.on("end", () => res(Buffer.concat(chunks))));}function readContent(zipfile: yauzl.ZipFile, entry: yauzl.Entry): Promise<Buffer> {return new Promise((res, rej) => {- zipfile.openReadStream(entry, function(err, readStream) {+ zipfile.openReadStream(entry, function (err, readStream) {if (err) rej(err);if (!readStream) throw new Error("Unable to read content.");@@ -627,12 +618,12 @@ function readContent(zipfile: yauzl.ZipFile, entry: yauzl.Entry): Promise<Bufferfunction readZipFile(buffer: Buffer, processEntryCallback: (zipfile: yauzl.ZipFile, entry: yauzl.Entry) => void) {return new Promise((res, rej) => {- yauzl.fromBuffer(buffer, {lazyEntries: true, validateEntrySizes: false}, function(err, zipfile) {+ yauzl.fromBuffer(buffer, { lazyEntries: true, validateEntrySizes: false }, function (err, zipfile) {if (err) rej(err);if (!zipfile) throw new Error("Unable to read zip file.");zipfile.readEntry();- zipfile.on("entry", async entry => {+ zipfile.on("entry", async (entry) => {try {await processEntryCallback(zipfile, entry);} catch (e) {@@ -646,12 +637,12 @@ function readZipFile(buffer: Buffer, processEntryCallback: (zipfile: yauzl.ZipFifunction resolveNoteType(type: string | undefined): NoteType {// BC for ZIPs created in Triliun 0.57 and older- if (type === 'relation-map') {- return 'relationMap';- } else if (type === 'note-map') {- return 'noteMap';- } else if (type === 'web-view') {- return 'webView';+ if (type === "relation-map") {+ return "relationMap";+ } else if (type === "note-map") {+ return "noteMap";+ } else if (type === "web-view") {+ return "webView";}if (type && (ALLOWED_NOTE_TYPES as readonly string[]).includes(type)) {diff --git a/src/services/keyboard_actions.ts b/src/services/keyboard_actions.tsindex 90f77a3204..0bb3380467 100644--- a/src/services/keyboard_actions.ts+++ b/src/services/keyboard_actions.ts@@ -3,7 +3,7 @@import optionService from "./options.js";import log from "./log.js";import { isElectron as getIsElectron, isMac as getIsMac } from "./utils.js";-import { KeyboardShortcut } from './keyboard_actions_interface.js';+import { KeyboardShortcut } from "./keyboard_actions_interface.js";import { t } from "i18next";const isMac = getIsMac();@@ -77,7 +77,6 @@ function getDefaultKeyboardActions() {scope: "note-tree"},-{separator: t("keyboard_actions.creating-and-moving-notes")},@@ -197,7 +196,6 @@ function getDefaultKeyboardActions() {scope: "note-tree"},-{separator: t("keyboard_actions.tabs-and-windows")},@@ -304,7 +302,6 @@ function getDefaultKeyboardActions() {scope: "window"},-{separator: t("keyboard_actions.dialogs")},@@ -351,7 +348,6 @@ function getDefaultKeyboardActions() {scope: "window"},-{separator: t("keyboard_actions.text-note-operations")},@@ -602,13 +598,13 @@ function getDefaultKeyboardActions() {];/*- * Apply macOS-specific tweaks.- */- const platformModifier = isMac ? 'Meta' : 'Ctrl';+ * Apply macOS-specific tweaks.+ */+ const platformModifier = isMac ? "Meta" : "Ctrl";for (const action of DEFAULT_KEYBOARD_ACTIONS) {if (action.defaultShortcuts) {- action.defaultShortcuts = action.defaultShortcuts.map(shortcut => shortcut.replace("CommandOrControl", platformModifier));+ action.defaultShortcuts = action.defaultShortcuts.map((shortcut) => shortcut.replace("CommandOrControl", platformModifier));}}@@ -623,21 +619,19 @@ function getKeyboardActions() {}for (const option of optionService.getOptions()) {- if (option.name.startsWith('keyboardShortcuts')) {+ if (option.name.startsWith("keyboardShortcuts")) {let actionName = option.name.substring(17);actionName = actionName.charAt(0).toLowerCase() + actionName.slice(1);- const action = actions.find(ea => ea.actionName === actionName);+ const action = actions.find((ea) => ea.actionName === actionName);if (action) {try {action.effectiveShortcuts = JSON.parse(option.value);- }- catch (e) {+ } catch (e) {log.error(`Could not parse shortcuts for action ${actionName}`);}- }- else {+ } else {log.info(`Keyboard action ${actionName} found in database, but not in action definition.`);}}diff --git a/src/services/keyboard_actions_interface.ts b/src/services/keyboard_actions_interface.tsindex 9be3f94839..f0f032e6ac 100644--- a/src/services/keyboard_actions_interface.ts+++ b/src/services/keyboard_actions_interface.ts@@ -101,13 +101,13 @@ export interface KeyboardShortcut {defaultShortcuts?: string[];effectiveShortcuts?: string[];/**- * Scope here means on which element the keyboard shortcuts are attached - this means that for the shortcut to work,- * the focus has to be inside the element.- *- * So e.g. shortcuts with "note-tree" scope work only when the focus is in note tree.- * This allows to have the same shortcut have different actions attached based on the context- * e.g. CTRL-C in note tree does something a bit different from CTRL-C in the text editor.- */+ * Scope here means on which element the keyboard shortcuts are attached - this means that for the shortcut to work,+ * the focus has to be inside the element.+ *+ * So e.g. shortcuts with "note-tree" scope work only when the focus is in note tree.+ * This allows to have the same shortcut have different actions attached based on the context+ * e.g. CTRL-C in note tree does something a bit different from CTRL-C in the text editor.+ */scope?: "window" | "note-tree" | "text-detail" | "code-detail";}diff --git a/src/services/log.ts b/src/services/log.tsindex cb207e3a63..257f4f81b1 100644--- a/src/services/log.ts+++ b/src/services/log.ts@@ -17,7 +17,7 @@ const MINUTE = 60 * SECOND;const HOUR = 60 * MINUTE;const DAY = 24 * HOUR;-const NEW_LINE = isWindows() ? '\r\n' : '\n';+const NEW_LINE = isWindows() ? "\r\n" : "\n";let todaysMidnight!: Date;@@ -38,7 +38,7 @@ function initLogFile() {logFile.end();}- logFile = fs.createWriteStream(path, {flags: 'a'});+ logFile = fs.createWriteStream(path, { flags: "a" });}function checkDate(millisSinceMidnight: number) {@@ -75,7 +75,7 @@ function error(message: string | Error) {log(`ERROR: ${message}`);}-const requestBlacklist = [ "/libraries", "/app", "/images", "/stylesheets", "/api/recent-notes" ];+const requestBlacklist = ["/libraries", "/app", "/images", "/stylesheets", "/api/recent-notes"];function request(req: Request, res: Response, timeMs: number, responseLength: number | string = "?") {for (const bl of requestBlacklist) {@@ -88,24 +88,21 @@ function request(req: Request, res: Response, timeMs: number, responseLength: nureturn;}- info((timeMs >= 10 ? "Slow " : "") +- `${res.statusCode} ${req.method} ${req.url} with ${responseLength} bytes took ${timeMs}ms`);+ info((timeMs >= 10 ? "Slow " : "") + `${res.statusCode} ${req.method} ${req.url} with ${responseLength} bytes took ${timeMs}ms`);}function pad(num: number) {num = Math.floor(num);- return num < 10 ? (`0${num}`) : num.toString();+ return num < 10 ? `0${num}` : num.toString();}function padMilli(num: number) {if (num < 10) {return `00${num}`;- }- else if (num < 100) {+ } else if (num < 100) {return `0${num}`;- }- else {+ } else {return num.toString();}}diff --git a/src/services/migration.ts b/src/services/migration.tsindex b4db324104..08b07f121f 100644--- a/src/services/migration.ts+++ b/src/services/migration.ts@@ -27,9 +27,7 @@ async function migrate() {// backup before attempting migrationawait backupService.backupNow(// creating a special backup for version 0.60.4, the changes in 0.61 are major.- currentDbVersion === 214- ? `before-migration-v060`- : 'before-migration'+ currentDbVersion === 214 ? `before-migration-v060` : "before-migration");const migrationFiles = fs.readdirSync(resourceDir.MIGRATIONS_DIR);@@ -37,27 +35,29 @@ async function migrate() {return;}- const migrations = migrationFiles.map(file => {- const match = file.match(/^([0-9]{4})__([a-zA-Z0-9_ ]+)\.(sql|js)$/);- if (!match) {- return null;- }+ const migrations = migrationFiles+ .map((file) => {+ const match = file.match(/^([0-9]{4})__([a-zA-Z0-9_ ]+)\.(sql|js)$/);+ if (!match) {+ return null;+ }- const dbVersion = parseInt(match[1]);- if (dbVersion > currentDbVersion) {- const name = match[2];- const type = match[3];-- return {- dbVersion: dbVersion,- name: name,- file: file,- type: type- };- } else {- return null;- }- }).filter((el): el is MigrationInfo => !!el);+ const dbVersion = parseInt(match[1]);+ if (dbVersion > currentDbVersion) {+ const name = match[2];+ const type = match[3];++ return {+ dbVersion: dbVersion,+ name: name,+ file: file,+ type: type+ };+ } else {+ return null;+ }+ })+ .filter((el): el is MigrationInfo => !!el);migrations.sort((a, b) => a.dbVersion - b.dbVersion);@@ -74,9 +74,12 @@ async function migrate() {await executeMigration(mig);- sql.execute(`UPDATE options+ sql.execute(+ `UPDATE optionsSET value = ?- WHERE name = ?`, [mig.dbVersion.toString(), "dbVersion"]);+ WHERE name = ?`,+ [mig.dbVersion.toString(), "dbVersion"]+ );log.info(`Migration to version ${mig.dbVersion} has been successful.`);} catch (e: any) {@@ -97,13 +100,13 @@ async function migrate() {}async function executeMigration(mig: MigrationInfo) {- if (mig.type === 'sql') {- const migrationSql = fs.readFileSync(`${resourceDir.MIGRATIONS_DIR}/${mig.file}`).toString('utf8');+ if (mig.type === "sql") {+ const migrationSql = fs.readFileSync(`${resourceDir.MIGRATIONS_DIR}/${mig.file}`).toString("utf8");console.log(`Migration with SQL script: ${migrationSql}`);sql.executeScript(migrationSql);- } else if (mig.type === 'js') {+ } else if (mig.type === "js") {console.log("Migration with JS module");const migrationModule = await import(`${resourceDir.MIGRATIONS_DIR}/${mig.file}`);@@ -132,8 +135,10 @@ function isDbUpToDate() {async function migrateIfNecessary() {const currentDbVersion = getDbVersion();- if (currentDbVersion > appInfo.dbVersion && process.env.TRILIUM_IGNORE_DB_VERSION !== 'true') {- log.error(`Current DB version ${currentDbVersion} is newer than the current DB version ${appInfo.dbVersion}, which means that it was created by a newer and incompatible version of Trilium. Upgrade to the latest version of Trilium to resolve this issue.`);+ if (currentDbVersion > appInfo.dbVersion && process.env.TRILIUM_IGNORE_DB_VERSION !== "true") {+ log.error(+ `Current DB version ${currentDbVersion} is newer than the current DB version ${appInfo.dbVersion}, which means that it was created by a newer and incompatible version of Trilium. Upgrade to the latest version of Trilium to resolve this issue.`+ );await crash();}diff --git a/src/services/note_types.ts b/src/services/note_types.tsindex 62121b12cb..4a810b6a2c 100644--- a/src/services/note_types.ts+++ b/src/services/note_types.ts@@ -1,24 +1,24 @@const noteTypes = [- { type: 'text', defaultMime: 'text/html' },- { type: 'code', defaultMime: 'text/plain' },- { type: 'render', defaultMime: '' },- { type: 'file', defaultMime: 'application/octet-stream' },- { type: 'image', defaultMime: '' },- { type: 'search', defaultMime: '' },- { type: 'relationMap', defaultMime: 'application/json' },- { type: 'book', defaultMime: '' },- { type: 'noteMap', defaultMime: '' },- { type: 'mermaid', defaultMime: 'text/plain' },- { type: 'canvas', defaultMime: 'application/json' },- { type: 'webView', defaultMime: '' },- { type: 'launcher', defaultMime: '' },- { type: 'doc', defaultMime: '' },- { type: 'contentWidget', defaultMime: '' },- { type: 'mindMap', defaultMime: 'application/json' }+ { type: "text", defaultMime: "text/html" },+ { type: "code", defaultMime: "text/plain" },+ { type: "render", defaultMime: "" },+ { type: "file", defaultMime: "application/octet-stream" },+ { type: "image", defaultMime: "" },+ { type: "search", defaultMime: "" },+ { type: "relationMap", defaultMime: "application/json" },+ { type: "book", defaultMime: "" },+ { type: "noteMap", defaultMime: "" },+ { type: "mermaid", defaultMime: "text/plain" },+ { type: "canvas", defaultMime: "application/json" },+ { type: "webView", defaultMime: "" },+ { type: "launcher", defaultMime: "" },+ { type: "doc", defaultMime: "" },+ { type: "contentWidget", defaultMime: "" },+ { type: "mindMap", defaultMime: "application/json" }];function getDefaultMimeForNoteType(typeName: string) {- const typeRec = noteTypes.find(nt => nt.type === typeName);+ const typeRec = noteTypes.find((nt) => nt.type === typeName);if (!typeRec) {throw new Error(`Cannot find note type '${typeName}'`);@@ -28,6 +28,6 @@ function getDefaultMimeForNoteType(typeName: string) {}export default {- getNoteTypeNames: () => noteTypes.map(nt => nt.type),+ getNoteTypeNames: () => noteTypes.map((nt) => nt.type),getDefaultMimeForNoteType};diff --git a/src/services/notes.ts b/src/services/notes.tsindex 193dde4d6a..9582b72812 100644--- a/src/services/notes.ts+++ b/src/services/notes.ts@@ -23,15 +23,15 @@ import noteTypesService from "./note_types.js";import fs from "fs";import ws from "./ws.js";import html2plaintext from "html2plaintext";-import { AttachmentRow, AttributeRow, BranchRow, NoteRow, NoteType } from '../becca/entities/rows.js';+import { AttachmentRow, AttributeRow, BranchRow, NoteRow, NoteType } from "../becca/entities/rows.js";import TaskContext from "./task_context.js";-import { NoteParams } from './note-interface.js';+import { NoteParams } from "./note-interface.js";import imageService from "./image.js";import { t } from "i18next";interface FoundLink {- name: "imageLink" | "internalLink" | "includeNoteLink" | "relationMapLink",- value: string+ name: "imageLink" | "internalLink" | "includeNoteLink" | "relationMapLink";+ value: string;}interface Attachment {@@ -40,15 +40,17 @@ interface Attachment {}function getNewNotePosition(parentNote: BNote) {- if (parentNote.isLabelTruthy('newNotesOnTop')) {- const minNotePos = parentNote.getChildBranches()- .filter(branch => branch?.noteId !== '_hidden') // has "always last" note position+ 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;} else {- const maxNotePos = parentNote.getChildBranches()- .filter(branch => branch?.noteId !== '_hidden') // has "always last" note position+ 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;@@ -75,9 +77,9 @@ function copyChildAttributes(parentNote: BNote, childNote: BNote) {for (const attr of parentNote.getAttributes()) {if (attr.name.startsWith("child:")) {const name = attr.name.substr(6);- const hasAlreadyTemplate = childNote.hasRelation('template');+ const hasAlreadyTemplate = childNote.hasRelation("template");- if (hasAlreadyTemplate && attr.type === 'relation' && name === '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: attrscontinue;@@ -98,7 +100,7 @@ function copyChildAttributes(parentNote: BNote, childNote: BNote) {function getNewNoteTitle(parentNote: BNote) {let title = t("notes.new-note");- const titleTemplate = parentNote.getLabelValue('titleTemplate');+ const titleTemplate = parentNote.getLabelValue("titleTemplate");if (titleTemplate !== null) {try {@@ -135,19 +137,16 @@ function getAndValidateParent(params: GetValidateParams) {throw new ValidationError(`Parent note '${params.parentNoteId}' was not found.`);}- if (parentNote.type === 'launcher' && parentNote.noteId !== '_lbBookmarks') {+ 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') {+ 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.isOptions()) {-+ if (["_lbRoot", "_hidden"].includes(parentNote.noteId) || parentNote.noteId.startsWith("_lbTpl") || parentNote.isOptions()) {throw new ValidationError(`Creating child notes into '${parentNote.noteId}' is not allowed.`);}}@@ -170,11 +169,11 @@ function createNewNote(params: NoteParams): {}let error;- if (error = dateUtils.validateLocalDateTime(params.dateCreated)) {+ if ((error = dateUtils.validateLocalDateTime(params.dateCreated))) {throw new Error(error);}- if (error = dateUtils.validateUtcDateTime(params.utcDateCreated)) {+ if ((error = dateUtils.validateUtcDateTime(params.utcDateCreated))) {throw new Error(error);}@@ -212,8 +211,7 @@ function createNewNote(params: NoteParams): {prefix: params.prefix || "",isExpanded: !!params.isExpanded}).save();- }- finally {+ } finally {if (!isEntityEventsDisabled) {// re-enable entity events only if they were previously enabled// (they can be disabled in case of import)@@ -228,20 +226,20 @@ function createNewNote(params: NoteParams): {throw new Error(`Template note '${params.templateNoteId}' does not exist.`);}- note.addRelation('template', params.templateNoteId);+ note.addRelation("template", params.templateNoteId);// 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 });+ 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.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: parentNote });log.info(`Created new note '${note.noteId}', branch '${branch.branchId}' of type '${note.type}', mime '${note.mime}'`);@@ -253,24 +251,22 @@ function createNewNote(params: NoteParams): {});}-function createNewNoteWithTarget(target: ("into" | "after"), targetBranchId: string | undefined, params: NoteParams) {+function createNewNoteWithTarget(target: "into" | "after", 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';+ params.type = parentNote.type === "code" ? "code" : "text";+ params.mime = parentNote.type === "code" ? parentNote.mime : "text/html";}- if (target === 'into') {+ if (target === "into") {return createNewNote(params);- }- else if (target === 'after' && targetBranchId) {+ } else if (target === "after" && targetBranchId) {const afterBranch = becca.branches[targetBranchId];// not updating utcDateModified to avoid having to sync whole rows- sql.execute('UPDATE branches SET notePosition = notePosition + 10 WHERE parentNoteId = ? AND notePosition > ? AND isDeleted = 0',- [params.parentNoteId, afterBranch.notePosition]);+ sql.execute("UPDATE branches SET notePosition = notePosition + 10 WHERE parentNoteId = ? AND notePosition > ? AND isDeleted = 0", [params.parentNoteId, afterBranch.notePosition]);params.notePosition = afterBranch.notePosition + 10;@@ -279,8 +275,7 @@ function createNewNoteWithTarget(target: ("into" | "after"), targetBranchId: strentityChangesService.putNoteReorderingEntityChange(params.parentNoteId);return retObject;- }- else {+ } else {throw new Error(`Unknown target '${target}'`);}}@@ -318,17 +313,15 @@ function protectNote(note: BNote, protect: boolean) {const content = attachment.getContent();attachment.isProtected = protect;- attachment.setContent(content, {forceSave: true});- }- catch (e) {+ attachment.setContent(content, { forceSave: true });+ } catch (e) {log.error(`Could not un/protect attachment '${attachment.attachmentId}'`);throw e;}}}- }- catch (e) {+ } catch (e) {log.error(`Could not un/protect note '${note.noteId}'`);throw e;@@ -340,12 +333,12 @@ function checkImageAttachments(note: BNote, content: string) {let match;const imgRegExp = /src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g;- while (match = imgRegExp.exec(content)) {+ while ((match = imgRegExp.exec(content))) {foundAttachmentIds.add(match[1]);}const linkRegExp = /href="[^"]+attachmentId=([a-zA-Z0-9_]+)/g;- while (match = linkRegExp.exec(content)) {+ while ((match = linkRegExp.exec(content))) {foundAttachmentIds.add(match[1]);}@@ -363,14 +356,14 @@ function checkImageAttachments(note: BNote, content: string) {}}- const existingAttachmentIds = new Set<string | undefined>(attachments.map(att => att.attachmentId));- const unknownAttachmentIds = Array.from(foundAttachmentIds).filter(foundAttId => !existingAttachmentIds.has(foundAttId));+ 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);+ let localAttachment = note.getAttachments().find((att) => att.role === unknownAttachment.role && att.blobId === unknownAttachment.blobId);if (localAttachment) {if (localAttachment.utcDateScheduledForErasureSince) {@@ -379,21 +372,25 @@ function checkImageAttachments(note: BNote, content: string) {localAttachment.save();}- log.info(`Found equivalent attachment '${localAttachment.attachmentId}' of note '${note.noteId}' for the linked foreign attachment '${unknownAttachment.attachmentId}' of note '${unknownAttachment.ownerId}'`);+ log.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});+ localAttachment.setContent(unknownAttachment.getContent(), { forceSave: true });- ws.sendMessageToAllClients({ type: 'toast', message: `Attachment '${localAttachment.title}' has been copied to note '${note.title}'.`});+ ws.sendMessageToAllClients({ type: "toast", message: `Attachment '${localAttachment.title}' has been copied to note '${note.title}'.` });log.info(`Copied attachment '${unknownAttachment.attachmentId}' of note '${unknownAttachment.ownerId}' to new '${localAttachment.attachmentId}' of note '${note.noteId}'`);}// replace image linkscontent = 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&attachmentId=${localAttachment.attachmentId}"`);+ content = content.replace(+ new RegExp(`href="[^"]+attachmentId=${unknownAttachment.attachmentId}[^"]*"`, "g"),+ `href="#root/${localAttachment.ownerId}?viewMode=attachments&attachmentId=${localAttachment.attachmentId}"`+ );}return {@@ -406,9 +403,9 @@ function findImageLinks(content: string, foundLinks: FoundLink[]) {const re = /src="[^"]*api\/images\/([a-zA-Z0-9_]+)\//g;let match;- while (match = re.exec(content)) {+ while ((match = re.exec(content))) {foundLinks.push({- name: 'imageLink',+ name: "imageLink",value: match[1]});}@@ -422,9 +419,9 @@ 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)) {+ while ((match = re.exec(content))) {foundLinks.push({- name: 'internalLink',+ name: "internalLink",value: match[1]});}@@ -437,9 +434,9 @@ 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)) {+ while ((match = re.exec(content))) {foundLinks.push({- name: 'includeNoteLink',+ name: "includeNoteLink",value: match[1]});}@@ -453,7 +450,7 @@ function findRelationMapLinks(content: string, foundLinks: FoundLink[]) {for (const note of obj.notes) {foundLinks.push({- name: 'relationMapLink',+ name: "relationMapLink",value: note.noteId});}@@ -498,8 +495,7 @@ async function downloadImage(noteId: string, imageUrl: string) {}log.info(`Download of '${imageUrl}' succeeded and was saved as image attachment '${attachment.attachmentId}' of note '${noteId}'`);- }- catch (e: any) {+ } catch (e: any) {log.error(`Download of '${imageUrl}' for note '${noteId}' failed with error: ${e.message} ${e.stack}`);}}@@ -514,27 +510,28 @@ function replaceUrl(content: string, url: string, attachment: Attachment) {}function downloadImages(noteId: string, content: string) {- const imageRe = /<img[^>]*?\ssrc=['"]([^'">]+)['"]/ig;+ const imageRe = /<img[^>]*?\ssrc=['"]([^'">]+)['"]/gi;let imageMatch;- while (imageMatch = imageRe.exec(content)) {+ while ((imageMatch = imageRe.exec(content))) {const url = imageMatch[1];const inlineImageMatch = /^data:image\/[a-z]+;base64,/.exec(url);if (inlineImageMatch) {const imageBase64 = url.substr(inlineImageMatch[0].length);- const imageBuffer = Buffer.from(imageBase64, 'base64');+ const imageBuffer = Buffer.from(imageBase64, "base64");const attachment = imageService.saveImageToAttachment(noteId, imageBuffer, "inline image", true, true);const encodedTitle = encodeURIComponent(attachment.title);content = `${content.substr(0, imageMatch.index)}<img src="api/attachments/${attachment.attachmentId}/image/${encodedTitle}"${content.substr(imageMatch.index + imageMatch[0].length)}`;- }- else if (!url.includes('api/images/') && !/api\/attachments\/.+\/image\/?.*/.test(url)+ } 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'))) {-+ (url.length !== 20 || url.toLowerCase().startsWith("http"))+ ) {if (!optionService.getOptionBool("downloadImagesAutomatically")) {continue;}@@ -544,8 +541,7 @@ function downloadImages(noteId: string, content: string) {if (!attachment) {delete imageUrlToAttachmentIdMapping[url];- }- else {+ } else {content = replaceUrl(content, url, attachment);continue;}@@ -591,7 +587,7 @@ function downloadImages(noteId: string, content: string) {}for (const url in imageUrlToAttachmentIdMapping) {- const imageNote = imageNotes.find(note => note.noteId === imageUrlToAttachmentIdMapping[url]);+ const imageNote = imageNotes.find((note) => note.noteId === imageUrlToAttachmentIdMapping[url]);if (imageNote) {updatedContent = replaceUrl(updatedContent, url, imageNote);@@ -614,19 +610,19 @@ function downloadImages(noteId: string, content: string) {}function saveAttachments(note: BNote, content: string) {- const inlineAttachmentRe = /<a[^>]*?\shref=['"]data:([^;'">]+);base64,([^'">]+)['"][^>]*>(.*?)<\/a>/igm;+ const inlineAttachmentRe = /<a[^>]*?\shref=['"]data:([^;'">]+);base64,([^'">]+)['"][^>]*>(.*?)<\/a>/gim;let attachmentMatch;- while (attachmentMatch = inlineAttachmentRe.exec(content)) {+ while ((attachmentMatch = inlineAttachmentRe.exec(content))) {const mime = attachmentMatch[1].toLowerCase();const base64data = attachmentMatch[2];- const buffer = Buffer.from(base64data, 'base64');+ const buffer = Buffer.from(base64data, "base64");const title = html2plaintext(attachmentMatch[3]);const attachment = note.saveAttachment({- role: 'file',+ role: "file",mime: mime,title: title,content: buffer@@ -643,8 +639,7 @@ function saveAttachments(note: BNote, content: string) {}function saveLinks(note: BNote, content: string | Buffer) {- if ((note.type !== 'text' && note.type !== 'relationMap')- || (note.isProtected && !protectedSessionService.isProtectedSessionAvailable())) {+ if ((note.type !== "text" && note.type !== "relationMap") || (note.isProtected && !protectedSessionService.isProtectedSessionAvailable())) {return {forceFrontendReload: false,content@@ -654,7 +649,7 @@ function saveLinks(note: BNote, content: string | Buffer) {const foundLinks: FoundLink[] = [];let forceFrontendReload = false;- if (note.type === 'text' && typeof content === "string") {+ if (note.type === "text" && typeof content === "string") {content = downloadImages(note.noteId, content);content = saveAttachments(note, content);@@ -662,17 +657,14 @@ function saveLinks(note: BNote, content: string | Buffer) {content = findInternalLinks(content, foundLinks);content = findIncludeNoteLinks(content, foundLinks);- ({forceFrontendReload, content} = checkImageAttachments(note, content));- }- else if (note.type === 'relationMap' && typeof content === "string") {+ ({ forceFrontendReload, content } = checkImageAttachments(note, content));+ } else if (note.type === "relationMap" && typeof content === "string") {findRelationMapLinks(content, foundLinks);- }- else {+ } else {throw new Error(`Unrecognized type '${note.type}'`);}- const existingLinks = note.getRelations().filter(rel =>- ['internalLink', 'imageLink', 'relationMapLink', 'includeNoteLink'].includes(rel.name));+ const existingLinks = note.getRelations().filter((rel) => ["internalLink", "imageLink", "relationMapLink", "includeNoteLink"].includes(rel.name));for (const foundLink of foundLinks) {const targetNote = becca.notes[foundLink.value];@@ -680,16 +672,14 @@ function saveLinks(note: BNote, content: string | Buffer) {continue;}- const existingLink = existingLinks.find(existingLink =>- existingLink.value === foundLink.value- && existingLink.name === foundLink.name);+ const existingLink = existingLinks.find((existingLink) => existingLink.value === foundLink.value && existingLink.name === foundLink.name);if (!existingLink) {const newLink = new BAttribute({noteId: note.noteId,- type: 'relation',+ type: "relation",name: foundLink.name,- value: foundLink.value,+ value: foundLink.value}).save();existingLinks.push(newLink);@@ -698,9 +688,7 @@ function saveLinks(note: BNote, content: string | Buffer) {}// 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));+ const unusedLinks = existingLinks.filter((existingLink) => !foundLinks.some((foundLink) => existingLink.value === foundLink.value && existingLink.name === foundLink.name));for (const unusedLink of unusedLinks) {unusedLink.markAsDeleted();@@ -711,17 +699,16 @@ function saveLinks(note: BNote, content: string | Buffer) {function saveRevisionIfNeeded(note: BNote) {// files and images are versioned separately- if (note.type === 'file' || note.type === 'image' || note.isLabelTruthy('disableVersioning')) {+ if (note.type === "file" || note.type === "image" || note.isLabelTruthy("disableVersioning")) {return;}const now = new Date();- const revisionSnapshotTimeInterval = parseInt(optionService.getOption('revisionSnapshotTimeInterval'));+ const revisionSnapshotTimeInterval = parseInt(optionService.getOption("revisionSnapshotTimeInterval"));const revisionCutoff = dateUtils.utcDateTimeStr(new Date(now.getTime() - revisionSnapshotTimeInterval * 1000));- const existingRevisionId = sql.getValue(- "SELECT revisionId FROM revisions WHERE noteId = ? AND utcDateCreated >= ?", [note.noteId, revisionCutoff]);+ const existingRevisionId = sql.getValue("SELECT revisionId FROM revisions WHERE noteId = ? AND utcDateCreated >= ?", [note.noteId, revisionCutoff]);const msSinceDateCreated = now.getTime() - dateUtils.parseDateTime(note.utcDateCreated).getTime();@@ -744,18 +731,18 @@ function updateNoteData(noteId: string, content: string, attachments: Attachmentnote.setContent(newContent, { forceFrontendReload });if (attachments?.length > 0) {- const existingAttachmentsByTitle = toMap(note.getAttachments({includeContentLength: false}), 'title');+ const existingAttachmentsByTitle = toMap(note.getAttachments({ includeContentLength: false }), "title");- for (const {attachmentId, role, mime, title, position, content} of attachments) {+ for (const { attachmentId, role, mime, title, position, content } of attachments) {if (attachmentId || !(title in existingAttachmentsByTitle)) {- note.saveAttachment({attachmentId, role, mime, title, content, position});+ note.saveAttachment({ attachmentId, role, mime, title, content, position });} else {const existingAttachment = existingAttachmentsByTitle[title];existingAttachment.role = role;existingAttachment.mime = mime;existingAttachment.position = position;if (content) {- existingAttachment.setContent(content, {forceSave: true});+ existingAttachment.setContent(content, { forceSave: true });}}}@@ -783,7 +770,7 @@ function undeleteNote(noteId: string, taskContext: TaskContext) {}function undeleteBranch(branchId: string, deleteId: string, taskContext: TaskContext) {- const branchRow = sql.getRow<BranchRow>("SELECT * FROM branches WHERE branchId = ?", [branchId])+ const branchRow = sql.getRow<BranchRow>("SELECT * FROM branches WHERE branchId = ?", [branchId]);if (!branchRow.isDeleted) {return;@@ -809,34 +796,43 @@ function undeleteBranch(branchId: string, deleteId: string, taskContext: TaskConnoteEntity.updateFromRow(noteRow);noteEntity.save();- const attributeRows = sql.getRows<AttributeRow>(`+ const attributeRows = sql.getRows<AttributeRow>(+ `SELECT * FROM attributesWHERE isDeleted = 1AND deleteId = ?AND (noteId = ?- OR (type = 'relation' AND value = ?))`, [deleteId, noteRow.noteId, noteRow.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});+ new BAttribute(attributeRow).save({ skipValidation: true });}- const attachmentRows = sql.getRows<AttachmentRow>(`+ const attachmentRows = sql.getRows<AttachmentRow>(+ `SELECT * FROM attachmentsWHERE isDeleted = 1AND deleteId = ?- AND ownerId = ?`, [deleteId, noteRow.noteId]);+ AND ownerId = ?`,+ [deleteId, noteRow.noteId]+ );for (const attachmentRow of attachmentRows) {new BAttachment(attachmentRow).save();}- const childBranchIds = sql.getColumn<string>(`+ const childBranchIds = sql.getColumn<string>(+ `SELECT branches.branchIdFROM branchesWHERE branches.isDeleted = 1AND branches.deleteId = ?- AND branches.parentNoteId = ?`, [deleteId, noteRow.noteId]);+ AND branches.parentNoteId = ?`,+ [deleteId, noteRow.noteId]+ );for (const childBranchId of childBranchIds) {undeleteBranch(childBranchId, deleteId, taskContext);@@ -848,18 +844,21 @@ function undeleteBranch(branchId: string, deleteId: string, taskContext: TaskCon* @returns return deleted branchIds of an undeleted parent note*/function getUndeletedParentBranchIds(noteId: string, deleteId: string) {- return sql.getColumn<string>(`+ return sql.getColumn<string>(+ `SELECT branches.branchIdFROM branchesJOIN notes AS parentNote ON parentNote.noteId = branches.parentNoteIdWHERE branches.noteId = ?AND branches.isDeleted = 1AND branches.deleteId = ?- AND parentNote.isDeleted = 0`, [noteId, deleteId]);+ AND parentNote.isDeleted = 0`,+ [noteId, deleteId]+ );}function scanForLinks(note: BNote, content: string | Buffer) {- if (!note || !['text', 'relationMap'].includes(note.type)) {+ if (!note || !["text", "relationMap"].includes(note.type)) {return;}@@ -871,8 +870,7 @@ function scanForLinks(note: BNote, content: string | Buffer) {note.setContent(newContent, { forceFrontendReload });}});- }- catch (e: any) {+ } catch (e: any) {log.error(`Could not scan for links note '${note.noteId}': ${e.message} ${e.stack}`);}}@@ -899,21 +897,21 @@ function replaceByMap(str: string, mapObj: Record<string, string>) {return str;}- const re = new RegExp(Object.keys(mapObj).join("|"),"g");+ const re = new RegExp(Object.keys(mapObj).join("|"), "g");- return str.replace(re, matched => mapObj[matched]);+ return str.replace(re, (matched) => mapObj[matched]);}function duplicateSubtree(origNoteId: string, newParentNoteId: string) {- if (origNoteId === 'root') {- throw new Error('Duplicating root is not possible');+ if (origNoteId === "root") {+ throw new Error("Duplicating root is not possible");}log.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 origBranch = origNote.getParentBranches().find((branch) => branch.parentNoteId === newParentNoteId);const noteIdMapping = getNoteIdMapping(origNote);@@ -935,8 +933,8 @@ function duplicateSubtree(origNoteId: string, newParentNoteId: string) {}function duplicateSubtreeWithoutRoot(origNoteId: string, newNoteId: string) {- if (origNoteId === 'root') {- throw new Error('Duplicating root is not possible');+ if (origNoteId === "root") {+ throw new Error("Duplicating root is not possible");}const origNote = becca.getNote(origNoteId);@@ -978,7 +976,7 @@ function duplicateSubtreeInner(origNote: BNote, origBranch: BBranch, newParentNolet content = origNote.getContent();- if (typeof content === "string" && ['text', 'relationMap', 'search'].includes(origNote.type)) {+ if (typeof content === "string" && ["text", "relationMap", "search"].includes(origNote.type)) {// fix links in the contentcontent = replaceByMap(content, noteIdMapping);}@@ -994,12 +992,12 @@ function duplicateSubtreeInner(origNote: BNote, origBranch: BBranch, newParentNo// 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) {+ 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});+ attr.save({ skipValidation: true });}for (const childBranch of origNote.getChildBranches()) {@@ -1013,20 +1011,20 @@ function duplicateSubtreeInner(origNote: BNote, origBranch: BBranch, newParentNoconst existingNote = becca.notes[newNoteId];- if (existingNote && existingNote.title !== undefined) { // checking that it's not just note's skeleton created because of Branch above+ 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 clonereturn {note: existingNote,branch: createDuplicatedBranch()- }- }- else {+ };+ } else {return {// order here is important, note needs to be created first to not mess up the beccanote: createDuplicatedNote(),branch: createDuplicatedBranch()- }+ };}}diff --git a/src/services/options.ts b/src/services/options.tsindex bcecc6c9e7..980a730a6c 100644--- a/src/services/options.ts+++ b/src/services/options.ts@@ -14,7 +14,7 @@import becca from "../becca/becca.js";import BOption from "../becca/entities/boption.js";-import { OptionRow } from '../becca/entities/rows.js';+import { OptionRow } from "../becca/entities/rows.js";import { FilterOptionsByType, OptionDefinitions, OptionMap, OptionNames } from "./options_interface.js";import sql from "./sql.js";@@ -60,11 +60,11 @@ function getOptionInt(name: FilterOptionsByType<number>, defaultValue?: number):function getOptionBool(name: FilterOptionsByType<boolean>): boolean {const val = getOption(name);- if (typeof val !== "string" || !['true', 'false'].includes(val)) {+ if (typeof val !== "string" || !["true", "false"].includes(val)) {throw new Error(`Could not parse '${val}' into boolean for option '${name}'`);}- return val === 'true';+ return val === "true";}function setOption<T extends OptionNames>(name: T, value: string | OptionDefinitions[T]) {@@ -74,8 +74,7 @@ function setOption<T extends OptionNames>(name: T, value: string | OptionDefinitoption.value = value as string;option.save();- }- else {+ } else {createOption(name, value, false);}}diff --git a/src/services/options_init.ts b/src/services/options_init.tsindex a87c2cb59c..b7d3fdf8e2 100644--- a/src/services/options_init.ts+++ b/src/services/options_init.ts@@ -5,11 +5,11 @@ import { randomSecureToken, isWindows } from "./utils.js";import log from "./log.js";import dateUtils from "./date_utils.js";import keyboardActions from "./keyboard_actions.js";-import { KeyboardShortcutWithRequiredActionName } from './keyboard_actions_interface.js';+import { KeyboardShortcutWithRequiredActionName } from "./keyboard_actions_interface.js";function initDocumentOptions() {- optionService.createOption('documentId', randomSecureToken(16), false);- optionService.createOption('documentSecret', randomSecureToken(16), false);+ optionService.createOption("documentId", randomSecureToken(16), false);+ optionService.createOption("documentSecret", randomSecureToken(16), false);}/**@@ -26,10 +26,10 @@ interface NotSyncedOpts {interface DefaultOption {name: OptionNames;/**- * The value to initialize the option with, if the option is not already present in the database.- *- * If a function is passed Gin instead, the function is called if the option does not exist (with access to the current options) and the return value is used instead. Useful to migrate a new option with a value depending on some other option that might be initialized.- */+ * The value to initialize the option with, if the option is not already present in the database.+ *+ * If a function is passed Gin instead, the function is called if the option does not exist (with access to the current options) and the return value is used instead. Useful to migrate a new option with a value depending on some other option that might be initialized.+ */value: string | ((options: OptionMap) => string);isSynced: boolean;}@@ -41,95 +41,107 @@ interface DefaultOption {* @param opts additional options to be initialized, for example the sync configuration.*/async function initNotSyncedOptions(initialized: boolean, opts: NotSyncedOpts = {}) {- optionService.createOption('openNoteContexts', JSON.stringify([- {- notePath: 'root',- active: true- }- ]), false);+ optionService.createOption(+ "openNoteContexts",+ JSON.stringify([+ {+ notePath: "root",+ active: true+ }+ ]),+ false+ );- optionService.createOption('lastDailyBackupDate', dateUtils.utcNowDateTime(), false);- optionService.createOption('lastWeeklyBackupDate', dateUtils.utcNowDateTime(), false);- optionService.createOption('lastMonthlyBackupDate', dateUtils.utcNowDateTime(), false);- optionService.createOption('dbVersion', appInfo.dbVersion.toString(), false);+ optionService.createOption("lastDailyBackupDate", dateUtils.utcNowDateTime(), false);+ optionService.createOption("lastWeeklyBackupDate", dateUtils.utcNowDateTime(), false);+ optionService.createOption("lastMonthlyBackupDate", dateUtils.utcNowDateTime(), false);+ optionService.createOption("dbVersion", appInfo.dbVersion.toString(), false);- optionService.createOption('initialized', initialized ? 'true' : 'false', false);+ optionService.createOption("initialized", initialized ? "true" : "false", false);- optionService.createOption('lastSyncedPull', '0', false);- optionService.createOption('lastSyncedPush', '0', false);+ optionService.createOption("lastSyncedPull", "0", false);+ optionService.createOption("lastSyncedPush", "0", false);- optionService.createOption('theme', 'next', false);+ optionService.createOption("theme", "next", false);- optionService.createOption('syncServerHost', opts.syncServerHost || '', false);- optionService.createOption('syncServerTimeout', '120000', false);- optionService.createOption('syncProxy', opts.syncProxy || '', false);+ optionService.createOption("syncServerHost", opts.syncServerHost || "", false);+ optionService.createOption("syncServerTimeout", "120000", false);+ optionService.createOption("syncProxy", opts.syncProxy || "", false);}/*** Contains all the default options that must be initialized on new and existing databases (at startup). The value can also be determined based on other options, provided they have already been initialized.*/const defaultOptions: DefaultOption[] = [- { name: 'revisionSnapshotTimeInterval', value: '600', isSynced: true },- { name: 'revisionSnapshotNumberLimit', value: '-1', isSynced: true },- { name: 'protectedSessionTimeout', value: '600', isSynced: true },- { name: 'zoomFactor', value: isWindows() ? '0.9' : '1.0', isSynced: false },- { name: 'overrideThemeFonts', value: 'false', isSynced: false },- { name: 'mainFontFamily', value: 'theme', isSynced: false },- { name: 'mainFontSize', value: '100', isSynced: false },- { name: 'treeFontFamily', value: 'theme', isSynced: false },- { name: 'treeFontSize', value: '100', isSynced: false },- { name: 'detailFontFamily', value: 'theme', isSynced: false },- { name: 'detailFontSize', value: '110', isSynced: false },- { name: 'monospaceFontFamily', value: 'theme', isSynced: false },- { name: 'monospaceFontSize', value: '110', isSynced: false },- { name: 'spellCheckEnabled', value: 'true', isSynced: false },- { name: 'spellCheckLanguageCode', value: 'en-US', isSynced: false },- { name: 'imageMaxWidthHeight', value: '2000', isSynced: true },- { name: 'imageJpegQuality', value: '75', isSynced: true },- { name: 'autoFixConsistencyIssues', value: 'true', isSynced: false },- { name: 'vimKeymapEnabled', value: 'false', isSynced: false },- { name: 'codeLineWrapEnabled', value: 'true', isSynced: false },- { name: 'codeNotesMimeTypes', value: '["text/x-csrc","text/x-c++src","text/x-csharp","text/css","text/x-go","text/x-groovy","text/x-haskell","text/html","message/http","text/x-java","application/javascript;env=frontend","application/javascript;env=backend","application/json","text/x-kotlin","text/x-markdown","text/x-perl","text/x-php","text/x-python","text/x-ruby",null,"text/x-sql","text/x-sqlite;schema=trilium","text/x-swift","text/xml","text/x-yaml","text/x-sh"]', isSynced: true },- { name: 'leftPaneWidth', value: '25', isSynced: false },- { name: 'leftPaneVisible', value: 'true', isSynced: false },- { name: 'rightPaneWidth', value: '25', isSynced: false },- { name: 'rightPaneVisible', value: 'true', isSynced: false },- { name: 'nativeTitleBarVisible', value: 'false', isSynced: false },- { name: 'eraseEntitiesAfterTimeInSeconds', value: '604800', isSynced: true }, // default is 7 days- { name: 'hideArchivedNotes_main', value: 'false', isSynced: false },- { name: 'debugModeEnabled', value: 'false', isSynced: false },- { name: 'headingStyle', value: 'underline', isSynced: true },- { name: 'autoCollapseNoteTree', value: 'true', isSynced: true },- { name: 'autoReadonlySizeText', value: '10000', isSynced: false },- { name: 'autoReadonlySizeCode', value: '30000', isSynced: false },- { name: 'dailyBackupEnabled', value: 'true', isSynced: false },- { name: 'weeklyBackupEnabled', value: 'true', isSynced: false },- { name: 'monthlyBackupEnabled', value: 'true', isSynced: false },- { name: 'maxContentWidth', value: '1200', isSynced: false },- { name: 'compressImages', value: 'true', isSynced: true },- { name: 'downloadImagesAutomatically', value: 'true', isSynced: true },- { name: 'minTocHeadings', value: '5', isSynced: true },- { name: 'highlightsList', value: '["bold","italic","underline","color","bgColor"]', isSynced: true },- { name: 'checkForUpdates', value: 'true', isSynced: true },- { name: 'disableTray', value: 'false', isSynced: false },- { name: 'eraseUnusedAttachmentsAfterSeconds', value: '2592000', isSynced: true },- { name: 'customSearchEngineName', value: 'DuckDuckGo', isSynced: true },- { name: 'customSearchEngineUrl', value: 'https://duckduckgo.com/?q={keyword}', isSynced: true },- { name: 'promotedAttributesOpenInRibbon', value: 'true', isSynced: true },- { name: 'editedNotesOpenInRibbon', value: 'true', isSynced: true },+ { name: "revisionSnapshotTimeInterval", value: "600", isSynced: true },+ { name: "revisionSnapshotNumberLimit", value: "-1", isSynced: true },+ { name: "protectedSessionTimeout", value: "600", isSynced: true },+ { name: "zoomFactor", value: isWindows() ? "0.9" : "1.0", isSynced: false },+ { name: "overrideThemeFonts", value: "false", isSynced: false },+ { name: "mainFontFamily", value: "theme", isSynced: false },+ { name: "mainFontSize", value: "100", isSynced: false },+ { name: "treeFontFamily", value: "theme", isSynced: false },+ { name: "treeFontSize", value: "100", isSynced: false },+ { name: "detailFontFamily", value: "theme", isSynced: false },+ { name: "detailFontSize", value: "110", isSynced: false },+ { name: "monospaceFontFamily", value: "theme", isSynced: false },+ { name: "monospaceFontSize", value: "110", isSynced: false },+ { name: "spellCheckEnabled", value: "true", isSynced: false },+ { name: "spellCheckLanguageCode", value: "en-US", isSynced: false },+ { name: "imageMaxWidthHeight", value: "2000", isSynced: true },+ { name: "imageJpegQuality", value: "75", isSynced: true },+ { name: "autoFixConsistencyIssues", value: "true", isSynced: false },+ { name: "vimKeymapEnabled", value: "false", isSynced: false },+ { name: "codeLineWrapEnabled", value: "true", isSynced: false },+ {+ name: "codeNotesMimeTypes",+ value: '["text/x-csrc","text/x-c++src","text/x-csharp","text/css","text/x-go","text/x-groovy","text/x-haskell","text/html","message/http","text/x-java","application/javascript;env=frontend","application/javascript;env=backend","application/json","text/x-kotlin","text/x-markdown","text/x-perl","text/x-php","text/x-python","text/x-ruby",null,"text/x-sql","text/x-sqlite;schema=trilium","text/x-swift","text/xml","text/x-yaml","text/x-sh"]',+ isSynced: true+ },+ { name: "leftPaneWidth", value: "25", isSynced: false },+ { name: "leftPaneVisible", value: "true", isSynced: false },+ { name: "rightPaneWidth", value: "25", isSynced: false },+ { name: "rightPaneVisible", value: "true", isSynced: false },+ { name: "nativeTitleBarVisible", value: "false", isSynced: false },+ { name: "eraseEntitiesAfterTimeInSeconds", value: "604800", isSynced: true }, // default is 7 days+ { name: "hideArchivedNotes_main", value: "false", isSynced: false },+ { name: "debugModeEnabled", value: "false", isSynced: false },+ { name: "headingStyle", value: "underline", isSynced: true },+ { name: "autoCollapseNoteTree", value: "true", isSynced: true },+ { name: "autoReadonlySizeText", value: "10000", isSynced: false },+ { name: "autoReadonlySizeCode", value: "30000", isSynced: false },+ { name: "dailyBackupEnabled", value: "true", isSynced: false },+ { name: "weeklyBackupEnabled", value: "true", isSynced: false },+ { name: "monthlyBackupEnabled", value: "true", isSynced: false },+ { name: "maxContentWidth", value: "1200", isSynced: false },+ { name: "compressImages", value: "true", isSynced: true },+ { name: "downloadImagesAutomatically", value: "true", isSynced: true },+ { name: "minTocHeadings", value: "5", isSynced: true },+ { name: "highlightsList", value: '["bold","italic","underline","color","bgColor"]', isSynced: true },+ { name: "checkForUpdates", value: "true", isSynced: true },+ { name: "disableTray", value: "false", isSynced: false },+ { name: "eraseUnusedAttachmentsAfterSeconds", value: "2592000", isSynced: true },+ { name: "customSearchEngineName", value: "DuckDuckGo", isSynced: true },+ { name: "customSearchEngineUrl", value: "https://duckduckgo.com/?q={keyword}", isSynced: true },+ { name: "promotedAttributesOpenInRibbon", value: "true", isSynced: true },+ { name: "editedNotesOpenInRibbon", value: "true", isSynced: true },// Internationalization- { name: 'locale', value: 'en', isSynced: true },- { name: 'firstDayOfWeek', value: '1', isSynced: true },+ { name: "locale", value: "en", isSynced: true },+ { name: "firstDayOfWeek", value: "1", isSynced: true },// Code block configuration- { name: "codeBlockTheme", value: (optionsMap) => {- if (optionsMap.theme === "light") {- return "default:stackoverflow-light";- } else {- return "default:stackoverflow-dark";- }- }, isSynced: false },+ {+ name: "codeBlockTheme",+ value: (optionsMap) => {+ if (optionsMap.theme === "light") {+ return "default:stackoverflow-light";+ } else {+ return "default:stackoverflow-dark";+ }+ },+ isSynced: false+ },{ name: "codeBlockWordWrap", value: "false", isSynced: true },// Text note configuration@@ -139,18 +151,106 @@ const defaultOptions: DefaultOption[] = [// HTML import configuration{ name: "layoutOrientation", value: "vertical", isSynced: false },{ name: "backgroundEffects", value: "false", isSynced: false },- { name: "allowedHtmlTags", value: JSON.stringify([- 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol',- 'li', 'b', 'i', 'strong', 'em', 'strike', 's', 'del', 'abbr', 'code', 'hr', 'br', 'div',- 'table', 'thead', 'caption', 'tbody', 'tfoot', 'tr', 'th', 'td', 'pre', 'section', 'img',- 'figure', 'figcaption', 'span', 'label', 'input', 'details', 'summary', 'address', 'aside', 'footer',- 'header', 'hgroup', 'main', 'nav', 'dl', 'dt', 'menu', 'bdi', 'bdo', 'dfn', 'kbd', 'mark', 'q', 'time',- 'var', 'wbr', 'area', 'map', 'track', 'video', 'audio', 'picture', 'del', 'ins',- 'en-media',- 'acronym', 'article', 'big', 'button', 'cite', 'col', 'colgroup', 'data', 'dd',- 'fieldset', 'form', 'legend', 'meter', 'noscript', 'option', 'progress', 'rp',- 'samp', 'small', 'sub', 'sup', 'template', 'textarea', 'tt'- ]), isSynced: true },+ {+ name: "allowedHtmlTags",+ value: JSON.stringify([+ "h1",+ "h2",+ "h3",+ "h4",+ "h5",+ "h6",+ "blockquote",+ "p",+ "a",+ "ul",+ "ol",+ "li",+ "b",+ "i",+ "strong",+ "em",+ "strike",+ "s",+ "del",+ "abbr",+ "code",+ "hr",+ "br",+ "div",+ "table",+ "thead",+ "caption",+ "tbody",+ "tfoot",+ "tr",+ "th",+ "td",+ "pre",+ "section",+ "img",+ "figure",+ "figcaption",+ "span",+ "label",+ "input",+ "details",+ "summary",+ "address",+ "aside",+ "footer",+ "header",+ "hgroup",+ "main",+ "nav",+ "dl",+ "dt",+ "menu",+ "bdi",+ "bdo",+ "dfn",+ "kbd",+ "mark",+ "q",+ "time",+ "var",+ "wbr",+ "area",+ "map",+ "track",+ "video",+ "audio",+ "picture",+ "del",+ "ins",+ "en-media",+ "acronym",+ "article",+ "big",+ "button",+ "cite",+ "col",+ "colgroup",+ "data",+ "dd",+ "fieldset",+ "form",+ "legend",+ "meter",+ "noscript",+ "option",+ "progress",+ "rp",+ "samp",+ "small",+ "sub",+ "sup",+ "template",+ "textarea",+ "tt"+ ]),+ isSynced: true+ }];/**@@ -163,7 +263,7 @@ function initStartupOptions() {const allDefaultOptions = defaultOptions.concat(getKeyboardDefaultOptions());- for (const {name, value, isSynced} of allDefaultOptions) {+ for (const { name, value, isSynced } of allDefaultOptions) {if (!(name in optionsMap)) {let resolvedValue;if (typeof value === "function") {@@ -178,23 +278,24 @@ function initStartupOptions() {}if (process.env.TRILIUM_START_NOTE_ID || process.env.TRILIUM_SAFE_MODE) {- optionService.setOption('openNoteContexts', JSON.stringify([- {- notePath: process.env.TRILIUM_START_NOTE_ID || 'root',- active: true- }- ]));+ optionService.setOption(+ "openNoteContexts",+ JSON.stringify([+ {+ notePath: process.env.TRILIUM_START_NOTE_ID || "root",+ active: true+ }+ ])+ );}}function getKeyboardDefaultOptions() {- return (keyboardActions.getDefaultKeyboardActions()- .filter(ka => !!ka.actionName) as KeyboardShortcutWithRequiredActionName[])- .map(ka => ({- name: `keyboardShortcuts${ka.actionName.charAt(0).toUpperCase()}${ka.actionName.slice(1)}`,- value: JSON.stringify(ka.defaultShortcuts),- isSynced: false- })) as DefaultOption[];+ return (keyboardActions.getDefaultKeyboardActions().filter((ka) => !!ka.actionName) as KeyboardShortcutWithRequiredActionName[]).map((ka) => ({+ name: `keyboardShortcuts${ka.actionName.charAt(0).toUpperCase()}${ka.actionName.slice(1)}`,+ value: JSON.stringify(ka.defaultShortcuts),+ isSynced: false+ })) as DefaultOption[];}export default {diff --git a/src/services/options_interface.ts b/src/services/options_interface.tsindex 3cbdfa6ef7..36c78be76d 100644--- a/src/services/options_interface.ts+++ b/src/services/options_interface.ts@@ -9,90 +9,90 @@ export type OptionMap = Record<OptionNames, string>;* For each keyboard action, there is a corresponding option which identifies the key combination defined by the user.*/type KeyboardShortcutsOptions<T extends KeyboardActionNames> = {- [key in T as `keyboardShortcuts${Capitalize<key>}`]: string+ [key in T as `keyboardShortcuts${Capitalize<key>}`]: string;};export type FontFamily = "theme" | "serif" | "sans-serif" | "monospace" | string;export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActionNames> {- "openNoteContexts": string;- "lastDailyBackupDate": string;- "lastWeeklyBackupDate": string;- "lastMonthlyBackupDate": string;- "dbVersion": string;- "theme": string;- "syncServerHost": string;- "syncServerTimeout": string;- "syncProxy": string;- "mainFontFamily": FontFamily;- "treeFontFamily": FontFamily;- "detailFontFamily": FontFamily;- "monospaceFontFamily": FontFamily;- "spellCheckLanguageCode": string;- "codeNotesMimeTypes": string;- "headingStyle": string;- "highlightsList": string;- "customSearchEngineName": string;- "customSearchEngineUrl": string;- "locale": string;- "codeBlockTheme": string;- "textNoteEditorType": string;- "layoutOrientation": string;- "allowedHtmlTags": string;- "documentId": string;- "documentSecret": string;- "passwordVerificationHash": string;- "passwordVerificationSalt": string;- "passwordDerivedKeySalt": string;- "encryptedDataKey": string;+ openNoteContexts: string;+ lastDailyBackupDate: string;+ lastWeeklyBackupDate: string;+ lastMonthlyBackupDate: string;+ dbVersion: string;+ theme: string;+ syncServerHost: string;+ syncServerTimeout: string;+ syncProxy: string;+ mainFontFamily: FontFamily;+ treeFontFamily: FontFamily;+ detailFontFamily: FontFamily;+ monospaceFontFamily: FontFamily;+ spellCheckLanguageCode: string;+ codeNotesMimeTypes: string;+ headingStyle: string;+ highlightsList: string;+ customSearchEngineName: string;+ customSearchEngineUrl: string;+ locale: string;+ codeBlockTheme: string;+ textNoteEditorType: string;+ layoutOrientation: string;+ allowedHtmlTags: string;+ documentId: string;+ documentSecret: string;+ passwordVerificationHash: string;+ passwordVerificationSalt: string;+ passwordDerivedKeySalt: string;+ encryptedDataKey: string;- "lastSyncedPull": number;- "lastSyncedPush": number;- "revisionSnapshotTimeInterval": number;- "revisionSnapshotNumberLimit": number;- "protectedSessionTimeout": number;- "zoomFactor": number;- "mainFontSize": number;- "treeFontSize": number;- "detailFontSize": number;- "monospaceFontSize": number;- "imageMaxWidthHeight": number;- "imageJpegQuality": number;- "leftPaneWidth": number;- "rightPaneWidth": number;- "eraseEntitiesAfterTimeInSeconds": number;- "autoReadonlySizeText": number;- "autoReadonlySizeCode": number;- "maxContentWidth": number;- "minTocHeadings": number;- "eraseUnusedAttachmentsAfterSeconds": number;- "firstDayOfWeek": number;+ lastSyncedPull: number;+ lastSyncedPush: number;+ revisionSnapshotTimeInterval: number;+ revisionSnapshotNumberLimit: number;+ protectedSessionTimeout: number;+ zoomFactor: number;+ mainFontSize: number;+ treeFontSize: number;+ detailFontSize: number;+ monospaceFontSize: number;+ imageMaxWidthHeight: number;+ imageJpegQuality: number;+ leftPaneWidth: number;+ rightPaneWidth: number;+ eraseEntitiesAfterTimeInSeconds: number;+ autoReadonlySizeText: number;+ autoReadonlySizeCode: number;+ maxContentWidth: number;+ minTocHeadings: number;+ eraseUnusedAttachmentsAfterSeconds: number;+ firstDayOfWeek: number;- "initialized": boolean;- "overrideThemeFonts": boolean;- "spellCheckEnabled": boolean;- "autoFixConsistencyIssues": boolean;- "vimKeymapEnabled": boolean;- "codeLineWrapEnabled": boolean;- "leftPaneVisible": boolean;- "rightPaneVisible": boolean;- "nativeTitleBarVisible": boolean;- "hideArchivedNotes_main": boolean;- "debugModeEnabled": boolean;- "autoCollapseNoteTree": boolean;- "dailyBackupEnabled": boolean;- "weeklyBackupEnabled": boolean;- "monthlyBackupEnabled": boolean;- "compressImages": boolean;- "downloadImagesAutomatically": boolean;- "checkForUpdates": boolean;- "disableTray": boolean;- "promotedAttributesOpenInRibbon": boolean;- "editedNotesOpenInRibbon": boolean;- "codeBlockWordWrap": boolean;- "textNoteEditorMultilineToolbar": boolean;- "backgroundEffects": boolean;-};+ initialized: boolean;+ overrideThemeFonts: boolean;+ spellCheckEnabled: boolean;+ autoFixConsistencyIssues: boolean;+ vimKeymapEnabled: boolean;+ codeLineWrapEnabled: boolean;+ leftPaneVisible: boolean;+ rightPaneVisible: boolean;+ nativeTitleBarVisible: boolean;+ hideArchivedNotes_main: boolean;+ debugModeEnabled: boolean;+ autoCollapseNoteTree: boolean;+ dailyBackupEnabled: boolean;+ weeklyBackupEnabled: boolean;+ monthlyBackupEnabled: boolean;+ compressImages: boolean;+ downloadImagesAutomatically: boolean;+ checkForUpdates: boolean;+ disableTray: boolean;+ promotedAttributesOpenInRibbon: boolean;+ editedNotesOpenInRibbon: boolean;+ codeBlockWordWrap: boolean;+ textNoteEditorMultilineToolbar: boolean;+ backgroundEffects: boolean;+}export type OptionNames = keyof OptionDefinitions;diff --git a/src/services/port.ts b/src/services/port.tsindex 0fffc7c24a..76cbd7bf92 100644--- a/src/services/port.ts+++ b/src/services/port.ts@@ -21,7 +21,7 @@ if (process.env.TRILIUM_PORT) {} else if (isElectron()) {port = env.isDev() ? 37740 : 37840;} else {- port = parseAndValidate(config['Network']['port'] || '3000', `Network.port in ${dataDir.CONFIG_INI_PATH}`);+ port = parseAndValidate(config["Network"]["port"] || "3000", `Network.port in ${dataDir.CONFIG_INI_PATH}`);}export default port;diff --git a/src/services/promoted_attribute_definition_parser.ts b/src/services/promoted_attribute_definition_parser.tsindex 1b9a73a80a..53a7d8e850 100644--- a/src/services/promoted_attribute_definition_parser.ts+++ b/src/services/promoted_attribute_definition_parser.ts@@ -1,35 +1,29 @@import { DefinitionObject } from "./promoted_attribute_definition_interface.js";function parse(value: string): DefinitionObject {- const tokens = value.split(',').map(t => t.trim());+ const tokens = value.split(",").map((t) => t.trim());const defObj: DefinitionObject = {};for (const token of tokens) {- if (token === 'promoted') {+ if (token === "promoted") {defObj.isPromoted = true;- }- else if (['text', 'number', 'boolean', 'date', 'datetime', 'time', 'url'].includes(token)) {+ } else if (["text", "number", "boolean", "date", "datetime", "time", "url"].includes(token)) {defObj.labelType = token;- }- else if (['single', 'multi'].includes(token)) {+ } else if (["single", "multi"].includes(token)) {defObj.multiplicity = token;- }- else if (token.startsWith('precision')) {- const chunks = token.split('=');+ } else if (token.startsWith("precision")) {+ const chunks = token.split("=");defObj.numberPrecision = parseInt(chunks[1]);- }- else if (token.startsWith('alias')) {- const chunks = token.split('=');+ } else if (token.startsWith("alias")) {+ const chunks = token.split("=");defObj.promotedAlias = chunks[1];- }- else if (token.startsWith('inverse')) {- const chunks = token.split('=');+ } else if (token.startsWith("inverse")) {+ const chunks = token.split("=");- defObj.inverseRelation = chunks[1].replace(/[^\p{L}\p{N}_:]/ug, "")- }- else {+ defObj.inverseRelation = chunks[1].replace(/[^\p{L}\p{N}_:]/gu, "");+ } else {console.log("Unrecognized attribute definition token:", token);}}diff --git a/src/services/protected_session.ts b/src/services/protected_session.tsindex b24b971d46..57a163e186 100644--- a/src/services/protected_session.ts+++ b/src/services/protected_session.ts@@ -58,11 +58,8 @@ function touchProtectedSession() {}function checkProtectedSessionExpiration() {- const protectedSessionTimeout = options.getOptionInt('protectedSessionTimeout');- if (isProtectedSessionAvailable()- && lastProtectedSessionOperationDate- && Date.now() - lastProtectedSessionOperationDate > protectedSessionTimeout * 1000) {-+ const protectedSessionTimeout = options.getOptionInt("protectedSessionTimeout");+ if (isProtectedSessionAvailable() && lastProtectedSessionOperationDate && Date.now() - lastProtectedSessionOperationDate > protectedSessionTimeout * 1000) {resetDataKey();log.info("Expiring protected session");diff --git a/src/services/request.ts b/src/services/request.tsindex 2273c9dff7..d06339fc8c 100644--- a/src/services/request.ts+++ b/src/services/request.ts@@ -4,7 +4,7 @@ import { isElectron } from "./utils.js";import log from "./log.js";import url from "url";import syncOptions from "./sync_options.js";-import { ExecOpts } from './request_interface.js';+import { ExecOpts } from "./request_interface.js";// this service provides abstraction over node's HTTP/HTTPS and electron net.client APIs// this allows supporting system proxy@@ -22,7 +22,7 @@ interface ClientOpts {proxy?: string | null;}-type RequestEvent = ("error" | "response" | "abort");+type RequestEvent = "error" | "response" | "abort";interface Request {on(event: RequestEvent, cb: (e: any) => void): void;@@ -37,14 +37,14 @@ async function exec<T>(opts: ExecOpts): Promise<T> {const client = getClient(opts);// hack for cases where electron.net does not work, but we don't want to set proxy- if (opts.proxy === 'noproxy') {+ if (opts.proxy === "noproxy") {opts.proxy = null;}const paging = opts.paging || {pageCount: 1,pageIndex: 0,- requestId: 'n/a'+ requestId: "n/a"};const proxyAgent = await getProxyAgent(opts);@@ -54,14 +54,14 @@ async function exec<T>(opts: ExecOpts): Promise<T> {try {const headers: Record<string, string | number> = {Cookie: (opts.cookieJar && opts.cookieJar.header) || "",- 'Content-Type': paging.pageCount === 1 ? 'application/json' : 'text/plain',+ "Content-Type": paging.pageCount === 1 ? "application/json" : "text/plain",pageCount: paging.pageCount,pageIndex: paging.pageIndex,requestId: paging.requestId};if (opts.auth) {- headers['trilium-cred'] = Buffer.from(`dummy:${opts.auth.password}`).toString('base64');+ headers["trilium-cred"] = Buffer.from(`dummy:${opts.auth.password}`).toString("base64");}const request = (await client).request({@@ -78,22 +78,22 @@ async function exec<T>(opts: ExecOpts): Promise<T> {agent: proxyAgent});- request.on('error', err => reject(generateError(opts, err)));+ request.on("error", (err) => reject(generateError(opts, err)));- request.on('response', response => {- if (opts.cookieJar && response.headers['set-cookie']) {- opts.cookieJar.header = response.headers['set-cookie'];+ request.on("response", (response) => {+ if (opts.cookieJar && response.headers["set-cookie"]) {+ opts.cookieJar.header = response.headers["set-cookie"];}- let responseStr = '';+ let responseStr = "";let chunks: Buffer[] = [];- response.on('data', (chunk: Buffer) => chunks.push(chunk));+ response.on("data", (chunk: Buffer) => chunks.push(chunk));- response.on('end', () => {+ response.on("end", () => {// use Buffer instead of string concatenation to avoid implicit decoding for each chunk// decode the entire data chunks explicitly as utf-8- responseStr = Buffer.concat(chunks).toString('utf-8')+ responseStr = Buffer.concat(chunks).toString("utf-8");if ([200, 201, 204].includes(response.statusCode)) {try {@@ -111,7 +111,7 @@ async function exec<T>(opts: ExecOpts): Promise<T> {try {const jsonObj = JSON.parse(responseStr);- errorMessage = jsonObj?.message || '';+ errorMessage = jsonObj?.message || "";} catch (e: any) {errorMessage = responseStr.substr(0, Math.min(responseStr.length, 100));}@@ -124,14 +124,11 @@ async function exec<T>(opts: ExecOpts): Promise<T> {let payload;if (opts.body) {- payload = typeof opts.body === 'object'- ? JSON.stringify(opts.body)- : opts.body;+ payload = typeof opts.body === "object" ? JSON.stringify(opts.body) : opts.body;}request.end(payload as string);- }- catch (e: any) {+ } catch (e: any) {reject(generateError(opts, e.message));}});@@ -140,7 +137,7 @@ async function exec<T>(opts: ExecOpts): Promise<T> {async function getImage(imageUrl: string): Promise<Buffer> {const proxyConf = syncOptions.getSyncProxy();const opts: ClientOpts = {- method: 'GET',+ method: "GET",url: imageUrl,proxy: proxyConf !== "noproxy" ? proxyConf : null};@@ -165,19 +162,19 @@ async function getImage(imageUrl: string): Promise<Buffer> {agent: proxyAgent});- request.on('error', err => reject(generateError(opts, err)));+ request.on("error", (err) => reject(generateError(opts, err)));- request.on('abort', err => reject(generateError(opts, err)));+ request.on("abort", (err) => reject(generateError(opts, err)));- request.on('response', response => {+ request.on("response", (response) => {if (![200, 201, 204].includes(response.statusCode)) {reject(generateError(opts, `${response.statusCode} ${response.statusMessage}`));}- const chunks: Buffer[] = []+ const chunks: Buffer[] = [];- response.on('data', (chunk: Buffer) => chunks.push(chunk));- response.on('end', () => resolve(Buffer.concat(chunks)));+ response.on("data", (chunk: Buffer) => chunks.push(chunk));+ response.on("end", () => resolve(Buffer.concat(chunks)));});request.end(undefined);@@ -187,22 +184,21 @@ async function getImage(imageUrl: string): Promise<Buffer> {});}-const HTTP = 'http:', HTTPS = 'https:';+const HTTP = "http:",+ HTTPS = "https:";async function getProxyAgent(opts: ClientOpts) {if (!opts.proxy) {return null;}- const {protocol} = url.parse(opts.url);+ const { protocol } = url.parse(opts.url);if (!protocol || ![HTTP, HTTPS].includes(protocol)) {return null;}- const AgentClass = HTTP === protocol- ? (await import('http-proxy-agent')).HttpProxyAgent- : (await import('https-proxy-agent')).HttpsProxyAgent;+ const AgentClass = HTTP === protocol ? (await import("http-proxy-agent")).HttpProxyAgent : (await import("https-proxy-agent")).HttpsProxyAgent;return new AgentClass(opts.proxy);}@@ -211,11 +207,11 @@ async function getClient(opts: ClientOpts): Promise<Client> {// it's not clear how to explicitly configure proxy (as opposed to system proxy),// so in that case, we always use node's modulesif (isElectron() && !opts.proxy) {- return (await import('electron')).net as Client;+ return (await import("electron")).net as Client;} else {- const {protocol} = url.parse(opts.url);+ const { protocol } = url.parse(opts.url);- if (protocol === 'http:' || protocol === 'https:') {+ if (protocol === "http:" || protocol === "https:") {return await import(protocol.substr(0, protocol.length - 1));} else {throw new Error(`Unrecognized protocol '${protocol}'`);@@ -223,10 +219,13 @@ async function getClient(opts: ClientOpts): Promise<Client> {}}-function generateError(opts: {- method: string;- url: string;-}, message: string) {+function generateError(+ opts: {+ method: string;+ url: string;+ },+ message: string+) {return new Error(`Request to ${opts.method} ${opts.url} failed, error: ${message}`);}diff --git a/src/services/request_interface.ts b/src/services/request_interface.tsindex a918bac45f..8ecd46bdb1 100644--- a/src/services/request_interface.ts+++ b/src/services/request_interface.ts@@ -14,7 +14,7 @@ export interface ExecOpts {cookieJar?: CookieJar;auth?: {password?: string;- },+ };timeout: number;body?: string | {};}diff --git a/src/services/revisions.ts b/src/services/revisions.tsindex cfe8f04c61..3688f9e5f9 100644--- a/src/services/revisions.ts+++ b/src/services/revisions.ts@@ -19,7 +19,7 @@ function protectRevisions(note: BNote) {revision.isProtected = !!note.isProtected;// this will force de/encryption- revision.setContent(content, {forceSave: true});+ revision.setContent(content, { forceSave: true });} catch (e) {log.error(`Could not un/protect note revision '${revision.revisionId}'`);@@ -33,7 +33,7 @@ function protectRevisions(note: BNote) {const content = attachment.getContent();attachment.isProtected = note.isProtected;- attachment.setContent(content, {forceSave: true});+ attachment.setContent(content, { forceSave: true });} catch (e) {log.error(`Could not un/protect attachment '${attachment.attachmentId}'`);diff --git a/src/services/sanitize_attribute_name.ts b/src/services/sanitize_attribute_name.tsindex b1f0e65798..3e597e94a8 100644--- a/src/services/sanitize_attribute_name.ts+++ b/src/services/sanitize_attribute_name.ts@@ -1,8 +1,6 @@export default function sanitizeAttributeName(origName: string) {- const fixedName = (origName === '')- ? "unnamed"- : origName.replace(/[^\p{L}\p{N}_:]/ug, "_");- // any not allowed character should be replaced with underscore+ const fixedName = origName === "" ? "unnamed" : origName.replace(/[^\p{L}\p{N}_:]/gu, "_");+ // any not allowed character should be replaced with underscorereturn fixedName;-}\ No newline at end of file+}diff --git a/src/services/scheduler.ts b/src/services/scheduler.tsindex 6d3dac8b81..73ab8832a8 100644--- a/src/services/scheduler.ts+++ b/src/services/scheduler.ts@@ -10,7 +10,7 @@ import BNote from "../becca/entities/bnote.js";function getRunAtHours(note: BNote): number[] {try {- return note.getLabelValues('runAtHour').map(hour => parseInt(hour));+ return note.getLabelValues("runAtHour").map((hour) => parseInt(hour));} catch (e: any) {log.error(`Could not parse runAtHour for note ${note.noteId}: ${e.message}`);@@ -21,15 +21,13 @@ function getRunAtHours(note: BNote): number[] {function runNotesWithLabel(runAttrValue: string) {const instanceName = config.General ? config.General.instanceName : null;const currentHours = new Date().getHours();- const notes = attributeService.getNotesWithLabel('run', runAttrValue);+ const notes = attributeService.getNotesWithLabel("run", runAttrValue);for (const note of notes) {- const runOnInstances = note.getLabelValues('runOnInstance');+ const runOnInstances = note.getLabelValues("runOnInstance");const runAtHours = getRunAtHours(note);- if ((runOnInstances.length === 0 || runOnInstances.includes(instanceName))- && (runAtHours.length === 0 || runAtHours.includes(currentHours))- ) {+ if ((runOnInstances.length === 0 || runOnInstances.includes(instanceName)) && (runAtHours.length === 0 || runAtHours.includes(currentHours))) {scriptService.executeNoteNoException(note, { originEntity: note });}}@@ -41,13 +39,25 @@ sqlInit.dbReady.then(() => {});if (!process.env.TRILIUM_SAFE_MODE) {- setTimeout(cls.wrap(() => runNotesWithLabel('backendStartup')), 10 * 1000);+ setTimeout(+ cls.wrap(() => runNotesWithLabel("backendStartup")),+ 10 * 1000+ );- setInterval(cls.wrap(() => runNotesWithLabel('hourly')), 3600 * 1000);+ setInterval(+ cls.wrap(() => runNotesWithLabel("hourly")),+ 3600 * 1000+ );- setInterval(cls.wrap(() => runNotesWithLabel('daily')), 24 * 3600 * 1000);+ setInterval(+ cls.wrap(() => runNotesWithLabel("daily")),+ 24 * 3600 * 1000+ );- setInterval(cls.wrap(() => hiddenSubtreeService.checkHiddenSubtree()), 7 * 3600 * 1000);+ setInterval(+ cls.wrap(() => hiddenSubtreeService.checkHiddenSubtree()),+ 7 * 3600 * 1000+ );}setInterval(() => protectedSessionService.checkProtectedSessionExpiration(), 30000);diff --git a/src/services/script.ts b/src/services/script.tsindex d421ca385b..300b2af983 100644--- a/src/services/script.ts+++ b/src/services/script.ts@@ -3,7 +3,7 @@ import cls from "./cls.js";import log from "./log.js";import becca from "../becca/becca.js";import BNote from "../becca/entities/bnote.js";-import { ApiParams } from './backend_script_api_interface.js';+import { ApiParams } from "./backend_script_api_interface.js";interface Bundle {note?: BNote;@@ -17,13 +17,13 @@ interface Bundle {type ScriptParams = any[];function executeNote(note: BNote, apiParams: ApiParams) {- if (!note.isJavaScript() || note.getScriptEnv() !== 'backend' || !note.isContentAvailable()) {+ if (!note.isJavaScript() || note.getScriptEnv() !== "backend" || !note.isContentAvailable()) {log.info(`Cannot execute note ${note.noteId} "${note.title}", note must be of type "Code: JS backend"`);return;}- const bundle = getScriptBundle(note, true, 'backend');+ const bundle = getScriptBundle(note, true, "backend");if (!bundle) {throw new Error("Unable to determine bundle.");}@@ -34,8 +34,7 @@ function executeNote(note: BNote, apiParams: ApiParams) {function executeNoteNoException(note: BNote, apiParams: ApiParams) {try {executeNote(note, apiParams);- }- catch (e) {+ } catch (e) {// just swallow, exception is logged already in executeNote}}@@ -46,10 +45,10 @@ function executeBundle(bundle: Bundle, apiParams: ApiParams = {}) {apiParams.startNote = bundle.note;}- const originalComponentId = cls.get('componentId');+ const originalComponentId = cls.get("componentId");- cls.set('componentId', 'script');- cls.set('bundleNoteId', bundle.note?.noteId);+ cls.set("componentId", "script");+ cls.set("bundleNoteId", bundle.note?.noteId);// last \r\n is necessary if the script contains line comment on its last lineconst script = `function() {\r@@ -59,14 +58,12 @@ ${bundle.script}\rtry {return execute(ctx, script);- }- catch (e: any) {+ } catch (e: any) {log.error(`Execution of script "${bundle.note?.title}" (${bundle.note?.noteId}) failed with error: ${e.message}`);throw e;- }- finally {- cls.set('componentId', originalComponentId);+ } finally {+ cls.set("componentId", originalComponentId);}}@@ -90,7 +87,7 @@ function executeScript(script: string, params: ScriptParams, startNoteId: string// override normal note's content, and it's mime type / script environmentconst overrideContent = `return (${script}\r\n)(${getParams(params)})`;- const bundle = getScriptBundle(currentNote, true, 'backend', [], overrideContent);+ const bundle = getScriptBundle(currentNote, true, "backend", [], overrideContent);if (!bundle) {throw new Error("Unable to determine script bundle.");}@@ -99,7 +96,9 @@ function executeScript(script: string, params: ScriptParams, startNoteId: string}function execute(ctx: ScriptContext, script: string) {- return function () { return eval(`const apiContext = this;\r\n(${script}\r\n)()`); }.call(ctx);+ return function () {+ return eval(`const apiContext = this;\r\n(${script}\r\n)()`);+ }.call(ctx);}function getParams(params?: ScriptParams) {@@ -107,14 +106,15 @@ function getParams(params?: ScriptParams) {return params;}- return params.map(p => {- if (typeof p === "string" && p.startsWith("!@#Function: ")) {- return p.substr(13);- }- else {- return JSON.stringify(p);- }- }).join(",");+ return params+ .map((p) => {+ if (typeof p === "string" && p.startsWith("!@#Function: ")) {+ return p.substr(13);+ } else {+ return JSON.stringify(p);+ }+ })+ .join(",");}function getScriptBundleForFrontend(note: BNote, script?: string, params?: ScriptParams) {@@ -124,7 +124,7 @@ function getScriptBundleForFrontend(note: BNote, script?: string, params?: ScripoverrideContent = `return (${script}\r\n)(${getParams(params)})`;}- const bundle = getScriptBundle(note, true, 'frontend', [], overrideContent);+ const bundle = getScriptBundle(note, true, "frontend", [], overrideContent);if (!bundle) {return;@@ -134,7 +134,7 @@ function getScriptBundleForFrontend(note: BNote, script?: string, params?: Scripbundle.noteId = bundle.note?.noteId;delete bundle.note;- bundle.allNoteIds = bundle.allNotes?.map(note => note.noteId);+ bundle.allNoteIds = bundle.allNotes?.map((note) => note.noteId);delete bundle.allNotes;return bundle;@@ -149,18 +149,18 @@ function getScriptBundle(note: BNote, root: boolean = true, scriptEnv: string |return;}- if (!root && note.hasOwnedLabel('disableInclusion')) {+ if (!root && note.hasOwnedLabel("disableInclusion")) {return;}- if (note.type !== 'file' && !root && scriptEnv !== note.getScriptEnv()) {+ if (note.type !== "file" && !root && scriptEnv !== note.getScriptEnv()) {return;}const bundle: Bundle = {note: note,- script: '',- html: '',+ script: "",+ html: "",allNotes: [note]};@@ -187,24 +187,23 @@ function getScriptBundle(note: BNote, root: boolean = true, scriptEnv: string |}}- const moduleNoteIds = modules.map(mod => mod.noteId);+ const moduleNoteIds = modules.map((mod) => mod.noteId);// only frontend scripts are async. Backend cannot be async because of transaction management.- const isFrontend = scriptEnv === 'frontend';+ const isFrontend = scriptEnv === "frontend";if (note.isJavaScript()) {bundle.script += `apiContext.modules['${note.noteId}'] = { exports: {} };-${root ? 'return ' : ''}${isFrontend ? 'await' : ''} ((${isFrontend ? 'async' : ''} function(exports, module, require, api${modules.length > 0 ? ', ' : ''}${modules.map(child => sanitizeVariableName(child.title)).join(', ')}) {+${root ? "return " : ""}${isFrontend ? "await" : ""} ((${isFrontend ? "async" : ""} function(exports, module, require, api${modules.length > 0 ? ", " : ""}${modules.map((child) => sanitizeVariableName(child.title)).join(", ")}) {try {${overrideContent || note.getContent()};} catch (e) { throw new Error("Load of script note \\"${note.title}\\" (${note.noteId}) failed with: " + e.message); }for (const exportKey in exports) module.exports[exportKey] = exports[exportKey];return module.exports;-}).call({}, {}, apiContext.modules['${note.noteId}'], apiContext.require(${JSON.stringify(moduleNoteIds)}), apiContext.apis['${note.noteId}']${modules.length > 0 ? ', ' : ''}${modules.map(mod => `apiContext.modules['${mod.noteId}'].exports`).join(', ')}));+}).call({}, {}, apiContext.modules['${note.noteId}'], apiContext.require(${JSON.stringify(moduleNoteIds)}), apiContext.apis['${note.noteId}']${modules.length > 0 ? ", " : ""}${modules.map((mod) => `apiContext.modules['${mod.noteId}'].exports`).join(", ")}));`;- }- else if (note.isHtml()) {+ } else if (note.isHtml()) {bundle.html += note.getContent();}diff --git a/src/services/script_context.ts b/src/services/script_context.tsindex cf016b4920..cd183b6ffe 100644--- a/src/services/script_context.ts+++ b/src/services/script_context.ts@@ -1,7 +1,7 @@import { toObject } from "./utils.js";import BackendScriptApi from "./backend_script_api.js";import BNote from "../becca/entities/bnote.js";-import { ApiParams } from './backend_script_api_interface.js';+import { ApiParams } from "./backend_script_api_interface.js";type Module = {exports: any[];@@ -16,22 +16,22 @@ class ScriptContext {constructor(allNotes: BNote[], apiParams: ApiParams) {this.allNotes = allNotes;this.modules = {};- this.notes = toObject(allNotes, note => [note.noteId, note]);- this.apis = toObject(allNotes, note => [note.noteId, new BackendScriptApi(note, apiParams)]);+ this.notes = toObject(allNotes, (note) => [note.noteId, note]);+ this.apis = toObject(allNotes, (note) => [note.noteId, new BackendScriptApi(note, apiParams)]);}require(moduleNoteIds: string[]) {return (moduleName: string) => {- const candidates = this.allNotes.filter(note => moduleNoteIds.includes(note.noteId));- const note = candidates.find(c => c.title === moduleName);+ const candidates = this.allNotes.filter((note) => moduleNoteIds.includes(note.noteId));+ const note = candidates.find((c) => c.title === moduleName);if (!note) {return require(moduleName);}return this.modules[note.noteId].exports;- }- };+ };+ }}export default ScriptContext;diff --git a/src/services/search/expressions/ancestor.ts b/src/services/search/expressions/ancestor.tsindex 8016e14921..2b5f5d4cbf 100644--- a/src/services/search/expressions/ancestor.ts+++ b/src/services/search/expressions/ancestor.ts@@ -7,10 +7,9 @@ import becca from "../../../becca/becca.js";import SearchContext from "../search_context.js";class AncestorExp extends Expression {-private ancestorNoteId: string;private ancestorDepthComparator;-+ancestorDepth?: string;constructor(ancestorNoteId: string, ancestorDepth?: string) {@@ -59,15 +58,12 @@ class AncestorExp extends Expression {const comparedDepth = parseInt(depthCondition.substr(2));if (depthCondition.startsWith("eq")) {- return depth => depth === comparedDepth;- }- else if (depthCondition.startsWith("gt")) {- return depth => depth > comparedDepth;- }- else if (depthCondition.startsWith("lt")) {- return depth => depth < comparedDepth;- }- else {+ return (depth) => depth === comparedDepth;+ } else if (depthCondition.startsWith("gt")) {+ return (depth) => depth > comparedDepth;+ } else if (depthCondition.startsWith("lt")) {+ return (depth) => depth < comparedDepth;+ } else {log.error(`Unrecognized depth condition value ${depthCondition}`);return null;}diff --git a/src/services/search/expressions/attribute_exists.ts b/src/services/search/expressions/attribute_exists.tsindex 625e4b2af4..1b0dc397b6 100644--- a/src/services/search/expressions/attribute_exists.ts+++ b/src/services/search/expressions/attribute_exists.ts@@ -7,7 +7,6 @@ import becca from "../../../becca/becca.js";import Expression from "./expression.js";class AttributeExistsExp extends Expression {-private attributeType: string;private attributeName: string;private isTemplateLabel: boolean;@@ -19,14 +18,12 @@ class AttributeExistsExp extends Expression {this.attributeType = attributeType;this.attributeName = attributeName;// template attr is used as a marker for templates, but it's not meant to be inherited- this.isTemplateLabel = this.attributeType === 'label' && (this.attributeName === 'template' || this.attributeName === 'workspacetemplate');+ this.isTemplateLabel = this.attributeType === "label" && (this.attributeName === "template" || this.attributeName === "workspacetemplate");this.prefixMatch = prefixMatch;}execute(inputNoteSet: NoteSet, executionContext: {}, searchContext: SearchContext) {- const attrs = this.prefixMatch- ? becca.findAttributesWithPrefix(this.attributeType, this.attributeName)- : becca.findAttributes(this.attributeType, this.attributeName);+ const attrs = this.prefixMatch ? becca.findAttributesWithPrefix(this.attributeType, this.attributeName) : becca.findAttributes(this.attributeType, this.attributeName);const resultNoteSet = new NoteSet();@@ -35,11 +32,9 @@ class AttributeExistsExp extends Expression {if (attr.isInheritable && !this.isTemplateLabel) {resultNoteSet.addAll(note.getSubtreeNotesIncludingTemplated());- }- else if (note.isInherited() && !this.isTemplateLabel) {+ } else if (note.isInherited() && !this.isTemplateLabel) {resultNoteSet.addAll(note.getInheritingNotes());- }- else {+ } else {resultNoteSet.add(note);}}diff --git a/src/services/search/expressions/child_of.ts b/src/services/search/expressions/child_of.tsindex 491eab3efe..aa5277423d 100644--- a/src/services/search/expressions/child_of.ts+++ b/src/services/search/expressions/child_of.ts@@ -5,7 +5,6 @@ import NoteSet from "../note_set.js";import SearchContext from "../search_context.js";class ChildOfExp extends Expression {-private subExpression: Expression;constructor(subExpression: Expression) {diff --git a/src/services/search/expressions/label_comparison.ts b/src/services/search/expressions/label_comparison.tsindex 85ef940963..ade1fed6cf 100644--- a/src/services/search/expressions/label_comparison.ts+++ b/src/services/search/expressions/label_comparison.ts@@ -8,7 +8,6 @@ import SearchContext from "../search_context.js";type Comparator = (value: string) => boolean;class LabelComparisonExp extends Expression {-private attributeType: string;private attributeName: string;private comparator: Comparator;@@ -32,11 +31,9 @@ class LabelComparisonExp extends Expression {if (inputNoteSet.hasNoteId(note.noteId) && this.comparator(value)) {if (attr.isInheritable) {resultNoteSet.addAll(note.getSubtreeNotesIncludingTemplated());- }- else if (note.isInherited()) {+ } else if (note.isInherited()) {resultNoteSet.addAll(note.getInheritingNotes());- }- else {+ } else {resultNoteSet.add(note);}}diff --git a/src/services/search/expressions/note_content_fulltext.ts b/src/services/search/expressions/note_content_fulltext.tsindex bc92cf26c3..15c722b083 100644--- a/src/services/search/expressions/note_content_fulltext.ts+++ b/src/services/search/expressions/note_content_fulltext.ts@@ -12,14 +12,13 @@ import striptags from "striptags";import { normalize } from "../../utils.js";import sql from "../../sql.js";--const ALLOWED_OPERATORS = new Set(['=', '!=', '*=*', '*=', '=*', '%=']);+const ALLOWED_OPERATORS = new Set(["=", "!=", "*=*", "*=", "=*", "%="]);const cachedRegexes: Record<string, RegExp> = {};function getRegex(str: string): RegExp {if (!(str in cachedRegexes)) {- cachedRegexes[str] = new RegExp(str, 'ms'); // multiline, dot-all+ cachedRegexes[str] = new RegExp(str, "ms"); // multiline, dot-all}return cachedRegexes[str];@@ -34,13 +33,12 @@ interface ConstructorOpts {type SearchRow = Pick<NoteRow, "noteId" | "type" | "mime" | "content" | "isProtected">;class NoteContentFulltextExp extends Expression {-private operator: string;private tokens: string[];private raw: boolean;private flatText: boolean;-- constructor(operator: string, {tokens, raw, flatText}: ConstructorOpts) {++ constructor(operator: string, { tokens, raw, flatText }: ConstructorOpts) {super();this.operator = operator;@@ -57,19 +55,18 @@ class NoteContentFulltextExp extends Expression {}const resultNoteSet = new NoteSet();-+for (const row of sql.iterateRows<SearchRow>(`SELECT noteId, type, mime, content, isProtectedFROM notes JOIN blobs USING (blobId)WHERE type IN ('text', 'code', 'mermaid', 'canvas', 'mindMap') AND isDeleted = 0`)) {-this.findInText(row, inputNoteSet, resultNoteSet);}return resultNoteSet;}- findInText({noteId, isProtected, content, type, mime}: SearchRow, inputNoteSet: NoteSet, resultNoteSet: NoteSet) {+ findInText({ noteId, isProtected, content, type, mime }: SearchRow, inputNoteSet: NoteSet, resultNoteSet: NoteSet) {if (!inputNoteSet.hasNoteId(noteId) || !(noteId in becca.notes)) {return;}@@ -96,24 +93,23 @@ class NoteContentFulltextExp extends Expression {if (this.tokens.length === 1) {const [token] = this.tokens;- if ((this.operator === '=' && token === content)- || (this.operator === '!=' && token !== content)- || (this.operator === '*=' && content.endsWith(token))- || (this.operator === '=*' && content.startsWith(token))- || (this.operator === '*=*' && content.includes(token))- || (this.operator === '%=' && getRegex(token).test(content))) {-+ if (+ (this.operator === "=" && token === content) ||+ (this.operator === "!=" && token !== content) ||+ (this.operator === "*=" && content.endsWith(token)) ||+ (this.operator === "=*" && content.startsWith(token)) ||+ (this.operator === "*=*" && content.includes(token)) ||+ (this.operator === "%=" && getRegex(token).test(content))+ ) {resultNoteSet.add(becca.notes[noteId]);}} else {- const nonMatchingToken = this.tokens.find(token =>- !content?.includes(token) &&- (+ const nonMatchingToken = this.tokens.find(+ (token) =>+ !content?.includes(token) &&// in case of default fulltext search, we should consider both title, attrs and content// so e.g. "hello world" should match when "hello" is in title and "world" in content- !this.flatText- || !becca.notes[noteId].getFlatText().includes(token)- )+ (!this.flatText || !becca.notes[noteId].getFlatText().includes(token)));if (!nonMatchingToken) {@@ -127,18 +123,17 @@ class NoteContentFulltextExp extends Expression {preprocessContent(content: string | Buffer, type: string, mime: string) {content = normalize(content.toString());- if (type === 'text' && mime === 'text/html') {- if (!this.raw && content.length < 20000) { // striptags is slow for very large notes+ if (type === "text" && mime === "text/html") {+ if (!this.raw && content.length < 20000) {+ // striptags is slow for very large notescontent = this.stripTags(content);}- content = content.replace(/ /g, ' ');- }- else if (type === 'mindMap' && mime === 'application/json') {-- let mindMapcontent = JSON.parse (content);+ content = content.replace(/ /g, " ");+ } else if (type === "mindMap" && mime === "application/json") {+ let mindMapcontent = JSON.parse(content);- // Define interfaces for the JSON structure+ // Define interfaces for the JSON structureinterface MindmapNode {id: string;topic: string;@@ -146,62 +141,58 @@ class NoteContentFulltextExp extends Expression {direction?: number;expanded?: boolean;}-+interface MindmapData {nodedata: MindmapNode;arrows: any[]; // If you know the structure, replace `any` with the correct typesummaries: any[];direction: number;theme: {- name: string;- type: string;- palette: string[];- cssvar: Record<string, string>; // Object with string keys and string values+ name: string;+ type: string;+ palette: string[];+ cssvar: Record<string, string>; // Object with string keys and string values};}-- // Recursive function to collect all topics- function collectTopics(node: MindmapNode): string[] {++ // Recursive function to collect all topics+ function collectTopics(node: MindmapNode): string[] {// Collect the current node's topiclet topics = [node.topic];-+// If the node has children, collect topics recursivelyif (node.children && node.children.length > 0) {- for (const child of node.children) {- topics = topics.concat(collectTopics(child));- }+ for (const child of node.children) {+ topics = topics.concat(collectTopics(child));+ }}-+return topics;}--+// Start extracting from the root nodeconst topicsArray = collectTopics(mindMapcontent.nodedata);-+// Combine topics into a single stringconst topicsString = topicsArray.join(", ");--+content = normalize(topicsString.toString());- }- else if (type === 'canvas' && mime === 'application/json') {+ } else if (type === "canvas" && mime === "application/json") {interface Element {type: string;text?: string; // Optional since not all objects have a `text` propertyid: string;[key: string]: any; // Other properties that may exist}-- let canvasContent = JSON.parse (content);- const elements: Element [] = canvasContent.elements;++ let canvasContent = JSON.parse(content);+ const elements: Element[] = canvasContent.elements;const texts = elements- .filter((element: Element) => element.type === 'text' && element.text) // Filter for 'text' type elements with a 'text' property+ .filter((element: Element) => element.type === "text" && element.text) // Filter for 'text' type elements with a 'text' property.map((element: Element) => element.text!); // Use `!` to assert `text` is defined after filtering- content = normalize(texts.toString())- }-+ content = normalize(texts.toString());+ }return content.trim();}@@ -210,17 +201,17 @@ class NoteContentFulltextExp extends Expression {// we want to allow link to preserve URLs: https://github.com/zadam/trilium/issues/2412// we want to insert space in place of block tags (because they imply text separation)// but we don't want to insert text for typical formatting inline tags which can occur within one word- const linkTag = 'a';- const inlineFormattingTags = ['b', 'strong', 'em', 'i', 'span', 'big', 'small', 'font', 'sub', 'sup'];+ const linkTag = "a";+ const inlineFormattingTags = ["b", "strong", "em", "i", "span", "big", "small", "font", "sub", "sup"];// replace tags which imply text separation with a space- content = striptags(content, [linkTag, ...inlineFormattingTags], ' ');+ content = striptags(content, [linkTag, ...inlineFormattingTags], " ");// replace the inline formatting tags (but not links) without a space- content = striptags(content, [linkTag], '');+ content = striptags(content, [linkTag], "");// at least the closing link tag can be easily stripped- return content.replace(/<\/a>/ig, "");+ return content.replace(/<\/a>/gi, "");}}diff --git a/src/services/search/expressions/note_flat_text.ts b/src/services/search/expressions/note_flat_text.tsindex 17363a91cd..5e5e41f35f 100644--- a/src/services/search/expressions/note_flat_text.ts+++ b/src/services/search/expressions/note_flat_text.ts@@ -47,7 +47,7 @@ class NoteFlatTextExp extends Expression {return;}- if (note.parents.length === 0 || note.noteId === 'root') {+ if (note.parents.length === 0 || note.noteId === "root") {// we've reached root, but there are still remaining tokens -> this candidate note produced no resultreturn;}@@ -82,15 +82,14 @@ class NoteFlatTextExp extends Expression {}if (foundTokens.length > 0) {- const newRemainingTokens = remainingTokens.filter(token => !foundTokens.includes(token));+ const newRemainingTokens = remainingTokens.filter((token) => !foundTokens.includes(token));searchPathTowardsRoot(parentNote, newRemainingTokens, [note.noteId, ...takenPath]);- }- else {+ } else {searchPathTowardsRoot(parentNote, remainingTokens, [note.noteId, ...takenPath]);}}- }+ };const candidateNotes = this.getCandidateNotes(inputNoteSet);@@ -109,9 +108,7 @@ class NoteFlatTextExp extends Expression {}for (const attribute of note.ownedAttributes) {- if (normalize(attribute.name).includes(token)- || normalize(attribute.value).includes(token)) {-+ if (normalize(attribute.name).includes(token) || normalize(attribute.value).includes(token)) {foundAttrTokens.push(token);}}@@ -128,7 +125,7 @@ class NoteFlatTextExp extends Expression {}if (foundTokens.length > 0) {- const remainingTokens = this.tokens.filter(token => !foundTokens.includes(token));+ const remainingTokens = this.tokens.filter((token) => !foundTokens.includes(token));searchPathTowardsRoot(parentNote, remainingTokens, [note.noteId]);}diff --git a/src/services/search/expressions/or.ts b/src/services/search/expressions/or.tsindex 7b141129c9..10dd5dc033 100644--- a/src/services/search/expressions/or.ts+++ b/src/services/search/expressions/or.ts@@ -9,15 +9,13 @@ class OrExp extends Expression {private subExpressions: Expression[];static of(subExpressions: Expression[]) {- subExpressions = subExpressions.filter(exp => !!exp);+ subExpressions = subExpressions.filter((exp) => !!exp);if (subExpressions.length === 1) {return subExpressions[0];- }- else if (subExpressions.length > 0) {+ } else if (subExpressions.length > 0) {return new OrExp(subExpressions);- }- else {+ } else {return new TrueExp();}}diff --git a/src/services/search/expressions/order_by_and_limit.ts b/src/services/search/expressions/order_by_and_limit.tsindex 21eb31fdf8..c0cb676a70 100644--- a/src/services/search/expressions/order_by_and_limit.ts+++ b/src/services/search/expressions/order_by_and_limit.ts@@ -17,7 +17,6 @@ interface OrderDefinition {}class OrderByAndLimitExp extends Expression {-private orderDefinitions: OrderDefinition[];private limit: number;subExpression: Expression | null;@@ -42,10 +41,10 @@ class OrderByAndLimitExp extends Expression {throw new Error("Missing subexpression");}- let {notes} = this.subExpression.execute(inputNoteSet, executionContext, searchContext);+ let { notes } = this.subExpression.execute(inputNoteSet, executionContext, searchContext);notes.sort((a, b) => {- for (const {valueExtractor, smaller, larger} of this.orderDefinitions) {+ for (const { valueExtractor, smaller, larger } of this.orderDefinitions) {let valA: string | number | Date | null = valueExtractor.extract(a);let valB: string | number | Date | null = valueExtractor.extract(b);@@ -60,25 +59,20 @@ class OrderByAndLimitExp extends Expression {if (valA === null && valB === null) {// neither has attribute at allcontinue;- }- else if (valB === null) {+ } else if (valB === null) {return smaller;- }- else if (valA === null) {+ } else if (valA === null) {return larger;}-// if both are dates, then parse them for dates comparison- if (typeof valA === "string" && this.isDate(valA) &&- typeof valB === "string" && this.isDate(valB)) {+ if (typeof valA === "string" && this.isDate(valA) && typeof valB === "string" && this.isDate(valB)) {valA = new Date(valA);valB = new Date(valB);}// if both are numbers, then parse them for numerical comparison- else if (typeof valA === "string" && this.isNumber(valA) &&- typeof valB === "string" && this.isNumber(valB)) {+ else if (typeof valA === "string" && this.isNumber(valA) && typeof valB === "string" && this.isNumber(valB)) {valA = parseFloat(valA);valB = parseFloat(valB);}@@ -108,13 +102,13 @@ class OrderByAndLimitExp extends Expression {}isDate(date: number | string) {- return !isNaN(new Date(date).getTime());+ return !isNaN(new Date(date).getTime());}isNumber(x: number | string) {- if (typeof x === 'number') {+ if (typeof x === "number") {return true;- } else if (typeof x === 'string') {+ } else if (typeof x === "string") {// isNaN will return false for blank stringreturn x.trim() !== "" && !isNaN(parseInt(x, 10));} else {diff --git a/src/services/search/expressions/property_comparison.ts b/src/services/search/expressions/property_comparison.tsindex a6b072d090..a29661c478 100644--- a/src/services/search/expressions/property_comparison.ts+++ b/src/services/search/expressions/property_comparison.ts@@ -9,31 +9,31 @@ import buildComparator from "../services/build_comparator.js";* we need the case-sensitive form, so we have this translation object.*/const PROP_MAPPING: Record<string, string> = {- "noteid": "noteId",- "title": "title",- "type": "type",- "mime": "mime",- "isprotected": "isProtected",- "isarchived": "isArchived",- "datecreated": "dateCreated",- "datemodified": "dateModified",- "utcdatecreated": "utcDateCreated",- "utcdatemodified": "utcDateModified",- "parentcount": "parentCount",- "childrencount": "childrenCount",- "attributecount": "attributeCount",- "labelcount": "labelCount",- "ownedlabelcount": "ownedLabelCount",- "relationcount": "relationCount",- "ownedrelationcount": "ownedRelationCount",- "relationcountincludinglinks": "relationCountIncludingLinks",- "ownedrelationcountincludinglinks": "ownedRelationCountIncludingLinks",- "targetrelationcount": "targetRelationCount",- "targetrelationcountincludinglinks": "targetRelationCountIncludingLinks",- "contentsize": "contentSize",- "contentandattachmentssize": "contentAndAttachmentsSize",- "contentandattachmentsandrevisionssize": "contentAndAttachmentsAndRevisionsSize",- "revisioncount": "revisionCount"+ noteid: "noteId",+ title: "title",+ type: "type",+ mime: "mime",+ isprotected: "isProtected",+ isarchived: "isArchived",+ datecreated: "dateCreated",+ datemodified: "dateModified",+ utcdatecreated: "utcDateCreated",+ utcdatemodified: "utcDateModified",+ parentcount: "parentCount",+ childrencount: "childrenCount",+ attributecount: "attributeCount",+ labelcount: "labelCount",+ ownedlabelcount: "ownedLabelCount",+ relationcount: "relationCount",+ ownedrelationcount: "ownedRelationCount",+ relationcountincludinglinks: "relationCountIncludingLinks",+ ownedrelationcountincludinglinks: "ownedRelationCountIncludingLinks",+ targetrelationcount: "targetRelationCount",+ targetrelationcountincludinglinks: "targetRelationCountIncludingLinks",+ contentsize: "contentSize",+ contentandattachmentssize: "contentAndAttachmentsSize",+ contentandattachmentsandrevisionssize: "contentAndAttachmentsAndRevisionsSize",+ revisioncount: "revisionCount"};interface SearchContext {@@ -41,7 +41,6 @@ interface SearchContext {}class PropertyComparisonExp extends Expression {-private propertyName: string;private operator: string;private comparedValue: string;@@ -59,7 +58,7 @@ class PropertyComparisonExp extends Expression {this.comparedValue = comparedValue; // for DEBUG modethis.comparator = buildComparator(operator, comparedValue);- if (['contentsize', 'contentandattachmentssize', 'contentandattachmentsandrevisionssize', 'revisioncount'].includes(this.propertyName)) {+ if (["contentsize", "contentandattachmentssize", "contentandattachmentsandrevisionssize", "revisioncount"].includes(this.propertyName)) {searchContext.dbLoadNeeded = true;}}@@ -70,7 +69,7 @@ class PropertyComparisonExp extends Expression {for (const note of inputNoteSet.notes) {let value = (note as any)[this.propertyName];- if (value !== undefined && value !== null && typeof value !== 'string') {+ if (value !== undefined && value !== null && typeof value !== "string") {value = value.toString();}diff --git a/src/services/search/expressions/relation_where.ts b/src/services/search/expressions/relation_where.tsindex d973da0ce2..50d733b5ea 100644--- a/src/services/search/expressions/relation_where.ts+++ b/src/services/search/expressions/relation_where.ts@@ -19,7 +19,7 @@ class RelationWhereExp extends Expression {execute(inputNoteSet: NoteSet, executionContext: {}, searchContext: SearchContext) {const candidateNoteSet = new NoteSet();- for (const attr of becca.findAttributes('relation', this.relationName)) {+ for (const attr of becca.findAttributes("relation", this.relationName)) {const note = attr.note;if (inputNoteSet.hasNoteId(note.noteId) && attr.targetNote) {diff --git a/src/services/search/note_set.ts b/src/services/search/note_set.tsindex aa95964480..0e146cfd3b 100644--- a/src/services/search/note_set.ts+++ b/src/services/search/note_set.ts@@ -3,7 +3,6 @@import BNote from "../../becca/entities/bnote.js";class NoteSet {-private noteIdSet: Set<string>;notes: BNote[];@@ -11,7 +10,7 @@ class NoteSet {constructor(notes: BNote[] = []) {this.notes = notes;- this.noteIdSet = new Set(notes.map(note => note.noteId));+ this.noteIdSet = new Set(notes.map((note) => note.noteId));this.sorted = false;}diff --git a/src/services/search/search_context.ts b/src/services/search/search_context.tsindex 8e6fdb5957..1b96e7474c 100644--- a/src/services/search/search_context.ts+++ b/src/services/search/search_context.ts@@ -1,10 +1,9 @@"use strict";import hoistedNoteService from "../hoisted_note.js";-import { SearchParams } from './services/types.js';+import { SearchParams } from "./services/types.js";class SearchContext {-fastSearch: boolean;includeArchivedNotes: boolean;includeHiddenNotes: boolean;diff --git a/src/services/search/search_result.ts b/src/services/search/search_result.tsindex 3e26080610..34a52612d2 100644--- a/src/services/search/search_result.ts+++ b/src/services/search/search_result.ts@@ -16,7 +16,7 @@ class SearchResult {}get notePath() {- return this.notePathArray.join('/');+ return this.notePathArray.join("/");}get noteId() {@@ -38,18 +38,14 @@ class SearchResult {// Title matching scores, make sure to always winif (normalizedTitle === normalizedQuery) {this.score += 2000; // Increased from 1000 to ensure exact matches always win- }- else if (normalizedTitle.startsWith(normalizedQuery)) {- this.score += 500; // Increased to give more weight to prefix matches- }- else if (normalizedTitle.includes(` ${normalizedQuery} `) ||- normalizedTitle.startsWith(`${normalizedQuery} `) ||- normalizedTitle.endsWith(` ${normalizedQuery}`)) {- this.score += 300; // Increased to better distinguish word matches+ } else if (normalizedTitle.startsWith(normalizedQuery)) {+ this.score += 500; // Increased to give more weight to prefix matches+ } else if (normalizedTitle.includes(` ${normalizedQuery} `) || normalizedTitle.startsWith(`${normalizedQuery} `) || normalizedTitle.endsWith(` ${normalizedQuery}`)) {+ this.score += 300; // Increased to better distinguish word matches}// Add scores for partial matches with adjusted weights- this.addScoreForStrings(tokens, note.title, 2.0); // Increased to give more weight to title matches+ this.addScoreForStrings(tokens, note.title, 2.0); // Increased to give more weight to title matchesthis.addScoreForStrings(tokens, this.notePathTitle, 0.3); // Reduced to further de-emphasize path matchesif (note.isInHiddenSubtree()) {diff --git a/src/services/search/services/build_comparator.ts b/src/services/search/services/build_comparator.tsindex c43de1ee39..752ad8ff44 100644--- a/src/services/search/services/build_comparator.ts+++ b/src/services/search/services/build_comparator.ts@@ -8,26 +8,26 @@ function getRegex(str: string) {return cachedRegexes[str];}-type Comparator<T> = (comparedValue: T) => ((val: string) => boolean);+type Comparator<T> = (comparedValue: T) => (val: string) => boolean;const stringComparators: Record<string, Comparator<string>> = {- "=": comparedValue => (val => val === comparedValue),- "!=": comparedValue => (val => val !== comparedValue),- ">": comparedValue => (val => val > comparedValue),- ">=": comparedValue => (val => val >= comparedValue),- "<": comparedValue => (val => val < comparedValue),- "<=": comparedValue => (val => val <= comparedValue),- "*=": comparedValue => (val => !!val && val.endsWith(comparedValue)),- "=*": comparedValue => (val => !!val && val.startsWith(comparedValue)),- "*=*": comparedValue => (val => !!val && val.includes(comparedValue)),- "%=": comparedValue => (val => !!val && !!getRegex(comparedValue).test(val)),+ "=": (comparedValue) => (val) => val === comparedValue,+ "!=": (comparedValue) => (val) => val !== comparedValue,+ ">": (comparedValue) => (val) => val > comparedValue,+ ">=": (comparedValue) => (val) => val >= comparedValue,+ "<": (comparedValue) => (val) => val < comparedValue,+ "<=": (comparedValue) => (val) => val <= comparedValue,+ "*=": (comparedValue) => (val) => !!val && val.endsWith(comparedValue),+ "=*": (comparedValue) => (val) => !!val && val.startsWith(comparedValue),+ "*=*": (comparedValue) => (val) => !!val && val.includes(comparedValue),+ "%=": (comparedValue) => (val) => !!val && !!getRegex(comparedValue).test(val)};const numericComparators: Record<string, Comparator<number>> = {- ">": comparedValue => (val => parseFloat(val) > comparedValue),- ">=": comparedValue => (val => parseFloat(val) >= comparedValue),- "<": comparedValue => (val => parseFloat(val) < comparedValue),- "<=": comparedValue => (val => parseFloat(val) <= comparedValue)+ ">": (comparedValue) => (val) => parseFloat(val) > comparedValue,+ ">=": (comparedValue) => (val) => parseFloat(val) >= comparedValue,+ "<": (comparedValue) => (val) => parseFloat(val) < comparedValue,+ "<=": (comparedValue) => (val) => parseFloat(val) <= comparedValue};function buildComparator(operator: string, comparedValue: string) {diff --git a/src/services/search/services/handle_parens.ts b/src/services/search/services/handle_parens.tsindex 3ce0d1fd3b..63deed2d18 100644--- a/src/services/search/services/handle_parens.ts+++ b/src/services/search/services/handle_parens.ts@@ -9,28 +9,28 @@ function handleParens(tokens: TokenStructure) {}while (true) {- const leftIdx = tokens.findIndex(token => "token" in token && token.token === '(');+ const leftIdx = tokens.findIndex((token) => "token" in token && token.token === "(");if (leftIdx === -1) {return tokens;}let rightIdx;- let parensLevel = 0+ let parensLevel = 0;for (rightIdx = leftIdx; rightIdx < tokens.length; rightIdx++) {const token = tokens[rightIdx];if (!("token" in token)) {continue;}-- if (token.token === ')') {++ if (token.token === ")") {parensLevel--;if (parensLevel === 0) {break;}- } else if (token.token === '(') {+ } else if (token.token === "(") {parensLevel++;}}@@ -39,11 +39,7 @@ function handleParens(tokens: TokenStructure) {throw new Error("Did not find matching right parenthesis.");}- tokens = [- ...tokens.slice(0, leftIdx),- handleParens(tokens.slice(leftIdx + 1, rightIdx)),- ...tokens.slice(rightIdx + 1)- ] as (TokenData | TokenData[])[];+ tokens = [...tokens.slice(0, leftIdx), handleParens(tokens.slice(leftIdx + 1, rightIdx)), ...tokens.slice(rightIdx + 1)] as (TokenData | TokenData[])[];}}diff --git a/src/services/search/services/lex.ts b/src/services/search/services/lex.tsindex 3adfcdc567..3247e0fda5 100644--- a/src/services/search/services/lex.ts+++ b/src/services/search/services/lex.ts@@ -9,23 +9,22 @@ function lex(str: string) {let quotes: boolean | string = false; // otherwise contains used quote - ', " or `let fulltextEnded = false;- let currentWord = '';+ let currentWord = "";function isSymbolAnOperator(chr: string) {- return ['=', '*', '>', '<', '!', "-", "+", '%', ','].includes(chr);+ return ["=", "*", ">", "<", "!", "-", "+", "%", ","].includes(chr);}function isPreviousSymbolAnOperator() {if (currentWord.length === 0) {return false;- }- else {+ } else {return isSymbolAnOperator(currentWord[currentWord.length - 1]);}}function finishWord(endIndex: number, createAlsoForEmptyWords = false) {- if (currentWord === '' && !createAlsoForEmptyWords) {+ if (currentWord === "" && !createAlsoForEmptyWords) {return;}@@ -44,84 +43,70 @@ function lex(str: string) {fulltextQuery = str.substr(0, endIndex + 1);}- currentWord = '';+ currentWord = "";}for (let i = 0; i < str.length; i++) {const chr = str[i];- if (chr === '\\') {+ if (chr === "\\") {if (i + 1 < str.length) {i++;currentWord += str[i];- }- else {+ } else {currentWord += chr;}continue;- }- else if (['"', "'", '`'].includes(chr)) {+ } else if (['"', "'", "`"].includes(chr)) {if (!quotes) {if (currentWord.length === 0 || isPreviousSymbolAnOperator()) {finishWord(i - 1);quotes = chr;- }- else {+ } else {// quote inside a word does not have special meening and does not break word// e.g. d'Artagnan is kept as a single tokencurrentWord += chr;}- }- else if (quotes === chr) {+ } else if (quotes === chr) {finishWord(i - 1, true);quotes = false;- }- else {+ } else {// it's a quote, but within other kind of quotes, so it's valid as a literal charactercurrentWord += chr;}continue;- }- else if (!quotes) {- if (!fulltextEnded && currentWord === 'note' && chr === '.' && i + 1 < str.length) {+ } else if (!quotes) {+ if (!fulltextEnded && currentWord === "note" && chr === "." && i + 1 < str.length) {fulltextEnded = true;}- if (chr === '#' || chr === '~') {+ if (chr === "#" || chr === "~") {if (!fulltextEnded) {fulltextEnded = true;- }- else {+ } else {finishWord(i - 1);}currentWord = chr;continue;- }- else if (['#', '~'].includes(currentWord) && chr === '!') {+ } else if (["#", "~"].includes(currentWord) && chr === "!") {currentWord += chr;continue;- }- else if (chr === ' ') {+ } else if (chr === " ") {finishWord(i - 1);continue;- }- else if (fulltextEnded && ['(', ')', '.'].includes(chr)) {+ } else if (fulltextEnded && ["(", ")", "."].includes(chr)) {finishWord(i - 1);currentWord += chr;finishWord(i);continue;- }- else if (fulltextEnded- && !['#!', '~!'].includes(currentWord)- && isPreviousSymbolAnOperator() !== isSymbolAnOperator(chr)) {-+ } else if (fulltextEnded && !["#!", "~!"].includes(currentWord) && isPreviousSymbolAnOperator() !== isSymbolAnOperator(chr)) {finishWord(i - 1);currentWord += chr;@@ -129,7 +114,7 @@ function lex(str: string) {}}- if (chr === ',') {+ if (chr === ",") {continue;}@@ -144,7 +129,7 @@ function lex(str: string) {fulltextQuery,fulltextTokens,expressionTokens- }+ };}export default lex;diff --git a/src/services/search/services/parse.ts b/src/services/search/services/parse.tsindex 5cd408d6b1..38c08c6920 100644--- a/src/services/search/services/parse.ts+++ b/src/services/search/services/parse.ts@@ -25,7 +25,7 @@ import { TokenData, TokenStructure } from "./types.js";import Expression from "../expressions/expression.js";function getFulltext(_tokens: TokenData[], searchContext: SearchContext) {- const tokens: string[] = _tokens.map(t => removeDiacritic(t.token));+ const tokens: string[] = _tokens.map((t) => removeDiacritic(t.token));searchContext.highlightedTokens.push(...tokens);@@ -34,28 +34,13 @@ function getFulltext(_tokens: TokenData[], searchContext: SearchContext) {}if (!searchContext.fastSearch) {- return new OrExp([- new NoteFlatTextExp(tokens),- new NoteContentFulltextExp('*=*', {tokens, flatText: true})- ]);- }- else {+ return new OrExp([new NoteFlatTextExp(tokens), new NoteContentFulltextExp("*=*", { tokens, flatText: true })]);+ } else {return new NoteFlatTextExp(tokens);}}-const OPERATORS = new Set([- "=",- "!=",- "*=*",- "*=",- "=*",- ">",- ">=",- "<",- "<=",- "%="-]);+const OPERATORS = new Set(["=", "!=", "*=*", "*=", "=*", ">", ">=", "<", "<=", "%="]);function isOperator(token: TokenData) {if (Array.isArray(token)) {@@ -76,7 +61,7 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levellet i: number;function context(i: number) {- let {startIndex, endIndex} = tokens[i];+ let { startIndex, endIndex } = tokens[i];startIndex = Math.max(0, (startIndex || 0) - 20);endIndex = Math.min(searchContext.originalQuery.length, (endIndex || Number.MAX_SAFE_INTEGER) + 20);@@ -86,8 +71,7 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levelconst resolveConstantOperand = () => {const operand = tokens[i];- if (!operand.inQuotes- && (operand.token.startsWith('#') || operand.token.startsWith('~') || operand.token === 'note')) {+ if (!operand.inQuotes && (operand.token.startsWith("#") || operand.token.startsWith("~") || operand.token === "note")) {searchContext.addError(`Error near token "${operand.token}" in ${context(i)}, it's possible to compare with constant only.`);return null;}@@ -99,12 +83,11 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levellet delta = 0;if (i + 2 < tokens.length) {- if (tokens[i + 1].token === '+') {+ if (tokens[i + 1].token === "+") {i += 2;delta += parseInt(tokens[i].token);- }- else if (tokens[i + 1].token === '-') {+ } else if (tokens[i + 1].token === "-") {i += 2;delta -= parseInt(tokens[i].token);@@ -113,39 +96,35 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levellet format, date;- if (operand.token === 'now') {- date = dayjs().add(delta, 'second');+ if (operand.token === "now") {+ date = dayjs().add(delta, "second");format = "YYYY-MM-DD HH:mm:ss";- }- else if (operand.token === 'today') {- date = dayjs().add(delta, 'day');+ } else if (operand.token === "today") {+ date = dayjs().add(delta, "day");format = "YYYY-MM-DD";- }- else if (operand.token === 'month') {- date = dayjs().add(delta, 'month');+ } else if (operand.token === "month") {+ date = dayjs().add(delta, "month");format = "YYYY-MM";- }- else if (operand.token === 'year') {- date = dayjs().add(delta, 'year');+ } else if (operand.token === "year") {+ date = dayjs().add(delta, "year");format = "YYYY";- }- else {+ } else {throw new Error(`Unrecognized keyword: ${operand.token}`);}return date.format(format);- }+ };const parseNoteProperty: () => Expression | undefined | null = () => {- if (tokens[i].token !== '.') {+ if (tokens[i].token !== ".") {searchContext.addError('Expected "." to separate field path');return;}i++;- if (['content', 'rawcontent'].includes(tokens[i].token)) {- const raw = tokens[i].token === 'rawcontent';+ if (["content", "rawcontent"].includes(tokens[i].token)) {+ const raw = tokens[i].token === "rawcontent";i += 1;@@ -158,35 +137,41 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, leveli++;- return new NoteContentFulltextExp(operator.token, {tokens: [tokens[i].token], raw});+ return new NoteContentFulltextExp(operator.token, { tokens: [tokens[i].token], raw });}- if (tokens[i].token === 'parents') {+ if (tokens[i].token === "parents") {i += 1;const expression = parseNoteProperty();- if (!expression) { return; }+ if (!expression) {+ return;+ }return new ChildOfExp(expression);}- if (tokens[i].token === 'children') {+ if (tokens[i].token === "children") {i += 1;const expression = parseNoteProperty();- if (!expression) { return; }+ if (!expression) {+ return;+ }return new ParentOfExp(expression);}- if (tokens[i].token === 'ancestors') {+ if (tokens[i].token === "ancestors") {i += 1;const expression = parseNoteProperty();- if (!expression) { return; }+ if (!expression) {+ return;+ }return new DescendantOfExp(expression);}- if (tokens[i].token === 'labels') {- if (tokens[i + 1].token !== '.') {+ if (tokens[i].token === "labels") {+ if (tokens[i + 1].token !== ".") {searchContext.addError(`Expected "." to separate field path, got "${tokens[i + 1].token}" in ${context(i)}`);return;}@@ -196,8 +181,8 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levelreturn parseLabel(tokens[i].token);}- if (tokens[i].token === 'relations') {- if (tokens[i + 1].token !== '.') {+ if (tokens[i].token === "relations") {+ if (tokens[i + 1].token !== ".") {searchContext.addError(`Expected "." to separate field path, got "${tokens[i + 1].token}" in ${context(i)}`);return;}@@ -207,18 +192,15 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levelreturn parseRelation(tokens[i].token);}- if (tokens[i].token === 'text') {- if (tokens[i + 1].token !== '*=*') {+ if (tokens[i].token === "text") {+ if (tokens[i + 1].token !== "*=*") {searchContext.addError(`Virtual attribute "note.text" supports only *=* operator, instead given "${tokens[i + 1].token}" in ${context(i)}`);return;}i += 2;- return new OrExp([- new PropertyComparisonExp(searchContext, 'title', '*=*', tokens[i].token),- new NoteContentFulltextExp('*=*', {tokens: [tokens[i].token]})- ]);+ return new OrExp([new PropertyComparisonExp(searchContext, "title", "*=*", tokens[i].token), new NoteContentFulltextExp("*=*", { tokens: [tokens[i].token] })]);}if (PropertyComparisonExp.isProperty(tokens[i].token)) {@@ -237,14 +219,14 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, level}searchContext.addError(`Unrecognized note property "${tokens[i].token}" in ${context(i)}`);- }+ };function parseAttribute(name: string) {- const isLabel = name.startsWith('#');+ const isLabel = name.startsWith("#");name = name.substr(1);- const isNegated = name.startsWith('!');+ const isNegated = name.startsWith("!");if (isNegated) {name = name.substr(1);@@ -271,8 +253,8 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levelsearchContext.highlightedTokens.push(comparedValue);- if (searchContext.fuzzyAttributeSearch && operator === '=') {- operator = '*=*';+ if (searchContext.fuzzyAttributeSearch && operator === "=") {+ operator = "*=*";}const comparator = buildComparator(operator, comparedValue);@@ -280,41 +262,41 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levelif (!comparator) {searchContext.addError(`Can't find operator '${operator}' in ${context(i - 1)}`);} else {- return new LabelComparisonExp('label', labelName, comparator);+ return new LabelComparisonExp("label", labelName, comparator);}} else {- return new AttributeExistsExp('label', labelName, searchContext.fuzzyAttributeSearch);+ return new AttributeExistsExp("label", labelName, searchContext.fuzzyAttributeSearch);}}function parseRelation(relationName: string) {searchContext.highlightedTokens.push(relationName);- if (i < tokens.length - 2 && tokens[i + 1].token === '.') {+ if (i < tokens.length - 2 && tokens[i + 1].token === ".") {i += 1;const expression = parseNoteProperty();- if (!expression) { return; }+ if (!expression) {+ return;+ }return new RelationWhereExp(relationName, expression);- }- else if (i < tokens.length - 2 && isOperator(tokens[i + 1])) {+ } else if (i < tokens.length - 2 && isOperator(tokens[i + 1])) {searchContext.addError(`Relation can be compared only with property, e.g. ~relation.title=hello in ${context(i)}`);return null;- }- else {- return new AttributeExistsExp('relation', relationName, searchContext.fuzzyAttributeSearch);+ } else {+ return new AttributeExistsExp("relation", relationName, searchContext.fuzzyAttributeSearch);}}function parseOrderByAndLimit() {const orderDefinitions: {- valueExtractor: ValueExtractor,- direction: string+ valueExtractor: ValueExtractor;+ direction: string;}[] = [];let limit;- if (tokens[i].token === 'orderby') {+ if (tokens[i].token === "orderby") {do {const propertyPath = [];let direction = "asc";@@ -325,7 +307,7 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levelpropertyPath.push(tokens[i].token);i++;- } while (i < tokens.length && tokens[i].token === '.');+ } while (i < tokens.length && tokens[i].token === ".");if (i < tokens.length && ["asc", "desc"].includes(tokens[i].token)) {direction = tokens[i].token;@@ -343,10 +325,10 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levelvalueExtractor,direction});- } while (i < tokens.length && tokens[i].token === ',');+ } while (i < tokens.length && tokens[i].token === ",");}- if (i < tokens.length && tokens[i].token === 'limit') {+ if (i < tokens.length && tokens[i].token === "limit") {limit = parseInt(tokens[i + 1].token);}@@ -354,13 +336,11 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, level}function getAggregateExpression() {- if (op === null || op === 'and') {+ if (op === null || op === "and") {return AndExp.of(expressions);- }- else if (op === 'or') {+ } else if (op === "or") {return OrExp.of(expressions);- }- else {+ } else {throw new Error(`Unrecognized op=${op}`);}}@@ -376,19 +356,18 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levelconst token = tokens[i].token;- if (token === '#' || token === '~') {+ if (token === "#" || token === "~") {continue;}- if (token.startsWith('#') || token.startsWith('~')) {+ if (token.startsWith("#") || token.startsWith("~")) {const attribute = parseAttribute(token);if (attribute) {expressions.push(attribute);}- }- else if (['orderby', 'limit'].includes(token)) {+ } else if (["orderby", "limit"].includes(token)) {if (level !== 0) {- searchContext.addError('orderBy can appear only on the top expression level');+ searchContext.addError("orderBy can appear only on the top expression level");continue;}@@ -400,8 +379,7 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levelexp.subExpression = getAggregateExpression();return exp;- }- else if (token === 'not') {+ } else if (token === "not") {i += 1;if (!Array.isArray(tokens[i])) {@@ -411,53 +389,46 @@ function getExpression(tokens: TokenData[], searchContext: SearchContext, levelconst tokenArray = tokens[i] as unknown as TokenData[];const expression = getExpression(tokenArray, searchContext, level++);- if (!expression) { return; }+ if (!expression) {+ return;+ }expressions.push(new NotExp(expression));- }- else if (token === 'note') {+ } else if (token === "note") {i++;const expression = parseNoteProperty();- if (!expression) { return; }+ if (!expression) {+ return;+ }expressions.push(expression);continue;- }- else if (['and', 'or'].includes(token)) {+ } else if (["and", "or"].includes(token)) {if (!op) {op = token;+ } else if (op !== token) {+ searchContext.addError("Mixed usage of AND/OR - always use parenthesis to group AND/OR expressions.");}- else if (op !== token) {- searchContext.addError('Mixed usage of AND/OR - always use parenthesis to group AND/OR expressions.');- }- }- else if (isOperator({token: token})) {+ } else if (isOperator({ token: token })) {searchContext.addError(`Misplaced or incomplete expression "${token}"`);- }- else {+ } else {searchContext.addError(`Unrecognized expression "${token}"`);}if (!op && expressions.length > 1) {- op = 'and';+ op = "and";}}return getAggregateExpression();}-function parse({fulltextTokens, expressionTokens, searchContext}: {- fulltextTokens: TokenData[],- expressionTokens: TokenStructure,- searchContext: SearchContext,- originalQuery: string-}) {+function parse({ fulltextTokens, expressionTokens, searchContext }: { fulltextTokens: TokenData[]; expressionTokens: TokenStructure; searchContext: SearchContext; originalQuery: string }) {let expression: Expression | undefined | null;try {expression = getExpression(expressionTokens as TokenData[], searchContext);- }- catch (e: any) {+ } catch (e: any) {searchContext.addError(e.message);expression = new TrueExp();@@ -470,13 +441,18 @@ function parse({fulltextTokens, expressionTokens, searchContext}: {expression]);- if (searchContext.orderBy && searchContext.orderBy !== 'relevancy') {+ if (searchContext.orderBy && searchContext.orderBy !== "relevancy") {const filterExp = exp;- exp = new OrderByAndLimitExp([{- valueExtractor: new ValueExtractor(searchContext, ['note', searchContext.orderBy]),- direction: searchContext.orderDirection- }], searchContext.limit || undefined);+ exp = new OrderByAndLimitExp(+ [+ {+ valueExtractor: new ValueExtractor(searchContext, ["note", searchContext.orderBy]),+ direction: searchContext.orderDirection+ }+ ],+ searchContext.limit || undefined+ );(exp as any).subExpression = filterExp;}@@ -484,8 +460,8 @@ function parse({fulltextTokens, expressionTokens, searchContext}: {return exp;}-function getAncestorExp({ancestorNoteId, ancestorDepth, includeHiddenNotes}: SearchContext) {- if (ancestorNoteId && ancestorNoteId !== 'root') {+function getAncestorExp({ ancestorNoteId, ancestorDepth, includeHiddenNotes }: SearchContext) {+ if (ancestorNoteId && ancestorNoteId !== "root") {return new AncestorExp(ancestorNoteId, ancestorDepth);} else if (!includeHiddenNotes) {return new NotExp(new IsHiddenExp());diff --git a/src/services/search/services/search.ts b/src/services/search/services/search.tsindex 663851325d..586f42c01c 100644--- a/src/services/search/services/search.ts+++ b/src/services/search/services/search.ts@@ -34,28 +34,27 @@ function searchFromNote(note: BNote): SearchNoteResult {let searchResultNoteIds;let highlightedTokens: string[];- const searchScript = note.getRelationValue('searchScript');- const searchString = note.getLabelValue('searchString') || "";+ const searchScript = note.getRelationValue("searchScript");+ const searchString = note.getLabelValue("searchString") || "";let error = null;if (searchScript) {- searchResultNoteIds = searchFromRelation(note, 'searchScript');+ searchResultNoteIds = searchFromRelation(note, "searchScript");highlightedTokens = [];} else {const searchContext = new SearchContext({- fastSearch: note.hasLabel('fastSearch'),- ancestorNoteId: note.getRelationValue('ancestor') || undefined,- ancestorDepth: note.getLabelValue('ancestorDepth') || undefined,- includeArchivedNotes: note.hasLabel('includeArchivedNotes'),- orderBy: note.getLabelValue('orderBy') || undefined,- orderDirection: note.getLabelValue('orderDirection') || undefined,- limit: parseInt(note.getLabelValue('limit') || "0", 10),- debug: note.hasLabel('debug'),+ fastSearch: note.hasLabel("fastSearch"),+ ancestorNoteId: note.getRelationValue("ancestor") || undefined,+ ancestorDepth: note.getLabelValue("ancestorDepth") || undefined,+ includeArchivedNotes: note.hasLabel("includeArchivedNotes"),+ orderBy: note.getLabelValue("orderBy") || undefined,+ orderDirection: note.getLabelValue("orderDirection") || undefined,+ limit: parseInt(note.getLabelValue("limit") || "0", 10),+ debug: note.hasLabel("debug"),fuzzyAttributeSearch: false});- searchResultNoteIds = findResultsWithQuery(searchString, searchContext)- .map(sr => sr.noteId);+ searchResultNoteIds = findResultsWithQuery(searchString, searchContext).map((sr) => sr.noteId);highlightedTokens = searchContext.highlightedTokens;error = searchContext.getError();@@ -64,7 +63,7 @@ function searchFromNote(note: BNote): SearchNoteResult {// we won't return search note's own noteId// also don't allow root since that would force infinite cyclereturn {- searchResultNoteIds: searchResultNoteIds.filter(resultNoteId => !['root', note.noteId].includes(resultNoteId)),+ searchResultNoteIds: searchResultNoteIds.filter((resultNoteId) => !["root", note.noteId].includes(resultNoteId)),highlightedTokens,error: error};@@ -79,7 +78,7 @@ function searchFromRelation(note: BNote, relationName: string) {return [];}- if (!scriptNote.isJavaScript() || scriptNote.getScriptEnv() !== 'backend') {+ if (!scriptNote.isJavaScript() || scriptNote.getScriptEnv() !== "backend") {log.info(`Note ${scriptNote.noteId} is not executable.`);return [];@@ -91,7 +90,7 @@ function searchFromRelation(note: BNote, relationName: string) {return [];}- const result = scriptService.executeNote(scriptNote, {originEntity: note});+ const result = scriptService.executeNote(scriptNote, { originEntity: note });if (!Array.isArray(result)) {log.info(`Result from ${scriptNote.noteId} is not an array.`);@@ -104,7 +103,7 @@ function searchFromRelation(note: BNote, relationName: string) {}// we expect either array of noteIds (strings) or notes, in that case we extract noteIds ourselves- return typeof result[0] === 'string' ? result : result.map(item => item.noteId);+ return typeof result[0] === "string" ? result : result.map((item) => item.noteId);}function loadNeededInfoFromDatabase() {@@ -131,7 +130,7 @@ function loadNeededInfoFromDatabase() {JOIN blobs USING(blobId)WHERE notes.isDeleted = 0`);- for (const {noteId, blobId, length} of noteContentLengths) {+ for (const { noteId, blobId, length } of noteContentLengths) {if (!(noteId in becca.notes)) {log.error(`Note '${noteId}' not found in becca.`);continue;@@ -159,7 +158,7 @@ function loadNeededInfoFromDatabase() {WHERE attachments.isDeleted = 0AND notes.isDeleted = 0`);- for (const {noteId, blobId, length} of attachmentContentLengths) {+ for (const { noteId, blobId, length } of attachmentContentLengths) {if (!(noteId in becca.notes)) {log.error(`Note '${noteId}' not found in becca.`);continue;@@ -205,7 +204,7 @@ function loadNeededInfoFromDatabase() {JOIN blobs ON attachments.blobId = blobs.blobIdWHERE notes.isDeleted = 0`);- for (const {noteId, blobId, length, isNoteRevision} of revisionContentLengths) {+ for (const { noteId, blobId, length, isNoteRevision } of revisionContentLengths) {if (!(noteId in becca.notes)) {log.error(`Note '${noteId}' not found in becca.`);continue;@@ -218,7 +217,7 @@ function loadNeededInfoFromDatabase() {noteBlobs[noteId][blobId] = length;- if (isNoteRevision) {+ if (isNoteRevision) {const noteRevision = becca.notes[noteId];if (noteRevision && noteRevision.revisionCount) {noteRevision.revisionCount++;@@ -245,16 +244,15 @@ function findResultsWithExpression(expression: Expression, searchContext: Searchconst noteSet = expression.execute(allNoteSet, executionContext, searchContext);- const searchResults = noteSet.notes- .map(note => {- const notePathArray = executionContext.noteIdToNotePath[note.noteId] || note.getBestNotePath();+ const searchResults = noteSet.notes.map((note) => {+ const notePathArray = executionContext.noteIdToNotePath[note.noteId] || note.getBestNotePath();- if (!notePathArray) {- throw new Error(`Can't find note path for note ${JSON.stringify(note.getPojo())}`);- }+ if (!notePathArray) {+ throw new Error(`Can't find note path for note ${JSON.stringify(note.getPojo())}`);+ }- return new SearchResult(notePathArray);- });+ return new SearchResult(notePathArray);+ });for (const res of searchResults) {res.computeScore(searchContext.fulltextQuery, searchContext.highlightedTokens);@@ -282,15 +280,14 @@ function findResultsWithExpression(expression: Expression, searchContext: Search}function parseQueryToExpression(query: string, searchContext: SearchContext) {- const {fulltextQuery, fulltextTokens, expressionTokens} = lex(query);+ const { fulltextQuery, fulltextTokens, expressionTokens } = lex(query);searchContext.fulltextQuery = fulltextQuery;let structuredExpressionTokens: TokenStructure;try {structuredExpressionTokens = handleParens(expressionTokens);- }- catch (e: any) {+ } catch (e: any) {structuredExpressionTokens = [];searchContext.addError(e.message);}@@ -318,7 +315,7 @@ function parseQueryToExpression(query: string, searchContext: SearchContext) {function searchNotes(query: string, params: SearchParams = {}): BNote[] {const searchResults = findResultsWithQuery(query, new SearchContext(params));- return searchResults.map(sr => becca.notes[sr.noteId]);+ return searchResults.map((sr) => becca.notes[sr.noteId]);}function findResultsWithQuery(query: string, searchContext: SearchContext): SearchResult[] {@@ -347,9 +344,7 @@ function searchNotesForAutocomplete(query: string, fastSearch: boolean = true) {includeHiddenNotes: true,fuzzyAttributeSearch: true,ignoreInternalAttributes: true,- ancestorNoteId: hoistedNoteService.isHoistedInHiddenSubtree()- ? 'root'- : hoistedNoteService.getHoistedNoteId()+ ancestorNoteId: hoistedNoteService.isHoistedInHiddenSubtree() ? "root" : hoistedNoteService.getHoistedNoteId()});const allSearchResults = findResultsWithQuery(query, searchContext);@@ -358,7 +353,7 @@ function searchNotesForAutocomplete(query: string, fastSearch: boolean = true) {highlightSearchResults(trimmed, searchContext.highlightedTokens, searchContext.ignoreInternalAttributes);- return trimmed.map(result => {+ return trimmed.map((result) => {return {notePath: result.notePath,noteTitle: beccaService.getNoteTitle(result.noteId),@@ -378,23 +373,21 @@ function highlightSearchResults(searchResults: SearchResult[], highlightedTokens// which would make the resulting HTML string invalid.// { and } are used for marking <b> and </b> tag (to avoid matches on single 'b' character)// < and > are used for marking <small> and </small>- highlightedTokens = highlightedTokens- .map(token => token.replace('/[<\{\}]/g', ''))- .filter(token => !!token?.trim());+ highlightedTokens = highlightedTokens.map((token) => token.replace("/[<\{\}]/g", "")).filter((token) => !!token?.trim());// sort by the longest, so we first highlight the longest matches- highlightedTokens.sort((a, b) => a.length > b.length ? -1 : 1);+ highlightedTokens.sort((a, b) => (a.length > b.length ? -1 : 1));for (const result of searchResults) {const note = becca.notes[result.noteId];- result.highlightedNotePathTitle = result.notePathTitle.replace(/[<{}]/g, '');+ result.highlightedNotePathTitle = result.notePathTitle.replace(/[<{}]/g, "");- if (highlightedTokens.find(token => note.type.includes(token))) {+ if (highlightedTokens.find((token) => note.type.includes(token))) {result.highlightedNotePathTitle += ` "type: ${note.type}'`;}- if (highlightedTokens.find(token => note.mime.includes(token))) {+ if (highlightedTokens.find((token) => note.mime.includes(token))) {result.highlightedNotePathTitle += ` "mime: ${note.mime}'`;}@@ -403,9 +396,7 @@ function highlightSearchResults(searchResults: SearchResult[], highlightedTokenscontinue;}- if (highlightedTokens.find(token => normalize(attr.name).includes(token)- || normalize(attr.value).includes(token))) {-+ if (highlightedTokens.find((token) => normalize(attr.name).includes(token) || normalize(attr.value).includes(token))) {result.highlightedNotePathTitle += ` "${formatAttribute(attr)}'`;}}@@ -427,7 +418,9 @@ function highlightSearchResults(searchResults: SearchResult[], highlightedTokenslet match;// Find all matches- if (!result.highlightedNotePathTitle) { continue; }+ if (!result.highlightedNotePathTitle) {+ continue;+ }while ((match = tokenRegex.exec(normalizeString(result.highlightedNotePathTitle))) !== null) {result.highlightedNotePathTitle = wrapText(result.highlightedNotePathTitle, match.index, token.length, "{", "}");@@ -438,20 +431,17 @@ function highlightSearchResults(searchResults: SearchResult[], highlightedTokens}for (const result of searchResults) {- if (!result.highlightedNotePathTitle) { continue; }- result.highlightedNotePathTitle = result.highlightedNotePathTitle- .replace(/"/g, "<small>")- .replace(/'/g, "</small>")- .replace(/{/g, "<b>")- .replace(/}/g, "</b>");+ if (!result.highlightedNotePathTitle) {+ continue;+ }+ result.highlightedNotePathTitle = result.highlightedNotePathTitle.replace(/"/g, "<small>").replace(/'/g, "</small>").replace(/{/g, "<b>").replace(/}/g, "</b>");}}function formatAttribute(attr: BAttribute) {- if (attr.type === 'relation') {+ if (attr.type === "relation") {return `~${escapeHtml(attr.name)}=…`;- }- else if (attr.type === 'label') {+ } else if (attr.type === "label") {let label = `#${escapeHtml(attr.name)}`;if (attr.value) {diff --git a/src/services/search/services/types.ts b/src/services/search/services/types.tsindex 47e641d37f..7edc3b4ae5 100644--- a/src/services/search/services/types.ts+++ b/src/services/search/services/types.ts@@ -21,4 +21,4 @@ export interface SearchParams {limit?: number | null;debug?: boolean;fuzzyAttributeSearch?: boolean;-}\ No newline at end of file+}diff --git a/src/services/search/value_extractor.ts b/src/services/search/value_extractor.tsindex a6df8fedac..531d68c099 100644--- a/src/services/search/value_extractor.ts+++ b/src/services/search/value_extractor.ts@@ -7,31 +7,31 @@ import BNote from "../../becca/entities/bnote.js";* we need a case-sensitive form, so we have this translation object.*/const PROP_MAPPING: Record<string, string> = {- "noteid": "noteId",- "title": "title",- "type": "type",- "mime": "mime",- "isprotected": "isProtected",- "isarchived": "isArchived",- "datecreated": "dateCreated",- "datemodified": "dateModified",- "utcdatecreated": "utcDateCreated",- "utcdatemodified": "utcDateModified",- "parentcount": "parentCount",- "childrencount": "childrenCount",- "attributecount": "attributeCount",- "labelcount": "labelCount",- "ownedlabelcount": "ownedLabelCount",- "relationcount": "relationCount",- "ownedrelationcount": "ownedRelationCount",- "relationcountincludinglinks": "relationCountIncludingLinks",- "ownedrelationcountincludinglinks": "ownedRelationCountIncludingLinks",- "targetrelationcount": "targetRelationCount",- "targetrelationcountincludinglinks": "targetRelationCountIncludingLinks",- "contentsize": "contentSize",- "contentandattachmentssize": "contentAndAttachmentsSize",- "contentandattachmentsandrevisionssize": "contentAndAttachmentsAndRevisionsSize",- "revisioncount": "revisionCount"+ noteid: "noteId",+ title: "title",+ type: "type",+ mime: "mime",+ isprotected: "isProtected",+ isarchived: "isArchived",+ datecreated: "dateCreated",+ datemodified: "dateModified",+ utcdatecreated: "utcDateCreated",+ utcdatemodified: "utcDateModified",+ parentcount: "parentCount",+ childrencount: "childrenCount",+ attributecount: "attributeCount",+ labelcount: "labelCount",+ ownedlabelcount: "ownedLabelCount",+ relationcount: "relationCount",+ ownedrelationcount: "ownedRelationCount",+ relationcountincludinglinks: "relationCountIncludingLinks",+ ownedrelationcountincludinglinks: "ownedRelationCountIncludingLinks",+ targetrelationcount: "targetRelationCount",+ targetrelationcountincludinglinks: "targetRelationCountIncludingLinks",+ contentsize: "contentSize",+ contentandattachmentssize: "contentAndAttachmentsSize",+ contentandattachmentsandrevisionssize: "contentAndAttachmentsAndRevisionsSize",+ revisioncount: "revisionCount"};interface SearchContext {@@ -42,48 +42,44 @@ class ValueExtractor {private propertyPath: string[];constructor(searchContext: SearchContext, propertyPath: string[]) {- this.propertyPath = propertyPath.map(pathEl => pathEl.toLowerCase());+ this.propertyPath = propertyPath.map((pathEl) => pathEl.toLowerCase());- if (this.propertyPath[0].startsWith('#')) {- this.propertyPath = ['note', 'labels', this.propertyPath[0].substr(1), ...this.propertyPath.slice( 1, this.propertyPath.length)];- }- else if (this.propertyPath[0].startsWith('~')) {- this.propertyPath = ['note', 'relations', this.propertyPath[0].substr(1), ...this.propertyPath.slice(1, this.propertyPath.length)];+ if (this.propertyPath[0].startsWith("#")) {+ this.propertyPath = ["note", "labels", this.propertyPath[0].substr(1), ...this.propertyPath.slice(1, this.propertyPath.length)];+ } else if (this.propertyPath[0].startsWith("~")) {+ this.propertyPath = ["note", "relations", this.propertyPath[0].substr(1), ...this.propertyPath.slice(1, this.propertyPath.length)];}- if (['contentsize', 'contentandattachmentssize', 'contentandattachmentsandrevisionssize', 'revisioncount'].includes(this.propertyPath[this.propertyPath.length - 1])) {+ if (["contentsize", "contentandattachmentssize", "contentandattachmentsandrevisionssize", "revisioncount"].includes(this.propertyPath[this.propertyPath.length - 1])) {searchContext.dbLoadNeeded = true;}}validate() {- if (this.propertyPath[0] !== 'note') {+ if (this.propertyPath[0] !== "note") {return `property specifier must start with 'note', but starts with '${this.propertyPath[0]}'`;}for (let i = 1; i < this.propertyPath.length; i++) {const pathEl = this.propertyPath[i];- if (pathEl === 'labels') {+ if (pathEl === "labels") {if (i !== this.propertyPath.length - 2) {return `label is a terminal property specifier and must be at the end`;}i++;- }- else if (pathEl === 'relations') {+ } else if (pathEl === "relations") {if (i >= this.propertyPath.length - 2) {return `relation name or property name is missing`;}i++;- }- else if (pathEl in PROP_MAPPING || pathEl === 'random') {+ } else if (pathEl in PROP_MAPPING || pathEl === "random") {if (i !== this.propertyPath.length - 1) {return `${pathEl} is a terminal property specifier and must be at the end`;}- }- else if (!["parents", "children"].includes(pathEl)) {+ } else if (!["parents", "children"].includes(pathEl)) {return `Unrecognized property specifier ${pathEl}`;}}@@ -101,33 +97,28 @@ class ValueExtractor {return cursor;}- if (cur() === 'labels') {+ if (cur() === "labels") {i++;- const attr = cursor.getAttributeCaseInsensitive('label', cur());+ const attr = cursor.getAttributeCaseInsensitive("label", cur());return attr ? attr.value : null;}- if (cur() === 'relations') {+ if (cur() === "relations") {i++;- const attr = cursor.getAttributeCaseInsensitive('relation', cur());+ const attr = cursor.getAttributeCaseInsensitive("relation", cur());cursor = attr?.targetNote || null;- }- else if (cur() === 'parents') {+ } else if (cur() === "parents") {cursor = cursor.parents[0];- }- else if (cur() === 'children') {+ } else if (cur() === "children") {cursor = cursor.children[0];- }- else if (cur() === 'random') {+ } else if (cur() === "random") {return Math.random().toString(); // string is expected for comparison- }- else if (cur() in PROP_MAPPING) {+ } else if (cur() in PROP_MAPPING) {return (cursor as any)[PROP_MAPPING[cur()]];- }- else {+ } else {// FIXME}}diff --git a/src/services/session_secret.ts b/src/services/session_secret.tsindex a536ebaaa7..551efffe28 100644--- a/src/services/session_secret.ts+++ b/src/services/session_secret.ts@@ -3,7 +3,7 @@import fs from "fs";import dataDir from "./data_dir.js";import log from "./log.js";-import { randomSecureToken } from "./utils.js"+import { randomSecureToken } from "./utils.js";const sessionSecretPath = `${dataDir.TRILIUM_DATA_DIR}/session_secret.txt`;@@ -17,8 +17,7 @@ if (!fs.existsSync(sessionSecretPath)) {log.info("Generated session secret");fs.writeFileSync(sessionSecretPath, sessionSecret, ENCODING);-}-else {+} else {sessionSecret = fs.readFileSync(sessionSecretPath, ENCODING);}diff --git a/src/services/setup.ts b/src/services/setup.tsindex 757444709f..b1b09a621c 100644--- a/src/services/setup.ts+++ b/src/services/setup.ts@@ -7,13 +7,15 @@ import request from "./request.js";import appInfo from "./app_info.js";import { timeLimit } from "./utils.js";import becca from "../becca/becca.js";-import { SetupStatusResponse, SetupSyncSeedResponse } from './api-interface.js';+import { SetupStatusResponse, SetupSyncSeedResponse } from "./api-interface.js";async function hasSyncServerSchemaAndSeed() {- const response = await requestToSyncServer<SetupStatusResponse>('GET', '/api/setup/status');+ const response = await requestToSyncServer<SetupStatusResponse>("GET", "/api/setup/status");if (response.syncVersion !== appInfo.syncVersion) {- throw new Error(`Could not setup sync since local sync protocol version is ${appInfo.syncVersion} while remote is ${response.syncVersion}. To fix this issue, use same Trilium version on all instances.`);+ throw new Error(+ `Could not setup sync since local sync protocol version is ${appInfo.syncVersion} while remote is ${response.syncVersion}. To fix this issue, use same Trilium version on all instances.`+ );}return response.schemaExists;@@ -23,7 +25,7 @@ function triggerSync() {log.info("Triggering sync.");// it's ok to not wait for it here- syncService.sync().then(res => {+ syncService.sync().then((res) => {if (res.success) {sqlInit.setDbAsInitialized();}@@ -33,34 +35,37 @@ function triggerSync() {async function sendSeedToSyncServer() {log.info("Initiating sync to server");- await requestToSyncServer<void>('POST', '/api/setup/sync-seed', {+ await requestToSyncServer<void>("POST", "/api/setup/sync-seed", {options: getSyncSeedOptions(),syncVersion: appInfo.syncVersion});// this is a completely new sync, need to reset counters. If this was not a new sync,// the previous request would have failed.- optionService.setOption('lastSyncedPush', 0);- optionService.setOption('lastSyncedPull', 0);+ optionService.setOption("lastSyncedPush", 0);+ optionService.setOption("lastSyncedPull", 0);}async function requestToSyncServer<T>(method: string, path: string, body?: string | {}): Promise<T> {const timeout = syncOptions.getSyncTimeout();- return await timeLimit(request.exec({- method,- url: syncOptions.getSyncServerHost() + path,- body,- proxy: syncOptions.getSyncProxy(),- timeout: timeout- }), timeout) as T;+ return (await timeLimit(+ request.exec({+ method,+ url: syncOptions.getSyncServerHost() + path,+ body,+ proxy: syncOptions.getSyncProxy(),+ timeout: timeout+ }),+ timeout+ )) as T;}async function setupSyncFromSyncServer(syncServerHost: string, syncProxy: string, password: string) {if (sqlInit.isDbInitialized()) {return {- result: 'failure',- error: 'DB is already initialized.'+ result: "failure",+ error: "DB is already initialized."};}@@ -69,7 +74,7 @@ async function setupSyncFromSyncServer(syncServerHost: string, syncProxy: string// the response is expected to contain documentId and documentSecret optionsconst resp = await request.exec<SetupSyncSeedResponse>({- method: 'get',+ method: "get",url: `${syncServerHost}/api/setup/sync-seed`,auth: { password },proxy: syncProxy,@@ -82,32 +87,28 @@ async function setupSyncFromSyncServer(syncServerHost: string, syncProxy: stringlog.error(message);return {- result: 'failure',+ result: "failure",error: message- }+ };}await sqlInit.createDatabaseForSync(resp.options, syncServerHost, syncProxy);triggerSync();- return { result: 'success' };- }- catch (e: any) {+ return { result: "success" };+ } catch (e: any) {log.error(`Sync failed: '${e.message}', stack: ${e.stack}`);return {- result: 'failure',+ result: "failure",error: e.message};}}function getSyncSeedOptions() {- return [- becca.getOption('documentId'),- becca.getOption('documentSecret')- ];+ return [becca.getOption("documentId"), becca.getOption("documentSecret")];}export default {diff --git a/src/services/spaced_update.ts b/src/services/spaced_update.tsindex 8fc5818be5..c1d6559e4a 100644--- a/src/services/spaced_update.ts+++ b/src/services/spaced_update.ts@@ -1,7 +1,6 @@type Updater = () => void;class SpacedUpdate {-private updater: Updater;private lastUpdated: number;private changed: boolean;@@ -29,8 +28,7 @@ class SpacedUpdate {try {await this.updater();- }- catch (e) {+ } catch (e) {this.changed = true;throw e;@@ -55,8 +53,7 @@ class SpacedUpdate {this.updater();this.lastUpdated = Date.now();this.changed = false;- }- else {+ } else {// update isn't triggered but changes are still pending, so we need to schedule another checkthis.scheduleUpdate();}@@ -67,8 +64,7 @@ class SpacedUpdate {try {await callback();- }- finally {+ } finally {this.changeForbidden = false;}}diff --git a/src/services/special_notes.ts b/src/services/special_notes.tsindex 991e7f3eae..81df0250f1 100644--- a/src/services/special_notes.ts+++ b/src/services/special_notes.ts@@ -20,35 +20,33 @@ function getInboxNote(date: string) {let inbox;if (!workspaceNote.isRoot()) {- inbox = workspaceNote.searchNoteInSubtree('#workspaceInbox');+ inbox = workspaceNote.searchNoteInSubtree("#workspaceInbox");if (!inbox) {- inbox = workspaceNote.searchNoteInSubtree('#inbox');+ inbox = workspaceNote.searchNoteInSubtree("#inbox");}if (!inbox) {inbox = workspaceNote;}- }- else {- inbox = attributeService.getNoteWithLabel('inbox')- || dateNoteService.getDayNote(date);+ } else {+ inbox = attributeService.getNoteWithLabel("inbox") || dateNoteService.getDayNote(date);}return inbox;}function createSqlConsole() {- const {note} = noteService.createNewNote({- parentNoteId: getMonthlyParentNoteId('_sqlConsole', 'sqlConsole'),- title: 'SQL Console - ' + dateUtils.localNowDate(),+ const { note } = noteService.createNewNote({+ parentNoteId: getMonthlyParentNoteId("_sqlConsole", "sqlConsole"),+ title: "SQL Console - " + dateUtils.localNowDate(),content: "SELECT title, isDeleted, isProtected FROM notes WHERE noteId = ''\n\n\n\n",- type: 'code',- mime: 'text/x-sqlite;schema=trilium'+ type: "code",+ mime: "text/x-sqlite;schema=trilium"});- note.setLabel('iconClass', 'bx bx-data');- note.setLabel('keepCurrentHoisting');+ note.setLabel("iconClass", "bx bx-data");+ note.setLabel("keepCurrentHoisting");return note;}@@ -58,14 +56,12 @@ function saveSqlConsole(sqlConsoleNoteId: string) {if (!sqlConsoleNote) throw new Error(`Unable to find SQL console note ID: ${sqlConsoleNoteId}`);const today = dateUtils.localNowDate();- const sqlConsoleHome =- attributeService.getNoteWithLabel('sqlConsoleHome')- || dateNoteService.getDayNote(today);+ const sqlConsoleHome = attributeService.getNoteWithLabel("sqlConsoleHome") || dateNoteService.getDayNote(today);const result = sqlConsoleNote.cloneTo(sqlConsoleHome.noteId);for (const parentBranch of sqlConsoleNote.getParentBranches()) {- if (parentBranch.parentNote?.hasAncestor('_hidden')) {+ if (parentBranch.parentNote?.hasAncestor("_hidden")) {parentBranch.markAsDeleted();}}@@ -74,19 +70,19 @@ function saveSqlConsole(sqlConsoleNoteId: string) {}function createSearchNote(searchString: string, ancestorNoteId: string) {- const {note} = noteService.createNewNote({- parentNoteId: getMonthlyParentNoteId('_search', 'search'),+ const { note } = noteService.createNewNote({+ parentNoteId: getMonthlyParentNoteId("_search", "search"),title: `${t("special_notes.search_prefix")} ${searchString}`,content: "",- type: 'search',- mime: 'application/json'+ type: "search",+ mime: "application/json"});- note.setLabel('searchString', searchString);- note.setLabel('keepCurrentHoisting');+ note.setLabel("searchString", searchString);+ note.setLabel("keepCurrentHoisting");if (ancestorNoteId) {- note.setRelation('ancestor', ancestorNoteId);+ note.setRelation("ancestor", ancestorNoteId);}return note;@@ -99,14 +95,11 @@ function getSearchHome() {}if (!workspaceNote.isRoot()) {- return workspaceNote.searchNoteInSubtree('#workspaceSearchHome')- || workspaceNote.searchNoteInSubtree('#searchHome')- || workspaceNote;+ return workspaceNote.searchNoteInSubtree("#workspaceSearchHome") || workspaceNote.searchNoteInSubtree("#searchHome") || workspaceNote;} else {const today = dateUtils.localNowDate();- return workspaceNote.searchNoteInSubtree('#searchHome')- || dateNoteService.getDayNote(today);+ return workspaceNote.searchNoteInSubtree("#searchHome") || dateNoteService.getDayNote(today);}}@@ -121,7 +114,7 @@ function saveSearchNote(searchNoteId: string) {const result = searchNote.cloneTo(searchHome.noteId);for (const parentBranch of searchNote.getParentBranches()) {- if (parentBranch.parentNote?.hasAncestor('_hidden')) {+ if (parentBranch.parentNote?.hasAncestor("_hidden")) {parentBranch.markAsDeleted();}}@@ -133,17 +126,16 @@ function getMonthlyParentNoteId(rootNoteId: string, prefix: string) {const month = dateUtils.localNowDate().substring(0, 7);const labelName = `${prefix}MonthNote`;- let monthNote = searchService.findFirstNoteWithQuery(`#${labelName}="${month}"`,- new SearchContext({ancestorNoteId: rootNoteId}));+ let monthNote = searchService.findFirstNoteWithQuery(`#${labelName}="${month}"`, new SearchContext({ ancestorNoteId: rootNoteId }));if (!monthNote) {monthNote = noteService.createNewNote({parentNoteId: rootNoteId,title: month,- content: '',+ content: "",isProtected: false,- type: 'book'- }).note+ type: "book"+ }).note;monthNote.addLabel(labelName, month);}@@ -155,12 +147,12 @@ function createScriptLauncher(parentNoteId: string, forceNoteId?: string) {const note = noteService.createNewNote({noteId: forceNoteId,title: "Script Launcher",- type: 'launcher',- content: '',+ type: "launcher",+ content: "",parentNoteId: parentNoteId}).note;- note.addRelation('template', LBTPL_SCRIPT);+ note.addRelation("template", LBTPL_SCRIPT);return note;}@@ -173,39 +165,39 @@ interface LauncherConfig {function createLauncher({ parentNoteId, launcherType, noteId }: LauncherConfig) {let note;- if (launcherType === 'note') {+ if (launcherType === "note") {note = noteService.createNewNote({noteId: noteId,title: "Note Launcher",- type: 'launcher',- content: '',+ type: "launcher",+ content: "",parentNoteId: parentNoteId}).note;- note.addRelation('template', LBTPL_NOTE_LAUNCHER);- } else if (launcherType === 'script') {+ note.addRelation("template", LBTPL_NOTE_LAUNCHER);+ } else if (launcherType === "script") {note = createScriptLauncher(parentNoteId, noteId);- } else if (launcherType === 'customWidget') {+ } else if (launcherType === "customWidget") {note = noteService.createNewNote({noteId: noteId,title: "Widget Launcher",- type: 'launcher',- content: '',+ type: "launcher",+ content: "",parentNoteId: parentNoteId}).note;- note.addRelation('template', LBTPL_CUSTOM_WIDGET);- } else if (launcherType === 'spacer') {+ note.addRelation("template", LBTPL_CUSTOM_WIDGET);+ } else if (launcherType === "spacer") {note = noteService.createNewNote({noteId: noteId,branchId: noteId,title: "Spacer",- type: 'launcher',- content: '',+ type: "launcher",+ content: "",parentNoteId: parentNoteId}).note;- note.addRelation('template', LBTPL_SPACER);+ note.addRelation("template", LBTPL_SPACER);} else {throw new Error(`Unrecognized launcher type '${launcherType}'`);}@@ -221,7 +213,7 @@ function resetLauncher(noteId: string) {if (note?.isLaunchBarConfig()) {if (note) {- if (noteId === '_lbRoot') {+ if (noteId === "_lbRoot") {// deleting hoisted notes are not allowed, so we just reset the childrenfor (const childNote of note.getChildNotes()) {childNote.deleteNote();@@ -247,42 +239,35 @@ function resetLauncher(noteId: string) {* Another use case was for script-packages (e.g. demo Task manager) which could this way register automatically/easily* into the launchbar - for this it's recommended to use backend API's createOrUpdateLauncher()*/-function createOrUpdateScriptLauncherFromApi(opts: {- id: string;- title: string;- action: string;- icon?: string;- shortcut?: string;-}) {+function createOrUpdateScriptLauncherFromApi(opts: { id: string; title: string; action: string; icon?: string; shortcut?: string }) {if (opts.id && !/^[a-z0-9]+$/i.test(opts.id)) {throw new Error(`Launcher ID can be alphanumeric only, '${opts.id}' given`);}- const launcherId = opts.id || (`tb_${opts.title.toLowerCase().replace(/[^[a-z0-9]/gi, "")}`);+ const launcherId = opts.id || `tb_${opts.title.toLowerCase().replace(/[^[a-z0-9]/gi, "")}`;if (!opts.title) {throw new Error("Title is mandatory property to create or update a launcher.");}- const launcherNote = becca.getNote(launcherId)- || createScriptLauncher('_lbVisibleLaunchers', launcherId);+ const launcherNote = becca.getNote(launcherId) || createScriptLauncher("_lbVisibleLaunchers", launcherId);launcherNote.title = opts.title;launcherNote.setContent(`(${opts.action})()`);- launcherNote.setLabel('scriptInLauncherContent'); // there's no target note, the script is in the launcher's content- launcherNote.mime = 'application/javascript;env=frontend';+ launcherNote.setLabel("scriptInLauncherContent"); // there's no target note, the script is in the launcher's content+ launcherNote.mime = "application/javascript;env=frontend";launcherNote.save();if (opts.shortcut) {- launcherNote.setLabel('keyboardShortcut', opts.shortcut);+ launcherNote.setLabel("keyboardShortcut", opts.shortcut);} else {- launcherNote.removeLabel('keyboardShortcut');+ launcherNote.removeLabel("keyboardShortcut");}if (opts.icon) {- launcherNote.setLabel('iconClass', `bx bx-${opts.icon}`);+ launcherNote.setLabel("iconClass", `bx bx-${opts.icon}`);} else {- launcherNote.removeLabel('iconClass');+ launcherNote.removeLabel("iconClass");}return launcherNote;diff --git a/src/services/sql.ts b/src/services/sql.tsindex 9dfafbc4db..ab98d3a04a 100644--- a/src/services/sql.ts+++ b/src/services/sql.ts@@ -36,16 +36,15 @@ function rebuildIntegrationTestDatabase() {statementCache = {};}-if (!process.env.TRILIUM_INTEGRATION_TEST) {- dbConnection.pragma('journal_mode = WAL');+ dbConnection.pragma("journal_mode = WAL");}const LOG_ALL_QUERIES = false;type Params = any;-[`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `SIGTERM`].forEach(eventType => {+[`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `SIGTERM`].forEach((eventType) => {process.on(eventType, () => {if (dbConnection) {// closing connection is especially important to fold -wal file into the main DB file@@ -63,7 +62,7 @@ function insert<T extends {}>(tableName: string, rec: T, replace = false) {}const columns = keys.join(", ");- const questionMarks = keys.map(p => "?").join(", ");+ const questionMarks = keys.map((p) => "?").join(", ");const query = `INSERT${replace ? "OR REPLACE" : ""} INTO@@ -91,9 +90,9 @@ function upsert<T extends {}>(tableName: string, primaryKey: string, rec: T) {const columns = keys.join(", ");- const questionMarks = keys.map(colName => `@${colName}`).join(", ");+ const questionMarks = keys.map((colName) => `@${colName}`).join(", ");- const updateMarks = keys.map(colName => `${colName} = @${colName}`).join(", ");+ const updateMarks = keys.map((colName) => `${colName} = @${colName}`).join(", ");const query = `INSERT INTO ${tableName} (${columns}) VALUES (${questionMarks})ON CONFLICT (${primaryKey}) DO UPDATE SET ${updateMarks}`;@@ -116,7 +115,7 @@ function stmt(sql: string) {}function getRow<T>(query: string, params: Params = []): T {- return wrap(query, s => s.get(params)) as T;+ return wrap(query, (s) => s.get(params)) as T;}function getRowOrNull<T>(query: string, params: Params = []): T | null {@@ -125,11 +124,11 @@ function getRowOrNull<T>(query: string, params: Params = []): T | null {return null;}- return (all.length > 0 ? all[0] : null) as (T | null);+ return (all.length > 0 ? all[0] : null) as T | null;}function getValue<T>(query: string, params: Params = []): T {- return wrap(query, s => s.pluck().get(params)) as T;+ return wrap(query, (s) => s.pluck().get(params)) as T;}// smaller values can result in better performance due to better usage of statement cache@@ -146,30 +145,28 @@ function getManyRows<T>(query: string, params: Params): T[] {let j = 1;for (const param of curParams) {- curParamsObj['param' + j++] = param;+ curParamsObj["param" + j++] = param;}let i = 1;const questionMarks = curParams.map(() => ":param" + i++).join(",");const curQuery = query.replace(/\?\?\?/g, questionMarks);- const statement = curParams.length === PARAM_LIMIT- ? stmt(curQuery)- : dbConnection.prepare(curQuery);+ const statement = curParams.length === PARAM_LIMIT ? stmt(curQuery) : dbConnection.prepare(curQuery);const subResults = statement.all(curParamsObj);results = results.concat(subResults);}- return (results as (T[] | null) || []);+ return (results as T[] | null) || [];}function getRows<T>(query: string, params: Params = []): T[] {- return wrap(query, s => s.all(params)) as T[];+ return wrap(query, (s) => s.all(params)) as T[];}function getRawRows<T extends {} | unknown[]>(query: string, params: Params = []): T[] {- return (wrap(query, s => s.raw().all(params)) as T[]) || [];+ return (wrap(query, (s) => s.raw().all(params)) as T[]) || [];}function iterateRows<T>(query: string, params: Params = []): IterableIterator<T> {@@ -192,11 +189,11 @@ function getMap<K extends string | number | symbol, V>(query: string, params: Pa}function getColumn<T>(query: string, params: Params = []): T[] {- return wrap(query, s => s.pluck().all(params)) as T[];+ return wrap(query, (s) => s.pluck().all(params)) as T[];}function execute(query: string, params: Params = []): RunResult {- return wrap(query, s => s.run(params)) as RunResult;+ return wrap(query, (s) => s.run(params)) as RunResult;}function executeMany(query: string, params: Params) {@@ -212,7 +209,7 @@ function executeMany(query: string, params: Params) {let j = 1;for (const param of curParams) {- curParamsObj['param' + j++] = param;+ curParamsObj["param" + j++] = param;}let i = 1;@@ -241,8 +238,7 @@ function wrap(query: string, func: (statement: Statement) => unknown): unknown {try {result = func(stmt(query));- }- catch (e: any) {+ } catch (e: any) {if (e.message.includes("The database connection is not open")) {// this often happens on killing the app which puts these alerts in front of user// in these cases error should be simply ignored.@@ -259,8 +255,7 @@ function wrap(query: string, func: (statement: Statement) => unknown): unknown {if (milliseconds >= 20 && !cls.isSlowQueryLoggingDisabled()) {if (query.includes("WITH RECURSIVE")) {log.info(`Slow recursive query took ${milliseconds}ms.`);- }- else {+ } else {log.info(`Slow query took ${milliseconds}ms: ${query.trim().replace(/\s+/g, " ")}`);}}@@ -272,13 +267,13 @@ function transactional<T>(func: (statement: Statement) => T) {try {const ret = (dbConnection.transaction(func) as any).deferred();- if (!dbConnection.inTransaction) { // i.e. transaction was really committed (and not just savepoint released)+ if (!dbConnection.inTransaction) {+ // i.e. transaction was really committed (and not just savepoint released)ws.sendTransactionEntityChangesToAllClients();}return ret;- }- catch (e) {+ } catch (e) {const entityChangeIds = cls.getAndClearEntityChangeIds();if (entityChangeIds.length > 0) {@@ -312,7 +307,7 @@ function fillParamList(paramIds: string[] | Set<string>, truncate = true) {}// doing it manually to avoid this showing up on the slow query list- const s = stmt(`INSERT INTO param_list VALUES ${paramIds.map(paramId => `(?)`).join(',')}`);+ const s = stmt(`INSERT INTO param_list VALUES ${paramIds.map((paramId) => `(?)`).join(",")}`);s.run(paramIds);}@@ -320,8 +315,7 @@ function fillParamList(paramIds: string[] | Set<string>, truncate = true) {async function copyDatabase(targetFilePath: string) {try {fs.unlinkSync(targetFilePath);- } catch (e) {- } // unlink throws exception if the file did not exist+ } catch (e) {} // unlink throws exception if the file did not existawait dbConnection.backup(targetFilePath);}@@ -333,8 +327,7 @@ function disableSlowQueryLogging<T>(cb: () => T) {cls.disableSlowQueryLogging(true);return cb();- }- finally {+ } finally {cls.disableSlowQueryLogging(orig);}}@@ -345,60 +338,60 @@ export default {replace,/**- * Get single value from the given query - first column from first returned row.- *- * @param query - SQL query with ? used as parameter placeholder- * @param params - array of params if needed- * @returns single value- */+ * Get single value from the given query - first column from first returned row.+ *+ * @param query - SQL query with ? used as parameter placeholder+ * @param params - array of params if needed+ * @returns single value+ */getValue,/**- * Get first returned row.- *- * @param query - SQL query with ? used as parameter placeholder- * @param params - array of params if needed- * @returns - map of column name to column value- */+ * Get first returned row.+ *+ * @param query - SQL query with ? used as parameter placeholder+ * @param params - array of params if needed+ * @returns - map of column name to column value+ */getRow,getRowOrNull,/**- * Get all returned rows.- *- * @param query - SQL query with ? used as parameter placeholder- * @param params - array of params if needed- * @returns - array of all rows, each row is a map of column name to column value- */+ * Get all returned rows.+ *+ * @param query - SQL query with ? used as parameter placeholder+ * @param params - array of params if needed+ * @returns - array of all rows, each row is a map of column name to column value+ */getRows,getRawRows,iterateRows,getManyRows,/**- * Get a map of first column mapping to second column.- *- * @param query - SQL query with ? used as parameter placeholder- * @param params - array of params if needed- * @returns - map of first column to second column- */+ * Get a map of first column mapping to second column.+ *+ * @param query - SQL query with ? used as parameter placeholder+ * @param params - array of params if needed+ * @returns - map of first column to second column+ */getMap,/**- * Get a first column in an array.- *- * @param query - SQL query with ? used as parameter placeholder- * @param params - array of params if needed- * @returns array of first column of all returned rows- */+ * Get a first column in an array.+ *+ * @param query - SQL query with ? used as parameter placeholder+ * @param params - array of params if needed+ * @returns array of first column of all returned rows+ */getColumn,/**- * Execute SQL- *- * @param query - SQL query with ? used as parameter placeholder- * @param params - array of params if needed- */+ * Execute SQL+ *+ * @param query - SQL query with ? used as parameter placeholder+ * @param params - array of params if needed+ */execute,executeMany,executeScript,diff --git a/src/services/sql_init.ts b/src/services/sql_init.tsindex 44c4a40439..a870c26ae7 100644--- a/src/services/sql_init.ts+++ b/src/services/sql_init.ts@@ -10,7 +10,7 @@ import TaskContext from "./task_context.js";import migrationService from "./migration.js";import cls from "./cls.js";import config from "./config.js";-import { OptionRow } from '../becca/entities/rows.js';+import { OptionRow } from "../becca/entities/rows.js";import BNote from "../becca/entities/bnote.js";import BBranch from "../becca/entities/bbranch.js";import zipImportService from "./import/zip.js";@@ -32,13 +32,12 @@ function isDbInitialized() {const initialized = sql.getValue("SELECT value FROM options WHERE name = 'initialized'");- return initialized === 'true';+ return initialized === "true";}async function initDbConnection() {if (!isDbInitialized()) {- log.info(`DB not initialized, please visit setup page` +- (isElectron() ? '' : ` - http://[your-server-host]:${port} to see instructions on how to initialize Trilium.`));+ log.info(`DB not initialized, please visit setup page` + (isElectron() ? "" : ` - http://[your-server-host]:${port} to see instructions on how to initialize Trilium.`));return;}@@ -73,17 +72,17 @@ async function createInitialDatabase() {log.info("Creating root note ...");rootNote = new BNote({- noteId: 'root',- title: 'root',- type: 'text',- mime: 'text/html'+ noteId: "root",+ title: "root",+ type: "text",+ mime: "text/html"}).save();- rootNote.setContent('');+ rootNote.setContent("");new BBranch({- noteId: 'root',- parentNoteId: 'none',+ noteId: "root",+ parentNoteId: "none",isExpanded: true,notePosition: 10}).save();@@ -96,7 +95,7 @@ async function createInitialDatabase() {log.info("Importing demo content ...");- const dummyTaskContext = new TaskContext("no-progress-reporting", 'import', false);+ const dummyTaskContext = new TaskContext("no-progress-reporting", "import", false);await zipImportService.importZip(dummyTaskContext, demoFile, rootNote);@@ -107,12 +106,15 @@ async function createInitialDatabase() {const startNoteId = sql.getValue("SELECT noteId FROM branches WHERE parentNoteId = 'root' AND isDeleted = 0 ORDER BY notePosition");- optionService.setOption('openNoteContexts', JSON.stringify([- {- notePath: startNoteId,- active: true- }- ]));+ optionService.setOption(+ "openNoteContexts",+ JSON.stringify([+ {+ notePath: startNoteId,+ active: true+ }+ ])+ );});log.info("Schema and initial content generated.");@@ -120,7 +122,7 @@ async function createInitialDatabase() {initDbConnection();}-async function createDatabaseForSync(options: OptionRow[], syncServerHost = '', syncProxy = '') {+async function createDatabaseForSync(options: OptionRow[], syncServerHost = "", syncProxy = "") {log.info("Creating database for sync");if (isDbInitialized()) {@@ -148,7 +150,7 @@ async function createDatabaseForSync(options: OptionRow[], syncServerHost = '',function setDbAsInitialized() {if (!isDbInitialized()) {- optionService.setOption('initialized', 'true');+ optionService.setOption("initialized", "true");initDbConnection();}diff --git a/src/services/sync.ts b/src/services/sync.tsindex 0c15180237..052ba6542d 100644--- a/src/services/sync.ts+++ b/src/services/sync.ts@@ -17,8 +17,8 @@ import ws from "./ws.js";import entityChangesService from "./entity_changes.js";import entityConstructor from "../becca/entity_constructor.js";import becca from "../becca/becca.js";-import { EntityChange, EntityChangeRecord, EntityRow } from './entity_changes_interface.js';-import { CookieJar, ExecOpts } from './request_interface.js';+import { EntityChange, EntityChangeRecord, EntityRow } from "./entity_changes_interface.js";+import { CookieJar, ExecOpts } from "./request_interface.js";import setupService from "./setup.js";import consistency_checks from "./consistency_checks.js";import becca_loader from "../becca/becca_loader.js";@@ -29,7 +29,7 @@ let outstandingPullCount = 0;interface CheckResponse {maxEntityChangeId: number;- entityHashes: Record<string, Record<string, string>>+ entityHashes: Record<string, Record<string, string>>;}interface SyncResponse {@@ -52,7 +52,7 @@ async function sync() {try {return await syncMutexService.doExclusively(async () => {if (!syncOptions.isSyncSetup()) {- return { success: false, errorCode: 'NOT_CONFIGURED', message: 'Sync not configured' };+ return { success: false, errorCode: "NOT_CONFIGURED", message: "Sync not configured" };}let continueSync = false;@@ -69,8 +69,7 @@ async function sync() {await syncFinished(syncContext);continueSync = await checkContentHash(syncContext);- }- while (continueSync);+ } while (continueSync);ws.syncFinished();@@ -78,15 +77,15 @@ async function sync() {success: true};});- }- catch (e: any) {+ } catch (e: any) {// we're dynamically switching whether we're using proxy or not based on whether we encountered error with the current methodproxyToggle = !proxyToggle;- if (e.message?.includes('ECONNREFUSED') ||- e.message?.includes('ERR_') || // node network errors- e.message?.includes('Bad Gateway')) {-+ if (+ e.message?.includes("ECONNREFUSED") ||+ e.message?.includes("ERR_") || // node network errors+ e.message?.includes("Bad Gateway")+ ) {ws.syncFailed();log.info("No connection to sync server.");@@ -95,8 +94,7 @@ async function sync() {success: false,message: "No connection to sync server."};- }- else {+ } else {log.info(`Sync failed: '${e.message}', stack: ${e.stack}`);ws.syncFailed();@@ -104,13 +102,13 @@ async function sync() {return {success: false,message: e.message- }+ };}}}async function login() {- if (!await setupService.hasSyncServerSchemaAndSeed()) {+ if (!(await setupService.hasSyncServerSchemaAndSeed())) {await setupService.sendSeedToSyncServer();}@@ -120,11 +118,11 @@ async function login() {async function doLogin(): Promise<SyncContext> {const timestamp = dateUtils.utcNowDateTime();- const documentSecret = optionService.getOption('documentSecret');+ const documentSecret = optionService.getOption("documentSecret");const hash = hmac(documentSecret, timestamp);const syncContext: SyncContext = { cookieJar: {} };- const resp = await syncRequest<SyncResponse>(syncContext, 'POST', '/api/login/sync', {+ const resp = await syncRequest<SyncResponse>(syncContext, "POST", "/api/login/sync", {timestamp: timestamp,syncVersion: appInfo.syncVersion,hash: hash@@ -135,7 +133,9 @@ async function doLogin(): Promise<SyncContext> {}if (resp.instanceId === instanceId) {- throw new Error(`Sync server has instance ID '${resp.instanceId}' which is also local. This usually happens when the sync client is (mis)configured to sync with itself (URL points back to client) instead of the correct sync server.`);+ throw new Error(+ `Sync server has instance ID '${resp.instanceId}' which is also local. This usually happens when the sync client is (mis)configured to sync with itself (URL points back to client) instead of the correct sync server.`+ );}syncContext.instanceId = resp.instanceId;@@ -161,11 +161,11 @@ async function pullChanges(syncContext: SyncContext) {const startDate = Date.now();- const resp = await syncRequest<ChangesResponse>(syncContext, 'GET', changesUri);+ const resp = await syncRequest<ChangesResponse>(syncContext, "GET", changesUri);if (!resp) {throw new Error("Request failed.");}- const {entityChanges, lastEntityChangeId} = resp;+ const { entityChanges, lastEntityChangeId } = resp;outstandingPullCount = resp.outstandingPullCount;@@ -184,12 +184,14 @@ async function pullChanges(syncContext: SyncContext) {if (entityChanges.length === 0) {break;} else {- try { // https://github.com/zadam/trilium/issues/4310+ try {+ // https://github.com/zadam/trilium/issues/4310const sizeInKb = Math.round(JSON.stringify(resp).length / 1024);- log.info(`Sync ${logMarkerId}: Pulled ${entityChanges.length} changes in ${sizeInKb} KB, starting at entityChangeId=${lastSyncedPull} in ${pulledDate - startDate}ms and applied them in ${Date.now() - pulledDate}ms, ${outstandingPullCount} outstanding pulls`);- }- catch (e: any) {+ log.info(+ `Sync ${logMarkerId}: Pulled ${entityChanges.length} changes in ${sizeInKb} KB, starting at entityChangeId=${lastSyncedPull} in ${pulledDate - startDate}ms and applied them in ${Date.now() - pulledDate}ms, ${outstandingPullCount} outstanding pulls`+ );+ } catch (e: any) {log.error(`Error occurred ${e.message} ${e.stack}`);}}@@ -202,7 +204,7 @@ async function pushChanges(syncContext: SyncContext) {let lastSyncedPush: number | null | undefined = getLastSyncedPush();while (true) {- const entityChanges = sql.getRows<EntityChange>('SELECT * FROM entity_changes WHERE isSynced = 1 AND id > ? LIMIT 1000', [lastSyncedPush]);+ const entityChanges = sql.getRows<EntityChange>("SELECT * FROM entity_changes WHERE isSynced = 1 AND id > ? LIMIT 1000", [lastSyncedPush]);if (entityChanges.length === 0) {log.info("Nothing to push");@@ -210,15 +212,14 @@ async function pushChanges(syncContext: SyncContext) {break;}- const filteredEntityChanges = entityChanges.filter(entityChange => {+ const filteredEntityChanges = entityChanges.filter((entityChange) => {if (entityChange.instanceId === syncContext.instanceId) {// this may set lastSyncedPush beyond what's actually sent (because of size limit)// so this is applied to the database only if there's no actual updatelastSyncedPush = entityChange.id;return false;- }- else {+ } else {return true;}});@@ -236,7 +237,7 @@ async function pushChanges(syncContext: SyncContext) {const logMarkerId = randomString(10); // to easily pair sync events between client and server logs- await syncRequest(syncContext, 'PUT', `/api/sync/update?logMarkerId=${logMarkerId}`, {+ await syncRequest(syncContext, "PUT", `/api/sync/update?logMarkerId=${logMarkerId}`, {entities: entityChangesRecords,instanceId});@@ -254,11 +255,11 @@ async function pushChanges(syncContext: SyncContext) {}async function syncFinished(syncContext: SyncContext) {- await syncRequest(syncContext, 'POST', '/api/sync/finished');+ await syncRequest(syncContext, "POST", "/api/sync/finished");}async function checkContentHash(syncContext: SyncContext) {- const resp = await syncRequest<CheckResponse>(syncContext, 'GET', '/api/sync/check');+ const resp = await syncRequest<CheckResponse>(syncContext, "GET", "/api/sync/check");if (!resp) {throw new Error("Got no response.");}@@ -285,13 +286,13 @@ async function checkContentHash(syncContext: SyncContext) {// before re-queuing sectors, make sure the entity changes are correctconsistency_checks.runEntityChangesChecks();- await syncRequest(syncContext, 'POST', `/api/sync/check-entity-changes`);+ await syncRequest(syncContext, "POST", `/api/sync/check-entity-changes`);}- for (const {entityName, sector} of failedChecks) {+ for (const { entityName, sector } of failedChecks) {entityChangesService.addEntityChangesForSector(entityName, sector);- await syncRequest(syncContext, 'POST', `/api/sync/queue-sector/${entityName}/${sector}`);+ await syncRequest(syncContext, "POST", `/api/sync/queue-sector/${entityName}/${sector}`);}return failedChecks.length > 0;@@ -300,11 +301,11 @@ async function checkContentHash(syncContext: SyncContext) {const PAGE_SIZE = 1000000;interface SyncContext {- cookieJar: CookieJar+ cookieJar: CookieJar;}async function syncRequest<T extends {}>(syncContext: SyncContext, method: string, requestPath: string, _body?: {}) {- const body = _body ? JSON.stringify(_body) : '';+ const body = _body ? JSON.stringify(_body) : "";const timeout = syncOptions.getSyncTimeout();@@ -328,19 +329,18 @@ async function syncRequest<T extends {}>(syncContext: SyncContext, method: strinproxy: proxyToggle ? syncOptions.getSyncProxy() : null};- response = await timeLimit(request.exec(opts), timeout) as T;+ response = (await timeLimit(request.exec(opts), timeout)) as T;}return response;}function getEntityChangeRow(entityChange: EntityChange) {- const {entityName, entityId} = entityChange;+ const { entityName, entityId } = entityChange;- if (entityName === 'note_reordering') {+ if (entityName === "note_reordering") {return sql.getMap("SELECT branchId, notePosition FROM branches WHERE parentNoteId = ? AND isDeleted = 0", [entityId]);- }- else {+ } else {const primaryKey = entityConstructor.getEntityFromEntityName(entityName).primaryKeyName;if (!primaryKey) {@@ -354,9 +354,9 @@ function getEntityChangeRow(entityChange: EntityChange) {return null;}- if (entityName === 'blobs' && entityRow.content !== null) {- if (typeof entityRow.content === 'string') {- entityRow.content = Buffer.from(entityRow.content, 'utf-8');+ if (entityName === "blobs" && entityRow.content !== null) {+ if (typeof entityRow.content === "string") {+ entityRow.content = Buffer.from(entityRow.content, "utf-8");}if (entityRow.content) {@@ -374,7 +374,7 @@ function getEntityChangeRecords(entityChanges: EntityChange[]) {for (const entityChange of entityChanges) {if (entityChange.isErased) {- records.push({entityChange});+ records.push({ entityChange });continue;}@@ -400,22 +400,23 @@ function getEntityChangeRecords(entityChanges: EntityChange[]) {}function getLastSyncedPull() {- return parseInt(optionService.getOption('lastSyncedPull'));+ return parseInt(optionService.getOption("lastSyncedPull"));}function setLastSyncedPull(entityChangeId: number) {- const lastSyncedPullOption = becca.getOption('lastSyncedPull');+ const lastSyncedPullOption = becca.getOption("lastSyncedPull");- if (lastSyncedPullOption) { // might be null in initial sync when becca is not loaded+ if (lastSyncedPullOption) {+ // might be null in initial sync when becca is not loadedlastSyncedPullOption.value = `${entityChangeId}`;}// this way we avoid updating entity_changes which otherwise means that we've never pushed all entity_changes- sql.execute("UPDATE options SET value = ? WHERE name = ?", [entityChangeId, 'lastSyncedPull']);+ sql.execute("UPDATE options SET value = ? WHERE name = ?", [entityChangeId, "lastSyncedPull"]);}function getLastSyncedPush() {- const lastSyncedPush = parseInt(optionService.getOption('lastSyncedPush'));+ const lastSyncedPush = parseInt(optionService.getOption("lastSyncedPush"));ws.setLastSyncedPush(lastSyncedPush);@@ -425,18 +426,19 @@ function getLastSyncedPush() {function setLastSyncedPush(entityChangeId: number) {ws.setLastSyncedPush(entityChangeId);- const lastSyncedPushOption = becca.getOption('lastSyncedPush');+ const lastSyncedPushOption = becca.getOption("lastSyncedPush");- if (lastSyncedPushOption) { // might be null in initial sync when becca is not loaded+ if (lastSyncedPushOption) {+ // might be null in initial sync when becca is not loadedlastSyncedPushOption.value = `${entityChangeId}`;}// this way we avoid updating entity_changes which otherwise means that we've never pushed all entity_changes- sql.execute("UPDATE options SET value = ? WHERE name = ?", [entityChangeId, 'lastSyncedPush']);+ sql.execute("UPDATE options SET value = ? WHERE name = ?", [entityChangeId, "lastSyncedPush"]);}function getMaxEntityChangeId() {- return sql.getValue('SELECT COALESCE(MAX(id), 0) FROM entity_changes');+ return sql.getValue("SELECT COALESCE(MAX(id), 0) FROM entity_changes");}function getOutstandingPullCount() {diff --git a/src/services/sync_mutex.ts b/src/services/sync_mutex.tsindex 5bdbaa36fc..e900117705 100644--- a/src/services/sync_mutex.ts+++ b/src/services/sync_mutex.ts@@ -11,8 +11,7 @@ async function doExclusively<T>(func: () => T) {try {return await func();- }- finally {+ } finally {releaseMutex();}}diff --git a/src/services/sync_options.ts b/src/services/sync_options.tsindex 6ba61fc82d..b7dc7f091a 100644--- a/src/services/sync_options.ts+++ b/src/services/sync_options.ts@@ -12,20 +12,20 @@ import config from "./config.js";*/function get(name: OptionNames) {- return (config['Sync'] && config['Sync'][name]) || optionService.getOption(name);+ return (config["Sync"] && config["Sync"][name]) || optionService.getOption(name);}export default {// env variable is the easiest way to guarantee we won't overwrite prod data during development// after copying prod document/data directory- getSyncServerHost: () => process.env.TRILIUM_SYNC_SERVER_HOST || get('syncServerHost'),+ getSyncServerHost: () => process.env.TRILIUM_SYNC_SERVER_HOST || get("syncServerHost"),isSyncSetup: () => {- const syncServerHost = get('syncServerHost');+ const syncServerHost = get("syncServerHost");// special value "disabled" is here to support a use case where the document is configured with sync server,// and we need to override it with config from config.ini- return !!syncServerHost && syncServerHost !== 'disabled';+ return !!syncServerHost && syncServerHost !== "disabled";},- getSyncTimeout: () => parseInt(get('syncServerTimeout')) || 120000,- getSyncProxy: () => get('syncProxy')+ getSyncTimeout: () => parseInt(get("syncServerTimeout")) || 120000,+ getSyncProxy: () => get("syncProxy")};diff --git a/src/services/sync_update.ts b/src/services/sync_update.tsindex 275477ba2f..326fc5d11b 100644--- a/src/services/sync_update.ts+++ b/src/services/sync_update.ts@@ -4,12 +4,12 @@ import entityChangesService from "./entity_changes.js";import eventService from "./events.js";import entityConstructor from "../becca/entity_constructor.js";import ws from "./ws.js";-import { EntityChange, EntityChangeRecord, EntityRow } from './entity_changes_interface.js';+import { EntityChange, EntityChangeRecord, EntityRow } from "./entity_changes_interface.js";interface UpdateContext {alreadyErased: number;erased: number;- updated: Record<string, string[]>+ updated: Record<string, string[]>;}function updateEntities(entityChanges: EntityChangeRecord[], instanceId: string) {@@ -25,9 +25,8 @@ function updateEntities(entityChanges: EntityChangeRecord[], instanceId: string)alreadyErased: 0};- for (const {entityChange, entity} of entityChanges) {- const changeAppliedAlready = entityChange.changeId- && !!sql.getValue("SELECT 1 FROM entity_changes WHERE changeId = ?", [entityChange.changeId]);+ for (const { entityChange, entity } of entityChanges) {+ const changeAppliedAlready = entityChange.changeId && !!sql.getValue("SELECT 1 FROM entity_changes WHERE changeId = ?", [entityChange.changeId]);if (changeAppliedAlready) {updateContext.alreadyUpdated++;@@ -35,7 +34,8 @@ function updateEntities(entityChanges: EntityChangeRecord[], instanceId: string)continue;}- if (!atLeastOnePullApplied) { // avoid spamming and send only for first+ if (!atLeastOnePullApplied) {+ // avoid spamming and send only for firstws.syncPullInProgress();atLeastOnePullApplied = true;@@ -48,13 +48,11 @@ function updateEntities(entityChanges: EntityChangeRecord[], instanceId: string)}function updateEntity(remoteEC: EntityChange, remoteEntityRow: EntityRow | undefined, instanceId: string, updateContext: UpdateContext) {- if (!remoteEntityRow && remoteEC.entityName === 'options') {+ if (!remoteEntityRow && remoteEC.entityName === "options") {return; // can be undefined for options with isSynced=false}- const updated = remoteEC.entityName === 'note_reordering'- ? updateNoteReordering(remoteEC, remoteEntityRow, instanceId)- : updateNormalEntity(remoteEC, remoteEntityRow, instanceId, updateContext);+ const updated = remoteEC.entityName === "note_reordering" ? updateNoteReordering(remoteEC, remoteEntityRow, instanceId) : updateNormalEntity(remoteEC, remoteEntityRow, instanceId, updateContext);if (updated) {if (remoteEntityRow?.isDeleted) {@@ -62,8 +60,7 @@ function updateEntity(remoteEC: EntityChange, remoteEntityRow: EntityRow | undefentityName: remoteEC.entityName,entityId: remoteEC.entityId});- }- else if (!remoteEC.isErased) {+ } else if (!remoteEC.isErased) {eventService.emit(eventService.ENTITY_CHANGE_SYNCED, {entityName: remoteEC.entityName,entityRow: remoteEntityRow@@ -74,9 +71,7 @@ function updateEntity(remoteEC: EntityChange, remoteEntityRow: EntityRow | undeffunction updateNormalEntity(remoteEC: EntityChange, remoteEntityRow: EntityRow | undefined, instanceId: string, updateContext: UpdateContext) {const localEC = sql.getRow<EntityChange | undefined>(`SELECT * FROM entity_changes WHERE entityName = ? AND entityId = ?`, [remoteEC.entityName, remoteEC.entityId]);- const localECIsOlderOrSameAsRemote = (- localEC && localEC.utcDateChanged && remoteEC.utcDateChanged &&- localEC.utcDateChanged <= remoteEC.utcDateChanged);+ const localECIsOlderOrSameAsRemote = localEC && localEC.utcDateChanged && remoteEC.utcDateChanged && localEC.utcDateChanged <= remoteEC.utcDateChanged;if (!localEC || localECIsOlderOrSameAsRemote) {if (remoteEC.isErased) {@@ -100,17 +95,12 @@ function updateNormalEntity(remoteEC: EntityChange, remoteEntityRow: EntityRow |updateContext.updated[remoteEC.entityName].push(remoteEC.entityId);}- if (!localEC- || localECIsOlderOrSameAsRemote- || localEC.hash !== remoteEC.hash- || localEC.isErased !== remoteEC.isErased- ) {+ if (!localEC || localECIsOlderOrSameAsRemote || localEC.hash !== remoteEC.hash || localEC.isErased !== remoteEC.isErased) {entityChangesService.putEntityChangeWithInstanceId(remoteEC, instanceId);}return true;- } else if ((localEC.hash !== remoteEC.hash || localEC.isErased !== remoteEC.isErased)- && !localECIsOlderOrSameAsRemote) {+ } else if ((localEC.hash !== remoteEC.hash || localEC.isErased !== remoteEC.isErased) && !localECIsOlderOrSameAsRemote) {// the change on our side is newer than on the other side, so the other side should updateentityChangesService.putEntityChangeForOtherInstances(localEC);@@ -121,12 +111,12 @@ function updateNormalEntity(remoteEC: EntityChange, remoteEntityRow: EntityRow |}function preProcessContent(remoteEC: EntityChange, remoteEntityRow: EntityRow) {- if (remoteEC.entityName === 'blobs' && remoteEntityRow.content !== null) {+ if (remoteEC.entityName === "blobs" && remoteEntityRow.content !== null) {// we always use a Buffer object which is different from normal saving - there we use a simple string type for// "string notes". The problem is that in general, it's not possible to detect whether a blob content// is string note or note (syncs can arrive out of order)if (typeof remoteEntityRow.content === "string") {- remoteEntityRow.content = Buffer.from(remoteEntityRow.content, 'base64');+ remoteEntityRow.content = Buffer.from(remoteEntityRow.content, "base64");if (remoteEntityRow.content.byteLength === 0) {// there seems to be a bug which causes empty buffer to be stored as NULL which is then picked up as inconsistency@@ -152,16 +142,9 @@ function updateNoteReordering(remoteEC: EntityChange, remoteEntityRow: EntityRow}function eraseEntity(entityChange: EntityChange) {- const {entityName, entityId} = entityChange;+ const { entityName, entityId } = entityChange;- const entityNames = [- "notes",- "branches",- "attributes",- "revisions",- "attachments",- "blobs"- ];+ const entityNames = ["notes", "branches", "attributes", "revisions", "attachments", "blobs"];if (!entityNames.includes(entityName)) {log.error(`Cannot erase ${entityName} '${entityId}'.`);@@ -174,10 +157,7 @@ function eraseEntity(entityChange: EntityChange) {}function logUpdateContext(updateContext: UpdateContext) {- const message = JSON.stringify(updateContext)- .replaceAll('"', '')- .replaceAll(":", ": ")- .replaceAll(",", ", ");+ const message = JSON.stringify(updateContext).replaceAll('"', "").replaceAll(":", ": ").replaceAll(",", ", ");log.info(message.substr(1, message.length - 2));}diff --git a/src/services/task_context.ts b/src/services/task_context.tsindex 64e57a000d..9319b84a8b 100644--- a/src/services/task_context.ts+++ b/src/services/task_context.ts@@ -1,13 +1,12 @@"use strict";-import { TaskData } from './task_context_interface.js';+import { TaskData } from "./task_context_interface.js";import ws from "./ws.js";// taskId => TaskContextconst taskContexts: Record<string, TaskContext> = {};class TaskContext {-private taskId: string;private taskType: string | null;private progressCount: number;@@ -43,11 +42,11 @@ class TaskContext {increaseProgressCount() {this.progressCount++;- if (Date.now() - this.lastSentCountTs >= 300 && this.taskId !== 'no-progress-reporting') {+ if (Date.now() - this.lastSentCountTs >= 300 && this.taskId !== "no-progress-reporting") {this.lastSentCountTs = Date.now();ws.sendMessageToAllClients({- type: 'taskProgressCount',+ type: "taskProgressCount",taskId: this.taskId,taskType: this.taskType,data: this.data,@@ -58,7 +57,7 @@ class TaskContext {reportError(message: string) {ws.sendMessageToAllClients({- type: 'taskError',+ type: "taskError",taskId: this.taskId,taskType: this.taskType,data: this.data,@@ -68,7 +67,7 @@ class TaskContext {taskSucceeded(result?: string | Record<string, string | undefined>) {ws.sendMessageToAllClients({- type: 'taskSucceeded',+ type: "taskSucceeded",taskId: this.taskId,taskType: this.taskType,data: this.data,diff --git a/src/services/tray.ts b/src/services/tray.tsindex a163a5a22a..1652dec4a8 100644--- a/src/services/tray.ts+++ b/src/services/tray.ts@@ -1,4 +1,4 @@-import { Menu, Tray } from 'electron';+import { Menu, Tray } from "electron";import path from "path";import windowService from "./window.js";import optionService from "./options.js";@@ -9,56 +9,52 @@ let tray: Tray;// is minimizedlet isVisible = true;-// Inspired by https://github.com/signalapp/Signal-Desktop/blob/dcb5bb672635c4b29a51adec8a5658e3834ec8fc/app/tray_icon.ts#L20const getIconSize = () => {switch (process.platform) {- case 'darwin':+ case "darwin":return 16;- case 'win32':+ case "win32":return 32;default:return 256;}-}+};const getIconPath = () => {const iconSize = getIconSize();- return path.join(- path.dirname(fileURLToPath(import.meta.url)),- "../..",- "images",- "app-icons",- "png",- `${iconSize}x${iconSize}.png`- )-}+ return path.join(path.dirname(fileURLToPath(import.meta.url)), "../..", "images", "app-icons", "png", `${iconSize}x${iconSize}.png`);+};const registerVisibilityListener = () => {const mainWindow = windowService.getMainWindow();- if (!mainWindow) { return; }+ if (!mainWindow) {+ return;+ }// They need to be registered before the tray updater is registered- mainWindow.on('show', () => {+ mainWindow.on("show", () => {isVisible = true;updateTrayMenu();});- mainWindow.on('hide', () => {+ mainWindow.on("hide", () => {isVisible = false;updateTrayMenu();});mainWindow.on("minimize", updateTrayMenu);mainWindow.on("maximize", updateTrayMenu);-}+};const updateTrayMenu = () => {const mainWindow = windowService.getMainWindow();- if (!mainWindow) { return; }+ if (!mainWindow) {+ return;+ }const contextMenu = Menu.buildFromTemplate([{- label: isVisible ? 'Hide' : 'Show',- type: 'normal',+ label: isVisible ? "Hide" : "Show",+ type: "normal",click: () => {if (isVisible) {mainWindow.hide();@@ -69,22 +65,24 @@ const updateTrayMenu = () => {}},{- type: 'separator'+ type: "separator"},{- label: 'Quit',- type: 'normal',+ label: "Quit",+ type: "normal",click: () => {mainWindow.close();}- },+ }]);tray?.setContextMenu(contextMenu);-}+};const changeVisibility = () => {const window = windowService.getMainWindow();- if (!window) { return; }+ if (!window) {+ return;+ }if (isVisible) {window.hide();@@ -92,7 +90,7 @@ const changeVisibility = () => {window.show();window.focus();}-}+};function createTray() {if (optionService.getOptionBool("disableTray")) {@@ -100,9 +98,9 @@ function createTray() {}tray = new Tray(getIconPath());- tray.setToolTip('TriliumNext Notes')+ tray.setToolTip("TriliumNext Notes");// Restore focus- tray.on('click', changeVisibility)+ tray.on("click", changeVisibility);updateTrayMenu();registerVisibilityListener();@@ -110,4 +108,4 @@ function createTray() {export default {createTray-}+};diff --git a/src/services/tree.ts b/src/services/tree.tsindex 0ab72e7f79..5a652a22d3 100644--- a/src/services/tree.ts+++ b/src/services/tree.ts@@ -14,11 +14,11 @@ interface ValidationResponse {}function validateParentChild(parentNoteId: string, childNoteId: string, branchId: string | null = null): ValidationResponse {- if (['root', '_hidden', '_share', '_lbRoot', '_lbAvailableLaunchers', '_lbVisibleLaunchers'].includes(childNoteId)) {+ if (["root", "_hidden", "_share", "_lbRoot", "_lbAvailableLaunchers", "_lbVisibleLaunchers"].includes(childNoteId)) {return { branch: null, success: false, message: `Cannot change this note's location.` };}- if (parentNoteId === 'none') {+ if (parentNoteId === "none") {// this shouldn't happenreturn { branch: null, success: false, message: `Cannot move anything into 'none' parent.` };}@@ -40,15 +40,15 @@ function validateParentChild(parentNoteId: string, childNoteId: string, branchIdreturn {branch: null,success: false,- message: 'Moving/cloning note here would create cycle.'+ message: "Moving/cloning note here would create cycle."};}- if (parentNoteId !== '_lbBookmarks' && becca.getNote(parentNoteId)?.type === 'launcher') {+ if (parentNoteId !== "_lbBookmarks" && becca.getNote(parentNoteId)?.type === "launcher") {return {branch: null,success: false,- message: 'Launcher note cannot have any children.'+ message: "Launcher note cannot have any children."};}@@ -74,16 +74,16 @@ function wouldAddingBranchCreateCycle(parentNoteId: string, childNoteId: string)const childSubtreeNoteIds = new Set(childNote.getSubtreeNoteIds());const parentAncestorNoteIds = parentNote.getAncestorNoteIds();- return parentAncestorNoteIds.some(parentAncestorNoteId => childSubtreeNoteIds.has(parentAncestorNoteId));+ return parentAncestorNoteIds.some((parentAncestorNoteId) => childSubtreeNoteIds.has(parentAncestorNoteId));}-function sortNotes(parentNoteId: string, customSortBy: string = 'title', reverse = false, foldersFirst = false, sortNatural = false, _sortLocale?: string | null) {+function sortNotes(parentNoteId: string, customSortBy: string = "title", reverse = false, foldersFirst = false, sortNatural = false, _sortLocale?: string | null) {if (!customSortBy) {- customSortBy = 'title';+ customSortBy = "title";}// sortLocale can not be empty string or null value, default value must be set to undefined.- const sortLocale = (_sortLocale || undefined);+ const sortLocale = _sortLocale || undefined;sql.transactional(() => {const note = becca.getNote(parentNoteId);@@ -92,7 +92,7 @@ function sortNotes(parentNoteId: string, customSortBy: string = 'title', reverse}const notes = note.getChildNotes();- const normalize = (obj: any) => (obj && typeof obj === 'string') ? obj.toLowerCase() : obj;+ const normalize = (obj: any) => (obj && typeof obj === "string" ? obj.toLowerCase() : obj);notes.sort((a, b) => {if (foldersFirst) {@@ -108,14 +108,12 @@ function sortNotes(parentNoteId: string, customSortBy: string = 'title', reversefunction fetchValue(note: BNote, key: string) {let rawValue;- if (key === 'title') {- const branch = note.getParentBranches().find(branch => branch.parentNoteId === parentNoteId);+ if (key === "title") {+ const branch = note.getParentBranches().find((branch) => branch.parentNoteId === parentNoteId);const prefix = branch?.prefix;rawValue = prefix ? `${prefix} - ${note.title}` : note.title;} else {- rawValue = ['dateCreated', 'dateModified'].includes(key)- ? (note as any)[key]- : note.getLabelValue(key);+ rawValue = ["dateCreated", "dateModified"].includes(key) ? (note as any)[key] : note.getLabelValue(key);}return normalize(rawValue);@@ -127,20 +125,20 @@ function sortNotes(parentNoteId: string, customSortBy: string = 'title', reversereturn b === null || b === undefined || a < b ? -1 : 1;} else {// natural sort- return a.localeCompare(b, sortLocale, {numeric: true, sensitivity: 'base'});+ return a.localeCompare(b, sortLocale, { numeric: true, sensitivity: "base" });}}- const topAEl = fetchValue(a, 'top');- const topBEl = fetchValue(b, 'top');+ const topAEl = fetchValue(a, "top");+ const topBEl = fetchValue(b, "top");if (topAEl !== topBEl) {// since "top" should not be reversible, we'll reverse it once more to nullify this effectreturn compare(topAEl, topBEl) * (reverse ? -1 : 1);}- const bottomAEl = fetchValue(a, 'bottom');- const bottomBEl = fetchValue(b, 'bottom');+ const bottomAEl = fetchValue(a, "bottom");+ const bottomBEl = fetchValue(b, "bottom");if (bottomAEl !== bottomBEl) {// since "bottom" should not be reversible, we'll reverse it once more to nullify this effect@@ -154,8 +152,8 @@ function sortNotes(parentNoteId: string, customSortBy: string = 'title', reversereturn compare(customAEl, customBEl);}- const titleAEl = fetchValue(a, 'title');- const titleBEl = fetchValue(b, 'title');+ const titleAEl = fetchValue(a, "title");+ const titleBEl = fetchValue(b, "title");return compare(titleAEl, titleBEl);});@@ -168,16 +166,17 @@ function sortNotes(parentNoteId: string, customSortBy: string = 'title', reverselet someBranchUpdated = false;for (const note of notes) {- const branch = note.getParentBranches().find(b => b.parentNoteId === parentNoteId);- if (!branch) { continue; }+ const branch = note.getParentBranches().find((b) => b.parentNoteId === parentNoteId);+ if (!branch) {+ continue;+ }- if (branch.noteId === '_hidden') {+ if (branch.noteId === "_hidden") {position = 999_999_999;}if (branch.notePosition !== position) {- sql.execute("UPDATE branches SET notePosition = ? WHERE branchId = ?",- [position, branch.branchId]);+ sql.execute("UPDATE branches SET notePosition = ? WHERE branchId = ?", [position, branch.branchId]);branch.notePosition = position;someBranchUpdated = true;@@ -198,16 +197,16 @@ function sortNotesIfNeeded(parentNoteId: string) {return;}- const sortedLabel = parentNote.getLabel('sorted');+ const sortedLabel = parentNote.getLabel("sorted");- if (!sortedLabel || sortedLabel.value === 'off') {+ if (!sortedLabel || sortedLabel.value === "off") {return;}- const sortReversed = parentNote.getLabelValue('sortDirection')?.toLowerCase() === "desc";- const sortFoldersFirst = parentNote.isLabelTruthy('sortFoldersFirst');- const sortNatural = parentNote.isLabelTruthy('sortNatural');- const sortLocale = parentNote.getLabelValue('sortLocale');+ const sortReversed = parentNote.getLabelValue("sortDirection")?.toLowerCase() === "desc";+ const sortFoldersFirst = parentNote.isLabelTruthy("sortFoldersFirst");+ const sortNatural = parentNote.isLabelTruthy("sortNatural");+ const sortLocale = parentNote.getLabelValue("sortLocale");sortNotes(parentNoteId, sortedLabel.value, sortReversed, sortFoldersFirst, sortNatural, sortLocale);}@@ -232,15 +231,13 @@ function setNoteToParent(noteId: string, prefix: string, parentNoteId: string) {log.info(`Removing note '${noteId}' from parent '${parentNoteId}'`);branch.markAsDeleted();- }- else {+ } else {const newBranch = branch.createClone(parentNoteId);newBranch.save();branch.markAsDeleted();}- }- else if (parentNoteId) {+ } else if (parentNoteId) {const note = becca.getNote(noteId);if (!note) {throw new Error(`Cannot find note '${noteId}.`);@@ -250,14 +247,13 @@ function setNoteToParent(noteId: string, prefix: string, parentNoteId: string) {throw new Error(`Cannot create a branch for '${noteId}' which is deleted.`);}- const branchId = sql.getValue<string>('SELECT branchId FROM branches WHERE isDeleted = 0 AND noteId = ? AND parentNoteId = ?', [noteId, parentNoteId]);+ const branchId = sql.getValue<string>("SELECT branchId FROM branches WHERE isDeleted = 0 AND noteId = ? AND parentNoteId = ?", [noteId, parentNoteId]);const branch = becca.getBranch(branchId);if (branch) {branch.prefix = prefix;branch.save();- }- else {+ } else {new BBranch({noteId: noteId,parentNoteId: parentNoteId,diff --git a/src/services/utils.ts b/src/services/utils.tsindex 854953f753..4d4f42936e 100644--- a/src/services/utils.ts+++ b/src/services/utils.ts@@ -11,7 +11,7 @@ import { fileURLToPath } from "url";import env from "./env.js";import { dirname, join } from "path";-const randtoken = generator({source: 'crypto'});+const randtoken = generator({ source: "crypto" });export function newEntityId() {return randomString(12);@@ -22,11 +22,11 @@ export function randomString(length: number): string {}export function randomSecureToken(bytes = 32) {- return crypto.randomBytes(bytes).toString('base64');+ return crypto.randomBytes(bytes).toString("base64");}export function md5(content: crypto.BinaryLike) {- return crypto.createHash('md5').update(content).digest('hex');+ return crypto.createHash("md5").update(content).digest("hex");}export function hashedBlobId(content: string | Buffer) {@@ -35,39 +35,37 @@ export function hashedBlobId(content: string | Buffer) {}// sha512 is faster than sha256- const base64Hash = crypto.createHash('sha512').update(content).digest('base64');+ const base64Hash = crypto.createHash("sha512").update(content).digest("base64");// we don't want such + and / in the IDs- const kindaBase62Hash = base64Hash- .replaceAll('+', 'X')- .replaceAll('/', 'Y');+ const kindaBase62Hash = base64Hash.replaceAll("+", "X").replaceAll("/", "Y");// 20 characters of base62 gives us ~120 bit of entropy which is plenty enoughreturn kindaBase62Hash.substr(0, 20);}export function toBase64(plainText: string | Buffer) {- return Buffer.from(plainText).toString('base64');+ return Buffer.from(plainText).toString("base64");}export function fromBase64(encodedText: string) {- return Buffer.from(encodedText, 'base64');+ return Buffer.from(encodedText, "base64");}export function hmac(secret: any, value: any) {- const hmac = crypto.createHmac('sha256', Buffer.from(secret.toString(), 'ascii'));+ const hmac = crypto.createHmac("sha256", Buffer.from(secret.toString(), "ascii"));hmac.update(value.toString());- return hmac.digest('base64');+ return hmac.digest("base64");}export function isElectron() {- return !!process.versions['electron'];+ return !!process.versions["electron"];}export function hash(text: string) {text = text.normalize();- return crypto.createHash('sha1').update(text).digest('base64');+ return crypto.createHash("sha1").update(text).digest("base64");}export function isEmptyOrWhitespace(str: string) {@@ -99,24 +97,25 @@ export function toObject<T, K extends string | number | symbol, V>(array: T[], f}export function stripTags(text: string) {- return text.replace(/<(?:.|\n)*?>/gm, '');+ return text.replace(/<(?:.|\n)*?>/gm, "");}export function union<T extends string | number | symbol>(a: T[], b: T[]): T[] {const obj: Record<T, T> = {} as Record<T, T>; // TODO: unsafe?- for (let i = a.length-1; i >= 0; i--) {+ for (let i = a.length - 1; i >= 0; i--) {obj[a[i]] = a[i];}- for (let i = b.length-1; i >= 0; i--) {+ for (let i = b.length - 1; i >= 0; i--) {obj[b[i]] = b[i];}const res: T[] = [];for (const k in obj) {- if (obj.hasOwnProperty(k)) { // <-- optional+ if (obj.hasOwnProperty(k)) {+ // <-- optionalres.push(obj[k]);}}@@ -152,23 +151,15 @@ export function getContentDisposition(filename: string) {return `file; filename="${sanitizedFilename}"; filename*=UTF-8''${sanitizedFilename}`;}-const STRING_MIME_TYPES = new Set([- "application/javascript",- "application/x-javascript",- "application/json",- "application/x-sql",- "image/svg+xml"-]);+const STRING_MIME_TYPES = new Set(["application/javascript", "application/x-javascript", "application/json", "application/x-sql", "image/svg+xml"]);export function isStringNote(type: string | undefined, mime: string) {// render and book are string note in the sense that they are expected to contain empty string- return (type && ["text", "code", "relationMap", "search", "render", "book", "mermaid", "canvas"].includes(type))- || mime.startsWith('text/')- || STRING_MIME_TYPES.has(mime);+ return (type && ["text", "code", "relationMap", "search", "render", "book", "mermaid", "canvas"].includes(type)) || mime.startsWith("text/") || STRING_MIME_TYPES.has(mime);}export function quoteRegex(url: string) {- return url.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');+ return url.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");}export function replaceAll(string: string, replaceWhat: string, replaceWith: string) {@@ -178,29 +169,29 @@ export function replaceAll(string: string, replaceWhat: string, replaceWith: str}export function formatDownloadTitle(fileName: string, type: string | null, mime: string) {- const fileNameBase = (!fileName) ? "untitled" : sanitize(fileName);+ const fileNameBase = !fileName ? "untitled" : sanitize(fileName);- const getExtension = () => {- if (type === "text") return ".html";- if (type === "relationMap" || type === "canvas" || type === "search") return ".json";- if (!mime) return "";+ const getExtension = () => {+ if (type === "text") return ".html";+ if (type === "relationMap" || type === "canvas" || type === "search") return ".json";+ if (!mime) return "";- const mimeLc = mime.toLowerCase();+ const mimeLc = mime.toLowerCase();- // better to just return the current name without a fake extension- // it's possible that the title still preserves the correct extension anyways- if (mimeLc === 'application/octet-stream') return "";+ // better to just return the current name without a fake extension+ // it's possible that the title still preserves the correct extension anyways+ if (mimeLc === "application/octet-stream") return "";- // if fileName has an extension matching the mime already - reuse it- const mimeTypeFromFileName = mimeTypes.lookup(fileName);- if (mimeTypeFromFileName === mimeLc) return "";+ // if fileName has an extension matching the mime already - reuse it+ const mimeTypeFromFileName = mimeTypes.lookup(fileName);+ if (mimeTypeFromFileName === mimeLc) return "";- // as last resort try to get extension from mimeType- const extensions = mimeTypes.extension(mime);- return extensions ? `.${extensions}` : "";- };+ // as last resort try to get extension from mimeType+ const extensions = mimeTypes.extension(mime);+ return extensions ? `.${extensions}` : "";+ };- return `${fileNameBase}${getExtension()}`;+ return `${fileNameBase}${getExtension()}`;}export function removeTextFileExtension(filePath: string) {@@ -223,14 +214,15 @@ export function getNoteTitle(filePath: string, replaceUnderscoresWithSpaces: boo} else {const basename = path.basename(removeTextFileExtension(filePath));if (replaceUnderscoresWithSpaces) {- return basename.replace(/_/g, ' ').trim();+ return basename.replace(/_/g, " ").trim();}return basename;}}export function timeLimit<T>(promise: Promise<T>, limitMs: number, errorMessage?: string): Promise<T> {- if (!promise || !promise.then) { // it's not actually a promise+ if (!promise || !promise.then) {+ // it's not actually a promisereturn promise;}@@ -240,12 +232,13 @@ export function timeLimit<T>(promise: Promise<T>, limitMs: number, errorMessage?return new Promise((res, rej) => {let resolved = false;- promise.then(result => {- resolved = true;+ promise+ .then((result) => {+ resolved = true;- res(result);- })- .catch(error => rej(error));+ res(result);+ })+ .catch((error) => rej(error));setTimeout(() => {if (!resolved) {@@ -256,8 +249,8 @@ export function timeLimit<T>(promise: Promise<T>, limitMs: number, errorMessage?}interface DeferredPromise<T> extends Promise<T> {- resolve: (value: T | PromiseLike<T>) => void,- reject: (reason?: any) => void+ resolve: (value: T | PromiseLike<T>) => void;+ reject: (reason?: any) => void;}export function deferred<T>(): DeferredPromise<T> {@@ -317,11 +310,11 @@ export function getResourceDir() {}export function isMac() {- return process.platform === "darwin";+ return process.platform === "darwin";}export function isWindows() {- return process.platform === "win32";+ return process.platform === "win32";}export default {diff --git a/src/services/window.ts b/src/services/window.tsindex 3d81d3e1d7..8333fe7274 100644--- a/src/services/window.ts+++ b/src/services/window.ts@@ -8,7 +8,7 @@ import sqlInit from "./sql_init.js";import cls from "./cls.js";import keyboardActionsService from "./keyboard_actions.js";import remoteMain from "@electron/remote/main/index.js";-import { App, BrowserWindow, BrowserWindowConstructorOptions, WebContents, ipcMain } from 'electron';+import { App, BrowserWindow, BrowserWindowConstructorOptions, WebContents, ipcMain } from "electron";import { isMac, isWindows } from "./utils.js";import { fileURLToPath } from "url";@@ -19,14 +19,14 @@ let mainWindow: BrowserWindow | null;let setupWindow: BrowserWindow | null;async function createExtraWindow(extraWindowHash: string) {- const spellcheckEnabled = optionService.getOptionBool('spellCheckEnabled');+ const spellcheckEnabled = optionService.getOptionBool("spellCheckEnabled");- const { BrowserWindow } = await import('electron');+ const { BrowserWindow } = await import("electron");const win = new BrowserWindow({width: 1000,height: 800,- title: 'TriliumNext Notes',+ title: "TriliumNext Notes",webPreferences: {nodeIntegration: true,contextIsolation: false,@@ -42,7 +42,7 @@ async function createExtraWindow(extraWindowHash: string) {configureWebContents(win.webContents, spellcheckEnabled);}-ipcMain.on('create-extra-window', (event, arg) => {+ipcMain.on("create-extra-window", (event, arg) => {createExtraWindow(arg.extraWindowHash);});@@ -51,16 +51,16 @@ async function createMainWindow(app: App) {app.setUserTasks([{program: process.execPath,- arguments: '--new-window',+ arguments: "--new-window",iconPath: process.execPath,iconIndex: 0,- title: 'Open New Window',- description: 'Open new window'+ title: "Open New Window",+ description: "Open new window"}]);}- const windowStateKeeper = (await import('electron-window-state')).default; // should not be statically imported+ const windowStateKeeper = (await import("electron-window-state")).default; // should not be statically importedconst mainWindowState = windowStateKeeper({// default window width & height, so it's usable on a 1600 * 900 display (including some extra panels etc.)@@ -68,18 +68,16 @@ async function createMainWindow(app: App) {defaultHeight: 800});- const spellcheckEnabled = optionService.getOptionBool('spellCheckEnabled');-- const { BrowserWindow } = (await import('electron')); // should not be statically imported-+ const spellcheckEnabled = optionService.getOptionBool("spellCheckEnabled");+ const { BrowserWindow } = await import("electron"); // should not be statically importedmainWindow = new BrowserWindow({x: mainWindowState.x,y: mainWindowState.y,width: mainWindowState.width,height: mainWindowState.height,- title: 'TriliumNext Notes',+ title: "TriliumNext Notes",webPreferences: {nodeIntegration: true,contextIsolation: false,@@ -94,12 +92,12 @@ async function createMainWindow(app: App) {mainWindow.setMenuBarVisibility(false);mainWindow.loadURL(`http://127.0.0.1:${port}`);- mainWindow.on('closed', () => mainWindow = null);+ mainWindow.on("closed", () => (mainWindow = null));configureWebContents(mainWindow.webContents, spellcheckEnabled);- app.on('second-instance', (event, commandLine) => {- if (commandLine.includes('--new-window')) {+ app.on("second-instance", (event, commandLine) => {+ if (commandLine.includes("--new-window")) {createExtraWindow("");} else if (mainWindow) {// Someone tried to run a second instance, we should focus our window.@@ -116,7 +114,7 @@ async function createMainWindow(app: App) {function getWindowExtraOpts() {const extraOpts: Partial<BrowserWindowConstructorOptions> = {};- if (!optionService.getOptionBool('nativeTitleBarVisible')) {+ if (!optionService.getOptionBool("nativeTitleBarVisible")) {if (isMac()) {extraOpts.titleBarStyle = "hiddenInset";extraOpts.titleBarOverlay = true;@@ -130,7 +128,7 @@ function getWindowExtraOpts() {}// Window effects (Mica)- if (optionService.getOptionBool('backgroundEffects') && isWindows()) {+ if (optionService.getOptionBool("backgroundEffects") && isWindows()) {extraOpts.backgroundMaterial = "auto";}@@ -142,34 +140,35 @@ function configureWebContents(webContents: WebContents, spellcheckEnabled: boolewebContents.setWindowOpenHandler((details) => {async function openExternal() {- (await import('electron')).shell.openExternal(details.url);+ (await import("electron")).shell.openExternal(details.url);}openExternal();- return { action: 'deny' }+ return { action: "deny" };});// prevent drag & drop to navigate away from trilium- webContents.on('will-navigate', (ev, targetUrl) => {+ webContents.on("will-navigate", (ev, targetUrl) => {const parsedUrl = url.parse(targetUrl);// we still need to allow internal redirects from setup and migration pages- if (!['localhost', '127.0.0.1'].includes(parsedUrl.hostname || "") || (parsedUrl.path && parsedUrl.path !== '/' && parsedUrl.path !== '/?')) {+ if (!["localhost", "127.0.0.1"].includes(parsedUrl.hostname || "") || (parsedUrl.path && parsedUrl.path !== "/" && parsedUrl.path !== "/?")) {ev.preventDefault();}});if (spellcheckEnabled) {- const languageCodes = (optionService.getOption('spellCheckLanguageCode'))- .split(',')- .map(code => code.trim());+ const languageCodes = optionService+ .getOption("spellCheckLanguageCode")+ .split(",")+ .map((code) => code.trim());webContents.session.setSpellCheckerLanguages(languageCodes);}}function getIcon() {- return path.join(dirname(fileURLToPath(import.meta.url)), '../../images/app-icons/png/256x256' + (env.isDev() ? '-dev' : '') + '.png');+ return path.join(dirname(fileURLToPath(import.meta.url)), "../../images/app-icons/png/256x256" + (env.isDev() ? "-dev" : "") + ".png");}async function createSetupWindow() {@@ -177,7 +176,7 @@ async function createSetupWindow() {setupWindow = new BrowserWindow({width: 800,height: 800,- title: 'TriliumNext Notes Setup',+ title: "TriliumNext Notes Setup",icon: getIcon(),webPreferences: {// necessary for e.g. utils.isElectron()@@ -187,7 +186,7 @@ async function createSetupWindow() {setupWindow.setMenuBarVisibility(false);setupWindow.loadURL(`http://127.0.0.1:${port}`);- setupWindow.on('closed', () => setupWindow = null);+ setupWindow.on("closed", () => (setupWindow = null));}function closeSetupWindow() {@@ -209,24 +208,26 @@ async function registerGlobalShortcuts() {}for (const shortcut of action.effectiveShortcuts) {- if (shortcut.startsWith('global:')) {+ if (shortcut.startsWith("global:")) {const translatedShortcut = shortcut.substr(7);- const result = globalShortcut.register(translatedShortcut, cls.wrap(() => {- if (!mainWindow) {- return;- }+ const result = globalShortcut.register(+ translatedShortcut,+ cls.wrap(() => {+ if (!mainWindow) {+ return;+ }- // window may be hidden / not in focus- mainWindow.focus();+ // window may be hidden / not in focus+ mainWindow.focus();- mainWindow.webContents.send('globalShortcut', action.actionName);- }));+ mainWindow.webContents.send("globalShortcut", action.actionName);+ })+ );if (result) {log.info(`Registered global shortcut ${translatedShortcut} for action ${action.actionName}`);- }- else {+ } else {log.info(`Could not register global shortcut ${translatedShortcut}`);}}diff --git a/src/services/ws.ts b/src/services/ws.tsindex 9993062a9d..19252d921c 100644--- a/src/services/ws.ts+++ b/src/services/ws.ts@@ -10,18 +10,18 @@ import becca from "../becca/becca.js";import AbstractBeccaEntity from "../becca/entities/abstract_becca_entity.js";import env from "./env.js";-import { IncomingMessage, Server } from 'http';-import { EntityChange } from './entity_changes_interface.js';+import { IncomingMessage, Server } from "http";+import { EntityChange } from "./entity_changes_interface.js";if (env.isDev()) {const chokidar = (await import("chokidar")).default;const debounce = (await import("debounce")).default;const debouncedReloadFrontend = debounce(() => reloadFrontend("source code change"), 200);chokidar- .watch(isElectron() ? 'dist/src/public' : 'src/public')- .on('add', debouncedReloadFrontend)- .on('change', debouncedReloadFrontend)- .on('unlink', debouncedReloadFrontend);+ .watch(isElectron() ? "dist/src/public" : "src/public")+ .on("add", debouncedReloadFrontend)+ .on("change", debouncedReloadFrontend)+ .on("unlink", debouncedReloadFrontend);}let webSocketServer!: WebSocket.Server;@@ -30,11 +30,11 @@ let lastSyncedPush: number | null = null;interface Message {type: string;data?: {- lastSyncedPush?: number | null,- entityChanges?: any[],- shrinkImages?: boolean- } | null,- lastSyncedPush?: number | null,+ lastSyncedPush?: number | null;+ entityChanges?: any[];+ shrinkImages?: boolean;+ } | null;+ lastSyncedPush?: number | null;progressCount?: number;taskId?: string;@@ -62,46 +62,41 @@ function init(httpServer: Server, sessionParser: SessionParser) {webSocketServer = new WebSocket.Server({verifyClient: (info, done) => {sessionParser(info.req, {}, () => {- const allowed = isElectron()- || (info.req as any).session.loggedIn- || (config.General && config.General.noAuthentication);+ const allowed = isElectron() || (info.req as any).session.loggedIn || (config.General && config.General.noAuthentication);if (!allowed) {log.error("WebSocket connection not allowed because session is neither electron nor logged in.");}- done(allowed)+ done(allowed);});},server: httpServer});- webSocketServer.on('connection', (ws, req) => {+ webSocketServer.on("connection", (ws, req) => {(ws as any).id = randomString(10);console.log(`websocket client connected`);- ws.on('message', async messageJson => {+ ws.on("message", async (messageJson) => {const message = JSON.parse(messageJson as any);- if (message.type === 'log-error') {+ if (message.type === "log-error") {log.info(`JS Error: ${message.error}\rStack: ${message.stack}`);- }- else if (message.type === 'log-info') {+ } else if (message.type === "log-info") {log.info(`JS Info: ${message.info}`);- }- else if (message.type === 'ping') {+ } else if (message.type === "ping") {await syncMutexService.doExclusively(() => sendPing(ws));- }- else {- log.error('Unrecognized message: ');+ } else {+ log.error("Unrecognized message: ");log.error(message);}});});- webSocketServer.on('error', error => {+ webSocketServer.on("error", (error) => {// https://github.com/zadam/trilium/issues/3374#issuecomment-1341053765console.log(error);});@@ -119,7 +114,7 @@ function sendMessageToAllClients(message: Message) {const jsonStr = JSON.stringify(message);if (webSocketServer) {- if (message.type !== 'sync-failed' && message.type !== 'api-log-messages') {+ if (message.type !== "sync-failed" && message.type !== "api-log-messages") {log.info(`Sending message to all clients: ${jsonStr}`);}@@ -139,19 +134,19 @@ function fillInAdditionalProperties(entityChange: EntityChange) {// fill in some extra data needed by the frontend// first try to use becca, which works for non-deleted entities// only when that fails, try to load from the database- if (entityChange.entityName === 'attributes') {+ if (entityChange.entityName === "attributes") {entityChange.entity = becca.getAttribute(entityChange.entityId);if (!entityChange.entity) {entityChange.entity = sql.getRow(`SELECT * FROM attributes WHERE attributeId = ?`, [entityChange.entityId]);}- } else if (entityChange.entityName === 'branches') {+ } else if (entityChange.entityName === "branches") {entityChange.entity = becca.getBranch(entityChange.entityId);if (!entityChange.entity) {entityChange.entity = sql.getRow(`SELECT * FROM branches WHERE branchId = ?`, [entityChange.entityId]);}- } else if (entityChange.entityName === 'notes') {+ } else if (entityChange.entityName === "notes") {entityChange.entity = becca.getNote(entityChange.entityId);if (!entityChange.entity) {@@ -161,11 +156,14 @@ function fillInAdditionalProperties(entityChange: EntityChange) {entityChange.entity.title = protectedSessionService.decryptString(entityChange.entity.title || "");}}- } else if (entityChange.entityName === 'revisions') {- entityChange.noteId = sql.getValue<string>(`SELECT noteId+ } else if (entityChange.entityName === "revisions") {+ entityChange.noteId = sql.getValue<string>(+ `SELECT noteIdFROM revisions- WHERE revisionId = ?`, [entityChange.entityId]);- } else if (entityChange.entityName === 'note_reordering') {+ WHERE revisionId = ?`,+ [entityChange.entityId]+ );+ } else if (entityChange.entityName === "note_reordering") {entityChange.positions = {};const parentNote = becca.getNote(entityChange.entityId);@@ -177,17 +175,20 @@ function fillInAdditionalProperties(entityChange: EntityChange) {}}}- } else if (entityChange.entityName === 'options') {+ } else if (entityChange.entityName === "options") {entityChange.entity = becca.getOption(entityChange.entityId);if (!entityChange.entity) {entityChange.entity = sql.getRow(`SELECT * FROM options WHERE name = ?`, [entityChange.entityId]);}- } else if (entityChange.entityName === 'attachments') {- entityChange.entity = sql.getRow(`SELECT attachments.*, LENGTH(blobs.content) AS contentLength+ } else if (entityChange.entityName === "attachments") {+ entityChange.entity = sql.getRow(+ `SELECT attachments.*, LENGTH(blobs.content) AS contentLengthFROM attachmentsJOIN blobs USING (blobId)- WHERE attachmentId = ?`, [entityChange.entityId]);+ WHERE attachmentId = ?`,+ [entityChange.entityId]+ );}if (entityChange.entity instanceof AbstractBeccaEntity) {@@ -197,20 +198,20 @@ function fillInAdditionalProperties(entityChange: EntityChange) {// entities with higher number can reference the entities with lower numberconst ORDERING: Record<string, number> = {- "etapi_tokens": 0,- "attributes": 2,- "branches": 2,- "blobs": 0,- "note_reordering": 2,- "revisions": 2,- "attachments": 3,- "notes": 1,- "options": 0+ etapi_tokens: 0,+ attributes: 2,+ branches: 2,+ blobs: 0,+ note_reordering: 2,+ revisions: 2,+ attachments: 3,+ notes: 1,+ options: 0};function sendPing(client: WebSocket, entityChangeIds = []) {if (entityChangeIds.length === 0) {- sendMessage(client, { type: 'ping' });+ sendMessage(client, { type: "ping" });return;}@@ -228,14 +229,13 @@ function sendPing(client: WebSocket, entityChangeIds = []) {for (const entityChange of entityChanges) {try {fillInAdditionalProperties(entityChange);- }- catch (e: any) {+ } catch (e: any) {log.error(`Could not fill additional properties for entity change ${JSON.stringify(entityChange)} because of error: ${e.message}: ${e.stack}`);}}sendMessage(client, {- type: 'frontend-update',+ type: "frontend-update",data: {lastSyncedPush,entityChanges@@ -247,28 +247,28 @@ function sendTransactionEntityChangesToAllClients() {if (webSocketServer) {const entityChangeIds = cls.getAndClearEntityChangeIds();- webSocketServer.clients.forEach(client => sendPing(client, entityChangeIds));+ webSocketServer.clients.forEach((client) => sendPing(client, entityChangeIds));}}function syncPullInProgress() {- sendMessageToAllClients({ type: 'sync-pull-in-progress', lastSyncedPush });+ sendMessageToAllClients({ type: "sync-pull-in-progress", lastSyncedPush });}function syncPushInProgress() {- sendMessageToAllClients({ type: 'sync-push-in-progress', lastSyncedPush });+ sendMessageToAllClients({ type: "sync-push-in-progress", lastSyncedPush });}function syncFinished() {- sendMessageToAllClients({ type: 'sync-finished', lastSyncedPush });+ sendMessageToAllClients({ type: "sync-finished", lastSyncedPush });}function syncFailed() {- sendMessageToAllClients({ type: 'sync-failed', lastSyncedPush });+ sendMessageToAllClients({ type: "sync-failed", lastSyncedPush });}function reloadFrontend(reason: string) {- sendMessageToAllClients({ type: 'reload-frontend', reason });+ sendMessageToAllClients({ type: "reload-frontend", reason });}function setLastSyncedPush(entityChangeId: number) {diff --git a/src/share/content_renderer.ts b/src/share/content_renderer.tsindex 31845d6ee8..6680bacda8 100644--- a/src/share/content_renderer.ts+++ b/src/share/content_renderer.ts@@ -14,32 +14,32 @@ interface Result {function getContent(note: SNote) {if (note.isProtected) {return {- header: '',- content: '<p>Protected note cannot be displayed</p>',+ header: "",+ content: "<p>Protected note cannot be displayed</p>",isEmpty: false};}const result: Result = {content: note.getContent(),- header: '',+ header: "",isEmpty: false};- if (note.type === 'text') {+ if (note.type === "text") {renderText(result, note);- } else if (note.type === 'code') {+ } else if (note.type === "code") {renderCode(result);- } else if (note.type === 'mermaid') {+ } else if (note.type === "mermaid") {renderMermaid(result, note);- } else if ([ "image", "canvas", "mindMap"].includes(note.type)) {+ } else if (["image", "canvas", "mindMap"].includes(note.type)) {renderImage(result, note);- } else if (note.type === 'file') {+ } else if (note.type === "file") {renderFile(note, result);- } else if (note.type === 'book') {+ } else if (note.type === "book") {result.isEmpty = true;} else {- result.content = '<p>This note type cannot be displayed.</p>';+ result.content = "<p>This note type cannot be displayed.</p>";}return result;@@ -57,14 +57,13 @@ function renderIndex(result: Result) {result.content += `<li><a class="${childNote.type}" href="${href}" ${target}>${childNote.escapedTitle}</a></li>`;}- result.content += '</ul>';+ result.content += "</ul>";}function renderText(result: Result, note: SNote) {const document = new JSDOM(result.content || "").window.document;- result.isEmpty = document.body.textContent?.trim().length === 0- && document.querySelectorAll("img").length === 0;+ result.isEmpty = document.body.textContent?.trim().length === 0 && document.querySelectorAll("img").length === 0;if (!result.isEmpty) {for (const linkEl of document.querySelectorAll("a")) {@@ -103,8 +102,8 @@ document.addEventListener("DOMContentLoaded", function() {function handleAttachmentLink(linkEl: HTMLAnchorElement, href: string) {const linkRegExp = /attachmentId=([a-zA-Z0-9_]+)/g;- let attachmentMatch- if (attachmentMatch = linkRegExp.exec(href)) {+ let attachmentMatch;+ if ((attachmentMatch = linkRegExp.exec(href))) {const attachmentId = attachmentMatch[1];const attachment = shaca.getAttachment(attachmentId);@@ -117,7 +116,7 @@ function handleAttachmentLink(linkEl: HTMLAnchorElement, href: string) {linkEl.removeAttribute("href");}} else {- const [notePath] = href.split('?');+ const [notePath] = href.split("?");const notePathSegments = notePath.split("/");const noteId = notePathSegments[notePathSegments.length - 1];const linkedNote = shaca.getNote(noteId);@@ -144,7 +143,7 @@ function renderCode(result: Result) {} else {const document = new JSDOM().window.document;- const preEl = document.createElement('pre');+ const preEl = document.createElement("pre");preEl.appendChild(document.createTextNode(result.content));result.content = preEl.outerHTML;@@ -162,7 +161,7 @@ function renderMermaid(result: Result, note: SNote) {<details><summary>Chart source</summary><pre>${escapeHtml(result.content)}</pre>-</details>`+</details>`;}function renderImage(result: Result, note: SNote) {@@ -170,8 +169,8 @@ function renderImage(result: Result, note: SNote) {}function renderFile(note: SNote, result: Result) {- if (note.mime === 'application/pdf') {- result.content = `<iframe class="pdf-view" src="api/notes/${note.noteId}/view"></iframe>`+ if (note.mime === "application/pdf") {+ result.content = `<iframe class="pdf-view" src="api/notes/${note.noteId}/view"></iframe>`;} else {result.content = `<button type="button" onclick="location.href='api/notes/${note.noteId}/download'">Download file</button>`;}diff --git a/src/share/routes.ts b/src/share/routes.tsindex da90625edb..de7a44c490 100644--- a/src/share/routes.ts+++ b/src/share/routes.ts@@ -38,22 +38,20 @@ function getSharedSubTreeRoot(note: SNote): { note?: SNote; branch?: SBranch } {}function addNoIndexHeader(note: SNote, res: Response) {- if (note.isLabelTruthy('shareDisallowRobotIndexing')) {- res.setHeader('X-Robots-Tag', 'noindex');+ if (note.isLabelTruthy("shareDisallowRobotIndexing")) {+ res.setHeader("X-Robots-Tag", "noindex");}}function requestCredentials(res: Response) {- res.setHeader('WWW-Authenticate', 'Basic realm="User Visible Realm", charset="UTF-8"')- .sendStatus(401);+ res.setHeader("WWW-Authenticate", 'Basic realm="User Visible Realm", charset="UTF-8"').sendStatus(401);}function checkAttachmentAccess(attachmentId: string, req: Request, res: Response) {const attachment = shaca.getAttachment(attachmentId);if (!attachment) {- res.status(404)- .json({ message: `Attachment '${attachmentId}' not found.` });+ res.status(404).json({ message: `Attachment '${attachmentId}' not found.` });return false;}@@ -68,15 +66,13 @@ function checkNoteAccess(noteId: string, req: Request, res: Response) {const note = shaca.getNote(noteId);if (!note) {- res.status(404)- .json({ message: `Note '${noteId}' not found.` });+ res.status(404).json({ message: `Note '${noteId}' not found.` });return false;}- if (noteId === '_share' && !shaca.shareIndexEnabled) {- res.status(403)- .json({ message: `Accessing share index is forbidden.` });+ if (noteId === "_share" && !shaca.shareIndexEnabled) {+ res.status(403).json({ message: `Accessing share index is forbidden.` });return false;}@@ -95,8 +91,8 @@ function checkNoteAccess(noteId: string, req: Request, res: Response) {}const base64Str = header.substring("Basic ".length);- const buffer = Buffer.from(base64Str, 'base64');- const authString = buffer.toString('utf-8');+ const buffer = Buffer.from(base64Str, "base64");+ const authString = buffer.toString("utf-8");for (const credentialLabel of credentials) {if (safeCompare(authString, credentialLabel.value)) {@@ -108,7 +104,7 @@ function checkNoteAccess(noteId: string, req: Request, res: Response) {}function renderImageAttachment(image: SNote, res: Response, attachmentName: string) {- let svgString = '<svg/>'+ let svgString = "<svg/>";const attachment = image.getAttachmentByTitle(attachmentName);if (!attachment) {res.status(404).render("share/404");@@ -126,8 +122,8 @@ function renderImageAttachment(image: SNote, res: Response, attachmentName: stri}}- const svg = svgString- res.set('Content-Type', "image/svg+xml");+ const svg = svgString;+ res.set("Content-Type", "image/svg+xml");res.set("Cache-Control", "no-cache, no-store, must-revalidate");res.send(svg);}@@ -147,9 +143,8 @@ function register(router: Router) {addNoIndexHeader(note, res);- if (note.isLabelTruthy('shareRaw')) {- res.setHeader('Content-Type', note.mime)- .send(note.getContent());+ if (note.isLabelTruthy("shareRaw")) {+ res.setHeader("Content-Type", note.mime).send(note.getContent());return;}@@ -160,19 +155,18 @@ function register(router: Router) {let useDefaultView = true;// Check if the user has their own template- if (note.hasRelation('shareTemplate')) {+ if (note.hasRelation("shareTemplate")) {// Get the template note and content- const templateId = note.getRelation('shareTemplate')?.value;+ const templateId = note.getRelation("shareTemplate")?.value;const templateNote = templateId && shaca.getNote(templateId);// Make sure the note type is correct- if (templateNote && templateNote.type === 'code' && templateNote.mime === 'application/x-ejs') {-+ if (templateNote && templateNote.type === "code" && templateNote.mime === "application/x-ejs") {// EJS caches the result of this so we don't need to pre-cacheconst includer = (path: string) => {- const childNote = templateNote.children.find(n => path === n.title);+ const childNote = templateNote.children.find((n) => path === n.title);if (!childNote) throw new Error("Unable to find child note.");- if (childNote.type !== 'code' || childNote.mime !== 'application/x-ejs') throw new Error("Incorrect child note type.");+ if (childNote.type !== "code" || childNote.mime !== "application/x-ejs") throw new Error("Incorrect child note type.");const template = childNote.getContent();if (typeof template !== "string") throw new Error("Invalid template content type.");@@ -188,36 +182,34 @@ function register(router: Router) {res.send(ejsResult);useDefaultView = false; // Rendering went okay, don't use default view}- }- catch (e: any) {+ } catch (e: any) {log.error(`Rendering user provided share template (${templateId}) threw exception ${e.message} with stacktrace: ${e.stack}`);}}}if (useDefaultView) {- res.render('share/page', opts);+ res.render("share/page", opts);}}- router.get('/share/', (req, res, next) => {- if (req.path.substr(-1) !== '/') {- res.redirect('../share/');+ router.get("/share/", (req, res, next) => {+ if (req.path.substr(-1) !== "/") {+ res.redirect("../share/");return;}shacaLoader.ensureLoad();if (!shaca.shareRootNote) {- res.status(404)- .json({ message: "Share root note not found" });+ res.status(404).json({ message: "Share root note not found" });return;}renderNote(shaca.shareRootNote, req, res);});- router.get('/share/:shareId', (req, res, next) => {+ router.get("/share/:shareId", (req, res, next) => {shacaLoader.ensureLoad();const { shareId } = req.params;@@ -227,7 +219,7 @@ function register(router: Router) {renderNote(note, req, res);});- router.get('/share/api/notes/:noteId', (req, res, next) => {+ router.get("/share/api/notes/:noteId", (req, res, next) => {shacaLoader.ensureLoad();let note: SNote | boolean;@@ -240,7 +232,7 @@ function register(router: Router) {res.json(note.getPojo());});- router.get('/share/api/notes/:noteId/download', (req, res, next) => {+ router.get("/share/api/notes/:noteId/download", (req, res, next) => {shacaLoader.ensureLoad();let note: SNote | boolean;@@ -253,16 +245,16 @@ function register(router: Router) {const filename = utils.formatDownloadTitle(note.title, note.type, note.mime);- res.setHeader('Content-Disposition', utils.getContentDisposition(filename));+ res.setHeader("Content-Disposition", utils.getContentDisposition(filename));res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");- res.setHeader('Content-Type', note.mime);+ res.setHeader("Content-Type", note.mime);res.send(note.getContent());});// :filename is not used by trilium, but instead used for "save as" to assign a human-readable filename- router.get('/share/api/images/:noteId/:filename', (req, res, next) => {+ router.get("/share/api/images/:noteId/:filename", (req, res, next) => {shacaLoader.ensureLoad();let image: SNote | boolean;@@ -271,25 +263,24 @@ function register(router: Router) {return;}- if (image.type === 'image') {+ if (image.type === "image") {// normal image- res.set('Content-Type', image.mime);+ res.set("Content-Type", image.mime);addNoIndexHeader(image, res);res.send(image.getContent());} else if (image.type === "canvas") {- renderImageAttachment(image, res, 'canvas-export.svg');- } else if (image.type === 'mermaid') {- renderImageAttachment(image, res, 'mermaid-export.svg');+ renderImageAttachment(image, res, "canvas-export.svg");+ } else if (image.type === "mermaid") {+ renderImageAttachment(image, res, "mermaid-export.svg");} else if (image.type === "mindMap") {- renderImageAttachment(image, res, 'mindmap-export.svg');+ renderImageAttachment(image, res, "mindmap-export.svg");} else {- res.status(400)- .json({ message: "Requested note is not a shareable image" });+ res.status(400).json({ message: "Requested note is not a shareable image" });}});// :filename is not used by trilium, but instead used for "save as" to assign a human-readable filename- router.get('/share/api/attachments/:attachmentId/image/:filename', (req, res, next) => {+ router.get("/share/api/attachments/:attachmentId/image/:filename", (req, res, next) => {shacaLoader.ensureLoad();let attachment: SAttachment | boolean;@@ -299,16 +290,15 @@ function register(router: Router) {}if (attachment.role === "image") {- res.set('Content-Type', attachment.mime);+ res.set("Content-Type", attachment.mime);addNoIndexHeader(attachment.note, res);res.send(attachment.getContent());} else {- res.status(400)- .json({ message: "Requested attachment is not a shareable image" });+ res.status(400).json({ message: "Requested attachment is not a shareable image" });}});- router.get('/share/api/attachments/:attachmentId/download', (req, res, next) => {+ router.get("/share/api/attachments/:attachmentId/download", (req, res, next) => {shacaLoader.ensureLoad();let attachment: SAttachment | boolean;@@ -321,16 +311,16 @@ function register(router: Router) {const filename = utils.formatDownloadTitle(attachment.title, null, attachment.mime);- res.setHeader('Content-Disposition', utils.getContentDisposition(filename));+ res.setHeader("Content-Disposition", utils.getContentDisposition(filename));res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");- res.setHeader('Content-Type', attachment.mime);+ res.setHeader("Content-Type", attachment.mime);res.send(attachment.getContent());});// used for PDF viewing- router.get('/share/api/notes/:noteId/view', (req, res, next) => {+ router.get("/share/api/notes/:noteId/view", (req, res, next) => {shacaLoader.ensureLoad();let note: SNote | boolean;@@ -342,13 +332,13 @@ function register(router: Router) {addNoIndexHeader(note, res);res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");- res.setHeader('Content-Type', note.mime);+ res.setHeader("Content-Type", note.mime);res.send(note.getContent());});// Used for searching, require noteId so we know the subTreeRoot- router.get('/share/api/notes', (req, res, next) => {+ router.get("/share/api/notes", (req, res, next) => {shacaLoader.ensureLoad();const ancestorNoteId = req.query.ancestorNoteId ?? "_share";@@ -373,11 +363,11 @@ function register(router: Router) {const searchContext = new SearchContext({ ancestorNoteId: ancestorNoteId });const searchResults = searchService.findResultsWithQuery(search, searchContext);- const filteredResults = searchResults.map(sr => {+ const filteredResults = searchResults.map((sr) => {const fullNote = shaca.notes[sr.noteId];const startIndex = sr.notePathArray.indexOf(ancestorNoteId);- const localPathArray = sr.notePathArray.slice(startIndex + 1).filter(id => shaca.notes[id]);- const pathTitle = localPathArray.map(id => shaca.notes[id].title).join(" / ");+ const localPathArray = sr.notePathArray.slice(startIndex + 1).filter((id) => shaca.notes[id]);+ const pathTitle = localPathArray.map((id) => shaca.notes[id].title).join(" / ");return { id: fullNote.shareId, title: fullNote.title, score: sr.score, path: pathTitle };});@@ -387,4 +377,4 @@ function register(router: Router) {export default {register-}+};diff --git a/src/share/shaca/entities/rows.ts b/src/share/shaca/entities/rows.tsindex ed20fea1fc..9b46b602b0 100644--- a/src/share/shaca/entities/rows.ts+++ b/src/share/shaca/entities/rows.ts@@ -1,4 +1,4 @@-export type SNoteRow = [ string, string, string, string, string, string, boolean ];-export type SBranchRow = [ string, string, string, string, string, boolean ];-export type SAttributeRow = [ string, string, string, string, string, boolean, number ];-export type SAttachmentRow = [ string, string, string, string, string, string, string ];+export type SNoteRow = [string, string, string, string, string, string, boolean];+export type SBranchRow = [string, string, string, string, string, boolean];+export type SAttributeRow = [string, string, string, string, string, boolean, number];+export type SAttachmentRow = [string, string, string, string, string, string, string];diff --git a/src/share/shaca/entities/sattachment.ts b/src/share/shaca/entities/sattachment.tsindex a442c42657..aa7a8a9ee8 100644--- a/src/share/shaca/entities/sattachment.ts+++ b/src/share/shaca/entities/sattachment.ts@@ -4,8 +4,8 @@ import sql from "../../sql.js";import utils from "../../../services/utils.js";import AbstractShacaEntity from "./abstract_shaca_entity.js";import SNote from "./snote.js";-import { Blob } from '../../../services/blob-interface.js';-import { SAttachmentRow } from './rows.js';+import { Blob } from "../../../services/blob-interface.js";+import { SAttachmentRow } from "./rows.js";class SAttachment extends AbstractShacaEntity {private attachmentId: string;@@ -42,8 +42,7 @@ class SAttachment extends AbstractShacaEntity {if (!row) {if (silentNotFoundError) {return undefined;- }- else {+ } else {throw new Error(`Cannot find blob for attachment '${this.attachmentId}', blob '${this.blobId}'`);}}@@ -51,11 +50,8 @@ class SAttachment extends AbstractShacaEntity {let content = row.content;if (this.hasStringContent()) {- return content === null- ? ""- : content.toString("utf-8");- }- else {+ return content === null ? "" : content.toString("utf-8");+ } else {return content;}}diff --git a/src/share/shaca/entities/sattribute.ts b/src/share/shaca/entities/sattribute.tsindex 2b7647e4e7..ba80c0a12b 100644--- a/src/share/shaca/entities/sattribute.ts+++ b/src/share/shaca/entities/sattribute.ts@@ -5,7 +5,6 @@ import { SAttributeRow } from "./rows.js";import SNote from "./snote.js";class SAttribute extends AbstractShacaEntity {-attributeId: string;private noteId: string;type: string;@@ -34,8 +33,8 @@ class SAttribute extends AbstractShacaEntity {targetNote.targetRelations.push(this);}- if (this.type === 'relation' && this.name === 'imageLink') {- const linkedChildNote = this.note.getChildNotes().find(childNote => childNote.noteId === this.value);+ if (this.type === "relation" && this.name === "imageLink") {+ const linkedChildNote = this.note.getChildNotes().find((childNote) => childNote.noteId === this.value);if (linkedChildNote) {const branch = this.shaca.getBranchFromChildAndParent(linkedChildNote.noteId, this.noteId);@@ -44,30 +43,30 @@ class SAttribute extends AbstractShacaEntity {}}- if (this.type === 'label' && this.name === 'shareAlias' && this.value.trim()) {+ if (this.type === "label" && this.name === "shareAlias" && this.value.trim()) {this.shaca.aliasToNote[this.value.trim()] = this.note;}- if (this.type === 'label' && this.name === 'shareRoot') {+ if (this.type === "label" && this.name === "shareRoot") {this.shaca.shareRootNote = this.note;}- if (this.type === 'label' && this.name === 'shareIndex') {+ if (this.type === "label" && this.name === "shareIndex") {this.shaca.shareIndexEnabled = true;}}get isAffectingSubtree() {- return this.isInheritable- || (this.type === 'relation' && ['template', 'inherit'].includes(this.name));+ return this.isInheritable || (this.type === "relation" && ["template", "inherit"].includes(this.name));}- get targetNoteId() { // alias- return this.type === 'relation' ? this.value : undefined;+ get targetNoteId() {+ // alias+ return this.type === "relation" ? this.value : undefined;}isAutoLink() {- return this.type === 'relation' && ['internalLink', 'imageLink', 'relationMapLink', 'includeNoteLink'].includes(this.name);+ return this.type === "relation" && ["internalLink", "imageLink", "relationMapLink", "includeNoteLink"].includes(this.name);}get note(): SNote {@@ -75,7 +74,7 @@ class SAttribute extends AbstractShacaEntity {}get targetNote(): SNote | null | undefined {- if (this.type === 'relation') {+ if (this.type === "relation") {return this.shaca.notes[this.value];}}@@ -85,7 +84,7 @@ class SAttribute extends AbstractShacaEntity {}getTargetNote(): SNote | null {- if (this.type !== 'relation') {+ if (this.type !== "relation") {throw new Error(`Attribute '${this.attributeId}' is not relation`);}diff --git a/src/share/shaca/entities/sbranch.ts b/src/share/shaca/entities/sbranch.tsindex cb71ed7804..82a8170ca5 100644--- a/src/share/shaca/entities/sbranch.ts+++ b/src/share/shaca/entities/sbranch.ts@@ -1,11 +1,10 @@"use strict";import AbstractShacaEntity from "./abstract_shaca_entity.js";-import { SBranchRow } from './rows.js';+import { SBranchRow } from "./rows.js";import SNote from "./snote.js";class SBranch extends AbstractShacaEntity {-private branchId: string;private noteId: string;parentNoteId: string;diff --git a/src/share/shaca/entities/snote.ts b/src/share/shaca/entities/snote.tsindex 459b5d10f2..511789f13e 100644--- a/src/share/shaca/entities/snote.ts+++ b/src/share/shaca/entities/snote.ts@@ -4,17 +4,17 @@ import sql from "../../sql.js";import utils from "../../../services/utils.js";import AbstractShacaEntity from "./abstract_shaca_entity.js";import escape from "escape-html";-import { Blob } from '../../../services/blob-interface.js';+import { Blob } from "../../../services/blob-interface.js";import SAttachment from "./sattachment.js";import SAttribute from "./sattribute.js";import SBranch from "./sbranch.js";-import { SNoteRow } from './rows.js';+import { SNoteRow } from "./rows.js";-const LABEL = 'label';-const RELATION = 'relation';-const CREDENTIALS = 'shareCredentials';+const LABEL = "label";+const RELATION = "relation";+const CREDENTIALS = "shareCredentials";-const isCredentials = (attr: SAttribute) => attr.type === 'label' && attr.name === CREDENTIALS;+const isCredentials = (attr: SAttribute) => attr.type === "label" && attr.name === CREDENTIALS;class SNote extends AbstractShacaEntity {noteId: string;@@ -67,13 +67,11 @@ class SNote extends AbstractShacaEntity {}getChildBranches(): SBranch[] {- return this.children.map(childNote => this.shaca.getBranchFromChildAndParent(childNote.noteId, this.noteId));+ return this.children.map((childNote) => this.shaca.getBranchFromChildAndParent(childNote.noteId, this.noteId));}getVisibleChildBranches() {- return this.getChildBranches()- .filter(branch => !branch.isHidden- && !branch.getNote().isLabelTruthy('shareHiddenFromTree'));+ return this.getChildBranches().filter((branch) => !branch.isHidden && !branch.getNote().isLabelTruthy("shareHiddenFromTree"));}getParentNotes() {@@ -85,8 +83,7 @@ class SNote extends AbstractShacaEntity {}getVisibleChildNotes() {- return this.getVisibleChildBranches()- .map(branch => branch.getNote());+ return this.getVisibleChildBranches().map((branch) => branch.getNote());}hasChildren() {@@ -103,8 +100,7 @@ class SNote extends AbstractShacaEntity {if (!row) {if (silentNotFoundError) {return undefined;- }- else {+ } else {throw new Error(`Cannot find note content for note '${this.noteId}', blob '${this.blobId}'`);}}@@ -112,11 +108,8 @@ class SNote extends AbstractShacaEntity {let content = row.content;if (this.hasStringContent()) {- return content === null- ? ""- : content.toString("utf-8");- }- else {+ return content === null ? "" : content.toString("utf-8");+ } else {return content;}}@@ -138,16 +131,13 @@ class SNote extends AbstractShacaEntity {}if (type && name) {- return attributeCache.filter(attr => attr.type === type && attr.name === name && !isCredentials(attr));- }- else if (type) {- return attributeCache.filter(attr => attr.type === type && !isCredentials(attr));- }- else if (name) {- return attributeCache.filter(attr => attr.name === name && !isCredentials(attr));- }- else {- return attributeCache.filter(attr => !isCredentials(attr));+ return attributeCache.filter((attr) => attr.type === type && attr.name === name && !isCredentials(attr));+ } else if (type) {+ return attributeCache.filter((attr) => attr.type === type && !isCredentials(attr));+ } else if (name) {+ return attributeCache.filter((attr) => attr.name === name && !isCredentials(attr));+ } else {+ return attributeCache.filter((attr) => !isCredentials(attr));}}@@ -164,7 +154,7 @@ class SNote extends AbstractShacaEntity {const parentAttributes = this.ownedAttributes.slice();const newPath = [...path, this.noteId];- if (this.noteId !== 'root') {+ if (this.noteId !== "root") {for (const parentNote of this.parents) {parentAttributes.push(...parentNote.__getInheritableAttributes(newPath));}@@ -172,8 +162,9 @@ class SNote extends AbstractShacaEntity {const templateAttributes: SAttribute[] = [];- for (const ownedAttr of parentAttributes) { // parentAttributes so we process also inherited templates- if (ownedAttr.type === 'relation' && ['template', 'inherit'].includes(ownedAttr.name)) {+ for (const ownedAttr of parentAttributes) {+ // parentAttributes so we process also inherited templates+ if (ownedAttr.type === "relation" && ["template", "inherit"].includes(ownedAttr.name)) {const templateNote = this.shaca.notes[ownedAttr.value];if (templateNote) {@@ -235,18 +226,17 @@ class SNote extends AbstractShacaEntity {getJsonContentSafely() {try {return this.getJsonContent();- }- catch (e) {+ } catch (e) {return null;}}hasAttribute(type: string, name: string) {- return !!this.getAttributes().find(attr => attr.type === type && attr.name === name);+ return !!this.getAttributes().find((attr) => attr.type === type && attr.name === name);}getRelationTarget(name: string) {- const relation = this.getAttributes().find(attr => attr.type === 'relation' && attr.name === name);+ const relation = this.getAttributes().find((attr) => attr.type === "relation" && attr.name === name);return relation ? relation.targetNote : null;}@@ -255,7 +245,9 @@ class SNote extends AbstractShacaEntity {* @param name - label name* @returns true if label exists (including inherited)*/- hasLabel(name: string) { return this.hasAttribute(LABEL, name); }+ hasLabel(name: string) {+ return this.hasAttribute(LABEL, name);+ }/*** @param name - label name@@ -268,74 +260,96 @@ class SNote extends AbstractShacaEntity {return false;}- return !!label && label.value !== 'false';+ return !!label && label.value !== "false";}/*** @param name - label name* @returns true if label exists (excluding inherited)*/- hasOwnedLabel(name: string) { return this.hasOwnedAttribute(LABEL, name); }+ hasOwnedLabel(name: string) {+ return this.hasOwnedAttribute(LABEL, name);+ }/*** @param name - relation name* @returns true if relation exists (including inherited)*/- hasRelation(name: string) { return this.hasAttribute(RELATION, name); }+ hasRelation(name: string) {+ return this.hasAttribute(RELATION, name);+ }/*** @param name - relation name* @returns true if relation exists (excluding inherited)*/- hasOwnedRelation(name: string) { return this.hasOwnedAttribute(RELATION, name); }+ hasOwnedRelation(name: string) {+ return this.hasOwnedAttribute(RELATION, name);+ }/*** @param name - label name* @returns label if it exists, null otherwise*/- getLabel(name: string) { return this.getAttribute(LABEL, name); }+ getLabel(name: string) {+ return this.getAttribute(LABEL, name);+ }/*** @param name - label name* @returns label if it exists, null otherwise*/- getOwnedLabel(name: string) { return this.getOwnedAttribute(LABEL, name); }+ getOwnedLabel(name: string) {+ return this.getOwnedAttribute(LABEL, name);+ }/*** @param name - relation name* @returns relation if it exists, null otherwise*/- getRelation(name: string) { return this.getAttribute(RELATION, name); }+ getRelation(name: string) {+ return this.getAttribute(RELATION, name);+ }/*** @param name - relation name* @returns relation if it exists, null otherwise*/- getOwnedRelation(name: string) { return this.getOwnedAttribute(RELATION, name); }+ getOwnedRelation(name: string) {+ return this.getOwnedAttribute(RELATION, name);+ }/*** @param name - label name* @returns label value if label exists, null otherwise*/- getLabelValue(name: string) { return this.getAttributeValue(LABEL, name); }+ getLabelValue(name: string) {+ return this.getAttributeValue(LABEL, name);+ }/*** @param name - label name* @returns label value if label exists, null otherwise*/- getOwnedLabelValue(name: string) { return this.getOwnedAttributeValue(LABEL, name); }+ getOwnedLabelValue(name: string) {+ return this.getOwnedAttributeValue(LABEL, name);+ }/*** @param name - relation name* @returns relation value if relation exists, null otherwise*/- getRelationValue(name: string) { return this.getAttributeValue(RELATION, name); }+ getRelationValue(name: string) {+ return this.getAttributeValue(RELATION, name);+ }/*** @param name - relation name* @returns relation value if relation exists, null otherwise*/- getOwnedRelationValue(name: string) { return this.getOwnedAttributeValue(RELATION, name); }+ getOwnedRelationValue(name: string) {+ return this.getOwnedAttributeValue(RELATION, name);+ }/*** @param type - attribute type (label, relation, etc.)@@ -355,7 +369,7 @@ class SNote extends AbstractShacaEntity {getAttribute(type: string, name: string) {const attributes = this.getAttributes();- return attributes.find(attr => attr.type === type && attr.name === name);+ return attributes.find((attr) => attr.type === type && attr.name === name);}/**@@ -377,7 +391,7 @@ class SNote extends AbstractShacaEntity {getOwnedAttributeValue(type: string, name: string) {const attr = this.getOwnedAttribute(type, name);- return attr ? attr.value as string : null; // FIXME+ return attr ? (attr.value as string) : null; // FIXME}/**@@ -393,7 +407,7 @@ class SNote extends AbstractShacaEntity {* @returns all note's label values, including inherited ones*/getLabelValues(name: string) {- return this.getLabels(name).map(l => l.value) as string[]; // FIXME+ return this.getLabels(name).map((l) => l.value) as string[]; // FIXME}/**@@ -409,7 +423,7 @@ class SNote extends AbstractShacaEntity {* @returns all note's label values, excluding inherited ones*/getOwnedLabelValues(name: string) {- return this.getOwnedAttributes(LABEL, name).map(l => l.value);+ return this.getOwnedAttributes(LABEL, name).map((l) => l.value);}/**@@ -440,15 +454,12 @@ class SNote extends AbstractShacaEntity {}if (type && name) {- return this.ownedAttributes.filter(attr => attr.type === type && attr.name === name);- }- else if (type) {- return this.ownedAttributes.filter(attr => attr.type === type);- }- else if (name) {- return this.ownedAttributes.filter(attr => attr.name === name);- }- else {+ return this.ownedAttributes.filter((attr) => attr.type === type && attr.name === name);+ } else if (type) {+ return this.ownedAttributes.filter((attr) => attr.type === type);+ } else if (name) {+ return this.ownedAttributes.filter((attr) => attr.name === name);+ } else {return this.ownedAttributes.slice();}}@@ -465,11 +476,11 @@ class SNote extends AbstractShacaEntity {}get isArchived() {- return this.hasAttribute('label', 'archived');+ return this.hasAttribute("label", "archived");}isInherited() {- return !!this.targetRelations.find(rel => rel.name === 'template' || rel.name === 'inherit');+ return !!this.targetRelations.find((rel) => rel.name === "template" || rel.name === "inherit");}getTargetRelations() {@@ -481,11 +492,11 @@ class SNote extends AbstractShacaEntity {}getAttachmentByTitle(title: string) {- return this.attachments.find(attachment => attachment.title === title);+ return this.attachments.find((attachment) => attachment.title === title);}get shareId() {- if (this.hasOwnedLabel('shareRoot')) {+ if (this.hasOwnedLabel("shareRoot")) {return "";}@@ -512,12 +523,11 @@ class SNote extends AbstractShacaEntity {attributes: this.getAttributes()// relations could link across shared subtrees which might leak them// individual relations might be whitelisted based on needs #3434- .filter(attr => attr.type === 'label')- .map(attr => attr.getPojo()),- attachments: this.getAttachments()- .map(attachment => attachment.getPojo()),- parentNoteIds: this.parents.map(parentNote => parentNote.noteId),- childNoteIds: this.children.map(child => child.noteId)+ .filter((attr) => attr.type === "label")+ .map((attr) => attr.getPojo()),+ attachments: this.getAttachments().map((attachment) => attachment.getPojo()),+ parentNoteIds: this.parents.map((parentNote) => parentNote.noteId),+ childNoteIds: this.children.map((child) => child.noteId)};}}diff --git a/src/share/shaca/shaca-interface.ts b/src/share/shaca/shaca-interface.tsindex ad255540a8..8cec3a7d2d 100644--- a/src/share/shaca/shaca-interface.ts+++ b/src/share/shaca/shaca-interface.ts@@ -4,7 +4,6 @@ import SBranch from "./entities/sbranch.js";import SNote from "./entities/snote.js";export default class Shaca {-notes!: Record<string, SNote>;branches!: Record<string, SBranch>;childParentToBranch!: Record<string, SBranch>;@@ -84,12 +83,7 @@ export default class Shaca {return null;}- const camelCaseEntityName = entityName.toLowerCase().replace(/(_[a-z])/g,- group =>- group- .toUpperCase()- .replace('_', '')- );+ const camelCaseEntityName = entityName.toLowerCase().replace(/(_[a-z])/g, (group) => group.toUpperCase().replace("_", ""));return (this as any)[camelCaseEntityName][entityId];}diff --git a/src/share/shaca/shaca_loader.ts b/src/share/shaca/shaca_loader.tsindex fd640ab91d..1766cdce41 100644--- a/src/share/shaca/shaca_loader.ts+++ b/src/share/shaca/shaca_loader.ts@@ -9,7 +9,7 @@ import SAttribute from "./entities/sattribute.js";import SAttachment from "./entities/sattachment.js";import shareRoot from "../share_root.js";import eventService from "../../services/events.js";-import { SAttachmentRow, SAttributeRow, SBranchRow, SNoteRow } from './entities/rows.js';+import { SAttachmentRow, SAttributeRow, SBranchRow, SNoteRow } from "./entities/rows.js";function load() {const start = Date.now();@@ -17,7 +17,8 @@ function load() {// using a raw query and passing arrays to avoid allocating new objects- const noteIds = sql.getColumn(`+ const noteIds = sql.getColumn(+ `WITH RECURSIVEtree(noteId) AS (SELECT ?@@ -26,7 +27,9 @@ function load() {JOIN tree ON branches.parentNoteId = tree.noteIdWHERE branches.isDeleted = 0)- SELECT noteId FROM tree`, [shareRoot.SHARE_ROOT_NOTE_ID]);+ SELECT noteId FROM tree`,+ [shareRoot.SHARE_ROOT_NOTE_ID]+ );if (noteIds.length === 0) {shaca.loaded = true;@@ -34,7 +37,7 @@ function load() {return;}- const noteIdStr = noteIds.map(noteId => `'${noteId}'`).join(",");+ const noteIdStr = noteIds.map((noteId) => `'${noteId}'`).join(",");const rawNoteRows = sql.getRawRows<SNoteRow>(`SELECT noteId, title, type, mime, blobId, utcDateModified, isProtected@@ -88,9 +91,12 @@ function ensureLoad() {}}-eventService.subscribe([eventService.ENTITY_CREATED, eventService.ENTITY_CHANGED, eventService.ENTITY_DELETED, eventService.ENTITY_CHANGE_SYNCED, eventService.ENTITY_DELETE_SYNCED], ({ entityName, entity }) => {- shaca.reset();-});+eventService.subscribe(+ [eventService.ENTITY_CREATED, eventService.ENTITY_CHANGED, eventService.ENTITY_DELETED, eventService.ENTITY_CHANGE_SYNCED, eventService.ENTITY_DELETE_SYNCED],+ ({ entityName, entity }) => {+ shaca.reset();+ }+);export default {load,diff --git a/src/share/share_root.ts b/src/share/share_root.tsindex 453d5ae8f4..cb649aebdb 100644--- a/src/share/share_root.ts+++ b/src/share/share_root.ts@@ -1,3 +1,3 @@export default {- SHARE_ROOT_NOTE_ID: '_share'-}+ SHARE_ROOT_NOTE_ID: "_share"+};diff --git a/src/share/sql.ts b/src/share/sql.tsindex 43664aa2ab..229e09ec70 100644--- a/src/share/sql.ts+++ b/src/share/sql.ts@@ -9,7 +9,7 @@ let dbConnection!: Database.Database;sql_init.dbReady.then(() => {dbConnection = new Database(dataDir.DOCUMENT_PATH, { readonly: true });- [`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `SIGTERM`].forEach(eventType => {+ [`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `SIGTERM`].forEach((eventType) => {process.on(eventType, () => {if (dbConnection) {// closing connection is especially important to fold -wal file into the main DB filediff --git a/src/tools/generate_document.ts b/src/tools/generate_document.tsindex 073a953359..8c2286dda8 100644--- a/src/tools/generate_document.ts+++ b/src/tools/generate_document.ts@@ -3,13 +3,13 @@* will create 1000 new notes and some clones into the current document.db*/-import sqlInit from '../services/sql_init.js';-import noteService from '../services/notes.js';-import attributeService from '../services/attributes.js';-import cls from '../services/cls.js';-import cloningService from '../services/cloning.js';-import loremIpsum from 'lorem-ipsum';-import '../becca/entity_constructor.js';+import sqlInit from "../services/sql_init.js";+import noteService from "../services/notes.js";+import attributeService from "../services/attributes.js";+import cls from "../services/cls.js";+import cloningService from "../services/cloning.js";+import loremIpsum from "lorem-ipsum";+import "../becca/entity_constructor.js";const noteCount = parseInt(process.argv[2]);@@ -18,7 +18,7 @@ if (!noteCount) {process.exit(1);}-const notes = ['root'];+const notes = ["root"];function getRandomNoteId() {const index = Math.floor(Math.random() * notes.length);@@ -30,7 +30,7 @@ async function start() {for (let i = 0; i < noteCount; i++) {const title = loremIpsum.loremIpsum({count: 1,- units: 'sentences',+ units: "sentences",sentenceLowerBound: 1,sentenceUpperBound: 10});@@ -38,19 +38,19 @@ async function start() {const paragraphCount = Math.floor(Math.random() * Math.random() * 100);const content = loremIpsum.loremIpsum({count: paragraphCount,- units: 'paragraphs',+ units: "paragraphs",sentenceLowerBound: 1,sentenceUpperBound: 15,paragraphLowerBound: 3,paragraphUpperBound: 10,- format: 'html'+ format: "html"});const { note } = noteService.createNewNote({parentNoteId: getRandomNoteId(),title,content,- type: 'text'+ type: "text"});console.log(`Created note ${i}: ${title}`);@@ -58,7 +58,7 @@ async function start() {if (Math.random() < 0.04) {const noteIdToClone = note.noteId;const parentNoteId = getRandomNoteId();- const prefix = Math.random() > 0.8 ? "prefix" : '';+ const prefix = Math.random() > 0.8 ? "prefix" : "";const result = await cloningService.cloneNoteToBranch(noteIdToClone, parentNoteId, prefix);@@ -68,16 +68,16 @@ async function start() {// does not have to be for the current noteawait attributeService.createAttribute({noteId: getRandomNoteId(),- type: 'label',- name: 'label',- value: 'value',+ type: "label",+ name: "label",+ value: "value",isInheritable: Math.random() > 0.1 // 10% are inheritable});await attributeService.createAttribute({noteId: getRandomNoteId(),- type: 'relation',- name: 'relation',+ type: "relation",+ name: "relation",value: getRandomNoteId(),isInheritable: Math.random() > 0.1 // 10% are inheritable});diff --git a/src/types.d.ts b/src/types.d.tsindex 1ceedddb5f..95698eb9fc 100644--- a/src/types.d.ts+++ b/src/types.d.ts@@ -3,22 +3,22 @@* in its library or in `@types/*` packages.*/-declare module 'unescape' {+declare module "unescape" {function unescape(str: string, type?: string): string;export default unescape;}-declare module 'html2plaintext' {+declare module "html2plaintext" {function html2plaintext(htmlText: string): string;export default html2plaintext;}-declare module 'normalize-strings' {+declare module "normalize-strings" {function normalizeString(string: string): string;export default normalizeString;}-declare module 'joplin-turndown-plugin-gfm' {+declare module "joplin-turndown-plugin-gfm" {import TurndownService from "turndown";namespace gfm {function gfm(service: TurndownService): void;@@ -26,7 +26,7 @@ declare module 'joplin-turndown-plugin-gfm' {export default gfm;}-declare module 'is-animated' {+declare module "is-animated" {function isAnimated(buffer: Buffer): boolean;export default isAnimated;}diff --git a/src/www.ts b/src/www.tsindex 982aa36381..643dbcfef6 100644--- a/src/www.ts+++ b/src/www.ts@@ -16,7 +16,7 @@ import semver from "semver";// setup basic error handling even before requiring dependencies, since those can produce errors as well-process.on('unhandledRejection', (error: Error) => {+process.on("unhandledRejection", (error: Error) => {// this makes sure that stacktrace of failed promise is printed outconsole.log(error);@@ -29,9 +29,8 @@ function exit() {process.exit(0);}-process.on('SIGINT', exit);-process.on('SIGTERM', exit);-+process.on("SIGINT", exit);+process.on("SIGTERM", exit);if (!semver.satisfies(process.version, ">=10.5.0")) {console.error("Trilium only supports node.js 10.5 and later");@@ -42,27 +41,28 @@ startTrilium();async function startTrilium() {/**- * The intended behavior is to detect when a second instance is running, in that case open the old instance- * instead of the new one. This is complicated by the fact that it is possible to run multiple instances of Trilium- * if port and data dir are configured separately. This complication is the source of the following weird usage.- *- * The line below makes sure that the "second-instance" (process in window.ts) is fired. Normally it returns a boolean- * indicating whether another instance is running or not, but we ignore that and kill the app only based on the port conflict.- *- * A bit weird is that "second-instance" is triggered also on the valid usecases (different port/data dir) and- * focuses the existing window. But the new process is start as well and will steal the focus too, it will win, because- * its startup is slower than focusing the existing process/window. So in the end, it works out without having- * to do a complex evaluation.- */+ * The intended behavior is to detect when a second instance is running, in that case open the old instance+ * instead of the new one. This is complicated by the fact that it is possible to run multiple instances of Trilium+ * if port and data dir are configured separately. This complication is the source of the following weird usage.+ *+ * The line below makes sure that the "second-instance" (process in window.ts) is fired. Normally it returns a boolean+ * indicating whether another instance is running or not, but we ignore that and kill the app only based on the port conflict.+ *+ * A bit weird is that "second-instance" is triggered also on the valid usecases (different port/data dir) and+ * focuses the existing window. But the new process is start as well and will steal the focus too, it will win, because+ * its startup is slower than focusing the existing process/window. So in the end, it works out without having+ * to do a complex evaluation.+ */if (utils.isElectron()) {- (await import('electron')).app.requestSingleInstanceLock();+ (await import("electron")).app.requestSingleInstanceLock();}log.info(JSON.stringify(appInfo, null, 2));// for perf. issues it's good to know the rough configuration- const cpuInfos = (await import('os')).cpus();- if (cpuInfos && cpuInfos[0] !== undefined) { // https://github.com/zadam/trilium/pull/3957+ const cpuInfos = (await import("os")).cpus();+ if (cpuInfos && cpuInfos[0] !== undefined) {+ // https://github.com/zadam/trilium/pull/3957const cpuModel = (cpuInfos[0].model || "").trimEnd();log.info(`CPU model: ${cpuModel}, logical cores: ${cpuInfos.length}, freq: ${cpuInfos[0].speed} Mhz`);}@@ -72,38 +72,38 @@ async function startTrilium() {ws.init(httpServer, sessionParser as any); // TODO: Not sure why session parser is incompatible.if (utils.isElectron()) {- const electronRouting = await import('./routes/electron.js');+ const electronRouting = await import("./routes/electron.js");electronRouting.default(app);}}function startHttpServer() {- app.set('port', port);- app.set('host', host);+ app.set("port", port);+ app.set("host", host);// Check from config whether to trust reverse proxies to supply user IPs, hostnames and protocols- if (config['Network']['trustedReverseProxy']) {- if (config['Network']['trustedReverseProxy'] === true || config['Network']['trustedReverseProxy'].trim().length) {- app.set('trust proxy', config['Network']['trustedReverseProxy'])+ if (config["Network"]["trustedReverseProxy"]) {+ if (config["Network"]["trustedReverseProxy"] === true || config["Network"]["trustedReverseProxy"].trim().length) {+ app.set("trust proxy", config["Network"]["trustedReverseProxy"]);}}- log.info(`Trusted reverse proxy: ${app.get('trust proxy')}`)+ log.info(`Trusted reverse proxy: ${app.get("trust proxy")}`);let httpServer;- if (config['Network']['https']) {- if (!config['Network']['keyPath'] || !config['Network']['keyPath'].trim().length) {+ if (config["Network"]["https"]) {+ if (!config["Network"]["keyPath"] || !config["Network"]["keyPath"].trim().length) {throw new Error("keyPath in config.ini is required when https=true, but it's empty");}- if (!config['Network']['certPath'] || !config['Network']['certPath'].trim().length) {+ if (!config["Network"]["certPath"] || !config["Network"]["certPath"].trim().length) {throw new Error("certPath in config.ini is required when https=true, but it's empty");}const options = {- key: fs.readFileSync(config['Network']['keyPath']),- cert: fs.readFileSync(config['Network']['certPath'])+ key: fs.readFileSync(config["Network"]["keyPath"]),+ cert: fs.readFileSync(config["Network"]["certPath"])};httpServer = https.createServer(options, app);@@ -116,8 +116,8 @@ function startHttpServer() {}/**- * Listen on provided port, on all network interfaces.- */+ * Listen on provided port, on all network interfaces.+ */httpServer.keepAliveTimeout = 120000 * 5;const listenOnTcp = port !== 0;@@ -128,19 +128,19 @@ function startHttpServer() {httpServer.listen(host); // Unix socket.}- httpServer.on('error', error => {+ httpServer.on("error", (error) => {let message = error.stack || "An unexpected error has occurred.";// handle specific listen errors with friendly messagesif ("code" in error) {switch (error.code) {- case 'EACCES':+ case "EACCES":message = `Port ${port} requires elevated privileges. It's recommended to use port above 1024.`;break;- case 'EADDRINUSE':+ case "EADDRINUSE":message = `Port ${port} is already in use. Most likely, another Trilium process is already running. You might try to find it, kill it, and try again.`;break;- case 'EADDRNOTAVAIL':+ case "EADDRNOTAVAIL":message = `Unable to start the server on host '${host}'. Make sure the host (defined in 'config.ini' or via the 'TRILIUM_HOST' environment variable) is an IP address that can be listened on.`;break;}@@ -151,8 +151,8 @@ function startHttpServer() {// Not all situations require showing an error dialog. When Trilium is already open,// clicking the shortcut, the software icon, or the taskbar icon, or when creating a new window,// should simply focus on the existing window or open a new one, without displaying an error message.- if ("code" in error && error.code == 'EADDRINUSE') {- if (process.argv.includes('--new-window') || !app.requestSingleInstanceLock()) {+ if ("code" in error && error.code == "EADDRINUSE") {+ if (process.argv.includes("--new-window") || !app.requestSingleInstanceLock()) {console.error(message);process.exit(1);}@@ -166,11 +166,11 @@ function startHttpServer() {}});- httpServer.on('listening', () => {+ httpServer.on("listening", () => {if (listenOnTcp) {- log.info(`Listening on port ${port}`)+ log.info(`Listening on port ${port}`);} else {- log.info(`Listening on unix socket ${host}`)+ log.info(`Listening on unix socket ${host}`);}});diff --git a/tests-examples/demo-todo-app.spec.ts b/tests-examples/demo-todo-app.spec.tsindex 52fe8db709..eb4ec98967 100644--- a/tests-examples/demo-todo-app.spec.ts+++ b/tests-examples/demo-todo-app.spec.ts@@ -1,437 +1,416 @@-import { test, expect, type Page } from '@playwright/test';+import { test, expect, type Page } from "@playwright/test";test.beforeEach(async ({ page }) => {- await page.goto('https://demo.playwright.dev/todomvc');+ await page.goto("https://demo.playwright.dev/todomvc");});-const TODO_ITEMS = [- 'buy some cheese',- 'feed the cat',- 'book a doctors appointment'-] as const;+const TODO_ITEMS = ["buy some cheese", "feed the cat", "book a doctors appointment"] as const;-test.describe('New Todo', () => {- test('should allow me to add todo items', async ({ page }) => {- // create a new todo locator- const newTodo = page.getByPlaceholder('What needs to be done?');+test.describe("New Todo", () => {+ test("should allow me to add todo items", async ({ page }) => {+ // create a new todo locator+ const newTodo = page.getByPlaceholder("What needs to be done?");- // Create 1st todo.- await newTodo.fill(TODO_ITEMS[0]);- await newTodo.press('Enter');+ // Create 1st todo.+ await newTodo.fill(TODO_ITEMS[0]);+ await newTodo.press("Enter");- // Make sure the list only has one todo item.- await expect(page.getByTestId('todo-title')).toHaveText([- TODO_ITEMS[0]- ]);+ // Make sure the list only has one todo item.+ await expect(page.getByTestId("todo-title")).toHaveText([TODO_ITEMS[0]]);- // Create 2nd todo.- await newTodo.fill(TODO_ITEMS[1]);- await newTodo.press('Enter');+ // Create 2nd todo.+ await newTodo.fill(TODO_ITEMS[1]);+ await newTodo.press("Enter");- // Make sure the list now has two todo items.- await expect(page.getByTestId('todo-title')).toHaveText([- TODO_ITEMS[0],- TODO_ITEMS[1]- ]);+ // Make sure the list now has two todo items.+ await expect(page.getByTestId("todo-title")).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]);- await checkNumberOfTodosInLocalStorage(page, 2);- });+ await checkNumberOfTodosInLocalStorage(page, 2);+ });- test('should clear text input field when an item is added', async ({ page }) => {- // create a new todo locator- const newTodo = page.getByPlaceholder('What needs to be done?');-- // Create one todo item.- await newTodo.fill(TODO_ITEMS[0]);- await newTodo.press('Enter');-- // Check that input is empty.- await expect(newTodo).toBeEmpty();- await checkNumberOfTodosInLocalStorage(page, 1);- });-- test('should append new items to the bottom of the list', async ({ page }) => {- // Create 3 items.- await createDefaultTodos(page);-- // create a todo count locator- const todoCount = page.getByTestId('todo-count')-- // Check test using different methods.- await expect(page.getByText('3 items left')).toBeVisible();- await expect(todoCount).toHaveText('3 items left');- await expect(todoCount).toContainText('3');- await expect(todoCount).toHaveText(/3/);-- // Check all items in one call.- await expect(page.getByTestId('todo-title')).toHaveText(TODO_ITEMS);- await checkNumberOfTodosInLocalStorage(page, 3);- });-});+ test("should clear text input field when an item is added", async ({ page }) => {+ // create a new todo locator+ const newTodo = page.getByPlaceholder("What needs to be done?");++ // Create one todo item.+ await newTodo.fill(TODO_ITEMS[0]);+ await newTodo.press("Enter");++ // Check that input is empty.+ await expect(newTodo).toBeEmpty();+ await checkNumberOfTodosInLocalStorage(page, 1);+ });++ test("should append new items to the bottom of the list", async ({ page }) => {+ // Create 3 items.+ await createDefaultTodos(page);++ // create a todo count locator+ const todoCount = page.getByTestId("todo-count");-test.describe('Mark all as completed', () => {- test.beforeEach(async ({ page }) => {- await createDefaultTodos(page);- await checkNumberOfTodosInLocalStorage(page, 3);- });-- test.afterEach(async ({ page }) => {- await checkNumberOfTodosInLocalStorage(page, 3);- });-- test('should allow me to mark all items as completed', async ({ page }) => {- // Complete all todos.- await page.getByLabel('Mark all as complete').check();-- // Ensure all todos have 'completed' class.- await expect(page.getByTestId('todo-item')).toHaveClass(['completed', 'completed', 'completed']);- await checkNumberOfCompletedTodosInLocalStorage(page, 3);- });-- test('should allow me to clear the complete state of all items', async ({ page }) => {- const toggleAll = page.getByLabel('Mark all as complete');- // Check and then immediately uncheck.- await toggleAll.check();- await toggleAll.uncheck();-- // Should be no completed classes.- await expect(page.getByTestId('todo-item')).toHaveClass(['', '', '']);- });-- test('complete all checkbox should update state when items are completed / cleared', async ({ page }) => {- const toggleAll = page.getByLabel('Mark all as complete');- await toggleAll.check();- await expect(toggleAll).toBeChecked();- await checkNumberOfCompletedTodosInLocalStorage(page, 3);-- // Uncheck first todo.- const firstTodo = page.getByTestId('todo-item').nth(0);- await firstTodo.getByRole('checkbox').uncheck();-- // Reuse toggleAll locator and make sure its not checked.- await expect(toggleAll).not.toBeChecked();-- await firstTodo.getByRole('checkbox').check();- await checkNumberOfCompletedTodosInLocalStorage(page, 3);-- // Assert the toggle all is checked again.- await expect(toggleAll).toBeChecked();- });+ // Check test using different methods.+ await expect(page.getByText("3 items left")).toBeVisible();+ await expect(todoCount).toHaveText("3 items left");+ await expect(todoCount).toContainText("3");+ await expect(todoCount).toHaveText(/3/);++ // Check all items in one call.+ await expect(page.getByTestId("todo-title")).toHaveText(TODO_ITEMS);+ await checkNumberOfTodosInLocalStorage(page, 3);+ });});-test.describe('Item', () => {+test.describe("Mark all as completed", () => {+ test.beforeEach(async ({ page }) => {+ await createDefaultTodos(page);+ await checkNumberOfTodosInLocalStorage(page, 3);+ });- test('should allow me to mark items as complete', async ({ page }) => {- // create a new todo locator- const newTodo = page.getByPlaceholder('What needs to be done?');+ test.afterEach(async ({ page }) => {+ await checkNumberOfTodosInLocalStorage(page, 3);+ });- // Create two items.- for (const item of TODO_ITEMS.slice(0, 2)) {- await newTodo.fill(item);- await newTodo.press('Enter');- }+ test("should allow me to mark all items as completed", async ({ page }) => {+ // Complete all todos.+ await page.getByLabel("Mark all as complete").check();- // Check first item.- const firstTodo = page.getByTestId('todo-item').nth(0);- await firstTodo.getByRole('checkbox').check();- await expect(firstTodo).toHaveClass('completed');+ // Ensure all todos have 'completed' class.+ await expect(page.getByTestId("todo-item")).toHaveClass(["completed", "completed", "completed"]);+ await checkNumberOfCompletedTodosInLocalStorage(page, 3);+ });- // Check second item.- const secondTodo = page.getByTestId('todo-item').nth(1);- await expect(secondTodo).not.toHaveClass('completed');- await secondTodo.getByRole('checkbox').check();+ test("should allow me to clear the complete state of all items", async ({ page }) => {+ const toggleAll = page.getByLabel("Mark all as complete");+ // Check and then immediately uncheck.+ await toggleAll.check();+ await toggleAll.uncheck();- // Assert completed class.- await expect(firstTodo).toHaveClass('completed');- await expect(secondTodo).toHaveClass('completed');- });+ // Should be no completed classes.+ await expect(page.getByTestId("todo-item")).toHaveClass(["", "", ""]);+ });- test('should allow me to un-mark items as complete', async ({ page }) => {- // create a new todo locator- const newTodo = page.getByPlaceholder('What needs to be done?');+ test("complete all checkbox should update state when items are completed / cleared", async ({ page }) => {+ const toggleAll = page.getByLabel("Mark all as complete");+ await toggleAll.check();+ await expect(toggleAll).toBeChecked();+ await checkNumberOfCompletedTodosInLocalStorage(page, 3);- // Create two items.- for (const item of TODO_ITEMS.slice(0, 2)) {- await newTodo.fill(item);- await newTodo.press('Enter');- }+ // Uncheck first todo.+ const firstTodo = page.getByTestId("todo-item").nth(0);+ await firstTodo.getByRole("checkbox").uncheck();++ // Reuse toggleAll locator and make sure its not checked.+ await expect(toggleAll).not.toBeChecked();++ await firstTodo.getByRole("checkbox").check();+ await checkNumberOfCompletedTodosInLocalStorage(page, 3);- const firstTodo = page.getByTestId('todo-item').nth(0);- const secondTodo = page.getByTestId('todo-item').nth(1);- const firstTodoCheckbox = firstTodo.getByRole('checkbox');-- await firstTodoCheckbox.check();- await expect(firstTodo).toHaveClass('completed');- await expect(secondTodo).not.toHaveClass('completed');- await checkNumberOfCompletedTodosInLocalStorage(page, 1);-- await firstTodoCheckbox.uncheck();- await expect(firstTodo).not.toHaveClass('completed');- await expect(secondTodo).not.toHaveClass('completed');- await checkNumberOfCompletedTodosInLocalStorage(page, 0);- });-- test('should allow me to edit an item', async ({ page }) => {- await createDefaultTodos(page);-- const todoItems = page.getByTestId('todo-item');- const secondTodo = todoItems.nth(1);- await secondTodo.dblclick();- await expect(secondTodo.getByRole('textbox', { name: 'Edit' })).toHaveValue(TODO_ITEMS[1]);- await secondTodo.getByRole('textbox', { name: 'Edit' }).fill('buy some sausages');- await secondTodo.getByRole('textbox', { name: 'Edit' }).press('Enter');-- // Explicitly assert the new text value.- await expect(todoItems).toHaveText([- TODO_ITEMS[0],- 'buy some sausages',- TODO_ITEMS[2]- ]);- await checkTodosInLocalStorage(page, 'buy some sausages');- });+ // Assert the toggle all is checked again.+ await expect(toggleAll).toBeChecked();+ });});-test.describe('Editing', () => {- test.beforeEach(async ({ page }) => {- await createDefaultTodos(page);- await checkNumberOfTodosInLocalStorage(page, 3);- });-- test('should hide other controls when editing', async ({ page }) => {- const todoItem = page.getByTestId('todo-item').nth(1);- await todoItem.dblclick();- await expect(todoItem.getByRole('checkbox')).not.toBeVisible();- await expect(todoItem.locator('label', {- hasText: TODO_ITEMS[1],- })).not.toBeVisible();- await checkNumberOfTodosInLocalStorage(page, 3);- });-- test('should save edits on blur', async ({ page }) => {- const todoItems = page.getByTestId('todo-item');- await todoItems.nth(1).dblclick();- await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill('buy some sausages');- await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).dispatchEvent('blur');-- await expect(todoItems).toHaveText([- TODO_ITEMS[0],- 'buy some sausages',- TODO_ITEMS[2],- ]);- await checkTodosInLocalStorage(page, 'buy some sausages');- });-- test('should trim entered text', async ({ page }) => {- const todoItems = page.getByTestId('todo-item');- await todoItems.nth(1).dblclick();- await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill(' buy some sausages ');- await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Enter');-- await expect(todoItems).toHaveText([- TODO_ITEMS[0],- 'buy some sausages',- TODO_ITEMS[2],- ]);- await checkTodosInLocalStorage(page, 'buy some sausages');- });-- test('should remove the item if an empty text string was entered', async ({ page }) => {- const todoItems = page.getByTestId('todo-item');- await todoItems.nth(1).dblclick();- await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill('');- await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Enter');-- await expect(todoItems).toHaveText([- TODO_ITEMS[0],- TODO_ITEMS[2],- ]);- });-- test('should cancel edits on escape', async ({ page }) => {- const todoItems = page.getByTestId('todo-item');- await todoItems.nth(1).dblclick();- await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill('buy some sausages');- await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Escape');- await expect(todoItems).toHaveText(TODO_ITEMS);- });+test.describe("Item", () => {+ test("should allow me to mark items as complete", async ({ page }) => {+ // create a new todo locator+ const newTodo = page.getByPlaceholder("What needs to be done?");++ // Create two items.+ for (const item of TODO_ITEMS.slice(0, 2)) {+ await newTodo.fill(item);+ await newTodo.press("Enter");+ }++ // Check first item.+ const firstTodo = page.getByTestId("todo-item").nth(0);+ await firstTodo.getByRole("checkbox").check();+ await expect(firstTodo).toHaveClass("completed");++ // Check second item.+ const secondTodo = page.getByTestId("todo-item").nth(1);+ await expect(secondTodo).not.toHaveClass("completed");+ await secondTodo.getByRole("checkbox").check();++ // Assert completed class.+ await expect(firstTodo).toHaveClass("completed");+ await expect(secondTodo).toHaveClass("completed");+ });++ test("should allow me to un-mark items as complete", async ({ page }) => {+ // create a new todo locator+ const newTodo = page.getByPlaceholder("What needs to be done?");++ // Create two items.+ for (const item of TODO_ITEMS.slice(0, 2)) {+ await newTodo.fill(item);+ await newTodo.press("Enter");+ }++ const firstTodo = page.getByTestId("todo-item").nth(0);+ const secondTodo = page.getByTestId("todo-item").nth(1);+ const firstTodoCheckbox = firstTodo.getByRole("checkbox");++ await firstTodoCheckbox.check();+ await expect(firstTodo).toHaveClass("completed");+ await expect(secondTodo).not.toHaveClass("completed");+ await checkNumberOfCompletedTodosInLocalStorage(page, 1);++ await firstTodoCheckbox.uncheck();+ await expect(firstTodo).not.toHaveClass("completed");+ await expect(secondTodo).not.toHaveClass("completed");+ await checkNumberOfCompletedTodosInLocalStorage(page, 0);+ });++ test("should allow me to edit an item", async ({ page }) => {+ await createDefaultTodos(page);++ const todoItems = page.getByTestId("todo-item");+ const secondTodo = todoItems.nth(1);+ await secondTodo.dblclick();+ await expect(secondTodo.getByRole("textbox", { name: "Edit" })).toHaveValue(TODO_ITEMS[1]);+ await secondTodo.getByRole("textbox", { name: "Edit" }).fill("buy some sausages");+ await secondTodo.getByRole("textbox", { name: "Edit" }).press("Enter");++ // Explicitly assert the new text value.+ await expect(todoItems).toHaveText([TODO_ITEMS[0], "buy some sausages", TODO_ITEMS[2]]);+ await checkTodosInLocalStorage(page, "buy some sausages");+ });});-test.describe('Counter', () => {- test('should display the current number of todo items', async ({ page }) => {- // create a new todo locator- const newTodo = page.getByPlaceholder('What needs to be done?');+test.describe("Editing", () => {+ test.beforeEach(async ({ page }) => {+ await createDefaultTodos(page);+ await checkNumberOfTodosInLocalStorage(page, 3);+ });- // create a todo count locator- const todoCount = page.getByTestId('todo-count')+ test("should hide other controls when editing", async ({ page }) => {+ const todoItem = page.getByTestId("todo-item").nth(1);+ await todoItem.dblclick();+ await expect(todoItem.getByRole("checkbox")).not.toBeVisible();+ await expect(+ todoItem.locator("label", {+ hasText: TODO_ITEMS[1]+ })+ ).not.toBeVisible();+ await checkNumberOfTodosInLocalStorage(page, 3);+ });- await newTodo.fill(TODO_ITEMS[0]);- await newTodo.press('Enter');+ test("should save edits on blur", async ({ page }) => {+ const todoItems = page.getByTestId("todo-item");+ await todoItems.nth(1).dblclick();+ await todoItems.nth(1).getByRole("textbox", { name: "Edit" }).fill("buy some sausages");+ await todoItems.nth(1).getByRole("textbox", { name: "Edit" }).dispatchEvent("blur");- await expect(todoCount).toContainText('1');+ await expect(todoItems).toHaveText([TODO_ITEMS[0], "buy some sausages", TODO_ITEMS[2]]);+ await checkTodosInLocalStorage(page, "buy some sausages");+ });++ test("should trim entered text", async ({ page }) => {+ const todoItems = page.getByTestId("todo-item");+ await todoItems.nth(1).dblclick();+ await todoItems.nth(1).getByRole("textbox", { name: "Edit" }).fill(" buy some sausages ");+ await todoItems.nth(1).getByRole("textbox", { name: "Edit" }).press("Enter");++ await expect(todoItems).toHaveText([TODO_ITEMS[0], "buy some sausages", TODO_ITEMS[2]]);+ await checkTodosInLocalStorage(page, "buy some sausages");+ });- await newTodo.fill(TODO_ITEMS[1]);- await newTodo.press('Enter');- await expect(todoCount).toContainText('2');+ test("should remove the item if an empty text string was entered", async ({ page }) => {+ const todoItems = page.getByTestId("todo-item");+ await todoItems.nth(1).dblclick();+ await todoItems.nth(1).getByRole("textbox", { name: "Edit" }).fill("");+ await todoItems.nth(1).getByRole("textbox", { name: "Edit" }).press("Enter");- await checkNumberOfTodosInLocalStorage(page, 2);- });+ await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]);+ });++ test("should cancel edits on escape", async ({ page }) => {+ const todoItems = page.getByTestId("todo-item");+ await todoItems.nth(1).dblclick();+ await todoItems.nth(1).getByRole("textbox", { name: "Edit" }).fill("buy some sausages");+ await todoItems.nth(1).getByRole("textbox", { name: "Edit" }).press("Escape");+ await expect(todoItems).toHaveText(TODO_ITEMS);+ });});-test.describe('Clear completed button', () => {- test.beforeEach(async ({ page }) => {- await createDefaultTodos(page);- });-- test('should display the correct text', async ({ page }) => {- await page.locator('.todo-list li .toggle').first().check();- await expect(page.getByRole('button', { name: 'Clear completed' })).toBeVisible();- });-- test('should remove completed items when clicked', async ({ page }) => {- const todoItems = page.getByTestId('todo-item');- await todoItems.nth(1).getByRole('checkbox').check();- await page.getByRole('button', { name: 'Clear completed' }).click();- await expect(todoItems).toHaveCount(2);- await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]);- });-- test('should be hidden when there are no items that are completed', async ({ page }) => {- await page.locator('.todo-list li .toggle').first().check();- await page.getByRole('button', { name: 'Clear completed' }).click();- await expect(page.getByRole('button', { name: 'Clear completed' })).toBeHidden();- });+test.describe("Counter", () => {+ test("should display the current number of todo items", async ({ page }) => {+ // create a new todo locator+ const newTodo = page.getByPlaceholder("What needs to be done?");++ // create a todo count locator+ const todoCount = page.getByTestId("todo-count");++ await newTodo.fill(TODO_ITEMS[0]);+ await newTodo.press("Enter");++ await expect(todoCount).toContainText("1");++ await newTodo.fill(TODO_ITEMS[1]);+ await newTodo.press("Enter");+ await expect(todoCount).toContainText("2");++ await checkNumberOfTodosInLocalStorage(page, 2);+ });});-test.describe('Persistence', () => {- test('should persist its data', async ({ page }) => {- // create a new todo locator- const newTodo = page.getByPlaceholder('What needs to be done?');+test.describe("Clear completed button", () => {+ test.beforeEach(async ({ page }) => {+ await createDefaultTodos(page);+ });- for (const item of TODO_ITEMS.slice(0, 2)) {- await newTodo.fill(item);- await newTodo.press('Enter');- }+ test("should display the correct text", async ({ page }) => {+ await page.locator(".todo-list li .toggle").first().check();+ await expect(page.getByRole("button", { name: "Clear completed" })).toBeVisible();+ });- const todoItems = page.getByTestId('todo-item');- const firstTodoCheck = todoItems.nth(0).getByRole('checkbox');- await firstTodoCheck.check();- await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]);- await expect(firstTodoCheck).toBeChecked();- await expect(todoItems).toHaveClass(['completed', '']);-- // Ensure there is 1 completed item.- await checkNumberOfCompletedTodosInLocalStorage(page, 1);-- // Now reload.- await page.reload();- await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]);- await expect(firstTodoCheck).toBeChecked();- await expect(todoItems).toHaveClass(['completed', '']);- });+ test("should remove completed items when clicked", async ({ page }) => {+ const todoItems = page.getByTestId("todo-item");+ await todoItems.nth(1).getByRole("checkbox").check();+ await page.getByRole("button", { name: "Clear completed" }).click();+ await expect(todoItems).toHaveCount(2);+ await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]);+ });++ test("should be hidden when there are no items that are completed", async ({ page }) => {+ await page.locator(".todo-list li .toggle").first().check();+ await page.getByRole("button", { name: "Clear completed" }).click();+ await expect(page.getByRole("button", { name: "Clear completed" })).toBeHidden();+ });});-test.describe('Routing', () => {- test.beforeEach(async ({ page }) => {- await createDefaultTodos(page);- // make sure the app had a chance to save updated todos in storage- // before navigating to a new view, otherwise the items can get lost :(- // in some frameworks like Durandal- await checkTodosInLocalStorage(page, TODO_ITEMS[0]);- });-- test('should allow me to display active items', async ({ page }) => {- const todoItem = page.getByTestId('todo-item');- await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check();-- await checkNumberOfCompletedTodosInLocalStorage(page, 1);- await page.getByRole('link', { name: 'Active' }).click();- await expect(todoItem).toHaveCount(2);- await expect(todoItem).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]);- });-- test('should respect the back button', async ({ page }) => {- const todoItem = page.getByTestId('todo-item');- await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check();-- await checkNumberOfCompletedTodosInLocalStorage(page, 1);-- await test.step('Showing all items', async () => {- await page.getByRole('link', { name: 'All' }).click();- await expect(todoItem).toHaveCount(3);+test.describe("Persistence", () => {+ test("should persist its data", async ({ page }) => {+ // create a new todo locator+ const newTodo = page.getByPlaceholder("What needs to be done?");++ for (const item of TODO_ITEMS.slice(0, 2)) {+ await newTodo.fill(item);+ await newTodo.press("Enter");+ }++ const todoItems = page.getByTestId("todo-item");+ const firstTodoCheck = todoItems.nth(0).getByRole("checkbox");+ await firstTodoCheck.check();+ await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]);+ await expect(firstTodoCheck).toBeChecked();+ await expect(todoItems).toHaveClass(["completed", ""]);++ // Ensure there is 1 completed item.+ await checkNumberOfCompletedTodosInLocalStorage(page, 1);++ // Now reload.+ await page.reload();+ await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]);+ await expect(firstTodoCheck).toBeChecked();+ await expect(todoItems).toHaveClass(["completed", ""]);});+});- await test.step('Showing active items', async () => {- await page.getByRole('link', { name: 'Active' }).click();+test.describe("Routing", () => {+ test.beforeEach(async ({ page }) => {+ await createDefaultTodos(page);+ // make sure the app had a chance to save updated todos in storage+ // before navigating to a new view, otherwise the items can get lost :(+ // in some frameworks like Durandal+ await checkTodosInLocalStorage(page, TODO_ITEMS[0]);});- await test.step('Showing completed items', async () => {- await page.getByRole('link', { name: 'Completed' }).click();+ test("should allow me to display active items", async ({ page }) => {+ const todoItem = page.getByTestId("todo-item");+ await page.getByTestId("todo-item").nth(1).getByRole("checkbox").check();++ await checkNumberOfCompletedTodosInLocalStorage(page, 1);+ await page.getByRole("link", { name: "Active" }).click();+ await expect(todoItem).toHaveCount(2);+ await expect(todoItem).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]);});- await expect(todoItem).toHaveCount(1);- await page.goBack();- await expect(todoItem).toHaveCount(2);- await page.goBack();- await expect(todoItem).toHaveCount(3);- });-- test('should allow me to display completed items', async ({ page }) => {- await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check();- await checkNumberOfCompletedTodosInLocalStorage(page, 1);- await page.getByRole('link', { name: 'Completed' }).click();- await expect(page.getByTestId('todo-item')).toHaveCount(1);- });-- test('should allow me to display all items', async ({ page }) => {- await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check();- await checkNumberOfCompletedTodosInLocalStorage(page, 1);- await page.getByRole('link', { name: 'Active' }).click();- await page.getByRole('link', { name: 'Completed' }).click();- await page.getByRole('link', { name: 'All' }).click();- await expect(page.getByTestId('todo-item')).toHaveCount(3);- });-- test('should highlight the currently applied filter', async ({ page }) => {- await expect(page.getByRole('link', { name: 'All' })).toHaveClass('selected');-- //create locators for active and completed links- const activeLink = page.getByRole('link', { name: 'Active' });- const completedLink = page.getByRole('link', { name: 'Completed' });- await activeLink.click();-- // Page change - active items.- await expect(activeLink).toHaveClass('selected');- await completedLink.click();-- // Page change - completed items.- await expect(completedLink).toHaveClass('selected');- });+ test("should respect the back button", async ({ page }) => {+ const todoItem = page.getByTestId("todo-item");+ await page.getByTestId("todo-item").nth(1).getByRole("checkbox").check();++ await checkNumberOfCompletedTodosInLocalStorage(page, 1);++ await test.step("Showing all items", async () => {+ await page.getByRole("link", { name: "All" }).click();+ await expect(todoItem).toHaveCount(3);+ });++ await test.step("Showing active items", async () => {+ await page.getByRole("link", { name: "Active" }).click();+ });++ await test.step("Showing completed items", async () => {+ await page.getByRole("link", { name: "Completed" }).click();+ });++ await expect(todoItem).toHaveCount(1);+ await page.goBack();+ await expect(todoItem).toHaveCount(2);+ await page.goBack();+ await expect(todoItem).toHaveCount(3);+ });++ test("should allow me to display completed items", async ({ page }) => {+ await page.getByTestId("todo-item").nth(1).getByRole("checkbox").check();+ await checkNumberOfCompletedTodosInLocalStorage(page, 1);+ await page.getByRole("link", { name: "Completed" }).click();+ await expect(page.getByTestId("todo-item")).toHaveCount(1);+ });++ test("should allow me to display all items", async ({ page }) => {+ await page.getByTestId("todo-item").nth(1).getByRole("checkbox").check();+ await checkNumberOfCompletedTodosInLocalStorage(page, 1);+ await page.getByRole("link", { name: "Active" }).click();+ await page.getByRole("link", { name: "Completed" }).click();+ await page.getByRole("link", { name: "All" }).click();+ await expect(page.getByTestId("todo-item")).toHaveCount(3);+ });++ test("should highlight the currently applied filter", async ({ page }) => {+ await expect(page.getByRole("link", { name: "All" })).toHaveClass("selected");++ //create locators for active and completed links+ const activeLink = page.getByRole("link", { name: "Active" });+ const completedLink = page.getByRole("link", { name: "Completed" });+ await activeLink.click();++ // Page change - active items.+ await expect(activeLink).toHaveClass("selected");+ await completedLink.click();++ // Page change - completed items.+ await expect(completedLink).toHaveClass("selected");+ });});async function createDefaultTodos(page: Page) {- // create a new todo locator- const newTodo = page.getByPlaceholder('What needs to be done?');+ // create a new todo locator+ const newTodo = page.getByPlaceholder("What needs to be done?");- for (const item of TODO_ITEMS) {- await newTodo.fill(item);- await newTodo.press('Enter');- }+ for (const item of TODO_ITEMS) {+ await newTodo.fill(item);+ await newTodo.press("Enter");+ }}async function checkNumberOfTodosInLocalStorage(page: Page, expected: number) {- return await page.waitForFunction(e => {- return JSON.parse(localStorage['react-todos']).length === e;- }, expected);+ return await page.waitForFunction((e) => {+ return JSON.parse(localStorage["react-todos"]).length === e;+ }, expected);}async function checkNumberOfCompletedTodosInLocalStorage(page: Page, expected: number) {- return await page.waitForFunction(e => {- return JSON.parse(localStorage['react-todos']).filter((todo: any) => todo.completed).length === e;- }, expected);+ return await page.waitForFunction((e) => {+ return JSON.parse(localStorage["react-todos"]).filter((todo: any) => todo.completed).length === e;+ }, expected);}async function checkTodosInLocalStorage(page: Page, title: string) {- return await page.waitForFunction(t => {- return JSON.parse(localStorage['react-todos']).map((todo: any) => todo.title).includes(t);- }, title);+ return await page.waitForFunction((t) => {+ return JSON.parse(localStorage["react-todos"])+ .map((todo: any) => todo.title)+ .includes(t);+ }, title);}diff --git a/translations/cn/server.json b/translations/cn/server.jsonindex af62aa155f..563233aa2b 100644--- a/translations/cn/server.json+++ b/translations/cn/server.json@@ -1,248 +1,248 @@{- "keyboard_actions": {- "open-jump-to-note-dialog": "打开“跳转到笔记”对话框",- "search-in-subtree": "在当前笔记的子树中搜索笔记",- "expand-subtree": "展开当前笔记的子树",- "collapse-tree": "折叠完整的笔记树",- "collapse-subtree": "折叠当前笔记的子树",- "sort-child-notes": "排序子笔记",- "creating-and-moving-notes": "创建和移动笔记",- "create-note-into-inbox": "在收件箱(如果有定义的话)或日记中创建笔记",- "delete-note": "删除笔记",- "move-note-up": "上移笔记",- "move-note-down": "下移笔记",- "move-note-up-in-hierarchy": "在层级中上移笔记",- "move-note-down-in-hierarchy": "在层级中下移笔记",- "edit-note-title": "从笔记树跳转到笔记详情并编辑标题",- "edit-branch-prefix": "显示编辑分支前缀对话框",- "note-clipboard": "笔记剪贴板",- "copy-notes-to-clipboard": "复制选定的笔记到剪贴板",- "paste-notes-from-clipboard": "从剪贴板粘贴笔记到活动笔记中",- "cut-notes-to-clipboard": "剪切选定的笔记到剪贴板",- "select-all-notes-in-parent": "选择当前笔记级别的所有笔记",- "add-note-above-to-the-selection": "将上方笔记添加到选择中",- "add-note-below-to-selection": "将下方笔记添加到选择中",- "duplicate-subtree": "复制子树",- "tabs-and-windows": "标签和窗口",- "open-new-tab": "打开新标签",- "close-active-tab": "关闭活动标签",- "reopen-last-tab": "重新打开最后关闭的标签",- "activate-next-tab": "激活右侧标签",- "activate-previous-tab": "激活左侧标签",- "open-new-window": "打开新空窗口",- "toggle-tray": "显示/隐藏应用程序的系统托盘",- "first-tab": "激活列表中的第一个标签",- "second-tab": "激活列表中的第二个标签",- "third-tab": "激活列表中的第三个标签",- "fourth-tab": "激活列表中的第四个标签",- "fifth-tab": "激活列表中的第五个标签",- "sixth-tab": "激活列表中的第六个标签",- "seventh-tab": "激活列表中的第七个标签",- "eight-tab": "激活列表中的第八个标签",- "ninth-tab": "激活列表中的第九个标签",- "last-tab": "激活列表中的最后一个标签",- "dialogs": "对话框",- "show-note-source": "显示笔记源对话框",- "show-options": "显示选项对话框",- "show-revisions": "显示笔记历史对话框",- "show-recent-changes": "显示最近更改对话框",- "show-sql-console": "显示SQL控制台对话框",- "show-backend-log": "显示后端日志对话框",- "text-note-operations": "文本笔记操作",- "add-link-to-text": "打开对话框以将链接添加到文本",- "follow-link-under-cursor": "跟随光标下的链接",- "insert-date-and-time-to-text": "将当前日期和时间插入文本",- "paste-markdown-into-text": "将剪贴板中的Markdown粘贴到文本笔记中",- "cut-into-note": "从当前笔记中剪切选择并创建包含选定文本的子笔记",- "add-include-note-to-text": "打开对话框以包含笔记",- "edit-readonly-note": "编辑只读笔记",- "attributes-labels-and-relations": "属性(标签和关系)",- "add-new-label": "创建新标签",- "create-new-relation": "创建新关系",- "ribbon-tabs": "功能区标签",- "toggle-basic-properties": "切换基本属性",- "toggle-file-properties": "切换文件属性",- "toggle-image-properties": "切换图像属性",- "toggle-owned-attributes": "切换拥有的属性",- "toggle-inherited-attributes": "切换继承的属性",- "toggle-promoted-attributes": "切换提升的属性",- "toggle-link-map": "切换链接地图",- "toggle-note-info": "切换笔记信息",- "toggle-note-paths": "切换笔记路径",- "toggle-similar-notes": "切换相似笔记",- "other": "其他",- "toggle-right-pane": "切换右侧面板的显示,包括目录和高亮",- "print-active-note": "打印活动笔记",- "open-note-externally": "以默认应用程序打开笔记文件",- "render-active-note": "渲染(重新渲染)活动笔记",- "run-active-note": "运行活动JavaScript(前端/后端)代码笔记",- "toggle-note-hoisting": "切换活动笔记的提升",- "unhoist": "从任何地方取消提升",- "reload-frontend-app": "重新加载前端应用",- "open-dev-tools": "打开开发工具",- "toggle-left-note-tree-panel": "切换左侧(笔记树)面板",- "toggle-full-screen": "切换全屏",- "zoom-out": "缩小",- "zoom-in": "放大",- "note-navigation": "笔记导航",- "reset-zoom-level": "重置缩放级别",- "copy-without-formatting": "不带格式复制选定文本",- "force-save-revision": "强制创建/保存当前笔记的历史版本",- "show-help": "显示内置帮助/备忘单",- "toggle-book-properties": "切换书籍属性",- "toggle-classic-editor-toolbar": "切换具有固定工具栏的编辑器格式化选项卡"- },- "login": {- "title": "登录",- "heading": "Trilium登录",- "incorrect-password": "密码不正确。请再试一次。",- "password": "密码",- "remember-me": "记住我",- "button": "登录"- },- "set_password": {- "title": "设置密码",- "heading": "设置密码",- "description": "在您可以从Web开始使用Trilium之前,您需要先设置一个密码。然后您将使用此密码登录。",- "password": "密码",- "password-confirmation": "密码确认",- "button": "设置密码"- },- "javascript-required": "Trilium需要启用JavaScript。",- "setup": {- "heading": "TriliumNext笔记设置",- "new-document": "我是新用户,我想为我的笔记创建一个新的Trilium文档",- "sync-from-desktop": "我已经有一个桌面实例,我想设置与它的同步",- "sync-from-server": "我已经有一个服务器实例,我想设置与它的同步",- "next": "下一步",- "init-in-progress": "文档初始化进行中",- "redirecting": "您将很快被重定向到应用程序。",- "title": "设置"- },- "setup_sync-from-desktop": {- "heading": "从桌面同步",- "description": "此设置需要从桌面实例启动:",- "step1": "打开您的TriliumNext笔记桌面实例。",- "step2": "从Trilium菜单中,点击选项。",- "step3": "点击同步。",- "step4": "将服务器实例地址更改为:{{- host}}并点击保存。",- "step5": "点击“测试同步”按钮以验证连接是否成功。",- "step6": "完成这些步骤后,点击{{- link}}。",- "step6-here": "这里"- },- "setup_sync-from-server": {- "heading": "从服务器同步",- "instructions": "请在下面输入Trilium服务器地址和密码。这将从服务器下载整个Trilium数据库文档并设置同步。根据数据库大小和您的连接速度,这可能需要一段时间。",- "server-host": "Trilium服务器地址",- "server-host-placeholder": "https://<主机名称>:<端口>",- "proxy-server": "代理服务器(可选)",- "proxy-server-placeholder": "https://<主机名称>:<端口>",- "note": "注意:",- "proxy-instruction": "如果您将代理设置留空,将使用系统代理(仅适用于桌面应用)",- "password": "密码",- "password-placeholder": "密码",- "back": "返回",- "finish-setup": "完成设置"- },- "setup_sync-in-progress": {- "heading": "同步中",- "successful": "同步已正确设置。初始同步完成可能需要一些时间。完成后,您将被重定向到登录页面。",- "outstanding-items": "未完成的同步项目:",- "outstanding-items-default": "无"- },- "share_404": {- "title": "未找到",- "heading": "未找到"- },- "share_page": {- "parent": "父级:",- "clipped-from": "此笔记最初剪切自 {{- url}}",- "child-notes": "子笔记:",- "no-content": "此笔记没有内容。"- },- "weekdays": {- "monday": "周一",- "tuesday": "周二",- "wednesday": "周三",- "thursday": "周四",- "friday": "周五",- "saturday": "周六",- "sunday": "周日"- },- "months": {- "january": "一月",- "february": "二月",- "march": "三月",- "april": "四月",- "may": "五月",- "june": "六月",- "july": "七月",- "august": "八月",- "september": "九月",- "october": "十月",- "november": "十一月",- "december": "十二月"- },- "special_notes": {- "search_prefix": "搜索:"- },- "code_block": {- "theme_none": "无语法高亮",- "theme_group_light": "浅色主题",- "theme_group_dark": "深色主题"- },- "test_sync": {- "not-configured": "同步服务器主机未配置。请先配置同步。",- "successful": "同步服务器握手成功,同步已开始。"- },- "hidden-subtree": {- "root-title": "隐藏笔记",- "search-history-title": "搜索历史",- "note-map-title": "笔记地图",- "sql-console-history-title": "SQL 控制台历史",- "shared-notes-title": "共享笔记",- "bulk-action-title": "批量操作",- "backend-log-title": "后端日志",- "user-hidden-title": "用户隐藏",- "launch-bar-templates-title": "启动栏模板",- "base-abstract-launcher-title": "基础抽象启动器",- "command-launcher-title": "命令启动器",- "note-launcher-title": "笔记启动器",- "script-launcher-title": "脚本启动器",- "built-in-widget-title": "内置小组件",- "spacer-title": "空白占位",- "custom-widget-title": "自定义小组件",- "launch-bar-title": "启动栏",- "available-launchers-title": "可用启动器",- "go-to-previous-note-title": "跳转到上一条笔记",- "go-to-next-note-title": "跳转到下一条笔记",- "new-note-title": "新建笔记",- "search-notes-title": "搜索笔记",- "jump-to-note-title": "跳转到笔记",- "calendar-title": "日历",- "recent-changes-title": "最近更改",- "bookmarks-title": "书签",- "open-today-journal-note-title": "打开今天的日记笔记",- "quick-search-title": "快速搜索",- "protected-session-title": "受保护的会话",- "sync-status-title": "同步状态",- "settings-title": "设置",- "options-title": "选项",- "appearance-title": "外观",- "shortcuts-title": "快捷键",- "text-notes": "文本笔记",- "code-notes-title": "代码笔记",- "images-title": "图片",- "spellcheck-title": "拼写检查",- "password-title": "密码",- "etapi-title": "ETAPI",- "backup-title": "备份",- "sync-title": "同步",- "other": "其他",- "advanced-title": "高级",- "visible-launchers-title": "可见启动器"- },- "notes": {- "new-note": "新建笔记"- }+ "keyboard_actions": {+ "open-jump-to-note-dialog": "打开“跳转到笔记”对话框",+ "search-in-subtree": "在当前笔记的子树中搜索笔记",+ "expand-subtree": "展开当前笔记的子树",+ "collapse-tree": "折叠完整的笔记树",+ "collapse-subtree": "折叠当前笔记的子树",+ "sort-child-notes": "排序子笔记",+ "creating-and-moving-notes": "创建和移动笔记",+ "create-note-into-inbox": "在收件箱(如果有定义的话)或日记中创建笔记",+ "delete-note": "删除笔记",+ "move-note-up": "上移笔记",+ "move-note-down": "下移笔记",+ "move-note-up-in-hierarchy": "在层级中上移笔记",+ "move-note-down-in-hierarchy": "在层级中下移笔记",+ "edit-note-title": "从笔记树跳转到笔记详情并编辑标题",+ "edit-branch-prefix": "显示编辑分支前缀对话框",+ "note-clipboard": "笔记剪贴板",+ "copy-notes-to-clipboard": "复制选定的笔记到剪贴板",+ "paste-notes-from-clipboard": "从剪贴板粘贴笔记到活动笔记中",+ "cut-notes-to-clipboard": "剪切选定的笔记到剪贴板",+ "select-all-notes-in-parent": "选择当前笔记级别的所有笔记",+ "add-note-above-to-the-selection": "将上方笔记添加到选择中",+ "add-note-below-to-selection": "将下方笔记添加到选择中",+ "duplicate-subtree": "复制子树",+ "tabs-and-windows": "标签和窗口",+ "open-new-tab": "打开新标签",+ "close-active-tab": "关闭活动标签",+ "reopen-last-tab": "重新打开最后关闭的标签",+ "activate-next-tab": "激活右侧标签",+ "activate-previous-tab": "激活左侧标签",+ "open-new-window": "打开新空窗口",+ "toggle-tray": "显示/隐藏应用程序的系统托盘",+ "first-tab": "激活列表中的第一个标签",+ "second-tab": "激活列表中的第二个标签",+ "third-tab": "激活列表中的第三个标签",+ "fourth-tab": "激活列表中的第四个标签",+ "fifth-tab": "激活列表中的第五个标签",+ "sixth-tab": "激活列表中的第六个标签",+ "seventh-tab": "激活列表中的第七个标签",+ "eight-tab": "激活列表中的第八个标签",+ "ninth-tab": "激活列表中的第九个标签",+ "last-tab": "激活列表中的最后一个标签",+ "dialogs": "对话框",+ "show-note-source": "显示笔记源对话框",+ "show-options": "显示选项对话框",+ "show-revisions": "显示笔记历史对话框",+ "show-recent-changes": "显示最近更改对话框",+ "show-sql-console": "显示SQL控制台对话框",+ "show-backend-log": "显示后端日志对话框",+ "text-note-operations": "文本笔记操作",+ "add-link-to-text": "打开对话框以将链接添加到文本",+ "follow-link-under-cursor": "跟随光标下的链接",+ "insert-date-and-time-to-text": "将当前日期和时间插入文本",+ "paste-markdown-into-text": "将剪贴板中的Markdown粘贴到文本笔记中",+ "cut-into-note": "从当前笔记中剪切选择并创建包含选定文本的子笔记",+ "add-include-note-to-text": "打开对话框以包含笔记",+ "edit-readonly-note": "编辑只读笔记",+ "attributes-labels-and-relations": "属性(标签和关系)",+ "add-new-label": "创建新标签",+ "create-new-relation": "创建新关系",+ "ribbon-tabs": "功能区标签",+ "toggle-basic-properties": "切换基本属性",+ "toggle-file-properties": "切换文件属性",+ "toggle-image-properties": "切换图像属性",+ "toggle-owned-attributes": "切换拥有的属性",+ "toggle-inherited-attributes": "切换继承的属性",+ "toggle-promoted-attributes": "切换提升的属性",+ "toggle-link-map": "切换链接地图",+ "toggle-note-info": "切换笔记信息",+ "toggle-note-paths": "切换笔记路径",+ "toggle-similar-notes": "切换相似笔记",+ "other": "其他",+ "toggle-right-pane": "切换右侧面板的显示,包括目录和高亮",+ "print-active-note": "打印活动笔记",+ "open-note-externally": "以默认应用程序打开笔记文件",+ "render-active-note": "渲染(重新渲染)活动笔记",+ "run-active-note": "运行活动JavaScript(前端/后端)代码笔记",+ "toggle-note-hoisting": "切换活动笔记的提升",+ "unhoist": "从任何地方取消提升",+ "reload-frontend-app": "重新加载前端应用",+ "open-dev-tools": "打开开发工具",+ "toggle-left-note-tree-panel": "切换左侧(笔记树)面板",+ "toggle-full-screen": "切换全屏",+ "zoom-out": "缩小",+ "zoom-in": "放大",+ "note-navigation": "笔记导航",+ "reset-zoom-level": "重置缩放级别",+ "copy-without-formatting": "不带格式复制选定文本",+ "force-save-revision": "强制创建/保存当前笔记的历史版本",+ "show-help": "显示内置帮助/备忘单",+ "toggle-book-properties": "切换书籍属性",+ "toggle-classic-editor-toolbar": "切换具有固定工具栏的编辑器格式化选项卡"+ },+ "login": {+ "title": "登录",+ "heading": "Trilium登录",+ "incorrect-password": "密码不正确。请再试一次。",+ "password": "密码",+ "remember-me": "记住我",+ "button": "登录"+ },+ "set_password": {+ "title": "设置密码",+ "heading": "设置密码",+ "description": "在您可以从Web开始使用Trilium之前,您需要先设置一个密码。然后您将使用此密码登录。",+ "password": "密码",+ "password-confirmation": "密码确认",+ "button": "设置密码"+ },+ "javascript-required": "Trilium需要启用JavaScript。",+ "setup": {+ "heading": "TriliumNext笔记设置",+ "new-document": "我是新用户,我想为我的笔记创建一个新的Trilium文档",+ "sync-from-desktop": "我已经有一个桌面实例,我想设置与它的同步",+ "sync-from-server": "我已经有一个服务器实例,我想设置与它的同步",+ "next": "下一步",+ "init-in-progress": "文档初始化进行中",+ "redirecting": "您将很快被重定向到应用程序。",+ "title": "设置"+ },+ "setup_sync-from-desktop": {+ "heading": "从桌面同步",+ "description": "此设置需要从桌面实例启动:",+ "step1": "打开您的TriliumNext笔记桌面实例。",+ "step2": "从Trilium菜单中,点击选项。",+ "step3": "点击同步。",+ "step4": "将服务器实例地址更改为:{{- host}}并点击保存。",+ "step5": "点击“测试同步”按钮以验证连接是否成功。",+ "step6": "完成这些步骤后,点击{{- link}}。",+ "step6-here": "这里"+ },+ "setup_sync-from-server": {+ "heading": "从服务器同步",+ "instructions": "请在下面输入Trilium服务器地址和密码。这将从服务器下载整个Trilium数据库文档并设置同步。根据数据库大小和您的连接速度,这可能需要一段时间。",+ "server-host": "Trilium服务器地址",+ "server-host-placeholder": "https://<主机名称>:<端口>",+ "proxy-server": "代理服务器(可选)",+ "proxy-server-placeholder": "https://<主机名称>:<端口>",+ "note": "注意:",+ "proxy-instruction": "如果您将代理设置留空,将使用系统代理(仅适用于桌面应用)",+ "password": "密码",+ "password-placeholder": "密码",+ "back": "返回",+ "finish-setup": "完成设置"+ },+ "setup_sync-in-progress": {+ "heading": "同步中",+ "successful": "同步已正确设置。初始同步完成可能需要一些时间。完成后,您将被重定向到登录页面。",+ "outstanding-items": "未完成的同步项目:",+ "outstanding-items-default": "无"+ },+ "share_404": {+ "title": "未找到",+ "heading": "未找到"+ },+ "share_page": {+ "parent": "父级:",+ "clipped-from": "此笔记最初剪切自 {{- url}}",+ "child-notes": "子笔记:",+ "no-content": "此笔记没有内容。"+ },+ "weekdays": {+ "monday": "周一",+ "tuesday": "周二",+ "wednesday": "周三",+ "thursday": "周四",+ "friday": "周五",+ "saturday": "周六",+ "sunday": "周日"+ },+ "months": {+ "january": "一月",+ "february": "二月",+ "march": "三月",+ "april": "四月",+ "may": "五月",+ "june": "六月",+ "july": "七月",+ "august": "八月",+ "september": "九月",+ "october": "十月",+ "november": "十一月",+ "december": "十二月"+ },+ "special_notes": {+ "search_prefix": "搜索:"+ },+ "code_block": {+ "theme_none": "无语法高亮",+ "theme_group_light": "浅色主题",+ "theme_group_dark": "深色主题"+ },+ "test_sync": {+ "not-configured": "同步服务器主机未配置。请先配置同步。",+ "successful": "同步服务器握手成功,同步已开始。"+ },+ "hidden-subtree": {+ "root-title": "隐藏笔记",+ "search-history-title": "搜索历史",+ "note-map-title": "笔记地图",+ "sql-console-history-title": "SQL 控制台历史",+ "shared-notes-title": "共享笔记",+ "bulk-action-title": "批量操作",+ "backend-log-title": "后端日志",+ "user-hidden-title": "用户隐藏",+ "launch-bar-templates-title": "启动栏模板",+ "base-abstract-launcher-title": "基础抽象启动器",+ "command-launcher-title": "命令启动器",+ "note-launcher-title": "笔记启动器",+ "script-launcher-title": "脚本启动器",+ "built-in-widget-title": "内置小组件",+ "spacer-title": "空白占位",+ "custom-widget-title": "自定义小组件",+ "launch-bar-title": "启动栏",+ "available-launchers-title": "可用启动器",+ "go-to-previous-note-title": "跳转到上一条笔记",+ "go-to-next-note-title": "跳转到下一条笔记",+ "new-note-title": "新建笔记",+ "search-notes-title": "搜索笔记",+ "jump-to-note-title": "跳转到笔记",+ "calendar-title": "日历",+ "recent-changes-title": "最近更改",+ "bookmarks-title": "书签",+ "open-today-journal-note-title": "打开今天的日记笔记",+ "quick-search-title": "快速搜索",+ "protected-session-title": "受保护的会话",+ "sync-status-title": "同步状态",+ "settings-title": "设置",+ "options-title": "选项",+ "appearance-title": "外观",+ "shortcuts-title": "快捷键",+ "text-notes": "文本笔记",+ "code-notes-title": "代码笔记",+ "images-title": "图片",+ "spellcheck-title": "拼写检查",+ "password-title": "密码",+ "etapi-title": "ETAPI",+ "backup-title": "备份",+ "sync-title": "同步",+ "other": "其他",+ "advanced-title": "高级",+ "visible-launchers-title": "可见启动器"+ },+ "notes": {+ "new-note": "新建笔记"+ }}diff --git a/translations/tw/server.json b/translations/tw/server.jsonindex 717d113761..d30f92bd91 100644--- a/translations/tw/server.json+++ b/translations/tw/server.json@@ -1,197 +1,197 @@{- "keyboard_actions":{- "open-jump-to-note-dialog":"打開「跳轉到筆記」對話框",- "search-in-subtree":"在當前筆記的子樹中搜索筆記",- "expand-subtree":"展開當前筆記的子樹",- "collapse-tree":"折疊完整的筆記樹",- "collapse-subtree":"折疊當前筆記的子樹",- "sort-child-notes":"排序子筆記",- "creating-and-moving-notes":"新增和移動筆記",- "create-note-into-inbox":"在收件匣(如果有定義的話)或日記中新增筆記",- "delete-note":"刪除筆記",- "move-note-up":"上移筆記",- "move-note-down":"下移筆記",- "move-note-up-in-hierarchy":"上移筆記層級",- "move-note-down-in-hierarchy":"下移筆記層級",- "edit-note-title":"從筆記樹跳轉到筆記詳情並編輯標題",- "edit-branch-prefix":"顯示編輯分支前綴對話框",- "note-clipboard":"筆記剪貼簿",- "copy-notes-to-clipboard":"複製選定的筆記到剪貼簿",- "paste-notes-from-clipboard":"從剪貼簿粘貼筆記到活動筆記中",- "cut-notes-to-clipboard":"剪下選定的筆記到剪貼簿",- "select-all-notes-in-parent":"選擇當前筆記級別的所有筆記",- "add-note-above-to-the-selection":"將上方筆記添加到選擇中",- "add-note-below-to-selection":"將下方筆記添加到選擇中",- "duplicate-subtree":"複製子樹",- "tabs-and-windows":"標籤和窗口",- "open-new-tab":"打開新標籤",- "close-active-tab":"關閉活動標籤",- "reopen-last-tab":"重新打開最後關閉的標籤",- "activate-next-tab":"激活右側標籤",- "activate-previous-tab":"激活左側標籤",- "open-new-window":"打開新空白窗口",- "toggle-tray":"顯示/隱藏應用程式的系統托盤",- "first-tab":"激活列表中的第一個標籤",- "second-tab":"激活列表中的第二個標籤",- "third-tab":"激活列表中的第三個標籤",- "fourth-tab":"激活列表中的第四個標籤",- "fifth-tab":"激活列表中的第五個標籤",- "sixth-tab":"激活列表中的第六個標籤",- "seventh-tab":"激活列表中的第七個標籤",- "eight-tab":"激活列表中的第八個標籤",- "ninth-tab":"激活列表中的第九個標籤",- "last-tab":"激活列表中的最後一個標籤",- "dialogs":"對話框",- "show-note-source":"顯示筆記源對話框",- "show-options":"顯示選項對話框",- "show-revisions":"顯示筆記歷史對話框",- "show-recent-changes":"顯示最近更改對話框",- "show-sql-console":"顯示SQL控制台對話框",- "show-backend-log":"顯示後端日誌對話框",- "text-note-operations":"文本筆記操作",- "add-link-to-text":"打開對話框以將鏈接添加到文本",- "follow-link-under-cursor":"跟隨遊標下的鏈接",- "insert-date-and-time-to-text":"將當前日期和時間插入文本",- "paste-markdown-into-text":"將剪貼簿中的Markdown粘貼到文本筆記中",- "cut-into-note":"從當前筆記中剪下選擇並新增包含選定文本的子筆記",- "add-include-note-to-text":"打開對話框以包含筆記",- "edit-readonly-note":"編輯唯讀筆記",- "attributes-labels-and-relations":"屬性(標籤和關係)",- "add-new-label":"新增新標籤",- "create-new-relation":"新增新關係",- "ribbon-tabs":"功能區標籤",- "toggle-basic-properties":"切換基本屬性",- "toggle-file-properties":"切換文件屬性",- "toggle-image-properties":"切換圖像屬性",- "toggle-owned-attributes":"切換擁有的屬性",- "toggle-inherited-attributes":"切換繼承的屬性",- "toggle-promoted-attributes":"切換提升的屬性",- "toggle-link-map":"切換鏈接地圖",- "toggle-note-info":"切換筆記資訊",- "toggle-note-paths":"切換筆記路徑",- "toggle-similar-notes":"切換相似筆記",- "other":"其他",- "toggle-right-pane":"切換右側面板的顯示,包括目錄和高亮",- "print-active-note":"打印活動筆記",- "open-note-externally":"以預設應用程式打開筆記文件",- "render-active-note":"渲染(重新渲染)活動筆記",- "run-active-note":"運行主動的JavaScript(前端/後端)代碼筆記",- "toggle-note-hoisting":"切換活動筆記的提升",- "unhoist":"從任何地方取消提升",- "reload-frontend-app":"重新加載前端應用",- "open-dev-tools":"打開開發工具",- "toggle-left-note-tree-panel":"切換左側(筆記樹)面板",- "toggle-full-screen":"切換全熒幕",- "zoom-out":"縮小",- "zoom-in":"放大",- "note-navigation":"筆記導航",- "reset-zoom-level":"重置縮放級別",- "copy-without-formatting":"複製不帶格式的選定文本",- "force-save-revision":"強制新增/保存當前筆記的歷史版本",- "show-help":"顯示內置說明/備忘單",- "toggle-book-properties":"切換書籍屬性"- },- "login":{- "title":"登入",- "heading":"Trilium登入",- "incorrect-password":"密碼不正確。請再試一次。",- "password":"密碼",- "remember-me":"記住我",- "button":"登入"- },- "set_password":{- "title":"設定密碼",- "heading":"設定密碼",- "description":"在您可以從Web開始使用Trilium之前,您需要先設定一個密碼。然後您將使用此密碼登錄。",- "password":"密碼",- "password-confirmation":"密碼確認",- "button":"設定密碼"- },- "javascript-required":"Trilium需要啓用JavaScript。",- "setup":{- "heading":"TriliumNext筆記設定",- "new-document":"我是新用戶,我想為我的筆記新增一個新的Trilium檔案",- "sync-from-desktop":"我已經有一個桌面實例,我想設定與它的同步",- "sync-from-server":"我已經有一個伺服器實例,我想設定與它的同步",- "next":"下一步",- "init-in-progress":"檔案初始化進行中",- "redirecting":"您將很快被重定向到應用程式。",- "title":"設定"- },- "setup_sync-from-desktop":{- "heading":"從桌面同步",- "description":"此設定需要從桌面實例啓動:",- "step1":"打開您的TriliumNext筆記桌面實例。",- "step2":"從Trilium菜單中,點擊選項。",- "step3":"點擊同步。",- "step4":"將伺服器實例地址更改為:{{- host}}並點擊保存。",- "step5":"點擊「測試同步」按鈕以驗證連接是否成功。",- "step6":"完成這些步驟後,點擊{{- link}}。",- "step6-here":"這裡"- },- "setup_sync-from-server":{- "heading":"從伺服器同步",- "instructions":"請在下面輸入Trilium伺服器地址和密碼。這將從伺服器下載整個Trilium數據庫檔案並設定同步。因應數據庫大小和您的連接速度,這可能需要一段時間。",- "server-host":"Trilium伺服器地址",- "server-host-placeholder":"https://<主機名稱>:<端口>",- "proxy-server":"代理伺服器(可選)",- "proxy-server-placeholder":"https://<主機名稱>:<端口>",- "note":"注意:",- "proxy-instruction":"如果您將代理設定留空,將使用系統代理(僅適用於桌面程式)",- "password":"密碼",- "password-placeholder":"密碼",- "back":"返回",- "finish-setup":"完成設定"- },- "setup_sync-in-progress":{- "heading":"同步中",- "successful":"同步已正確設定。初始同步完成可能需要一些時間。完成後,您將被重定向到登入頁面。",- "outstanding-items":"未完成的同步項目:",- "outstanding-items-default":"無"- },- "share_404":{- "title":"未找到",- "heading":"未找到"- },- "share_page":{- "parent":"上級目錄:",- "clipped-from":"此筆記最初剪下自 {{- url}}",- "child-notes":"子筆記:",- "no-content":"此筆記沒有內容。"- },- "weekdays":{- "monday":"週一",- "tuesday":"週二",- "wednesday":"週三",- "thursday":"週四",- "friday":"週五",- "saturday":"週六",- "sunday":"週日"- },- "months":{- "january":"一月",- "february":"二月",- "march":"三月",- "april":"四月",- "may":"五月",- "june":"六月",- "july":"七月",- "august":"八月",- "september":"九月",- "october":"十月",- "november":"十一月",- "december":"十二月"- },- "special_notes":{- "search_prefix":"搜尋:"- },- "code_block":{- "theme_none":"無格式高亮",- "theme_group_light":"淺色主題",- "theme_group_dark":"深色主題"- },- "test_sync":{- "not-configured":"並未設定同步伺服器主機,請先設定同步",- "successful":"成功與同步伺服器握手,現在開始同步"- }- }+ "keyboard_actions": {+ "open-jump-to-note-dialog": "打開「跳轉到筆記」對話框",+ "search-in-subtree": "在當前筆記的子樹中搜索筆記",+ "expand-subtree": "展開當前筆記的子樹",+ "collapse-tree": "折疊完整的筆記樹",+ "collapse-subtree": "折疊當前筆記的子樹",+ "sort-child-notes": "排序子筆記",+ "creating-and-moving-notes": "新增和移動筆記",+ "create-note-into-inbox": "在收件匣(如果有定義的話)或日記中新增筆記",+ "delete-note": "刪除筆記",+ "move-note-up": "上移筆記",+ "move-note-down": "下移筆記",+ "move-note-up-in-hierarchy": "上移筆記層級",+ "move-note-down-in-hierarchy": "下移筆記層級",+ "edit-note-title": "從筆記樹跳轉到筆記詳情並編輯標題",+ "edit-branch-prefix": "顯示編輯分支前綴對話框",+ "note-clipboard": "筆記剪貼簿",+ "copy-notes-to-clipboard": "複製選定的筆記到剪貼簿",+ "paste-notes-from-clipboard": "從剪貼簿粘貼筆記到活動筆記中",+ "cut-notes-to-clipboard": "剪下選定的筆記到剪貼簿",+ "select-all-notes-in-parent": "選擇當前筆記級別的所有筆記",+ "add-note-above-to-the-selection": "將上方筆記添加到選擇中",+ "add-note-below-to-selection": "將下方筆記添加到選擇中",+ "duplicate-subtree": "複製子樹",+ "tabs-and-windows": "標籤和窗口",+ "open-new-tab": "打開新標籤",+ "close-active-tab": "關閉活動標籤",+ "reopen-last-tab": "重新打開最後關閉的標籤",+ "activate-next-tab": "激活右側標籤",+ "activate-previous-tab": "激活左側標籤",+ "open-new-window": "打開新空白窗口",+ "toggle-tray": "顯示/隱藏應用程式的系統托盤",+ "first-tab": "激活列表中的第一個標籤",+ "second-tab": "激活列表中的第二個標籤",+ "third-tab": "激活列表中的第三個標籤",+ "fourth-tab": "激活列表中的第四個標籤",+ "fifth-tab": "激活列表中的第五個標籤",+ "sixth-tab": "激活列表中的第六個標籤",+ "seventh-tab": "激活列表中的第七個標籤",+ "eight-tab": "激活列表中的第八個標籤",+ "ninth-tab": "激活列表中的第九個標籤",+ "last-tab": "激活列表中的最後一個標籤",+ "dialogs": "對話框",+ "show-note-source": "顯示筆記源對話框",+ "show-options": "顯示選項對話框",+ "show-revisions": "顯示筆記歷史對話框",+ "show-recent-changes": "顯示最近更改對話框",+ "show-sql-console": "顯示SQL控制台對話框",+ "show-backend-log": "顯示後端日誌對話框",+ "text-note-operations": "文本筆記操作",+ "add-link-to-text": "打開對話框以將鏈接添加到文本",+ "follow-link-under-cursor": "跟隨遊標下的鏈接",+ "insert-date-and-time-to-text": "將當前日期和時間插入文本",+ "paste-markdown-into-text": "將剪貼簿中的Markdown粘貼到文本筆記中",+ "cut-into-note": "從當前筆記中剪下選擇並新增包含選定文本的子筆記",+ "add-include-note-to-text": "打開對話框以包含筆記",+ "edit-readonly-note": "編輯唯讀筆記",+ "attributes-labels-and-relations": "屬性(標籤和關係)",+ "add-new-label": "新增新標籤",+ "create-new-relation": "新增新關係",+ "ribbon-tabs": "功能區標籤",+ "toggle-basic-properties": "切換基本屬性",+ "toggle-file-properties": "切換文件屬性",+ "toggle-image-properties": "切換圖像屬性",+ "toggle-owned-attributes": "切換擁有的屬性",+ "toggle-inherited-attributes": "切換繼承的屬性",+ "toggle-promoted-attributes": "切換提升的屬性",+ "toggle-link-map": "切換鏈接地圖",+ "toggle-note-info": "切換筆記資訊",+ "toggle-note-paths": "切換筆記路徑",+ "toggle-similar-notes": "切換相似筆記",+ "other": "其他",+ "toggle-right-pane": "切換右側面板的顯示,包括目錄和高亮",+ "print-active-note": "打印活動筆記",+ "open-note-externally": "以預設應用程式打開筆記文件",+ "render-active-note": "渲染(重新渲染)活動筆記",+ "run-active-note": "運行主動的JavaScript(前端/後端)代碼筆記",+ "toggle-note-hoisting": "切換活動筆記的提升",+ "unhoist": "從任何地方取消提升",+ "reload-frontend-app": "重新加載前端應用",+ "open-dev-tools": "打開開發工具",+ "toggle-left-note-tree-panel": "切換左側(筆記樹)面板",+ "toggle-full-screen": "切換全熒幕",+ "zoom-out": "縮小",+ "zoom-in": "放大",+ "note-navigation": "筆記導航",+ "reset-zoom-level": "重置縮放級別",+ "copy-without-formatting": "複製不帶格式的選定文本",+ "force-save-revision": "強制新增/保存當前筆記的歷史版本",+ "show-help": "顯示內置說明/備忘單",+ "toggle-book-properties": "切換書籍屬性"+ },+ "login": {+ "title": "登入",+ "heading": "Trilium登入",+ "incorrect-password": "密碼不正確。請再試一次。",+ "password": "密碼",+ "remember-me": "記住我",+ "button": "登入"+ },+ "set_password": {+ "title": "設定密碼",+ "heading": "設定密碼",+ "description": "在您可以從Web開始使用Trilium之前,您需要先設定一個密碼。然後您將使用此密碼登錄。",+ "password": "密碼",+ "password-confirmation": "密碼確認",+ "button": "設定密碼"+ },+ "javascript-required": "Trilium需要啓用JavaScript。",+ "setup": {+ "heading": "TriliumNext筆記設定",+ "new-document": "我是新用戶,我想為我的筆記新增一個新的Trilium檔案",+ "sync-from-desktop": "我已經有一個桌面實例,我想設定與它的同步",+ "sync-from-server": "我已經有一個伺服器實例,我想設定與它的同步",+ "next": "下一步",+ "init-in-progress": "檔案初始化進行中",+ "redirecting": "您將很快被重定向到應用程式。",+ "title": "設定"+ },+ "setup_sync-from-desktop": {+ "heading": "從桌面同步",+ "description": "此設定需要從桌面實例啓動:",+ "step1": "打開您的TriliumNext筆記桌面實例。",+ "step2": "從Trilium菜單中,點擊選項。",+ "step3": "點擊同步。",+ "step4": "將伺服器實例地址更改為:{{- host}}並點擊保存。",+ "step5": "點擊「測試同步」按鈕以驗證連接是否成功。",+ "step6": "完成這些步驟後,點擊{{- link}}。",+ "step6-here": "這裡"+ },+ "setup_sync-from-server": {+ "heading": "從伺服器同步",+ "instructions": "請在下面輸入Trilium伺服器地址和密碼。這將從伺服器下載整個Trilium數據庫檔案並設定同步。因應數據庫大小和您的連接速度,這可能需要一段時間。",+ "server-host": "Trilium伺服器地址",+ "server-host-placeholder": "https://<主機名稱>:<端口>",+ "proxy-server": "代理伺服器(可選)",+ "proxy-server-placeholder": "https://<主機名稱>:<端口>",+ "note": "注意:",+ "proxy-instruction": "如果您將代理設定留空,將使用系統代理(僅適用於桌面程式)",+ "password": "密碼",+ "password-placeholder": "密碼",+ "back": "返回",+ "finish-setup": "完成設定"+ },+ "setup_sync-in-progress": {+ "heading": "同步中",+ "successful": "同步已正確設定。初始同步完成可能需要一些時間。完成後,您將被重定向到登入頁面。",+ "outstanding-items": "未完成的同步項目:",+ "outstanding-items-default": "無"+ },+ "share_404": {+ "title": "未找到",+ "heading": "未找到"+ },+ "share_page": {+ "parent": "上級目錄:",+ "clipped-from": "此筆記最初剪下自 {{- url}}",+ "child-notes": "子筆記:",+ "no-content": "此筆記沒有內容。"+ },+ "weekdays": {+ "monday": "週一",+ "tuesday": "週二",+ "wednesday": "週三",+ "thursday": "週四",+ "friday": "週五",+ "saturday": "週六",+ "sunday": "週日"+ },+ "months": {+ "january": "一月",+ "february": "二月",+ "march": "三月",+ "april": "四月",+ "may": "五月",+ "june": "六月",+ "july": "七月",+ "august": "八月",+ "september": "九月",+ "october": "十月",+ "november": "十一月",+ "december": "十二月"+ },+ "special_notes": {+ "search_prefix": "搜尋:"+ },+ "code_block": {+ "theme_none": "無格式高亮",+ "theme_group_light": "淺色主題",+ "theme_group_dark": "深色主題"+ },+ "test_sync": {+ "not-configured": "並未設定同步伺服器主機,請先設定同步",+ "successful": "成功與同步伺服器握手,現在開始同步"+ }+}diff --git a/tsconfig.json b/tsconfig.jsonindex d1c25dd309..03f9119c9e 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -1,32 +1,19 @@{- "compilerOptions": {- "module": "NodeNext",- "declaration": false,- "sourceMap": true,- "outDir": "./build",- "strict": true,- "noImplicitAny": true,- "resolveJsonModule": true,- "allowJs": true,- "lib": [- "ES2022"- ],- "downlevelIteration": true,- "skipLibCheck": true,- "esModuleInterop": true,- },- "include": [- "./src/**/*.js",- "./src/**/*.ts",- "./*.ts",- "./spec/**/*.ts"- ],- "exclude": [- "./node_modules/**/*",- "./spec-es6/**/*.ts"- ],- "files": [- "src/types.d.ts",- "src/public/app/types.d.ts"- ]-}\ No newline at end of file+ "compilerOptions": {+ "module": "NodeNext",+ "declaration": false,+ "sourceMap": true,+ "outDir": "./build",+ "strict": true,+ "noImplicitAny": true,+ "resolveJsonModule": true,+ "allowJs": true,+ "lib": ["ES2022"],+ "downlevelIteration": true,+ "skipLibCheck": true,+ "esModuleInterop": true+ },+ "include": ["./src/**/*.js", "./src/**/*.ts", "./*.ts", "./spec/**/*.ts"],+ "exclude": ["./node_modules/**/*", "./spec-es6/**/*.ts"],+ "files": ["src/types.d.ts", "src/public/app/types.d.ts"]+}diff --git a/tsconfig.webpack.json b/tsconfig.webpack.jsonindex 564e9c441a..157eef76d7 100644--- a/tsconfig.webpack.json+++ b/tsconfig.webpack.json@@ -1,24 +1,18 @@{- "compilerOptions": {- "module": "NodeNext",- "declaration": false,- "sourceMap": true,- "outDir": "./build",- "strict": true,- "noImplicitAny": true,- "resolveJsonModule": true,- "lib": [- "ES2022"- ],- "downlevelIteration": true,- "skipLibCheck": true,- "esModuleInterop": true,- "allowJs": true- },- "include": [- "./src/public/app/**/*",- ],- "files": [- "./src/public/app/types.d.ts"- ]-}\ No newline at end of file+ "compilerOptions": {+ "module": "NodeNext",+ "declaration": false,+ "sourceMap": true,+ "outDir": "./build",+ "strict": true,+ "noImplicitAny": true,+ "resolveJsonModule": true,+ "lib": ["ES2022"],+ "downlevelIteration": true,+ "skipLibCheck": true,+ "esModuleInterop": true,+ "allowJs": true+ },+ "include": ["./src/public/app/**/*"],+ "files": ["./src/public/app/types.d.ts"]+}diff --git a/typedoc.json b/typedoc.jsonindex 4ecad5a1fb..2696403017 100644--- a/typedoc.json+++ b/typedoc.json@@ -5,4 +5,4 @@"path": "./docs/backend_api"}]-}\ No newline at end of file+}diff --git a/webpack.config.ts b/webpack.config.tsindex 9470d7a79b..b8c787118d 100644--- a/webpack.config.ts+++ b/webpack.config.ts@@ -4,39 +4,41 @@ import assetPath from "./src/services/asset_path.js";const rootDir = path.dirname(fileURLToPath(import.meta.url));export default {- mode: 'production',+ mode: "production",entry: {- setup: './src/public/app/setup.js',- mobile: './src/public/app/mobile.js',- desktop: './src/public/app/desktop.js',+ setup: "./src/public/app/setup.js",+ mobile: "./src/public/app/mobile.js",+ desktop: "./src/public/app/desktop.js"},output: {publicPath: `${assetPath}/app-dist/`,- path: path.resolve(rootDir, 'src/public/app-dist'),- filename: '[name].js',+ path: path.resolve(rootDir, "src/public/app-dist"),+ filename: "[name].js"},module: {rules: [{- test: /\.ts$/,- use: [{- loader: 'ts-loader',- options: {- configFile: path.join(rootDir, "tsconfig.webpack.json")- }- }],- exclude: /node_modules/,- },+ test: /\.ts$/,+ use: [+ {+ loader: "ts-loader",+ options: {+ configFile: path.join(rootDir, "tsconfig.webpack.json")+ }+ }+ ],+ exclude: /node_modules/+ }]},resolve: {- extensions: ['.ts', '.js'],+ extensions: [".ts", ".js"],extensionAlias: {".js": [".js", ".ts"],".cjs": [".cjs", ".cts"],".mjs": [".mjs", ".mts"]}},- devtool: 'source-map',- target: 'electron-renderer',+ devtool: "source-map",+ target: "electron-renderer"};