Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 30 additions & 20 deletions site/client/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { type ColumnDef, createSortedRowModel, rowSortingFeature, tableFeatures,
import { entitiesText, entityTotal, sizeText, type Dimensions } from "../dimensions";
import { listingColumnWidths } from "../listing-columns";
import { matchingGroups, orderGroups, type GroupLink, type GroupOrder } from "../group-index";
import { EMPTY_LISTING_QUERY, FACETS, initialListingQuery, listingLocation, mapFacets, matchesFacets, parseListingQuery, type Facet, type FacetValues, type ListingQuery } from "../listing-query";
import { EMPTY_LISTING_QUERY, FACETS, facetValueCounts, initialListingQuery, listingLocation, mapFacets, matchesFacets, parseListingQuery, type Facet, type FacetValues, type ListingQuery } from "../listing-query";
import { siteRoot } from "./site-root";
import "../styles.css";

Expand Down Expand Up @@ -92,26 +92,26 @@ const FACET_CONTROLS: Readonly<Record<Facet, { readonly label: string; readonly
};

/**
* One attribute's options: every value a record holds, labelled with how many records hold it, and every value the query already chose, so a value from a shared link that no record holds still shows as chosen and can be removed.
* @param records - Every record.
* One attribute's options: every value a record holds, and every value the query already chose, so a value from a shared link that no record holds still shows as chosen and can be cleared. Each is labelled with how many records it would add to the listing given the other filters, and, where that differs, how many hold it in all.
* @param totals - How many of every record hold each value.
* @param relative - How many of the records the other filters admit hold each value.
* @param facet - The attribute.
* @param chosen - The values already chosen.
* @returns The chosen values first, then the rest, each group in the attribute's order.
* @returns The chosen values first, then the rest, each group in the attribute's order (by total, so an option does not move as the other filters change).
*/
function facetOptions(records: readonly SearchRecord[], facet: Facet, chosen: readonly string[]): { value: string; label: string }[] {
const counts = new Map<string, number>(chosen.map((value) => [value, 0]));
for (const record of records) {
for (const value of new Set(heldBy(record)[facet])) {
counts.set(value, (counts.get(value) ?? 0) + 1);
}
}
const byLabel = [...counts].sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));

function facetOptions(totals: ReadonlyMap<string, number>, relative: ReadonlyMap<string, number>, facet: Facet, chosen: readonly string[]): { value: string; label: string }[] {
const values = new Map<string, number>([...chosen.map((value): [string, number] => [value, 0]), ...totals]);
const byLabel = [...values].sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
const ordered = FACET_CONTROLS[facet].byCount ? byLabel.sort(([, left], [, right]) => right - left) : byLabel;
const picked = new Set(chosen);
const label = (value: string, total: number): string => {
const shown = relative.get(value) ?? 0;

return shown === total ? `${value} (${String(total)})` : `${value} (${String(shown)} of ${String(total)})`;
};

// The chosen values lead, in the attribute's own order, so they sit where a finger or the keyboard lands first and a click on one clears it.
return [...ordered.filter(([value]) => picked.has(value)), ...ordered.filter(([value]) => !picked.has(value))].map(([value, count]) => ({ value, label: `${value} (${String(count)})` }));
return [...ordered.filter(([value]) => picked.has(value)), ...ordered.filter(([value]) => !picked.has(value))].map(([value, total]) => ({ value, label: label(value, total) }));
}

/** Where a listing sits: the path back to the site root, the page's own filter as a query string (absent on the home listing), and the page's and the home listing's paths. */
Expand Down Expand Up @@ -165,15 +165,12 @@ function Listing({ records, place }: { readonly records: readonly SearchRecord[]
};
}, [place]);

const options = useMemo(() => mapFacets((facet) => facetOptions(records, facet, query.facets[facet])), [records, query.facets]);

