From 24082fe63cdcdf41993f9e1430d1405152a2c930 Mon Sep 17 00:00:00 2001 From: AAGaming Date: Sat, 21 Nov 2026 22:23:03 -0500 Subject: feat: Support new Steam Betas (only) and Frame (#1019) --- frontend/DeckyErrorBoundary.tsx | 444 +++++++++++++++++++++ frontend/ErrorBoundary.ts | 6 + frontend/genClassMap.js | 70 ++++ frontend/global.d.ts | 10 + frontend/package.json | 2 +- frontend/pnpm-lock.yaml | 174 ++++---- frontend/pnpm-workspace.yaml | 7 +- frontend/src/components/NotificationBadge.tsx | 55 ++- frontend/src/components/PluginView.tsx | 40 +- .../src/components/QuickAccessVisibleState.tsx | 17 +- frontend/src/components/Toast.tsx | 47 ++- .../components/settings/pages/developer/index.tsx | 33 +- .../components/settings/pages/general/index.tsx | 3 +- frontend/src/components/store/Store.tsx | 8 +- frontend/src/developer.tsx | 25 +- frontend/src/errorboundary-hook.tsx | 5 +- frontend/src/hooks/router.tsx | 348 ++++++++++++++++ frontend/src/hooks/tabs.tsx | 131 ++++++ frontend/src/hooks/toaster.tsx | 128 ++++++ frontend/src/hooks/vr-dashboard-bar.tsx | 106 +++++ frontend/src/index.ts | 82 ++-- frontend/src/plugin-loader.tsx | 58 ++- frontend/src/router-hook.tsx | 359 ----------------- frontend/src/tabs-hook.tsx | 131 ------ frontend/src/toaster.tsx | 125 ------ frontend/src/updater.ts | 1 + 26 files changed, 1597 insertions(+), 818 deletions(-) create mode 100644 frontend/DeckyErrorBoundary.tsx create mode 100644 frontend/ErrorBoundary.ts create mode 100644 frontend/genClassMap.js create mode 100644 frontend/global.d.ts create mode 100644 frontend/src/hooks/router.tsx create mode 100644 frontend/src/hooks/tabs.tsx create mode 100644 frontend/src/hooks/toaster.tsx create mode 100644 frontend/src/hooks/vr-dashboard-bar.tsx delete mode 100644 frontend/src/router-hook.tsx delete mode 100644 frontend/src/tabs-hook.tsx delete mode 100644 frontend/src/toaster.tsx (limited to 'frontend') diff --git a/frontend/DeckyErrorBoundary.tsx b/frontend/DeckyErrorBoundary.tsx new file mode 100644 index 00000000..f9032a2b --- /dev/null +++ b/frontend/DeckyErrorBoundary.tsx @@ -0,0 +1,444 @@ +import { joinClassNames, sleep } from '@decky/ui'; +import { FunctionComponent, useEffect, useReducer, useState } from 'react'; + +import { disablePlugin, uninstallPlugin } from '../plugin'; +import { VerInfo, doRestart, doShutdown } from '../updater'; +import { ValveReactErrorInfo, getLikelyErrorSourceFromValveReactError } from '../utils/errors'; +import { useSetting } from '../utils/hooks/useSetting'; +import { UpdateBranch } from './settings/pages/general/BranchSelect'; + +interface DeckyErrorBoundaryProps { + error: ValveReactErrorInfo; + errorKey: string; + identifier: string; + reset: () => void; +} + +declare global { + interface Window { + SystemNetworkStore?: any; + } +} + +const classes = { + root: 'deckyErrorBoundary', + likelyOccurred: 'likely-occured-msg', + panel: 'panel-section', + panelHeader: 'panel-header', + trace: 'trace', + rowList: 'row-list', + rowItem: 'row-item', + buttonDescRow: 'button-description-row', + flexRowWGap: 'flex-row', + marginBottom: 'margin-bottom', + swipePrompt: 'swipe-prompt', +}; + +const vars = { + scrollBarwidth: '18px', + rootMarginLeft: '15px', + panelXPadding: '20px', +}; + +export const startSSH = DeckyBackend.callable('utilities/start_ssh'); +export const starrCEFForwarding = DeckyBackend.callable('utilities/allow_remote_debugging'); + +function ipToString(ip: number) { + return [(ip >>> 24) & 255, (ip >>> 16) & 255, (ip >>> 8) & 255, (ip >>> 0) & 255].join('.'); +} + +// Intentionally not localized since we can't really trust React here +const DeckyErrorBoundary: FunctionComponent = ({ error, identifier, reset }) => { + const [actionLog, addLogLine] = useReducer((log: string, line: string) => (log += '\n' + line), ''); + const [actionsEnabled, setActionsEnabled] = useState(true); + const [debugAllowed, setDebugAllowed] = useState(true); + // Intentionally doesn't use DeckyState. + const [versionInfo, setVersionInfo] = useState(); + const [errorSource, wasCausedByPlugin, shouldReportToValve] = getLikelyErrorSourceFromValveReactError(error); + useEffect(() => { + if (!shouldReportToValve) DeckyPluginLoader.errorBoundaryHook.temporarilyDisableReporting(); + DeckyPluginLoader.updateVersion().then(setVersionInfo); + }, []); + + const [selectedBranch, setSelectedBranch] = useSetting('branch', UpdateBranch.Stable); + const [isChecking, setIsChecking] = useState(false); + const [updateProgress, setUpdateProgress] = useState(-1); + const [versionToUpdateTo, setSetVersionToUpdateTo] = useState(''); + + useEffect(() => { + const a = DeckyBackend.addEventListener('updater/update_download_percentage', (percentage) => { + setUpdateProgress(percentage); + }); + + const b = DeckyBackend.addEventListener('updater/finish_download', () => { + setUpdateProgress(-2); + }); + + return () => { + DeckyBackend.removeEventListener('updater/update_download_percentage', a); + DeckyBackend.removeEventListener('updater/finish_download', b); + }; + }, []); + + return ( + <> + +
+
An error occurred while rendering this content.
+
+          
+            {identifier && `Error Reference: ${identifier}`}
+            {versionInfo?.current && `\nDecky Version: ${versionInfo.current}${versionInfo.supported ? '' : '[U]'}`}
+          
+        
+
+ This error likely occurred in {errorSource}. +
+ {actionLog?.length > 0 && ( +
+            
+              Running actions...
+              {actionLog}
+            
+          
+ )} + {actionsEnabled && ( +
+
+
Actions
+
+ Use the touch screen. Solutions are listed in the recommended order. If you are still experiencing + issues, please post in the #loader-support channel at decky.xyz/discord. +
+
+
+
+ Retry the action or restart +
+ + + +
+
+ {wasCausedByPlugin && ( +
+ Disable or uninstall the suspected plugin +
+ + +
+
+ )} +
+ Disable all plugins + +
+ { +
+ {updateProgress > -1 + ? 'Update in progress... ' + updateProgress + '%' + : updateProgress == -2 + ? 'Update complete. Restarting...' + : 'Check for Decky updates'} + { +
+ {updateProgress == -1 && ( + <> + + + + )} +
+ } +
+ } +
+ Disable Decky until next boot + +
+ {debugAllowed && ( +
+ Enable remote debugging and SSH until next boot (for developers) + +
+ )} +
+
+ )} + {actionsEnabled && ( +
+ Swipe to scroll +
+ )} +
+
Trace
+
+            
+              {error.error.stack}
+              {'\n\n'}
+              Component Stack:
+              {error.info.componentStack}
+            
+          
+
+
+ + ); +}; + +export default DeckyErrorBoundary; diff --git a/frontend/ErrorBoundary.ts b/frontend/ErrorBoundary.ts new file mode 100644 index 00000000..a19ad788 --- /dev/null +++ b/frontend/ErrorBoundary.ts @@ -0,0 +1,6 @@ +import { FC, PropsWithChildren } from "react"; +import { findModuleExport } from "../module-system"; + +export const ErrorBoundary = findModuleExport( + (e) => e?.prototype?.Reset && e?.prototype?.componentDidCatch && e.prototype?.render?.toString().includes("lastErrorKey"), +) as FC; // Actually a class but @types/react is broken lol \ No newline at end of file diff --git a/frontend/genClassMap.js b/frontend/genClassMap.js new file mode 100644 index 00000000..704a22cc --- /dev/null +++ b/frontend/genClassMap.js @@ -0,0 +1,70 @@ +import { writeFile, readdir } from 'fs/promises'; + +import oldClasses from './data/oldClasses.json' with { type: 'json' }; + +const data = ( + await import(`./data/mappings/${process.argv[2]}.json`, { + with: { type: 'json' }, + }) +).default; + +const { map } = data; + +let classes = {}; +let classesStub = {}; + +let skip = ['appDetailsHeaderClasses', 'gamepadUIClasses', 'gamepadTabbedPageClasses', 'gamepadContextMenuClasses']; + +for (let classModName in oldClasses) { + if (skip.includes(classModName)) continue; + const classMod = oldClasses[classModName]; + classes[classModName] = {}; + classesStub[classModName] = {}; + for (let className in classMod) { + const oldClass = classMod[className]; + const newClass = map[oldClass]; + if (newClass) { + console.log(`${className} -> ${newClass}`); + classes[classModName][className] = newClass; + classesStub[classModName][className] = ''; + } else { + console.log(`${className}: not found`); + } + } +} + +const classString = JSON.stringify(classes, null, 2); +await writeFile('./generated.json', classString); + +let fileStr = '// GENERATED FILE DO NOT EDIT\n'; +for (let classModName in classes) { + fileStr += `export const ${classModName} = ${JSON.stringify(classes[classModName], null, 2)};\n\n`; +} + +await writeFile(`../src/utils/classData/${process.argv[2]}.ts`, fileStr); + +const dir = await readdir("../src/utils/classData"); +const versions = dir.filter(f => f != "index.ts").map(f => parseInt(f.replace(".ts", ""))); +console.log("Supported:", versions) + +let importerStr = `// GENERATED FILE DO NOT EDIT +declare global { + interface Window { + CLSTAMP: string; + } +} +`; + +for (let classModName in classesStub) { + importerStr += `export let ${classModName} = ${JSON.stringify(classesStub[classModName], null, 2)};\n\n`; +} + +importerStr += ` +const data = await import(\`./\${window.CLSTAMP}.ts\`); +`; + +for (let classModName in classesStub) { + importerStr += `${classModName} = data["${classModName}"];\n`; +} + +await writeFile(`../src/utils/classData/index.ts`, importerStr); \ No newline at end of file diff --git a/frontend/global.d.ts b/frontend/global.d.ts new file mode 100644 index 00000000..bc193a94 --- /dev/null +++ b/frontend/global.d.ts @@ -0,0 +1,10 @@ +import type * as React from 'react'; +import type * as ReactDOM from 'react-dom'; +import type * as JSXRuntime from 'react/jsx-runtime'; +declare global { + interface Window { + SP_REACT: typeof React; + SP_REACTDOM: typeof ReactDOM; + SP_JSX: typeof JSXRuntime; + } +} diff --git a/frontend/package.json b/frontend/package.json index be9a5b3c..6c34acd7 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -47,7 +47,7 @@ } }, "dependencies": { - "@decky/ui": "^4.16.4", + "@decky/ui": "^5.0.0", "compare-versions": "^6.1.1", "filesize": "^10.1.2", "i18next": "^25.6.0", diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml index 4aef2541..b0b551ad 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -9,8 +9,8 @@ importers: .: dependencies: '@decky/ui': - specifier: ^4.16.4 - version: 4.16.4 + specifier: ^5.0.0 + version: 5.0.0 compare-versions: specifier: ^6.1.1 version: 6.1.1 @@ -34,10 +34,10 @@ importers: version: 5.2.1(react@19.1.1) react-markdown: specifier: ^9.0.1 - version: 9.0.1(@types/react@19.1.1)(react@19.1.1) + version: 9.0.1(@types/react@19.1.1)(react@19.1.1)(supports-color@7.2.0) remark-gfm: specifier: ^4.0.0 - version: 4.0.0 + version: 4.0.0(supports-color@7.2.0) devDependencies: '@decky/api': specifier: ^1.1.3 @@ -77,7 +77,7 @@ importers: version: 9.0.11 i18next-parser: specifier: ^9.0.0 - version: 9.0.0 + version: 9.0.0(supports-color@7.2.0) import-sort-style-module: specifier: ^6.0.0 version: 6.0.0 @@ -89,7 +89,7 @@ importers: version: 3.3.2 prettier-plugin-import-sort: specifier: ^0.0.7 - version: 0.0.7(prettier@3.3.2) + version: 0.0.7(prettier@3.3.2)(supports-color@7.2.0) react: specifier: 19.1.1 version: 19.1.1 @@ -222,8 +222,8 @@ packages: '@decky/api@1.1.3': resolution: {integrity: sha512-XsPCZxfxk5I1UtylIUN3qaWQI31siQbKfbLIskkI5innEatY1m4NQqBv/6hwPaO9mKMbdqYpnh5PSJDeMEOOBA==} - '@decky/ui@4.16.4': - resolution: {integrity: sha512-XvnLXa0RcffsIMkl82s2puWQjgSYMnZj9C6N/xoL+9SmJ53V/65HPXU6Yw840hky6784Llc1sVRb5z/jByhB+A==} + '@decky/ui@5.0.0': + resolution: {integrity: sha512-gOgB49uv4qSaMhIspfpqS5qJVbo7XXOgDFbIkaQ+bbOeqykC4CA39pUs8SiwaJL1gsRNtMh7Ed3DkRbTcLhgRA==} '@esbuild/aix-ppc64@0.20.2': resolution: {integrity: sha512-D+EBOJHXdNZcLJRBkhENNG8Wji2kgc9AZ9KiPr1JuZjsNtyHzrsfLRrY0tk2H2aoFu6RANO1y1iPPUCDYWkb5g==} @@ -513,46 +513,55 @@ packages: resolution: {integrity: sha512-j63YtCIRAzbO+gC2L9dWXRh5BFetsv0j0va0Wi9epXDgU/XUi5dJKo4USTttVyK7fGw2nPWK0PbAvyliz50SCQ==} cpu: [arm] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm-musleabihf@4.22.4': resolution: {integrity: sha512-dJnWUgwWBX1YBRsuKKMOlXCzh2Wu1mlHzv20TpqEsfdZLb3WoJW2kIEsGwLkroYf24IrPAvOT/ZQ2OYMV6vlrg==} cpu: [arm] os: [linux] + libc: [musl] '@rollup/rollup-linux-arm64-gnu@4.22.4': resolution: {integrity: sha512-AdPRoNi3NKVLolCN/Sp4F4N1d98c4SBnHMKoLuiG6RXgoZ4sllseuGioszumnPGmPM2O7qaAX/IJdeDU8f26Aw==} cpu: [arm64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm64-musl@4.22.4': resolution: {integrity: sha512-Gl0AxBtDg8uoAn5CCqQDMqAx22Wx22pjDOjBdmG0VIWX3qUBHzYmOKh8KXHL4UpogfJ14G4wk16EQogF+v8hmA==} cpu: [arm64] os: [linux] + libc: [musl] '@rollup/rollup-linux-powerpc64le-gnu@4.22.4': resolution: {integrity: sha512-3aVCK9xfWW1oGQpTsYJJPF6bfpWfhbRnhdlyhak2ZiyFLDaayz0EP5j9V1RVLAAxlmWKTDfS9wyRyY3hvhPoOg==} cpu: [ppc64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-riscv64-gnu@4.22.4': resolution: {integrity: sha512-ePYIir6VYnhgv2C5Xe9u+ico4t8sZWXschR6fMgoPUK31yQu7hTEJb7bCqivHECwIClJfKgE7zYsh1qTP3WHUA==} cpu: [riscv64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-s390x-gnu@4.22.4': resolution: {integrity: sha512-GqFJ9wLlbB9daxhVlrTe61vJtEY99/xB3C8e4ULVsVfflcpmR6c8UZXjtkMA6FhNONhj2eA5Tk9uAVw5orEs4Q==} cpu: [s390x] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-gnu@4.22.4': resolution: {integrity: sha512-87v0ol2sH9GE3cLQLNEy0K/R0pz1nvg76o8M5nhMR0+Q+BBGLnb35P0fVz4CQxHYXaAOhE8HhlkaZfsdUOlHwg==} cpu: [x64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-musl@4.22.4': resolution: {integrity: sha512-UV6FZMUgePDZrFjrNGIWzDo/vABebuXBhJEqrHxrGiU6HikPy0Z3LfdtciIttEUQfuDdCn8fqh7wiFJjCNwO+g==} cpu: [x64] os: [linux] + libc: [musl] '@rollup/rollup-win32-arm64-msvc@4.22.4': resolution: {integrity: sha512-BjI+NVVEGAXjGWYHz/vv0pBqfGoUH0IGZ0cICTn7kB9PyjrATSkX+8WkguNjWoj2qSr1im/+tTGRaY+4/PdcQw==} @@ -630,6 +639,7 @@ packages: '@ungap/structured-clone@1.2.0': resolution: {integrity: sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==} + deprecated: Potential CWE-502 - Update to 1.3.1 or higher aggregate-error@3.1.0: resolution: {integrity: sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==} @@ -1110,6 +1120,7 @@ packages: glob@10.4.1: resolution: {integrity: sha512-2jelhlq3E4ho74ZyVLN03oKdAZVUa6UDZzFLVH1H7dnoax+y9qyaq8zBkfDIggjniU19z0wU18y16jMB2eyVIw==} engines: {node: '>=16 || 14 >=14.18'} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me hasBin: true glob@7.2.3: @@ -1188,6 +1199,7 @@ packages: i18next-parser@9.0.0: resolution: {integrity: sha512-ZguWdu91Qthd001ilX8LdkYrlyYJM8pefnmgTXKTQwd8M2RJAlTCd2ww5uEyAUQe2jxzqSxfTh6XTOJbw5qP5A==} engines: {node: '>=18.0.0 || >=20.0.0 || >=22.0.0', npm: '>=6', yarn: '>=1'} + deprecated: Project is deprecated, use i18next-cli instead hasBin: true i18next@23.16.8: @@ -2177,20 +2189,20 @@ snapshots: '@babel/compat-data@7.24.7': {} - '@babel/core@7.24.7': + '@babel/core@7.24.7(supports-color@7.2.0)': dependencies: '@ampproject/remapping': 2.3.0 '@babel/code-frame': 7.24.7 '@babel/generator': 7.24.7 '@babel/helper-compilation-targets': 7.24.7 - '@babel/helper-module-transforms': 7.24.7(@babel/core@7.24.7) + '@babel/helper-module-transforms': 7.24.7(@babel/core@7.24.7(supports-color@7.2.0))(supports-color@7.2.0) '@babel/helpers': 7.24.7 '@babel/parser': 7.24.7 '@babel/template': 7.24.7 - '@babel/traverse': 7.24.7 + '@babel/traverse': 7.24.7(supports-color@7.2.0) '@babel/types': 7.24.7 convert-source-map: 2.0.0 - debug: 4.3.5 + debug: 4.3.5(supports-color@7.2.0) gensync: 1.0.0-beta.2 json5: 2.2.3 semver: 6.3.1 @@ -2225,27 +2237,27 @@ snapshots: dependencies: '@babel/types': 7.24.7 - '@babel/helper-module-imports@7.24.7': + '@babel/helper-module-imports@7.24.7(supports-color@7.2.0)': dependencies: - '@babel/traverse': 7.24.7 + '@babel/traverse': 7.24.7(supports-color@7.2.0) '@babel/types': 7.24.7 transitivePeerDependencies: - supports-color - '@babel/helper-module-transforms@7.24.7(@babel/core@7.24.7)': + '@babel/helper-module-transforms@7.24.7(@babel/core@7.24.7(supports-color@7.2.0))(supports-color@7.2.0)': dependencies: - '@babel/core': 7.24.7 + '@babel/core': 7.24.7(supports-color@7.2.0) '@babel/helper-environment-visitor': 7.24.7 - '@babel/helper-module-imports': 7.24.7 - '@babel/helper-simple-access': 7.24.7 + '@babel/helper-module-imports': 7.24.7(supports-color@7.2.0) + '@babel/helper-simple-access': 7.24.7(supports-color@7.2.0) '@babel/helper-split-export-declaration': 7.24.7 '@babel/helper-validator-identifier': 7.24.7 transitivePeerDependencies: - supports-color - '@babel/helper-simple-access@7.24.7': + '@babel/helper-simple-access@7.24.7(supports-color@7.2.0)': dependencies: - '@babel/traverse': 7.24.7 + '@babel/traverse': 7.24.7(supports-color@7.2.0) '@babel/types': 7.24.7 transitivePeerDependencies: - supports-color @@ -2288,7 +2300,7 @@ snapshots: '@babel/parser': 7.24.7 '@babel/types': 7.24.7 - '@babel/traverse@7.24.7': + '@babel/traverse@7.24.7(supports-color@7.2.0)': dependencies: '@babel/code-frame': 7.24.7 '@babel/generator': 7.24.7 @@ -2298,7 +2310,7 @@ snapshots: '@babel/helper-split-export-declaration': 7.24.7 '@babel/parser': 7.24.7 '@babel/types': 7.24.7 - debug: 4.3.5 + debug: 4.3.5(supports-color@7.2.0) globals: 11.12.0 transitivePeerDependencies: - supports-color @@ -2311,7 +2323,7 @@ snapshots: '@decky/api@1.1.3': {} - '@decky/ui@4.16.4': {} + '@decky/ui@5.0.0': {} '@esbuild/aix-ppc64@0.20.2': optional: true @@ -2688,19 +2700,19 @@ snapshots: broccoli-node-info@2.2.0: {} - broccoli-output-wrapper@3.2.5: + broccoli-output-wrapper@3.2.5(supports-color@7.2.0): dependencies: fs-extra: 8.1.0 - heimdalljs-logger: 0.1.10 + heimdalljs-logger: 0.1.10(supports-color@7.2.0) symlink-or-copy: 1.3.1 transitivePeerDependencies: - supports-color - broccoli-plugin@4.0.7: + broccoli-plugin@4.0.7(supports-color@7.2.0): dependencies: broccoli-node-api: 1.7.0 - broccoli-output-wrapper: 3.2.5 - fs-merger: 3.2.1 + broccoli-output-wrapper: 3.2.5(supports-color@7.2.0) + fs-merger: 3.2.1(supports-color@7.2.0) promise-map-series: 0.3.0 quick-temp: 0.1.8 rimraf: 3.0.2 @@ -2874,13 +2886,17 @@ snapshots: csstype@3.1.3: {} - debug@2.6.9: + debug@2.6.9(supports-color@7.2.0): dependencies: ms: 2.0.0 + optionalDependencies: + supports-color: 7.2.0 - debug@4.3.5: + debug@4.3.5(supports-color@7.2.0): dependencies: ms: 2.1.2 + optionalDependencies: + supports-color: 7.2.0 decode-named-character-reference@1.0.2: dependencies: @@ -3056,12 +3072,12 @@ snapshots: jsonfile: 4.0.0 universalify: 0.1.2 - fs-merger@3.2.1: + fs-merger@3.2.1(supports-color@7.2.0): dependencies: broccoli-node-api: 1.7.0 broccoli-node-info: 2.2.0 fs-extra: 8.1.0 - fs-tree-diff: 2.0.1 + fs-tree-diff: 2.0.1(supports-color@7.2.0) walk-sync: 2.2.0 transitivePeerDependencies: - supports-color @@ -3071,10 +3087,10 @@ snapshots: graceful-fs: 4.2.11 streamx: 2.18.0 - fs-tree-diff@2.0.1: + fs-tree-diff@2.0.1(supports-color@7.2.0): dependencies: '@types/symlink-or-copy': 1.2.2 - heimdalljs-logger: 0.1.10 + heimdalljs-logger: 0.1.10(supports-color@7.2.0) object-assign: 4.1.1 path-posix: 1.0.0 symlink-or-copy: 1.3.1 @@ -3175,7 +3191,7 @@ snapshots: dependencies: function-bind: 1.1.2 - hast-util-to-jsx-runtime@2.3.0: + hast-util-to-jsx-runtime@2.3.0(supports-color@7.2.0): dependencies: '@types/estree': 1.0.5 '@types/hast': 3.0.4 @@ -3184,9 +3200,9 @@ snapshots: devlop: 1.1.0 estree-util-is-identifier-name: 3.0.0 hast-util-whitespace: 3.0.0 - mdast-util-mdx-expression: 2.0.0 - mdast-util-mdx-jsx: 3.1.2 - mdast-util-mdxjs-esm: 2.0.1 + mdast-util-mdx-expression: 2.0.0(supports-color@7.2.0) + mdast-util-mdx-jsx: 3.1.2(supports-color@7.2.0) + mdast-util-mdxjs-esm: 2.0.1(supports-color@7.2.0) property-information: 6.5.0 space-separated-tokens: 2.0.2 style-to-object: 1.0.6 @@ -3199,9 +3215,9 @@ snapshots: dependencies: '@types/hast': 3.0.4 - heimdalljs-logger@0.1.10: + heimdalljs-logger@0.1.10(supports-color@7.2.0): dependencies: - debug: 2.6.9 + debug: 2.6.9(supports-color@7.2.0) heimdalljs: 0.2.6 transitivePeerDependencies: - supports-color @@ -3231,10 +3247,10 @@ snapshots: transitivePeerDependencies: - encoding - i18next-parser@9.0.0: + i18next-parser@9.0.0(supports-color@7.2.0): dependencies: '@babel/runtime': 7.24.7 - broccoli-plugin: 4.0.7 + broccoli-plugin: 4.0.7(supports-color@7.2.0) cheerio: 1.0.0-rc.12 colors: 1.4.0 commander: 12.1.0 @@ -3287,11 +3303,11 @@ snapshots: minimatch: 3.1.2 resolve-from: 4.0.0 - import-sort-parser-babylon@6.0.0: + import-sort-parser-babylon@6.0.0(supports-color@7.2.0): dependencies: - '@babel/core': 7.24.7 + '@babel/core': 7.24.7(supports-color@7.2.0) '@babel/parser': 7.24.7 - '@babel/traverse': 7.24.7 + '@babel/traverse': 7.24.7(supports-color@7.2.0) '@babel/types': 7.24.7 find-line-column: 0.5.2 transitivePeerDependencies: @@ -3485,14 +3501,14 @@ snapshots: unist-util-is: 6.0.0 unist-util-visit-parents: 6.0.1 - mdast-util-from-markdown@2.0.1: + mdast-util-from-markdown@2.0.1(supports-color@7.2.0): dependencies: '@types/mdast': 4.0.4 '@types/unist': 3.0.2 decode-named-character-reference: 1.0.2 devlop: 1.1.0 mdast-util-to-string: 4.0.0 - micromark: 4.0.0 + micromark: 4.0.0(supports-color@7.2.0) micromark-util-decode-numeric-character-reference: 2.0.1 micromark-util-decode-string: 2.0.0 micromark-util-normalize-identifier: 2.0.0 @@ -3510,67 +3526,67 @@ snapshots: mdast-util-find-and-replace: 3.0.1 micromark-util-character: 2.1.0 - mdast-util-gfm-footnote@2.0.0: + mdast-util-gfm-footnote@2.0.0(supports-color@7.2.0): dependencies: '@types/mdast': 4.0.4 devlop: 1.1.0 - mdast-util-from-markdown: 2.0.1 + mdast-util-from-markdown: 2.0.1(supports-color@7.2.0) mdast-util-to-markdown: 2.1.0 micromark-util-normalize-identifier: 2.0.0 transitivePeerDependencies: - supports-color - mdast-util-gfm-strikethrough@2.0.0: + mdast-util-gfm-strikethrough@2.0.0(supports-color@7.2.0): dependencies: '@types/mdast': 4.0.4 - mdast-util-from-markdown: 2.0.1 + mdast-util-from-markdown: 2.0.1(supports-color@7.2.0) mdast-util-to-markdown: 2.1.0 transitivePeerDependencies: - supports-color - mdast-util-gfm-table@2.0.0: + mdast-util-gfm-table@2.0.0(supports-color@7.2.0): dependencies: '@types/mdast': 4.0.4 devlop: 1.1.0 markdown-table: 3.0.3 - mdast-util-from-markdown: 2.0.1 + mdast-util-from-markdown: 2.0.1(supports-color@7.2.0) mdast-util-to-markdown: 2.1.0 transitivePeerDependencies: - supports-color - mdast-util-gfm-task-list-item@2.0.0: + mdast-util-gfm-task-list-item@2.0.0(supports-color@7.2.0): dependencies: '@types/mdast': 4.0.4 devlop: 1.1.0 - mdast-util-from-markdown: 2.0.1 + mdast-util-from-markdown: 2.0.1(supports-color@7.2.0) mdast-util-to-markdown: 2.1.0 transitivePeerDependencies: - supports-color - mdast-util-gfm@3.0.0: + mdast-util-gfm@3.0.0(supports-color@7.2.0): dependencies: - mdast-util-from-markdown: 2.0.1 + mdast-util-from-markdown: 2.0.1(supports-color@7.2.0) mdast-util-gfm-autolink-literal: 2.0.0 - mdast-util-gfm-footnote: 2.0.0 - mdast-util-gfm-strikethrough: 2.0.0 - mdast-util-gfm-table: 2.0.0 - mdast-util-gfm-task-list-item: 2.0.0 + mdast-util-gfm-footnote: 2.0.0(supports-color@7.2.0) + mdast-util-gfm-strikethrough: 2.0.0(supports-color@7.2.0) + mdast-util-gfm-table: 2.0.0(supports-color@7.2.0) + mdast-util-gfm-task-list-item: 2.0.0(supports-color@7.2.0) mdast-util-to-markdown: 2.1.0 transitivePeerDependencies: - supports-color - mdast-util-mdx-expression@2.0.0: + mdast-util-mdx-expression@2.0.0(supports-color@7.2.0): dependencies: '@types/estree-jsx': 1.0.5 '@types/hast': 3.0.4 '@types/mdast': 4.0.4 devlop: 1.1.0 - mdast-util-from-markdown: 2.0.1 + mdast-util-from-markdown: 2.0.1(supports-color@7.2.0) mdast-util-to-markdown: 2.1.0 transitivePeerDependencies: - supports-color - mdast-util-mdx-jsx@3.1.2: + mdast-util-mdx-jsx@3.1.2(supports-color@7.2.0): dependencies: '@types/estree-jsx': 1.0.5 '@types/hast': 3.0.4 @@ -3578,7 +3594,7 @@ snapshots: '@types/unist': 3.0.2 ccount: 2.0.1 devlop: 1.1.0 - mdast-util-from-markdown: 2.0.1 + mdast-util-from-markdown: 2.0.1(supports-color@7.2.0) mdast-util-to-markdown: 2.1.0 parse-entities: 4.0.1 stringify-entities: 4.0.4 @@ -3588,13 +3604,13 @@ snapshots: transitivePeerDependencies: - supports-color - mdast-util-mdxjs-esm@2.0.1: + mdast-util-mdxjs-esm@2.0.1(supports-color@7.2.0): dependencies: '@types/estree-jsx': 1.0.5 '@types/hast': 3.0.4 '@types/mdast': 4.0.4 devlop: 1.1.0 - mdast-util-from-markdown: 2.0.1 + mdast-util-from-markdown: 2.0.1(supports-color@7.2.0) mdast-util-to-markdown: 2.1.0 transitivePeerDependencies: - supports-color @@ -3802,10 +3818,10 @@ snapshots: micromark-util-types@2.0.0: {} - micromark@4.0.0: + micromark@4.0.0(supports-color@7.2.0): dependencies: '@types/debug': 4.1.12 - debug: 4.3.5 + debug: 4.3.5(supports-color@7.2.0) decode-named-character-reference: 1.0.2 devlop: 1.1.0 micromark-core-commonmark: 2.0.1 @@ -3945,11 +3961,11 @@ snapshots: picomatch@2.3.1: {} - prettier-plugin-import-sort@0.0.7(prettier@3.3.2): + prettier-plugin-import-sort@0.0.7(prettier@3.3.2)(supports-color@7.2.0): dependencies: import-sort: 6.0.0 import-sort-config: 6.0.0 - import-sort-parser-babylon: 6.0.0 + import-sort-parser-babylon: 6.0.0(supports-color@7.2.0) import-sort-parser-typescript: 6.0.0 prettier: 3.3.2 transitivePeerDependencies: @@ -4007,16 +4023,16 @@ snapshots: react-is@16.13.1: {} - react-markdown@9.0.1(@types/react@19.1.1)(react@19.1.1): + react-markdown@9.0.1(@types/react@19.1.1)(react@19.1.1)(supports-color@7.2.0): dependencies: '@types/hast': 3.0.4 '@types/react': 19.1.1 devlop: 1.1.0 - hast-util-to-jsx-runtime: 2.3.0 + hast-util-to-jsx-runtime: 2.3.0(supports-color@7.2.0) html-url-attributes: 3.0.0 mdast-util-to-hast: 13.2.0 react: 19.1.1 - remark-parse: 11.0.0 + remark-parse: 11.0.0(supports-color@7.2.0) remark-rehype: 11.1.0 unified: 11.0.4 unist-util-visit: 5.0.0 @@ -4044,21 +4060,21 @@ snapshots: regenerator-runtime@0.14.1: {} - remark-gfm@4.0.0: + remark-gfm@4.0.0(supports-color@7.2.0): dependencies: '@types/mdast': 4.0.4 - mdast-util-gfm: 3.0.0 + mdast-util-gfm: 3.0.0(supports-color@7.2.0) micromark-extension-gfm: 3.0.0 - remark-parse: 11.0.0 + remark-parse: 11.0.0(supports-color@7.2.0) remark-stringify: 11.0.0 unified: 11.0.4 transitivePeerDependencies: - supports-color - remark-parse@11.0.0: + remark-parse@11.0.0(supports-color@7.2.0): dependencies: '@types/mdast': 4.0.4 - mdast-util-from-markdown: 2.0.1 + mdast-util-from-markdown: 2.0.1(supports-color@7.2.0) micromark-util-types: 2.0.0 unified: 11.0.4 transitivePeerDependencies: diff --git a/frontend/pnpm-workspace.yaml b/frontend/pnpm-workspace.yaml index a6e847b3..80cb4cd7 100644 --- a/frontend/pnpm-workspace.yaml +++ b/frontend/pnpm-workspace.yaml @@ -1,5 +1,6 @@ -minimumReleaseAgeExclude: -- "@decky/api" -- "@decky/ui" allowBuilds: esbuild: true + +minimumReleaseAgeExclude: + - '@decky/api' + - '@decky/ui' diff --git a/frontend/src/components/NotificationBadge.tsx b/frontend/src/components/NotificationBadge.tsx index 3c5d8215..1d14d576 100644 --- a/frontend/src/components/NotificationBadge.tsx +++ b/frontend/src/components/NotificationBadge.tsx @@ -2,23 +2,52 @@ import { CSSProperties, FunctionComponent } from 'react'; interface NotificationBadgeProps { show?: boolean; + vr?: boolean; style?: CSSProperties; } -const NotificationBadge: FunctionComponent = ({ show, style }) => { +const NotificationBadge: FunctionComponent = ({ show, style, vr }) => { return show ? ( -
+ vr ? ( + // whoever made transform:scale completely break absolute positioning goes straight to super turbo hell this took me an hour +
+
+
+ ) : ( +
+ ) ) : null; }; diff --git a/frontend/src/components/PluginView.tsx b/frontend/src/components/PluginView.tsx index fbafaf05..27c1f2f1 100644 --- a/frontend/src/components/PluginView.tsx +++ b/frontend/src/components/PluginView.tsx @@ -1,4 +1,12 @@ -import { ButtonItem, ErrorBoundary, Focusable, PanelSection, PanelSectionRow } from '@decky/ui'; +import { + ButtonItem, + ErrorBoundary, + Focusable, + PanelSection, + PanelSectionRow, + joinClassNames, + vrDashboardClasses, +} from '@decky/ui'; import { FC, useMemo } from 'react'; import { useTranslation } from 'react-i18next'; import { FaBan, FaEyeSlash } from 'react-icons/fa'; @@ -8,7 +16,7 @@ import NotificationBadge from './NotificationBadge'; import { useQuickAccessVisible } from './QuickAccessVisibleState'; import TitleView from './TitleView'; -const PluginView: FC = () => { +const PluginView: FC<{ vr?: boolean }> = ({ vr }) => { const { plugins, disabledPlugins, @@ -40,20 +48,38 @@ const PluginView: FC = () => { if (activePlugin) { return ( - + -
+
{(visible || activePlugin.alwaysRender) && activePlugin.content}
); } return ( - <> +
@@ -92,7 +118,7 @@ const PluginView: FC = () => {
- +
); }; diff --git a/frontend/src/components/QuickAccessVisibleState.tsx b/frontend/src/components/QuickAccessVisibleState.tsx index f90c24b4..83e45177 100644 --- a/frontend/src/components/QuickAccessVisibleState.tsx +++ b/frontend/src/components/QuickAccessVisibleState.tsx @@ -1,16 +1,21 @@ import { FC, PropsWithChildren, createContext, useContext, useState } from 'react'; -const QuickAccessVisibleState = createContext(false); +export const QuickAccessVisibleState = createContext(false); export const useQuickAccessVisible = () => useContext(QuickAccessVisibleState); -export const QuickAccessVisibleStateProvider: FC> = ({ children, tab }) => { - const initial = tab.initialVisibility; +export const QuickAccessVisibleStateProvider: FC> = ({ + children, + tab, + initialVal, +}) => { + const initial = initialVal || tab?.initialVisibility; const [visible, setVisible] = useState(initial); // HACK but i can't think of a better way to do this - tab.qAMVisibilitySetter = (val: boolean) => { - if (val != visible) setVisible(val); - }; + if (tab) + tab.qAMVisibilitySetter = (val: boolean) => { + if (val != visible) setVisible(val); + }; return {children}; }; diff --git a/frontend/src/components/Toast.tsx b/frontend/src/components/Toast.tsx index e86e9337..8b6b9d63 100644 --- a/frontend/src/components/Toast.tsx +++ b/frontend/src/components/Toast.tsx @@ -1,5 +1,5 @@ import type { ToastData } from '@decky/api'; -import { Focusable, Navigation, findClassModule, joinClassNames } from '@decky/ui'; +import { Focusable, Navigation, joinClassNames, toastClasses } from '@decky/ui'; import { FC, memo } from 'react'; import Logger from '../logger'; @@ -23,7 +23,14 @@ interface ToastRendererProps extends ToastProps { location: ToastLocation; } -const templateClasses = findClassModule((m) => m.ShortTemplate) || {}; +const popupClasses = { + ShortTemplate: 'kg8VJS07NZk-', + Content: 'vjeKRorxqWY-', + Header: 'UWjdKshdhD8-', + Icon: 'q9vQBNOskjU-', + Title: 'RZ1644uUH-k-', + Body: '_5LTIC-a3DVw-', +}; // These are memoized as they like to randomly rerender @@ -32,15 +39,15 @@ const GamepadUIPopupToast: FC> = memo(({ toast
- {toast.logo &&
{toast.logo}
} -
-
- {toast.icon &&
{toast.icon}
} -
{toast.title}
+ {toast.logo &&
{toast.logo}
} +
+
+ {toast.icon &&
{toast.icon}
} +
{toast.title}
-
{toast.body}
+
{toast.body}
); @@ -55,30 +62,30 @@ const GamepadUIQAMToast: FC = memo(({ toast, newIndicator }) => { Navigation.CloseSideMenus(); }} className={joinClassNames( - templateClasses.StandardTemplateContainer, + toastClasses.StandardTemplateContainer, toast.className || '', 'DeckyGamepadUIQAMToast', )} > -
- {toast.logo &&
{toast.logo}
} -
-
- {toast.icon &&
{toast.icon}
} - {toast.title &&
{toast.title}
} +
+ {toast.logo &&
{toast.logo}
} +
+
+ {toast.icon &&
{toast.icon}
} + {toast.title &&
{toast.title}
} {/* timestamp should always be defined by toaster */} {/* TODO check how valve does this */} {toast.timestamp && ( -
+
{toast.timestamp.toLocaleTimeString(undefined, { timeStyle: 'short' })}
)}
- {toast.body &&
{toast.body}
} - {toast.subtext &&
{toast.subtext}
} + {toast.body &&
{toast.body}
} + {toast.subtext &&
{toast.subtext}
}
{newIndicator && ( -
+
diff --git a/frontend/src/components/settings/pages/developer/index.tsx b/frontend/src/components/settings/pages/developer/index.tsx index 17187675..b6a337f0 100644 --- a/frontend/src/components/settings/pages/developer/index.tsx +++ b/frontend/src/components/settings/pages/developer/index.tsx @@ -9,7 +9,7 @@ import { Toggle, showModal, } from '@decky/ui'; -import { useRef, useState } from 'react'; +import { useState } from 'react'; import { useTranslation } from 'react-i18next'; import { FaFileArchive, FaLink, FaReact, FaSteamSymbol, FaTerminal } from 'react-icons/fa'; @@ -49,7 +49,6 @@ export default function DeveloperSettings() { const [acceptedWarning, setAcceptedWarning] = useSetting('developer.warn.third_party', false); const waitTime = acceptedWarning ? 0 : 5; const [pluginURL, setPluginURL] = useState(''); - const textRef = useRef(null); const { t } = useTranslation(); return ( @@ -82,13 +81,6 @@ export default function DeveloperSettings() { setPluginURL(e?.target.value)} - /> - } icon={} > + setPluginURL(e?.target.value)} + /> {t('SettingsDeveloperIndex.header')} @@ -160,18 +157,7 @@ export default function DeveloperSettings() { - {t('SettingsDeveloperIndex.react_devtools.desc')} -
-
-
- setReactDevtoolsIP(e?.target.value)} - /> -
- + {t('SettingsDeveloperIndex.react_devtools.desc')} } icon={} > @@ -184,6 +170,11 @@ export default function DeveloperSettings() { }} />
+ setReactDevtoolsIP(e?.target.value)} + />
); diff --git a/frontend/src/components/settings/pages/general/index.tsx b/frontend/src/components/settings/pages/general/index.tsx index 401da1d2..215d392c 100644 --- a/frontend/src/components/settings/pages/general/index.tsx +++ b/frontend/src/components/settings/pages/general/index.tsx @@ -58,7 +58,8 @@ export default function GeneralSettings({ {t('SettingsGeneralIndex.about.header')}
- {versionInfo?.current} ({versionInfo?.repo}#{versionInfo?.gitBranch}) + {versionInfo?.current} ({versionInfo?.repo}#{versionInfo?.gitBranch} + {versionInfo?.gitPR ? ` (#${versionInfo.gitPR})` : ''})
diff --git a/frontend/src/components/store/Store.tsx b/frontend/src/components/store/Store.tsx index cfa83aff..e66899be 100644 --- a/frontend/src/components/store/Store.tsx +++ b/frontend/src/components/store/Store.tsx @@ -7,7 +7,7 @@ import { SteamSpinner, Tabs, TextField, - findModule, + tabsClasses, } from '@decky/ui'; import { Dispatch, FC, SetStateAction, useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; @@ -32,10 +32,6 @@ const logger = new Logger('Store'); const StorePage: FC<{}> = () => { const [currentTabRoute, setCurrentTabRoute] = useState('browse'); const [pluginCount, setPluginCount] = useState(null); - const { TabCount } = findModule((m) => { - if (m?.TabCount && m?.TabTitle) return true; - return false; - }); const { t } = useTranslation(); @@ -58,7 +54,7 @@ const StorePage: FC<{}> = () => { title: t('Store.store_tabs.title'), content: , id: 'browse', - renderTabAddon: () => {pluginCount}, + renderTabAddon: () => {pluginCount}, }, { title: t('Store.store_tabs.about'), diff --git a/frontend/src/developer.tsx b/frontend/src/developer.tsx index 67d9c4b8..6e1b9599 100644 --- a/frontend/src/developer.tsx +++ b/frontend/src/developer.tsx @@ -30,17 +30,18 @@ export async function setShowValveInternal(show: boolean) { } } -export async function setShouldConnectToReactDevTools(enable: boolean) { - DeckyPluginLoader.toaster.toast({ - title: enable ? ( - - ) : ( - - ), - body: , - icon: , - }); - await sleep(5000); +export async function setShouldConnectToReactDevTools(enable: boolean, skipWait?: boolean) { + skipWait || + DeckyPluginLoader.toaster.toast({ + title: enable ? ( + + ) : ( + + ), + body: , + icon: , + }); + skipWait || (await sleep(5000)); return enable ? DeckyBackend.call('utilities/enable_rdt') : DeckyBackend.call('utilities/disable_rdt'); } @@ -51,5 +52,5 @@ export async function startup() { if (isValveInternalEnabled) setShowValveInternal(isValveInternalEnabled); if ((isRDTEnabled && !window.deckyHasConnectedRDT) || (!isRDTEnabled && window.deckyHasConnectedRDT)) - setShouldConnectToReactDevTools(isRDTEnabled); + setShouldConnectToReactDevTools(isRDTEnabled, true); } diff --git a/frontend/src/errorboundary-hook.tsx b/frontend/src/errorboundary-hook.tsx index 9dbe9dcd..0c98c6ff 100644 --- a/frontend/src/errorboundary-hook.tsx +++ b/frontend/src/errorboundary-hook.tsx @@ -26,7 +26,10 @@ class ErrorBoundaryHook extends Logger { // valve writes only the sanest of code const exp = /^\(\)=>\([\w$]+\|\|(?:[\w$]+\(|\([\w$]+=)new [\w$]+\),[\w$]+\)$/; const initErrorReportingStore = findModuleExport( - (e) => typeof e == 'function' && e?.toString && exp.test(e.toString()), + (e) => + typeof e == 'function' && + e?.toString && + (exp.test(e.toString()) || e.toString() == '()=>(store||=new CErrorReportingStore,store)'), ); if (!initErrorReportingStore) { diff --git a/frontend/src/hooks/router.tsx b/frontend/src/hooks/router.tsx new file mode 100644 index 00000000..95fd8eeb --- /dev/null +++ b/frontend/src/hooks/router.tsx @@ -0,0 +1,348 @@ +import { + EUIMode, + ErrorBoundary, + Patch, + afterPatch, + findInReactTree, + findInTree, + findVar, + getReactRoot, + sleep, +} from '@decky/ui'; +import { FC, JSX, ReactElement, ReactNode, cloneElement, createElement } from 'react'; +import type { Route } from 'react-router'; + +import { + DeckyGlobalComponentsState, + DeckyGlobalComponentsStateContextProvider, + useDeckyGlobalComponentsState, +} from '../components/DeckyGlobalComponentsState'; +import { + DeckyRouterState, + DeckyRouterStateContextProvider, + RoutePatch, + RouterEntry, + useDeckyRouterState, +} from '../components/DeckyRouterState'; +import Logger from '../logger'; + +declare global { + interface Window { + __ROUTER_HOOK_INSTANCE: any; + } +} + +const isPatched = Symbol('is patched'); + +class RouterHook extends Logger { + private routerState: DeckyRouterState = new DeckyRouterState(); + private globalComponentsState: DeckyGlobalComponentsState = new DeckyGlobalComponentsState(); + private renderedComponents: ReactElement[] = []; + private Route: any; + private DeckyGamepadRouterWrapper = this.gamepadRouterWrapper.bind(this); + private DeckyDesktopRouterWrapper = this.desktopRouterWrapper.bind(this); + private DeckyGlobalComponentsWrapper = this.globalComponentsWrapper.bind(this); + private toReplace = new Map(); + private desktopRouterPatch?: Patch; + private gamepadRouterPatch?: Patch; + private modeChangeRegistration?: any; + private patchedModes = new Set(); + public routes?: any[]; + + constructor() { + super('RouterHook'); + + this.log('Initialized'); + window.__ROUTER_HOOK_INSTANCE?.deinit?.(); + window.__ROUTER_HOOK_INSTANCE = this; + + this.Route = findVar((e) => typeof e == 'function' && /routePath:[\w$]+\.match\?\.path./.test(e.toString())); + if (!this.Route) { + this.error('Failed to find Route component'); + } + + this.modeChangeRegistration = SteamClient.UI.RegisterForUIModeChanged((mode: EUIMode) => { + this.debug(`UI mode changed to ${mode}`); + if (this.patchedModes.has(mode)) return; + this.patchedModes.add(mode); + this.debug(`Patching router for UI mode ${mode}`); + switch (mode) { + case EUIMode.GamePad: + this.debug('Patching gamepad router'); + this.patchGamepadRouter(); + break; + // Not fully implemented yet + // case EUIMode.Desktop: + // this.debug("Patching desktop router"); + // this.patchDesktopRouter(); + // break; + default: + this.warn(`Router patch not implemented for UI mode ${mode}`); + break; + } + }); + } + + private async patchGamepadRouter() { + const root = getReactRoot(document.getElementById('root') as any); + const findRouterNode = () => + findInReactTree( + root, + (node) => + typeof node?.pendingProps?.loggedIn == 'undefined' && node?.type?.toString().includes('Settings.Root()'), + ); + await this.waitForUnlock(); + let routerNode = findRouterNode(); + while (!routerNode) { + this.warn('Failed to find Router node, reattempting in 5 seconds.'); + await sleep(5000); + await this.waitForUnlock(); + routerNode = findRouterNode(); + } + if (routerNode) { + // Patch the component globally + this.gamepadRouterPatch = afterPatch(routerNode.elementType, 'type', this.handleGamepadRouterRender.bind(this)); + // Swap out the current instance + routerNode.type = routerNode.elementType.type; + if (routerNode?.alternate) { + routerNode.alternate.type = routerNode.type; + } + // Force a full rerender via our custom error boundary + const errorBoundaryNode = findInTree(routerNode, (e) => e?.stateNode?._deckyForceRerender, { + walkable: ['return'], + }); + errorBoundaryNode?.stateNode?._deckyForceRerender?.(); + } + } + + // Currently unused + // @ts-expect-error 6133 + private async patchDesktopRouter() { + const root = getReactRoot(document.getElementById('root') as any); + const findRouterNode = () => + findInReactTree(root, (node) => node?.elementType?.type?.toString?.()?.includes('bShowDesktopUIContent:')); + let routerNode = findRouterNode(); + while (!routerNode) { + this.warn('Failed to find Router node, reattempting in 5 seconds.'); + await sleep(5000); + routerNode = findRouterNode(); + } + if (routerNode) { + // this.debug("desktop router node", routerNode); + // Patch the component globally + this.desktopRouterPatch = afterPatch(routerNode.elementType, 'type', this.handleDesktopRouterRender.bind(this)); + // Swap out the current instance + routerNode.type = routerNode.elementType.type; + if (routerNode?.alternate) { + routerNode.alternate.type = routerNode.type; + } + // Force a full rerender via our custom error boundary + const errorBoundaryNode = findInTree(routerNode, (e) => e?.stateNode?._deckyForceRerender, { + walkable: ['return'], + }); + errorBoundaryNode?.stateNode?._deckyForceRerender?.(); + // this.debug("desktop router node", routerNode); + // // Patch the component globally + // this.desktopRouterPatch = afterPatch(routerNode.type.prototype, 'render', this.handleDesktopRouterRender.bind(this)); + // const stateNodeClone = { render: routerNode.stateNode.render } as any; + // // Patch the current instance. render is readonly so we have to do this. + // Object.assign(stateNodeClone, routerNode.stateNode); + // Object.setPrototypeOf(stateNodeClone, Object.getPrototypeOf(routerNode.stateNode)); + // this.desktopRouterFirstInstancePatch = afterPatch(stateNodeClone, 'render', this.handleDesktopRouterRender.bind(this)); + // routerNode.stateNode = stateNodeClone; + // // Swap out the current instance + // if (routerNode?.alternate) { + // routerNode.alternate.type = routerNode.type; + // routerNode.alternate.stateNode = routerNode.stateNode; + // } + // routerNode.stateNode.forceUpdate(); + // Force a full rerender via our custom error boundary + // const errorBoundaryNode = findInTree(routerNode, e => e?.stateNode?._deckyForceRerender, { walkable: ["return"] }); + // errorBoundaryNode?.stateNode?._deckyForceRerender?.(); + } + } + + public async waitForUnlock() { + try { + while (window?.securitystore?.IsLockScreenActive?.()) { + await sleep(500); + } + } catch (e) { + this.warn('Error while checking if unlocked:', e); + } + } + + public handleDesktopRouterRender(_: any, ret: any) { + const DeckyDesktopRouterWrapper = this.DeckyDesktopRouterWrapper; + const DeckyGlobalComponentsWrapper = this.DeckyGlobalComponentsWrapper; + this.debug('desktop router render', ret); + if (ret._decky) { + return ret; + } + const returnVal = ( + <> + + {ret} + + + + + + ); + (returnVal as any)._decky = true; + return returnVal; + } + + public handleGamepadRouterRender(_: any, ret: any) { + const DeckyGamepadRouterWrapper = this.DeckyGamepadRouterWrapper; + const DeckyGlobalComponentsWrapper = this.DeckyGlobalComponentsWrapper; + if (ret._decky) { + return ret; + } + const returnVal = ( + <> + + {ret} + + + + + + ); + (returnVal as any)._decky = true; + return returnVal; + } + + private globalComponentsWrapper() { + const { components } = useDeckyGlobalComponentsState(); + if (this.renderedComponents.length != components.size) { + this.debug('Rerendering global components'); + this.renderedComponents = Array.from(components.values()).map((GComponent) => ); + } + return <>{this.renderedComponents}; + } + + private gamepadRouterWrapper({ children }: { children: ReactElement }) { + // Used to store the new replicated routes we create to allow routes to be unpatched. + + const { routes, routePatches } = useDeckyRouterState(); + // TODO make more redundant + if (!children?.props?.children?.[0]?.props?.children) { + this.debug('routerWrapper wrong component?', children); + return children; + } + const mainRouteList = children.props.children[0].props.children; + const ingameRouteList = children.props.children[1].props.children; // /appoverlay and /apprunning + this.processList(mainRouteList, routes, routePatches, true); + this.processList(ingameRouteList, null, routePatches, false); + + this.debug('Rerendered gamepadui routes list'); + return children; + } + + private desktopRouterWrapper({ children }: { children: ReactElement }) { + // Used to store the new replicated routes we create to allow routes to be unpatched. + this.debug('desktop router wrapper render', children); + const { routes, routePatches } = useDeckyRouterState(); + const routeList = findInReactTree( + children, + (node) => node?.length > 2 && node?.find((elem: any) => elem?.props?.path == '/library/home'), + ); + if (!routeList) { + this.debug('routerWrapper wrong component?', children); + return children; + } + const library = children.props.children[1].props.children.props; + if (!Array.isArray(library.children)) { + library.children = [library.children]; + } + this.debug('library', library); + this.processList(library.children, routes, routePatches, true); + + this.debug('Rerendered desktop routes list'); + return children; + } + + private processList( + routeList: any[], + routes: Map | null, + routePatches: Map>, + save: boolean, + ) { + const Route = this.Route; + this.debug('Route list: ', routeList); + if (save) this.routes = routeList; + let routerIndex = routeList.length; + if (routes) { + if (!routeList[routerIndex - 1]?.length || routeList[routerIndex - 1]?.length !== routes.size) { + if (routeList[routerIndex - 1]?.length && routeList[routerIndex - 1].length !== routes.size) routerIndex--; + const newRouterArray: (ReactElement | JSX.Element)[] = []; + routes.forEach(({ component, props }, path) => { + newRouterArray.push( + + {createElement(component)} + , + ); + }); + routeList[routerIndex] = newRouterArray; + } + } + routeList.forEach((route: Route, index: number) => { + const replaced = this.toReplace.get(route?.props?.path as string); + if (replaced) { + routeList[index].props.children = replaced; + this.toReplace.delete(route?.props?.path as string); + } + if (route?.props?.path && routePatches.has(route.props.path as string)) { + this.toReplace.set( + route?.props?.path as string, + // @ts-ignore + routeList[index].props.children, + ); + routePatches.get(route.props.path as string)?.forEach((patch) => { + const oType = routeList[index].props.children.type; + routeList[index].props.children = patch({ + ...routeList[index].props, + children: { + ...cloneElement(routeList[index].props.children), + type: routeList[index].props.children[isPatched] ? oType : (props) => createElement(oType, props), + }, + }).children; + routeList[index].props.children[isPatched] = true; + }); + } + }); + } + + addRoute(path: string, component: RouterEntry['component'], props: RouterEntry['props'] = {}) { + this.routerState.addRoute(path, component, props); + } + + addPatch(path: string, patch: RoutePatch) { + return this.routerState.addPatch(path, patch); + } + + addGlobalComponent(name: string, component: FC) { + this.globalComponentsState.addComponent(name, component); + } + + removeGlobalComponent(name: string) { + this.globalComponentsState.removeComponent(name); + } + + removePatch(path: string, patch: RoutePatch) { + this.routerState.removePatch(path, patch); + } + + removeRoute(path: string) { + this.routerState.removeRoute(path); + } + + deinit() { + this.modeChangeRegistration?.unregister(); + this.gamepadRouterPatch?.unpatch(); + this.desktopRouterPatch?.unpatch(); + } +} + +export default RouterHook; diff --git a/frontend/src/hooks/tabs.tsx b/frontend/src/hooks/tabs.tsx new file mode 100644 index 00000000..35f05472 --- /dev/null +++ b/frontend/src/hooks/tabs.tsx @@ -0,0 +1,131 @@ +// TabsHook for versions after the Desktop merge +import { + ErrorBoundary, + Patch, + QuickAccessTab, + afterPatch, + createReactTreePatcher, + findInReactTree, + findModuleScopeByVar, + getReactRoot, +} from '@decky/ui'; + +import { QuickAccessVisibleStateProvider } from '../components/QuickAccessVisibleState'; +import Logger from '../logger'; + +declare global { + interface Window { + __TABS_HOOK_INSTANCE: any; + } +} + +interface Tab { + id: QuickAccessTab | number; + title: any; + content: any; + icon: any; +} + +class TabsHook extends Logger { + // private keys = 7; + tabs: Tab[] = []; + private qamBrowserViewPatch?: Patch; + private qamEmbeddedPatch?: Patch; + + constructor() { + super('TabsHook'); + + this.log('Initialized'); + window.__TABS_HOOK_INSTANCE?.deinit?.(); + window.__TABS_HOOK_INSTANCE = this; + } + + init() { + const qamModule = findModuleScopeByVar((e) => e?.type?.toString?.()?.includes('QuickAccessMenuBrowserView')); + const qamBrowserViewRenderer = Object.values(qamModule).find((e: any) => + e?.type?.toString?.()?.includes('QuickAccessMenuBrowserView'), + ); + const qamEmbeddedRenderer = Object.values(qamModule).find((e: any) => + e?.type?.toString?.()?.includes('QuickAccessMenuEmbedded'), + ); + + const patchHandler = createReactTreePatcher( + [(tree) => findInReactTree(tree, (node) => node?.props?.onFocusNavDeactivated)], + (args, ret) => { + const tabs = findInReactTree(ret, (x) => x?.props?.tabs); + this.render(tabs.props.tabs, args[0].visible); + return ret; + }, + 'TabsHook', + ); + + this.qamBrowserViewPatch = afterPatch(qamBrowserViewRenderer, 'type', patchHandler); + if (qamEmbeddedRenderer) this.qamEmbeddedPatch = afterPatch(qamEmbeddedRenderer, 'type', patchHandler); + + // Patch already rendered qam + const root = getReactRoot(document.getElementById('root') as any); + const qamNode = + root && + findInReactTree( + root, + (n: any) => + n.elementType == qamBrowserViewRenderer || + (qamEmbeddedRenderer != null && n.elementType == qamEmbeddedRenderer), + ); // need elementType, because type is actually mobx wrapper + if (qamNode) { + // Only affects this fiber node so we don't need to unpatch here + qamNode.type = qamNode.elementType.type; + if (qamNode?.alternate) { + qamNode.alternate.type = qamNode.type; + } + } + } + + deinit() { + this.qamBrowserViewPatch?.unpatch(); + this.qamEmbeddedPatch?.unpatch(); + } + + add(tab: Tab) { + this.debug('Adding tab', tab.id, 'to render array'); + this.tabs.push(tab); + } + + removeById(id: number) { + this.debug('Removing tab', id); + this.tabs = this.tabs.filter((tab) => tab.id !== id); + } + + render(existingTabs: any[], visible: boolean) { + let deckyTabAmount = existingTabs.reduce((prev: any, cur: any) => (cur.decky ? prev + 1 : prev), 0); + if (deckyTabAmount == this.tabs.length) { + for (let tab of existingTabs) { + if (tab?.decky) { + if (tab?.qAMVisibilitySetter) { + tab?.qAMVisibilitySetter(visible); + } else { + tab.initialVisibility = visible; + } + } + } + return; + } + for (const { title, icon, content, id } of this.tabs) { + const tab: any = { + key: id, + title, + tab: icon, + decky: true, + initialVisibility: visible, + }; + tab.panel = ( + + {content} + + ); + existingTabs.push(tab); + } + } +} + +export default TabsHook; diff --git a/frontend/src/hooks/toaster.tsx b/frontend/src/hooks/toaster.tsx new file mode 100644 index 00000000..cc604d0f --- /dev/null +++ b/frontend/src/hooks/toaster.tsx @@ -0,0 +1,128 @@ +import type { ToastData, ToastNotification } from '@decky/api'; +import { + ESteamNotificationAction, + ErrorBoundary, + Patch, + callOriginal, + findVar, + injectFCTrampoline, + replacePatch, +} from '@decky/ui'; + +import Toast from '../components/Toast'; +import Logger from '../logger'; + +declare global { + interface Window { + __TOASTER_INSTANCE: any; + } +} + +class Toaster extends Logger { + private toastPatch?: Patch; + + constructor() { + super('Toaster'); + + window.__TOASTER_INSTANCE?.deinit?.(); + window.__TOASTER_INSTANCE = this; + + // TODO regex? + const ValveToastRenderer = findVar( + (e) => typeof e == 'function' && e?.toString?.()?.includes(`controller:\`notification\`,method:`), + ); + // TODO find a way to undo this if possible? + const patchedRenderer = injectFCTrampoline(ValveToastRenderer); + this.toastPatch = replacePatch(patchedRenderer, 'component', (args: any[]) => { + if (args?.[0]?.group?.decky || args?.[0]?.group?.notifications?.[0]?.decky) { + return args[0].group.notifications.map((notification: any) => ( + + + + )); + } + return callOriginal; + }); + + this.log('Initialized'); + } + + toast(toast: ToastData): ToastNotification { + if (toast.sound === undefined) toast.sound = 6; + if (toast.playSound === undefined) toast.playSound = true; + if (toast.showToast === undefined) toast.showToast = true; + if (toast.timestamp === undefined) toast.timestamp = new Date(); + if (toast.showNewIndicator === undefined) toast.showNewIndicator = true; + /* eType 13 + 13: { + proto: m.mu, + fnTray: null, + showToast: !0, + sound: f.PN.ToastMisc, + eFeature: l.uX + } + */ + let toastData = { + nNotificationID: window.NotificationStore.m_nNextTestNotificationID++, + bNewIndicator: toast.showNewIndicator, + rtCreated: Date.now(), + eType: toast.eType || 31, + eSource: 1, // Client + nToastDurationMS: toast.duration || (toast.duration = 5e3), + data: toast, + decky: true, + }; + let group: any; + function fnTray(toast: any, tray: any) { + group = { + eType: toast.eType, + notifications: [toast], + }; + tray.unshift(group); + } + const info = { + showToast: toast.showToast, + sound: toast.sound, + playSound: toast.playSound, + eFeature: 0, + toastDurationMS: toastData.nToastDurationMS, + bCritical: toast.critical, + fnTray, + }; + const self = this; + let expirationTimeout: number; + const toastResult: ToastNotification = { + data: toast, + dismiss() { + // it checks against the id of notifications[0] + try { + expirationTimeout && clearTimeout(expirationTimeout); + group && window.NotificationStore.RemoveGroupFromTray(group); + } catch (e) { + self.error('Error while dismissing toast:', e); + } + }, + }; + if (toast.expiration) { + expirationTimeout = setTimeout(() => { + try { + group && window.NotificationStore.RemoveGroupFromTray(group); + } catch (e) { + this.error('Error while dismissing expired toast:', e); + } + }, toast.expiration); + } + try { + window.NotificationStore.ProcessNotification(info, toastData, ESteamNotificationAction.New); + } catch (e) { + this.error('Error while sending toast:', e); + } + return toastResult; + } + + deinit() { + this.toastPatch?.unpatch(); + } +} + +export default Toaster; diff --git a/frontend/src/hooks/vr-dashboard-bar.tsx b/frontend/src/hooks/vr-dashboard-bar.tsx new file mode 100644 index 00000000..3fe1ad73 --- /dev/null +++ b/frontend/src/hooks/vr-dashboard-bar.tsx @@ -0,0 +1,106 @@ +// Hook the SteamVR Hotbar +import { ErrorBoundary, Patch, afterPatch, findInReactTree, findVar, getReactRoot } from '@decky/ui'; +import { ReactNode, createElement } from 'react'; + +import Logger from '../logger'; + +declare global { + interface Window { + __VR_DASHBAORD_BAR_HOOK_INSTANCE: any; + } +} + +// TODO kinda dumb +enum VRDashboardBarButtonID { + Decky = 999, +} + +export interface VRDashboardBarButton { + id: VRDashboardBarButtonID | number; + active?: boolean; + children?: ReactNode; + tooltip?: ReactNode; + popupContents?: ReactNode; + onActivate?: () => void; + refBarPopupHandle?: any; // TODO idk + onPopupVisibilityChanged?: (visible: boolean) => void; +} + +class VRDashboardBarHook extends Logger { + rightSideButtons: VRDashboardBarButton[] = []; + private rendererdRightSideButtons: ReactNode[] = []; + private barPatch?: Patch; + private barButton?: any; + + constructor() { + super('VRDashboardBarHook'); + + this.log('Initialized'); + window.__VR_DASHBAORD_BAR_HOOK_INSTANCE?.deinit?.(); + window.__VR_DASHBAORD_BAR_HOOK_INSTANCE = this; + } + + init() { + this.barButton = findVar((e) => e?.render?.toString()?.includes('VRDashboardBarSmallButtonActive')); + const barComponent = findVar((e) => e?.type?.toString()?.includes('vrLocation==`dashboard-bar`')); + + this.barPatch = afterPatch(barComponent, 'type', (_, ret) => { + const nodes = findInReactTree(ret, (x) => x?.length > 6); + if (!window?.securitystore?.IsLockScreenActive?.()) nodes.splice(4, 0, this.rendererdRightSideButtons); + return ret; + }); + + // Patch already rendered bar + // THIS DOES NOT WORK so frame needs a lockscreen for now :/ + const root = getReactRoot(document.getElementById('root') as any); + const barNode = + root && + findInReactTree( + root, + (n: any) => n.elementType == barComponent || (barComponent != null && n.elementType == barComponent), + ); // need elementType, because case where type is actually mobx wrapper + if (barNode) { + // Only affects this fiber node so we don't need to unpatch here + barNode.type = barNode.elementType.type; + if (barNode?.alternate) { + barNode.alternate.type = barNode.type; + } + } + } + + deinit() { + this.barPatch?.unpatch(); + } + + addRightSideButton(button: VRDashboardBarButton) { + this.debug('Adding RSB', button.id, 'to render array'); + this.rightSideButtons.push(button); + this.renderRightSideButtons(); + } + + removeRightSideButton(id: number) { + this.debug('Removing RSB', id); + this.rightSideButtons = this.rightSideButtons.filter((button) => button.id !== id); + this.renderRightSideButtons(); + } + + renderRightSideButtons() { + const arr = []; + for (const button of this.rightSideButtons) { + arr.push( + createElement(this.barButton, { + active: button.active, + children: {button.children}, + tooltip: button.tooltip, + popupContents: {button.popupContents}, + onActivate: button.onActivate, + refBarPopupHandle: button.refBarPopupHandle, + onPopupVisibilityChanged: button.onPopupVisibilityChanged, + }), + ); + } + this.rendererdRightSideButtons = arr; + } +} + +export default VRDashboardBarHook; diff --git a/frontend/src/index.ts b/frontend/src/index.ts index 67b30d15..f21c4802 100644 --- a/frontend/src/index.ts +++ b/frontend/src/index.ts @@ -1,5 +1,12 @@ // Sets up DFL, then loads start.ts which starts up the loader +interface Window { + _deckyModuleResolverInternals: { + scopes: Map>; + scopedObjects: Map; + }; +} + interface SteamAppInitialization { BFinishedInitBeforeLogin?: () => boolean; BFinishedInitStageOne?: () => boolean; @@ -13,42 +20,65 @@ const isSteamAppInitialized = () => { (async () => { console.debug('[Decky:Boot] Frontend init'); + console.debug('[Decky:Boot] Authenticating with Decky backend...'); + window.deckyAuthToken = await fetch('http://127.0.0.1:1337/auth/token').then((r) => r.text()); + console.debug('[Decky:Boot] Connecting to Decky backend...'); + const ws = (window.DeckyBackend = new (await import('./wsrouter')).WSRouter()); + await ws.connect(); + console.time('[Decky:Boot] Waiting for SteamApp init stage 1 to finish...'); while (!isSteamAppInitialized()) { await new Promise((r) => setTimeout(r, 0)); // Can't use DFL sleep here. } - console.timeEnd('[Decky:Boot] Waiting for SteamApp init stage 1 to finish...'); - - if (!window.SP_REACT) { - console.debug('[Decky:Boot] Setting up Webpack & React globals...'); - // deliberate partial import - const DFLWebpack = await import('@decky/ui/dist/webpack'); - window.SP_REACT = DFLWebpack.findModule((m) => m.Component && m.PureComponent && m.useLayoutEffect); - window.SP_REACTDOM = - DFLWebpack.findModule((m) => m.createPortal && m.createRoot) || - DFLWebpack.findModule((m) => m.createPortal && m.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE); - - console.debug('[Decky:Boot] Setting up JSX internals...'); - const jsxModule = DFLWebpack.findModule((m) => (m.jsx && m.jsxs) || (m.jsx && Object.keys(m).length == 1)); - if (jsxModule.jsxs) { - window.SP_JSX = jsxModule; - } else { - window.SP_JSX = { - jsx: jsxModule.jsx, - jsxs: jsxModule.jsx, - Fragment: window.SP_REACT.Fragment, - }; + console.debug('[Decky:Boot] Setting up Module System & React globals...'); + + let moduleId = 0; + const int = (window._deckyModuleResolverInternals = { + scopes: new Map(), + scopedObjects: new Map(), + }); + const resolveThroughBackend = ws.callable<[objectKey: number]>('instrumentation/resolve_scope'); + async function resolveModuleScope(objectFromScope: any, moduleForDebug?: string) { + let ret; + const id = ++moduleId; + try { + int.scopedObjects.set(id, objectFromScope); + await resolveThroughBackend(id); + ret = int.scopes.get(id); + } catch (e) { + console.debug(`[Decky:Instrumentation] Scope resolution failed for module ${moduleForDebug}`, e); + } finally { + int.scopes.delete(id); + int.scopedObjects.delete(id); } + return ret; + } + + // deliberate partial import + const DFLModules = await import('@decky/ui/dist/module-system'); + await DFLModules.initModules(resolveModuleScope); + // @ts-ignore + window.DFLModules = DFLModules; + window.SP_REACT = DFLModules.findModule((m) => m.Component && m.PureComponent && m.useLayoutEffect); + window.SP_REACTDOM = + DFLModules.findModule((m) => m.createPortal && m.createRoot) || + DFLModules.findModule((m) => m.createPortal && m.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE); + + console.debug('[Decky:Boot] Setting up JSX internals...'); + const jsxModule = DFLModules.findModule((m) => (m.jsx && m.jsxs) || (m.jsx && Object.keys(m).length == 1)); + if (jsxModule?.jsxs) { + window.SP_JSX = jsxModule; + } else { + window.SP_JSX = { + jsx: jsxModule.jsx, + jsxs: jsxModule.jsx, + Fragment: window.SP_REACT.Fragment, + }; } console.debug('[Decky:Boot] Setting up @decky/ui...'); window.DFL = await import('@decky/ui'); - console.debug('[Decky:Boot] Authenticating with Decky backend...'); - window.deckyAuthToken = await fetch('http://127.0.0.1:1337/auth/token').then((r) => r.text()); - console.debug('[Decky:Boot] Connecting to Decky backend...'); - window.DeckyBackend = new (await import('./wsrouter')).WSRouter(); - await DeckyBackend.connect(); console.debug('[Decky:Boot] Starting Decky!'); await import('./start'); })(); diff --git a/frontend/src/plugin-loader.tsx b/frontend/src/plugin-loader.tsx index 81b96dcc..b16e1bb1 100644 --- a/frontend/src/plugin-loader.tsx +++ b/frontend/src/plugin-loader.tsx @@ -7,9 +7,11 @@ import { PanelSectionRow, QuickAccessTab, findSP, + joinClassNames, quickAccessMenuClasses, showModal, sleep, + vrDashboardClasses, } from '@decky/ui'; import { FC, lazy } from 'react'; import { FaDownload, FaExclamationCircle, FaExclamationTriangle, FaPlug } from 'react-icons/fa'; @@ -24,19 +26,20 @@ import PluginInstallModal from './components/modals/PluginInstallModal'; import PluginUninstallModal from './components/modals/PluginUninstallModal'; import NotificationBadge from './components/NotificationBadge'; import PluginView from './components/PluginView'; -import { useQuickAccessVisible } from './components/QuickAccessVisibleState'; +import { QuickAccessVisibleStateProvider, useQuickAccessVisible } from './components/QuickAccessVisibleState'; import WithSuspense from './components/WithSuspense'; import ErrorBoundaryHook from './errorboundary-hook'; import { FrozenPluginService } from './frozen-plugins-service'; import { HiddenPluginsService } from './hidden-plugins-service'; +import RouterHook from './hooks/router'; +import TabsHook from './hooks/tabs'; +import Toaster from './hooks/toaster'; +import VRDashboardBarHook from './hooks/vr-dashboard-bar'; import Logger from './logger'; import { NotificationService } from './notification-service'; import { DisabledPlugin, InstallType, Plugin, PluginLoadType } from './plugin'; -import RouterHook from './router-hook'; import { deinitSteamFixes, initSteamFixes } from './steamfixes'; import { PluginUpdateMapping, checkForPluginUpdates } from './store'; -import TabsHook from './tabs-hook'; -import Toaster from './toaster'; import { getVersionInfo } from './updater'; import { getPluginDisplayName } from './utils/pluginHelpers'; import { getSetting, setSetting } from './utils/settings'; @@ -70,6 +73,7 @@ class PluginLoader extends Logger { private plugins: Plugin[] = []; public errorBoundaryHook: ErrorBoundaryHook = new ErrorBoundaryHook(); private tabsHook: TabsHook = new TabsHook(); + private vrDashboardBarHook: VRDashboardBarHook = new VRDashboardBarHook(); // TODO public? unsure public routerHook: RouterHook = new RouterHook(); public toaster: Toaster = new Toaster(); private deckyState: DeckyState = new DeckyState(); @@ -105,10 +109,11 @@ class PluginLoader extends Logger { DeckyBackend.addEventListener(`loader/plugin_event`, this.pluginEventListener); this.tabsHook.init(); + this.vrDashboardBarHook.init(); - const TabBadge = () => { + const TabBadge = ({ vr }: { vr?: boolean }) => { const { updates, hasLoaderUpdate } = useDeckyState(); - return 0) || hasLoaderUpdate} />; + return 0) || hasLoaderUpdate} />; }; this.tabsHook.add({ @@ -127,6 +132,44 @@ class PluginLoader extends Logger { ), }); + this.vrDashboardBarHook.addRightSideButton({ + id: 999, + tooltip: 'Decky', + popupContents: ( + + {' '} + {/*for compat only, these don't render when inactive*/} + +
+ +
+
+
+ ), + children: ( + +
+ + + +
+
+ ), + }); + this.routerHook.addRoute('/decky/store', () => ( @@ -399,6 +442,7 @@ class PluginLoader extends Logger { deinitFilepickerPatches(); this.routerHook.deinit(); this.tabsHook.deinit(); + this.vrDashboardBarHook.deinit(); this.toaster.deinit(); this.errorBoundaryHook.deinit(); } @@ -554,7 +598,7 @@ class PluginLoader extends Logger { -
+
[] = []; - private Route: any; - private DeckyGamepadRouterWrapper = this.gamepadRouterWrapper.bind(this); - private DeckyDesktopRouterWrapper = this.desktopRouterWrapper.bind(this); - private DeckyGlobalComponentsWrapper = this.globalComponentsWrapper.bind(this); - private toReplace = new Map(); - private desktopRouterPatch?: Patch; - private gamepadRouterPatch?: Patch; - private modeChangeRegistration?: any; - private patchedModes = new Set(); - public routes?: any[]; - - constructor() { - super('RouterHook'); - - this.log('Initialized'); - window.__ROUTER_HOOK_INSTANCE?.deinit?.(); - window.__ROUTER_HOOK_INSTANCE = this; - - const reactRouterStackModule = findModuleByExport((e) => typeof e == 'string' && e == 'router-backstack', 20); - if (reactRouterStackModule) { - this.Route = - Object.values(reactRouterStackModule).find( - (e) => typeof e == 'function' && /routePath:[\w$]+\.match\?\.path./.test(e.toString()), - ) || - Object.values(reactRouterStackModule).find( - (e) => typeof e == 'function' && /routePath:null===\(.=.\.match\)/.test(e.toString()), - ); - if (!this.Route) { - this.error('Failed to find Route component'); - } - } else { - this.error('Failed to find router stack module'); - } - - this.modeChangeRegistration = SteamClient.UI.RegisterForUIModeChanged((mode: EUIMode) => { - this.debug(`UI mode changed to ${mode}`); - if (this.patchedModes.has(mode)) return; - this.patchedModes.add(mode); - this.debug(`Patching router for UI mode ${mode}`); - switch (mode) { - case EUIMode.GamePad: - this.debug('Patching gamepad router'); - this.patchGamepadRouter(); - break; - // Not fully implemented yet - // case UIMode.Desktop: - // this.debug("Patching desktop router"); - // this.patchDesktopRouter(); - // break; - default: - this.warn(`Router patch not implemented for UI mode ${mode}`); - break; - } - }); - } - - private async patchGamepadRouter() { - const root = getReactRoot(document.getElementById('root') as any); - const findRouterNode = () => - findInReactTree( - root, - (node) => - typeof node?.pendingProps?.loggedIn == 'undefined' && node?.type?.toString().includes('Settings.Root()'), - ); - await this.waitForUnlock(); - let routerNode = findRouterNode(); - while (!routerNode) { - this.warn('Failed to find Router node, reattempting in 5 seconds.'); - await sleep(5000); - await this.waitForUnlock(); - routerNode = findRouterNode(); - } - if (routerNode) { - // Patch the component globally - this.gamepadRouterPatch = afterPatch(routerNode.elementType, 'type', this.handleGamepadRouterRender.bind(this)); - // Swap out the current instance - routerNode.type = routerNode.elementType.type; - if (routerNode?.alternate) { - routerNode.alternate.type = routerNode.type; - } - // Force a full rerender via our custom error boundary - const errorBoundaryNode = findInTree(routerNode, (e) => e?.stateNode?._deckyForceRerender, { - walkable: ['return'], - }); - errorBoundaryNode?.stateNode?._deckyForceRerender?.(); - } - } - - // Currently unused - // @ts-expect-error 6133 - private async patchDesktopRouter() { - const root = getReactRoot(document.getElementById('root') as any); - const findRouterNode = () => - findInReactTree(root, (node) => node?.elementType?.type?.toString?.()?.includes('bShowDesktopUIContent:')); - let routerNode = findRouterNode(); - while (!routerNode) { - this.warn('Failed to find Router node, reattempting in 5 seconds.'); - await sleep(5000); - routerNode = findRouterNode(); - } - if (routerNode) { - // this.debug("desktop router node", routerNode); - // Patch the component globally - this.desktopRouterPatch = afterPatch(routerNode.elementType, 'type', this.handleDesktopRouterRender.bind(this)); - // Swap out the current instance - routerNode.type = routerNode.elementType.type; - if (routerNode?.alternate) { - routerNode.alternate.type = routerNode.type; - } - // Force a full rerender via our custom error boundary - const errorBoundaryNode = findInTree(routerNode, (e) => e?.stateNode?._deckyForceRerender, { - walkable: ['return'], - }); - errorBoundaryNode?.stateNode?._deckyForceRerender?.(); - // this.debug("desktop router node", routerNode); - // // Patch the component globally - // this.desktopRouterPatch = afterPatch(routerNode.type.prototype, 'render', this.handleDesktopRouterRender.bind(this)); - // const stateNodeClone = { render: routerNode.stateNode.render } as any; - // // Patch the current instance. render is readonly so we have to do this. - // Object.assign(stateNodeClone, routerNode.stateNode); - // Object.setPrototypeOf(stateNodeClone, Object.getPrototypeOf(routerNode.stateNode)); - // this.desktopRouterFirstInstancePatch = afterPatch(stateNodeClone, 'render', this.handleDesktopRouterRender.bind(this)); - // routerNode.stateNode = stateNodeClone; - // // Swap out the current instance - // if (routerNode?.alternate) { - // routerNode.alternate.type = routerNode.type; - // routerNode.alternate.stateNode = routerNode.stateNode; - // } - // routerNode.stateNode.forceUpdate(); - // Force a full rerender via our custom error boundary - // const errorBoundaryNode = findInTree(routerNode, e => e?.stateNode?._deckyForceRerender, { walkable: ["return"] }); - // errorBoundaryNode?.stateNode?._deckyForceRerender?.(); - } - } - - public async waitForUnlock() { - try { - while (window?.securitystore?.IsLockScreenActive?.()) { - await sleep(500); - } - } catch (e) { - this.warn('Error while checking if unlocked:', e); - } - } - - public handleDesktopRouterRender(_: any, ret: any) { - const DeckyDesktopRouterWrapper = this.DeckyDesktopRouterWrapper; - const DeckyGlobalComponentsWrapper = this.DeckyGlobalComponentsWrapper; - this.debug('desktop router render', ret); - if (ret._decky) { - return ret; - } - const returnVal = ( - <> - - {ret} - - - - - - ); - (returnVal as any)._decky = true; - return returnVal; - } - - public handleGamepadRouterRender(_: any, ret: any) { - const DeckyGamepadRouterWrapper = this.DeckyGamepadRouterWrapper; - const DeckyGlobalComponentsWrapper = this.DeckyGlobalComponentsWrapper; - if (ret._decky) { - return ret; - } - const returnVal = ( - <> - - {ret} - - - - - - ); - (returnVal as any)._decky = true; - return returnVal; - } - - private globalComponentsWrapper() { - const { components } = useDeckyGlobalComponentsState(); - if (this.renderedComponents.length != components.size) { - this.debug('Rerendering global components'); - this.renderedComponents = Array.from(components.values()).map((GComponent) => ); - } - return <>{this.renderedComponents}; - } - - private gamepadRouterWrapper({ children }: { children: ReactElement }) { - // Used to store the new replicated routes we create to allow routes to be unpatched. - - const { routes, routePatches } = useDeckyRouterState(); - // TODO make more redundant - if (!children?.props?.children?.[0]?.props?.children) { - this.debug('routerWrapper wrong component?', children); - return children; - } - const mainRouteList = children.props.children[0].props.children; - const ingameRouteList = children.props.children[1].props.children; // /appoverlay and /apprunning - this.processList(mainRouteList, routes, routePatches, true); - this.processList(ingameRouteList, null, routePatches, false); - - this.debug('Rerendered gamepadui routes list'); - return children; - } - - private desktopRouterWrapper({ children }: { children: ReactElement }) { - // Used to store the new replicated routes we create to allow routes to be unpatched. - this.debug('desktop router wrapper render', children); - const { routes, routePatches } = useDeckyRouterState(); - const routeList = findInReactTree( - children, - (node) => node?.length > 2 && node?.find((elem: any) => elem?.props?.path == '/library/home'), - ); - if (!routeList) { - this.debug('routerWrapper wrong component?', children); - return children; - } - const library = children.props.children[1].props.children.props; - if (!Array.isArray(library.children)) { - library.children = [library.children]; - } - this.debug('library', library); - this.processList(library.children, routes, routePatches, true); - - this.debug('Rerendered desktop routes list'); - return children; - } - - private processList( - routeList: any[], - routes: Map | null, - routePatches: Map>, - save: boolean, - ) { - const Route = this.Route; - this.debug('Route list: ', routeList); - if (save) this.routes = routeList; - let routerIndex = routeList.length; - if (routes) { - if (!routeList[routerIndex - 1]?.length || routeList[routerIndex - 1]?.length !== routes.size) { - if (routeList[routerIndex - 1]?.length && routeList[routerIndex - 1].length !== routes.size) routerIndex--; - const newRouterArray: (ReactElement | JSX.Element)[] = []; - routes.forEach(({ component, props }, path) => { - newRouterArray.push( - - {createElement(component)} - , - ); - }); - routeList[routerIndex] = newRouterArray; - } - } - routeList.forEach((route: Route, index: number) => { - const replaced = this.toReplace.get(route?.props?.path as string); - if (replaced) { - routeList[index].props.children = replaced; - this.toReplace.delete(route?.props?.path as string); - } - if (route?.props?.path && routePatches.has(route.props.path as string)) { - this.toReplace.set( - route?.props?.path as string, - // @ts-ignore - routeList[index].props.children, - ); - routePatches.get(route.props.path as string)?.forEach((patch) => { - const oType = routeList[index].props.children.type; - routeList[index].props.children = patch({ - ...routeList[index].props, - children: { - ...cloneElement(routeList[index].props.children), - type: routeList[index].props.children[isPatched] ? oType : (props) => createElement(oType, props), - }, - }).children; - routeList[index].props.children[isPatched] = true; - }); - } - }); - } - - addRoute(path: string, component: RouterEntry['component'], props: RouterEntry['props'] = {}) { - this.routerState.addRoute(path, component, props); - } - - addPatch(path: string, patch: RoutePatch) { - return this.routerState.addPatch(path, patch); - } - - addGlobalComponent(name: string, component: FC) { - this.globalComponentsState.addComponent(name, component); - } - - removeGlobalComponent(name: string) { - this.globalComponentsState.removeComponent(name); - } - - removePatch(path: string, patch: RoutePatch) { - this.routerState.removePatch(path, patch); - } - - removeRoute(path: string) { - this.routerState.removeRoute(path); - } - - deinit() { - this.modeChangeRegistration?.unregister(); - this.gamepadRouterPatch?.unpatch(); - this.desktopRouterPatch?.unpatch(); - } -} - -export default RouterHook; diff --git a/frontend/src/tabs-hook.tsx b/frontend/src/tabs-hook.tsx deleted file mode 100644 index ecb60f30..00000000 --- a/frontend/src/tabs-hook.tsx +++ /dev/null @@ -1,131 +0,0 @@ -// TabsHook for versions after the Desktop merge -import { - ErrorBoundary, - Patch, - QuickAccessTab, - afterPatch, - createReactTreePatcher, - findInReactTree, - findModuleByExport, - getReactRoot, -} from '@decky/ui'; - -import { QuickAccessVisibleStateProvider } from './components/QuickAccessVisibleState'; -import Logger from './logger'; - -declare global { - interface Window { - __TABS_HOOK_INSTANCE: any; - } -} - -interface Tab { - id: QuickAccessTab | number; - title: any; - content: any; - icon: any; -} - -class TabsHook extends Logger { - // private keys = 7; - tabs: Tab[] = []; - private qamBrowserViewPatch?: Patch; - private qamEmbeddedPatch?: Patch; - - constructor() { - super('TabsHook'); - - this.log('Initialized'); - window.__TABS_HOOK_INSTANCE?.deinit?.(); - window.__TABS_HOOK_INSTANCE = this; - } - - init() { - const qamModule = findModuleByExport((e) => e?.type?.toString?.()?.includes('QuickAccessMenuBrowserView')); - const qamBrowserViewRenderer = Object.values(qamModule).find((e: any) => - e?.type?.toString?.()?.includes('QuickAccessMenuBrowserView'), - ); - const qamEmbeddedRenderer = Object.values(qamModule).find((e: any) => - e?.type?.toString?.()?.includes('QuickAccessMenuEmbedded'), - ); - - const patchHandler = createReactTreePatcher( - [(tree) => findInReactTree(tree, (node) => node?.props?.onFocusNavDeactivated)], - (args, ret) => { - const tabs = findInReactTree(ret, (x) => x?.props?.tabs); - this.render(tabs.props.tabs, args[0].visible); - return ret; - }, - 'TabsHook', - ); - - this.qamBrowserViewPatch = afterPatch(qamBrowserViewRenderer, 'type', patchHandler); - if (qamEmbeddedRenderer) this.qamEmbeddedPatch = afterPatch(qamEmbeddedRenderer, 'type', patchHandler); - - // Patch already rendered qam - const root = getReactRoot(document.getElementById('root') as any); - const qamNode = - root && - findInReactTree( - root, - (n: any) => - n.elementType == qamBrowserViewRenderer || - (qamEmbeddedRenderer != null && n.elementType == qamEmbeddedRenderer), - ); // need elementType, because type is actually mobx wrapper - if (qamNode) { - // Only affects this fiber node so we don't need to unpatch here - qamNode.type = qamNode.elementType.type; - if (qamNode?.alternate) { - qamNode.alternate.type = qamNode.type; - } - } - } - - deinit() { - this.qamBrowserViewPatch?.unpatch(); - this.qamEmbeddedPatch?.unpatch(); - } - - add(tab: Tab) { - this.debug('Adding tab', tab.id, 'to render array'); - this.tabs.push(tab); - } - - removeById(id: number) { - this.debug('Removing tab', id); - this.tabs = this.tabs.filter((tab) => tab.id !== id); - } - - render(existingTabs: any[], visible: boolean) { - let deckyTabAmount = existingTabs.reduce((prev: any, cur: any) => (cur.decky ? prev + 1 : prev), 0); - if (deckyTabAmount == this.tabs.length) { - for (let tab of existingTabs) { - if (tab?.decky) { - if (tab?.qAMVisibilitySetter) { - tab?.qAMVisibilitySetter(visible); - } else { - tab.initialVisibility = visible; - } - } - } - return; - } - for (const { title, icon, content, id } of this.tabs) { - const tab: any = { - key: id, - title, - tab: icon, - decky: true, - initialVisibility: visible, - }; - tab.panel = ( - - {content} - - ); - existingTabs.push(tab); - } - } -} - -export default TabsHook; diff --git a/frontend/src/toaster.tsx b/frontend/src/toaster.tsx deleted file mode 100644 index e5b2d986..00000000 --- a/frontend/src/toaster.tsx +++ /dev/null @@ -1,125 +0,0 @@ -import type { ToastData, ToastNotification } from '@decky/api'; -import { - ESteamNotificationAction, - ErrorBoundary, - Patch, - callOriginal, - findModuleExport, - injectFCTrampoline, - replacePatch, -} from '@decky/ui'; - -import Toast from './components/Toast'; -import Logger from './logger'; - -declare global { - interface Window { - __TOASTER_INSTANCE: any; - } -} - -class Toaster extends Logger { - private toastPatch?: Patch; - - constructor() { - super('Toaster'); - - window.__TOASTER_INSTANCE?.deinit?.(); - window.__TOASTER_INSTANCE = this; - - const ValveToastRenderer = findModuleExport((e) => e?.toString?.()?.includes(`controller:"notification",method:`)); - // TODO find a way to undo this if possible? - const patchedRenderer = injectFCTrampoline(ValveToastRenderer); - this.toastPatch = replacePatch(patchedRenderer, 'component', (args: any[]) => { - if (args?.[0]?.group?.decky || args?.[0]?.group?.notifications?.[0]?.decky) { - return args[0].group.notifications.map((notification: any) => ( - - - - )); - } - return callOriginal; - }); - - this.log('Initialized'); - } - - toast(toast: ToastData): ToastNotification { - if (toast.sound === undefined) toast.sound = 6; - if (toast.playSound === undefined) toast.playSound = true; - if (toast.showToast === undefined) toast.showToast = true; - if (toast.timestamp === undefined) toast.timestamp = new Date(); - if (toast.showNewIndicator === undefined) toast.showNewIndicator = true; - /* eType 13 - 13: { - proto: m.mu, - fnTray: null, - showToast: !0, - sound: f.PN.ToastMisc, - eFeature: l.uX - } - */ - let toastData = { - nNotificationID: window.NotificationStore.m_nNextTestNotificationID++, - bNewIndicator: toast.showNewIndicator, - rtCreated: Date.now(), - eType: toast.eType || 31, - eSource: 1, // Client - nToastDurationMS: toast.duration || (toast.duration = 5e3), - data: toast, - decky: true, - }; - let group: any; - function fnTray(toast: any, tray: any) { - group = { - eType: toast.eType, - notifications: [toast], - }; - tray.unshift(group); - } - const info = { - showToast: toast.showToast, - sound: toast.sound, - playSound: toast.playSound, - eFeature: 0, - toastDurationMS: toastData.nToastDurationMS, - bCritical: toast.critical, - fnTray, - }; - const self = this; - let expirationTimeout: number; - const toastResult: ToastNotification = { - data: toast, - dismiss() { - // it checks against the id of notifications[0] - try { - expirationTimeout && clearTimeout(expirationTimeout); - group && window.NotificationStore.RemoveGroupFromTray(group); - } catch (e) { - self.error('Error while dismissing toast:', e); - } - }, - }; - if (toast.expiration) { - expirationTimeout = setTimeout(() => { - try { - group && window.NotificationStore.RemoveGroupFromTray(group); - } catch (e) { - this.error('Error while dismissing expired toast:', e); - } - }, toast.expiration); - } - try { - window.NotificationStore.ProcessNotification(info, toastData, ESteamNotificationAction.New); - } catch (e) { - this.error('Error while sending toast:', e); - } - return toastResult; - } - - deinit() { - this.toastPatch?.unpatch(); - } -} - -export default Toaster; diff --git a/frontend/src/updater.ts b/frontend/src/updater.ts index c4b9034f..ba81ffb8 100644 --- a/frontend/src/updater.ts +++ b/frontend/src/updater.ts @@ -20,6 +20,7 @@ export interface VerInfo { current: string; repo: string; gitBranch: string; + gitPR: string | null; remote: RemoteVerInfo | null; all: RemoteVerInfo[] | null; updatable: boolean; -- cgit v1.2.3