Skip to content

Commit

Permalink
feat: load surveys package on-the-fly in web-app (#2375)
Browse files Browse the repository at this point in the history
Co-authored-by: Matthias Nannt <mail@matthiasnannt.com>
  • Loading branch information
ShubhamPalriwala and mattinannt committed Apr 8, 2024
1 parent 62da302 commit 4cd23e6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 12 deletions.
30 changes: 18 additions & 12 deletions packages/ui/Survey/index.tsx
Original file line number Diff line number Diff line change
@@ -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 changes: 10 additions & 0 deletions packages/ui/Survey/lib/loadScript.ts
Original file line number Diff line number Diff line change
@@ -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);
}
};

0 comments on commit 4cd23e6

Please sign in to comment.