Fix recaptcha in storybook

This commit is contained in:
Joseph Garrone
2024-06-04 01:39:54 +02:00
parent 6b570f2b9a
commit 17e1655eaf
2 changed files with 24 additions and 33 deletions

View File

@ -1,5 +1,4 @@
import { useCallback } from "react"; import { useCallback } from "react";
import { useConst } from "keycloakify/tools/useConst";
import { assert } from "tsafe/assert"; import { assert } from "tsafe/assert";
export type ScriptTag = ScriptTag.TextContent | ScriptTag.Src; export type ScriptTag = ScriptTag.TextContent | ScriptTag.Src;
@ -20,42 +19,19 @@ export namespace ScriptTag {
export function createUseInsertScriptTags() { export function createUseInsertScriptTags() {
let areScriptsInserted = false; let areScriptsInserted = false;
let scriptTagsFingerprint: string | undefined;
function useInsertScriptTags(params: { scriptTags: ScriptTag[] }) { function useInsertScriptTags(params: { scriptTags: ScriptTag[] }) {
const { scriptTags } = params; const { scriptTags } = params;
const currentScriptTagsRef = useConst(() => ({ if (scriptTagsFingerprint === undefined) {
current: scriptTags scriptTagsFingerprint = getScriptTagsFingerprint(scriptTags);
})); } else if (getScriptTagsFingerprint(scriptTags) !== scriptTagsFingerprint) {
// NOTE: This is for storybook, when we switch to a page that has different scripts.
currentScriptTagsRef.current = scriptTags; window.location.reload();
}
const insertScriptTags = useCallback(() => { const insertScriptTags = useCallback(() => {
{
const getFingerprint = (scriptTags: ScriptTag[]) =>
scriptTags
.map((scriptTag): string => {
if ("textContent" in scriptTag) {
return scriptTag.textContent;
}
if ("src" in scriptTag) {
return scriptTag.src;
}
assert(false);
})
.join("---");
if (
getFingerprint(scriptTags) !==
getFingerprint(currentScriptTagsRef.current)
) {
// NOTE: This is for when the scripts imported in the Template have changed switching
// from one page to another in storybook.
window.location.reload();
return;
}
}
if (areScriptsInserted) { if (areScriptsInserted) {
return; return;
} }
@ -109,3 +85,17 @@ export function createUseInsertScriptTags() {
return { useInsertScriptTags }; return { useInsertScriptTags };
} }
function getScriptTagsFingerprint(scriptTags: ScriptTag[]) {
return scriptTags
.map((scriptTag): string => {
if ("textContent" in scriptTag) {
return scriptTag.textContent;
}
if ("src" in scriptTag) {
return scriptTag.src;
}
assert(false);
})
.join("---");
}

View File

@ -68,8 +68,9 @@ export const WithRecaptcha: Story = {
render: () => ( render: () => (
<PageStory <PageStory
kcContext={{ kcContext={{
scripts: ["https://www.google.com/recaptcha/api.js?hl=en"],
recaptchaRequired: true, recaptchaRequired: true,
recaptchaSiteKey: "foobar" recaptchaSiteKey: "6LfQHvApAAAAAE73SYTd5vS0lB1Xr7zdiQ-6iBVa"
}} }}
/> />
) )