Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(sort): validate the dialog's label name and share the grammar through commons
BeatLinkf72da41c22b6
diff --git a/apps/client/src/widgets/dialogs/sort_child_notes.css b/apps/client/src/widgets/dialogs/sort_child_notes.cssindex 6839f8a7cb..160c47fb3f 100644--- a/apps/client/src/widgets/dialogs/sort_child_notes.css+++ b/apps/client/src/widgets/dialogs/sort_child_notes.css@@ -3,6 +3,7 @@:where(body:not(.mobile)) & .modal-dialog {width: fit-content;min-width: 440px;+ max-width: 680px;}.modal-body > :not(.sort-criteria),diff --git a/apps/client/src/widgets/dialogs/sort_child_notes.spec.tsx b/apps/client/src/widgets/dialogs/sort_child_notes.spec.tsxindex 7be425dd21..5fa0c9ab12 100644--- a/apps/client/src/widgets/dialogs/sort_child_notes.spec.tsx+++ b/apps/client/src/widgets/dialogs/sort_child_notes.spec.tsx@@ -12,12 +12,12 @@ vi.mock("../../services/i18n", () => ({}));describe("serializeSortLevels", () => {- it("writes each level as key:direction, skipping a label level with no name", () => {+ it("writes each level as its key plus desc where descending, skipping a nameless label", () => {expect(serializeSortLevels([- { kind: "label", labelName: " priority ", descending: true },- { kind: "label", labelName: "", descending: false },- { kind: "dateCreated", labelName: "", descending: false },- { kind: "title", labelName: "ignored", descending: true }+ { kind: "label", labelName: " priority ", direction: "desc" },+ { kind: "label", labelName: "", direction: "asc" },+ { kind: "dateCreated", labelName: "", direction: "asc" },+ { kind: "title", labelName: "ignored", direction: "desc" }])).toBe("priority desc, dateCreated, title desc");});});@@ -81,8 +81,9 @@ describe("SortChildNotesDialog", () => {});}- it("starts with one level and sends the classic single-criterion sort", async () => {+ it("starts with one unremovable level and sends the single-criterion sort", async () => {expect(levels()).toHaveLength(1);+ expect(levels()[0].querySelector(".sort-level-remove")).toHaveProperty("disabled", true);await submit();expect(put).toHaveBeenCalledWith("notes/parent/sort-children", expect.objectContaining({sortBy: "title",@@ -126,8 +127,15 @@ describe("SortChildNotesDialog", () => {}));});- it("keeps the only level from being removed", () => {- const remove = levels()[0].querySelector<HTMLButtonElement>(".sort-level-remove[disabled]");- expect(remove).not.toBeNull();+ it("refuses a label name the attribute rules would not allow", async () => {+ await choose(levels()[0].querySelector("select"), "label");+ const input = levels()[0].querySelector<HTMLInputElement>(".sort-level-label");+ await type(input, "priority desc");+ expect(input?.checkValidity()).toBe(false);+ // A browser compiles `pattern` with the v flag, which happy-dom lacks; check the rule itself.+ const pattern = new RegExp(`^(?:${input?.getAttribute("pattern")})$`, "v");+ expect(pattern.test("priority")).toBe(true);+ expect(pattern.test("calendar:view")).toBe(true);+ expect(pattern.test("priority desc")).toBe(false);});});diff --git a/apps/client/src/widgets/dialogs/sort_child_notes.tsx b/apps/client/src/widgets/dialogs/sort_child_notes.tsxindex 4219e0065a..7499f848ce 100644--- a/apps/client/src/widgets/dialogs/sort_child_notes.tsx+++ b/apps/client/src/widgets/dialogs/sort_child_notes.tsx@@ -1,5 +1,10 @@import "./sort_child_notes.css";+import {+ ATTRIBUTE_NAME_PATTERN,+ serializeSortCriteria,+ type SortCriterion+} from "@triliumnext/commons";import { useState } from "preact/hooks";import { t } from "../../services/i18n";@@ -12,7 +17,7 @@ import FormSelect from "../react/FormSelect";import FormTextBox from "../react/FormTextBox";import { useTriliumEvent } from "../react/hooks";import Modal from "../react/Modal";-import SegmentedChoice from "../react/SegmentedChoice";+import SegmentedChoice, { type SegmentedChoiceOption } from "../react/SegmentedChoice";type SortKind = "title" | "dateCreated" | "dateModified" | "label";@@ -20,10 +25,10 @@ interface SortLevel {kind: SortKind;/** The label the level sorts by; only read where {@link kind} is `label`. */labelName: string;- descending: boolean;+ direction: "asc" | "desc";}-const NEW_LEVEL: SortLevel = { kind: "title", labelName: "", descending: false };+const NEW_LEVEL: SortLevel = { kind: "title", labelName: "", direction: "asc" };export default function SortChildNotesDialog() {const [ parentNoteId, setParentNoteId ] = useState<string>();@@ -57,7 +62,7 @@ export default function SortChildNotesDialog() {{ kind: "dateModified", title: t("sort_child_notes.date_modified") },{ kind: "label", title: t("sort_child_notes.label") }];- const directionOptions = [+ const directionOptions: SegmentedChoiceOption<SortLevel["direction"]>[] = [{ value: "asc", icon: "bx-sort-up", title: t("sort_child_notes.ascending") },{ value: "desc", icon: "bx-sort-down", title: t("sort_child_notes.descending") }];@@ -78,7 +83,7 @@ export default function SortChildNotesDialog() {<ModalclassName="sort-child-notes-dialog"title={t("sort_child_notes.sort_children_by")}- size="lg" maxWidth={680}+ size="lg"onSubmit={onSubmit}onHidden={() => setShown(false)}show={shown}@@ -108,16 +113,15 @@ export default function SortChildNotesDialog() {className="sort-level-label"placeholder={t("sort_child_notes.label_name")}required+ pattern={ATTRIBUTE_NAME_PATTERN}currentValue={level.labelName}onChange={(labelName) => updateLevel(index, { labelName })}/>)}<SegmentedChoiceoptions={directionOptions}- currentValue={level.descending ? "desc" : "asc"}- onChange={(direction) => {- updateLevel(index, { descending: direction === "desc" });- }}+ currentValue={level.direction}+ onChange={(direction) => updateLevel(index, { direction })}/><ActionButtonclassName="sort-level-up"@@ -145,7 +149,7 @@ export default function SortChildNotesDialog() {</div><ButtonclassName="sort-level-add"- icon="bx bx-plus"+ icon="bx-plus"text={t("sort_child_notes.add_level")}size="small"onClick={() => setLevels([ ...levels, NEW_LEVEL ])}@@ -173,14 +177,14 @@ export default function SortChildNotesDialog() {)}-/** Writes the levels in the `#sorted` format the server parses, e.g. `priority desc, title`. */+/** Writes the levels in the `#sorted` grammar, skipping a label level that names no label. */export function serializeSortLevels(levels: SortLevel[]) {- return levels- .map((level) => ({- ...level,- key: level.kind === "label" ? level.labelName.trim() : level.kind- }))- .filter((level) => level.key)- .map((level) => (level.descending ? `${level.key} desc` : level.key))- .join(", ");+ const criteria: SortCriterion[] = [];+ for (const level of levels) {+ const key = level.kind === "label" ? level.labelName.trim() : level.kind;+ if (key) {+ criteria.push({ key, descending: level.direction === "desc" });+ }+ }+ return serializeSortCriteria(criteria);}diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex cf140e0042..175686f352 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -17,6 +17,7 @@ export * from "./lib/shared_constants.js";export * from "./lib/shared_types.js";export * from "./lib/ws_api.js";export * from "./lib/attribute_names.js";+export * from "./lib/sort_criteria.js";export * from "./lib/note_type_ids.js";export * from "./lib/promoted_attribute_definition_parser.js";export { default as promotedAttributeDefinitionParser } from "./lib/promoted_attribute_definition_parser.js";diff --git a/packages/commons/src/lib/attribute_names.ts b/packages/commons/src/lib/attribute_names.tsindex 422a85b346..b77e5a736b 100644--- a/packages/commons/src/lib/attribute_names.ts+++ b/packages/commons/src/lib/attribute_names.ts@@ -14,6 +14,8 @@* stripping), so it is not expressed in terms of these helpers.*/const ATTRIBUTE_NAME_CHARS = "\\p{L}\\p{N}_:";+/** The same rule as an HTML `pattern` attribute, for an input that takes an attribute name. */+export const ATTRIBUTE_NAME_PATTERN = `[${ATTRIBUTE_NAME_CHARS}]+`;const DISALLOWED_MATCHER = new RegExp(`[^${ATTRIBUTE_NAME_CHARS}]`, "gu");const ATTR_NAME_MATCHER = new RegExp(`^[${ATTRIBUTE_NAME_CHARS}]+$`, "u");diff --git a/packages/commons/src/lib/script_api.ts b/packages/commons/src/lib/script_api.tsindex 93d9544afa..e3819dd726 100644--- a/packages/commons/src/lib/script_api.ts+++ b/packages/commons/src/lib/script_api.ts@@ -1310,7 +1310,10 @@ export interface BackendApi {getYearNote(year: string, rootNote?: ScriptBNote): ScriptBNote | null;/**- * Sort child notes of a given note.+ * Sort child notes of a given note. `sortBy` takes the `#sorted` grammar — comma-separated+ * levels of `title`, `dateCreated`, `dateModified` or a label name, each optionally followed by+ * `asc` or `desc` (`priority desc, dueDate`); `reverse` is the direction of the levels without+ * their own, of the folders grouping and of ties.*/sortNotes(parentNoteId: string, sortConfig: { sortBy?: string; reverse?: boolean; foldersFirst?: boolean }): void;/**diff --git a/packages/commons/src/lib/sort_criteria.spec.ts b/packages/commons/src/lib/sort_criteria.spec.tsnew file mode 100644index 0000000000..ca2e1f8979--- /dev/null+++ b/packages/commons/src/lib/sort_criteria.spec.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from "vitest";++import { parseSortCriteria, serializeSortCriteria } from "./sort_criteria.js";++describe("sort criteria", () => {+ it("parses a #sorted value into its levels", () => {+ expect(parseSortCriteria("")).toEqual([{ key: "title" }]);+ expect(parseSortCriteria(null)).toEqual([{ key: "title" }]);+ expect(parseSortCriteria("myOrder")).toEqual([{ key: "myOrder", descending: undefined }]);+ expect(parseSortCriteria(" priority DESC , , area asc, title ")).toEqual([+ { key: "priority", descending: true },+ { key: "area", descending: false },+ { key: "title", descending: undefined }+ ]);+ // A colon is an ordinary character of a label name.+ expect(parseSortCriteria("calendar:view desc,calendar:view")).toEqual([+ { key: "calendar:view", descending: true },+ { key: "calendar:view", descending: undefined }+ ]);+ // A direction word on its own is a key, not a direction.+ expect(parseSortCriteria("desc")).toEqual([{ key: "desc", descending: undefined }]);+ });++ it("writes levels back so that they parse to the same thing", () => {+ const criteria = [+ { key: "priority", descending: true },+ { key: "dateCreated", descending: false },+ { key: "title", descending: undefined }+ ];+ const written = serializeSortCriteria(criteria);+ expect(written).toBe("priority desc, dateCreated, title");+ expect(parseSortCriteria(written).map((c) => Boolean(c.descending)))+ .toEqual(criteria.map((c) => Boolean(c.descending)));+ });+});diff --git a/packages/commons/src/lib/sort_criteria.ts b/packages/commons/src/lib/sort_criteria.tsnew file mode 100644index 0000000000..3da99a77cd--- /dev/null+++ b/packages/commons/src/lib/sort_criteria.ts@@ -0,0 +1,33 @@+/**+ * The grammar of the `#sorted` label: comma-separated sort keys, each optionally followed by `asc`+ * or `desc`, the way a search's `orderBy` is written — `priority desc, dueDate, title`. A key is+ * `title`, `dateCreated`, `dateModified` or the name of a label on the child notes.+ */++export interface SortCriterion {+ key: string;+ /** Set by an explicit `asc`/`desc` after the key; `undefined` follows `#sortDirection`. */+ descending?: boolean;+}++/** Parses a `#sorted` value into its levels; an empty value sorts by title. */+export function parseSortCriteria(value: string | null | undefined): SortCriterion[] {+ const criteria: SortCriterion[] = [];+ for (const level of (value ?? "").split(",")) {+ const words = level.trim().split(/\s+/);+ const last = words[words.length - 1].toLowerCase();+ const isDirection = words.length > 1 && (last === "asc" || last === "desc");+ const key = (isDirection ? words.slice(0, -1) : words).join(" ");+ if (key) {+ criteria.push({ key, descending: isDirection ? last === "desc" : undefined });+ }+ }+ return criteria.length > 0 ? criteria : [{ key: "title" }];+}++/** Writes levels back into the `#sorted` grammar; a level that is not descending is written bare. */+export function serializeSortCriteria(criteria: SortCriterion[]) {+ return criteria+ .map(({ key, descending }) => (descending ? `${key} desc` : key))+ .join(", ");+}diff --git a/packages/trilium-core/src/services/backend_script_api.ts b/packages/trilium-core/src/services/backend_script_api.tsindex 090a6be752..5268c9b5f6 100644--- a/packages/trilium-core/src/services/backend_script_api.ts+++ b/packages/trilium-core/src/services/backend_script_api.ts@@ -344,11 +344,10 @@ export interface Api {sortNotes(parentNoteId: string,sortConfig: {- /** Comma-separated levels of 'title', 'dateCreated', 'dateModified' or a label name,- * each optionally followed by 'asc' or 'desc', e.g. 'priority desc, dueDate'. The- * format is that of the #sorted label, see "Sorting Notes" in the User Guide. */+ /** The `#sorted` grammar: 'title', 'dateCreated', 'dateModified' or a label name per+ * level, each optionally followed by 'asc' or 'desc', e.g. 'priority desc, dueDate'. */sortBy?: string;- /** Sorts the levels without a flag of their own descending. */+ /** Descending for levels without their own direction, the folders grouping and ties. */reverse?: boolean;foldersFirst?: boolean;}diff --git a/packages/trilium-core/src/services/handlers.ts b/packages/trilium-core/src/services/handlers.tsindex d47c3fc008..ebe1eae148 100644--- a/packages/trilium-core/src/services/handlers.ts+++ b/packages/trilium-core/src/services/handlers.ts@@ -1,7 +1,9 @@+import { parseSortCriteria } from "@triliumnext/commons";+import eventService from "./events.js";import { isScriptingEnabled } from "./scripting_guard.js";import scriptService from "./script.js";-import treeService, { parseSortCriteria } from "./tree.js";+import treeService from "./tree.js";import noteService from "./notes.js";import becca from "../becca/becca.js";import BAttribute from "../becca/entities/battribute.js";diff --git a/packages/trilium-core/src/services/tree.spec.ts b/packages/trilium-core/src/services/tree.spec.tsindex 05dffe641b..3a41dbbb9d 100644--- a/packages/trilium-core/src/services/tree.spec.ts+++ b/packages/trilium-core/src/services/tree.spec.ts@@ -3,7 +3,7 @@ import {note, NoteBuilder} from "../test/becca_mocking.js";import becca from "../becca/becca.js";import BBranch from "../becca/entities/bbranch.js";import BNote from "../becca/entities/bnote.js";-import tree, { parseSortCriteria } from "./tree.js";+import tree from "./tree.js";import {buildNote} from "../test/becca_easy_mocking.js";import { getContext } from "./context.js";@@ -198,23 +198,25 @@ describe("Tree", () => {it("applies #sortDirection to the levels without their own and to the title tiebreak", () => {const note = buildNote({children: [- {title: "a", "#priority": "1"},- {title: "b", "#priority": "2"},- {title: "c", "#priority": "2"},+ {title: "a", "#priority": "1", "#area": "home"},+ {title: "b", "#priority": "2", "#area": "home"},+ {title: "c", "#priority": "2", "#area": "work"},+ {title: "d", "#priority": "2", "#area": "work"},{title: "top", "#top": ""},{title: "bottom", "#bottom": ""}],- "#sorted": "priority asc,dateCreated",+ "#sorted": "priority asc, area","#sortDirection": "desc"});getContext().init(() => {tree.sortNotesIfNeeded(note.noteId);});+ // priority ascending as written; area and the title tiebreak follow #sortDirection.const orderedTitles = note.children.map((child) => child.title);- expect(orderedTitles).toStrictEqual(["top", "a", "c", "b", "bottom"]);+ expect(orderedTitles).toStrictEqual(["top", "a", "d", "c", "b", "bottom"]);});- it("groups folders last under #sortDirection=desc, as the single-key sort did", () => {+ it("groups folders last under #sortDirection=desc", () => {const note = buildNote({children: [{title: "a"},@@ -268,22 +270,4 @@ describe("Tree", () => {const orderedTitles = note.children.map((child) => child.title);expect(orderedTitles).toStrictEqual(["a", "unlabelled", "m"]);});-- it("parses a #sorted value into its levels", () => {- expect(parseSortCriteria("")).toEqual([{ key: "title", descending: undefined }]);- expect(parseSortCriteria(null)).toEqual([{ key: "title", descending: undefined }]);- expect(parseSortCriteria("myOrder")).toEqual([{ key: "myOrder", descending: undefined }]);- expect(parseSortCriteria(" priority DESC , , area asc, title ")).toEqual([- { key: "priority", descending: true },- { key: "area", descending: false },- { key: "title", descending: undefined }- ]);- // A colon is an ordinary character of a label name.- expect(parseSortCriteria("calendar:view desc,calendar:view")).toEqual([- { key: "calendar:view", descending: true },- { key: "calendar:view", descending: undefined }- ]);- // A direction word on its own is a key, not a direction.- expect(parseSortCriteria("desc")).toEqual([{ key: "desc", descending: undefined }]);- });});diff --git a/packages/trilium-core/src/services/tree.ts b/packages/trilium-core/src/services/tree.tsindex 853a30f086..520413fb13 100644--- a/packages/trilium-core/src/services/tree.ts+++ b/packages/trilium-core/src/services/tree.ts@@ -1,5 +1,7 @@"use strict";+import { parseSortCriteria } from "@triliumnext/commons";+import { getLog } from "./log.js";import BBranch from "../becca/entities/bbranch.js";import entityChangesService from "./entity_changes.js";@@ -77,36 +79,9 @@ function wouldAddingBranchCreateCycle(parentNoteId: string, childNoteId: string)return parentAncestorNoteIds.some((parentAncestorNoteId) => childSubtreeNoteIds.has(parentAncestorNoteId));}-export interface SortCriterion {- /** `title`, `dateCreated`, `dateModified` or the name of a label on the child notes. */- key: string;- /** Set by an explicit `asc`/`desc` after the key; `undefined` follows `#sortDirection`. */- descending?: boolean;-}--/**- * Parses a `#sorted` value such as `priority desc, dueDate, title` into its levels: comma-separated- * sort keys, each optionally followed by `asc` or `desc`, the way search's `orderBy` is written.- * An empty value sorts by title.- */-export function parseSortCriteria(value: string | null | undefined): SortCriterion[] {- const criteria: SortCriterion[] = [];- for (const level of (value ?? "").split(",")) {- const words = level.trim().split(/\s+/);- const last = words[words.length - 1].toLowerCase();- const isDirection = words.length > 1 && (last === "asc" || last === "desc");- const key = (isDirection ? words.slice(0, -1) : words).join(" ");- if (key) {- criteria.push({ key, descending: isDirection ? last === "desc" : undefined });- }- }- return criteria.length > 0 ? criteria : [{ key: "title" }];-}-/**- * Sorts the children of `parentNoteId` by the levels of `sortBy` (see {@link parseSortCriteria});- * a level without its own direction, the folders-first grouping and the final title tiebreak- * follow `reverse`; `#top` and `#bottom` take precedence over everything and ignore it.+ * Sorts the children of `parentNoteId` by the levels of `sortBy`; `reverse` is the direction of a+ * level without its own, of the folders grouping and of ties, never of `#top` and `#bottom`.*/function sortNotes(parentNoteId: string,@@ -139,8 +114,8 @@ function sortNotes(const prefix = branch?.prefix;rawValue = prefix ? `${prefix} - ${note.title}` : note.title;} else {- rawValue = ["dateCreated", "dateModified"].includes(key)- ? (note as any)[key]+ rawValue = key === "dateCreated" || key === "dateModified"+ ? note[key] ?? null: note.getLabelValue(key);}@@ -185,7 +160,7 @@ function sortNotes(const aHasChildren = a.hasChildren();const bHasChildren = b.hasChildren();- // Folders group first ascending and last descending, as the single-key sort did.+ // Folders group first ascending and last descending.if (aHasChildren !== bHasChildren) {return (aHasChildren ? -1 : 1) * (reverse ? -1 : 1);}