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: add a toggle switch to enable/disable items
Adorian Doranf179a051dc69
diff --git a/apps/client/src/services/content_manager.spec.ts b/apps/client/src/services/content_manager.spec.tsindex cef5bbd5c1..e648cef082 100644--- a/apps/client/src/services/content_manager.spec.ts+++ b/apps/client/src/services/content_manager.spec.ts@@ -1,7 +1,19 @@import { describe, expect, it } from "vitest";import { buildNote } from "../test/easy-froca";-import { buildCategoryQuery, CONTENT_CATEGORIES, isUserContent } from "./content_manager";+import {+ buildCategoryQuery,+ CONTENT_CATEGORIES,+ isCategoryEnabled,+ isUserContent,+ parseFilterTriggers+} from "./content_manager";++function categoryById(id: string) {+ const category = CONTENT_CATEGORIES.find((candidate) => candidate.id === id);+ if (!category) throw new Error(`Unknown category '${id}'`);+ return category;+}describe("buildCategoryQuery", () => {it("orders alphabetically by title", () => {@@ -61,6 +73,59 @@ describe("CONTENT_CATEGORIES", () => {});});+describe("parseFilterTriggers", () => {+ it("reads attribute names off a filter, ignoring values and the disabled: spelling", () => {+ expect(parseFilterTriggers("#run = hourly OR #disabled:run = hourly")).toEqual([+ { type: "label", name: "run" }+ ]);+ });++ it("distinguishes labels from relations", () => {+ expect(parseFilterTriggers("~renderNote OR ~disabled:renderNote OR #webViewSrc")).toEqual([+ { type: "relation", name: "renderNote" },+ { type: "label", name: "webViewSrc" }+ ]);+ });++ it("finds the triggers of every real category", () => {+ expect(parseFilterTriggers(categoryById("snippets").filter)).toEqual([+ { type: "label", name: "snippet" },+ { type: "label", name: "textSnippet" }+ ]);+ expect(parseFilterTriggers(categoryById("backendScripts").filter)).toEqual([+ { type: "label", name: "run" }+ ]);+ });+});++describe("isCategoryEnabled", () => {+ const scripts = categoryById("backendScripts");+ const widgets = categoryById("widgets");++ it("reports an enabled trigger as on and a disabled one as off", () => {+ expect(isCategoryEnabled(buildNote({ title: "Live", "#run": "hourly" }), scripts)).toBe(true);+ expect(isCategoryEnabled(buildNote({ title: "Paused", "#disabled:run": "hourly" }), scripts)).toBe(false);+ });++ it("only considers the triggers of the category asked about", () => {+ // The note is a live widget but a disabled backend script; each row answers for itself.+ const note = buildNote({ title: "Both", "#widget": "", "#disabled:run": "daily" });++ expect(isCategoryEnabled(note, widgets)).toBe(true);+ expect(isCategoryEnabled(note, scripts)).toBe(false);+ });++ it("is off for a note carrying none of the category's triggers", () => {+ expect(isCategoryEnabled(buildNote({ title: "Plain" }), scripts)).toBe(false);+ });++ it("counts the note as on while any one of its triggers is still live", () => {+ const note = buildNote({ title: "Mixed", "#run": "daily", "#disabled:customRequestHandler": "api/x" });++ expect(isCategoryEnabled(note, scripts)).toBe(true);+ });+});+describe("isUserContent", () => {it("accepts notes the user created", () => {expect(isUserContent(buildNote({ id: "abc123", title: "My script" }))).toBe(true);diff --git a/apps/client/src/services/content_manager.ts b/apps/client/src/services/content_manager.tsindex c335d0bb77..7cfdba037d 100644--- a/apps/client/src/services/content_manager.ts+++ b/apps/client/src/services/content_manager.ts@@ -1,6 +1,13 @@import type FNote from "../entities/fnote";+import attributes from "./attributes";import search from "./search";+/** An attribute that makes a note part of a category. */+export interface ContentTrigger {+ type: "label" | "relation";+ name: string;+}+/** How the notes within each category are ordered. */export type ContentSortOrder = "title" | "dateCreated";@@ -93,3 +100,72 @@ export function buildCategoryQuery(filter: string, sortOrder: ContentSortOrder)export function isUserContent(note: FNote) {return !note.noteId.startsWith("_");}++/** Whether the note is currently active in this category, i.e. at least one trigger is not disabled. */+export function isCategoryEnabled(note: FNote, category: ContentCategory) {+ return getCategoryTriggers(note, category).some(({ enabled }) => enabled);+}++/**+ * Enables or disables the note's participation in this category, and only this one.+ *+ * A note can be active content in several ways at once — a script that is also a template — so the+ * triggers of other categories are deliberately left alone.+ */+export async function setCategoryEnabled(note: FNote, category: ContentCategory, enabled: boolean) {+ for (const { type, name } of getCategoryTriggers(note, category)) {+ await attributes.toggleDangerousAttribute(note, type, name, enabled);+ }+}++/**+ * The triggers of this category that the note actually owns, deduplicated by type and name, with+ * `disabled:` stripped so the name is the one to write back.+ */+function getCategoryTriggers(note: FNote, category: ContentCategory) {+ const wanted = new Set(parseFilterTriggers(category.filter).map(toTriggerKey));+ const found = new Map<string, ContentTrigger & { enabled: boolean }>();++ for (const attribute of note.getOwnedAttributes()) {+ if (attribute.type !== "label" && attribute.type !== "relation") {+ continue;+ }++ const trigger: ContentTrigger = {+ type: attribute.type,+ name: attributes.getNameWithoutDangerousPrefix(attribute.name)+ };+ const key = toTriggerKey(trigger);++ if (!wanted.has(key)) {+ continue;+ }++ // An enabled spelling wins: the note counts as active if any of its triggers is live.+ const enabled = !attribute.name.startsWith(DISABLED_PREFIX);+ found.set(key, { ...trigger, enabled: enabled || (found.get(key)?.enabled ?? false) });+ }++ return [ ...found.values() ];+}++/** Reads the attribute names out of a category's search query, so it stays the single source of truth. */+export function parseFilterTriggers(filter: string): ContentTrigger[] {+ const triggers = new Map<string, ContentTrigger>();++ for (const match of filter.match(/[#~][\w:]+/g) ?? []) {+ const trigger: ContentTrigger = {+ type: match.startsWith("#") ? "label" : "relation",+ name: attributes.getNameWithoutDangerousPrefix(match.slice(1))+ };+ triggers.set(toTriggerKey(trigger), trigger);+ }++ return [ ...triggers.values() ];+}++function toTriggerKey({ type, name }: ContentTrigger) {+ return `${type}-${name.toLowerCase()}`;+}++const DISABLED_PREFIX = "disabled:";diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 930b379407..192dee9a65 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2610,6 +2610,8 @@"category_templates": "Templates","category_snippets": "Snippets","loading": "Retrieving content...",+ "toggle_enable": "Enable",+ "toggle_disable": "Disable","sort_order": "Sort by:","sort_by_name": "Name","sort_by_date_created": "Creation date",diff --git a/apps/client/src/widgets/type_widgets/options/content_manager.tsx b/apps/client/src/widgets/type_widgets/options/content_manager.tsxindex 332aed972c..9f42cc04a5 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager.tsx@@ -8,11 +8,14 @@ import {CONTENT_CATEGORIES,type ContentCategory,type ContentSortOrder,- findCategoryNotes+ findCategoryNotes,+ isCategoryEnabled,+ setCategoryEnabled} from "../../../services/content_manager";import { t } from "../../../services/i18n";import { ListView, type ListViewOptions } from "../../collections/legacy/ListOrGridView";import Button, { ButtonGroup } from "../../react/Button";+import FormToggle from "../../react/FormToggle";import { useTriliumEvent, useTriliumOption } from "../../react/hooks";import NoItems from "../../react/NoItems";import type { TypeWidgetProps } from "../type_widget";@@ -20,6 +23,27 @@ import OptionsPageHeader from "./components/OptionsPageHeader";const NOOP = () => {};+function ContentToggle({ note, category }: { note: FNote, category: ContentCategory }) {+ const [ enabled, setEnabled ] = useState(() => isCategoryEnabled(note, category));++ // Re-sync when the row is reused for another note, or the state changed elsewhere.+ useEffect(() => setEnabled(isCategoryEnabled(note, category)), [ note, category ]);++ return (+ <FormToggle+ switchOnName="" switchOffName=""+ currentValue={enabled}+ switchOnTooltip={t("content_manager.toggle_enable")}+ switchOffTooltip={t("content_manager.toggle_disable")}+ onChange={(willEnable) => {+ // Applied straight away so the switch responds before the lists are rebuilt.+ setEnabled(willEnable);+ void setCategoryEnabled(note, category, willEnable);+ }}+ />+ );+}+const LIST_OPTIONS: ListViewOptions = {// These notes are scattered across the tree rather than being children of this page, so they are// listed flat with their real location shown underneath, the way search results are.@@ -28,10 +52,7 @@ const LIST_OPTIONS: ListViewOptions = {// Collapsed by default: the list is meant to be scanned, and expanding reveals the note's own// preview rather than a subtree.expandDepth: 0,- pageSize: 50,- // Deliberately empty for now: it suppresses the note's attributes and reserves the spot for the- // enable/disable toggle and status badges.- renderItemActions: () => null+ pageSize: 50};export default function ContentManagerSettings({ note }: TypeWidgetProps) {@@ -82,7 +103,11 @@ function CategoryList({ pageNote, categories }: { pageNote: FNote, categories: CsaveConfig={NOOP}media="screen"onReady={NOOP}- listOptions={{ ...LIST_OPTIONS, title: t(category.titleKey) }}+ listOptions={{+ ...LIST_OPTIONS,+ title: t(category.titleKey),+ renderItemActions: (note) => <ContentToggle note={note} category={category} />+ }}/>))}</>diff --git a/packages/commons/src/lib/builtin_attributes.ts b/packages/commons/src/lib/builtin_attributes.tsindex cd589f0693..3b89a57901 100644--- a/packages/commons/src/lib/builtin_attributes.ts+++ b/packages/commons/src/lib/builtin_attributes.ts@@ -67,6 +67,8 @@ export default [{ type: "label", name: "hideRelations" },{ type: "label", name: "titleTemplate", isDangerous: true },{ type: "label", name: "template" },+ { type: "label", name: "snippet" },+ { type: "label", name: "textSnippet" },{ type: "label", name: "toc" },{ type: "label", name: "color" },{ type: "label", name: "keepCurrentHoisting" },