Bin
2025-12-17 611bfe34c3c96199eaaf6cf9e41a75892e44e879
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import { configure } from "mobx";
import { destroy } from "mobx-state-tree";
import { render, unmountComponentAtNode } from "react-dom";
import { createRoot } from "react-dom/client";
import camelCase from "lodash/camelCase";
import { LabelStudio as LabelStudioReact } from "./Component";
import App from "./components/App/App";
import { configureStore } from "./configureStore";
import legacyEvents from "./core/External";
import { Hotkey } from "./core/Hotkey";
import defaultOptions from "./defaultOptions";
import { destroy as destroySharedStore } from "./mixins/SharedChoiceStore/mixin";
import { EventInvoker } from "./utils/events";
import { FF_LSDV_4620_3_ML, isFF } from "./utils/feature-flags";
import { cleanDomAfterReact, findReactKey } from "./utils/reactCleaner";
import { isDefined } from "./utils/utilities";
 
// Extend window interface for TypeScript
declare global {
  interface Window {
    Htx: any;
  }
}
 
configure({
  isolateGlobalState: true,
});
 
type Callback = (...args: any[]) => any;
 
type LSFUser = any;
type LSFTask = any;
 
// @todo type LSFOptions = SnapshotIn<typeof AppStore>;
// because those options will go as initial values for AppStore
// but it's not types yet, so here is some excerpt of its parameters
type LSFOptions = Record<string, any> & {
  interfaces: string[];
  keymap?: any;
  user?: LSFUser;
  users?: LSFUser[];
  task?: LSFTask;
  settings?: {
    forceBottomPanel?: boolean;
  };
  instanceOptions?: {
    reactVersion?: "v18" | "v17";
  };
};
 
export class LabelStudio {
  static Component = LabelStudioReact;
 
  static instances = new Set<LabelStudio>();
 
  static destroyAll() {
    LabelStudio.instances.forEach((inst) => inst.destroy?.());
    LabelStudio.instances.clear();
  }
 
  options: Partial<LSFOptions>;
  root: Element | string;
  store: any;
  reactRoot: any;
 
  destroy: (() => void) | null = () => {};
  events = new EventInvoker();
 
  getRootElement(root: Element | string) {
    let element: Element | null = null;
 
    if (typeof root === "string") {
      element = document.getElementById(root);
    } else {
      element = root;
    }
 
    if (!element) {
      throw new Error(`Root element not found (selector: ${root})`);
    }
 
    return element;
  }
 
  constructor(root: Element | string, userOptions: Partial<LSFOptions> = {}) {
    const options = { ...defaultOptions, ...userOptions };
 
    if (options.keymap) {
      Hotkey.setKeymap(options.keymap);
    }
 
    this.root = root;
    this.options = options;
    if (options.instanceOptions?.reactVersion === "v18") {
      this.createAppV18();
    } else {
      this.createAppV17();
    }
 
    // @todo whole approach to hotkeys should be rewritten,
    // @todo but for now we need a way to export Hotkey to different app
    if (window.Htx) window.Htx.Hotkey = Hotkey;
 
    this.supportLegacyEvents();
 
    if (options.instanceOptions?.reactVersion !== "v18") {
      LabelStudio.instances.add(this);
    }
  }
 
  on(eventName: string, callback: Callback) {
    this.events.on(eventName, callback);
  }
 
  off(eventName: string, callback: Callback) {
    if (isDefined(callback)) {
      this.events.off(eventName, callback);
    } else {
      this.events.removeAll(eventName);
    }
  }
 
  // This is a temporary solution that allows React 17 to work in the meantime.
  // and we can update our other usages of LabelStudio to use createRoot, namely tests will likely be affected.
  async createAppV17() {
    const { store } = await configureStore(this.options, this.events);
    const rootElement = this.getRootElement(this.root);
 
    this.store = store;
    window.Htx = this.store;
 
    const isRendered = false;
 
    const renderApp = () => {
      if (isRendered) {
        clearRenderedApp();
      }
      render(<App store={this.store} />, rootElement);
    };
 
    const clearRenderedApp = () => {
      if (!rootElement.childNodes?.length) return;
 
      const childNodes = [...rootElement.childNodes];
      // cleanDomAfterReact needs this key to be sure that cleaning affects only current react subtree
      const reactKey = findReactKey(childNodes[0]);
 
      unmountComponentAtNode(rootElement);
      /*
        Unmounting doesn't help with clearing React's fibers
        but removing the manually helps
        @see https://github.com/facebook/react/pull/20290 (similar problem)
        That's maybe not relevant in version 18
       */
      cleanDomAfterReact(childNodes, reactKey);
      cleanDomAfterReact([rootElement], reactKey);
    };
 
    renderApp();
    store.setAppControls({
      isRendered() {
        return isRendered;
      },
      render: renderApp,
      clear: clearRenderedApp,
    });
 
    this.destroy = () => {
      if (isFF(FF_LSDV_4620_3_ML)) {
        clearRenderedApp();
      }
      destroySharedStore();
      if (isFF(FF_LSDV_4620_3_ML)) {
        /*
           It seems that destroying children separately helps GC to collect garbage
           ...
         */
        this.store.selfDestroy();
      }
      destroy(this.store);
      Hotkey.unbindAll();
      if (isFF(FF_LSDV_4620_3_ML)) {
        /*
            ...
            as well as nulling all these this.store
         */
        this.store = null;
        this.destroy = null;
        LabelStudio.instances.delete(this);
      }
    };
  }
 
  // To support React 18 properly, we need to use createRoot
  // and render the app with it, and properly unmount it and cleanup all references
  async createAppV18() {
    const { store } = await configureStore(this.options, this.events);
    const rootElement = this.getRootElement(this.root);
 
    this.store = store;
    window.Htx = this.store;
 
    let isRendered = false;
 
    const renderApp = () => {
      if (isRendered) {
        clearRenderedApp();
      }
      this.reactRoot = createRoot(rootElement);
      const AppComponent = App as any;
      this.reactRoot.render(<AppComponent store={this.store} />);
      isRendered = true;
    };
 
    const clearRenderedApp = () => {
      if (this.reactRoot && isRendered) {
        this.reactRoot.unmount();
        this.reactRoot = null;
        isRendered = false;
      }
    };
 
    renderApp();
 
    store.setAppControls({
      isRendered() {
        return isRendered;
      },
      render: renderApp,
      clear: clearRenderedApp,
    });
 
    this.destroy = () => {
      // Clear rendered app
      clearRenderedApp();
 
      // Destroy shared store
      destroySharedStore();
 
      // Destroy store
      destroy(this.store);
 
      // Unbind all hotkeys
      Hotkey.unbindAll();
 
      // Clear references
      this.store = null;
      window.Htx = null;
      this.destroy = null;
    };
  }
 
  supportLegacyEvents() {
    const keys = Object.keys(legacyEvents);
 
    keys.forEach((key) => {
      const callback = this.options[key];
 
      if (isDefined(callback)) {
        const eventName = camelCase(key.replace(/^on/, ""));
 
        this.events.on(eventName, callback);
      }
    });
  }
}