Compare commits

...

9 Commits

Author SHA1 Message Date
semantic-release-bot
1f7178f175 chore(release): 4.4.0 [CI SKIP] 2024-07-18 04:55:06 +00:00
AAGaming
44fdf9ed3b feat(utils/react): add injectFCTrampoline 2024-07-18 00:54:29 -04:00
semantic-release-bot
1b5fd78bc2 chore(release): 4.3.1 [CI SKIP] 2024-07-17 23:30:02 +00:00
AAGaming
d64c42ac31 fix(Menu/MenuGroup): rewrite filter to work on beta and prevent future errors 2024-07-17 19:29:25 -04:00
semantic-release-bot
0ec60edf4d chore(release): 4.3.0 [CI SKIP] 2024-07-09 06:38:22 +00:00
AAGaming
2c3a9f81de feat(utils): react tree patching api 2024-07-09 02:37:46 -04:00
semantic-release-bot
00079a71cc chore(release): 4.2.2 [CI SKIP] 2024-07-04 05:18:57 +00:00
AAGaming
c04f024b34 fix(SteamSpinner): add background option 2024-07-04 01:18:27 -04:00
AAGaming
5dae77b003 chore(ci): update actions to remove deprecation warnings 2024-06-29 17:53:00 -04:00
12 changed files with 4493 additions and 3504 deletions

View File

@@ -12,19 +12,19 @@ jobs:
runs-on: ubuntu-22.04
steps:
- name: Setup | Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
fetch-depth: 0
path: lib
- name: Setup | Checkout wiki
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
repository: SteamDeckHomebrew/wiki
path: wiki
ssh-key: ${{ secrets.SSH_DEPLOY_KEY }}
persist-credentials: true
- name: Setup | Node.js
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version: 18
- name: Setup | Dependencies

View File

@@ -12,11 +12,11 @@ jobs:
runs-on: ubuntu-22.04
steps:
- name: Setup | Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup | Node.js
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version: 20
- name: Setup | Dependencies

View File

