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
47 changes: 42 additions & 5 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
`<MainContext.Provider value={…}>`. 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 `<MainContext.Provider>` that has an `api`.
- **nests elements HTML doesn't allow** (`validateDOMNesting`), such as a `<p>`
inside a `<p>`. Render the outer element as a `<div>` (`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
Expand All @@ -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

Expand Down
71 changes: 15 additions & 56 deletions src/renderer/src/contexts/MainContext.tsx
Original file line number Diff line number Diff line change
@@ -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<string, string> = {
application_settings: "game_settings",
};

const defaultValue: IComponentContext = {
api: undefined,
menuLayer: undefined,
getModifiers: () => ({ alt: false, ctrl: false, shift: false }),
};

export const MainContext = createContext<IComponentContext>(defaultValue);

export interface IMainProviderProps {
children: ReactNode;
}
Expand Down Expand Up @@ -67,14 +55,13 @@ export const MainProvider: FC<React.PropsWithChildren<IMainProviderProps>> = ({
};
}, [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 (
<MainContext.Provider value={contextValue}>
Expand All @@ -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<IComponentExProviderProps> {
public static contextType = MainContext;
declare public context: IComponentContext;

public static childContextTypes: ValidationMap<unknown> = {
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;
}
}
83 changes: 83 additions & 0 deletions src/renderer/src/contexts/main_context/MainContext.test.tsx
Original file line number Diff line number Diff line change
@@ -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<IComponentContext>;
class LegacyContextExtension extends React.Component {
public static contextTypes = { api: PropTypes.object, menuLayer: PropTypes.object };

public render() {
seen = this.context;
return null;
}
}

render(
<MainContext.Provider value={value}>
<ComponentExProvider>
<LegacyContextExtension />
</ComponentExProvider>
</MainContext.Provider>,
);

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(<Reader onContext={(context) => (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(
<MainContext.Provider value={{ ...value, menuLayer: dialogLayer }}>
<Reader onContext={(context) => (seen = context)} />
</MainContext.Provider>,
);

expect(seen.menuLayer).toBe(dialogLayer);
});
});
58 changes: 58 additions & 0 deletions src/renderer/src/contexts/main_context/MainContext.ts
Original file line number Diff line number Diff line change
@@ -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<IComponentContext>(fallback);

/** Makes `value` what a component with no MainContext provider above it reads. */
export function setMainContextFallback(value: Partial<IComponentContext>): 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<unknown> = {
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<IComponentExProviderProps> {
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;
}
}
Loading