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/options/shortcuts: switch to the new card component
Adorian Doran50ef975c3fd4
diff --git a/apps/client/src/widgets/type_widgets/options/shortcuts.css b/apps/client/src/widgets/type_widgets/options/shortcuts.cssindex f1cc25c4a8..960e563f7f 100644--- a/apps/client/src/widgets/type_widgets/options/shortcuts.css+++ b/apps/client/src/widgets/type_widgets/options/shortcuts.css@@ -1,41 +1,36 @@-/* The shortcuts page feeds its controls into its OptionsPageHeader: the conflicts badge and reset- buttons on the title row, the filter/search box on the full-width row beneath. The sticky bar,+/* The shortcuts page feeds its controls into its OptionsPageHeader: the conflicts badge on the title+ row, the filter box and the page's actions on the full-width row beneath. The sticky bar,background and bottom border come from the header itself. */-.shortcut-header-buttons {- display: flex;- align-items: center;- gap: 0.5em;- justify-content: flex-end;- /* Keep the reset buttons clear of the dialog's window buttons (top-right). */- margin-inline-end: 3em;- /* Prominent danger badge flagging that conflicts exist; click to filter to them. Pushed to the- leading edge of the row, away from the buttons. */- .shortcut-conflicts-badge {- flex: 0 0 auto;- margin-inline-end: auto;- --color: var(--icon-button-danger-color, #d9534f);- }+/* Prominent danger badge flagging that conflicts exist; click to filter to them. Kept clear of the+ dialog's own window buttons, which share the title row with it. */+.shortcut-conflicts-badge {+ --color: var(--icon-button-danger-color, #d9534f);+ flex: 0 0 auto;+ margin-inline-end: 3em;+}- /* While the conflicts filter is active, fill the outline badge solid. */- .shortcut-conflicts-badge.active {- background-color: var(--color);- color: white;- }+/* While the conflicts filter is active, fill the outline badge solid. */+.shortcut-conflicts-badge.active {+ background-color: var(--color);+ color: white;}.shortcut-header-filter {display: flex;+ flex-wrap: wrap;align-items: center;gap: 0.5em;- /* The search box grows so the filter button sits at the trailing edge. */+ /* The search box grows so the filter button and the actions after it sit at the trailing edge. */> :first-child {flex: 1;}- .dropdown {+ .dropdown,+ > .btn {flex: 0 0 auto;+ white-space: nowrap;}/* Highlight the filter button while a filter is applied. */@@ -57,10 +52,14 @@.shortcut-editor {display: flex;+ /* A card option holds its controls at their natural width; this one is a set that wraps, so+ it gives way to the name beside it instead of carrying the chips off the card. */+ flex-shrink: 1;flex-wrap: wrap;align-items: center;justify-content: flex-end;gap: 0.4em;+ min-width: 0;}/* Reserve the revert button's slot (matching its .icon-action width) so the add button to its@@ -150,7 +149,7 @@transition: opacity 0.15s ease;}- .option-row:hover .shortcut-recorder,+ .tn-card-option:hover .shortcut-recorder,.shortcut-recorder:focus,.shortcut-recorder.recording {opacity: 1;@@ -158,17 +157,12 @@}}- /* On mobile, stack each row so the shortcut editor sits underneath the action label.- OptionsRow keeps these rows inline because they contain .icon-action buttons. */+ /* On mobile, stack each segment so the shortcut editor sits underneath the action label. A card+ option only stacks itself for a button or a slider, and this is neither. */body.mobile & {- .option-row {+ .tn-card-option {flex-direction: column;align-items: stretch;- gap: 8px;- }-- .option-row-input {- width: 100%;}.shortcut-editor {diff --git a/apps/client/src/widgets/type_widgets/options/shortcuts.filter.spec.tsx b/apps/client/src/widgets/type_widgets/options/shortcuts.filter.spec.tsxnew file mode 100644index 0000000000..43c7f4ca8f--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/shortcuts.filter.spec.tsx@@ -0,0 +1,140 @@+import type { KeyboardShortcut } from "@triliumnext/commons";+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++/** The shortcuts the page is handed, in the shape the server sends: separators name the categories. */+const SHORTCUTS = vi.hoisted(() => ([+ { separator: "Note navigation" },+ {+ actionName: "backInNoteHistory",+ friendlyName: "Back in note history",+ description: "Goes back to the previously visited note.",+ effectiveShortcuts: [ "Alt+Left" ],+ defaultShortcuts: [ "Alt+Left" ],+ scope: "window"+ },+ {+ actionName: "jumpToNote",+ friendlyName: "Jump to note",+ effectiveShortcuts: [ "Ctrl+J" ],+ defaultShortcuts: [ "Ctrl+J" ],+ scope: "window"+ },+ { separator: "Editing" },+ {+ actionName: "addLinkToText",+ friendlyName: "Add link",+ effectiveShortcuts: [ "Ctrl+L" ],+ defaultShortcuts: [ "Ctrl+L" ],+ scope: "text-detail"+ }+] as KeyboardShortcut[]));++vi.mock("../../../services/server", () => ({+ default: { get: vi.fn(async () => SHORTCUTS) }+}));++// i18next is never initialised here and answers `undefined` until it is, which would make every+// assertion about a placeholder true of any string at all.+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));++// Stubbed for the note context it would otherwise need, but its second row is rendered: the filter+// box lives there, and it is what these cases drive.+vi.mock("./components/OptionsPageHeader", () => ({+ default: ({ below }: { below?: preact.ComponentChildren }) => <div className="header-stub">{below}</div>+}));++vi.mock("../../react/hooks", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../react/hooks")>()),+ useStaticTooltip: vi.fn()+}));++import ShortcutSettings from "./shortcuts";++let host: HTMLElement;++beforeEach(async () => {+ host = document.body.appendChild(document.createElement("div"));+ await act(async () => {+ render(<ShortcutSettings />, host);+ });+});++afterEach(() => {+ render(null, host);+ document.body.innerHTML = "";+});++/** The categories on show, each read as its heading. */+const categories = () =>+ [ ...host.querySelectorAll(".tn-card-heading") ].map((heading) => heading.textContent);++/** The shortcuts on show, each read as the name leading its segment's label. */+const shortcuts = () =>+ [ ...host.querySelectorAll(".tn-card-option-label") ].map((label) => label.firstChild?.textContent);++/** Types into the filter box, as a keystroke rather than an assignment. */+async function filterBy(text: string) {+ const box = host.querySelector<HTMLInputElement>(".header-stub input");+ expect(box).not.toBeNull();++ await act(async () => {+ if (box) {+ box.value = text;+ box.dispatchEvent(new Event("input", { bubbles: true }));+ }+ });+}++describe("the shortcuts list", () => {+ it("gives each category a card and each shortcut a segment of it", () => {+ expect(categories()).toEqual([ "Note navigation", "Editing" ]);+ expect(shortcuts()).toEqual([ "Back in note history", "Jump to note", "Add link" ]);+ });+});++describe("filtering the shortcuts", () => {+ it("keeps what matches the typed text, and the category it was filed under", async () => {+ await filterBy("jump");++ expect(categories()).toEqual([ "Note navigation" ]);+ expect(shortcuts()).toEqual([ "Jump to note" ]);+ });++ it("matches on the key combination as well as on the name", async () => {+ await filterBy("ctrl+l");++ expect(categories()).toEqual([ "Editing" ]);+ expect(shortcuts()).toEqual([ "Add link" ]);+ });++ it("matches on the description, which is the only place some wording appears", async () => {+ await filterBy("previously visited");++ expect(shortcuts()).toEqual([ "Back in note history" ]);+ });++ it("drops a category once nothing in it matches", async () => {+ await filterBy("note");++ // "Add link" is in neither its name, its description nor its combination.+ expect(categories()).toEqual([ "Note navigation" ]);+ expect(shortcuts()).toEqual([ "Back in note history", "Jump to note" ]);+ });++ it("says so rather than showing an empty card when nothing matches at all", async () => {+ await filterBy("nothing matches this");++ expect(categories()).toEqual([]);+ expect(host.querySelector(".no-items")?.textContent).toContain("shortcuts.no_results");+ });++ it("brings everything back when the text is cleared", async () => {+ await filterBy("jump");+ await filterBy("");++ expect(categories()).toEqual([ "Note navigation", "Editing" ]);+ expect(shortcuts()).toEqual([ "Back in note history", "Jump to note", "Add link" ]);+ });+});diff --git a/apps/client/src/widgets/type_widgets/options/shortcuts.tsx b/apps/client/src/widgets/type_widgets/options/shortcuts.tsxindex aaca7b1cc5..db0de1fe8c 100644--- a/apps/client/src/widgets/type_widgets/options/shortcuts.tsx+++ b/apps/client/src/widgets/type_widgets/options/shortcuts.tsx@@ -16,6 +16,7 @@ import { arrayEqual, isElectron, isMobile, reloadFrontendApp } from "../../../seimport ActionButton from "../../react/ActionButton";import { Badge } from "../../react/Badge";import Button from "../../react/Button";+import { Card, CardOption } from "../../react/Card";import Dropdown from "../../react/Dropdown";import { FormDropdownDivider, FormListItem } from "../../react/FormList";import FormTextBox from "../../react/FormTextBox";@@ -23,8 +24,6 @@ import { useStaticTooltip, useTriliumEvent } from "../../react/hooks";import { TooltipIcon } from "../../react/Icon";import NoItems from "../../react/NoItems";import OptionsPageHeader from "./components/OptionsPageHeader";-import OptionsRow from "./components/OptionsRow";-import OptionsSection from "./components/OptionsSection";export default function ShortcutSettings() {const [ keyboardShortcuts, setKeyboardShortcuts ] = useState<KeyboardShortcut[]>([]);@@ -116,32 +115,16 @@ export default function ShortcutSettings() {return (<><OptionsPageHeader- actions={- <div className="shortcut-header-buttons">- {conflictCount > 0 &&- <Badge- className={`shortcut-conflicts-badge ${activeFilter === "conflicts" ? "active" : ""}`}- icon="bx bx-error-circle"- text={t("shortcuts.conflicts_badge", { count: conflictCount })}- tooltip={t("shortcuts.conflicts_badge_tooltip")}- outline- onClick={() => setActiveFilter(activeFilter === "conflicts" ? null : "conflicts")}- />}- <Button- text={t("shortcuts.reload_app")}- // Called rather than handed over: its one argument is the reason to be- // logged for the reload, and passed straight to the button that would- // have been the click event.- onClick={() => reloadFrontendApp()}- size="micro"- />- <Button- text={t("shortcuts.set_all_to_default")}- onClick={resetShortcuts}- size="micro"- />- </div>- }+ actions={conflictCount > 0 && (+ <Badge+ className={`shortcut-conflicts-badge ${activeFilter === "conflicts" ? "active" : ""}`}+ icon="bx bx-error-circle"+ text={t("shortcuts.conflicts_badge", { count: conflictCount })}+ tooltip={t("shortcuts.conflicts_badge_tooltip")}+ outline+ onClick={() => setActiveFilter(activeFilter === "conflicts" ? null : "conflicts")}+ />+ )}below={<div className="shortcut-header-filter"><FormTextBox@@ -166,6 +149,20 @@ export default function ShortcutSettings() {modifiedCount={modifiedCount}/></Dropdown>++ <Button+ text={t("shortcuts.reload_app")}+ // Called rather than handed over: its one argument is the reason to be+ // logged for the reload, and passed straight to the button that would+ // have been the click event.+ onClick={() => reloadFrontendApp()}+ size="micro"+ />+ <Button+ text={t("shortcuts.set_all_to_default")}+ onClick={resetShortcuts}+ size="micro"+ /></div>}/>@@ -173,11 +170,13 @@ export default function ShortcutSettings() {<div className="shortcuts-options-section">{filteredGroups.length > 0? filteredGroups.map((group) => (- <OptionsSection key={group.title} title={group.title}>- {group.actions.map((action) => (- <ShortcutRow key={action.actionName} action={action} conflicts={conflicts.get(action.actionName)} />- ))}- </OptionsSection>+ <div key={group.title} className="options-section">+ <Card heading={group.title}>+ {group.actions.map((action) => (+ <ShortcutRow key={action.actionName} action={action} conflicts={conflicts.get(action.actionName)} />+ ))}+ </Card>+ </div>)): filter? (@@ -429,10 +428,13 @@ export function filterKeyboardAction(action: ActionKeyboardShortcut, filter: str(action.description && action.description.toLowerCase().includes(filter));}+/**+ * Deliberately unnamed, so the label is not tied to a control: what stands on the trailing edge is a+ * set of chips and buttons rather than one input, and a `for` naming any of them would be wrong.+ */function ShortcutRow({ action, conflicts }: { action: ActionKeyboardShortcut; conflicts?: ShortcutConflicts }) {return (- <OptionsRow- name={action.actionName}+ <CardOptionlabel={<>{isShortcutModified(action) &&@@ -443,7 +445,7 @@ function ShortcutRow({ action, conflicts }: { action: ActionKeyboardShortcut; codescription={action.description}><ShortcutEditor keyboardShortcut={action} conflicts={conflicts} />- </OptionsRow>+ </CardOption>);}