diff --git a/src/components/adjustments/AdjustmentForm.wiring.test.ts b/src/components/adjustments/AdjustmentForm.wiring.test.ts index 661315b..1db8eb7 100644 --- a/src/components/adjustments/AdjustmentForm.wiring.test.ts +++ b/src/components/adjustments/AdjustmentForm.wiring.test.ts @@ -6,12 +6,13 @@ // mounted form, and the test calls the props the form hands to each // CategoryCombobox and to its buttons, then renders again to read the lines. import { describe, it, expect, vi, beforeEach } from "vitest"; -import { isValidElement, type ReactElement, type ReactNode } from "react"; +import type { ReactNode } from "react"; vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig())); vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock()); import { hookHarness } from "../../test/hookHarness"; +import { find } from "../../test/elementTree"; import AdjustmentForm from "./AdjustmentForm"; import CategoryCombobox from "../shared/CategoryCombobox"; import type { Category } from "../../shared/types"; @@ -19,15 +20,6 @@ import type { AdjustmentFormData, EntryFormData } from "../../hooks/useAdjustmen const harness = hookHarness(); -type Props = Record & { children?: ReactNode }; - -function find(node: ReactNode, match: (el: ReactElement) => boolean): ReactElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, match)); - if (!isValidElement(node)) return []; - const el = node as ReactElement; - return [...(match(el) ? [el] : []), ...find(el.props.children, match)]; -} - /** Text of an element's children, elements left out. */ const text = (node: ReactNode): string => Array.isArray(node) ? node.map(text).join("") : typeof node === "string" ? node : ""; diff --git a/src/components/balance/LinkTransfersModal.wiring.test.ts b/src/components/balance/LinkTransfersModal.wiring.test.ts index acd9e53..10c1265 100644 --- a/src/components/balance/LinkTransfersModal.wiring.test.ts +++ b/src/components/balance/LinkTransfersModal.wiring.test.ts @@ -7,7 +7,7 @@ // filter, and `commit()` runs the effect that reloads the transactions. // `createPortal` is the identity and `document` a stub: the window is a portal. import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from "vitest"; -import { isValidElement, type ReactElement, type ReactNode } from "react"; +import type { ReactNode } from "react"; vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig())); vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock()); @@ -24,21 +24,13 @@ vi.mock("../../services/balance.service", () => ({ })); import { hookHarness } from "../../test/hookHarness"; +import { find } from "../../test/elementTree"; import LinkTransfersModal from "./LinkTransfersModal"; import CategoryCombobox from "../shared/CategoryCombobox"; import type { Category } from "../../shared/types"; const harness = hookHarness(); -type Props = Record & { children?: ReactNode }; - -function find(node: ReactNode, type: unknown): ReactElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, type)); - if (!isValidElement(node)) return []; - const el = node as ReactElement; - return [...(el.type === type ? [el] : []), ...find(el.props.children, type)]; -} - const TRANSFERS: Category = { id: 7, name: "Virements", @@ -61,7 +53,7 @@ const PROPS = { /** One render of the mounted window; its category filter. */ const filter = () => { - const [combobox] = find(harness.render(() => LinkTransfersModal(PROPS)), CategoryCombobox); + const [combobox] = find(harness.render(() => LinkTransfersModal(PROPS)), (el) => el.type === CategoryCombobox); return combobox.props; }; diff --git a/src/components/categories/HierarchyCheckModal.wiring.test.ts b/src/components/categories/HierarchyCheckModal.wiring.test.ts index 6c087a1..14b5fee 100644 --- a/src/components/categories/HierarchyCheckModal.wiring.test.ts +++ b/src/components/categories/HierarchyCheckModal.wiring.test.ts @@ -5,7 +5,7 @@ // state survives from one call to the next, the test calls the props it hands // to each CategoryCombobox and to its buttons, then renders again. import { describe, it, expect, vi, beforeEach } from "vitest"; -import { isValidElement, type ReactElement, type ReactNode } from "react"; +import type { ReactElement, ReactNode } from "react"; vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig())); vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock()); @@ -16,6 +16,7 @@ vi.mock("./parentOptions", async (importOriginal) => { }); import { hookHarness } from "../../test/hookHarness"; +import { find } from "../../test/elementTree"; import HierarchyCheckModal from "./HierarchyCheckModal"; import CategoryCombobox from "../shared/CategoryCombobox"; import { buildParentOptions } from "./parentOptions"; @@ -26,14 +27,7 @@ const harness = hookHarness(); type Props = Record & { children?: ReactNode }; -function find(node: ReactNode, match: (el: ReactElement) => boolean): ReactElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, match)); - if (!isValidElement(node)) return []; - const el = node as ReactElement; - return [...(match(el) ? [el] : []), ...find(el.props.children, match)]; -} - -const node = (id: number, parent_id: number | null): CategoryTreeNode => ({ +const node =(id: number, parent_id: number | null): CategoryTreeNode => ({ id, name: `c${id}`, parent_id, diff --git a/src/components/dashboard/OnboardingChecklist.test.tsx b/src/components/dashboard/OnboardingChecklist.test.tsx index 0b53bf7..9ac49c0 100644 --- a/src/components/dashboard/OnboardingChecklist.test.tsx +++ b/src/components/dashboard/OnboardingChecklist.test.tsx @@ -18,26 +18,13 @@ vi.mock("lucide-react", () => ({ })); import { CheckCircle2, Circle, Lock, SkipForward } from "lucide-react"; +import { find, texts } from "../../test/elementTree"; import OnboardingChecklist, { type OnboardingChecklistProps } from "./OnboardingChecklist"; import { computeChecklist } from "../../utils/onboardingChecklist"; import type { ChecklistItemKey, OnboardingCounters } from "../../shared/types"; type AnyElement = ReactElement & { children?: ReactNode }>; -function find(node: ReactNode, pred: (el: AnyElement) => boolean): AnyElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, pred)); - if (!isValidElement(node)) return []; - const el = node as AnyElement; - return [...(pred(el) ? [el] : []), ...find(el.props.children, pred)]; -} - -function texts(node: ReactNode): string[] { - if (Array.isArray(node)) return node.flatMap(texts); - if (typeof node === "string") return [node]; - if (!isValidElement(node)) return []; - return texts((node as AnyElement).props.children); -} - // Leaves of the walk: react-router's Link and the mocked icons keep their type. const LEAVES = new Set([Link, CheckCircle2, Circle, Lock, SkipForward]); diff --git a/src/components/import/ImportEmptyState.test.tsx b/src/components/import/ImportEmptyState.test.tsx index bd7e652..6bb0aed 100644 --- a/src/components/import/ImportEmptyState.test.tsx +++ b/src/components/import/ImportEmptyState.test.tsx @@ -19,6 +19,7 @@ vi.mock("lucide-react", () => ({ })); import { FileText, Folder, FolderOpen, Inbox } from "lucide-react"; +import { find, texts } from "../../test/elementTree"; import ImportEmptyState, { CSV_EXPORT_GUIDE_PATH, folderNameFromPath, @@ -27,20 +28,6 @@ import ImportEmptyState, { type AnyElement = ReactElement & { children?: ReactNode }>; -function find(node: ReactNode, pred: (el: AnyElement) => boolean): AnyElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, pred)); - if (!isValidElement(node)) return []; - const el = node as AnyElement; - return [...(pred(el) ? [el] : []), ...find(el.props.children, pred)]; -} - -function texts(node: ReactNode): string[] { - if (Array.isArray(node)) return node.flatMap(texts); - if (typeof node === "string") return [node]; - if (!isValidElement(node)) return []; - return texts((node as AnyElement).props.children); -} - // Leaves of the walk: react-router's Link and the mocked icons keep their type. const LEAVES = new Set([Link, FolderOpen, Inbox, Folder, FileText]); diff --git a/src/components/layout/AppShell.slot.test.tsx b/src/components/layout/AppShell.slot.test.tsx index 9695e0e..5cbfbc6 100644 --- a/src/components/layout/AppShell.slot.test.tsx +++ b/src/components/layout/AppShell.slot.test.tsx @@ -5,7 +5,7 @@ // its state survives from one call to the next as it would between two // renders of a mounted component. import { describe, it, expect, vi, beforeEach } from "vitest"; -import { isValidElement, type ReactElement, type ReactNode } from "react"; +import type { ReactElement, ReactNode } from "react"; import { Outlet } from "react-router-dom"; vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig())); @@ -24,6 +24,7 @@ vi.mock("../../contexts/OnboardingContext", () => ({ vi.mock("./Sidebar", () => ({ default: () => null })); import { hookHarness } from "../../test/hookHarness"; +import { find } from "../../test/elementTree"; import AppShell, { OnboardingBannerSlot } from "./AppShell"; import OnboardingBanner, { type OnboardingBannerProps } from "../onboarding/OnboardingBanner"; import { computeChecklist } from "../../utils/onboardingChecklist"; @@ -34,13 +35,6 @@ const harness = hookHarness(); type AnyElement = ReactElement & { children?: ReactNode }>; -function find(node: ReactNode, pred: (el: AnyElement) => boolean): AnyElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, pred)); - if (!isValidElement(node)) return []; - const el = node as AnyElement; - return [...(pred(el) ? [el] : []), ...find(el.props.children, pred)]; -} - function onboardingValue(): OnboardingValue { const counters = { sources: 1, imports: 1, manualCategorized: 0, budgetEntries: 0, transactions: 40 }; // Stopped after the import: the visit steps are acknowledged (rule of the templates, #425). diff --git a/src/components/onboarding/OnboardingBanner.render.test.tsx b/src/components/onboarding/OnboardingBanner.render.test.tsx index b4ad18f..e08377c 100644 --- a/src/components/onboarding/OnboardingBanner.render.test.tsx +++ b/src/components/onboarding/OnboardingBanner.render.test.tsx @@ -3,7 +3,7 @@ // and the component is called as a function for what the markup does not // carry (a link's navigation state, the handlers). import { describe, it, expect, vi } from "vitest"; -import { isValidElement, type ReactElement, type ReactNode } from "react"; +import type { ReactElement, ReactNode } from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { Link, MemoryRouter } from "react-router-dom"; @@ -11,6 +11,7 @@ import { Link, MemoryRouter } from "react-router-dom"; // skipped `t` would show unmarked. vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock()); +import { find, texts } from "../../test/elementTree"; import OnboardingBanner, { GETTING_STARTED_GUIDE, ONBOARDING_BANNER_LIST_ID, @@ -23,20 +24,6 @@ import type { OnboardingCounters } from "../../shared/types"; type AnyElement = ReactElement & { children?: ReactNode }>; -function find(node: ReactNode, pred: (el: AnyElement) => boolean): AnyElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, pred)); - if (!isValidElement(node)) return []; - const el = node as AnyElement; - return [...(pred(el) ? [el] : []), ...find(el.props.children, pred)]; -} - -function texts(node: ReactNode): string[] { - if (Array.isArray(node)) return node.flatMap(texts); - if (typeof node === "string") return [node]; - if (!isValidElement(node)) return []; - return texts((node as AnyElement).props.children); -} - const ZERO: OnboardingCounters = { sources: 0, imports: 0, diff --git a/src/components/onboarding/StepCard.render.test.tsx b/src/components/onboarding/StepCard.render.test.tsx index f52d401..55bc115 100644 --- a/src/components/onboarding/StepCard.render.test.tsx +++ b/src/components/onboarding/StepCard.render.test.tsx @@ -3,7 +3,7 @@ // and the component is called as a function for what the markup does not // carry (a link's navigation state, the handlers, the title's ref). import { describe, it, expect, vi } from "vitest"; -import { createRef, isValidElement, type ReactElement, type ReactNode } from "react"; +import { createRef, type ReactNode } from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { Link, MemoryRouter } from "react-router-dom"; @@ -11,27 +11,12 @@ import { Link, MemoryRouter } from "react-router-dom"; // skipped `t` would show unmarked. vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock()); +import { find, texts } from "../../test/elementTree"; import StepCard, { type StepCardProps } from "./StepCard"; import { GETTING_STARTED_GUIDE } from "./OnboardingBanner"; import { computeChecklist } from "../../utils/onboardingChecklist"; import type { ChecklistItem, ChecklistItemKey, OnboardingCounters } from "../../shared/types"; -type AnyElement = ReactElement & { children?: ReactNode }>; - -function find(node: ReactNode, pred: (el: AnyElement) => boolean): AnyElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, pred)); - if (!isValidElement(node)) return []; - const el = node as AnyElement; - return [...(pred(el) ? [el] : []), ...find(el.props.children, pred)]; -} - -function texts(node: ReactNode): string[] { - if (Array.isArray(node)) return node.flatMap(texts); - if (typeof node === "string") return [node]; - if (!isValidElement(node)) return []; - return texts((node as AnyElement).props.children); -} - const ZERO: OnboardingCounters = { sources: 0, imports: 0, diff --git a/src/components/settings/ChangelogContent.test.tsx b/src/components/settings/ChangelogContent.test.tsx index 8999f5b..8fc468c 100644 --- a/src/components/settings/ChangelogContent.test.tsx +++ b/src/components/settings/ChangelogContent.test.tsx @@ -6,7 +6,7 @@ // handlers of the rendered tree are called as clicks would. The markup is // read through renderToStaticMarkup. import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { isValidElement, type ReactElement, type ReactNode } from "react"; +import type { ReactElement, ReactNode } from "react"; vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig())); const ctx = vi.hoisted(() => ({ language: "fr" })); @@ -16,6 +16,7 @@ vi.mock("react-i18next", async () => import { renderToStaticMarkup } from "react-dom/server"; import { hookHarness } from "../../test/hookHarness"; +import { find, texts } from "../../test/elementTree"; import ChangelogContent, { CHANGELOG_NOTES_ID_PREFIX } from "./ChangelogContent"; const harness = hookHarness(); @@ -58,20 +59,6 @@ const FR_DEV = FR.replace("## [Non publié]\n", "## [Non publié]\n\n### Modifi type AnyElement = ReactElement & { children?: ReactNode }>; -function find(node: ReactNode, pred: (el: AnyElement) => boolean): AnyElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, pred)); - if (!isValidElement(node)) return []; - const el = node as AnyElement; - return [...(pred(el) ? [el] : []), ...find(el.props.children, pred)]; -} - -function texts(node: ReactNode): string[] { - if (Array.isArray(node)) return node.flatMap(texts); - if (typeof node === "string") return [node]; - if (!isValidElement(node)) return []; - return texts((node as AnyElement).props.children); -} - interface FetchedFile { text: () => Promise; } diff --git a/src/components/shared/CategoryCombobox.placement.test.ts b/src/components/shared/CategoryCombobox.placement.test.ts index ae0c5bb..acd469b 100644 --- a/src/components/shared/CategoryCombobox.placement.test.ts +++ b/src/components/shared/CategoryCombobox.placement.test.ts @@ -10,7 +10,7 @@ // React skipping the render on an unchanged state (here, the same object in // the state slot stands for it). import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import { isValidElement, type ReactElement, type ReactNode } from "react"; +import type { ReactNode } from "react"; vi.mock("react", async (orig) => { const fake = (await import("../../test/hookHarness")).fakeReact(await orig()); @@ -23,19 +23,11 @@ vi.mock("react-dom", async (orig) => ({ vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock()); import { hookHarness } from "../../test/hookHarness"; +import { find } from "../../test/elementTree"; import CategoryCombobox from "./CategoryCombobox"; const harness = hookHarness(); -type Props = Record & { children?: ReactNode }; - -function find(node: ReactNode, type: unknown): ReactElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, type)); - if (!isValidElement(node)) return []; - const el = node as ReactElement; - return [...(el.type === type ? [el] : []), ...find(el.props.children, type)]; -} - const CATEGORIES = [{ id: 7, name: "Épicerie", parent_id: null, sort_order: 1 }]; /** The input's place on screen, which a render of the parent can change. */ @@ -48,14 +40,14 @@ const render = () => /** The open list's style, or null when no list is rendered. */ const listStyle = (tree: ReactNode) => { - const [list] = find(tree, "ul"); + const [list] = find(tree, (el) => el.type === "ul"); return list ? (list.props.style as { top?: number; bottom?: number }) : null; }; /** Mounts the combobox, hands its input ref the fake input, then focuses it: the list opens. */ function open(): ReactNode { const closed = render(); - const [input] = find(closed, "input"); + const [input] = find(closed, (el) => el.type === "input"); (input.props.ref as { current: unknown }).current = fakeInput; harness.commit(); (input.props.onFocus as () => void)(); diff --git a/src/components/shared/EmptyState.test.tsx b/src/components/shared/EmptyState.test.tsx index df6f4d3..7654ba5 100644 --- a/src/components/shared/EmptyState.test.tsx +++ b/src/components/shared/EmptyState.test.tsx @@ -5,26 +5,13 @@ // React-element tree is walked directly. `Link` is react-router's real // component: creating the element never needs a router, only rendering would. import { describe, it, expect, vi } from "vitest"; -import { isValidElement, type ReactElement, type ReactNode } from "react"; +import type { ReactElement, ReactNode } from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { Link, MemoryRouter } from "react-router-dom"; +import { find, texts } from "../../test/elementTree"; import EmptyState, { EMPTY_STATE_TARGET, type EmptyStateAction } from "./EmptyState"; -function find(node: ReactNode, pred: (el: ReactElement) => boolean): ReactElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, pred)); - if (!isValidElement(node)) return []; - const el = node as ReactElement<{ children?: ReactNode }>; - return [...(pred(el) ? [el] : []), ...find(el.props.children, pred)]; -} - -function texts(node: ReactNode): string[] { - if (Array.isArray(node)) return node.flatMap(texts); - if (typeof node === "string") return [node]; - if (!isValidElement(node)) return []; - return texts((node as ReactElement<{ children?: ReactNode }>).props.children); -} - const ICON = "ICON_MARKER"; describe("EmptyState", () => { diff --git a/src/components/shared/UpsellCtas.render.test.tsx b/src/components/shared/UpsellCtas.render.test.tsx index b1f9d03..9bb3c32 100644 --- a/src/components/shared/UpsellCtas.render.test.tsx +++ b/src/components/shared/UpsellCtas.render.test.tsx @@ -2,7 +2,7 @@ // react-dom/server renders in vitest's node environment, and calling a // component as a function (FilterPanel.test.tsx pattern) exposes its props. import { describe, it, expect, vi, beforeEach } from "vitest"; -import { isValidElement, type ReactElement, type ReactNode } from "react"; +import type { ReactElement, ReactNode } from "react"; import { renderToStaticMarkup } from "react-dom/server"; import { MemoryRouter } from "react-router-dom"; @@ -34,19 +34,13 @@ vi.mock("../../hooks/useUpdater", () => ({ }), })); +import { find } from "../../test/elementTree"; import UpsellGate from "./UpsellGate"; import PurchaseButton from "./PurchaseButton"; import DownloadLatestButton from "./DownloadLatestButton"; import HaveKeyButton from "./HaveKeyButton"; import UpdateCard from "../settings/UpdateCard"; -function find(node: ReactNode, pred: (el: ReactElement) => boolean): ReactElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, pred)); - if (!isValidElement(node)) return []; - const el = node as ReactElement<{ children?: ReactNode }>; - return [...(pred(el) ? [el] : []), ...find(el.props.children, pred)]; -} - beforeEach(() => { openUrl.mockClear(); logError.mockClear(); diff --git a/src/components/transactions/TransactionTable.wiring.test.ts b/src/components/transactions/TransactionTable.wiring.test.ts index d74355b..d11f463 100644 --- a/src/components/transactions/TransactionTable.wiring.test.ts +++ b/src/components/transactions/TransactionTable.wiring.test.ts @@ -9,12 +9,13 @@ // SplitButton (or to a row's notes button), then renders again to read what // opened. import { describe, it, expect, vi, beforeEach } from "vitest"; -import { Fragment, isValidElement, type ReactElement, type ReactNode } from "react"; +import { Fragment, type ReactNode } from "react"; vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig())); vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock()); import { hookHarness } from "../../test/hookHarness"; +import { find } from "../../test/elementTree"; import TransactionTable from "./TransactionTable"; import SplitButton from "./SplitButton"; import SplitAdjustmentModal from "./SplitAdjustmentModal"; @@ -24,15 +25,6 @@ import type { Category, TransactionRow } from "../../shared/types"; const harness = hookHarness(); -type Props = Record & { children?: ReactNode }; - -function find(node: ReactNode, type: unknown): ReactElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, type)); - if (!isValidElement(node)) return []; - const el = node as ReactElement; - return [...(el.type === type ? [el] : []), ...find(el.props.children, type)]; -} - const GROCERIES: Category = { id: 7, name: "Épicerie", @@ -78,9 +70,9 @@ const render = (splitAccess: SplitAccess) => }), ); -const splitButtons = (tree: ReactNode) => find(tree, SplitButton); -const upsells = (tree: ReactNode) => find(tree, UpsellDialog); -const splitWindows = (tree: ReactNode) => find(tree, SplitAdjustmentModal); +const splitButtons = (tree: ReactNode) => find(tree, (el) => el.type === SplitButton); +const upsells = (tree: ReactNode) => find(tree, (el) => el.type === UpsellDialog); +const splitWindows = (tree: ReactNode) => find(tree, (el) => el.type === SplitAdjustmentModal); beforeEach(() => harness.clear()); @@ -146,13 +138,13 @@ describe("TransactionTable — the Répartition button's wiring (#369)", () => { describe("TransactionTable — the notes row (#437)", () => { /** The rows' notes buttons, named by their title (pinned in TransactionTable.render.test.tsx). */ const notesButtons = (tree: ReactNode) => - find(tree, "button").filter((b) => b.props.title === "t(transactions.notes.placeholder)"); + find(tree, (el) => el.type === "button").filter((b) => b.props.title === "t(transactions.notes.placeholder)"); it("a row's notes button opens one textarea, named through t", () => { - expect(find(render("open"), "textarea")).toHaveLength(0); + expect(find(render("open"), (el) => el.type === "textarea")).toHaveLength(0); (notesButtons(render("open"))[1].props.onClick as () => void)(); const opened = render("open"); - const areas = find(opened, "textarea"); + const areas = find(opened, (el) => el.type === "textarea"); expect(areas).toHaveLength(1); expect(areas[0].props.placeholder).toBe("t(transactions.notes.placeholder)"); }); @@ -161,9 +153,9 @@ describe("TransactionTable — the notes row (#437)", () => { (notesButtons(render("open"))[1].props.onClick as () => void)(); // Each row and the rows it opens sit in a Fragment keyed by the row's id // (the unkeyed ones are inside the cells). - const byRow = find(render("open"), Fragment) + const byRow = find(render("open"), (el) => el.type === Fragment) .filter((row) => row.key !== null) - .map((row) => [row.key, find(row.props.children, "textarea").length]); + .map((row) => [row.key, find(row.props.children, (el) => el.type === "textarea").length]); expect(byRow).toEqual([ ["1", 0], ["2", 1], diff --git a/src/pages/settings/SystemsSettingsPage.test.tsx b/src/pages/settings/SystemsSettingsPage.test.tsx index d6b4f5b..57cfb17 100644 --- a/src/pages/settings/SystemsSettingsPage.test.tsx +++ b/src/pages/settings/SystemsSettingsPage.test.tsx @@ -6,7 +6,7 @@ // the next render reads what the effect stored. The cards are stubs: only // where the page puts them, and what it hands the history, are under test. import { describe, it, expect, vi, beforeEach } from "vitest"; -import { isValidElement, type ReactElement, type ReactNode } from "react"; +import type { ReactNode } from "react"; vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig())); vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock()); @@ -26,6 +26,7 @@ vi.mock("../../components/settings/ChangelogContent", () => ({ default: () => "[ import { renderToStaticMarkup } from "react-dom/server"; import { getVersion } from "@tauri-apps/api/app"; import { hookHarness } from "../../test/hookHarness"; +import { find } from "../../test/elementTree"; import { logWarn } from "../../services/logService"; import ChangelogContent from "../../components/settings/ChangelogContent"; import SystemsSettingsPage from "./SystemsSettingsPage"; @@ -33,15 +34,6 @@ import { SECTIONS } from "./SettingsHomePage"; const harness = hookHarness(); -type AnyElement = ReactElement & { children?: ReactNode }>; - -function find(node: ReactNode, pred: (el: AnyElement) => boolean): AnyElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, pred)); - if (!isValidElement(node)) return []; - const el = node as AnyElement; - return [...(pred(el) ? [el] : []), ...find(el.props.children, pred)]; -} - /** One render of the mounted page. */ const render = (): ReactNode => harness.render(() => SystemsSettingsPage() as ReactNode); diff --git a/src/pages/settings/UsersSettingsPage.test.tsx b/src/pages/settings/UsersSettingsPage.test.tsx index ab4db00..82845cf 100644 --- a/src/pages/settings/UsersSettingsPage.test.tsx +++ b/src/pages/settings/UsersSettingsPage.test.tsx @@ -7,7 +7,7 @@ // page" is a new `useOnboarding()` value on the next render, without // remounting, and an effect of the page that read the preference would run. import { describe, it, expect, vi, beforeEach } from "vitest"; -import { isValidElement, type ReactElement, type ReactNode } from "react"; +import type { ReactNode } from "react"; vi.mock("react", async (orig) => (await import("../../test/hookHarness")).fakeReact(await orig())); const ctx = vi.hoisted(() => ({ onboarding: null as unknown })); @@ -25,28 +25,13 @@ vi.mock("../../services/userPreferenceService", () => ({ getPreference: vi.fn() vi.mock("../../services/onboardingService", () => ({ showChecklist: vi.fn() })); import { hookHarness } from "../../test/hookHarness"; +import { find, texts } from "../../test/elementTree"; import UsersSettingsPage from "./UsersSettingsPage"; import { getPreference } from "../../services/userPreferenceService"; import { showChecklist } from "../../services/onboardingService"; const harness = hookHarness(); -type AnyElement = ReactElement & { children?: ReactNode }>; - -function find(node: ReactNode, pred: (el: AnyElement) => boolean): AnyElement[] { - if (Array.isArray(node)) return node.flatMap((n) => find(n, pred)); - if (!isValidElement(node)) return []; - const el = node as AnyElement; - return [...(pred(el) ? [el] : []), ...find(el.props.children, pred)]; -} - -function texts(node: ReactNode): string[] { - if (Array.isArray(node)) return node.flatMap(texts); - if (typeof node === "string") return [node]; - if (!isValidElement(node)) return []; - return texts((node as AnyElement).props.children); -} - /** What the page reads from the provider: only `hidden` and `show` matter here. */ function path(hidden: boolean) { return { hidden, show: vi.fn(async () => undefined) }; diff --git a/src/test/elementTree.test.ts b/src/test/elementTree.test.ts index d2db6d9..0e22426 100644 --- a/src/test/elementTree.test.ts +++ b/src/test/elementTree.test.ts @@ -1,13 +1,13 @@ -// elementTree — each semantic of the two helpers proved by its own test (#467). +// elementTree — each semantic of the three helpers proved by its own test (#467, #495). // // The tests that search a rendered tree can only be as true as these helpers. // The trees are built here with the real React (`createElement`), in the shapes // JSX gives them: several children in an array, a `.map` as one child, nested -// arrays, fragments, texts and holes. +// arrays, fragments, texts, numbers and holes. import { describe, it, expect, vi } from "vitest"; import { createElement as h, Fragment, type ReactNode } from "react"; import { Pencil, Trash2 } from "lucide-react"; -import { find, holding, type TreeElement } from "./elementTree"; +import { find, holding, texts, type TreeElement } from "./elementTree"; /** The `id` prop of each element, in the order the helper returns them. */ const ids = (elements: TreeElement[]) => elements.map((el) => el.props.id); @@ -134,3 +134,61 @@ describe("elementTree — holding", () => { expect(holding(null, Trash2)).toEqual([]); }); }); + +describe("elementTree — texts", () => { + it("returns every string of the tree, depth first: in the order the page shows them", () => { + const node = h( + "section", + { id: "s" }, + "a", + h("p", { id: "p" }, "b", h("b", { id: "b" }, "c"), "d"), + h("p", { id: "q" }, "e"), + ); + expect(texts(node)).toEqual(["a", "b", "c", "d", "e"]); + expect(texts("alone")).toEqual(["alone"]); + }); + + it("reads arrays at any depth: a .map as one child, a list beside a sibling, a nested array, a top-level array", () => { + const rows = ["x", "y"].map((s) => h("li", { key: s }, s)); + const list = h("ul", { key: "ul" }, h("li", null, "first"), rows); + const node: ReactNode = [list, [["last", [h("p", { key: "p" }, "p")]]]]; + expect(texts(node)).toEqual(["first", "x", "y", "last", "p"]); + expect(texts(h("ol", null, rows))).toEqual(["x", "y"]); + }); + + it("reads through a fragment: its strings in their place", () => { + const node = h("div", null, "before", h(Fragment, null, "in", h("i", null, "nested")), "after"); + expect(texts(node)).toEqual(["before", "in", "nested", "after"]); + expect(texts(h(Fragment, null, "only"))).toEqual(["only"]); + }); + + it("leaves a number out: a number is not a string, and is never rendered", () => { + const node = h("p", null, "count: ", 3, h("b", null, 0), [1, "one"]); + expect(texts(node)).toEqual(["count: ", "one"]); + expect(texts(h("span", null, 42))).toEqual([]); + expect(texts(3)).toEqual([]); + }); + + it("keeps each string as it is: neither trimmed nor joined to its neighbour, an empty one kept", () => { + expect(texts(h("p", null, " a ", "", "b"))).toEqual([" a ", "", "b"]); + }); + + it("skips holes: null, undefined and booleans", () => { + expect(texts(h("p", null, null, undefined, false, true, "x"))).toEqual(["x"]); + expect(texts(null)).toEqual([]); + expect(texts(undefined)).toEqual([]); + expect(texts(true)).toEqual([]); + }); + + it("reads props.children only: an element or a string passed in another prop is not reached", () => { + const node = h("button", { title: "title", "aria-label": "label", icon: h("i", null, "icon") }, "text"); + expect(texts(node)).toEqual(["text"]); + }); + + it("never calls a component of the tree: what it renders is not there", () => { + const Child = vi.fn(() => h("b", null, "inside")); + const node = h("div", null, h(Child, { label: "prop" }), "after"); + expect(texts(node)).toEqual(["after"]); + expect(Child).not.toHaveBeenCalled(); + }); +}); diff --git a/src/test/elementTree.ts b/src/test/elementTree.ts index 02b40c0..4c6888b 100644 --- a/src/test/elementTree.ts +++ b/src/test/elementTree.ts @@ -1,9 +1,9 @@ -// elementTree — searching the tree a component returns, for tests without jsdom (#467). +// elementTree — searching the tree a component returns, for tests without jsdom (#467, #495). // // A test that calls a component as a plain function, under the shared hook // harness of this folder or without it, gets back a tree of React elements, -// not a DOM. These two helpers search that tree, shared since #467 (several -// test files still keep a copy of their own). Each semantic below is proved by +// not a DOM. These three helpers search that tree: `find` and `holding` since +// #467, `texts` since #495. Each semantic below is proved by // elementTree.test.ts. // // - `find(node, pred)`: every element of the tree for which `pred` is true, @@ -20,12 +20,19 @@ // in `{label}{rows}` they are not. A fragment holds its own // children, not its parent. An absence is proved with `find`, never with // `holding`: its one-level read would miss an element nested deeper. +// - `texts(node)`: every string of the tree, depth first, so in the order the +// page shows them, through arrays at any depth and fragments. Each string +// comes as it is, neither trimmed nor joined to its neighbour. A number is +// not a string: `texts` leaves it out and never renders it (`{count}` shows +// "3" on the page, not in `texts`), as it leaves out the holes (`null`, +// `undefined`, booleans). // -// Both read `props.children` only: an element passed in another prop -// (`icon={}`) is not reached. A component in the tree is an element, -// never called, as under the harness: what a child component renders is not -// in the tree, and the test reaches it through the props of the child's -// element (`find(tree, (el) => el.type === CategoryForm)[0].props.onDelete()`). +// All three read `props.children` only: an element or a string passed in +// another prop (`icon={}`, `title="…"`) is not reached. A component in +// the tree is an element, never called, as under the harness: what a child +// component renders is not in the tree, and the test reaches it through the +// props of the child's element +// (`find(tree, (el) => el.type === CategoryForm)[0].props.onDelete()`). import { isValidElement, type ReactElement, type ReactNode } from "react"; /** The props of an element of the tree: any props, and its children. */ @@ -54,3 +61,11 @@ export function holding

(node: ReactNode, type: const holds = children.some((c) => isValidElement(c) && c.type === type); return [...(holds ? [el] : []), ...holding

(el.props.children, type)]; } + +/** Every string of `node`, depth first, through arrays and fragments; a number is left out. */ +export function texts(node: ReactNode): string[] { + if (Array.isArray(node)) return node.flatMap((n) => texts(n)); + if (typeof node === "string") return [node]; + if (!isValidElement(node)) return []; + return texts((node as TreeElement).props.children); +}