summaryrefslogtreecommitdiff
path: root/frontend/src/menu-hook.tsx
blob: 5a3ffde54be5d9e653db78d01505535797b73779 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import {
  CustomMainMenuItem,
  ItemPatch,
  MainMenuItem,
  OverlayPatch,
  afterPatch,
  findInReactTree,
  sleep,
} from 'decky-frontend-lib';
import { FC } from 'react';
import { ReactNode, cloneElement, createElement } from 'react';

import { DeckyMenuState, DeckyMenuStateContextProvider, useDeckyMenuState } from './components/DeckyMenuState';
import Logger from './logger';

declare global {
  interface Window {
    __MENU_HOOK_INSTANCE: any;
  }
}

class MenuHook extends Logger {
  private menuRenderer?: any;
  private originalRenderer?: any;
  private menuState: DeckyMenuState = new DeckyMenuState();

  constructor() {
    super('MenuHook');

    this.log('Initialized');
    window.__MENU_HOOK_INSTANCE?.deinit?.();
    window.__MENU_HOOK_INSTANCE = this;
  }

  init() {
    const tree = (document.getElementById('root') as any)._reactRootContainer._internalRoot.current;
    let outerMenuRoot: any;
    const findMenuRoot = (currentNode: any, iters: number): any => {
      if (iters >= 60) {
        // currently 54
        return null;
      }
      if (currentNode?.memoizedProps?.navID == 'MainNavMenuContainer') {
        this.log(`Menu root was found in ${iters} recursion cycles`);
        return currentNode;
      }
      if (currentNode.child) {
        let node = findMenuRoot(currentNode.child, iters + 1);
        if (node !== null) return node;
      }
      if (currentNode.sibling) {
        let node = findMenuRoot(currentNode.sibling, iters + 1);
        if (node !== null) return node;
      }
      return null;
    };

    (async () => {
      outerMenuRoot = findMenuRoot(tree, 0);
      while (!outerMenuRoot) {
        this.error(
          'Failed to find Menu root node, reattempting in 5 seconds. A developer may need to increase the recursion limit.',
        );
        await sleep(5000);
        outerMenuRoot = findMenuRoot(tree, 0);
      }
      this.log('found outermenuroot', outerMenuRoot);
      const menuRenderer = outerMenuRoot.return;
      this.menuRenderer = menuRenderer;
      this.originalRenderer = menuRenderer.type;
      let toReplace = new Map<string, ReactNode>();

      let patchedInnerMenu: any;
      let overlayComponentManager: any;

      const DeckyOverlayComponentManager = () => {
        const { overlayComponents } = useDeckyMenuState();

        return <>{overlayComponents.values()}</>;
      };

      const DeckyInnerMenuWrapper = (props: { innerProps: any }) => {
        const { overlayPatches } = useDeckyMenuState();

        const rendererRet = this.originalRenderer(props.innerProps);

        // Find the first array of children, this contains [mainmenu, overlay]
        const childArray = findInReactTree(rendererRet, (x) => x?.[0]?.type);

        // Insert the overlay components manager
        if (!overlayComponentManager) {
          overlayComponentManager = <DeckyOverlayComponentManager />;
        }

        childArray.push(overlayComponentManager);

        // This must be cached in patchedInnerMenu to prevent re-renders
        if (patchedInnerMenu) {
          childArray[0].type = patchedInnerMenu;
        } else {
          afterPatch(childArray[0], 'type', (_, ret) => {
            const { itemPatches, items } = useDeckyMenuState();

            const itemList = ret.props.children;

            // Add custom menu items
            if (items.size > 0) {
              const button = findInReactTree(ret.props.children, (x) =>
                x?.type?.toString()?.includes('exactRouteMatch:'),
              );

              const MenuItemComponent: FC<MainMenuItem> = button.type;

              items.forEach((item) => {
                let realIndex = 0; // there are some non-item things in the array
                let count = 0;
                itemList.forEach((i: any) => {
                  if (count == item.index) return;
                  if (i?.type == MenuItemComponent) count++;
                  realIndex++;
                });
                itemList.splice(realIndex, 0, createElement(MenuItemComponent, item));
              });
            }

            // Apply and revert patches
            itemList.forEach((item: { props: MainMenuItem }, index: number) => {
              if (!item?.props?.route) return;
              const replaced = toReplace.get(item?.props?.route as string);
              if (replaced) {
                itemList[index] = replaced;
                toReplace.delete(item?.props.route as string);
              }
              if (item?.props?.route && itemPatches.has(item.props.route as string)) {
                toReplace.set(item?.props?.route as string, itemList[index]);
                itemPatches.get(item.props.route as string)?.forEach((patch) => {
                  const oType = itemList[index].type;
                  itemList[index] = patch({
                    ...cloneElement(itemList[index]),
                    type: (props) => createElement(oType, props),
                  });
                });
              }
            });

            return ret;
          });
          patchedInnerMenu = childArray[0].type;
        }

        // Apply patches to the overlay
        if (childArray[1]) {
          overlayPatches.forEach((patch) => (childArray[1] = patch(childArray[1])));
        }

        return rendererRet;
      };

      const DeckyOuterMenuWrapper = (props: any) => {
        return (
          <DeckyMenuStateContextProvider deckyMenuState={this.menuState}>
            <DeckyInnerMenuWrapper innerProps={props} />
          </DeckyMenuStateContextProvider>
        );
      };
      menuRenderer.type = DeckyOuterMenuWrapper;
      if (menuRenderer.alternate) {
        menuRenderer.alternate.type = menuRenderer.type;
      }
      this.log('Finished initial injection');
    })();
  }

  deinit() {
    this.menuRenderer.type = this.originalRenderer;
    this.menuRenderer.alternate.type = this.menuRenderer.type;
  }

  addItem(item: CustomMainMenuItem) {
    return this.menuState.addItem(item);
  }

  addPatch(path: string, patch: ItemPatch) {
    return this.menuState.addPatch(path, patch);
  }

  addOverlayPatch(patch: OverlayPatch) {
    return this.menuState.addOverlayPatch(patch);
  }

  addOverlayComponent(component: ReactNode) {
    return this.menuState.addOverlayComponent(component);
  }

  removePatch(path: string, patch: ItemPatch) {
    return this.menuState.removePatch(path, patch);
  }

  removeItem(item: CustomMainMenuItem) {
    return this.menuState.removeItem(item);
  }

  removeOverlayPatch(patch: OverlayPatch) {
    return this.menuState.removeOverlayPatch(patch);
  }

  removeOverlayComponent(component: ReactNode) {
    return this.menuState.removeOverlayComponent(component);
  }
}

export default MenuHook;