diff --git a/docs/testing.md b/docs/testing.md index b2149f95a5..53b68723fb 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -101,6 +101,24 @@ The usual sources: testing-library's, that microtask lands outside `act()`. Re-render inside an async `act()`: `await act(async () => { rerender(…); })`. +### findDOMNode + +A test also fails when our own code calls `findDOMNode`, which React 19 +removes: `findDOMNode was called from X`, naming the caller. Put a ref on the +element instead. Where the element belongs to a react-bootstrap 0.33 component, +which doesn't pass refs on, hand it a `componentClass` made with `withDomRef` +(`src/renderer/src/controls/with_dom_ref/withDomRef.ts`) and a `domRef` prop: +`ToolbarIcon` and `ContextMenu` do this. + +The check catches the call, not React's warning. React logs that warning once +per test file, and react-bootstrap and react-overlays still call `findDOMNode` +themselves, so their warning would hide ours. Their calls don't fail a test. + +One call of ours is let through: `findDOMNodeUntilReact19` in +`VisibilityProxy`, which finds the element of an extension's `componentClass` +that doesn't pass its ref on. It goes when React 19 does. The names let through +are listed in `allowedFindDOMNodeCallers` in the test setup. + ### What the check can't see - `waitFor`, the `findBy…` queries and `userEvent` turn React's `act()` checks @@ -114,11 +132,15 @@ The usual sources: - An update that lands after testing-library's cleanup fails the next test in the file, or the file's `afterAll` after its last test, rather than the test that caused it. -- Only `act()` warnings fail a test. The deprecation warnings still in the log - (`findDOMNode`, `defaultProps`, legacy `contextTypes`) come from older code: - class components built on `ComponentEx` in `src/renderer/src/controls/`, and - old dependencies such as `react-bootstrap` 0.33. Clearing them means changing - that code, not the tests. +- Only `act()` warnings and our own `findDOMNode` calls fail a test. The + deprecation warnings still in the log (`findDOMNode` from react-bootstrap, + `defaultProps`, legacy `contextTypes`) come from older code: class components + built on `ComponentEx` in `src/renderer/src/controls/`, and old dependencies + such as `react-bootstrap` 0.33. Clearing them means changing that code, not + the tests. +- The `findDOMNode` check only sees code that runs in a test. The renderer + still has calls outside the tested paths, such as `Dropdown`, + `ActionDropdown`, `OverlayTrigger` and `DraggableList`. ## Extension tests diff --git a/extensions/mod-dependency-manager/src/views/ConflictEditor.tsx b/extensions/mod-dependency-manager/src/views/ConflictEditor.tsx index 1e3f0d7330..3fa97a791a 100644 --- a/extensions/mod-dependency-manager/src/views/ConflictEditor.tsx +++ b/extensions/mod-dependency-manager/src/views/ConflictEditor.tsx @@ -148,6 +148,7 @@ function VisibilityProxyWrap(props: IVisibilityProxyWrapProps) { return ( ({ default: () => null })); + // ContextMenu extends ComponentEx which reads api/menuLayer/getModifiers from // the legacy context; provide the minimum via a legacy-context provider. class LegacyContextProvider extends React.Component<{ @@ -30,7 +35,13 @@ class LegacyContextProvider extends React.Component<{ } } -function Harness(props: { menuLayer: HTMLElement }) { +const testAction: IActionDefinitionEx = { + title: "Test Action", + action: () => undefined, + show: true, +}; + +function Harness(props: { menuLayer: HTMLElement; actions?: any[] }) { const [visible, setVisible] = React.useState(false); const [position, setPosition] = React.useState({ x: 0, y: 0 }); @@ -49,7 +60,7 @@ function Harness(props: { menuLayer: HTMLElement }) { onHide={onHide} position={position} instanceId="test-instance" - actions={[{ title: "Test Action", action: () => undefined, show: true } as any]} + actions={props.actions ?? [testAction]} /> ); @@ -65,6 +76,7 @@ describe("ContextMenu", () => { afterEach(() => { menuLayer.remove(); + vi.restoreAllMocks(); }); it("stays open after the right-click that opened it (React 17 delegation)", () => { @@ -93,4 +105,21 @@ describe("ContextMenu", () => { expect(menuLayer.textContent).not.toContain("Test Action"); }); }); + + it("places a submenu by the item that opens it", async () => { + const measured = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect"); + const more = { + title: "More", + show: true, + subMenus: [{ title: "Sub Action", action: () => undefined, show: true }], + }; + render(); + fireEvent.contextMenu(screen.getByTestId("row"), { clientX: 10, clientY: 10 }); + const [anchor] = within(menuLayer).getAllByRole("menuitem"); + + fireEvent.mouseEnter(anchor); + + await waitFor(() => expect(within(menuLayer).getAllByRole("menuitem")).toHaveLength(2)); + expect(measured.mock.contexts).toContain(anchor.closest("li")); + }); }); diff --git a/src/renderer/src/controls/ContextMenu.tsx b/src/renderer/src/controls/ContextMenu.tsx index ee4cd204b8..ba68544e86 100644 --- a/src/renderer/src/controls/ContextMenu.tsx +++ b/src/renderer/src/controls/ContextMenu.tsx @@ -2,7 +2,6 @@ import { clearTimeout } from "timers"; import * as React from "react"; import { MenuItem } from "react-bootstrap"; -import ReactDOM from "react-dom"; import { Portal } from "react-overlays"; import type { TFunction } from "../util/i18n"; @@ -11,6 +10,14 @@ import { ComponentEx } from "./ComponentEx"; import { HOVER_DELAY } from "./constants"; import Dropdown from "./Dropdown"; import Icon from "./Icon"; +import { withDomRef } from "./with_dom_ref/withDomRef"; + +/** + * The a MenuItem renders, handed back through domRef: react-bootstrap 0.33's MenuItem + * doesn't pass a ref on. MenuItem renders an
  • around it, and a submenu opens next to that + *
  • , the 's parent. + */ +const AnchorWithDomRef = withDomRef("a"); export interface IMenuActionProps { t: TFunction; @@ -115,9 +122,10 @@ function MenuAction(props: IMenuActionProps) { }, HOVER_DELAY); }, [setOpen]); - const setItemRef = (ref) => { - itemRef.current = ReactDOM.findDOMNode(ref) as HTMLElement; - }; + const setAnchorRef = React.useCallback((anchor: HTMLAnchorElement | null) => { + itemRef.current = anchor?.parentElement ?? undefined; + }, []); + const anchorProps = { componentClass: AnchorWithDomRef, domRef: setAnchorRef }; return ( {action.component !== undefined ? ( diff --git a/src/renderer/src/controls/IconBar.tsx b/src/renderer/src/controls/IconBar.tsx index d27a46915b..c0a9e031c4 100644 --- a/src/renderer/src/controls/IconBar.tsx +++ b/src/renderer/src/controls/IconBar.tsx @@ -3,7 +3,6 @@ import * as _ from "lodash"; import * as PropTypes from "prop-types"; import * as React from "react"; import { ButtonGroup, Dropdown, MenuItem } from "react-bootstrap"; -import ReactDOM from "react-dom"; import type { IActionDefinition } from "../types/IActionDefinition"; import type { IExtensibleProps } from "../types/IExtensionProvider"; @@ -14,8 +13,8 @@ import ActionControl from "./ActionControl"; import { HOVER_DELAY } from "./constants"; import Icon from "./Icon"; import PortalMenu from "./PortalMenu"; +import ToolbarIcon from "./toolbar_icon/ToolbarIcon"; import ToolbarDropdown from "./ToolbarDropdown"; -import ToolbarIcon from "./ToolbarIcon"; import { IconButton } from "./TooltipControls"; export type ButtonType = "text" | "icon" | "both" | "menu"; @@ -109,7 +108,7 @@ function IconBarIcon(props: IIconBarIconProps) { [setOpenMenu, icon.subMenus], ); - const itemRef = React.useRef(); + const itemRef = React.useRef(null); const trigger = React.useCallback(() => { icon.action?.(instanceIds, icon.data); @@ -128,14 +127,10 @@ function IconBarIcon(props: IIconBarIconProps) { const tooltip = typeof icon.show === "string" ? icon.show : t(icon.title, { ns: icon.options?.namespace }); - const setItemRef = (ref) => { - itemRef.current = ReactDOM.findDOMNode(ref) as HTMLElement; - }; - return ( void; @@ -174,7 +175,7 @@ class SuperTable extends ComponentEx { // when the pane mounts, which is before any row renders. private mScrollContainer: HTMLElement | null; private mHeaderRef: HTMLElement; - private mRowRefs: { [id: string]: HTMLElement } = {}; + private mRowRefs: { [id: string]: VisibilityProxy } = {}; private mLastSelectOnly: number = 0; private mLastDetailIds: string[] = []; private mDetailTimer: NodeJS.Timeout = null; @@ -625,7 +626,7 @@ class SuperTable extends ComponentEx { private scrollTo = (id: string, mayRetry?: boolean) => { try { - const node = ReactDOM.findDOMNode(this.mRowRefs[id]) as HTMLElement; + const node = this.mRowRefs[id]?.element ?? null; if (node !== null) { this.scrollToItem(node, false); } else if (mayRetry !== false) { @@ -1022,8 +1023,8 @@ class SuperTable extends ComponentEx { // the previously selected row might no longer be visible, which would cause // an exception when trying to find the associated dom node const lastIdx = sortedRows.indexOf(lastSelected.rowId); - if (lastIdx !== -1) { - const selectedNode = ReactDOM.findDOMNode(this.mRowRefs[lastSelected.rowId]) as Element; + const selectedNode = this.mRowRefs[lastSelected.rowId].element; + if (lastIdx !== -1 && selectedNode !== null) { visibleLineCount = this.rowScroller().clientHeight / selectedNode.clientHeight; // account for the header. quite inaccurate. visibleLineCount -= 2; @@ -1054,11 +1055,9 @@ class SuperTable extends ComponentEx { evt.preventDefault(); const groupId = evt.currentTarget.getAttribute("data-group") || undefined; const newItem = this.selectRelative(offset, groupId, evt.shiftKey); - if (this.mRowRefs[newItem] !== undefined && this.mMounted) { - this.scrollToItem( - ReactDOM.findDOMNode(this.mRowRefs[newItem]) as HTMLElement, - Math.abs(offset) > 1, - ); + const newNode = this.mRowRefs[newItem]?.element ?? null; + if (newNode !== null && this.mMounted) { + this.scrollToItem(newNode, Math.abs(offset) > 1); } } else { const action = this.props.actions.find((iter) => @@ -1205,7 +1204,7 @@ class SuperTable extends ComponentEx { this.mPinnedRef = ref; }; - private setRowRef = (ref: any) => { + private setRowRef = (ref: VisibilityProxy | null) => { if (ref !== null) { this.mRowRefs[ref.props["data-rowid"]] = ref; } @@ -1266,7 +1265,7 @@ class SuperTable extends ComponentEx { return this.mScrollContainer ?? (document.scrollingElement as HTMLElement); } - private scrollToItem = (item: HTMLElement, smooth: boolean, iterations: number = 3) => { + private scrollToItem = (item: Element, smooth: boolean, iterations: number = 3) => { const scroller = this.rowScroller(); // Measured against the scroller rather than the item's offsetParent: the page around a // sticky-header table holds more than the table, so the two don't share an origin. diff --git a/src/renderer/src/controls/VisibilityProxy.hide.test.tsx b/src/renderer/src/controls/VisibilityProxy.hide.test.tsx index ad4cdffe00..76b54bbbdd 100644 --- a/src/renderer/src/controls/VisibilityProxy.hide.test.tsx +++ b/src/renderer/src/controls/VisibilityProxy.hide.test.tsx @@ -169,9 +169,88 @@ describe("VisibilityProxy hiding", () => { expect(vi.getTimerCount()).toBe(0); }); - // Without a componentClass the proxy renders its content bare, so the node it observes is - // whatever the placeholder rendered. ConflictEditor (mod-dependency-manager) renders a
    - // for both, which React keeps as the same node. + // A componentClass made inline is a new component on every render, and Fast Refresh remounts + // one in development: either way the row's element is replaced while the proxy stays mounted. + it("keeps showing a row whose componentClass replaces its element", () => { + const makeRow = () => + React.forwardRef>((props, ref) => ( +
    + )); + const onSetVisible = vi.fn(); + function Entry(props: { componentClass: React.ElementType }) { + const [visible, setVisible] = React.useState(false); + return ( + } + data-testid="row" + placeholder={() => } + visible={visible} + setVisible={(value: boolean) => { + onSetVisible(value); + setVisible(value); + }} + /> + ); + } + const { getByTestId, queryByTestId, rerender } = render(); + report(getByTestId("row"), true); + + rerender(); + report(getByTestId("row"), true); + act(() => vi.advanceTimersByTime(5000)); + + expect(onSetVisible.mock.calls).toEqual([[true]]); + expect(queryByTestId("content")).not.toBeNull(); + }); + + // Fast Refresh does this in development: the componentClass remounts its element while the + // proxy's props, and so the proxy, stay as they were. + it("keeps showing a row whose componentClass replaces its element on its own", () => { + let replaceElement: () => void = () => undefined; + const SelfReplacing = React.forwardRef>( + function SelfReplacing(props, ref) { + const [key, setKey] = React.useState(0); + replaceElement = () => setKey((value) => value + 1); + return
    ; + }, + ); + const onSetVisible = vi.fn(); + function Entry() { + const [visible, setVisible] = React.useState(false); + return ( + } + data-testid="row" + placeholder={() => } + visible={visible} + setVisible={(value: boolean) => { + onSetVisible(value); + setVisible(value); + }} + /> + ); + } + const { getByTestId, queryByTestId } = render(); + const before = getByTestId("row"); + report(before, true); + + act(() => replaceElement()); + const after = getByTestId("row"); + expect(after).not.toBe(before); + expect(FakeIntersectionObserver.sInstances.some((obs) => obs.observes(before))).toBe(false); + report(after, true); + act(() => vi.advanceTimersByTime(5000)); + + expect(onSetVisible.mock.calls).toEqual([[true]]); + expect(queryByTestId("content")).not.toBeNull(); + }); + + // Without a componentClass the proxy wraps its content in a
    and observes that, so + // swapping the placeholder for content doesn't change the node it observes. describe("without a componentClass", () => { function renderEntry(placeholder: () => React.ReactNode, content: () => React.ReactNode) { const onSetVisible = vi.fn(); @@ -198,33 +277,32 @@ describe("VisibilityProxy hiding", () => { () =>
    , () =>
    content
    , ); - const entry = getByTestId("entry"); + const wrapper = getByTestId("entry").parentElement; - report(entry, true); - report(entry, false); + report(wrapper, true); + report(wrapper, false); act(() => vi.advanceTimersByTime(1000)); - report(entry, true); + report(wrapper, true); expect(onSetVisible.mock.calls).toEqual([[true], [false], [true]]); expect(getByTestId("entry").textContent).toBe("content"); }); - // Showing the content removed the observed node, and the observer reports a removed node - // as out of view. Hiding on that would bring back a placeholder nothing observes, which - // would then never fill. - it("doesn't hide on a report for a node it has since replaced", () => { + it("hides and shows again when content and placeholder render different elements", () => { const { getByTestId, onSetVisible, queryByTestId } = renderEntry( () => , () =>
    , ); - const placeholder = getByTestId("placeholder"); + const wrapper = getByTestId("placeholder").parentElement; - report(placeholder, true); - expect(placeholder.isConnected).toBe(false); - report(placeholder, false); - act(() => vi.advanceTimersByTime(5000)); + report(wrapper, true); + expect(queryByTestId("content")).not.toBeNull(); + report(wrapper, false); + act(() => vi.advanceTimersByTime(1000)); + expect(queryByTestId("placeholder")).not.toBeNull(); + report(wrapper, true); - expect(onSetVisible.mock.calls).toEqual([[true]]); + expect(onSetVisible.mock.calls).toEqual([[true], [false], [true]]); expect(queryByTestId("content")).not.toBeNull(); }); }); diff --git a/src/renderer/src/controls/VisibilityProxy.test.tsx b/src/renderer/src/controls/VisibilityProxy.test.tsx index 0946506e07..bb84595ec5 100644 --- a/src/renderer/src/controls/VisibilityProxy.test.tsx +++ b/src/renderer/src/controls/VisibilityProxy.test.tsx @@ -5,10 +5,13 @@ */ import { render } from "@testing-library/react"; import * as React from "react"; -import { beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { log } from "../util/log"; import VisibilityProxy from "./VisibilityProxy"; +vi.mock("../util/log", () => ({ log: vi.fn() })); + interface IObserverCall { op: "observe" | "unobserve"; root: Element | null; @@ -42,6 +45,10 @@ beforeEach(() => { calls.length = 0; }); +afterEach(() => { + vi.restoreAllMocks(); +}); + function Proxy(props: { container: HTMLElement | null }) { return ( and passes its ref on to it. */ +const Section = React.forwardRef>( + function Section(props, ref) { + return
    ; + }, +); + +/** A componentClass whose ref is its instance, not an element. */ +class Opaque extends React.Component<{ children?: React.ReactNode }> { + public render() { + return
    {this.props.children}
    ; + } +} + describe("VisibilityProxy", () => { it("is observed against the container it mounts with", () => { const scroller = document.createElement("div"); const { getByTestId } = render(); - expect(calls).toEqual([{ op: "observe", root: scroller, target: getByTestId("entry") }]); + expect(calls).toEqual([ + { op: "observe", root: scroller, target: getByTestId("entry").parentElement }, + ]); }); // The conflict editor passes a ref's `current`: null on the first render, where the @@ -67,14 +90,250 @@ describe("VisibilityProxy", () => { // an unclipped wrapper
    on every render after that. it("keeps the root it mounted with when the container changes", () => { const { getByTestId, rerender, unmount } = render(); - const entry = getByTestId("entry"); + const wrapper = getByTestId("entry").parentElement; rerender(); unmount(); expect(calls).toEqual([ - { op: "observe", root: null, target: entry }, - { op: "unobserve", root: null, target: entry }, + { op: "observe", root: null, target: wrapper }, + { op: "unobserve", root: null, target: wrapper }, + ]); + }); + + it("observes a
    around its content when it has no componentClass", () => { + const { getByTestId } = render(); + + const wrapper = getByTestId("entry").parentElement; + expect(wrapper?.tagName).toBe("DIV"); + expect(calls).toEqual([{ op: "observe", root: null, target: wrapper }]); + }); + + it("observes the element its componentClass renders", () => { + const { getByTestId } = render( + null} + data-testid="row" + placeholder={() => null} + visible={false} + setVisible={() => undefined} + />, + ); + + expect(calls).toEqual([{ op: "observe", root: null, target: getByTestId("row") }]); + }); + + it("observes the element a componentClass passes its ref on to", () => { + const { getByTestId } = render( + null} + data-testid="row" + placeholder={() => null} + visible={false} + setVisible={() => undefined} + />, + ); + + expect(calls).toEqual([{ op: "observe", root: null, target: getByTestId("row") }]); + }); + + it("is observed against the viewport when its container is undefined", () => { + const { getByTestId } = render(); + + expect(calls).toEqual([ + { op: "observe", root: null, target: getByTestId("entry").parentElement }, ]); }); + + it("observes an SVG element its componentClass renders", () => { + const { getByTestId } = render( + null} + data-testid="row" + placeholder={() => null} + visible={false} + setVisible={() => undefined} + />, + ); + + expect(calls).toEqual([{ op: "observe", root: null, target: getByTestId("row") }]); + }); + + // e.g. a componentClass made inline, which is a new component on every render + it("moves to the new element when its componentClass replaces it", () => { + const Other = React.forwardRef>( + function Other(props, ref) { + return
    ; + }, + ); + const renderWith = (componentClass: React.ElementType) => ( + null} + data-testid="row" + placeholder={() => null} + visible={false} + setVisible={() => undefined} + /> + ); + const { getByTestId, rerender } = render(renderWith(Section)); + const before = getByTestId("row"); + + rerender(renderWith(Other)); + + expect(calls).toEqual([ + { op: "observe", root: null, target: before }, + { op: "unobserve", root: null, target: before }, + { op: "observe", root: null, target: getByTestId("row") }, + ]); + }); + + // An extension's componentClass may not pass its ref on. Its element is found the way it was + // before refs, so its layout doesn't change, until React 19 removes findDOMNode. + it("observes the element of a class componentClass, with nothing added around its content", () => { + const setVisible = vi.fn(); + + const { container, getByTestId } = render( + null} + placeholder={() => } + visible={false} + setVisible={setVisible} + />, + ); + + const element = getByTestId("entry").parentElement; + expect(element?.parentElement).toBe(container); + expect(calls).toEqual([{ op: "observe", root: null, target: element }]); + expect(setVisible).not.toHaveBeenCalled(); + // an extension author learns to forward the ref before React 19 + expect(log).toHaveBeenCalledWith( + "warn", + expect.stringContaining("React.forwardRef"), + expect.objectContaining({ componentClass: "Opaque" }), + ); + }); + + it("keeps the cells of a function componentClass's straight in it", () => { + const consoleError = vi.spyOn(console, "error"); + const Row = (props: React.HTMLAttributes) => ; + + const { getByTestId } = render( + + + null} + placeholder={() => +
    } + visible={false} + setVisible={() => undefined} + /> +
    , + ); + + const row = getByTestId("cell").parentElement; + expect(row?.tagName).toBe("TR"); + expect(calls).toEqual([{ op: "observe", root: null, target: row }]); + // a function component can't take a ref, so the proxy doesn't give it one + expect(consoleError).not.toHaveBeenCalled(); + }); + + it("names a memo componentClass after the function it wraps", () => { + const Row = (props: React.HTMLAttributes) =>
    ; + + render( + null} + placeholder={() => null} + visible={false} + setVisible={() => undefined} + />, + ); + + expect(log).toHaveBeenCalledWith("warn", expect.stringContaining("doesn't pass its ref on"), { + componentClass: "Row", + }); + }); + + // StrictMode mounts each component, unmounts it and mounts the same instance again + it("observes again when the same instance mounts again", () => { + const { getByTestId } = render( + + null} + data-testid="row" + placeholder={() => null} + visible={false} + setVisible={() => undefined} + /> + , + ); + + const row = getByTestId("row"); + expect(calls).toEqual([ + { op: "observe", root: null, target: row }, + { op: "unobserve", root: null, target: row }, + { op: "observe", root: null, target: row }, + ]); + }); + + it("warns once per componentClass that gives no element, however many entries use it", () => { + class Item extends React.Component<{ children?: React.ReactNode }> { + public render() { + return
  • {this.props.children}
  • ; + } + } + render( +
      + {[1, 2, 3].map((key) => ( + null} + placeholder={() => null} + visible={false} + setVisible={() => undefined} + /> + ))} +
    , + ); + + const warnings = vi + .mocked(log) + .mock.calls.filter( + ([, , meta]) => (meta as { componentClass?: string })?.componentClass === "Item", + ); + expect(warnings).toHaveLength(1); + }); + + // Logged once for the whole app, so this counts every proxy this file has mounted without one. + it("warns once about proxies without a componentClass, however many mount", () => { + render( + <> + + + , + ); + + const warnings = vi + .mocked(log) + .mock.calls.filter(([, message]) => message.includes("without a componentClass")); + expect(warnings).toHaveLength(1); + }); }); diff --git a/src/renderer/src/controls/VisibilityProxy.tsx b/src/renderer/src/controls/VisibilityProxy.tsx index 76b53598b8..38514eb9c1 100644 --- a/src/renderer/src/controls/VisibilityProxy.tsx +++ b/src/renderer/src/controls/VisibilityProxy.tsx @@ -17,28 +17,122 @@ export interface IProps { componentClass?: React.ElementType; } +/** + * The componentClasses already warned about, and whether a proxy without one has been. Each + * warning is logged once, not once per proxy: a list of thousands of entries would flood the log. + */ +const sWarnedComponentClasses = new WeakSet(); +let sWarnedNoComponentClass = false; + +interface INamedType { + displayName?: string; + name?: string; +} + +/** A name for the log; a bare `React.memo(fn)` or `forwardRef` has none of its own. */ +function componentClassName(componentClass: React.ElementType): string { + if (typeof componentClass === "string") { + return componentClass; + } + const type = componentClass as INamedType & { type?: INamedType; render?: INamedType }; + return ( + type.displayName || + type.name || + type.type?.displayName || + type.type?.name || + type.render?.name || + "anonymous" + ); +} + +/** Tells an extension author once that a proxy without a componentClass adds a
    . */ +function warnNoComponentClass() { + if (sWarnedNoComponentClass) { + return; + } + sWarnedNoComponentClass = true; + log( + "warn", + "VisibilityProxy without a componentClass wraps its content in a
    , which breaks " + + "layout inside a , a list, a flex or a grid. Pass the element to render as " + + "componentClass", + ); +} + +/** Tells an extension author once per componentClass to pass its ref on before React 19. */ +function warnNoElement(componentClass: React.ElementType) { + if (typeof componentClass !== "string") { + if (sWarnedComponentClasses.has(componentClass)) { + return; + } + sWarnedComponentClasses.add(componentClass); + } + log( + "warn", + "VisibilityProxy: componentClass doesn't pass its ref on to an element, so Vortex finds " + + "the element with findDOMNode, which React 19 removes. Wrap the componentClass in " + + "React.forwardRef and pass the ref to the element it renders", + { componentClass: componentClassName(componentClass) }, + ); +} + +/** Whether a ref holds a DOM element, from this window or another. */ +function isElement(ref: unknown): ref is Element { + return (ref as Node | null)?.nodeType === Node.ELEMENT_NODE; +} + +const FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); +const MEMO_TYPE = Symbol.for("react.memo"); + +/** + * Whether a ref given to this componentClass reaches whatever it chooses: a tag, a forwardRef, + * or a memo of one. It's decided before rendering because a plain function component can't + * take a ref at all (React logs an error), and a class takes it as its instance, not an element. + */ +function passesRefOn(componentClass: React.ElementType): boolean { + if (typeof componentClass === "string") { + return true; + } + const type = componentClass as { $$typeof?: symbol; type?: React.ElementType }; + if (type.$$typeof === FORWARD_REF_TYPE) { + return true; + } + return type.$$typeof === MEMO_TYPE && type.type !== undefined && passesRefOn(type.type); +} + +/** + * Finds the element of a componentClass that doesn't pass its ref on, an extension's, the way + * Vortex did before refs, so its layout stays as it was. React 19 removes findDOMNode, and this + * goes with it. The test setup lets this one caller through by its name. + */ +function findDOMNodeUntilReact19(instance: React.Component): Element | null { + const node = ReactDOM.findDOMNode(instance); + return isElement(node) ? node : null; +} + /** * proxy component that delays loading of a control until it comes into view * * @class VisibilityProxy - * @extends {React.Component} + * @extends {React.Component} */ -class VisibilityProxy extends React.PureComponent { +class VisibilityProxy extends React.PureComponent { // need to use maps because the keys aren't PODs private static sObservers: Map = new Map(); private static sInstances: Map void> = new Map(); private static getObserver(container: HTMLElement) { - if (!VisibilityProxy.sObservers.has(container || null)) { + const root = container || null; + if (!VisibilityProxy.sObservers.has(root)) { VisibilityProxy.sObservers.set( - container || null, + root, new IntersectionObserver(VisibilityProxy.callback, { - root: container, + root, rootMargin: "360px 0px 360px 0px", } as any), ); } - return VisibilityProxy.sObservers.get(container); + return VisibilityProxy.sObservers.get(root); } private static callback(entries: IntersectionObserverEntry[], observer: IntersectionObserver) { @@ -50,16 +144,12 @@ class VisibilityProxy extends React.PureComponent { }); } - private static observe( - container: HTMLElement, - target: HTMLElement, - cb: (visible: boolean) => void, - ) { + private static observe(container: HTMLElement, target: Element, cb: (visible: boolean) => void) { VisibilityProxy.sInstances.set(target, cb); VisibilityProxy.getObserver(container).observe(target); } - private static unobserve(container: HTMLElement, target: HTMLElement) { + private static unobserve(container: HTMLElement, target: Element) { if (target === null) { return; } @@ -77,26 +167,97 @@ class VisibilityProxy extends React.PureComponent { private mLastVisible: boolean = false; private mVisibleTime: number = 0; - // `container` is read once, on mount; a later change is ignored. The conflict editor - // passes a ref's `current`, null until it re-renders and then an element that doesn't - // clip, so moving to the new container would count every entry as visible. - #observed: { container: HTMLElement; node: HTMLElement }; + /** + * The container read on mount; a later change is ignored. The conflict editor passes a ref's + * `current`, null until it re-renders and then an element that doesn't clip, so moving to the + * new container would count every entry as visible. + */ + #container: HTMLElement | undefined; + #mounted: boolean = false; + #observed: Element | undefined; + /** the element the ref gave: the componentClass's, or the
    used when there's none */ + #element: Element | null = null; #inView: boolean = false; #hideTimer: ReturnType | undefined; public componentDidMount() { - const node = ReactDOM.findDOMNode(this) as HTMLElement; - this.#observed = { container: this.props.container, node }; - VisibilityProxy.observe(this.props.container, node, (visible: boolean) => - this.onIntersection(node, visible), - ); + this.#mounted = true; + this.#container = this.props.container; + if (this.props.componentClass === undefined) { + warnNoComponentClass(); + } + this.observeElement(); } + public componentDidUpdate() { + this.observeElement(); + } + + /** + * Forgets the observed element as well as unobserving it: StrictMode and `` mount + * the same instance again, and it has to start observing afresh. + */ public componentWillUnmount() { + this.#mounted = false; clearTimeout(this.#hideTimer); - VisibilityProxy.unobserve(this.#observed.container, this.#observed.node); + if (this.#observed !== undefined) { + VisibilityProxy.unobserve(this.#container, this.#observed); + this.#observed = undefined; + } + } + + /** The element whose visibility this proxy tracks: the componentClass's, or its own
    . */ + public get element(): Element | null { + return this.#observed ?? null; } + /** + * Observes the element the content is in, moving off the one observed before if it was + * replaced, e.g. by a new componentClass. One that doesn't pass its ref on to an element is + * found with findDOMNode instead. + */ + private observeElement() { + const element = this.#element ?? this.findElementWithoutRef(); + if (element === null || element === this.#observed) { + return; + } + if (this.#observed !== undefined) { + VisibilityProxy.unobserve(this.#container, this.#observed); + } + this.#observed = element; + VisibilityProxy.observe(this.#container, element, (visible: boolean) => + this.onIntersection(visible), + ); + } + + /** + * The element of a componentClass whose ref gave none. Without a componentClass there's + * nothing to find: the
    rendered in its place always hands over its ref. No warning when + * there's no element yet: a forwardRef that renders null at first gives its ref later. + */ + private findElementWithoutRef(): Element | null { + const { componentClass } = this.props; + if (componentClass === undefined) { + return null; + } + const element = findDOMNodeUntilReact19(this); + if (element !== null) { + warnNoElement(componentClass); + } + return element; + } + + /** + * Once mounted, a new element is observed as soon as its ref arrives: a componentClass can + * replace its element without this proxy re-rendering, as Fast Refresh does in development. + */ + private setElement = (ref: unknown) => { + this.#element = isElement(ref) ? ref : null; + if (this.#mounted && this.#element !== null) { + this.observeElement(); + } + }; + // workaround: There is the situation where when an element becomes visible it // changes the layout around it which in turn pushes the element somwhere where it // _isn't_ visible anymore, triggering an endless loop of the element switching @@ -104,7 +265,7 @@ class VisibilityProxy extends React.PureComponent { // became visible less than a second ago. The observer is flank triggered, so it won't // report the element again: a hide that arrives within that second is deferred until // the second has passed, then applied if the element is still out of view. - private onIntersection(node: HTMLElement, visible: boolean) { + private onIntersection(visible: boolean) { this.#inView = visible; if (visible) { clearTimeout(this.#hideTimer); @@ -121,9 +282,7 @@ class VisibilityProxy extends React.PureComponent { } else { this.#hideTimer = setTimeout(() => { this.#hideTimer = undefined; - // without a componentClass, content that renders a different element replaces the - // observed node. A report on the detached node says nothing about the content. - if (!this.#inView && node.isConnected) { + if (!this.#inView) { this.applyVisible(false); } }, remaining); @@ -154,11 +313,13 @@ class VisibilityProxy extends React.PureComponent { : this.props.placeholder(); if (Component === undefined) { - // return
    {content}
    ; - return <>{content}; - } else { - return {content}; + return
    {content}
    ; } + return ( + + {content} + + ); } } diff --git a/src/renderer/src/controls/api.ts b/src/renderer/src/controls/api.ts index 993b3f4c40..32ffdc9519 100644 --- a/src/renderer/src/controls/api.ts +++ b/src/renderer/src/controls/api.ts @@ -35,7 +35,7 @@ import OptionsFilter from "./table/OptionsFilter"; import TableTextFilter from "./table/TextFilter"; import Timer from "./Timer"; import Toggle from "./Toggle"; -import ToolbarIcon from "./ToolbarIcon"; +import ToolbarIcon from "./toolbar_icon/ToolbarIcon"; import ToolIcon from "./ToolIcon"; import * as tooltip from "./TooltipControls"; import TriStateCheckbox from "./TriStateCheckbox"; diff --git a/src/renderer/src/controls/table/MyTable.tsx b/src/renderer/src/controls/table/MyTable.tsx index 8e958bd7f4..74acc3d0c9 100644 --- a/src/renderer/src/controls/table/MyTable.tsx +++ b/src/renderer/src/controls/table/MyTable.tsx @@ -74,22 +74,35 @@ export class TH extends React.Component { } type TRProps = DProps & { - domRef?: (ref: HTMLDivElement) => void; + domRef?: (ref: HTMLTableRowElement | null) => void; }; -export function TR(props: TRProps) { +// Passes a ref on to its as well as domRef, so VisibilityProxy can observe the row +// when TableRow hands it TR as its componentClass. +export const TR = React.forwardRef(function TR(props, ref) { const { className, domRef } = props; const classes = ["xtr"].concat((className || "").split(" ")); + const setRef = React.useCallback( + (element: HTMLTableRowElement | null) => { + domRef?.(element); + if (typeof ref === "function") { + ref(element); + } else if (ref !== null) { + ref.current = element; + } + }, + [domRef, ref], + ); return ( {props.children} ); -} +}); type TDProps = DProps & { domRef?: (ref: HTMLDivElement) => void; diff --git a/src/renderer/src/controls/toolbar_icon/ToolbarIcon.test.tsx b/src/renderer/src/controls/toolbar_icon/ToolbarIcon.test.tsx new file mode 100644 index 0000000000..fc2babf272 --- /dev/null +++ b/src/renderer/src/controls/toolbar_icon/ToolbarIcon.test.tsx @@ -0,0 +1,32 @@ +import { render } from "@testing-library/react"; +import React, { createRef } from "react"; +import { describe, expect, it } from "vitest"; + +import ToolbarIcon from "./ToolbarIcon"; + +describe("ToolbarIcon", () => { + it("hands its button element to domRef", () => { + const domRef = createRef(); + const { getByRole } = render(); + + expect(domRef.current).toBe(getByRole("button")); + }); + + it("renders the same button without a domRef", () => { + const { getByRole } = render(); + + expect(getByRole("button")).toHaveClass("manage"); + }); + + // a new ); + + expect(domRef.current).toBe(screen.getByRole("button", { name: "Manage" })); + expect(domRef.current).toHaveClass("btn"); + }); + + it("gets the element out of react-bootstrap's MenuItem", () => { + const domRef = createRef(); + const props = { componentClass: AnchorWithDomRef, domRef }; + + render(Open); + + expect(domRef.current).toBe(screen.getByRole("menuitem", { name: "Open" })); + }); +}); diff --git a/src/renderer/src/controls/with_dom_ref/withDomRef.ts b/src/renderer/src/controls/with_dom_ref/withDomRef.ts new file mode 100644 index 0000000000..48ab3d3b15 --- /dev/null +++ b/src/renderer/src/controls/with_dom_ref/withDomRef.ts @@ -0,0 +1,23 @@ +// react-bootstrap 0.33's components (Button, MenuItem) don't pass a ref on to the element they +// render, so getting at that element used to take findDOMNode. They do render their +// componentClass with every prop they don't use themselves, so a componentClass made here, given +// a domRef prop, hands back the element instead. +import { createElement, type FC, type HTMLAttributes, type Ref } from "react"; + +export type WithDomRefProps = HTMLAttributes< + HTMLElementTagNameMap[K] +> & { + /** receives the rendered element */ + domRef?: Ref; +}; + +/** + * Makes a component that renders a `tag` element and hands that element to its `domRef` prop. + * Pass it to a react-bootstrap 0.33 component as `componentClass`, with `domRef`. + */ +export function withDomRef(tag: K): FC> { + const ElementWithDomRef: FC> = ({ domRef, ...props }) => + createElement(tag, { ...props, ref: domRef }); + ElementWithDomRef.displayName = `withDomRef(${tag})`; + return ElementWithDomRef; +} diff --git a/src/renderer/src/extensions/download_management/views/ShutdownButton.tsx b/src/renderer/src/extensions/download_management/views/ShutdownButton.tsx index 569abea2d5..5294a2caa1 100644 --- a/src/renderer/src/extensions/download_management/views/ShutdownButton.tsx +++ b/src/renderer/src/extensions/download_management/views/ShutdownButton.tsx @@ -1,6 +1,6 @@ import * as React from "react"; -import ToolbarIcon from "../../../controls/ToolbarIcon"; +import ToolbarIcon from "../../../controls/toolbar_icon/ToolbarIcon"; import type { TFunction } from "../../../util/i18n"; import type { IDownload } from "../types/IDownload"; diff --git a/src/renderer/src/extensions/file_based_loadorder/views/FileBasedLoadOrderPage.tsx b/src/renderer/src/extensions/file_based_loadorder/views/FileBasedLoadOrderPage.tsx index 6a7ed9a35c..a29f5d7de2 100644 --- a/src/renderer/src/extensions/file_based_loadorder/views/FileBasedLoadOrderPage.tsx +++ b/src/renderer/src/extensions/file_based_loadorder/views/FileBasedLoadOrderPage.tsx @@ -6,8 +6,8 @@ import type { Dispatch } from "redux"; import { ComponentEx } from "../../../controls/ComponentEx"; import IconBar from "../../../controls/IconBar"; +import ToolbarIcon from "../../../controls/toolbar_icon/ToolbarIcon"; import ToolbarDropdown from "../../../controls/ToolbarDropdown"; -import ToolbarIcon from "../../../controls/ToolbarIcon"; import type { IActionDefinition } from "../../../types/IActionDefinition"; import type { IState } from "../../../types/IState"; import { TabBar } from "../../../ui/components/tabs/TabBar"; diff --git a/src/renderer/src/extensions/gamebryo_plugin_management/views/PluginList.tsx b/src/renderer/src/extensions/gamebryo_plugin_management/views/PluginList.tsx index 118d3dc1b3..2b726a7bf6 100644 --- a/src/renderer/src/extensions/gamebryo_plugin_management/views/PluginList.tsx +++ b/src/renderer/src/extensions/gamebryo_plugin_management/views/PluginList.tsx @@ -27,7 +27,7 @@ import More from "../../../controls/More"; import Spinner from "../../../controls/Spinner"; import Table, { type ITableRowAction } from "../../../controls/Table"; import TableTextFilter from "../../../controls/table/TextFilter"; -import ToolbarIcon from "../../../controls/ToolbarIcon"; +import ToolbarIcon from "../../../controls/toolbar_icon/ToolbarIcon"; import * as tooltip from "../../../controls/TooltipControls"; import Usage from "../../../controls/Usage"; import { log } from "../../../logging"; diff --git a/src/renderer/src/extensions/gamemode_management/views/HideGameIcon.tsx b/src/renderer/src/extensions/gamemode_management/views/HideGameIcon.tsx index ffe798788e..bb3889a844 100644 --- a/src/renderer/src/extensions/gamemode_management/views/HideGameIcon.tsx +++ b/src/renderer/src/extensions/gamemode_management/views/HideGameIcon.tsx @@ -4,7 +4,7 @@ import type { ThunkDispatch } from "redux-thunk"; import { ComponentEx, connect } from "../../../controls/ComponentEx"; import type { ButtonType } from "../../../controls/IconBar"; -import ToolbarIcon from "../../../controls/ToolbarIcon"; +import ToolbarIcon from "../../../controls/toolbar_icon/ToolbarIcon"; import { getSafe } from "../../../util/storeHelper"; import { setGameHidden } from "../actions/settings"; import type { IDiscoveryResult } from "../types/IDiscoveryResult"; diff --git a/src/renderer/src/extensions/mod_management/views/ActivationButton.tsx b/src/renderer/src/extensions/mod_management/views/ActivationButton.tsx index 91f310dcfc..6bf3549ef2 100644 --- a/src/renderer/src/extensions/mod_management/views/ActivationButton.tsx +++ b/src/renderer/src/extensions/mod_management/views/ActivationButton.tsx @@ -5,7 +5,7 @@ import type { ThunkDispatch } from "redux-thunk"; import { addNotification } from "../../../actions/notifications"; import { setSettingsPage } from "../../../actions/session"; import { ComponentEx, connect, translate } from "../../../controls/ComponentEx"; -import ToolbarIcon from "../../../controls/ToolbarIcon"; +import ToolbarIcon from "../../../controls/toolbar_icon/ToolbarIcon"; import type { INotificationAction } from "../../../types/INotification"; import type { IState } from "../../../types/IState"; import { UserCanceled } from "../../../util/CustomErrors"; diff --git a/src/renderer/src/extensions/mod_management/views/CheckModVersionsButton.tsx b/src/renderer/src/extensions/mod_management/views/CheckModVersionsButton.tsx index 4c67275565..5b1249cc7b 100644 --- a/src/renderer/src/extensions/mod_management/views/CheckModVersionsButton.tsx +++ b/src/renderer/src/extensions/mod_management/views/CheckModVersionsButton.tsx @@ -3,7 +3,7 @@ import * as React from "react"; import { ComponentEx, connect, translate } from "../../../controls/ComponentEx"; import type { ButtonType } from "../../../controls/IconBar"; -import ToolbarIcon from "../../../controls/ToolbarIcon"; +import ToolbarIcon from "../../../controls/toolbar_icon/ToolbarIcon"; import { activeGameId, activeProfile } from "../../../util/selectors"; import { getSafe } from "../../../util/storeHelper"; import type { IProfileMod } from "../../profile_management/types/IProfile"; diff --git a/src/renderer/src/extensions/mod_management/views/DeactivationButton.tsx b/src/renderer/src/extensions/mod_management/views/DeactivationButton.tsx index fb788eaf29..601709e891 100644 --- a/src/renderer/src/extensions/mod_management/views/DeactivationButton.tsx +++ b/src/renderer/src/extensions/mod_management/views/DeactivationButton.tsx @@ -12,7 +12,7 @@ import type { import { addNotification, showDialog } from "../../../actions/notifications"; import { setSettingsPage } from "../../../actions/session"; import { ComponentEx, connect, translate } from "../../../controls/ComponentEx"; -import ToolbarIcon from "../../../controls/ToolbarIcon"; +import ToolbarIcon from "../../../controls/toolbar_icon/ToolbarIcon"; import type { INotificationAction } from "../../../types/INotification"; import type { IState } from "../../../types/IState"; import { TemporaryError, UserCanceled } from "../../../util/CustomErrors"; diff --git a/src/renderer/src/extensions/mod_management/views/InstallArchiveButton.tsx b/src/renderer/src/extensions/mod_management/views/InstallArchiveButton.tsx index 9b3918c612..6460c82f9b 100644 --- a/src/renderer/src/extensions/mod_management/views/InstallArchiveButton.tsx +++ b/src/renderer/src/extensions/mod_management/views/InstallArchiveButton.tsx @@ -3,7 +3,7 @@ import * as React from "react"; import { ComponentEx, connect, translate } from "../../../controls/ComponentEx"; import type { ButtonType } from "../../../controls/IconBar"; -import ToolbarIcon from "../../../controls/ToolbarIcon"; +import ToolbarIcon from "../../../controls/toolbar_icon/ToolbarIcon"; import type { IState } from "../../../types/IState"; import { fileMD5 } from "../../../util/checksum"; import * as fs from "../../../util/fs"; diff --git a/src/renderer/test-setup.mts b/src/renderer/test-setup.mts index e7992e265e..5d9d6e67b9 100644 --- a/src/renderer/test-setup.mts +++ b/src/renderer/test-setup.mts @@ -11,6 +11,7 @@ install(); import "@testing-library/jest-dom/vitest"; import type { VortexPaths } from "@vortex/shared/ipc"; +import type * as ReactDOMModule from "react-dom"; import { afterAll, afterEach, beforeAll, vi } from "vitest"; import { ApplicationData } from "./src/applicationData.js"; @@ -19,7 +20,7 @@ import { ApplicationData } from "./src/applicationData.js"; // says how to fix one. console.error is assigned rather than spied on so vi.restoreAllMocks() // leaves it be, and the check runs after testing-library's cleanup (vitest.config.mts runs hooks // last-registered first), so an update that lands while a test is torn down still counts. -let componentsUpdatedOutsideAct = new Set(); +const componentsUpdatedOutsideAct = new Set(); const originalConsoleError = console.error; console.error = (...args: unknown[]) => { if (typeof args[0] === "string" && args[0].includes("not wrapped in act")) { @@ -28,17 +29,55 @@ console.error = (...args: unknown[]) => { } originalConsoleError.apply(console, args); }; -const failOnActWarnings = () => { - const components = [...componentsUpdatedOutsideAct]; - componentsUpdatedOutsideAct = new Set(); - if (components.length > 0) { - throw new Error( - `React updated ${components.join(", ")} outside act(); see "React warnings" in docs/testing.md`, - ); + +// A call to findDOMNode from our own code fails the test it ran in; React 19 removes it, and +// "React warnings" in docs/testing.md says what to use instead. React's own warning can't drive +// this: it's logged once per test file, and react-bootstrap 0.33 and react-overlays still call +// findDOMNode themselves, so theirs would hide ours. vi.mock only reaches the modules vitest +// transforms, our source, and not the copy of react-dom those libraries require() for themselves. +// The callers named in `allowedFindDOMNodeCallers` are let through. +const { allowedFindDOMNodeCallers, findDOMNodeCallers } = vi.hoisted(() => ({ + /** + * Functions that call findDOMNode on purpose until React 19, for extension components that + * don't pass a ref on. Each is named for that, so a new call elsewhere still fails. + */ + allowedFindDOMNodeCallers: ["findDOMNodeUntilReact19"], + findDOMNodeCallers: new Set(), +})); +vi.mock("react-dom", async (importOriginal) => { + const original = await importOriginal(); + const findDOMNode: typeof original.findDOMNode = (instance) => { + // the frame below this one is whoever called findDOMNode + const caller = new Error().stack?.split("\n")[2]?.trim().replace(/^at /, ""); + if (!allowedFindDOMNodeCallers.some((allowed) => caller?.startsWith(`${allowed} `))) { + findDOMNodeCallers.add(caller ?? "unknown code"); + } + return original.findDOMNode(instance); + }; + return { ...original, findDOMNode, default: { ...original, findDOMNode } }; +}); + +/** + * Fails the test for both checks above at once. Vitest skips the after-hooks left to run once + * one throws, so with a hook each, a test failing one check would leave the other's findings + * to be blamed on the next test. + */ +const failOnReactWarnings = () => { + const problems: string[] = []; + if (componentsUpdatedOutsideAct.size > 0) { + problems.push(`React updated ${[...componentsUpdatedOutsideAct].join(", ")} outside act()`); + } + if (findDOMNodeCallers.size > 0) { + problems.push(`findDOMNode was called from ${[...findDOMNodeCallers].join(", ")}`); + } + componentsUpdatedOutsideAct.clear(); + findDOMNodeCallers.clear(); + if (problems.length > 0) { + throw new Error(`${problems.join("; ")}; see "React warnings" in docs/testing.md`); } }; -afterEach(failOnActWarnings); -afterAll(failOnActWarnings); +afterEach(failOnReactWarnings); +afterAll(failOnReactWarnings); // No test initialises i18next, so react-i18next warns once per file and falls back to // returning the key. The source strings in this repo are the keys, so that fallback is