Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 27 additions & 5 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ function VisibilityProxyWrap(props: IVisibilityProxyWrapProps) {

return (
<VisibilityProxy
componentClass="div"
container={container}
content={content}
placeholder={placeholder}
Expand Down
37 changes: 33 additions & 4 deletions src/renderer/src/controls/ContextMenu.test.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
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 type { IActionDefinitionEx } from "./ActionControl";
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<{
Expand All @@ -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 });

Expand All @@ -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]}
/>
</LegacyContextProvider>
);
Expand All @@ -65,6 +76,7 @@ describe("ContextMenu", () => {

afterEach(() => {
menuLayer.remove();
vi.restoreAllMocks();
});

it("stays open after the right-click that opened it (React 17 delegation)", () => {
Expand Down Expand Up @@ -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");
Comment thread
r1chm8 marked this conversation as resolved.
Resolved
const more = {
title: "More",
show: true,
subMenus: [{ title: "Sub Action", action: () => undefined, show: true }],
};
render(<Harness menuLayer={menuLayer} actions={[more]} />);
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"));
});
});
18 changes: 13 additions & 5 deletions src/renderer/src/controls/ContextMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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> a MenuItem renders, handed back through domRef: react-bootstrap 0.33's MenuItem
* doesn't pass a ref on. MenuItem renders an <li> around it, and a submenu opens next to that
* <li>, the <a>'s parent.
*/
const AnchorWithDomRef = withDomRef("a");

export interface IMenuActionProps {
t: TFunction;
Expand Down Expand Up @@ -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 (
<MenuItem
Expand All @@ -126,7 +134,7 @@ function MenuAction(props: IMenuActionProps) {
onMouseEnter={action.subMenus !== undefined ? show : undefined}
onMouseLeave={action.subMenus !== undefined ? hide : undefined}
disabled={action.show !== true}
ref={setItemRef}
{...anchorProps}
title={typeof action.show === "string" ? t(action.show) : undefined}
>
{action.component !== undefined ? (
Expand Down
11 changes: 3 additions & 8 deletions src/renderer/src/controls/IconBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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";
Expand Down Expand Up @@ -109,7 +108,7 @@ function IconBarIcon(props: IIconBarIconProps) {
[setOpenMenu, icon.subMenus],
);

const itemRef = React.useRef<HTMLElement>();
const itemRef = React.useRef<HTMLButtonElement>(null);

const trigger = React.useCallback(() => {
icon.action?.(instanceIds, icon.data);
Expand All @@ -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 (
<ToolbarIcon
key={actionId}
ref={setItemRef}
domRef={itemRef}
className={actionId}
instanceId={instanceIds}
icon={hasIcon ? icon.icon : undefined}
Expand Down
2 changes: 1 addition & 1 deletion src/renderer/src/controls/InputButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
23 changes: 11 additions & 12 deletions src/renderer/src/controls/Table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@ 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";

export type ChangeDataHandler = (rowId: string, attributeId: string, newValue: any) => void;

Expand Down Expand Up @@ -174,7 +175,7 @@ class SuperTable extends ComponentEx<IProps, IComponentState> {
// 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;
Expand Down Expand Up @@ -625,7 +626,7 @@ class SuperTable extends ComponentEx<IProps, IComponentState> {

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) {
Expand Down Expand Up @@ -1022,8 +1023,8 @@ class SuperTable extends ComponentEx<IProps, IComponentState> {
// 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;
Expand Down Expand Up @@ -1054,11 +1055,9 @@ class SuperTable extends ComponentEx<IProps, IComponentState> {
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) =>
Expand Down Expand Up @@ -1205,7 +1204,7 @@ class SuperTable extends ComponentEx<IProps, IComponentState> {
this.mPinnedRef = ref;
};

private setRowRef = (ref: any) => {
private setRowRef = (ref: VisibilityProxy | null) => {
if (ref !== null) {
this.mRowRefs[ref.props["data-rowid"]] = ref;
}
Expand Down Expand Up @@ -1266,7 +1265,7 @@ class SuperTable extends ComponentEx<IProps, IComponentState> {
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.
Expand Down
Loading