diff --git a/docs/testing.md b/docs/testing.md index b2149f95a5..b89f94dea4 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -101,6 +101,43 @@ The usual sources: testing-library's, that microtask lands outside `act()`. Re-render inside an async `act()`: `await act(async () => { rerender(…); })`. +### Legacy context, nesting and refs + +A test also fails when React warns that our own code: + +- **reads or provides legacy context** (`contextTypes`, `childContextTypes`). + Read `MainContext` instead, with `static contextType = MainContext` in a class + or `useMainContext()` in a function component. `ComponentEx` already does. A + test that renders a `ComponentEx` without the app provides it with + ``. A `ComponentEx` subclass that declares + `contextTypes` of its own reads legacy context instead, so drop them. +- **declares `contextTypes` on a class that also has `contextType`.** React + ignores the `contextTypes`; drop them. +- **fails a context type check,** such as `ComponentExProvider` rendered + without the `api` it requires (`Failed child context type`). Render it inside + a `` that has an `api`. +- **nests elements HTML doesn't allow** (`validateDOMNesting`), such as a `

` + inside a `

`. Render the outer element as a `

` (`Typography` takes + `as="div"`). +- **gives a ref to a function component.** Wrap the component in + `forwardRef`, including a test's mock of one. + +The message names the component React blamed. Warnings about react-bootstrap's +own components don't fail a test. Two components keep legacy context on purpose: +`ComponentExProvider`, which hands `MainContext` on to community extensions that +still read legacy context, and `FormFeedback`, which reads react-bootstrap's +`FormGroup`. Tests standing in for such an extension name their component +`LegacyContextExtension`, which is allowed too. + +`MainContext` lives in `src/renderer/src/contexts/main_context/MainContext.ts`. +A component that React renders as a separate root, as react-bootstrap's +`OverlayTrigger` does with its overlay, has no provider above it, so it reads +the app-wide values `MainProvider` fills in. Use `MainContextOverlayTrigger` +(`src/renderer/src/controls/main_context_overlay/`) in place of react-bootstrap's +`OverlayTrigger`: it hands the overlay the trigger's own `MainContext`, so a +popover in a dialog gets the dialog's menu layer. Our `OverlayTrigger` control +and `TooltipControls` use it. + ### What the check can't see - `waitFor`, the `findBy…` queries and `userEvent` turn React's `act()` checks @@ -114,11 +151,11 @@ 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. +- The deprecation warnings that don't fail a test (`findDOMNode`, + `defaultProps`, and legacy context from react-bootstrap) come from older + code: class components in `src/renderer/src/controls/`, and old dependencies + such as `react-bootstrap` 0.33. Clearing them means changing that code, not + the tests. ## Extension tests diff --git a/src/renderer/src/contexts/MainContext.tsx b/src/renderer/src/contexts/MainContext.tsx index 18147c1888..335040a53d 100644 --- a/src/renderer/src/contexts/MainContext.tsx +++ b/src/renderer/src/contexts/MainContext.tsx @@ -1,38 +1,26 @@ -import PropTypes from "prop-types"; -import React, { - Component, - createContext, - type ReactNode, - type FC, - useContext, - useEffect, - useMemo, - useReducer, - type ValidationMap, -} from "react"; +import React, { type ReactNode, type FC, useContext, useEffect, useMemo, useReducer } from "react"; import { useDispatch, useSelector } from "react-redux"; import { setOpenMainPage } from "../actions/session"; import { useExtensionContext } from "../ExtensionProvider"; import type { IComponentContext } from "../types/IComponentContext"; import type { IState } from "../types/IState"; +import { + ComponentExProvider, + MainContext, + setMainContextFallback, +} from "./main_context/MainContext"; import { useMenuLayerContext } from "./MenuLayerContext"; import { useWindowContext } from "./WindowContext"; +export { MainContext }; + // In modern layout, some pages move to a different location (e.g. Mods settings // moves from global settings to the per-game preferences page) const PAGE_REDIRECTS_MODERN: Record = { application_settings: "game_settings", }; -const defaultValue: IComponentContext = { - api: undefined, - menuLayer: undefined, - getModifiers: () => ({ alt: false, ctrl: false, shift: false }), -}; - -export const MainContext = createContext(defaultValue); - export interface IMainProviderProps { children: ReactNode; } @@ -67,14 +55,13 @@ export const MainProvider: FC> = ({ }; }, [api, dispatch, useModernLayout]); - const contextValue = useMemo( - () => ({ - api, - menuLayer: menuLayerElement, - getModifiers, - }), - [api, menuLayerElement, getModifiers], - ); + const contextValue = useMemo(() => { + const value = { api, menuLayer: menuLayerElement, getModifiers }; + // Set during render rather than in an effect: effects run children first, and a child can + // render a separate root (react-bootstrap's OverlayTrigger) before this one's effect runs. + setMainContextFallback(value); + return value; + }, [api, menuLayerElement, getModifiers]); return ( @@ -88,31 +75,3 @@ export const MainConsumer = MainContext.Consumer; export const useMainContext = (): IComponentContext => { return useContext(MainContext); }; - -interface IComponentExProviderProps { - children: ReactNode; -} - -// This class component provides the legacy React context API (childContextTypes/getChildContext) -// required by child components using ComponentEx with contextTypes. Cannot be replaced with a -// functional component as the legacy context API is only available in class components. -// eslint-disable-next-line @eslint-react/no-class-component -class ComponentExProvider extends Component { - public static contextType = MainContext; - declare public context: IComponentContext; - - public static childContextTypes: ValidationMap = { - api: PropTypes.object.isRequired, - menuLayer: PropTypes.object, - getModifiers: PropTypes.func, - }; - - // eslint-disable-next-line @eslint-react/no-unused-class-component-members - public getChildContext(): IComponentContext { - return this.context; - } - - public render() { - return this.props.children; - } -} diff --git a/src/renderer/src/contexts/main_context/MainContext.test.tsx b/src/renderer/src/contexts/main_context/MainContext.test.tsx new file mode 100644 index 0000000000..f3257c0034 --- /dev/null +++ b/src/renderer/src/contexts/main_context/MainContext.test.tsx @@ -0,0 +1,83 @@ +import { render } from "@testing-library/react"; +import * as PropTypes from "prop-types"; +import * as React from "react"; +import { afterEach, describe, expect, it } from "vitest"; + +import type { IComponentContext } from "../../types/IComponentContext"; +import { ComponentExProvider, MainContext, setMainContextFallback } from "./MainContext"; + +const api = { events: {} } as unknown as IComponentContext["api"]; +const menuLayer = document.createElement("div"); +const value: IComponentContext = { api, menuLayer, getModifiers: () => undefined }; + +/** Reads MainContext the way ComponentEx does. */ +class Reader extends React.Component<{ onContext: (context: IComponentContext) => void }> { + public static contextType = MainContext; + declare public context: IComponentContext; + + public render() { + this.props.onContext(this.context); + return null; + } +} + +afterEach(() => { + // back to MainContext's own default + setMainContextFallback({ + api: undefined, + menuLayer: undefined, + getModifiers: () => ({ alt: false, ctrl: false, shift: false }), + }); +}); + +describe("MainContext", () => { + // Community extensions may still declare contextTypes of their own instead of extending + // ComponentEx. ComponentExProvider keeps handing them the same values. + it("passes MainContext on to a component that reads old-style context", () => { + let seen: Partial; + class LegacyContextExtension extends React.Component { + public static contextTypes = { api: PropTypes.object, menuLayer: PropTypes.object }; + + public render() { + seen = this.context; + return null; + } + } + + render( + + + + + , + ); + + expect(seen).toEqual({ api, menuLayer }); + }); + + // react-bootstrap 0.33's OverlayTrigger renders its overlay as a separate root, which no + // provider is above. + it("gives a component with no provider above it the app-wide values", () => { + let seen: IComponentContext; + setMainContextFallback(value); + + render( (seen = context)} />); + + expect(seen.api).toBe(api); + expect(seen.menuLayer).toBe(menuLayer); + }); + + it("prefers a provider's values over the app-wide ones", () => { + let seen: IComponentContext; + const dialogLayer = document.createElement("div"); + setMainContextFallback(value); + + render( + + (seen = context)} /> + , + ); + + expect(seen.menuLayer).toBe(dialogLayer); + }); +}); diff --git a/src/renderer/src/contexts/main_context/MainContext.ts b/src/renderer/src/contexts/main_context/MainContext.ts new file mode 100644 index 0000000000..10ca581028 --- /dev/null +++ b/src/renderer/src/contexts/main_context/MainContext.ts @@ -0,0 +1,58 @@ +// The context every ComponentEx reads: the extension api, the layer menus open on, and the +// current modifier keys. MainProvider (contexts/MainContext.tsx) provides it. It lives here, +// apart from MainProvider, because MainProvider's imports reach most of the app, ComponentEx's +// subclasses among them, and ComponentEx needs this at class definition. +import PropTypes from "prop-types"; +import { Component, createContext, type ReactNode, type ValidationMap } from "react"; + +import type { IComponentContext } from "../../types/IComponentContext"; + +// What a component reads when no provider is above it. React gives a separate root no +// provider, and react-bootstrap 0.33's OverlayTrigger renders its overlay as one, so +// MainProvider fills this in with the app's values for anything rendered that way. +const fallback: IComponentContext = { + api: undefined, + menuLayer: undefined, + getModifiers: () => ({ alt: false, ctrl: false, shift: false }), +}; + +export const MainContext = createContext(fallback); + +/** Makes `value` what a component with no MainContext provider above it reads. */ +export function setMainContextFallback(value: Partial): void { + Object.assign(fallback, value); +} + +/** + * The legacy context keys ComponentExProvider provides, which are the ones ComponentEx declared + * before it read MainContext. + */ +export const legacyContextTypes: ValidationMap = { + api: PropTypes.object.isRequired, + menuLayer: PropTypes.object, + getModifiers: PropTypes.func, +}; + +interface IComponentExProviderProps { + children: ReactNode; +} + +// Hands MainContext on as old-style (legacy) context, for community extensions whose classes +// declare contextTypes themselves instead of extending ComponentEx. The legacy context API is +// only available to class components. +// eslint-disable-next-line @eslint-react/no-class-component +export class ComponentExProvider extends Component { + public static contextType = MainContext; + declare public context: IComponentContext; + + public static childContextTypes = legacyContextTypes; + + // eslint-disable-next-line @eslint-react/no-unused-class-component-members + public getChildContext(): IComponentContext { + return this.context; + } + + public render() { + return this.props.children; + } +} diff --git a/src/renderer/src/controls/ComponentEx.test.tsx b/src/renderer/src/controls/ComponentEx.test.tsx new file mode 100644 index 0000000000..1f6496e0f1 --- /dev/null +++ b/src/renderer/src/controls/ComponentEx.test.tsx @@ -0,0 +1,122 @@ +import { render } from "@testing-library/react"; +import * as PropTypes from "prop-types"; +import * as React from "react"; +import { describe, expect, it } from "vitest"; + +import { ComponentExProvider, MainContext } from "../contexts/main_context/MainContext"; +import type { IComponentContext } from "../types/IComponentContext"; +import { ComponentEx, PureComponentEx } from "./ComponentEx"; + +const context: IComponentContext = { + api: { events: {} } as unknown as IComponentContext["api"], + menuLayer: document.createElement("div"), + getModifiers: () => ({ alt: false, ctrl: true, shift: false }), +}; + +describe("ComponentEx", () => { + it("reads api, menuLayer and getModifiers from MainContext", () => { + let seen: IComponentContext; + class Example extends ComponentEx<{}, {}> { + public render() { + seen = this.context; + return null; + } + } + + render( + + + , + ); + + expect(seen).toBe(context); + }); + + it("does the same as a PureComponentEx", () => { + let seen: IComponentContext; + class Example extends PureComponentEx<{}, {}> { + public render() { + seen = this.context; + return null; + } + } + + render( + + + , + ); + + expect(seen).toBe(context); + }); + + // Community extensions written against ComponentEx's old legacy context keep working. + describe("for extensions that read legacy context", () => { + function renderInApp(element: React.ReactElement) { + render( + + {element} + , + ); + } + + it("still has ComponentEx.contextTypes, for a plain class that copies it", () => { + let seen: Partial; + class LegacyContextExtension extends React.Component { + public static contextTypes = ComponentEx.contextTypes; + + public render() { + seen = this.context; + return null; + } + } + + renderInApp(); + + expect(seen.api).toBe(context.api); + }); + + it("doesn't pass ComponentEx.contextTypes on to subclasses, which read MainContext", () => { + class Example extends ComponentEx<{}, {}> { + public render() { + return null; + } + } + + expect(Example.contextTypes).toBeUndefined(); + expect(Example.contextType).toBe(MainContext); + }); + + it("gives a subclass that declares contextTypes of its own legacy context, as before", () => { + let seen: Partial; + class LegacyContextExtension extends ComponentEx<{}, {}> { + public static contextTypes = { menuLayer: PropTypes.object }; + + public render() { + seen = this.context; + return null; + } + } + + renderInApp(); + + // legacy context holds just the keys the class declared + expect(seen).toEqual({ menuLayer: context.menuLayer }); + }); + + it("lets a subclass assign contextTypes, as older compilers emit class fields", () => { + let seen: Partial; + class LegacyContextExtension extends PureComponentEx<{}, {}> { + public render() { + seen = this.context; + return null; + } + } + LegacyContextExtension.contextTypes = { menuLayer: PropTypes.object }; + + renderInApp(); + + expect(seen).toEqual({ menuLayer: context.menuLayer }); + }); + }); +}); diff --git a/src/renderer/src/controls/ComponentEx.ts b/src/renderer/src/controls/ComponentEx.ts index d77df50201..0917e1d785 100644 --- a/src/renderer/src/controls/ComponentEx.ts +++ b/src/renderer/src/controls/ComponentEx.ts @@ -1,10 +1,10 @@ import { clearImmediate, setImmediate } from "timers"; -import * as PropTypes from "prop-types"; import * as React from "react"; import type { WithTranslation } from "react-i18next"; import { withTranslation } from "react-i18next"; +import { legacyContextTypes, MainContext } from "../contexts/main_context/MainContext"; import type { IComponentContext } from "../types/IComponentContext"; import { deleteOrNop, setSafe } from "../util/storeHelper"; import { truthy } from "../util/util"; @@ -138,11 +138,10 @@ export class ComponentEx extends React.Component< P & Partial, S > { - public static contextTypes: React.ValidationMap = { - api: PropTypes.object.isRequired, - menuLayer: PropTypes.object, - getModifiers: PropTypes.func, - }; + // Both set up by keepLegacyContextWorking below; declared here so extensions can still use them + // Typed like React.Component's own so extensions compile against it; the getter can still return null + declare public static contextType: React.Context | undefined; + declare public static contextTypes: React.ValidationMap | undefined; declare public context: IComponentContext; @@ -161,11 +160,10 @@ export class PureComponentEx extends React.PureComponent< P & Partial, S > { - public static contextTypes: React.ValidationMap = { - api: PropTypes.object.isRequired, - menuLayer: PropTypes.object, - getModifiers: PropTypes.func, - }; + // Both set up by keepLegacyContextWorking below; declared here so extensions can still use them + // Typed like React.Component's own so extensions compile against it; the getter can still return null + declare public static contextType: React.Context | undefined; + declare public static contextTypes: React.ValidationMap | undefined; declare public context: IComponentContext; @@ -179,3 +177,58 @@ export class PureComponentEx extends React.PureComponent< this.nextState = new Proxy(value, proxyHandler); } } + +/** + * Sets `base` up to read MainContext while keeping community extensions written against its old + * legacy context working. React reads `contextType` and `contextTypes` off the class it renders, + * which inherits them from `base`, so both are accessors that answer for that class: + * + * - A subclass that declares contextTypes of its own reads legacy context, as it did before, + * instead of MainContext, which would leave any key MainContext lacks undefined. + * - `ComponentEx.contextTypes` is still the old map, for extensions that copy it onto a plain + * React.Component. Subclasses don't inherit it: React would ignore it and warn. + * + * The setters let a subclass assign either static, as code compiled with assignment-style class + * fields does, instead of failing on a getter with no setter. + */ +function keepLegacyContextWorking(base: abstract new (...args: never[]) => unknown): void { + const defineOwn = (target: object, key: string, value: unknown) => + Object.defineProperty(target, key, { + value, + writable: true, + enumerable: true, + configurable: true, + }); + const declaresContextTypes = (cls: object): boolean => { + for (let current = cls; current !== base; current = Object.getPrototypeOf(current)) { + if (Object.hasOwn(current, "contextTypes")) { + return true; + } + } + return false; + }; + Object.defineProperties(base, { + contextType: { + configurable: true, + // null rather than undefined: React warns about a contextType that is undefined + get(this: object) { + return declaresContextTypes(this) ? null : MainContext; + }, + set(this: object, value: unknown) { + defineOwn(this, "contextType", value); + }, + }, + contextTypes: { + configurable: true, + get(this: object) { + return this === base ? legacyContextTypes : undefined; + }, + set(this: object, value: unknown) { + defineOwn(this, "contextTypes", value); + }, + }, + }); +} + +keepLegacyContextWorking(ComponentEx); +keepLegacyContextWorking(PureComponentEx); diff --git a/src/renderer/src/controls/ContextMenu.test.tsx b/src/renderer/src/controls/ContextMenu.test.tsx index a4c71a4be0..69dec82d4b 100644 --- a/src/renderer/src/controls/ContextMenu.test.tsx +++ b/src/renderer/src/controls/ContextMenu.test.tsx @@ -1,33 +1,20 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react"; -import * as PropTypes from "prop-types"; import * as React from "react"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { MainContext } from "../contexts/main_context/MainContext"; +import type { IComponentContext } from "../types/IComponentContext"; import ContextMenu from "./ContextMenu"; -// 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<{ - menuLayer: HTMLElement; - children: React.ReactNode; -}> { - public static childContextTypes = { - api: PropTypes.object, - menuLayer: PropTypes.object, - getModifiers: PropTypes.func, - }; - - public getChildContext() { - return { - api: { events: { on: () => undefined, off: () => undefined } }, - menuLayer: this.props.menuLayer, - getModifiers: () => ({}), - }; - } - - public render() { - return this.props.children; - } +// ContextMenu extends ComponentEx, which reads api, menuLayer and getModifiers from +// MainContext; provide the minimum. +function ContextProvider(props: { menuLayer: HTMLElement; children: React.ReactNode }) { + const context = { + api: { events: { on: () => undefined, off: () => undefined } }, + menuLayer: props.menuLayer, + getModifiers: () => ({ alt: false, ctrl: false, shift: false }), + } as unknown as IComponentContext; + return {props.children}; } function Harness(props: { menuLayer: HTMLElement }) { @@ -42,7 +29,7 @@ function Harness(props: { menuLayer: HTMLElement }) { const onHide = React.useCallback(() => setVisible(false), []); return ( - +
undefined, show: true } as any]} /> - + ); } diff --git a/src/renderer/src/controls/IconBar.tsx b/src/renderer/src/controls/IconBar.tsx index d27a46915b..a206e47871 100644 --- a/src/renderer/src/controls/IconBar.tsx +++ b/src/renderer/src/controls/IconBar.tsx @@ -1,11 +1,12 @@ import update from "immutability-helper"; 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 { MainContext } from "../contexts/main_context/MainContext"; import type { IActionDefinition } from "../types/IActionDefinition"; +import type { IComponentContext } from "../types/IComponentContext"; import type { IExtensibleProps } from "../types/IExtensionProvider"; import type { TFunction } from "../util/i18n"; import { setdefault } from "../util/util"; @@ -172,11 +173,8 @@ function IconBarIcon(props: IIconBarIconProps) { * @extends {ComponentEx} */ class IconBar extends React.Component { - public static contextTypes: React.ValidationMap = { - menuLayer: PropTypes.object, - }; - - declare public context: { menuLayer: JSX.Element }; + public static contextType = MainContext; + declare public context: IComponentContext; private portalTargetRef: Element; private mBackgroundClick: (evt: React.MouseEvent) => void; diff --git a/src/renderer/src/controls/Modal.test.tsx b/src/renderer/src/controls/Modal.test.tsx new file mode 100644 index 0000000000..9041c7c28a --- /dev/null +++ b/src/renderer/src/controls/Modal.test.tsx @@ -0,0 +1,79 @@ +import { cleanup, render } from "@testing-library/react"; +import * as PropTypes from "prop-types"; +import * as React from "react"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { MainContext } from "../contexts/main_context/MainContext"; +import type { IComponentContext } from "../types/IComponentContext"; +import { ComponentEx } from "./ComponentEx"; +import Modal from "./Modal"; + +const appLayer = document.createElement("div"); +const context: IComponentContext = { + api: { events: {} } as unknown as IComponentContext["api"], + menuLayer: appLayer, + getModifiers: () => undefined, +}; + +let overlays: HTMLElement; + +beforeEach(() => { + // the dialog mounts into the app's overlay host + overlays = document.createElement("div"); + overlays.id = "overlays"; + document.body.appendChild(overlays); +}); + +afterEach(() => { + // This hook runs before testing-library's own cleanup (after-hooks run last-registered + // first), so unmount the dialog here, while the host it's mounted in is still attached. + cleanup(); + overlays.remove(); +}); + +// A menu opened inside a dialog goes on the dialog's own menu layer, so it sits above the +// dialog instead of behind it. +describe("Modal", () => { + it("gives what's inside it the dialog's menu layer and the app's api", () => { + let seen: IComponentContext; + class Inside extends ComponentEx<{}, {}> { + public render() { + seen = this.context; + return null; + } + } + + render( + + undefined}> + + + , + ); + + expect(seen.api).toBe(context.api); + expect(seen.menuLayer).toBe(document.querySelector(".modal .menu-layer")); + }); + + it("gives the same to a component that reads old-style context", () => { + let seen: Partial; + class LegacyContextExtension extends React.Component { + public static contextTypes = { api: PropTypes.object, menuLayer: PropTypes.object }; + + public render() { + seen = this.context; + return null; + } + } + + render( + + undefined}> + + + , + ); + + expect(seen.menuLayer).toBe(document.querySelector(".modal .menu-layer")); + }); +}); diff --git a/src/renderer/src/controls/Modal.tsx b/src/renderer/src/controls/Modal.tsx index 29569f0ab6..e7a582c1c1 100644 --- a/src/renderer/src/controls/Modal.tsx +++ b/src/renderer/src/controls/Modal.tsx @@ -1,9 +1,9 @@ import memoizeOne from "memoize-one"; -import * as PropTypes from "prop-types"; import * as React from "react"; import type { ModalBody, ModalFooter, ModalHeader, ModalTitle } from "react-bootstrap"; import { Modal } from "react-bootstrap"; +import { ComponentExProvider, MainContext } from "../contexts/main_context/MainContext"; import type { IComponentContext } from "../types/IComponentContext"; import { MutexWrapper } from "../util/MutexContext"; @@ -13,19 +13,23 @@ class MyModal extends React.PureComponent { public static Body: typeof ModalBody = Modal.Body; public static Footer: typeof ModalFooter = Modal.Footer; - public static childContextTypes: React.ValidationMap = { - menuLayer: PropTypes.object, - }; - - declare public context: Partial; + public static contextType = MainContext; + declare public context: IComponentContext; private getContainer = memoizeOne(() => this.getContainerImpl()); - private mMenuLayer: Element = null; + // What's inside the dialog gets its own menu layer, so a menu opened there sits above the + // dialog rather than behind it. Memoized on the values rather than the outer context object: + // with no provider above, that object is MainContext's fallback, which is updated in place. + private getInnerContext = memoizeOne( + ( + api: IComponentContext["api"], + getModifiers: IComponentContext["getModifiers"], + menuLayer: HTMLDivElement, + ): IComponentContext => ({ api, getModifiers, menuLayer }), + ); - public getChildContext(): any { - return { ...this.context, menuLayer: this.mMenuLayer }; - } + private mMenuLayer: HTMLDivElement = null; public render(): JSX.Element { return ( @@ -33,7 +37,17 @@ class MyModal extends React.PureComponent {
- {this.mMenuLayer !== null ? this.props.children : null} + {this.mMenuLayer !== null ? ( + + {this.props.children} + + ) : null}
@@ -44,7 +58,7 @@ class MyModal extends React.PureComponent { return document.getElementById("overlays"); } - private setMenuLayer = (ref: Element) => { + private setMenuLayer = (ref: HTMLDivElement) => { this.mMenuLayer = ref; this.forceUpdate(); }; diff --git a/src/renderer/src/controls/OverlayTrigger.tsx b/src/renderer/src/controls/OverlayTrigger.tsx index de7b72d30e..30d7b98fee 100644 --- a/src/renderer/src/controls/OverlayTrigger.tsx +++ b/src/renderer/src/controls/OverlayTrigger.tsx @@ -1,8 +1,10 @@ import * as _ from "lodash"; import * as React from "react"; -import { OverlayTrigger } from "react-bootstrap"; +import type { OverlayTrigger } from "react-bootstrap"; import * as ReactDOM from "react-dom"; +import { MainContextOverlayTrigger } from "./main_context_overlay/MainContextOverlay"; + export interface IBaseProps { triggerRef?: (ref: HTMLElement) => void; getBounds: () => ClientRect; @@ -48,14 +50,14 @@ class MyOverlayTrigger extends React.Component { const { placement } = this.state; const relayProps: any = _.omit(this.props, ["getBounds", "placement", "onEnter", "triggerRef"]); return ( - {this.props.children} - + ); } diff --git a/src/renderer/src/controls/PortalMenu.tsx b/src/renderer/src/controls/PortalMenu.tsx index d86b8125ee..d268e5221f 100644 --- a/src/renderer/src/controls/PortalMenu.tsx +++ b/src/renderer/src/controls/PortalMenu.tsx @@ -1,8 +1,9 @@ -import * as PropTypes from "prop-types"; import * as React from "react"; import type { SelectCallback } from "react-bootstrap"; import { Overlay } from "react-overlays"; +import { MainContext } from "../contexts/main_context/MainContext"; +import type { IComponentContext } from "../types/IComponentContext"; import Dropdown from "./Dropdown"; interface IPortalMenuProps { @@ -22,11 +23,8 @@ function nop() { } class PortalMenu extends React.Component { - public static contextTypes: React.ValidationMap = { - menuLayer: PropTypes.object, - }; - - declare public context: { menuLayer: JSX.Element }; + public static contextType = MainContext; + declare public context: IComponentContext; constructor(props: IPortalMenuProps) { super(props); diff --git a/src/renderer/src/controls/Table.test.tsx b/src/renderer/src/controls/Table.test.tsx index 784903e279..f6a08b71c1 100644 --- a/src/renderer/src/controls/Table.test.tsx +++ b/src/renderer/src/controls/Table.test.tsx @@ -5,12 +5,13 @@ * page scroll, not the pane. */ import { act, fireEvent, render, waitFor } from "@testing-library/react"; -import * as PropTypes from "prop-types"; import * as React from "react"; import { Provider } from "react-redux"; import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { MainContext } from "../contexts/main_context/MainContext"; import * as scrolling from "../smoothScroll"; +import type { IComponentContext } from "../types/IComponentContext"; import SuperTable from "./Table"; import HeaderCell from "./table/HeaderCell"; @@ -49,24 +50,26 @@ const listeners = new Map void>(); const state = { settings: { interface: { usage: {} } }, persistent: {} }; const store = { getState: () => state, subscribe: () => () => undefined, dispatch: vi.fn() }; -class LegacyContext extends React.Component<{ children: React.ReactNode }> { - public static childContextTypes = { api: PropTypes.object }; - public getChildContext() { - return { - api: { - events: { - on: (event: string, listener: (...args: any[]) => void) => listeners.set(event, listener), - emit: vi.fn(), - removeAllListeners: vi.fn(), - }, - getState: () => state, - store, - }, - }; - } - public render() { - return {this.props.children}; - } +const appContext = { + api: { + events: { + on: (event: string, listener: (...args: any[]) => void) => listeners.set(event, listener), + emit: vi.fn(), + removeAllListeners: vi.fn(), + }, + getState: () => state, + store, + }, + menuLayer: undefined, + getModifiers: () => ({ alt: false, ctrl: false, shift: false }), +} as unknown as IComponentContext; + +function AppContext(props: { children: React.ReactNode }) { + return ( + + {props.children} + + ); } const attributes = [ @@ -98,7 +101,7 @@ function renderTable( document.body.appendChild(page); const result = render( - + { if (instance) tableInstance = instance; @@ -122,7 +125,7 @@ function renderTable( onCollapseGroup={vi.fn()} onSetCollapsedGroups={vi.fn()} /> - , + , { container: host }, ); const pane = host.querySelector(".table-main-pane"); diff --git a/src/renderer/src/controls/TooltipControls.tsx b/src/renderer/src/controls/TooltipControls.tsx index 6a36f7712a..c4c3d6136d 100644 --- a/src/renderer/src/controls/TooltipControls.tsx +++ b/src/renderer/src/controls/TooltipControls.tsx @@ -5,12 +5,12 @@ import { Button as BootstrapButton, NavItem as BootstrapNavItem, Overlay, - OverlayTrigger, Popover, } from "react-bootstrap"; import SvgIcon from "./Icon"; import type { ButtonType } from "./IconBar"; +import { MainContextOverlayTrigger } from "./main_context_overlay/MainContextOverlay"; export interface ITooltipProps { tooltip: string | React.ReactElement; @@ -41,14 +41,14 @@ export class Button extends React.PureComponent { } else { const tooltipCtrl = {this.props.tooltip}; return ( - {this.props.children} - + ); } } @@ -133,7 +133,7 @@ export class IconButton extends React.Component { } else { const tooltip = {this.props.tooltip}; return ( - { {this.props.children} - + ); } } @@ -188,7 +188,7 @@ export class ToggleButton extends React.Component { const tooltipContent = React.isValidElement(tooltipText) ? tooltipText : null; const tooltip = {tooltipContent}; return ( - { ) : null} {this.props.children} - + ); } } @@ -224,14 +224,14 @@ export class NavItem extends React.Component { } else { const tooltip = {this.props.tooltip}; return ( - {this.props.children} - + ); } } @@ -285,7 +285,7 @@ export class Icon extends React.Component { const tooltip = {this.props.tooltip}; return ( - { - + ); } } diff --git a/src/renderer/src/controls/ZoomableImage.tsx b/src/renderer/src/controls/ZoomableImage.tsx index 365779f38c..657639058a 100644 --- a/src/renderer/src/controls/ZoomableImage.tsx +++ b/src/renderer/src/controls/ZoomableImage.tsx @@ -1,9 +1,10 @@ import * as _ from "lodash"; -import * as PropTypes from "prop-types"; import * as React from "react"; import { Image } from "react-bootstrap"; import { Portal } from "react-overlays"; +import { MainContext } from "../contexts/main_context/MainContext"; +import type { IComponentContext } from "../types/IComponentContext"; import { setSafe } from "../util/storeHelper"; import Icon from "./Icon"; @@ -27,11 +28,8 @@ export interface IZoomableImageProps { } class ZoomableImage extends React.Component { - public static contextTypes: React.ValidationMap = { - menuLayer: PropTypes.object, - }; - - declare public context: { menuLayer: JSX.Element }; + public static contextType = MainContext; + declare public context: IComponentContext; constructor(props) { super(props); diff --git a/src/renderer/src/controls/bbcode/SafeSimpleTag.tsx b/src/renderer/src/controls/bbcode/SafeSimpleTag.tsx index d62f085b58..b41f3eb1c0 100644 --- a/src/renderer/src/controls/bbcode/SafeSimpleTag.tsx +++ b/src/renderer/src/controls/bbcode/SafeSimpleTag.tsx @@ -74,6 +74,34 @@ const keptParams = (params: Record, kept: Record property.replace(/-(\w)/g, (_, letter: string) => letter.toUpperCase()); +/** + * A table's children with each run of rows written straight in it put in a ``, as the + * browser does when it parses the page. Drawn without one, React's tree wouldn't match the page. + * Rows already in a `[thead]` or `[tbody]` are left as they are. + */ +const rowsInBody = (children: React.ReactNode): React.ReactNode[] => { + const drawn: React.ReactNode[] = []; + let rows: React.ReactNode[] = []; + const endRows = () => { + if (rows.length > 0) { + drawn.push(React.createElement("tbody", { key: `rows-${drawn.length}` }, rows)); + rows = []; + } + }; + + for (const child of React.Children.toArray(children)) { + if (React.isValidElement(child) && child.type === "tr") { + rows.push(child); + } else { + endRows(); + drawn.push(child); + } + } + endRows(); + + return drawn; +}; + /** * A plain tag, such as `[b]` or `[td]`, as its element with only the parameters it keeps. The * parser's own hands every parameter to the element, so `[td background=…]` would load an image @@ -114,7 +142,12 @@ const safeSimpleTag = ( ); } - return React.createElement(element, props, this.getComponents()); + const children = this.getComponents(); + return React.createElement( + element, + props, + element === "table" ? rowsInBody(children) : children, + ); } }; diff --git a/src/renderer/src/controls/main_context_overlay/MainContextOverlay.test.tsx b/src/renderer/src/controls/main_context_overlay/MainContextOverlay.test.tsx new file mode 100644 index 0000000000..e85c6c60fe --- /dev/null +++ b/src/renderer/src/controls/main_context_overlay/MainContextOverlay.test.tsx @@ -0,0 +1,87 @@ +import { render, screen } from "@testing-library/react"; +import React, { Component, type ComponentType, type ReactElement } from "react"; +import { OverlayTrigger, Popover } from "react-bootstrap"; +import { describe, expect, it } from "vitest"; + +import { MainContext } from "../../contexts/main_context/MainContext"; +import type { IComponentContext } from "../../types/IComponentContext"; +import { MainContextOverlayTrigger } from "./MainContextOverlay"; + +const dialogLayer = document.createElement("div"); +const dialogContext: IComponentContext = { + api: { events: {} } as unknown as IComponentContext["api"], + menuLayer: dialogLayer, + getModifiers: () => ({ alt: false, ctrl: false, shift: false }), +}; + +/** Reads MainContext the way ComponentEx does. */ +// eslint-disable-next-line @eslint-react/no-class-component +class Reader extends Component<{ onContext: (context: IComponentContext) => void }> { + public static contextType = MainContext; + declare public context: IComponentContext; + + public render() { + this.props.onContext(this.context); + return null; + } +} + +/** Renders `Trigger` inside a dialog's MainContext, with `overlay` already shown. */ +function renderShownOverlay( + Trigger: ComponentType, + overlay: ReactElement, +) { + render( + + + of its own, so they're + // drawn in one, or React's tree wouldn't match the page. + it("puts a table's rows in a tbody", () => { + const { container } = render( + , + ); + + expect(container.querySelectorAll("table > tbody > tr")).toHaveLength(2); + }); + + it("keeps a table's own thead and tbody", () => { + const { container } = render( + , + ); + + expect(container.querySelectorAll("table > thead > tr")).toHaveLength(1); + expect(container.querySelectorAll("table > tbody > tr")).toHaveLength(1); + expect(container.querySelectorAll("tbody tbody")).toHaveLength(0); + }); + it("keeps how far a table cell spans and where its text sits", () => { render( , diff --git a/src/renderer/test-setup.mts b/src/renderer/test-setup.mts index e7992e265e..a6e17d1db3 100644 --- a/src/renderer/test-setup.mts +++ b/src/renderer/test-setup.mts @@ -19,7 +19,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 +28,78 @@ 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`, - ); + +// React warnings about our own code fail the test they're logged in, as act() warnings do above; +// "React warnings" in docs/testing.md says how to fix each. A warning is ours when the first +// component in React's stack that has a file isn't in node_modules: react-bootstrap 0.33 logs +// the same warnings about its own components, and those go when it does. +// `about`, when set, is the first value React fills into the message. +const ourWarnings: { logged: string; about?: string; failure: string }[] = [ + { logged: "uses the legacy contextTypes API", failure: "reads legacy context" }, + { logged: "uses the legacy childContextTypes API", failure: "provides legacy context" }, + { + logged: "declares both contextTypes and contextType", + failure: "declares both contextType and legacy contextTypes", + }, + { logged: "Failed %s type", about: "context", failure: "fails a context type check" }, + { + logged: "Failed %s type", + about: "child context", + failure: "fails a child context type check", + }, + { logged: "validateDOMNesting", failure: "nests elements HTML doesn't allow" }, + { + logged: "Function components cannot be given refs", + failure: "gives a ref to a function component", + }, +]; +// Legacy context on purpose: ComponentExProvider hands MainContext on to extensions that still +// read legacy context, LegacyContextExtension is the tests' stand-in for one of those, and +// FormFeedback reads react-bootstrap's FormGroup, which only has legacy context. +const legacyContextOnPurpose = ["ComponentExProvider", "LegacyContextExtension", "FormFeedback"]; +const ourWarningsLogged = new Set(); +const consoleErrorBeforeOurWarnings = console.error; +console.error = (...args: unknown[]) => { + const message = args[0]; + const warning = + typeof message === "string" + ? ourWarnings.find( + ({ logged, about }) => + message.includes(logged) && (about === undefined || args[1] === about), + ) + : undefined; + if (warning !== undefined && !legacyContextOnPurpose.includes(String(args[1]))) { + // React passes the component stack last + const stack = [...args] + .reverse() + .find((arg) => typeof arg === "string" && arg.includes(" at ")); + const frame = /\bat (\S+) \(([^)]+)\)/.exec(String(stack ?? "")); + if (frame === null || !/[\\/]node_modules[\\/]/.test(frame[2])) { + ourWarningsLogged.add(`${frame?.[1] ?? "a component"} ${warning.failure}`); + } + } + consoleErrorBeforeOurWarnings.apply(console, args); +}; + +/** + * 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()`); + } + problems.push(...ourWarningsLogged); + componentsUpdatedOutsideAct.clear(); + ourWarningsLogged.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