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(segmented choice): let an option carry its count as a badge
Elian Dorand3ccdbd071bc
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 84e3de3180..5bdb8dc0a3 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1479,8 +1479,8 @@"owning_note": "Owning note: ","upload_attachments": "Upload attachments","no_attachments": "This note has no attachments.",- "group_user": "Yours ({{total}})",- "group_system": "System ({{total}})",+ "group_user": "Yours",+ "group_system": "System","no_attachments_in_group": "No attachments of this kind."},"book": {diff --git a/apps/client/src/widgets/react/SegmentedChoice.css b/apps/client/src/widgets/react/SegmentedChoice.cssnew file mode 100644index 0000000000..3c7fc71a33--- /dev/null+++ b/apps/client/src/widgets/react/SegmentedChoice.css@@ -0,0 +1,29 @@+/*+ * How much an option holds, shown after its name.+ *+ * Bootstrap's `.badge`, which the theme already dresses in a half-transparent fill (see+ * `--badge-background-color`) — the reason it is the right pill here rather than `.ext-badge`, whose+ * fill is a solid colour of the caller's choosing: the segment underneath it is a recessed track on+ * one option and a raised chip on the other, and a transparent fill sits on both without being told+ * which it is on.+ */+/* The name and its count, kept on one line: the two are read as a single label, and the group is free+ to make a segment narrower than the pair. */+.tn-segmented-choice .tn-segmented-choice-label {+ white-space: nowrap;+}++.tn-segmented-choice .tn-segmented-choice-count {+ /* Centred on the text rather than on the button: `middle` measures from the baseline in the font's+ own units, so the pill stays put as the label's size changes. */+ vertical-align: middle;+ /* Bootstrap rounds a badge to the same radius as a card; these are single digits beside a word,+ and want the pill shape the app's other badges have. */+ border-radius: var(--badge-radius, 12px);+ /* The theme uppercases badge text for the words most of them hold. Digits have no case, but the+ letter-spacing it comes with sits a number off-centre in its own pill. */+ letter-spacing: 0;+ /* `.badge` carries a lead margin for the sentences it usually trails; this one sits against a+ single word inside a button. */+ margin-inline-start: 6px;+}diff --git a/apps/client/src/widgets/react/SegmentedChoice.spec.tsx b/apps/client/src/widgets/react/SegmentedChoice.spec.tsxnew file mode 100644index 0000000000..da9df79f14--- /dev/null+++ b/apps/client/src/widgets/react/SegmentedChoice.spec.tsx@@ -0,0 +1,59 @@+import { render } from "preact";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import SegmentedChoice from "./SegmentedChoice";++describe("SegmentedChoice", () => {+ let container: HTMLDivElement;++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ const options = (extra?: { count?: number }) => [+ { value: "user" as const, label: "Yours", ...extra },+ { value: "system" as const, label: "System", count: extra?.count === undefined ? undefined : 7 }+ ];++ it("offers one button per option, marking the current one", () => {+ render(<SegmentedChoice options={options()} currentValue="system" onChange={() => {}} />, container);++ const buttons = [ ...container.querySelectorAll("button") ];+ expect(buttons.map((button) => button.textContent?.trim())).toStrictEqual([ "Yours", "System" ]);+ expect(buttons.map((button) => button.classList.contains("active"))).toStrictEqual([ false, true ]);+ });++ it("shows a count as a badge beside the name rather than inside it", () => {+ render(<SegmentedChoice options={options({ count: 3 })} currentValue="user" onChange={() => {}} />, container);++ const badges = [ ...container.querySelectorAll(".tn-segmented-choice-count") ];+ expect(badges.map((badge) => badge.textContent)).toStrictEqual([ "3", "7" ]);+ // The name is the label alone: a caller that has moved its count out of the string should not+ // find it written back into one.+ expect(badges[0]?.parentElement?.textContent?.trim()).toBe("Yours3");+ });++ it("shows a count of zero, and no badge at all where there is no count", () => {+ // An option offering nothing is worth saying so — and a badge that came and went with the last+ // item would resize the group under the pointer.+ render(<SegmentedChoice options={options({ count: 0 })} currentValue="user" onChange={() => {}} />, container);+ expect(container.querySelector(".tn-segmented-choice-count")?.textContent).toBe("0");++ render(<SegmentedChoice options={options()} currentValue="user" onChange={() => {}} />, container);+ expect(container.querySelectorAll(".tn-segmented-choice-count")).toHaveLength(0);+ });++ it("reports the option that was pressed", () => {+ const onChange = vi.fn();+ render(<SegmentedChoice options={options({ count: 3 })} currentValue="user" onChange={onChange} />, container);++ container.querySelectorAll("button")[1].click();+ expect(onChange).toHaveBeenCalledWith("system");+ });+});diff --git a/apps/client/src/widgets/react/SegmentedChoice.tsx b/apps/client/src/widgets/react/SegmentedChoice.tsxindex ea3adec395..55ec28b756 100644--- a/apps/client/src/widgets/react/SegmentedChoice.tsx+++ b/apps/client/src/widgets/react/SegmentedChoice.tsx@@ -1,9 +1,12 @@+import "./SegmentedChoice.css";+import clsx from "clsx";+import SimpleBadge from "./Badge";import Button, { ButtonGroup } from "./Button";interface SegmentedChoiceProps<T extends string> {- options: { value: T, label: string }[];+ options: SegmentedChoiceOption<T>[];/*** Kept a plain string rather than {@link T}: callers routinely hold the value as a raw option* string, and a value outside the options simply highlights nothing.@@ -13,17 +16,42 @@ interface SegmentedChoiceProps<T extends string> {className?: string;}+export interface SegmentedChoiceOption<T extends string> {+ value: T;+ label: string;+ /**+ * How much the option holds, shown as a badge after its name.+ *+ * For a choice between views of the same things, where the size of the one not on show is part of+ * the decision to look at it — and where writing it into the label instead ("Yours (3)") reads as+ * part of the name rather than as a quantity. Zero is a count like any other and is shown: an+ * option offering nothing is worth saying so, and hiding it would leave the group's widths moving+ * as the last item goes.+ */+ count?: number;+}+/*** A row of buttons acting as one exclusive choice, the current one highlighted — for switching* between a few named views or sections where a dropdown would hide the alternatives.*/export default function SegmentedChoice<T extends string>({ options, currentValue, onChange, className }: SegmentedChoiceProps<T>) {return (- <ButtonGroup size="sm" className={className}>- {options.map(({ value, label }) => (+ <ButtonGroup size="sm" className={clsx("tn-segmented-choice", className)}>+ {options.map(({ value, label, count }) => (<Buttonkey={value}- text={label}+ // Name and count share one inline box, rather than being two children of the+ // button: the button is a flex row, so a badge left as a child of its own is laid+ // out against the row's centre line instead of against the text, and lands a+ // pixel above it. Inside a line box it aligns to the text itself, in the text's+ // own units.+ text={count !== undefined ? (+ <span class="tn-segmented-choice-label">+ {label}+ <SimpleBadge className="tn-segmented-choice-count" title={count} />+ </span>+ ) : label}size="small"className={clsx(currentValue === value && "active")}onClick={() => onChange(value)}diff --git a/apps/client/src/widgets/type_widgets/Attachment.tsx b/apps/client/src/widgets/type_widgets/Attachment.tsxindex b77e2ae811..e47c6008c2 100644--- a/apps/client/src/widgets/type_widgets/Attachment.tsx+++ b/apps/client/src/widgets/type_widgets/Attachment.tsx@@ -75,10 +75,9 @@ export function AttachmentList({ note }: TypeWidgetProps) {}/**- * Which half of the list is on show. Both halves are named with their size, so the group not being- * looked at still says how much is in it — the point of the switcher being that a note can carry far- * more of the app's own attachments than of the reader's, and neither number is guessable from the- * other's list.+ * Which half of the list is on show. Both halves carry a count, so the group not being looked at still+ * says how much is in it — the point of the switcher being that a note can carry far more of the app's+ * own attachments than of the reader's, and neither number is guessable from the other's list.*/function AttachmentGroupChoice({ groups, currentGroup, onChange }: {groups: Record<AttachmentGroup, FAttachment[]>,@@ -89,8 +88,8 @@ function AttachmentGroupChoice({ groups, currentGroup, onChange }: {<div className="attachment-group-choice"><SegmentedChoiceoptions={[- { value: "user", label: t("attachment_list.group_user", { total: groups.user.length }) },- { value: "system", label: t("attachment_list.group_system", { total: groups.system.length }) }+ { value: "user", label: t("attachment_list.group_user"), count: groups.user.length },+ { value: "system", label: t("attachment_list.group_system"), count: groups.system.length }]}currentValue={currentGroup}onChange={onChange}