frontAnswerer/src/widgets/container/ContainerWidget.tsx

48 lines
1.3 KiB
TypeScript
Raw Normal View History

import { ComponentPropsWithoutRef } from "react";
2024-04-24 15:56:11 +00:00
import { Root, createRoot } from "react-dom/client";
import { pollForSelector } from "../shared/pollForSelector";
import QuizContainer from "./QuizContainer";
2024-04-24 15:56:11 +00:00
type Props = ComponentPropsWithoutRef<typeof QuizContainer>;
2024-04-24 15:56:11 +00:00
export class ContainerWidget {
root: Root | undefined;
constructor(props: Props & {
2024-04-24 15:56:11 +00:00
selector: string;
/**
* In seconds, null - polling disabled
*/
selectorPollingTimeLimit?: number | null;
2024-04-24 15:56:11 +00:00
}) {
const { selector, selectorPollingTimeLimit = 60 } = props;
const element = document.querySelector(selector);
if (element) {
this.root = createRoot(element);
this.render(props);
2024-04-24 15:56:11 +00:00
return;
}
2024-04-24 15:56:11 +00:00
if (!selectorPollingTimeLimit) {
console.error(`Не удалось найти элемент ${selector} для вставки виджета`);
return;
}
pollForSelector(selector, selectorPollingTimeLimit, (element) => {
this.root = createRoot(element);
this.render(props);
});
2024-04-24 15:56:11 +00:00
}
render(props: Props) {
this.root?.render(<QuizContainer {...props} />);
}
2024-04-24 15:56:11 +00:00
destroy() {
if (this.root) this.root.unmount();
}
}