UNPKG

@andersundsehr/storybook-typo3

Version:

The one and only Storybook Renderer for TYPO3 Fluid Components

66 lines (65 loc) 2.92 kB
import { url } from '@andersundsehr/storybook-typo3'; import { fetchWithUserRetry } from './fetchWithUserRetry'; import { GLOBALS_UPDATED, SET_GLOBALS } from 'storybook/internal/core-events'; import { addons } from 'storybook/preview-api'; function getLocation() { let location = window.location; if (window.parent?.location && window.parent !== window) { location = window.parent.location; } return location; } function getGlobalsFromUrl() { const url = new URL(getLocation().href); const globalsString = url.searchParams.get('globals') || ''; const globalsArray = globalsString.split(';').filter(Boolean); const entries = globalsArray.map(global => global.split(':')); return Object.fromEntries(entries); } function setGlobalsToUrl(globals) { const location = getLocation(); const url = new URL(location.href); const globalString = Object.entries(globals).map(([key, value]) => `${key}:${value}`).join(';'); url.searchParams.set('globals', globalString); location.href = url.toString(); } export async function fetchPreviewConfig(currentGlobals) { const apiEndpoint = url + '/_storybook/preview'; const globals = currentGlobals || getGlobalsFromUrl(); return await fetchWithUserRetry(apiEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ globals }), }, 'preview config'); } export function initGlobalsHandling(initalGlobalTypes) { const channel = addons.getChannel(); let oldGlobalTypes = initalGlobalTypes; // eslint-disable-next-line @typescript-eslint/no-misused-promises channel.on(GLOBALS_UPDATED, async ({ globals }) => { const previewConfig = await fetchPreviewConfig(globals); oldGlobalTypes = previewConfig.globalTypes; const newGlobals = getGlobalsFromUrl(); let changed = false; for (const key in previewConfig.globalTypes) { const inputType = previewConfig.globalTypes[key]; if (!inputType.toolbar?.items?.some((item) => item.value === globals[key])) { newGlobals[key] = inputType.toolbar?.items?.[0]?.value || ''; changed = true; } } if (changed) { // change URL search params and reload page (this is the only way to set the globals, that worked)!! setGlobalsToUrl(newGlobals); return; } if (JSON.stringify(oldGlobalTypes) !== JSON.stringify(previewConfig.globalTypes)) { // this only sets the globalTypes and not the globals :( // see https://github.com/storybookjs/storybook/blob/3ac2fece4c41955e7349f6f825b7d21dd18ff9a9/code/core/src/manager-api/modules/globals.ts#L141-L149 channel.emit(SET_GLOBALS, { globals, globalTypes: previewConfig.globalTypes }); return; } }); }