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/text editor/sort selection: fix some issues
Adorian Doran1202264048e3
diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.tsindex 302de7af7d..e226a2a559 100644--- a/apps/client/src/menus/note_context_menu.spec.ts+++ b/apps/client/src/menus/note_context_menu.spec.ts@@ -387,7 +387,7 @@ describe("buildNoteContextMenuItems", () => {]);});- it("puts the sort submenu below the clipboard rows, outside a table only", async () => {+ it("puts the sort submenu below the clipboard rows, or beside the table's", async () => {const host = browserLikeHost({paste: { enabled: true, run: vi.fn(), runAsPlainText: vi.fn(), read: vi.fn() }});@@ -405,12 +405,22 @@ describe("buildNoteContextMenuItems", () => {"electron_context_menu.search_online","electron_context_menu.search_in_trilium"]);+ expect(buildSortSelectionMenuItem)+ .toHaveBeenLastCalledWith(null, { isRowsExcluded: false });- vi.mocked(buildSortSelectionMenuItem).mockClear();+ // In a cell, the submenu sorts what the selection holds there; the table sorts the rows.+ vi.mocked(buildSortSelectionMenuItem).mockReturnValueOnce({ title: "SORT" });vi.mocked(buildTableContextMenuSections).mockResolvedValueOnce({- main: [], sort: { title: "S" }, delete: [], select: { title: "SEL" }, pasteRows: []+ main: [], sort: { title: "S" }, delete: [ { title: "DEL" } ], select: { title: "SEL" },+ pasteRows: []} as TableMenuSections);- await build({ isEditable: true, element: document.createElement("td") }, host);+ const cell = document.createElement("td");+ const cellItems = await build({ isEditable: true, element: cell, selectionText: "" }, host);+ expect(buildSortSelectionMenuItem).toHaveBeenLastCalledWith(null, { isRowsExcluded: true });+ expect(titles(cellItems).slice(-7))+ .toEqual([ "---", "S", "SORT", "---", "DEL", "---", "SEL" ]);++ vi.mocked(buildSortSelectionMenuItem).mockClear();await build({ element: document.createElement("p") }, host);expect(buildSortSelectionMenuItem).not.toHaveBeenCalled();});diff --git a/apps/client/src/menus/note_context_menu.ts b/apps/client/src/menus/note_context_menu.tsindex 32d8ede3e6..dd65244cab 100644--- a/apps/client/src/menus/note_context_menu.ts+++ b/apps/client/src/menus/note_context_menu.ts@@ -147,9 +147,10 @@ export async function buildNoteContextMenuItems(const codeEditorItems = target.isEditable? await buildCodeEditorContextMenuItems(target.element): null;- // A table has its own sort section.- const sortItem = target.isEditable && !tableSections- ? buildSortSelectionMenuItem(await getTextEditorContaining(target.element))+ // The table section sorts the rows.+ const sortItem = target.isEditable+ ? buildSortSelectionMenuItem(await getTextEditorContaining(target.element),+ { isRowsExcluded: tableSections !== null }): null;const hasText = !hasCellSelection && target.selectionText.trim().length > 0;const hasClipboardContent = hasText || hasCellSelection;@@ -258,11 +259,10 @@ export async function buildNoteContextMenuItems(}if (tableSections) {- items.push({ kind: "separator" }, tableSections.sort, { kind: "separator" },+ const sortItems = sortItem ? [ tableSections.sort, sortItem ] : [ tableSections.sort ];+ items.push({ kind: "separator" }, ...sortItems, { kind: "separator" },...tableSections.delete, { kind: "separator" }, tableSections.select);- }-- if (sortItem) {+ } else if (sortItem) {items.push({ kind: "separator" }, sortItem);}diff --git a/apps/client/src/menus/text_editor_context_menu.spec.ts b/apps/client/src/menus/text_editor_context_menu.spec.tsindex 7e3ee1bc97..8b603215e2 100644--- a/apps/client/src/menus/text_editor_context_menu.spec.ts+++ b/apps/client/src/menus/text_editor_context_menu.spec.ts@@ -322,12 +322,16 @@ describe("buildSortSelectionMenuItem", () => {expect(editor.editing.view.focus).toHaveBeenCalled();rows[0].handler?.(rows[0], null as never);expect(editor.execute).toHaveBeenLastCalledWith("triliumSortSelectionAscending");++ expect(buildSortSelectionMenuItem(sortEditor("listItems"), { isRowsExcluded: true }))+ .toMatchObject({ title: "sort_selection.sort_list_items" });});- it("is absent for one block, nothing to sort, no editor, or with the feature off", () => {+ it("is absent for one block, nothing to sort, excluded rows, no editor or feature", () => {expect(buildSortSelectionMenuItem(sortEditor("blocks", 1))).toBeNull();expect(buildSortSelectionMenuItem(sortEditor(null))).toBeNull();expect(buildSortSelectionMenuItem(sortEditor("rows", 2, false))).toBeNull();+ expect(buildSortSelectionMenuItem(sortEditor("rows"), { isRowsExcluded: true })).toBeNull();expect(buildSortSelectionMenuItem(null)).toBeNull();experimentalState.enabled.clear();diff --git a/apps/client/src/menus/text_editor_context_menu.ts b/apps/client/src/menus/text_editor_context_menu.tsindex d5aebdf9bf..67122f2cd0 100644--- a/apps/client/src/menus/text_editor_context_menu.ts+++ b/apps/client/src/menus/text_editor_context_menu.ts@@ -138,13 +138,16 @@ function buildQuickActionItems(/*** The _Sort_ submenu for a selection over several blocks of `editor`, named by what it sorts. It* is `null` while the experimental feature is off, for a selection inside one block, and when- * nothing at the selection can be sorted.+ * nothing at the selection can be sorted. `isRowsExcluded` leaves out a sort of table rows, for a+ * menu that has its own.*/export function buildSortSelectionMenuItem(- editor: CKTextEditor | null | undefined+ editor: CKTextEditor | null | undefined,+ { isRowsExcluded = false } = {}): MenuItem<CommandNames> | null {const command = editor?.commands.get("triliumSortSelectionAscending");if (!editor || !command?.isEnabled || !command.value+ || (isRowsExcluded && command.value === "rows")|| !isExperimentalFeatureEnabled("sortSelection")|| Array.from(editor.model.document.selection.getSelectedBlocks()).length < 2) {return null;diff --git a/packages/ckeditor5/src/plugins/sort_selection/sort_selection.spec.ts b/packages/ckeditor5/src/plugins/sort_selection/sort_selection.spec.tsindex c06a65cd6d..c5f737ff90 100644--- a/packages/ckeditor5/src/plugins/sort_selection/sort_selection.spec.ts+++ b/packages/ckeditor5/src/plugins/sort_selection/sort_selection.spec.ts@@ -12,7 +12,7 @@ import {TodoList} from "ckeditor5";import type { ButtonView, ClassicEditor, DropdownView, ModelElement } from "ckeditor5";-import { beforeEach, describe, expect, it } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";import { modelTable, selectCells } from "../../../test/table-kit.js";@@ -84,9 +84,31 @@ describe("SortSelection", () => {it("sorts only the selected items of a range", () => {setModelData(editor.model,- item("d", "d") + item("c", "[c") + item("b", "b]") + item("a", "a"));+ item("d", "d") + item("c", "c") + item("c", "[an aside") + item("b", "b]")+ + item("a", "a"));sort();- expect(outline()).toEqual([ "* d", "* b", "* c", "* a" ]);+ expect(outline()).toEqual([ "* d", "* b", "* c", "* an aside", "* a" ]);+ });++ it("reads no text and no item past the next one until it sorts", () => {+ setModelData(editor.model,+ item("a", "a[]") + item("a", "a more") + item("c", "c") + item("b", "b"));+ const model = editor.model;+ const lastItem = model.document.getRoot()?.getChild(3) as ModelElement;+ const createRangeIn = vi.spyOn(model, "createRangeIn");+ const reads = [+ vi.spyOn(lastItem, "getAttribute"),+ vi.spyOn(lastItem, "hasAttribute")+ ];++ editor.commands.get(ASCENDING)?.refresh();+ expect(isEnabled()).toBe(true);+ expect(reads.map((read) => read.mock.calls.length)).toEqual([ 0, 0 ]);+ expect(createRangeIn).not.toHaveBeenCalled();++ sort();+ expect(createRangeIn).toHaveBeenCalled();+ expect(outline()).toEqual([ "* a", "* a more", "* b", "* c" ]);});it("sorts the items at the lowest level of a range starting in a nested item", () => {@@ -120,6 +142,10 @@ describe("SortSelection", () => {setModelData(editor.model, item("a", "a[]") + "<paragraph>b</paragraph>");expect(isEnabled()).toBe(false);+ setModelData(editor.model,+ item("a", "a[]") + item("a1", "a1", 1) + item("a", "a more"));+ expect(isEnabled()).toBe(false);+setModelData(editor.model,item("b", "[b") + "<blockQuote>" + item("a", "a]") + "</blockQuote>");expect(isEnabled()).toBe(false);diff --git a/packages/ckeditor5/src/plugins/sort_selection/sort_selection.ts b/packages/ckeditor5/src/plugins/sort_selection/sort_selection.tsindex 632074d3bb..047012f208 100644--- a/packages/ckeditor5/src/plugins/sort_selection/sort_selection.ts+++ b/packages/ckeditor5/src/plugins/sort_selection/sort_selection.ts@@ -79,7 +79,7 @@ export class SortSelectionCommand extends Command {// A caret moves with its block. A range is set over the sorted runs, as its ends moved.const isRange = !editor.model.document.selection.isCollapsed;- sortRuns(editor, target.runs, this.isDescending, (writer, sorted) => {+ sortRuns(editor, target.getRuns(), this.isDescending, (writer, sorted) => {if (isRange) {writer.setSelection(writer.createRange(writer.createPositionBefore(sorted[0].first),diff --git a/packages/ckeditor5/src/plugins/sort_selection/sort_targets.ts b/packages/ckeditor5/src/plugins/sort_selection/sort_targets.tsindex aaa6dfea5e..c45a009002 100644--- a/packages/ckeditor5/src/plugins/sort_selection/sort_targets.ts+++ b/packages/ckeditor5/src/plugins/sort_selection/sort_targets.ts@@ -3,6 +3,7 @@ import {_getListItems as getListItems,_isFirstBlockOfListItem as isFirstBlockOfListItem,_isListItemBlock as isListItemBlock,+ _ListWalker as ListWalker,TableUtils} from "ckeditor5";import type { _ListElement as ListElement, Editor, Model, ModelElement } from "ckeditor5";@@ -14,7 +15,7 @@ import { unitText } from "./sort_runs.js";export type SortTargetKind = "listItems" | "blocks" | "rows";export type SortTarget =- | { kind: "listItems" | "blocks"; runs: SortRun[] }+ | { kind: "listItems" | "blocks"; getRuns: () => SortRun[] }| { kind: "rows" };/** The table commands that a sort of rows runs. */@@ -26,7 +27,8 @@ export const TABLE_SORT_COMMANDS = {/*** What a sort of the current selection reorders, or `null` when nothing can be sorted. The* innermost structure is sorted: in a table cell, a list or several selected blocks are sorted,- * and a caret elsewhere in the cell sorts the rows.+ * and a caret elsewhere in the cell sorts the rows. Commands refresh on every change, so the text+ * is read and a whole list walked only in `getRuns()`.*/export function resolveSortTarget(editor: Editor): SortTarget | null {const model = editor.model;@@ -62,27 +64,24 @@ function getListTarget(model: Model, blocks: ModelElement[]): SortTarget | null}const level = Math.min(...listBlocks.map(getIndent));- const firstItem = getAncestorItem(listBlocks[0], level);- const lastItem = getAncestorItem(listBlocks[listBlocks.length - 1], level);- const firstId = firstItem.getAttribute("listItemId");- const lastId = lastItem.getAttribute("listItemId");- const heads = getListItems(firstItem).filter((block) => isFirstBlockOfListItem(block));-- let selected = heads;- if (firstId !== lastId) {- const first = heads.findIndex((head) => head.getAttribute("listItemId") === firstId);- const last = heads.findIndex((head) => head.getAttribute("listItemId") === lastId);- // `slice()` returns nothing when the last item is in another list, such as a numbered- // list after a bulleted one or a list in a quote.- selected = heads.slice(first, last + 1);+ const firstHead = getItemHead(listBlocks[0], level);+ const lastHead = getItemHead(listBlocks[listBlocks.length - 1], level);+ if (firstHead === lastHead) {+ return hasSiblingItem(firstHead)+ ? getListItemsTarget(model,+ () => getListItems(firstHead).filter((block) => isFirstBlockOfListItem(block)))+ : null;}- if (selected.length < 2) {- return null;- }+ const heads = getHeadsBetween(firstHead, lastHead);+ return heads && getListItemsTarget(model, () => heads);+}++/** Sorts the items whose first blocks `getHeads()` returns, each with its nested items. */+function getListItemsTarget(model: Model, getHeads: () => ListElement[]): SortTarget {return {kind: "listItems",- runs: selected.map((head) => {+ getRuns: () => getHeads().map((head) => {const itemBlocks = getAllListItemBlocks(head, { higherIndent: true });return {first: head,@@ -93,6 +92,46 @@ function getListTarget(model: Model, blocks: ModelElement[]): SortTarget | null};}+/** Whether the list of `item` has another item at its level, read from the closest blocks. */+function hasSiblingItem(item: ListElement): boolean {+ for (const direction of [ "backward", "forward" ] as const) {+ const walker = new ListWalker(item, {+ direction,+ sameIndent: true,+ sameAttributes: "listType"+ });+ for (const block of walker) {+ if (block.getAttribute("listItemId") !== item.getAttribute("listItemId")) {+ return true;+ }+ }+ }+ return false;+}++/**+ * The first block of each item from `firstHead` to `lastHead`, or `null` when `lastHead` is in+ * another list, such as a numbered list after a bulleted one or a list in a quote.+ */+function getHeadsBetween(firstHead: ListElement, lastHead: ListElement): ListElement[] | null {+ const heads: ListElement[] = [];+ const walker = new ListWalker(firstHead, {+ direction: "forward",+ includeSelf: true,+ sameIndent: true,+ sameAttributes: "listType"+ });+ for (const block of walker) {+ if (isFirstBlockOfListItem(block)) {+ heads.push(block);+ }+ if (block === lastHead) {+ return heads;+ }+ }+ return null;+}+/*** The siblings from the one holding `firstBlock` to the one holding `lastBlock`. A collapsible's* title is replaced by the collapsible, as in the block moves. Not sortable when one of them is a@@ -127,7 +166,8 @@ function getBlocksTarget(return {kind: "blocks",- runs: units.map((unit) => ({ first: unit, last: unit, text: unitText(model, unit) }))+ getRuns: () => units.map((unit) =>+ ({ first: unit, last: unit, text: unitText(model, unit) }))};}@@ -137,13 +177,13 @@ function getSortableBlock(block: ModelElement): ModelElement {return block.is("element", "summary") ? block.parent as ModelElement : block;}-/** The item at `level` that holds `block`: itself, or the closest preceding item at that level. */-function getAncestorItem(block: ListElement, level: number): ListElement {+/** The first block of the item at `level` that holds `block`. */+function getItemHead(block: ListElement, level: number): ListElement {let item = block;while (getIndent(item) > level && isListItemBlock(item.previousSibling)) {item = item.previousSibling;}- return item;+ return getAllListItemBlocks(item)[0];}function getIndent(block: ListElement): number {