mirror of
https://github.com/formbricks/formbricks.git
synced 2026-01-30 03:20:40 -06:00
feat: load surveys package on-the-fly in web-app (#2375)
Co-authored-by: Matthias Nannt <mail@matthiasnannt.com>
This commit is contained in:
committed by
GitHub
parent
62da30246a
commit
4cd23e62bb
@@ -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>;
|
||||
};
|
||||
|
||||
10
packages/ui/Survey/lib/loadScript.ts
Normal file
10
packages/ui/Survey/lib/loadScript.ts
Normal 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);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user