From 2e7a08ad97c355f4a3b77f6bf7d2c10b9bdf7631 Mon Sep 17 00:00:00 2001 From: ecemooo Date: Wed, 18 Nov 2026 18:59:24 +0300 Subject: [PATCH 1/4] fix: stop calling findDOMNode from our own components (LAZ-1698) --- docs/testing.md | 27 ++++-- .../src/controls/ContextMenu.test.tsx | 31 ++++++- src/renderer/src/controls/ContextMenu.tsx | 22 +++-- src/renderer/src/controls/IconBar.tsx | 9 +- src/renderer/src/controls/Table.tsx | 19 ++-- .../src/controls/ToolbarIcon.test.tsx | 22 +++++ src/renderer/src/controls/ToolbarIcon.tsx | 30 ++++++- .../controls/VisibilityProxy.hide.test.tsx | 33 ++++--- .../src/controls/VisibilityProxy.test.tsx | 86 +++++++++++++++++-- src/renderer/src/controls/VisibilityProxy.tsx | 44 +++++++--- src/renderer/src/controls/table/MyTable.tsx | 19 +++- src/renderer/test-setup.mts | 29 +++++++ 12 files changed, 301 insertions(+), 70 deletions(-) create mode 100644 src/renderer/src/controls/ToolbarIcon.test.tsx diff --git a/docs/testing.md b/docs/testing.md index b2149f95a5..d1e52de19a 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -101,6 +101,19 @@ 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` that does: +`ButtonWithRef` in `src/renderer/src/controls/ToolbarIcon.tsx` and +`AnchorWithRef` in `src/renderer/src/controls/ContextMenu.tsx` 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. + ### What the check can't see - `waitFor`, the `findBy…` queries and `userEvent` turn React's `act()` checks @@ -114,11 +127,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` and `DraggableList`. ## Extension tests diff --git a/src/renderer/src/controls/ContextMenu.test.tsx b/src/renderer/src/controls/ContextMenu.test.tsx index a4c71a4be0..d9bd4a8213 100644 --- a/src/renderer/src/controls/ContextMenu.test.tsx +++ b/src/renderer/src/controls/ContextMenu.test.tsx @@ -1,10 +1,14 @@ -import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import * as PropTypes from "prop-types"; import * as React from "react"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import ContextMenu from "./ContextMenu"; +// Icon loads its font set into an `#icon-sets` element the test document lacks; a submenu +// item shows one. +vi.mock("./Icon", () => ({ 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 +34,9 @@ class LegacyContextProvider extends React.Component<{ } } -function Harness(props: { menuLayer: HTMLElement }) { +const testAction = { title: "Test Action", action: () => undefined, show: true } as any; + +function Harness(props: { menuLayer: HTMLElement; actions?: any[] }) { const [visible, setVisible] = React.useState(false); const [position, setPosition] = React.useState({ x: 0, y: 0 }); @@ -49,7 +55,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]} /> ); @@ -93,4 +99,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 item = within(menuLayer).getByText("More").closest("li"); + + fireEvent.mouseEnter(item.querySelector("a")); + + await waitFor(() => expect(menuLayer.textContent).toContain("Sub Action")); + expect(measured.mock.contexts).toContain(item); + }); }); diff --git a/src/renderer/src/controls/ContextMenu.tsx b/src/renderer/src/controls/ContextMenu.tsx index ee4cd204b8..1f5c75575b 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"; @@ -12,6 +11,17 @@ import { HOVER_DELAY } from "./constants"; import Dropdown from "./Dropdown"; import Icon from "./Icon"; +type AnchorWithRefProps = React.AnchorHTMLAttributes & { + anchorRef: React.Ref; +}; + +// react-bootstrap 0.33's MenuItem doesn't pass a ref on to its element. It renders an
  • +// around its componentClass, and gives that componentClass every prop it doesn't use itself, +// anchorRef among them. +function AnchorWithRef({ anchorRef, ...props }: AnchorWithRefProps) { + return ; +} + export interface IMenuActionProps { t: TFunction; id: string; @@ -115,9 +125,11 @@ function MenuAction(props: IMenuActionProps) { }, HOVER_DELAY); }, [setOpen]); - const setItemRef = (ref) => { - itemRef.current = ReactDOM.findDOMNode(ref) as HTMLElement; - }; + // the submenu opens next to the item's
  • , the parent of its + const setAnchorRef = React.useCallback((anchor: HTMLAnchorElement | null) => { + itemRef.current = anchor?.parentElement ?? undefined; + }, []); + const anchorProps = { componentClass: AnchorWithRef, anchorRef: setAnchorRef }; return ( {action.component !== undefined ? ( diff --git a/src/renderer/src/controls/IconBar.tsx b/src/renderer/src/controls/IconBar.tsx index d27a46915b..7c7ca1a8c1 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"; @@ -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; } diff --git a/src/renderer/src/controls/ToolbarIcon.test.tsx b/src/renderer/src/controls/ToolbarIcon.test.tsx new file mode 100644 index 0000000000..281b9336fe --- /dev/null +++ b/src/renderer/src/controls/ToolbarIcon.test.tsx @@ -0,0 +1,22 @@ +import { render } from "@testing-library/react"; +import * as React from "react"; +import { describe, expect, it } from "vitest"; + +import ToolbarIcon from "./ToolbarIcon"; + +describe("ToolbarIcon", () => { + it("hands its button element to buttonRef", () => { + const buttonRef = React.createRef(); + const { getByRole } = render( + , + ); + + expect(buttonRef.current).toBe(getByRole("button")); + }); + + it("renders the same button without a buttonRef", () => { + const { getByRole } = render(); + + expect(getByRole("button")).toHaveClass("manage"); + }); +}); diff --git a/src/renderer/src/controls/ToolbarIcon.tsx b/src/renderer/src/controls/ToolbarIcon.tsx index fa49f7f0c9..3aedf7500d 100644 --- a/src/renderer/src/controls/ToolbarIcon.tsx +++ b/src/renderer/src/controls/ToolbarIcon.tsx @@ -19,13 +19,38 @@ export interface IToolbarIconProps { stroke?: boolean; hollow?: boolean; children?: React.ReactNode; + /** receives the icon's ); + + 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; +} From 450028c134326baa2b2686729afa239550c7b424 Mon Sep 17 00:00:00 2001 From: ecemooo Date: Thu, 19 Nov 2026 18:01:10 +0300 Subject: [PATCH 3/4] fix: keep VisibilityProxy lazy for any componentClass and follow a replaced element (LAZ-1698) --- .../src/views/ConflictEditor.tsx | 1 + .../src/controls/ContextMenu.test.tsx | 9 +- src/renderer/src/controls/ContextMenu.tsx | 8 +- src/renderer/src/controls/IconBar.tsx | 2 +- src/renderer/src/controls/InputButton.tsx | 2 +- src/renderer/src/controls/Table.tsx | 4 +- .../controls/VisibilityProxy.hide.test.tsx | 36 ++++ .../src/controls/VisibilityProxy.test.tsx | 117 +++++++++++- src/renderer/src/controls/VisibilityProxy.tsx | 169 +++++++++++++----- src/renderer/src/controls/api.ts | 2 +- .../{ => toolbar_icon}/ToolbarIcon.test.tsx | 0 .../{ => toolbar_icon}/ToolbarIcon.tsx | 12 +- .../views/ShutdownButton.tsx | 2 +- .../views/FileBasedLoadOrderPage.tsx | 2 +- .../views/PluginList.tsx | 2 +- .../views/HideGameIcon.tsx | 2 +- .../mod_management/views/ActivationButton.tsx | 2 +- .../views/CheckModVersionsButton.tsx | 2 +- .../views/DeactivationButton.tsx | 2 +- .../views/InstallArchiveButton.tsx | 2 +- src/renderer/test-setup.mts | 40 ++--- 21 files changed, 322 insertions(+), 96 deletions(-) rename src/renderer/src/controls/{ => toolbar_icon}/ToolbarIcon.test.tsx (100%) rename src/renderer/src/controls/{ => toolbar_icon}/ToolbarIcon.tsx (86%) 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 ( { afterEach(() => { menuLayer.remove(); + vi.restoreAllMocks(); }); it("stays open after the right-click that opened it (React 17 delegation)", () => { @@ -114,11 +115,11 @@ describe("ContextMenu", () => { }; render(); fireEvent.contextMenu(screen.getByTestId("row"), { clientX: 10, clientY: 10 }); - const item = within(menuLayer).getByText("More").closest("li"); + const [anchor] = within(menuLayer).getAllByRole("menuitem"); - fireEvent.mouseEnter(item.querySelector("a")); + fireEvent.mouseEnter(anchor); - await waitFor(() => expect(menuLayer.textContent).toContain("Sub Action")); - expect(measured.mock.contexts).toContain(item); + 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 493dcb8d0a..ba68544e86 100644 --- a/src/renderer/src/controls/ContextMenu.tsx +++ b/src/renderer/src/controls/ContextMenu.tsx @@ -12,8 +12,11 @@ import Dropdown from "./Dropdown"; import Icon from "./Icon"; import { withDomRef } from "./with_dom_ref/withDomRef"; -// react-bootstrap 0.33's MenuItem doesn't pass a ref on. It renders an
  • around its -// componentClass, so the comes back through domRef and the
  • is its parent. +/** + * 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 { @@ -119,7 +122,6 @@ function MenuAction(props: IMenuActionProps) { }, HOVER_DELAY); }, [setOpen]); - // the submenu opens next to the item's
  • , the parent of its const setAnchorRef = React.useCallback((anchor: HTMLAnchorElement | null) => { itemRef.current = anchor?.parentElement ?? undefined; }, []); diff --git a/src/renderer/src/controls/IconBar.tsx b/src/renderer/src/controls/IconBar.tsx index 10ecf22b2f..c0a9e031c4 100644 --- a/src/renderer/src/controls/IconBar.tsx +++ b/src/renderer/src/controls/IconBar.tsx @@ -13,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"; diff --git a/src/renderer/src/controls/InputButton.tsx b/src/renderer/src/controls/InputButton.tsx index 57d36c0441..81b9023170 100644 --- a/src/renderer/src/controls/InputButton.tsx +++ b/src/renderer/src/controls/InputButton.tsx @@ -9,7 +9,7 @@ import type { IState } from "../types/IState"; import { getSafe } from "../util/storeHelper"; import { ComponentEx, connect, translate } from "./ComponentEx"; import Icon from "./Icon"; -import ToolbarIcon from "./ToolbarIcon"; +import ToolbarIcon from "./toolbar_icon/ToolbarIcon"; import { Button } from "./TooltipControls"; export interface IBaseProps { diff --git a/src/renderer/src/controls/Table.tsx b/src/renderer/src/controls/Table.tsx index a9767b8def..e0e8356d64 100644 --- a/src/renderer/src/controls/Table.tsx +++ b/src/renderer/src/controls/Table.tsx @@ -47,7 +47,7 @@ import { registerTableAttribute } from "./table/registerTableAttribute"; import { scrollContainerOf } from "./table/scrollContainer"; import TableDetail from "./table/TableDetail"; import TableRow from "./table/TableRow"; -import ToolbarIcon from "./ToolbarIcon"; +import ToolbarIcon from "./toolbar_icon/ToolbarIcon"; import { UsageAlert } from "./UsageAlert"; import type VisibilityProxy from "./VisibilityProxy"; @@ -1265,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 be6d3680ec..1bbae1b9fa 100644 --- a/src/renderer/src/controls/VisibilityProxy.hide.test.tsx +++ b/src/renderer/src/controls/VisibilityProxy.hide.test.tsx @@ -169,6 +169,42 @@ describe("VisibilityProxy hiding", () => { expect(vi.getTimerCount()).toBe(0); }); + // 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(); + }); + // 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. // ConflictEditor (mod-dependency-manager) uses it this way. diff --git a/src/renderer/src/controls/VisibilityProxy.test.tsx b/src/renderer/src/controls/VisibilityProxy.test.tsx index 4ced1b3d17..139b55c8d2 100644 --- a/src/renderer/src/controls/VisibilityProxy.test.tsx +++ b/src/renderer/src/controls/VisibilityProxy.test.tsx @@ -137,29 +137,130 @@ describe("VisibilityProxy", () => { expect(calls).toEqual([{ op: "observe", root: null, target: getByTestId("row") }]); }); - // An extension's componentClass may not give a ref to its element. The proxy can't know - // when that comes into view, so it shows the content rather than a placeholder forever. - it("shows the content when its componentClass gives no element to observe", () => { + 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 give a ref to its element, so the proxy puts a
    + // inside it to observe instead, and the content still loads as it scrolls into view. + it("observes a
    inside a componentClass that gives no element", () => { const setVisible = vi.fn(); - render( + const { getByTestId } = render( null} - placeholder={() => null} + placeholder={() => } visible={false} setVisible={setVisible} />, ); - expect(calls).toEqual([]); - expect(setVisible).toHaveBeenCalledWith(true); - // an extension author can see why their content no longer loads lazily + const wrapper = getByTestId("entry").parentElement; + expect(wrapper?.parentElement?.tagName).toBe("DIV"); + expect(calls).toEqual([{ op: "observe", root: null, target: wrapper }]); + expect(setVisible).not.toHaveBeenCalled(); + // an extension author can see where the extra
    comes from expect(log).toHaveBeenCalledWith( "warn", expect.stringContaining("doesn't pass its ref on"), expect.objectContaining({ componentClass: "Opaque" }), ); }); + + 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 44ecb502cf..de6ce71e7d 100644 --- a/src/renderer/src/controls/VisibilityProxy.tsx +++ b/src/renderer/src/controls/VisibilityProxy.tsx @@ -16,28 +16,82 @@ export interface IProps { componentClass?: React.ElementType; } +interface IState { + /** the componentClass gave no element to observe, so the content goes in a
    inside it */ + wrapContent: boolean; +} + +/** + * 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; + +function componentClassName(componentClass: React.ElementType): string | undefined { + return typeof componentClass === "string" + ? componentClass + : ((componentClass as { displayName?: string }).displayName ?? componentClass.name); +} + +/** 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 that their content gets an extra
    . */ +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 its content " + + "is wrapped in a
    to see when it scrolls into view", + { 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; +} + /** * proxy component that delays loading of a control until it comes into view * * @class VisibilityProxy * @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) { @@ -49,16 +103,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; } @@ -74,58 +124,84 @@ class VisibilityProxy extends React.PureComponent { } } + public state: IState = { wrapContent: false }; + 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 } | undefined; - // the element render() puts the content in: the componentClass's, or the wrapping
    - #element: HTMLElement | null = null; + /** + * 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 render() puts the content in: the componentClass's, or the wrapping
    */ + #element: Element | null = null; #inView: boolean = false; #hideTimer: ReturnType | undefined; public componentDidMount() { - const node = this.#element; - if (node === null) { - // A componentClass that doesn't pass its ref on to an element leaves nothing to observe, - // so there's no telling when it comes into view. Show the content rather than a - // placeholder that never fills, and say so: that content no longer loads lazily. - const { componentClass } = this.props; - log( - "warn", - "VisibilityProxy: componentClass doesn't pass its ref on to an element, so its " + - "content renders right away instead of when it scrolls into view", - { - componentClass: - typeof componentClass === "string" - ? componentClass - : (componentClass?.displayName ?? componentClass?.name), - }, - ); - this.applyVisible(true); - return; + this.#mounted = true; + this.#container = this.props.container; + if (this.props.componentClass === undefined) { + warnNoComponentClass(); } - this.#observed = { container: this.props.container, node }; - VisibilityProxy.observe(this.props.container, node, (visible: boolean) => - this.onIntersection(visible), - ); + this.observeElement(); + } + + public componentDidUpdate() { + this.observeElement(); } public componentWillUnmount() { + this.#mounted = false; clearTimeout(this.#hideTimer); if (this.#observed !== undefined) { - VisibilityProxy.unobserve(this.#observed.container, this.#observed.node); + VisibilityProxy.unobserve(this.#container, this.#observed); } } /** The element whose visibility this proxy tracks: the componentClass's, or its own
    . */ - public get element(): HTMLElement | null { + public get element(): Element | null { return this.#element; } + /** + * Observes the element render() put the content in, moving off the one observed before if + * it was replaced, e.g. by a new componentClass. A componentClass that gave no element gets + * its content wrapped in a
    on the next render, and that
    is observed instead. + */ + private observeElement() { + const element = this.#element; + if (element === null) { + if (!this.state.wrapContent) { + warnNoElement(this.props.componentClass); + this.setState({ wrapContent: true }); + } + return; + } + if (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), + ); + } + + /** + * 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 = ref instanceof HTMLElement ? ref : null; + 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 @@ -169,6 +245,7 @@ class VisibilityProxy extends React.PureComponent { public render(): JSX.Element { const { componentClass: Component } = this.props; + const { wrapContent } = this.state; const props = _.omit(this.props, [ "container", "placeholder", @@ -184,6 +261,12 @@ class VisibilityProxy extends React.PureComponent { if (Component === undefined) { return
    {content}
    ; + } else if (wrapContent) { + return ( + +
    {content}
    +
    + ); } else { return ( 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/ToolbarIcon.test.tsx b/src/renderer/src/controls/toolbar_icon/ToolbarIcon.test.tsx similarity index 100% rename from src/renderer/src/controls/ToolbarIcon.test.tsx rename to src/renderer/src/controls/toolbar_icon/ToolbarIcon.test.tsx diff --git a/src/renderer/src/controls/ToolbarIcon.tsx b/src/renderer/src/controls/toolbar_icon/ToolbarIcon.tsx similarity index 86% rename from src/renderer/src/controls/ToolbarIcon.tsx rename to src/renderer/src/controls/toolbar_icon/ToolbarIcon.tsx index 5294b5abb3..2f54543c53 100644 --- a/src/renderer/src/controls/ToolbarIcon.tsx +++ b/src/renderer/src/controls/toolbar_icon/ToolbarIcon.tsx @@ -1,8 +1,8 @@ import * as React from "react"; -import Icon from "./Icon"; -import { Button } from "./TooltipControls"; -import { withDomRef } from "./with_dom_ref/withDomRef"; +import Icon from "../Icon"; +import { Button } from "../TooltipControls"; +import { withDomRef } from "../with_dom_ref/withDomRef"; export interface IToolbarIconProps { id?: string; @@ -20,7 +20,10 @@ export interface IToolbarIconProps { stroke?: boolean; hollow?: boolean; children?: React.ReactNode; - /** receives the icon's