Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(issue-views): settle overflow fitting before updating state (#9409)
epolevov-nsp8724fcf9815f
diff --git a/packages/views/common/single-row-fit.ts b/packages/views/common/single-row-fit.tsindex 9bcc4d0c37..9216d4dc3e 100644--- a/packages/views/common/single-row-fit.ts+++ b/packages/views/common/single-row-fit.ts@@ -14,11 +14,11 @@ import { useCallback, useLayoutEffect, useRef, useState } from "react";* never depends on what is currently mounted for real — no feedback* loop between measurement and rendering.*- * Rule: the longest prefix that fits alongside `reserve` px of trailing- * chrome wins. `reserve` must cover everything that is ALWAYS rendered- * after the items (triggers, menus) — it is subtracted even when every- * item fits, otherwise a row that exactly fits its items clips the- * chrome off the end.+ * Rule: the longest prefix that fits alongside its trailing chrome wins.+ * `reserve` returns the chrome width for a candidate fit count, including+ * permanent menus even when every item fits. Resolve both from the same+ * measurement before updating state, so overflow controls cannot feed a+ * stale fit back into a later render.** Remeasures on container resize (ResizeObserver) and after every* commit (labels/items change the mirror); state only updates when the@@ -33,8 +33,8 @@ export function useSingleRowFit({count: number;/** Horizontal gap between items in px (the container's `gap`). */gap: number;- /** Width in px to hold back for the overflow trigger. */- reserve: number;+ /** Trailing chrome width in px for a candidate number of fitting items. */+ reserve: (fitCount: number) => number;}) {const containerRef = useRef<HTMLDivElement | null>(null);const measureRef = useRef<HTMLDivElement | null>(null);@@ -49,19 +49,17 @@ export function useSingleRowFit({(child) => (child as HTMLElement).offsetWidth,);- let used = 0;- let next = 0;- for (let i = 0; i < widths.length; i++) {- const withItem = used + (i > 0 ? gap : 0) + widths[i]!;- if (withItem + gap + reserve > available) break;- used = withItem;- next = i + 1;+ let next = widths.length;+ let used =+ widths.reduce((sum, width) => sum + width, 0) + Math.max(0, next - 1) * gap;+ while (next > 0 && used + gap + reserve(next) > available) {+ next--;+ used -= widths[next]! + (next > 0 ? gap : 0);}setFitCount((current) => (current === next ? current : next));}, [gap, reserve]);// After every commit: the mirror just re-rendered with current labels.- // eslint-disable-next-line react-hooks/exhaustive-deps -- deliberate every-commit measure; the setState inside is change-guardeduseLayoutEffect(() => {recompute();});diff --git a/packages/views/issues/components/view-bar.test.tsx b/packages/views/issues/components/view-bar.test.tsxnew file mode 100644index 0000000000..54eafc5cad--- /dev/null+++ b/packages/views/issues/components/view-bar.test.tsx@@ -0,0 +1,192 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, cleanup, screen } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { createAuthStore, registerAuthStore } from "@multica/core/auth";+import type { ApiClient } from "@multica/core/api/client";+import { IssueViewSchema, type IssueView } from "@multica/core/api/schemas";+import { issueViewPrefKeys } from "@multica/core/issue-views/preferences";+import { workspaceKeys } from "@multica/core/workspace/queries";+import { renderWithI18n } from "../../test/i18n";+import { ViewBar, type ViewBarBuiltin } from "./view-bar";++vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "ws-1",+}));++const scope = { scope_type: "project" as const, scope_id: "project-1" };+const builtins: ViewBarBuiltin[] = [+ { key: "all", label: "All issues", active: true, onSelect: vi.fn() },+ { key: "board", label: "Board", active: false, onSelect: vi.fn() },+ { key: "timeline", label: "Timeline", active: false, onSelect: vi.fn() },+];+const views = [+ IssueViewSchema.parse({ id: "view-1", name: "My issues" }),+ IssueViewSchema.parse({ id: "view-2", name: "Recently updated" }),+];++let queryClient: QueryClient;+let containerWidth: number;+const resizeObservers = new Set<TestResizeObserver>();++class TestResizeObserver {+ private targets = new Set<Element>();++ constructor(private callback: ResizeObserverCallback) {+ resizeObservers.add(this);+ }++ observe(target: Element) {+ this.targets.add(target);+ }++ unobserve(target: Element) {+ this.targets.delete(target);+ }++ disconnect() {+ resizeObservers.delete(this);+ }++ notify(target: Element) {+ if (this.targets.has(target)) {+ this.callback(+ [{ target } as ResizeObserverEntry],+ this as unknown as ResizeObserver,+ );+ }+ }+}++function renderBar({+ initialViews = views,+ activeView = null,+ viewsReady = true,+}: {+ initialViews?: IssueView[];+ activeView?: IssueView | null;+ viewsReady?: boolean;+} = {}) {+ const props = {+ wsId: "ws-1",+ scope,+ builtins,+ activeView,+ onSelectView: vi.fn(),+ onNewView: vi.fn(),+ onEditView: vi.fn(),+ };+ const result = renderWithI18n(+ <QueryClientProvider client={queryClient}>+ <ViewBar {...props} views={initialViews} viewsReady={viewsReady} />+ </QueryClientProvider>,+ );+ return {+ ...result,+ loadViews: () => result.rerender(+ <QueryClientProvider client={queryClient}>+ <ViewBar {...props} views={views} viewsReady />+ </QueryClientProvider>,+ ),+ resize: (width: number) => {+ act(() => {+ containerWidth = width;+ for (const observer of resizeObservers) {+ observer.notify(result.container.firstElementChild!);+ }+ });+ },+ };+}++beforeEach(() => {+ registerAuthStore(+ createAuthStore({+ api: {} as ApiClient,+ storage: {+ getItem: () => null,+ setItem: () => {},+ removeItem: () => {},+ },+ }),+ );+ queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false, staleTime: Infinity, gcTime: Infinity },+ },+ });+ queryClient.setQueryData(workspaceKeys.members("ws-1"), []);+ queryClient.setQueryData(issueViewPrefKeys.scope("ws-1", scope), {+ scope_type: "project",+ scope_id: scope.scope_id,+ prefs: {+ hidden: [],+ order: [+ ...builtins.map((item) => `builtin:${item.key}`),+ ...views.map((view) => `view:${view.id}`),+ ],+ },+ updated_at: "",+ });+ // Five 100px tabs fit with the permanent menu, but not with an overflow+ // trigger: 5 * 100 + 5 * 4 + 36 <= 570 < 5 * 100 + 5 * 4 + 68.+ containerWidth = 570;+ vi.stubGlobal("ResizeObserver", TestResizeObserver);+ vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockImplementation(+ () => containerWidth,+ );+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(100);+});++afterEach(() => {+ cleanup();+ queryClient.clear();+ resizeObservers.clear();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe("ViewBar fitting", () => {+ it("settles when saved views load at the overflow boundary", () => {+ const { loadViews } = renderBar({ initialViews: [], viewsReady: false });+ expect(loadViews).not.toThrow();++ for (const item of [...builtins, ...views.map((view) => ({ label: view.name }))]) {+ expect(screen.getByRole("button", { name: item.label })).toBeInTheDocument();+ }+ expect(screen.queryByRole("button", { name: "More views" })).not.toBeInTheDocument();+ });++ it("restores all tabs when the container grows past the overflow boundary", () => {+ containerWidth = 400;+ const { resize } = renderBar();++ expect(screen.getByRole("button", { name: "More views" })).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: views[0]!.name })).not.toBeInTheDocument();++ resize(570);++ for (const item of [...builtins, ...views.map((view) => ({ label: view.name }))]) {+ expect(screen.getByRole("button", { name: item.label })).toBeInTheDocument();+ }+ expect(screen.queryByRole("button", { name: "More views" })).not.toBeInTheDocument();+ });++ it("keeps the active overflowed view available by name", () => {+ containerWidth = 450;+ renderBar({ activeView: views[1]! });++ expect(screen.getByRole("button", { name: "All issues" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Board" })).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Timeline" })).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: views[1]!.name })).toBeInTheDocument();+ });++ it("keeps overflow controls available when no tab fits", () => {+ containerWidth = 80;+ renderBar();++ expect(screen.getByRole("button", { name: "More views" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Views" })).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "All issues" })).not.toBeInTheDocument();+ });+});diff --git a/packages/views/issues/components/view-bar.tsx b/packages/views/issues/components/view-bar.tsxindex e69b04ea1e..bdb04eded4 100644--- a/packages/views/issues/components/view-bar.tsx+++ b/packages/views/issues/components/view-bar.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useQuery } from "@tanstack/react-query";import {DndContext,@@ -273,34 +273,27 @@ export function ViewBar({);// --- single-row fit ------------------------------------------------------ // The reserve feeds back into the fit, but only ever grows when items- // fall out (the "more" trigger appears, then the promoted active tab- // widens it), which shrinks the fit further and keeps them out — the- // settle is monotonic in both directions.const activeBarId = activeView ? `view:${activeView.id}` : null;- const [reserveTier, setReserveTier] = useState<"menu" | "more" | "promoted">(- "menu",+ const activeIndex = visible.findIndex((item) => item.barItemId === activeBarId);+ const reserve = useCallback(+ (fittingCount: number) =>+ activeIndex >= fittingCount+ ? RESERVE_PROMOTED+ : fittingCount < visible.length+ ? RESERVE_MORE+ : RESERVE_MENU,+ [activeIndex, visible.length],);const { containerRef, measureRef, fitCount } = useSingleRowFit({count: visible.length,gap: 4,- reserve:- reserveTier === "promoted"- ? RESERVE_PROMOTED- : reserveTier === "more"- ? RESERVE_MORE- : RESERVE_MENU,+ reserve,});const fitting = visible.slice(0, fitCount);const overflowed = visible.slice(fitCount);const activeOverflowed =!!activeBarId && overflowed.some((item) => item.barItemId === activeBarId);- useEffect(() => {- setReserveTier(- activeOverflowed ? "promoted" : overflowed.length > 0 ? "more" : "menu",- );- }, [activeOverflowed, overflowed.length]);- const promoted = reserveTier === "promoted" && activeOverflowed;+ const promoted = activeOverflowed;const savePrefs = (next: { hidden: string[]; order: string[] }) => {// A drag can land before the views list has loaded; pruning against an