feat: load surveys package on-the-fly in web-app (#2375)

Co-authored-by: Matthias Nannt <mail@matthiasnannt.com>
This commit is contained in:
Shubham Palriwala
2024-04-08 11:33:24 +05:30
committed by GitHub
parent 62da30246a
commit 4cd23e62bb
2 changed files with 28 additions and 12 deletions

View File

@@ -1,24 +1,30 @@
import { useEffect, useMemo } from "react";
import { renderSurveyInline, renderSurveyModal } from "@formbricks/surveys";
import { SurveyInlineProps, SurveyModalProps } from "@formbricks/types/formbricksSurveys";
import { loadSurveyScript } from "./lib/loadScript";
const createContainerId = () => `formbricks-survey-container`;
declare global {
interface Window {
formbricksSurveys: {
renderSurveyInline: (props: SurveyInlineProps) => void;
renderSurveyModal: (props: SurveyModalProps) => void;
};
}
}
export const SurveyInline = (props: Omit<SurveyInlineProps, "containerId">) => {
const containerId = useMemo(() => createContainerId(), []);
useEffect(() => {
renderSurveyInline({
...props,
containerId,
});
if (typeof window !== "undefined") {
const renderInline = () => window.formbricksSurveys.renderSurveyInline({ ...props, containerId });
if (!window.formbricksSurveys) {
loadSurveyScript().then(renderInline);
} else {
renderInline();
}
}
}, [containerId, props]);
return <div id={containerId} className="h-full w-full" />;
};
export const SurveyModal = (props: SurveyModalProps) => {
useEffect(() => {
renderSurveyModal(props);
}, [props]);
return <div id="formbricks-survey"></div>;
};

View File

@@ -0,0 +1,10 @@
export const loadSurveyScript: () => Promise<void> = async () => {
try {
const scriptContent = await (await fetch("/api/packages/surveys")).text();
document.head.appendChild(
Object.assign(document.createElement("script"), { textContent: scriptContent })
);
} catch (error) {
console.error("Failed to load the surveys package:", error);
}
};