frontAnswerer/src/widgets/button/ButtonWidget.tsx

71 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-04-24 15:56:11 +00:00
import { Root, createRoot } from "react-dom/client";
import OpenQuizButton from "./OpenQuizButton";
import { createPortal } from "react-dom";
import { pollForSelector } from "../shared/pollForSelector";
2024-04-24 15:56:11 +00:00
export class ButtonWidget {
root: Root | undefined;
element = document.createElement("div");
constructor({ quizId, selector, selectorPollingTimeLimit = 60 }: {
quizId: string;
selector: string;
/**
* In seconds, null - polling disabled
*/
selectorPollingTimeLimit?: number | null;
}) {
const element = document.querySelector(selector);
if (element) {
this.root = createRoot(element);
this.root.render(<OpenQuizButton quizId={quizId} />);
2024-04-24 15:56:11 +00:00
return;
}
if (!selectorPollingTimeLimit) {
console.error(`Не удалось найти элемент ${selector} для вставки виджета`);
return;
}
pollForSelector(selector, selectorPollingTimeLimit, (element) => {
this.root = createRoot(element);
this.root.render(<OpenQuizButton quizId={quizId} />);
});
}
destroy() {
if (this.root) this.root.unmount();
this.element.remove();
}
}
export class ButtonWidgetFixed {
root: Root | undefined;
element = document.createElement("div");
constructor({ quizId, side }: {
quizId: string;
side: "left" | "right";
}) {
2024-04-24 15:56:11 +00:00
this.element.style.setProperty("display", "none");
document.body.appendChild(this.element);
this.root = createRoot(this.element);
this.root.render(createPortal(
2024-04-24 15:56:11 +00:00
<OpenQuizButton
fixedSide={side}
2024-04-24 15:56:11 +00:00
quizId={quizId}
/>,
document.body
));
2024-04-24 15:56:11 +00:00
}
destroy() {
if (this.root) this.root.unmount();
this.element.remove();
}
}