const filtered = useMemo(() => {
// What the free text and the entity bounds admit; the attributes narrow this further, and each attribute's options are counted against the other attributes' choices over this set.
const scoped = useMemo(() => {
const needle = query.text.trim().toLowerCase();

return records.filter((record) => {
if (!matchesFacets(heldBy(record), query.facets)) {
return false;
}
if (!within(entityTotal(record), query.minEntities, query.maxEntities)) {
return false;
}
Expand All @@ -184,7 +181,20 @@ function Listing({ records, place }: { readonly records: readonly SearchRecord[]

return haystack.some((field) => field.toLowerCase().includes(needle));
});
}, [records, query]);
}, [records, query.text, query.minEntities, query.maxEntities]);
const filtered = useMemo(() => scoped.filter((record) => matchesFacets(heldBy(record), query.facets)), [scoped, query.facets]);

const totals = useMemo(() => {
const held = records.map(heldBy);

return mapFacets((facet) => facetValueCounts(held, facet, EMPTY_LISTING_QUERY.facets));
}, [records]);
const options = useMemo(() => {
const held = scoped.map(heldBy);

return mapFacets((facet) => facetOptions(totals[facet], facetValueCounts(held, facet, query.facets), facet, query.facets[facet]));
}, [scoped, totals, query.facets]);


// Column definitions are written as plain literals against the hook's own column type, not built through createColumnHelper: the helper infers each accessor over its own value type, which does not inter-type with the widened union under exactOptionalPropertyTypes. The order matches the static table's Name, Id, Kind, Domain so the two views of the listing read the same way.
const columns: readonly ColumnDef<ListingFeatures, SearchRecord>[] = [
Expand Down
21 changes: 21 additions & 0 deletions site/e2e/site.browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,27 @@ test("choosing a filter value adds a history entry, typing does not, and Back an
expect((await shownOf(page)).shown).toBeLessThan(graphs.shown);
});

test("a dropdown counts each option against the other filters, and says how many there are in all when that differs", async ({ page }) => {
await page.goto("/");
const subject = page.getByRole("combobox", { name: "Subject", exact: true });
await subject.click();
const unfiltered = await page.getByRole("option").allInnerTexts();
expect(unfiltered.every((text) => !text.includes(" of "))).toBe(true);
await page.keyboard.press("Escape");

await page.goto("/?kind=graph");
await subject.click();
const narrowed = await page.getByRole("option").allInnerTexts();
const counted = narrowed.map((text) => /^(.*) \((?:(\d+) of )?(\d+)\)$/.exec(text.replaceAll("\n", " ")));
expect(counted.every((match) => match !== null)).toBe(true);
const partial = counted.filter((match) => match?.[2] !== undefined);
expect(partial.length).toBeGreaterThan(0);
expect(partial.every((match) => Number(match?.[2]) < Number(match?.[3]))).toBe(true);
// The listing's own total is the sum of the filtered rows, so no option can claim more than the page holds.
const { shown } = await shownOf(page);
expect(counted.every((match) => Number(match?.[2] ?? match?.[3]) <= shown)).toBe(true);
});

test("a chosen value leads its dropdown, ticked, and a click on it clears it", async ({ page }) => {
await page.goto("/?kind=resources");
const kind = page.getByRole("combobox", { name: "Kind", exact: true });
Expand Down
22 changes: 22 additions & 0 deletions site/listing-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,25 @@ export function listingLocation(query: ListingQuery, own: string | undefined, he
export function matchesFacets(held: FacetValues, facets: FacetValues): boolean {
return FACETS.every((facet) => facets[facet].length === 0 || facets[facet].some((value) => held[facet].includes(value)));
}

/**
* How many of some records hold each value of one attribute, given the choices made in the other attributes: the number an option would add to the listing if it were chosen alongside what is already chosen. The attribute's own choices are not applied, since several values of one attribute are alternatives, so each of its options is counted against the same other filters.
* @param held - What each record holds, already narrowed by every filter that is not an attribute (free text, entity bounds).
* @param facet - The attribute whose options are counted.
* @param facets - The values chosen for every attribute.
* @returns For each value some record holds, how many of the records the other attributes admit hold it.
*/
export function facetValueCounts(held: readonly FacetValues[], facet: Facet, facets: FacetValues): ReadonlyMap<string, number> {
const others = { ...facets, [facet]: [] };
const counts = new Map<string, number>();
for (const record of held) {
if (!matchesFacets(record, others)) {
continue;
}
for (const value of new Set(record[facet])) {
counts.set(value, (counts.get(value) ?? 0) + 1);
}
}

return counts;
}
24 changes: 23 additions & 1 deletion site/listing-query.unit.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { EMPTY_LISTING_QUERY, facetQuery, initialListingQuery, listingLocation, matchesFacets, parseListingQuery, serialiseListingQuery, type ListingQuery } from "./listing-query";
import { EMPTY_LISTING_QUERY, facetQuery, facetValueCounts, initialListingQuery, listingLocation, matchesFacets, parseListingQuery, serialiseListingQuery, type FacetValues, type ListingQuery } from "./listing-query";

const full: ListingQuery = {
text: "lead time & cost",
Expand Down Expand Up @@ -84,3 +84,25 @@ describe("where a listing starts and what link it writes", () => {
expect(listingLocation(EMPTY_LISTING_QUERY, own, "/keepset/tags/weight/", "/keepset/")).toBe("/keepset/");
});
});

describe("facetValueCounts", () => {
const record = (kind: string, domain: string, subjects: readonly string[]): FacetValues => ({ ...EMPTY_LISTING_QUERY.facets, kind: [kind], domain: [domain], subject: subjects });
const held = [record("graph", "Social", ["a", "b"]), record("graph", "Academic", ["a"]), record("table", "Academic", ["c"])];

it("counts every value against all records when nothing is chosen", () => {
expect([...facetValueCounts(held, "subject", EMPTY_LISTING_QUERY.facets)]).toEqual([["a", 2], ["b", 1], ["c", 1]]);
});

it("counts a value against the other attributes' choices only", () => {
const counts = facetValueCounts(held, "subject", { ...EMPTY_LISTING_QUERY.facets, domain: ["Social"] });
expect(counts.get("a")).toBe(1);
expect(counts.get("b")).toBe(1);
expect(counts.get("c")).toBeUndefined();
});

it("does not apply the attribute's own choices, so its alternatives are counted alike", () => {
const counts = facetValueCounts(held, "subject", { ...EMPTY_LISTING_QUERY.facets, subject: ["c"], domain: ["Academic"] });
expect(counts.get("a")).toBe(1);
expect(counts.get("c")).toBe(1);
});
});
Loading