diff --git a/src/components/RefFilter.tsx b/src/components/RefFilter.tsx new file mode 100644 index 0000000..6a342fa --- /dev/null +++ b/src/components/RefFilter.tsx @@ -0,0 +1,48 @@ +import { Show } from "solid-js"; + +import type { Refs } from "../lib/refs"; + +/** + * Narrowing the sidebar down. + * + * A `search` input rather than a plain text one: it carries the right + * semantics, and browsers give it a clear affordance for free. Escape is + * handled explicitly because whether it clears the field is left to the + * browser otherwise, and WebKit and Chromium do not agree. + */ +export default function RefFilter(props: { refs: Refs }) { + function onKeyDown(event: KeyboardEvent) { + if (event.key !== "Escape") return; + + event.preventDefault(); + props.refs.setQuery(""); + } + + return ( +
+ + props.refs.setQuery(event.currentTarget.value)} + onKeyDown={onKeyDown} + class="w-full rounded-small border border-outline bg-surface px-2 py-1 text-body-sm text-on-surface focus-visible:outline-2 focus-visible:outline-offset-[-1px] focus-visible:outline-primary" + /> + + {/* An is a polite live region, so the result of typing is + announced without stealing focus from the field. */} + + + {props.refs.counts().matched} of {props.refs.counts().total} match + + +
+ ); +} diff --git a/src/components/RepositoryNav.tsx b/src/components/RepositoryNav.tsx index 2907cdf..9457063 100644 --- a/src/components/RepositoryNav.tsx +++ b/src/components/RepositoryNav.tsx @@ -1,7 +1,8 @@ import { For, Show } from "solid-js"; import type { RefEntry } from "../lib/bindings"; -import type { Refs } from "../lib/refs"; +import { highlight, type Refs } from "../lib/refs"; +import RefFilter from "./RefFilter"; /** * The repository's references. @@ -20,63 +21,128 @@ export default function RepositoryNav(props: { return ( ); } -function Section(props: { title: string; entries: RefEntry[]; head?: string; isOpen: boolean }) { +function Section(props: { + title: string; + entries: RefEntry[]; + head?: string; + refs: Refs; + isOpen: boolean; +}) { const headingId = () => `refs-${props.title.toLowerCase()}`; + /** How many there are, and — while filtering — of how many. */ + const count = () => { + if (!props.refs.isFiltering()) return `${props.entries.length}`; + + const all = props.refs.entries().filter((entry) => kindOf(props.title) === entry.kind); + + return `${props.entries.length} of ${all.length}`; + }; + return ( -
  • -

    - {props.title} - 0}> - {/* A count is worth having when a repository has hundreds of remote + // While filtering, a section with nothing left in it is dropped entirely. + // "None" would read as "this repository has no tags" when what is true is + // "no tags match what you typed". + 0}> +
  • +

    + {props.title} + 0}> + {/* A count is worth having when a repository has hundreds of remote branches and the list below is mostly off screen. */} - - {props.entries.length} - - -

    + {count()} + +
  • - 0} - fallback={ -

    {props.isOpen ? "None" : "—"}

    - } - > - -
    -
  • + 0} + fallback={ +

    {props.isOpen ? "None" : "—"}

    + } + > + +
    + + ); } + +/** Which ref kind a section heading stands for. */ +function kindOf(title: string): RefEntry["kind"] { + switch (title) { + case "Remotes": + return "remoteBranch"; + case "Tags": + return "tag"; + default: + return "localBranch"; + } +} diff --git a/src/lib/refs.ts b/src/lib/refs.ts index 74ab19e..0be216c 100644 --- a/src/lib/refs.ts +++ b/src/lib/refs.ts @@ -43,13 +43,66 @@ export function groupRefs(entries: RefEntry[]): GroupedRefs { }; } +/** + * Keep the refs whose shorthand contains `query`, ignoring case. + * + * A plain substring match rather than anything fuzzy: it is predictable, and a + * person can see why a result appeared without having to learn the rules. The + * shorthand is what the sidebar shows, so it is what gets matched — searching + * text that is not on screen would be a surprise. + */ +export function filterRefs(entries: RefEntry[], query: string): RefEntry[] { + const wanted = query.trim().toLowerCase(); + if (!wanted) return entries; + + return entries.filter((entry) => entry.shorthand.toLowerCase().includes(wanted)); +} + +/** A run of text, and whether the filter matched it. */ +export type Segment = { text: string; matched: boolean }; + +/** + * Split text into matched and unmatched runs, so the matches can be marked. + * + * Done by scanning rather than with a regular expression, which would mean + * escaping whatever the user typed — a branch name can contain `.` and `+`, + * and `*` would otherwise throw. + */ +export function highlight(text: string, query: string): Segment[] { + const wanted = query.trim().toLowerCase(); + if (!wanted) return [{ text, matched: false }]; + + const haystack = text.toLowerCase(); + const segments: Segment[] = []; + let cursor = 0; + + for (;;) { + const found = haystack.indexOf(wanted, cursor); + if (found === -1) break; + + if (found > cursor) segments.push({ text: text.slice(cursor, found), matched: false }); + segments.push({ text: text.slice(found, found + wanted.length), matched: true }); + cursor = found + wanted.length; + } + + if (cursor < text.length) segments.push({ text: text.slice(cursor), matched: false }); + + return segments; +} + export function createRefs() { const [entries, setEntries] = createSignal([]); + const [query, setQuery] = createSignal(""); const [message, setMessage] = createSignal(); + const matching = () => filterRefs(entries(), query()); + /** Load a repository's refs, replacing whatever was shown before. */ async function show(id: RepositoryId) { setMessage(undefined); + // A filter written for one repository almost never means anything in the + // next, and leaving it on would make a full sidebar look empty. + setQuery(""); try { setEntries(await listReferences(id)); @@ -62,10 +115,31 @@ export function createRefs() { function clear() { setEntries([]); + setQuery(""); setMessage(undefined); } - return { entries, grouped: () => groupRefs(entries()), message, show, clear }; + return { + entries, + query, + setQuery, + /** Grouped and sorted, with the filter applied. */ + grouped: () => groupRefs(matching()), + /** How many refs the filter kept, of how many there are worth showing. */ + counts: () => { + const shown = groupRefs(matching()); + const all = groupRefs(entries()); + + return { + matched: shown.branches.length + shown.remotes.length + shown.tags.length, + total: all.branches.length + all.remotes.length + all.tags.length, + }; + }, + isFiltering: () => query().trim().length > 0, + message, + show, + clear, + }; } export type Refs = ReturnType; diff --git a/tests/e2e/sidebar.spec.ts b/tests/e2e/sidebar.spec.ts index 34b3ad4..6e597be 100644 --- a/tests/e2e/sidebar.spec.ts +++ b/tests/e2e/sidebar.spec.ts @@ -1,4 +1,4 @@ -import { expect, test } from "@playwright/test"; +import { expect, test, type Page } from "@playwright/test"; import { linearHistory, reference } from "../fixtures/rows"; import { mockTauri, openRepository, sidebarSection } from "./tauri"; @@ -126,3 +126,117 @@ test.describe("sidebar", () => { await expect(sidebarSection(page, "Remotes")).toHaveCount(400); }); }); + +/** Open a repository with a busy set of refs and hand back the filter field. */ +async function withRefs(page: Page, references = REFERENCES) { + await mockTauri(page, { rows: linearHistory(10), references, chooseFolder: "/demo" }); + await page.goto("/"); + await openRepository(page); + await expect(sidebarSection(page, "Branches").first()).toBeVisible(); + + return page.getByRole("searchbox", { name: "Filter references" }); +} + +test.describe("filtering", () => { + test("offers a filter only once there is a repository to filter", async ({ page }) => { + await mockTauri(page, { rows: [], references: REFERENCES, chooseFolder: "/demo" }); + await page.goto("/"); + + await expect(page.getByRole("searchbox", { name: "Filter references" })).toBeHidden(); + + await openRepository(page); + + await expect(page.getByRole("searchbox", { name: "Filter references" })).toBeVisible(); + }); + + test("narrows branches, remotes and tags together", async ({ page }) => { + const filter = await withRefs(page); + + await filter.fill("main"); + + await expect(sidebarSection(page, "Branches")).toHaveText(["current branch: main"]); + await expect(sidebarSection(page, "Remotes")).toHaveText(["origin/main"]); + // Nothing in Tags matched, so the section goes rather than saying "None". + await expect(page.getByRole("heading", { name: /^Tags/u })).toBeHidden(); + }); + + test("says how much survived, in each section and altogether", async ({ page }) => { + const filter = await withRefs(page); + + await filter.fill("feature"); + + await expect(page.getByRole("heading", { name: "Branches 1 of 2" })).toBeVisible(); + await expect(page.getByRole("navigation", { name: "Repository" })).toContainText( + "2 of 6 match", + ); + }); + + test("marks the part of each name that matched", async ({ page }) => { + const filter = await withRefs(page); + + await filter.fill("graph"); + + await expect(page.getByRole("navigation", { name: "Repository" }).locator("mark")).toHaveText([ + "graph", + "graph", + ]); + }); + + test("says so once when nothing matches", async ({ page }) => { + const filter = await withRefs(page); + + await filter.fill("no-such-branch"); + + await expect(page.getByText("Nothing matches")).toBeVisible(); + await expect(page.getByRole("heading", { name: /^Branches/u })).toBeHidden(); + }); + + test("puts everything back when cleared", async ({ page }) => { + const filter = await withRefs(page); + await filter.fill("main"); + await expect(page.getByRole("heading", { name: /^Tags/u })).toBeHidden(); + + await filter.fill(""); + + await expect(sidebarSection(page, "Tags")).toHaveText(["v1.0.0", "v2.0.0"]); + await expect(page.getByRole("navigation", { name: "Repository" }).locator("mark")).toHaveCount( + 0, + ); + }); + + test("clears on Escape, in both engines", async ({ page }) => { + // Whether a search input clears itself on Escape is left to the browser, + // and WebKit and Chromium disagree — so it is handled explicitly. + const filter = await withRefs(page); + await filter.fill("main"); + + await filter.press("Escape"); + + await expect(filter).toHaveValue(""); + await expect(sidebarSection(page, "Tags")).toHaveText(["v1.0.0", "v2.0.0"]); + }); + + test("makes a repository with hundreds of refs usable", async ({ page }) => { + // The reason this exists: 400 entries is a scroll, 3 is a list. + const many = Array.from({ length: 400 }, (_, index) => + reference(`origin/branch-${index}`, "remoteBranch"), + ); + const filter = await withRefs(page, [reference("main"), ...many]); + await expect(sidebarSection(page, "Remotes")).toHaveCount(400); + + await filter.fill("branch-17"); + + // branch-17, branch-170 through branch-179. + await expect(sidebarSection(page, "Remotes")).toHaveCount(11); + }); + + test("keeps the filter reachable by keyboard alone", async ({ page }) => { + const filter = await withRefs(page); + + await filter.focus(); + await page.keyboard.type("tags"); + + await expect(filter).toBeFocused(); + await expect(filter).toHaveValue("tags"); + }); +}); diff --git a/tests/unit/refs.test.ts b/tests/unit/refs.test.ts index 1c8ab72..1dd89dc 100644 --- a/tests/unit/refs.test.ts +++ b/tests/unit/refs.test.ts @@ -1,7 +1,7 @@ import { flush } from "solid-js"; import { beforeEach, describe, expect, test, vi } from "vitest"; -import { createRefs, groupRefs } from "../../src/lib/refs"; +import { createRefs, filterRefs, groupRefs, highlight } from "../../src/lib/refs"; import { reference } from "../fixtures/rows"; const listReferences = vi.fn(async () => [reference("main"), reference("v1.0.0", "tag")]); @@ -77,6 +77,117 @@ describe("groupRefs", () => { }); }); +describe("filterRefs", () => { + const REFS = [ + reference("main"), + reference("feature/graph"), + reference("origin/main", "remoteBranch"), + reference("v1.0.0", "tag"), + ]; + + test("keeps everything when nothing was typed", () => { + expect(filterRefs(REFS, "")).toHaveLength(4); + expect(filterRefs(REFS, " ")).toHaveLength(4); + }); + + test("keeps refs whose name contains what was typed", () => { + expect(filterRefs(REFS, "main").map((entry) => entry.shorthand)).toEqual([ + "main", + "origin/main", + ]); + }); + + test("ignores case, because nobody wants to match a branch name exactly", () => { + expect(filterRefs(REFS, "MAIN")).toHaveLength(2); + expect(filterRefs([reference("Feature/Thing")], "feature")).toHaveLength(1); + }); + + test("ignores surrounding space, which is easy to type by accident", () => { + expect(filterRefs(REFS, " main ")).toHaveLength(2); + }); + + test("matches anywhere in the name, not only at the start", () => { + expect(filterRefs(REFS, "graph").map((entry) => entry.shorthand)).toEqual(["feature/graph"]); + }); + + test("treats what was typed as text, not as a pattern", () => { + // A regular expression would throw on this, or match far too much. + const refs = [reference("release/v1.0"), reference("release/v1x0")]; + + expect(filterRefs(refs, "v1.0").map((entry) => entry.shorthand)).toEqual(["release/v1.0"]); + expect(filterRefs(refs, "*")).toHaveLength(0); + expect(filterRefs(refs, "(")).toHaveLength(0); + }); + + test("keeps nothing when nothing contains it", () => { + expect(filterRefs(REFS, "nowhere")).toEqual([]); + }); + + test("does not mutate what it was given", () => { + const refs = [reference("zebra"), reference("alpha")]; + + filterRefs(refs, "a"); + + expect(refs).toHaveLength(2); + }); +}); + +describe("highlight", () => { + test("returns the text untouched when nothing is being filtered", () => { + expect(highlight("main", "")).toEqual([{ text: "main", matched: false }]); + }); + + test("splits around a match", () => { + expect(highlight("feature/graph", "graph")).toEqual([ + { text: "feature/", matched: false }, + { text: "graph", matched: true }, + ]); + }); + + test("keeps the original casing of what it marks", () => { + // Matching ignores case, but the name must still read as it is stored. + expect(highlight("Feature/Graph", "graph")).toEqual([ + { text: "Feature/", matched: false }, + { text: "Graph", matched: true }, + ]); + }); + + test("marks every occurrence", () => { + expect(highlight("release/release-notes", "release")).toEqual([ + { text: "release", matched: true }, + { text: "/", matched: false }, + { text: "release", matched: true }, + { text: "-notes", matched: false }, + ]); + }); + + test("marks a match at the very start and the very end", () => { + expect(highlight("main", "main")).toEqual([{ text: "main", matched: true }]); + expect(highlight("origin/main", "main")).toEqual([ + { text: "origin/", matched: false }, + { text: "main", matched: true }, + ]); + }); + + test("leaves text alone when there is no match in it", () => { + expect(highlight("main", "zzz")).toEqual([{ text: "main", matched: false }]); + }); + + test("handles text that is entirely one repeated match", () => { + expect(highlight("aaa", "a")).toHaveLength(3); + }); + + test("puts the text back together exactly as it was", () => { + for (const query of ["a", "e", "feature", "/", "zzz", ""]) { + const rebuilt = highlight("feature/a-feature", query) + .map((segment) => segment.text) + .join(""); + + expect(rebuilt).toBe("feature/a-feature"); + } + }); +}); + describe("createRefs", () => { test("starts empty and asks for nothing", () => { const refs = createRefs(); @@ -120,6 +231,30 @@ describe("createRefs", () => { expect(refs.entries()).toEqual([]); }); + test("forgets the filter when another repository opens", async () => { + // A filter written for one repository rarely means anything in the next, + // and leaving it on would make a full sidebar look empty. + const refs = createRefs(); + await refs.show("/first/.git"); + refs.setQuery("feature"); + await flush(); + + await refs.show("/second/.git"); + await flush(); + + expect(refs.query()).toBe(""); + expect(refs.isFiltering()).toBe(false); + }); + + test("counts what matched against what there is", async () => { + const refs = createRefs(); + await refs.show("/demo/.git"); + refs.setQuery("main"); + await flush(); + + expect(refs.counts()).toEqual({ matched: 1, total: 2 }); + }); + test("reports a failure without leaving stale refs on screen", async () => { // Showing another repository's branches would be worse than showing none. const refs = createRefs(); diff --git a/tests/unit/repository-nav.test.tsx b/tests/unit/repository-nav.test.tsx index 0058847..8377ad2 100644 --- a/tests/unit/repository-nav.test.tsx +++ b/tests/unit/repository-nav.test.tsx @@ -1,23 +1,37 @@ import { render } from "@solidjs/testing-library"; -import { createSignal, flush } from "solid-js"; -import { describe, expect, test, vi } from "vitest"; +import { flush } from "solid-js"; +import { beforeEach, describe, expect, test, vi } from "vitest"; import RepositoryNav from "../../src/components/RepositoryNav"; import type { RefEntry } from "../../src/lib/bindings"; -import { groupRefs, type Refs } from "../../src/lib/refs"; +import { createRefs, type Refs } from "../../src/lib/refs"; import { reference } from "../fixtures/rows"; -/** A stand-in for the store, so these tests never touch IPC. */ -function store(entries: RefEntry[]): Refs { - const [current] = createSignal(entries); - - return { - entries: current, - grouped: () => groupRefs(current()), - message: () => undefined, - show: vi.fn(), - clear: vi.fn(), - } as unknown as Refs; +/** What the mocked backend will hand over next. */ +let available: RefEntry[] = []; + +vi.mock("../../src/lib/api", () => ({ + listReferences: async () => available, +})); + +beforeEach(() => { + available = []; +}); + +/** + * The real store, loaded with the given refs. + * + * Using the real one rather than a hand-written stand-in means these tests + * exercise the actual grouping and filtering, and cannot drift from it. + */ +async function loaded(entries: RefEntry[], query = ""): Promise { + available = entries; + const refs = createRefs(); + await refs.show("/demo/.git"); + if (query) refs.setQuery(query); + await flush(); + + return refs; } /** The entries under a given heading. */ @@ -37,14 +51,16 @@ const REFS = [ describe("RepositoryNav", () => { test("is a labelled landmark, so it can be jumped to", async () => { - const { getByRole } = render(() => ); + const refs = await loaded([]); + const { getByRole } = render(() => ); await flush(); expect(getByRole("navigation", { name: "Repository" })).toBeTruthy(); }); test("lists branches, remotes and tags under their own headings", async () => { - const { container } = render(() => ); + const refs = await loaded(REFS); + const { container } = render(() => ); await flush(); expect(section(container, "branches")).toEqual(["feature/graph", "main"]); @@ -53,8 +69,8 @@ describe("RepositoryNav", () => { }); test("counts what is in each section", async () => { - // Worth having when a repository has hundreds of remote branches. - const { getByRole } = render(() => ); + const refs = await loaded(REFS); + const { getByRole } = render(() => ); await flush(); expect(getByRole("heading", { name: "Branches 2" })).toBeTruthy(); @@ -62,14 +78,16 @@ describe("RepositoryNav", () => { }); test("shows no count for a section with nothing in it", async () => { - const { getByRole } = render(() => ); + const refs = await loaded([reference("main")]); + const { getByRole } = render(() => ); await flush(); expect(getByRole("heading", { name: "Tags" })).toBeTruthy(); }); test("marks the checked out branch in words, not just colour", async () => { - const { container } = render(() => ); + const refs = await loaded(REFS); + const { container } = render(() => ); await flush(); const branches = section(container, "branches"); @@ -79,48 +97,128 @@ describe("RepositoryNav", () => { }); test("marks nothing when HEAD is detached", async () => { - // headBranch gives undefined for a detached or unborn HEAD. - const { container } = render(() => ); + const refs = await loaded(REFS); + const { container } = render(() => ); await flush(); expect(section(container, "branches").join(" ")).not.toContain("current branch"); }); - test("does not confuse a remote branch that ends with the branch name", async () => { - const { container } = render(() => ( - - )); - await flush(); - - expect(section(container, "remotes")).toEqual(["origin/main"]); - }); - test("says a section is empty when a repository is open", async () => { - const { container } = render(() => ); + const refs = await loaded([reference("main")]); + const { container } = render(() => ); await flush(); expect(container.textContent).toContain("None"); }); test("says nothing definite before a repository is open", async () => { - // "None" would be a claim about a repository that has not been read. - const { container } = render(() => ); + const refs = await loaded([]); + const { container } = render(() => ); await flush(); expect(container.textContent).not.toContain("None"); }); test("keeps the full ref name available for a truncated entry", async () => { - const { container } = render(() => ( - - )); + const refs = await loaded([reference("feature/a-very-long-branch-name")]); + const { container } = render(() => ); await flush(); const entry = container.querySelector('ul[aria-labelledby="refs-branches"] li'); expect(entry?.getAttribute("title")).toBe("refs/heads/feature/a-very-long-branch-name"); }); }); + +describe("RepositoryNav filtering", () => { + test("offers a filter once a repository is open", async () => { + const refs = await loaded(REFS); + const { getByLabelText } = render(() => ); + await flush(); + + expect(getByLabelText("Filter references")).toBeTruthy(); + }); + + test("offers no filter before there is anything to filter", async () => { + const refs = await loaded([]); + const { queryByLabelText } = render(() => ); + await flush(); + + expect(queryByLabelText("Filter references")).toBeNull(); + }); + + test("narrows every section at once, not just one", async () => { + // A branch, a remote and a tag all containing "main". + const refs = await loaded(REFS, "main"); + const { container } = render(() => ); + await flush(); + + expect(section(container, "branches")).toEqual(["main"]); + expect(section(container, "remotes")).toEqual(["origin/main"]); + expect(container.querySelector('ul[aria-labelledby="refs-tags"]')).toBeNull(); + }); + + test("shows how much of each section survived the filter", async () => { + const refs = await loaded(REFS, "main"); + const { getByRole } = render(() => ); + await flush(); + + expect(getByRole("heading", { name: "Branches 1 of 2" })).toBeTruthy(); + }); + + test("announces how many matched altogether", async () => { + const refs = await loaded(REFS, "main"); + const { container } = render(() => ); + await flush(); + + // An is a polite live region, so this is spoken as it changes. + expect(container.querySelector("output")?.textContent).toContain("2 of 5 match"); + }); + + test("marks the part that matched", async () => { + const refs = await loaded([reference("feature/graph")], "graph"); + const { container } = render(() => ); + await flush(); + + const marked = [...container.querySelectorAll("mark")].map((node) => node.textContent); + expect(marked).toEqual(["graph"]); + }); + + test("marks every occurrence, not only the first", async () => { + const refs = await loaded([reference("release/release-notes")], "release"); + const { container } = render(() => ); + await flush(); + + expect(container.querySelectorAll("mark")).toHaveLength(2); + }); + + test("marks nothing when nothing is being filtered", async () => { + const refs = await loaded(REFS); + const { container } = render(() => ); + await flush(); + + expect(container.querySelectorAll("mark")).toHaveLength(0); + }); + + test("says so once, rather than three times, when nothing matches", async () => { + const refs = await loaded(REFS, "nothing-like-this"); + const { container } = render(() => ); + await flush(); + + expect(container.textContent).toContain("Nothing matches"); + expect(container.textContent).not.toContain("None"); + expect(container.querySelectorAll("h2")).toHaveLength(0); + }); + + test("puts everything back when the filter is cleared", async () => { + const refs = await loaded(REFS, "main"); + const { container } = render(() => ); + await flush(); + + refs.setQuery(""); + await flush(); + + expect(section(container, "tags")).toEqual(["v1.0.0", "v2.0.0"]); + expect(container.querySelectorAll("mark")).toHaveLength(0); + }); +});