UNPKG

1.85 kBTypeScriptView Raw
1// *****************************************************************************
2// Copyright (C) 2018 TypeFox and others.
3//
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License v. 2.0 which is available at
6// http://www.eclipse.org/legal/epl-2.0.
7//
8// This Source Code may also be made available under the following Secondary
9// Licenses when the conditions for such availability set forth in the Eclipse
10// Public License v. 2.0 are satisfied: GNU General Public License, version 2
11// with the GNU Classpath Exception which is available at
12// https://www.gnu.org/software/classpath/license.html.
13//
14// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15// *****************************************************************************
16
17import { inject, injectable, optional } from 'inversify';
18import * as React from 'react';
19import { createRoot, Root } from 'react-dom/client';
20import { Disposable, DisposableCollection } from '../../common';
21
22export type RendererHost = HTMLElement;
23export const RendererHost = Symbol('RendererHost');
24
25@injectable()
26export class ReactRenderer implements Disposable {
27 protected readonly toDispose = new DisposableCollection();
28 readonly host: HTMLElement;
29 protected hostRoot: Root;
30
31 constructor(
32 @inject(RendererHost) @optional() host?: RendererHost
33 ) {
34 this.host = host || document.createElement('div');
35 this.hostRoot = createRoot(this.host);
36 this.toDispose.push(Disposable.create(() => this.hostRoot.unmount()));
37 }
38
39 dispose(): void {
40 this.toDispose.dispose();
41 }
42
43 render(): void {
44 this.hostRoot.render(<React.Fragment>{this.doRender()}</React.Fragment>);
45 }
46
47 protected doRender(): React.ReactNode {
48 return undefined;
49 }
50}