import type { Root } from "react-dom/client"; import { createRoot } from "react-dom/client"; import { getDocument } from "ssr-window"; import { getCfg } from "../../utils/getCfg"; import type { TCollectionItemDefaultCfg } from "../collection"; /** * Factory. Подходит в ситуациях, когда React-компонент выводится на страницу единожды без добавления в коллекцию. Он делает доступными поля `cfg`, `root`, а также методы `render`, который вызывается автоматически в случае нахождения элемента, и `unmount`. * @module StandaloneReactItem * @param selector{String} передаваемый селектор элемента * @param defaultCfg{Object=} конфигурация плагина по умолчанию * @example * import { StandaloneReactItem } from "@delement/ui/plugins" * * class MyPlugin extends StandaloneReactItem { * * static selector = "[data-js-MyPlugin]"; * * static defaultCfg = {} * * constructor() { * super(MyPlugin.selector, MyPlugin.defaultCfg); * // console.debug(this.cfg, this.root, this.render, this.unmount); * } * * render() { * // вызывается автоматически, если был найден элемент * } * * } */ class StandaloneReactItem { instance: HTMLElement | null; cfg: TCollectionItemDefaultCfg; root: Root | null; constructor(selector: string, defaultCfg: TCollectionItemDefaultCfg = {}) { this.root = null; const element = getDocument().querySelector(selector); this.instance = element as HTMLElement | null; if (this.instance) { this.cfg = getCfg(this.instance, selector, defaultCfg); this.root = createRoot(this.instance); this.render(); } } /** * Метод для рендера приложения, если его элемент существует на страницу */ render() { } /** * Метод для размонтирования приложения */ unmount() { this.root?.unmount(); } } export { StandaloneReactItem };