vite-plugin-symfony
Version:
A Vite plugin to integrate easily Vite in your Symfony application
70 lines (68 loc) • 2.43 kB
JavaScript
// src/stimulus/helpers/react/util.ts
var reactImportedModules = {};
function registerReactControllerComponents(modules, controllersDir = "./react/controllers") {
reactImportedModules = { ...reactImportedModules, ...modules };
window.resolveReactComponent = (name) => {
const reactModule = reactImportedModules[`${controllersDir}/${name}.jsx`] || reactImportedModules[`${controllersDir}/${name}.tsx`];
if (typeof reactModule === "undefined") {
const possibleValues = Object.keys(reactImportedModules).map(
(key) => key.replace(`${controllersDir}/`, "").replace(".jsx", "").replace(".tsx", "")
);
throw new Error(`React controller "${name}" does not exist. Possible values: ${possibleValues.join(", ")}`);
}
return reactModule;
};
}
// src/stimulus/helpers/react/render_controller.ts
import React from "react";
import { createRoot } from "react-dom/client";
import { Controller } from "@hotwired/stimulus";
var render_controller_default = class extends Controller {
static values = {
component: String,
props: Object
};
connect() {
const props = this.propsValue ? this.propsValue : null;
this.dispatchEvent("connect", { component: this.componentValue, props });
if (!this.componentValue) {
throw new Error("No component specified.");
}
const importedReactModule = window.resolveReactComponent(this.componentValue);
const onload = (reactModule) => {
const component = reactModule.default;
this._renderReactElement(React.createElement(component, props, null));
this.dispatchEvent("mount", {
componentName: this.componentValue,
component,
props
});
};
if (typeof importedReactModule === "function") {
importedReactModule().then(onload);
} else {
onload(importedReactModule);
}
}
disconnect() {
this.element.root.unmount();
this.dispatchEvent("unmount", {
component: this.componentValue,
props: this.propsValue ? this.propsValue : null
});
}
_renderReactElement(reactElement) {
const element = this.element;
if (!element.root) {
element.root = createRoot(this.element);
}
element.root.render(reactElement);
}
dispatchEvent(name, payload) {
this.dispatch(name, { detail: payload, prefix: "react" });
}
};
export {
render_controller_default as ReactController,
registerReactControllerComponents
};