refactor(chips): share the chip-overflow measure core between the two lanes (S3)

ActiveFilterChips (feed applied-filter row) and ChannelTagsControl both
hand-rolled the same single-line chip-fit measurer: a hidden mirror + a
layout-effect + ResizeObserver reading chip right edges, the real rem gap,
the pill width and the lane width. The policy half was already extracted
(decideChipLayout); the DOM-measurement half was still duplicated.

Promote that half to useChipOverflowFit(rowRef, chipsRef, pillRef, deps,
decide, initial): it owns the effect + observer + initial measure and reads
the common geometry, then hands it to each caller's own policy. The feed
row layers its leading label + trailing "Clear all" reservation on top and
keeps decideChipLayout; the tag cell's chips-only policy is extracted as
fitChipsWithPill (pure, unit-tested) alongside it. Add a jsdom test for the
hook (stubbed offsets, re-measure on deps). Behaviour unchanged — verified
in the browser: feed all/count modes + popover, tag "+N" fit + hover reveal.
This commit is contained in:
2026-08-23 23:22:52 +02:00
parent 9538fb1b7a
commit fc32188fd2
6 changed files with 313 additions and 109 deletions
+27 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
import { decideChipLayout, type ChipFitInput } from "./chipOverflow";
import { decideChipLayout, fitChipsWithPill, type ChipFitInput } from "./chipOverflow";
// Build measurer-style right edges for `n` chips of a fixed width, starting after a label, with a gap.
function rights(labelRight: number, widths: number[], gap: number): number[] {
@@ -91,3 +91,29 @@ describe("decideChipLayout", () => {
expect(decideChipLayout(input)).toEqual({ mode: "count", visible: 0 });
});
});
describe("fitChipsWithPill", () => {
// Three chips of width 50, gap 6, starting at 0 -> right edges 50, 106, 162.
const chipRights = rights(0, [50, 50, 50], 6);
it("shows all chips (no pill) when the last chip's right edge fits — the whole-set fast path", () => {
expect(fitChipsWithPill({ chipRights, pillW: 40, gap: 6, avail: 200 })).toBe(3);
});
it("returns 0 for an empty chip set", () => {
expect(fitChipsWithPill({ chipRights: [], pillW: 40, gap: 6, avail: 200 })).toBe(0);
});
it("reserves the pill width for all but the last chip when overflowing", () => {
// avail 120: whole set (162) doesn't fit. chip0 right 50 <= 120-(40+6)=74 ok; chip1 right 106 > 74
// -> dropped at i=1 -> visible 1.
expect(fitChipsWithPill({ chipRights, pillW: 40, gap: 6, avail: 120 })).toBe(1);
});
it("keeps the whole set via the fast path even when a reserve-for-all loop would drop chips", () => {
// Right edges 56, 112, 118; avail 120: the whole set fits (118 <= 120). A naive loop that reserves
// pill+gap (46) for every non-last chip would drop at chip1 (112 > 120-46=74) and show "+2" beside
// empty space — the fast path returns all 3 instead.
expect(fitChipsWithPill({ chipRights: [56, 112, 118], pillW: 40, gap: 6, avail: 120 })).toBe(3);
});
});
+44 -8
View File
@@ -1,11 +1,13 @@
// Pure fit decision for a single-line chip lane that must share its width with fixed trailing
// controls (the feed's applied-filter row + Sort/View). Lifted out of ActiveFilterChips so the
// all/some/count math is unit-testable without a layout engine (jsdom reports 0-width boxes), the
// same split as lib/dateFilter and lib/columnSort. The caller measures real widths off a hidden
// mirror (including the live rem gap, so nothing is frozen in px) and hands them here.
//
// A sibling one-line-fit measurer lives in ChannelTags (ChannelTagsControl); if a third appears,
// promote the DOM-measurement half to a shared hook and keep this as its policy core.
// Pure fit decisions for a single-line chip lane that collapses its overflow into a "+N" pill.
// Lifted out of the components so the math is unit-testable without a layout engine (jsdom reports
// 0-width boxes), the same split as lib/dateFilter and lib/columnSort. The shared DOM-measurement
// half — the layout-effect + ResizeObserver that reads real rem boxes off a hidden mirror — lives in
// lib/useChipOverflowFit; it hands the measured geometry to one of these policies:
// - decideChipLayout: the feed's applied-filter row, which also shares its width with fixed trailing
// controls (Sort/View), reserves a leading label + a trailing "Clear all", and collapses to a
// single count pill on a narrow lane.
// - fitChipsWithPill: the chips-only channel tag cell (ChannelTagsControl) — just "how many fit
// before the +N pill".
export interface ChipFitInput {
/** Number of chips. */
@@ -51,3 +53,37 @@ export function decideChipLayout(p: ChipFitInput): ChipFit {
if (k === 0 && labelRight + gap + plusW > avail) return { mode: "count", visible: 0 };
return { mode: "some", visible: k };
}
// The chips-only policy (ChannelTagsControl): how many chips fit on the line, reserving the "+N" pill's
// width whenever any overflow. Returns the visible count.
export interface ChipsWithPillInput {
/** Right edge (offsetLeft + offsetWidth) of each chip, index-aligned. */
chipRights: number[];
/** Width of the "+N" pill. */
pillW: number;
/** Available lane width. */
avail: number;
/** The real (rem-scaled) inter-item gap. */
gap: number;
}
export function fitChipsWithPill(p: ChipsWithPillInput): number {
const { chipRights, pillW, avail, gap } = p;
const n = chipRights.length;
if (n === 0) return 0;
// Whole-set fast path: if the LAST chip's right edge already fits, every chip fits and NO pill is
// needed. The reservation loop below reserves the pill for every chip except the last and breaks at
// the first overflow, so on its own it would collapse a short trailing chip (narrower than the pill)
// that would actually have fitted, leaving "+N" beside empty space.
if ((chipRights[n - 1] ?? 0) <= avail) return n;
let count = n;
for (let i = 0; i < n; i++) {
const right = chipRights[i] ?? 0;
const moreAfter = i < n - 1;
if (right > avail - (moreAfter ? pillW + gap : 0)) {
count = i;
break;
}
}
return count;
}
@@ -0,0 +1,102 @@
// @vitest-environment jsdom
//
// The shared chip-overflow measure core (S3). jsdom has no layout engine — every offset* / clientWidth
// is 0 — so we stub those on the real ref'd nodes and assert the hook (a) reads the geometry off them
// (chip right edges, pill width, the gap between the last chip and the pill, and the lane's available
// width), (b) returns the caller's `decide` result, and (c) re-measures when `deps` changes.
import { describe, it, expect, afterEach } from "vitest";
import { useRef } from "react";
import { render, screen, cleanup, act } from "@testing-library/react";
import { useChipOverflowFit, type ChipRowGeometry } from "./useChipOverflowFit";
function stub(
el: HTMLElement,
props: Partial<Record<"offsetLeft" | "offsetWidth" | "clientWidth", number>>,
) {
for (const [k, v] of Object.entries(props)) {
Object.defineProperty(el, k, { configurable: true, get: () => v });
}
}
let lastGeom: ChipRowGeometry | null = null;
function Harness({ deps }: { deps: string }) {
const rowRef = useRef<HTMLDivElement | null>(null);
const chipRefs = useRef<Array<HTMLElement | null>>([]);
const pillRef = useRef<HTMLSpanElement | null>(null);
const visible = useChipOverflowFit<number>({
rowRef,
chipsRef: chipRefs,
pillRef,
deps,
initial: -1,
decide: (g) => {
lastGeom = g;
// A trivial policy: count the chips whose right edge fits the lane.
return g.chipRights.filter((r) => r <= g.avail).length;
},
});
return (
<div>
<div ref={rowRef} data-testid="row" />
<span
ref={(el) => {
chipRefs.current[0] = el;
}}
data-testid="chip0"
/>
<span
ref={(el) => {
chipRefs.current[1] = el;
}}
data-testid="chip1"
/>
<span ref={pillRef} data-testid="pill" />
<div data-testid="visible">{visible}</div>
</div>
);
}
afterEach(() => {
cleanup();
lastGeom = null;
});
describe("useChipOverflowFit", () => {
it("reads geometry off the refs and returns the decide() result; re-measures on deps change", () => {
const { rerender } = render(<Harness deps="a" />);
// First pass ran against jsdom's 0-sized boxes.
expect(lastGeom).toEqual({ avail: 0, chipRights: [0, 0], pillW: 0, gap: 0 });
// Give the boxes real geometry, then bump deps to force a re-measure.
stub(screen.getByTestId("row"), { clientWidth: 100 });
stub(screen.getByTestId("chip0"), { offsetLeft: 0, offsetWidth: 30 }); // right edge 30
stub(screen.getByTestId("chip1"), { offsetLeft: 36, offsetWidth: 30 }); // right edge 66
stub(screen.getByTestId("pill"), { offsetLeft: 72, offsetWidth: 20 }); // gap = 72 - 66 = 6
act(() => {
rerender(<Harness deps="b" />);
});
expect(lastGeom).toEqual({ avail: 100, chipRights: [30, 66], pillW: 20, gap: 6 });
// decide counted both chips (30 and 66 both <= 100).
expect(screen.getByTestId("visible").textContent).toBe("2");
});
it("drops a chip whose right edge exceeds the lane, via the caller's policy", () => {
const { rerender } = render(<Harness deps="a" />);
stub(screen.getByTestId("row"), { clientWidth: 40 });
stub(screen.getByTestId("chip0"), { offsetLeft: 0, offsetWidth: 30 }); // right edge 30 <= 40
stub(screen.getByTestId("chip1"), { offsetLeft: 36, offsetWidth: 30 }); // right edge 66 > 40
stub(screen.getByTestId("pill"), { offsetLeft: 72, offsetWidth: 20 });
act(() => {
rerender(<Harness deps="b" />);
});
expect(lastGeom).toEqual({ avail: 40, chipRights: [30, 66], pillW: 20, gap: 6 });
// Only chip0 (right edge 30) fits the 40-wide lane; chip1 (66) is dropped by the policy.
expect(screen.getByTestId("visible").textContent).toBe("1");
});
});
+79
View File
@@ -0,0 +1,79 @@
import { useLayoutEffect, useRef, useState, type RefObject } from "react";
// The shared DOM-measure-and-fit core for a single-line chip lane that collapses its overflow into a
// trailing "+N" pill. Owns the layout-effect + ResizeObserver + initial-measure wiring and reads the
// common geometry off a hidden mirror (each chip's right edge, the real rem gap, the pill width, and
// the lane's available width); each caller layers its OWN fit policy in `decide` and gets that result
// back. This was hand-rolled twice — the feed's applied-filter row (ActiveFilterChips, whose policy
// also reserves a leading label + a trailing "Clear all" and can collapse to a single count pill) and
// the channel tag cell (ChannelTagsControl, chips-only) — with the same measurement half copied in
// both. The policy halves live in lib/chipOverflow.ts; this owns the measurement half.
//
// Coordinate note: `chipRights` are offsets within the hidden mirror (its children's offsetParent),
// while `avail` is the VISIBLE lane's clientWidth — the two are comparable because the mirror is laid
// out `absolute left-0 top-0` over the lane's start, so a mirror-relative right edge is the position a
// chip would take in the real lane. Reads real rem boxes, so nothing is frozen in px (the text-size
// slider scales the gap and chip widths, and the fit follows).
export interface ChipRowGeometry {
/** Available lane width — the visible row's clientWidth. */
avail: number;
/** Right edge (offsetLeft + offsetWidth) of each chip in the measurer, index-aligned to the chips. */
chipRights: number[];
/** Width of the trailing sample "+N" pill in the measurer. */
pillW: number;
/** The real rendered inter-item gap (rem-scaled), read off the box between the last chip and the pill. */
gap: number;
}
export function useChipOverflowFit<R>(args: {
/** The VISIBLE lane; its clientWidth is the available width, and resize is observed on it. */
rowRef: RefObject<HTMLElement | null>;
/** The measurer's chip elements, index-aligned (a hidden mirror of the full chip set). */
chipsRef: RefObject<Array<HTMLElement | null>>;
/** The sample "+N" pill in the measurer. */
pillRef: RefObject<HTMLElement | null>;
/** Re-measure when this changes (a key over the chip set — count + labels, so a rename re-fits too). */
deps: unknown;
/** The caller's fit policy over the measured geometry. */
decide: (geom: ChipRowGeometry) => R;
/** Value used until the first measure (and while the refs aren't mounted). */
initial: R;
}): R {
const { rowRef, chipsRef, pillRef, deps, decide, initial } = args;
const [result, setResult] = useState<R>(initial);
// Read `decide` fresh each run without making it an effect dependency: the effect re-runs on `deps`
// (and resize), and a caller's decide closure is rebuilt every render — depending on it would
// resubscribe the ResizeObserver on every render.
const decideRef = useRef(decide);
decideRef.current = decide;
useLayoutEffect(() => {
const row = rowRef.current;
const pill = pillRef.current;
if (!row || !pill) return;
const rightOf = (el: HTMLElement | null | undefined) =>
el ? el.offsetLeft + el.offsetWidth : 0;
const run = () => {
const chips = (chipsRef.current ?? []).filter((c): c is HTMLElement => c != null);
const lastChip = chips[chips.length - 1];
setResult(
decideRef.current({
avail: row.clientWidth,
chipRights: chips.map(rightOf),
pillW: pill.offsetWidth,
gap: lastChip ? Math.max(0, pill.offsetLeft - rightOf(lastChip)) : 0,
}),
);
};
run();
// jsdom has no ResizeObserver — the one-shot measure above still runs there (unit tests drive it).
if (typeof ResizeObserver === "undefined") return;
const ro = new ResizeObserver(run);
ro.observe(row);
return () => ro.disconnect();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [deps]);
return result;
}