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(delete_notes): list the notes to be deleted as chips
Elian Doran35c50fbbdfea
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 75f4cf42f4..02284ae329 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -85,7 +85,6 @@"bulk_actions": {"bulk_actions": "Bulk actions","selected_notes": "Selected notes",- "more_notes": "+{{count}} more","remove_from_selection": "Remove from the selection","affected_note_count_one": "The actions apply to {{count}} note.","affected_note_count_other": "The actions apply to {{count}} notes.",@@ -104,6 +103,9 @@"notes": "Notes","other": "Other"},+ "note_chips": {+ "more": "+{{count}} more"+ },"clone_to": {"clone_notes_to": "Clone notes to...","help_on_links": "Help on links",diff --git a/apps/client/src/widgets/dialogs/bulk_actions.css b/apps/client/src/widgets/dialogs/bulk_actions.cssindex ada5651e9f..4d82d908c2 100644--- a/apps/client/src/widgets/dialogs/bulk_actions.css+++ b/apps/client/src/widgets/dialogs/bulk_actions.css@@ -7,24 +7,6 @@margin-bottom: 0;}- .bulk-actions-selected-notes {- display: flex;- flex-wrap: wrap;- align-items: center;- gap: 6px;- max-height: 30vh;- overflow-y: auto;-- .tn-chip {- max-width: 100%;- min-width: 0;- }-- .bulk-actions-more-notes {- padding-inline: 4px;- }- }-.bulk-actions-add-action {display: flex;justify-content: flex-end;diff --git a/apps/client/src/widgets/dialogs/bulk_actions.spec.tsx b/apps/client/src/widgets/dialogs/bulk_actions.spec.tsxindex 1fbe655cc8..5cd848a25f 100644--- a/apps/client/src/widgets/dialogs/bulk_actions.spec.tsx+++ b/apps/client/src/widgets/dialogs/bulk_actions.spec.tsx@@ -47,7 +47,7 @@ describe("BulkActionsDialog", () => {}function chipNoteIds() {- return [ ...container.querySelectorAll(".bulk-actions-selected-notes .tn-chip .note-link") ]+ return [ ...container.querySelectorAll(".note-chips .tn-chip .note-link") ].map((el) => el.textContent);}@@ -60,12 +60,12 @@ describe("BulkActionsDialog", () => {await open(noteIds);expect(chipNoteIds()).toStrictEqual([ "n1", "n2", "n3", "n4", "n5" ]);- const more = container.querySelector<HTMLElement>(".bulk-actions-selected-notes .bulk-actions-more-notes");- expect(more?.textContent).toBe("bulk_actions.more_notes:2");+ const more = container.querySelector<HTMLElement>(".note-chips .note-chips-more");+ expect(more?.textContent).toBe("note_chips.more:2");await act(async () => more?.click());expect(chipNoteIds()).toStrictEqual(noteIds);- expect(container.querySelector(".bulk-actions-more-notes")).toBeNull();+ expect(container.querySelector(".note-chips-more")).toBeNull();});it("says so when no action is chosen yet", async () => {@@ -227,7 +227,7 @@ describe("BulkActionsDialog", () => {await open([ "n1", "n2" ]);expect(lastAffectedNotesRequest()).toStrictEqual({ noteIds: [ "n1", "n2" ], includeDescendants: false });- const removeButtons = container.querySelectorAll<HTMLButtonElement>(".bulk-actions-selected-notes .tn-chip-remove");+ const removeButtons = container.querySelectorAll<HTMLButtonElement>(".note-chips .tn-chip-remove");expect(removeButtons).toHaveLength(2);await act(async () => removeButtons[0].click());diff --git a/apps/client/src/widgets/dialogs/bulk_actions.tsx b/apps/client/src/widgets/dialogs/bulk_actions.tsxindex 752dcd91fe..d5253938c7 100644--- a/apps/client/src/widgets/dialogs/bulk_actions.tsx+++ b/apps/client/src/widgets/dialogs/bulk_actions.tsx@@ -18,11 +18,7 @@ import AbstractBulkAction from "../bulk_actions/abstract_bulk_action";import FNote from "../../entities/fnote";import froca from "../../services/froca";import { useTriliumEvent } from "../react/hooks";-import Chip from "../react/Chip";-import NoteLink from "../react/NoteLink";-import LinkButton from "../react/LinkButton";--const COLLAPSED_NOTE_CHIP_COUNT = 5;+import NoteChips from "../react/NoteChips";export default function BulkActionsDialog() {const [ selectedOrActiveNoteIds, setSelectedOrActiveNoteIds ] = useState<string[]>();@@ -135,7 +131,13 @@ export default function BulkActionsDialog() {<Card heading={t("bulk_actions.selected_notes")}>{selectedOrActiveNoteIds && (<CardSection>- <SelectedNotes noteIds={selectedOrActiveNoteIds} onChange={setSelectedOrActiveNoteIds} />+ <NoteChips+ noteIds={selectedOrActiveNoteIds}+ removeButtonText={t("bulk_actions.remove_from_selection")}+ onRemove={selectedOrActiveNoteIds.length > 1+ ? (noteId) => setSelectedOrActiveNoteIds(selectedOrActiveNoteIds.filter((id) => id !== noteId))+ : undefined}+ /></CardSection>)}<CardSection>@@ -164,34 +166,6 @@ export default function BulkActionsDialog() {);}-function SelectedNotes({ noteIds, onChange }: { noteIds: string[]; onChange(noteIds: string[]): void }) {- const [ expanded, setExpanded ] = useState(false);- const shownNoteIds = expanded ? noteIds : noteIds.slice(0, COLLAPSED_NOTE_CHIP_COUNT);- const hiddenCount = noteIds.length - shownNoteIds.length;-- return (- <div className="bulk-actions-selected-notes">- {shownNoteIds.map((noteId) => (- <Chip- key={noteId}- removeButtonText={t("bulk_actions.remove_from_selection")}- disabled={noteIds.length === 1}- onRemove={() => onChange(noteIds.filter((id) => id !== noteId))}- >- <NoteLink notePath={noteId} showNoteIcon />- </Chip>- ))}- {hiddenCount > 0 && (- <LinkButton- className="bulk-actions-more-notes"- text={t("bulk_actions.more_notes", { count: hiddenCount })}- onClick={() => setExpanded(true)}- />- )}- </div>- );-}-function ExistingActionsList({ existingActions }: { existingActions: AbstractBulkAction[] }) {if (!existingActions.length) {return (diff --git a/apps/client/src/widgets/dialogs/delete_notes.css b/apps/client/src/widgets/dialogs/delete_notes.cssindex adae0dd789..66c78662f7 100644--- a/apps/client/src/widgets/dialogs/delete_notes.css+++ b/apps/client/src/widgets/dialogs/delete_notes.css@@ -5,29 +5,3 @@.delete-notes-dialog .tn-card:last-child {margin-bottom: 0;}--.delete-notes-dialog .preview-list {- margin: 0;- padding: 0;- list-style: none;- max-height: 400px;- overflow: auto;-}--.delete-notes-dialog .preview-list li {- padding: 6px 16px;- border-bottom: 1px solid var(--main-border-color);- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;-}--.delete-notes-dialog .preview-list li:last-child {- border-bottom: none;-}--.delete-notes-dialog .preview-list small {- margin-inline-start: 8px;- font-size: 0.8em;- color: var(--muted-text-color);-}diff --git a/apps/client/src/widgets/dialogs/delete_notes.spec.tsx b/apps/client/src/widgets/dialogs/delete_notes.spec.tsxnew file mode 100644index 0000000000..e16865bd8b--- /dev/null+++ b/apps/client/src/widgets/dialogs/delete_notes.spec.tsx@@ -0,0 +1,53 @@+import { act } from "preact/test-utils";+import { describe, expect, it, vi } from "vitest";++import Component from "../../components/component";+import { renderInto } from "../../test/render";+import { ParentComponent } from "../react/react_utils";+import DeleteNotesDialog from "./delete_notes";++const server = vi.hoisted(() => ({+ get: vi.fn(async () => []),+ post: vi.fn()+}));++vi.mock("../../services/i18n", async (importOriginal) => ({+ ...await importOriginal<typeof import("../../services/i18n")>(),+ t: (key: string, opts?: { count?: number }) => (opts?.count !== undefined ? `${key}:${opts.count}` : key)+}));+vi.mock("../../services/server", () => ({ default: server }));+vi.mock("../react/NoteLink", () => ({+ default: ({ notePath }: { notePath: string }) => <span className="note-link">{notePath}</span>+}));++describe("DeleteNotesDialog", () => {+ it("lists the notes to be deleted as read-only chips", async () => {+ const noteIdsToBeDeleted = [ "n1", "n2", "n3", "n4", "n5", "n6", "n7" ];+ server.post.mockResolvedValue({ brokenRelations: [], noteIdsToBeDeleted });+ const host = new Component();+ const container = renderInto(+ <ParentComponent.Provider value={host}>+ <DeleteNotesDialog />+ </ParentComponent.Provider>+ );++ await act(async () => {+ await host.handleEventInChildren("showDeleteNotesDialog", {+ branchIdsToDelete: [ "b1" ], callback: vi.fn(), forceDeleteAllClones: false+ });+ });+ // The preview is requested once the dialog has taken the branches.+ for (let attempt = 0; attempt < 5; attempt++) {+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 1));+ });+ }+ expect(server.post).toHaveBeenCalledWith("delete-notes-preview", expect.anything());++ const chips = [ ...container.querySelectorAll(".delete-notes-dialog .note-chips .tn-chip .note-link") ];+ expect(chips.map((chip) => chip.textContent)).toStrictEqual([ "n1", "n2", "n3", "n4", "n5" ]);+ expect(container.querySelector(".note-chips .note-chips-more")?.textContent).toBe("note_chips.more:2");+ expect([ ...container.querySelectorAll<HTMLButtonElement>(".note-chips .tn-chip-remove") ].every((b) => b.disabled))+ .toBe(true);+ });+});diff --git a/apps/client/src/widgets/dialogs/delete_notes.tsx b/apps/client/src/widgets/dialogs/delete_notes.tsxindex b6cf390ec9..8d77571889 100644--- a/apps/client/src/widgets/dialogs/delete_notes.tsx+++ b/apps/client/src/widgets/dialogs/delete_notes.tsx@@ -1,10 +1,7 @@import "./delete_notes.css";import type { DeleteNotesPreview } from "@triliumnext/commons";-import { CSSProperties } from "preact";import { useEffect, useRef, useState } from "preact/hooks";-import type React from "react";-import { List, type RowComponentProps } from "react-window";import froca from "../../services/froca.js";import { t } from "../../services/i18n.js";@@ -14,6 +11,7 @@ import { Card, CardSection } from "../react/Card.js";import FormToggle from "../react/FormToggle.js";import { useTriliumEvent } from "../react/hooks.jsx";import Modal from "../react/Modal.js";+import NoteChips from "../react/NoteChips.js";import NoteLink from "../react/NoteLink.js";import OptionsRow from "../type_widgets/options/components/OptionsRow.js";@@ -188,40 +186,12 @@ function DeleteAllClonesOption({ cloneInfo, deleteAllClones, setDeleteAllClones);}-const ROW_HEIGHT = 36;-const VIRTUALIZE_THRESHOLD = 100;--function DeletedNoteRow({ index, style, noteIds }: RowComponentProps<{ noteIds: string[] }>) {- return (- <li style={style as CSSProperties} key={noteIds[index]}>- <NoteLink notePath={noteIds[index]} showNotePath showNoteIcon />- </li>- ) as React.ReactElement;-}-function DeletedNotes({ noteIdsToBeDeleted }: { noteIdsToBeDeleted: DeleteNotesPreview["noteIdsToBeDeleted"] }) {return (<Card heading={t("delete_notes.notes_to_be_deleted", { notesCount: noteIdsToBeDeleted.length })}>- <CardSection noPadding={noteIdsToBeDeleted.length > 0}>+ <CardSection>{noteIdsToBeDeleted.length ? (- noteIdsToBeDeleted.length > VIRTUALIZE_THRESHOLD ? (- <List- className="preview-list"- tagName="ul"- rowComponent={DeletedNoteRow}- rowCount={noteIdsToBeDeleted.length}- rowHeight={ROW_HEIGHT}- rowProps={{ noteIds: noteIdsToBeDeleted }}- />- ) : (- <ul className="preview-list">- {noteIdsToBeDeleted.map((noteId) => (- <li key={noteId}>- <NoteLink notePath={noteId} showNotePath showNoteIcon />- </li>- ))}- </ul>- )+ <NoteChips noteIds={noteIdsToBeDeleted} />) : (<span className="muted-text">{t("delete_notes.no_note_to_delete")}</span>)}diff --git a/apps/client/src/widgets/react/NoteChips.css b/apps/client/src/widgets/react/NoteChips.cssnew file mode 100644index 0000000000..a236170818--- /dev/null+++ b/apps/client/src/widgets/react/NoteChips.css@@ -0,0 +1,17 @@+.note-chips {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px;+ max-height: 30vh;+ overflow-y: auto;++ .tn-chip {+ max-width: 100%;+ min-width: 0;+ }++ .note-chips-more {+ padding-inline: 4px;+ }+}diff --git a/apps/client/src/widgets/react/NoteChips.spec.tsx b/apps/client/src/widgets/react/NoteChips.spec.tsxnew file mode 100644index 0000000000..4aef9e2c9c--- /dev/null+++ b/apps/client/src/widgets/react/NoteChips.spec.tsx@@ -0,0 +1,51 @@+import { act } from "preact/test-utils";+import { describe, expect, it, vi } from "vitest";++import { renderInto } from "../../test/render";+import NoteChips from "./NoteChips";++vi.mock("../../services/i18n", () => ({+ t: (key: string, opts?: { count?: number }) => (opts?.count !== undefined ? `${key}:${opts.count}` : key)+}));+vi.mock("./NoteLink", () => ({+ default: ({ notePath }: { notePath: string }) => <span className="note-link">{notePath}</span>+}));++const ids = (count: number) => Array.from({ length: count }, (_, index) => `n${index + 1}`);++describe("NoteChips", () => {+ it("shows the first notes and reveals the rest a page at a time", async () => {+ const container = renderInto(<NoteChips noteIds={ids(250)} />);+ expect(shownIds(container)).toStrictEqual(ids(5));+ expect(moreLink(container)?.textContent).toBe("note_chips.more:245");++ await act(async () => moreLink(container)?.click());+ expect(shownIds(container)).toHaveLength(105);+ expect(moreLink(container)?.textContent).toBe("note_chips.more:145");++ await act(async () => moreLink(container)?.click());+ await act(async () => moreLink(container)?.click());+ expect(shownIds(container)).toHaveLength(250);+ expect(moreLink(container)).toBeNull();+ });++ it("offers no removal unless asked to", async () => {+ const readOnly = renderInto(<NoteChips noteIds={ids(2)} />);+ expect([ ...readOnly.querySelectorAll<HTMLButtonElement>(".tn-chip-remove") ].every((b) => b.disabled)).toBe(true);++ const onRemove = vi.fn();+ const editable = renderInto(<NoteChips noteIds={ids(2)} onRemove={onRemove} removeButtonText="remove" />);+ const button = editable.querySelector<HTMLButtonElement>(".tn-chip-remove");+ expect(button?.disabled).toBe(false);+ await act(async () => button?.click());+ expect(onRemove).toHaveBeenCalledWith("n1");+ });+});++function shownIds(container: HTMLElement) {+ return [ ...container.querySelectorAll(".note-chips .tn-chip .note-link") ].map((el) => el.textContent);+}++function moreLink(container: HTMLElement) {+ return container.querySelector<HTMLElement>(".note-chips .note-chips-more");+}diff --git a/apps/client/src/widgets/react/NoteChips.tsx b/apps/client/src/widgets/react/NoteChips.tsxnew file mode 100644index 0000000000..7713b57059--- /dev/null+++ b/apps/client/src/widgets/react/NoteChips.tsx@@ -0,0 +1,53 @@+import "./NoteChips.css";++import { useState } from "preact/hooks";++import { t } from "../../services/i18n";+import Chip from "./Chip";+import LinkButton from "./LinkButton";+import NoteLink from "./NoteLink";++/** How many chips show before the rest are asked for. */+const COLLAPSED_COUNT = 5;+/** How many more each "+N more" reveals, so a set of thousands is never drawn at once. */+const PAGE_SIZE = 100;++interface NoteChipsProps {+ noteIds: string[];+ /** Removes a note from the set. Without it, the chips only show the set. */+ onRemove?(noteId: string): void;+ /** What removing a chip means, in the host's own words. Required with {@link onRemove}. */+ removeButtonText?: string;+}++/**+ * A set of notes as chips, each the note's icon and title linking to it: the first few, then a+ * "+N more" link that reveals the rest a page at a time.+ */+export default function NoteChips({ noteIds, onRemove, removeButtonText }: NoteChipsProps) {+ const [ shownCount, setShownCount ] = useState(COLLAPSED_COUNT);+ const shownNoteIds = noteIds.slice(0, shownCount);+ const hiddenCount = noteIds.length - shownNoteIds.length;++ return (+ <div className="note-chips">+ {shownNoteIds.map((noteId) => (+ <Chip+ key={noteId}+ removeButtonText={removeButtonText ?? ""}+ disabled={!onRemove}+ onRemove={() => onRemove?.(noteId)}+ >+ <NoteLink notePath={noteId} showNoteIcon />+ </Chip>+ ))}+ {hiddenCount > 0 && (+ <LinkButton+ className="note-chips-more"+ text={t("note_chips.more", { count: hiddenCount })}+ onClick={() => setShownCount((count) => count + PAGE_SIZE)}+ />+ )}+ </div>+ );+}