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
client/content manager: create the foundation
Adorian Doran0436e262437a
diff --git a/apps/client/src/services/content_manager.spec.ts b/apps/client/src/services/content_manager.spec.tsnew file mode 100644index 0000000000..cef5bbd5c1--- /dev/null+++ b/apps/client/src/services/content_manager.spec.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from "vitest";++import { buildNote } from "../test/easy-froca";+import { buildCategoryQuery, CONTENT_CATEGORIES, isUserContent } from "./content_manager";++describe("buildCategoryQuery", () => {+ it("orders alphabetically by title", () => {+ expect(buildCategoryQuery("#appCss", "title")).toBe("#appCss orderBy note.title");+ });++ it("orders newest first by creation date", () => {+ expect(buildCategoryQuery("#appCss", "dateCreated")).toBe("#appCss orderBy note.dateCreated desc");+ });++ it("keeps the ordering clause at the top level of an OR chain", () => {+ // `orderBy` is rejected by the parser unless it sits on the top expression level, so the+ // filters must not be wrapped in parentheses.+ const query = buildCategoryQuery("#widget OR #disabled:widget", "title");++ expect(query).toBe("#widget OR #disabled:widget orderBy note.title");+ expect(query).not.toContain("(");+ });+});++describe("CONTENT_CATEGORIES", () => {+ it("asks for the disabled counterpart of every attribute it filters on", () => {+ for (const { id, filter } of CONTENT_CATEGORIES) {+ const attributes = filter.match(/[#~](?!disabled:)[\w:]+/g) ?? [];++ expect(attributes.length, `${id} filters on at least one attribute`).toBeGreaterThan(0);++ for (const attribute of attributes) {+ const sigil = attribute[0];+ const disabled = `${sigil}disabled:${attribute.slice(1)}`;++ expect(filter, `${id} also matches ${disabled}`).toContain(disabled);+ }+ }+ });++ it("uses unique ids and distinct filters", () => {+ const ids = CONTENT_CATEGORIES.map((category) => category.id);+ const filters = CONTENT_CATEGORIES.map((category) => category.filter);++ expect(new Set(ids).size).toBe(ids.length);+ expect(new Set(filters).size).toBe(filters.length);+ });++ it("covers the categories the manager is expected to list", () => {+ expect(CONTENT_CATEGORIES.map((category) => category.id)).toEqual([+ "backendScripts",+ "frontendScripts",+ "widgets",+ "renderNotes",+ "themes",+ "customCss",+ "iconPacks",+ "templates",+ "snippets"+ ]);+ });+});++describe("isUserContent", () => {+ it("accepts notes the user created", () => {+ expect(isUserContent(buildNote({ id: "abc123", title: "My script" }))).toBe(true);+ });++ it("rejects built-in notes from the hidden subtree", () => {+ // Their attributes are re-enforced on every startup, so changes made here would be reverted.+ expect(isUserContent(buildNote({ id: "_template_text_snippet", title: "Text Snippet" }))).toBe(false);+ expect(isUserContent(buildNote({ id: "_optionsAppearance", title: "Appearance" }))).toBe(false);+ });+});diff --git a/apps/client/src/services/content_manager.ts b/apps/client/src/services/content_manager.tsnew file mode 100644index 0000000000..c335d0bb77--- /dev/null+++ b/apps/client/src/services/content_manager.ts@@ -0,0 +1,95 @@+import type FNote from "../entities/fnote";+import search from "./search";++/** How the notes within each category are ordered. */+export type ContentSortOrder = "title" | "dateCreated";++export interface ContentCategory {+ id: string;+ /** Translation key for the category heading. */+ titleKey: string;+ /**+ * Search query selecting the notes of this category.+ *+ * Each query has to ask for the `disabled:` spelling of its attributes as well: disabling active+ * content renames its attribute, which is precisely what makes every collector stop seeing it —+ * so the Content Manager is the one place that has to look for both.+ */+ filter: string;+}++export const CONTENT_CATEGORIES: ContentCategory[] = [+ {+ id: "backendScripts",+ titleKey: "content_manager.category_backend_scripts",+ filter: "#run = backendStartup OR #run = hourly OR #run = daily"+ + " OR #disabled:run = backendStartup OR #disabled:run = hourly OR #disabled:run = daily"+ },+ {+ id: "frontendScripts",+ titleKey: "content_manager.category_frontend_scripts",+ filter: "#run = frontendStartup OR #run = mobileStartup"+ + " OR #disabled:run = frontendStartup OR #disabled:run = mobileStartup"+ },+ {+ id: "widgets",+ titleKey: "content_manager.category_widgets",+ filter: "#widget OR #disabled:widget"+ },+ {+ id: "renderNotes",+ titleKey: "content_manager.category_render_notes",+ filter: "~renderNote OR ~disabled:renderNote"+ },+ {+ id: "themes",+ titleKey: "content_manager.category_themes",+ filter: "#appTheme OR #disabled:appTheme"+ },+ {+ id: "customCss",+ titleKey: "content_manager.category_custom_css",+ filter: "#appCss OR #disabled:appCss"+ },+ {+ id: "iconPacks",+ titleKey: "content_manager.category_icon_packs",+ filter: "#iconPack OR #disabled:iconPack"+ },+ {+ id: "templates",+ titleKey: "content_manager.category_templates",+ filter: "#template OR #disabled:template"+ },+ {+ id: "snippets",+ titleKey: "content_manager.category_snippets",+ filter: "#snippet OR #textSnippet OR #disabled:snippet OR #disabled:textSnippet"+ }+];++/** Runs one category's query and returns the user-made notes it matches, already sorted. */+export async function findCategoryNotes(category: ContentCategory, sortOrder: ContentSortOrder) {+ const notes = await search.searchForNotes(buildCategoryQuery(category.filter, sortOrder));++ return notes.filter((note) => isUserContent(note));+}++/** Appends the ordering clause, which the search engine applies server-side. */+export function buildCategoryQuery(filter: string, sortOrder: ContentSortOrder) {+ // Newest first reads better for dates, while titles are most useful alphabetically.+ const orderBy = sortOrder === "dateCreated" ? "note.dateCreated desc" : "note.title";++ return `${filter} orderBy ${orderBy}`;+}++/**+ * Whether a note is the user's own active content rather than something Trilium ships.+ *+ * Built-in notes live in the hidden subtree under reserved `_`-prefixed IDs. They are excluded+ * because the user did not create them and cannot meaningfully manage them: `checkHiddenSubtree()`+ * enforces their attributes on every startup, so any change made here would be reverted.+ */+export function isUserContent(note: FNote) {+ return !note.noteId.startsWith("_");+}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 3a05cbfd37..f8cf3222f4 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2599,6 +2599,22 @@"content_widget": {"unknown_widget": "Unknown widget for \"{{id}}\"."},+ "content_manager": {+ "category_backend_scripts": "Backend Scripts",+ "category_frontend_scripts": "Front-end Scripts",+ "category_widgets": "Custom Widgets",+ "category_render_notes": "Render Notes",+ "category_themes": "Custom Themes",+ "category_custom_css": "Custom CSS",+ "category_icon_packs": "Icon Packs",+ "category_templates": "Templates",+ "category_snippets": "Snippets",+ "sort_order": "Sort by",+ "sort_by_name": "Name",+ "sort_by_date_created": "Creation date",+ "no_items": "No active content found.",+ "no_items_hint": "Scripts, themes, templates and snippets you create will be listed here."+ },"note_language": {"not_set": "No language set","configure-languages": "Configure languages...",diff --git a/apps/client/src/widgets/type_widgets/ContentWidget.tsx b/apps/client/src/widgets/type_widgets/ContentWidget.tsxindex 4ff5992a62..3329a5ad09 100644--- a/apps/client/src/widgets/type_widgets/ContentWidget.tsx+++ b/apps/client/src/widgets/type_widgets/ContentWidget.tsx@@ -4,6 +4,7 @@ import AppearanceSettings from "./options/appearance";import ShortcutSettings from "./options/shortcuts";import TextNoteSettings from "./options/text_notes";import CodeNoteSettings from "./options/code_notes";+import ContentManagerSettings from "./options/content_manager";import MediaSettings from "./options/media";import SpellcheckSettings from "./options/spellcheck";import PasswordSettings from "./options/password";@@ -20,13 +21,14 @@ import "./ContentWidget.css";import { t } from "../../services/i18n";import BackendLog from "./code/BackendLog";-export type OptionPages = "_optionsAppearance" | "_optionsShortcuts" | "_optionsTextNotes" | "_optionsCodeNotes" | "_optionsMedia" | "_optionsSpellcheck" | "_optionsPassword" | "_optionsEtapi" | "_optionsBackup" | "_optionsSync" | "_optionsDesktop" | "_optionsOther" | "_optionsLocalization" | "_optionsSecurity" | "_optionsAdvanced" | "_optionsLlm";+export type OptionPages = "_optionsAppearance" | "_optionsShortcuts" | "_optionsTextNotes" | "_optionsCodeNotes" | "_optionsContentManager" | "_optionsMedia" | "_optionsSpellcheck" | "_optionsPassword" | "_optionsEtapi" | "_optionsBackup" | "_optionsSync" | "_optionsDesktop" | "_optionsOther" | "_optionsLocalization" | "_optionsSecurity" | "_optionsAdvanced" | "_optionsLlm";const CONTENT_WIDGETS: Record<OptionPages | "_backendLog", (props: TypeWidgetProps) => JSX.Element> = {_optionsAppearance: AppearanceSettings,_optionsShortcuts: ShortcutSettings,_optionsTextNotes: TextNoteSettings,_optionsCodeNotes: CodeNoteSettings,+ _optionsContentManager: ContentManagerSettings,_optionsMedia: MediaSettings,_optionsSpellcheck: SpellcheckSettings,_optionsPassword: PasswordSettings,diff --git a/apps/client/src/widgets/type_widgets/options/content_manager.css b/apps/client/src/widgets/type_widgets/options/content_manager.cssnew file mode 100644index 0000000000..4de0e24572--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/content_manager.css@@ -0,0 +1,20 @@+.content-manager-toolbar {+ display: flex;+ align-items: center;+ gap: 0.75em;+ margin-bottom: 1em;+}++.content-manager-toolbar-label {+ white-space: nowrap;+}++.content-manager-items {+ display: flex;+ flex-direction: column;+ gap: 0.35em;+}++.content-manager-item {+ margin: 0;+}diff --git a/apps/client/src/widgets/type_widgets/options/content_manager.tsx b/apps/client/src/widgets/type_widgets/options/content_manager.tsxnew file mode 100644index 0000000000..1f31cf156a--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/content_manager.tsx@@ -0,0 +1,108 @@+import "./content_manager.css";++import clsx from "clsx";+import { useCallback, useEffect, useState } from "preact/hooks";++import type FNote from "../../../entities/fnote";+import {+ CONTENT_CATEGORIES,+ type ContentCategory,+ type ContentSortOrder,+ findCategoryNotes+} from "../../../services/content_manager";+import { t } from "../../../services/i18n";+import Button, { ButtonGroup } from "../../react/Button";+import { useTriliumEvent, useTriliumOption } from "../../react/hooks";+import NoItems from "../../react/NoItems";+import NoteLink from "../../react/NoteLink";+import OptionsPageHeader from "./components/OptionsPageHeader";+import OptionsSection from "./components/OptionsSection";++export default function ContentManagerSettings() {+ const [ sortOrder, setSortOrder ] = useTriliumOption("contentManagerSortOrder");+ const categories = useCategoryNotes(sortOrder as ContentSortOrder);+ const isEmpty = categories.every(({ notes }) => !notes.length);++ return (+ <>+ <OptionsPageHeader />++ <div className="content-manager-toolbar">+ <span className="content-manager-toolbar-label">{t("content_manager.sort_order")}</span>+ <SortOrderSelect currentValue={sortOrder} onChange={(newValue) => void setSortOrder(newValue)} />+ </div>++ {isEmpty+ ? <NoItems icon="bx bx-package" text={t("content_manager.no_items")}>+ <small>{t("content_manager.no_items_hint")}</small>+ </NoItems>+ : categories.map(({ category, notes }) => notes.length > 0 && (+ <OptionsSection key={category.id} title={t(category.titleKey)}>+ <div className="content-manager-items">+ {notes.map((note) => (+ <p key={note.noteId} className="content-manager-item">+ <NoteLink notePath={note.noteId} showNoteIcon showNotePath />+ </p>+ ))}+ </div>+ </OptionsSection>+ ))}+ </>+ );+}++function SortOrderSelect({ currentValue, onChange }: { currentValue: string, onChange: (newValue: string) => void }) {+ return (+ <ButtonGroup size="sm">+ {SORT_ORDERS.map(({ value, label }) => (+ <Button+ key={value}+ text={label}+ size="small"+ className={clsx(currentValue === value && "active")}+ onClick={() => onChange(value)}+ />+ ))}+ </ButtonGroup>+ );+}++const SORT_ORDERS: { value: ContentSortOrder, label: string }[] = [+ { value: "title", label: t("content_manager.sort_by_name") },+ { value: "dateCreated", label: t("content_manager.sort_by_date_created") }+];++interface CategoryNotes {+ category: ContentCategory;+ notes: FNote[];+}++/**+ * Runs every category's query and keeps the results in sync with the note tree.+ *+ * One query per category is more requests than a single combined search would need, but it keeps+ * each category's definition self-contained and the counts stay far too small for the difference to+ * be noticeable.+ */+function useCategoryNotes(sortOrder: ContentSortOrder) {+ const [ categories, setCategories ] = useState<CategoryNotes[]>(() =>+ CONTENT_CATEGORIES.map((category) => ({ category, notes: [] })));++ const refresh = useCallback(async () => {+ setCategories(await Promise.all(CONTENT_CATEGORIES.map(async (category) => ({+ category,+ notes: await findCategoryNotes(category, sortOrder)+ }))));+ }, [ sortOrder ]);++ useEffect(() => { void refresh(); }, [ refresh ]);++ // Creating, deleting or relabelling a note can add or remove entries from any category.+ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {+ if (loadResults.getAttributeRows().length || loadResults.getNoteIds().length) {+ void refresh();+ }+ });++ return categories;+}diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex 79888af14c..8a7b99f434 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -293,6 +293,7 @@"shortcuts-title": "Shortcuts","text-notes": "Text Notes","code-notes-title": "Code Notes",+ "content-manager-title": "Content Manager","images-title": "Media","spellcheck-title": "Spellcheck","desktop-title": "Desktop",diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 1829c9ee00..526888dc7c 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -68,6 +68,7 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActimonospaceFontFamily: FontFamily;spellCheckLanguageCode: string;codeNotesMimeTypes: string;+ contentManagerSortOrder: string;headingStyle: string;highlightsList: string;customSearchEngineName: string;diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex 1274a8a8df..bbf5c44102 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -61,6 +61,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["vimKeymapEnabled","codeLineWrapEnabled","codeNotesMimeTypes",+ "contentManagerSortOrder","spellCheckEnabled","spellCheckLanguageCode","imageMaxWidthHeight",diff --git a/packages/trilium-core/src/services/hidden_subtree.ts b/packages/trilium-core/src/services/hidden_subtree.tsindex de67b7886e..cb12729ff0 100644--- a/packages/trilium-core/src/services/hidden_subtree.ts+++ b/packages/trilium-core/src/services/hidden_subtree.ts@@ -299,6 +299,7 @@ function buildHiddenSubtreeDefinition(helpSubtree: HiddenSubtreeItem[]): HiddenS{ 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: "_optionsContentManager", title: t("hidden-subtree.content-manager-title"), type: "contentWidget", icon: "bx-package" },{ id: "_optionsImages", title: "Images", type: "contentWidget", enforceDeleted: true },{ id: "_optionsMedia", 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", attributes: [{ type: "label", name: "electronOnly" }] },diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex f446cd0ba1..81afa92bd7 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -175,6 +175,7 @@ const defaultOptions: DefaultOption[] = [value: '["text/x-csrc","text/x-c++src","text/x-csharp","text/css","text/x-elixir","text/x-go","text/x-groovy","text/x-haskell","text/html","message/http","text/x-java","text/javascript","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","application/typescript"]',isSynced: true},+ { name: "contentManagerSortOrder", value: "title", isSynced: true },{ name: "leftPaneWidth", value: "25", isSynced: false },{ name: "leftPaneVisible", value: "true", isSynced: false },{ name: "rightPaneWidth", value: "25", isSynced: false },