2022-07-28 17:52:50 +03:00
|
|
|
import Modifier from 'ember-modifier';
|
2022-08-02 11:42:25 +03:00
|
|
|
import React from 'react';
|
|
|
|
import ReactDOM from 'react-dom';
|
|
|
|
import {createRoot} from 'react-dom/client';
|
2022-08-02 11:23:43 +03:00
|
|
|
import {registerDestructor} from '@ember/destroyable';
|
2022-08-02 11:42:25 +03:00
|
|
|
|
|
|
|
// make globals available for any pulled in UMD components
|
|
|
|
// - avoids external components needing to bundle React and running into multiple version errors
|
|
|
|
window.React = React;
|
|
|
|
window.ReactDOM = ReactDOM;
|
2022-07-28 17:52:50 +03:00
|
|
|
|
|
|
|
export default class ReactRenderModifier extends Modifier {
|
2022-08-02 11:23:43 +03:00
|
|
|
constructor(owner, args) {
|
|
|
|
super(owner, args);
|
|
|
|
registerDestructor(this, this.cleanup);
|
|
|
|
}
|
2022-07-28 17:52:50 +03:00
|
|
|
|
2022-08-02 11:23:43 +03:00
|
|
|
modify(element, [reactComponent], {props}) {
|
|
|
|
if (!this.didSetup) {
|
|
|
|
if (!this.root) {
|
|
|
|
this.root = createRoot(element);
|
|
|
|
}
|
|
|
|
|
|
|
|
this.root.render(React.createElement(reactComponent, {...props}));
|
|
|
|
|
|
|
|
this.didSetup = true;
|
2022-07-28 17:52:50 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-02 11:23:43 +03:00
|
|
|
cleanup = () => {
|
2022-07-28 17:52:50 +03:00
|
|
|
if (!this.root) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.root.unmount();
|
2022-08-02 11:23:43 +03:00
|
|
|
};
|
2022-07-28 17:52:50 +03:00
|
|
|
}
|