summaryrefslogtreecommitdiff
path: root/frontend/src/tabs-hook.tsx
blob: 56ff8f10b7133818eeb3462941602c8d20ba40ba (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
// TabsHook for versions after the Desktop merge
import { Patch, QuickAccessTab, afterPatch, findInReactTree, getReactRoot, sleep } from 'decky-frontend-lib';

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 qAMRoot?: any;
  private qamPatch?: Patch;

  constructor() {
    super('TabsHook');

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

  init() {
    const tree = getReactRoot(document.getElementById('root') as any);
    let qAMRoot: any;
    const findQAMRoot = (currentNode: any, iters: number): any => {
      if (iters >= 80) {
        // currently 67
        return null;
      }
      if (
        typeof currentNode?.memoizedProps?.visible == 'boolean' &&
        currentNode?.type?.toString()?.includes('QuickAccessMenuBrowserView')
      ) {
        this.log(`QAM root was found in ${iters} recursion cycles`);
        return currentNode;
      }
      if (currentNode.child) {
        let node = findQAMRoot(currentNode.child, iters + 1);
        if (node !== null) return node;
      }
      if (currentNode.sibling) {
        let node = findQAMRoot(currentNode.sibling, iters + 1);
        if (node !== null) return node;
      }
      return null;
    };
    (async () => {
      qAMRoot = findQAMRoot(tree, 0);
      while (!qAMRoot) {
        this.error(
          'Failed to find QAM root node, reattempting in 5 seconds. A developer may need to increase the recursion limit.',
        );
        await sleep(5000);
        qAMRoot = findQAMRoot(tree, 0);
      }
      this.qAMRoot = qAMRoot;
      let patchedInnerQAM: any;
      this.qamPatch = afterPatch(qAMRoot.return, 'type', (_: any, ret: any) => {
        try {
          if (!qAMRoot?.child) {
            qAMRoot = findQAMRoot(tree, 0);
            this.qAMRoot = qAMRoot;
          }
          if (qAMRoot?.child && !qAMRoot?.child?.type?.decky) {
            afterPatch(qAMRoot.child, 'type', (_: any, ret: any) => {
              try {
                const qamTabsRenderer = findInReactTree(ret, (x) => x?.props?.onFocusNavDeactivated);
                if (patchedInnerQAM) {
                  qamTabsRenderer.type = patchedInnerQAM;
                } else {
                  afterPatch(qamTabsRenderer, 'type', (innerArgs: any, ret: any) => {
                    const tabs = findInReactTree(ret, (x) => x?.props?.tabs);
                    this.render(tabs.props.tabs, innerArgs[0].visible);
                    return ret;
                  });
                  patchedInnerQAM = qamTabsRenderer.type;
                }
              } catch (e) {
                this.error('Error patching QAM inner', e);
              }
              return ret;
            });
            qAMRoot.child.type.decky = true;
            qAMRoot.child.alternate.type = qAMRoot.child.type;
          }
        } catch (e) {
          this.error('Error patching QAM', e);
        }

        return ret;
      });

      if (qAMRoot.return.alternate) {
        qAMRoot.return.alternate.type = qAMRoot.return.type;
      }
      this.log('Finished initial injection');
    })();
  }

  deinit() {
    this.qamPatch?.unpatch();
    this.qAMRoot.return.alternate.type = this.qAMRoot.return.type;
  }

  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 = <QuickAccessVisibleStateProvider tab={tab}>{content}</QuickAccessVisibleStateProvider>;
      existingTabs.push(tab);
    }
  }
}

export default TabsHook;