@@ -1,3 +1,31 @@
# [4.4.0](https://github.com/SteamDeckHomebrew/decky-frontend-lib/compare/v4.3.1...v4.4.0) (2024-07-18)
### Features
* **utils/react:** add injectFCTrampoline ([44fdf9e](https://github.com/SteamDeckHomebrew/decky-frontend-lib/commit/44fdf9ed3b9a676a88b0ddc6a1c2c89d46ff7651))
## [4.3.1](https://github.com/SteamDeckHomebrew/decky-frontend-lib/compare/v4.3.0...v4.3.1) (2024-07-17)
### Bug Fixes
* **Menu/MenuGroup:** rewrite filter to work on beta and prevent future errors ([d64c42a](https://github.com/SteamDeckHomebrew/decky-frontend-lib/commit/d64c42ac310d3c3266c4ff610d9ec5ab6c7707b6))
# [4.3.0](https://github.com/SteamDeckHomebrew/decky-frontend-lib/compare/v4.2.2...v4.3.0) (2024-07-09)
### Features
* **utils:** react tree patching api ([2c3a9f8](https://github.com/SteamDeckHomebrew/decky-frontend-lib/commit/2c3a9f81de0b63364bb31f4a4dd8e559784ece16))
## [4.2.2](https://github.com/SteamDeckHomebrew/decky-frontend-lib/compare/v4.2.1...v4.2.2) (2024-07-04)
### Bug Fixes
* **SteamSpinner:** add background option ([c04f024](https://github.com/SteamDeckHomebrew/decky-frontend-lib/commit/c04f024b34b1148c965850965127f9fd44204157))
## [4.2.1](https://github.com/SteamDeckHomebrew/decky-frontend-lib/compare/v4.2.0...v4.2.1) (2024-06-27)

View File

@@ -1,6 +1,6 @@
{
"name": "@decky/ui",
"version": "4.2.1",
"version": "4.4.0",
"description": "A library for interacting with the Steam frontend in Decky plugins and elsewhere.",
"main": "dist/index.js",
"types": "dist/index.d.ts",

7701
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,6 @@
import { FC, ReactNode } from 'react';
import { fakeRenderComponent } from '../utils';
import { Export, findModuleExport } from '../webpack';
import { Export, findModuleByExport, findModuleExport } from '../webpack';
import { FooterLegendProps } from './FooterLegend';
export const showContextMenu: (children: ReactNode, parent?: EventTarget) => void = findModuleExport(
@@ -26,12 +25,8 @@ export interface MenuGroupProps {
children?: ReactNode;
}
export const MenuGroup: FC<MenuGroupProps> = findModuleExport(
(e: Export) =>
(e?.toString()?.includes?.('bInGamepadUI:') &&
fakeRenderComponent(() => e({ overview: { appid: 7 } }), {useContext: () => ({IN_GAMEPADUI: true})})?.type?.prototype?.RenderSubMenu) ||
(e?.prototype?.RenderSubMenu && e?.prototype?.ShowSubMenu)
);
const MenuGoupModule = findModuleByExport(e => e?.prototype?.Focus && e?.prototype?.OnOKButton && e?.prototype?.render?.toString().includes?.(`"emphasis"==this.props.tone`));
export const MenuGroup: FC<MenuGroupProps> = MenuGoupModule && Object.values(MenuGoupModule).find((e: Export) => typeof e == "function" && e?.toString()?.includes("bInGamepadUI:"));
export interface MenuItemProps extends FooterLegendProps {
bInteractableItem?: boolean;
onClick?(evt: Event): void;

View File

@@ -1,7 +1,12 @@
import { FC, SVGAttributes } from 'react';
import { FC, ReactNode, SVGAttributes } from 'react';
import { Export, findModuleExport } from '../webpack';
interface SteamSpinnerProps {
children?: ReactNode;
background?: "transparent"; // defaults to black seemingly, but only "transparent" is checked against
}
export const SteamSpinner = findModuleExport(
(e: Export) => e?.toString?.()?.includes('Steam Spinner') && e?.toString?.()?.includes('src'),
) as FC<SVGAttributes<SVGElement>>;
) as FC<SVGAttributes<SVGElement> & SteamSpinnerProps>;

View File

@@ -1,6 +1,8 @@
export * from './patcher';
export * from './react';
export * from './static-classes';
export * from './react/react';
export * from './react/fc';
export * from './react/treepatcher';
declare global {
var FocusNavController: any;

View File

@@ -6,7 +6,7 @@ export interface PatchOptions {
singleShot?: boolean;
}
type GenericPatchHandler = (args: any[], ret?: any) => any;
export type GenericPatchHandler = (args: any[], ret?: any) => any;
export interface Patch {
original: Function;

109
src/utils/react/fc.ts Normal file
View File

@@ -0,0 +1,109 @@
// Utilities for patching function components
import { createElement, type FC } from 'react';
import { applyHookStubs, removeHookStubs } from './react';
import Logger from '../../logger';
export interface FCTrampoline {
component: FC
}
let loggingEnabled = false;
export function setFCTrampolineLoggingEnabled(value: boolean = true) { loggingEnabled = value };
let logger = new Logger('FCTrampoline');
/**
* Directly hooks a function component from its reference, redirecting it to a user-patchable wrapper in its returned object.
* This only works if the original component when called directly returns either nothing, null, or another child element.
*
* This works by tricking react into thinking it's a class component by cleverly working around its class component checks,
* keeping the unmodified function component intact as a mostly working constructor (as it is impossible to direcly modify a function),
* stubbing out hooks to prevent errors by detecting setter/getter triggers that occur direcly before/after the class component is instantiated by react,
* and creating a fake class component render method to trampoline out into your own handler.
*
* Due to the nature of this method of hooking a component, please only use this where it is *absolutely necessary.*
* Incorrect hook stubs can cause major instability, be careful when writing them. Refer to fakeRenderComponent for the hook stub implementation.
* Make sure your hook stubs can handle all the cases they could possibly need to within the component you are injecting into.
* You do not need to worry about its children, as they are never called due to the first instance never actually rendering.
*/
export function injectFCTrampoline(component: FC, customHooks?: any): FCTrampoline {
// It needs to be wrapped so React doesn't infinitely call the fake class render method.
const newComponent = function (this: any, ...args: any) {
loggingEnabled && logger.debug("new component rendering with props", args);
return component.apply(this, args);
}
const userComponent = { component: newComponent };
// Create a fake class component render method
component.prototype.render = function (...args: any[]) {
loggingEnabled && logger.debug("rendering trampoline", args, this);
// Pass through rendering via creating the component as a child so React can use function component logic instead of class component logic (setting up the hooks)
return createElement(userComponent.component, this.props, this.props.children);
};
component.prototype.isReactComponent = true;
let stubsApplied = false;
let oldCreateElement = window.SP_REACT.createElement;
const applyStubsIfNeeded = () => {
if (!stubsApplied) {
loggingEnabled && logger.debug("applied stubs");
stubsApplied = true;
applyHookStubs(customHooks)
// we have to redirect this to return an object with component's prototype as a constructor returning a value overrides its prototype
window.SP_REACT.createElement = () => {
loggingEnabled && logger.debug("createElement hook called");
return Object.create(component.prototype);
};
}
}
const removeStubsIfNeeded = () => {
if (stubsApplied) {
loggingEnabled && logger.debug("removed stubs");
stubsApplied = false;
removeHookStubs();
window.SP_REACT.createElement = oldCreateElement;
}
}
// Accessed two times, once directly before class instantiation, and again in some extra logic we don't need to worry about that we hanlde below just in case.
Object.defineProperty(component, "contextType", {
configurable: true,
get: function () {
loggingEnabled && logger.debug("get contexttype", this, stubsApplied);
applyStubsIfNeeded();
return this._contextType;
},
set: function (value) {
this._contextType = value;
}
});
// Undoes the second contextType access we can't detect shortly before render before it's able to cause any damage
Object.defineProperty(component, "getDerivedStateFromProps", {
configurable: true,
get: function () {
loggingEnabled && logger.debug("get getDerivedStateFromProps", this, stubsApplied);
removeStubsIfNeeded();
return this._getDerivedStateFromProps;
},
set: function (value) {
this._getDerivedStateFromProps = value;
}
});
// Set directly after class is instantiated
Object.defineProperty(component.prototype, "updater", {
configurable: true,
get: function () {
return this._updater;
},
set: function (value) {
loggingEnabled && logger.debug("set updater", this, value, stubsApplied);
removeStubsIfNeeded();
return this._updater = value;
}
});
return userComponent;
}

View File

@@ -30,13 +30,15 @@ export function createPropListRegex(propList: string[], fromStart: boolean = tru
return new RegExp(regexString);
}
export function fakeRenderComponent(fun: Function, customHooks: any = {}): any {
let oldHooks = {};
export function applyHookStubs(customHooks: any = {}): any {
const hooks = (window.SP_REACT as any).__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher
.current;
// TODO: add more hooks
let oldHooks = {
oldHooks = {
useContext: hooks.useContext,
useCallback: hooks.useCallback,
useLayoutEffect: hooks.useLayoutEffect,
@@ -60,9 +62,22 @@ export function fakeRenderComponent(fun: Function, customHooks: any = {}): any {
Object.assign(hooks, customHooks);
const res = fun(hooks);
return hooks;
}
export function removeHookStubs() {
const hooks = (window.SP_REACT as any).__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher
.current;
Object.assign(hooks, oldHooks);
oldHooks = {};
}
export function fakeRenderComponent(fun: Function, customHooks?: any): any {
const hooks = applyHookStubs(customHooks);
const res = fun(hooks); // TODO why'd we do this?
removeHookStubs();
return res;
}

View File

@@ -0,0 +1,100 @@
import Logger from '../../logger';
import { GenericPatchHandler, afterPatch } from '../patcher';
import { wrapReactClass, wrapReactType } from './react';
// TODO max size limit? could implement as a class extending map perhaps
type PatchedComponentCache = Map<any, any>;
export type GenericNodeStep = (node: any) => any;
// to patch a specific method of a class component other than render. TODO implement
// export type ClassNodeStep = [finder: GenericNodeStep, method: string];
// export type NodeStep = GenericNodeStep | ClassNodeStep;
export type NodeStep = GenericNodeStep;
export type ReactPatchHandler = GenericPatchHandler;
// These will get *very* spammy.
let loggingEnabled = false;
let perfLoggingEnabled = false;
export function setReactPatcherLoggingEnabled(value: boolean = true) { loggingEnabled = value };
export function setReactPatcherPerformanceLoggingEnabled(value: boolean = true) { perfLoggingEnabled = value };
function patchComponent(node: any, handler: GenericPatchHandler, steps: NodeStep[], step: number, caches: PatchedComponentCache[], logger: Logger, prop: string = 'type') {
loggingEnabled && logger.group('Patching node:', node);
// We need to take extra care to not mutate the original node.type
switch (typeof node?.[prop]) {
case 'function':
// Function component
const patch = afterPatch(node, prop, steps[step + 1] ? createStepHandler(handler, steps, step + 1, caches, logger) : handler);
loggingEnabled && logger.debug('Patched a function component', patch);
break;
case 'object':
if (node[prop]?.prototype?.render) {
// Class component
// TODO handle patching custom methods
wrapReactClass(node);
const patch = afterPatch(node[prop].prototype, 'render', steps[step + 1] ? createStepHandler(handler, steps, step + 1, caches, logger) : handler);
loggingEnabled && logger.debug('Patched class component', patch);
} else {
loggingEnabled && logger.debug('Patching forwardref/memo');
wrapReactType(node, prop);
// Step down the object
patchComponent(node[prop], handler, steps, step, caches, logger, node[prop]?.render ? 'render' : 'type');
}
break;
default:
logger.error('Unhandled component type', node);
break;
}
loggingEnabled && logger.groupEnd();
}
function handleStep(tree: any, handler: GenericPatchHandler, steps: NodeStep[], step: number, caches: PatchedComponentCache[], logger: Logger): any {
const startTime = (loggingEnabled || perfLoggingEnabled) ? performance.now() : 0;
const stepHandler = steps[step];
const cache = caches[step] || (caches[step] = new Map());
loggingEnabled && logger.debug(`Patch step ${step} running`, { tree, stepHandler, step, caches });
const node = stepHandler(tree);
if (node && node.type) {
loggingEnabled && logger.debug('Found node', node);
} else if (node) {
loggingEnabled && logger.error('Found node without type. Something is probably wrong.', node);
return tree;
} else {
loggingEnabled && logger.warn('Found no node. Depending on your usecase, this might be fine.', node);
return tree;
}
let cachedType;
if (cachedType = cache.get(node.type)) {
loggingEnabled && logger.debug('Found cached patched component', node);
node.type = cachedType;
(loggingEnabled || perfLoggingEnabled) && logger.debug(`Patch step ${step} took ${performance.now() - startTime}ms with cache`);
return tree;
}
const originalType = node.type;
patchComponent(node, handler, steps, step, caches, logger);
cache.set(originalType, node.type);
(loggingEnabled || perfLoggingEnabled) && logger.debug(`Patch step ${step} took ${performance.now() - startTime}ms`);
return tree;
};
function createStepHandler(handler: GenericPatchHandler, steps: NodeStep[], step: number, caches: PatchedComponentCache[], logger: Logger) {
loggingEnabled && logger.debug(`Creating handler for step ${step}`);
return (_: any, tree: any) => handleStep(tree, handler, steps, step, caches, logger);
}
// TODO handle createReactTreePatcher inside handler and cache it (or warn)
export function createReactTreePatcher(steps: NodeStep[], handler: GenericPatchHandler, debugName: string = 'ReactPatch'): GenericPatchHandler {
const caches: PatchedComponentCache[] = [];
const logger = new Logger(`ReactTreePatcher -> ${debugName}`);
loggingEnabled && logger.debug('Init with options:', steps, debugName);
return createStepHandler(handler, steps, 0, caches, logger);
}