-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: load surveys package on-the-fly in web-app (#2375)
Co-authored-by: Matthias Nannt <mail@matthiasnannt.com>
- Loading branch information
1 parent
62da302
commit 4cd23e6
Showing
2 changed files
with
28 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
}; |