|
| 1 | +import { removeEdgesAndNodes } from '@bigcommerce/catalyst-client'; |
| 2 | +import Script from 'next/script'; |
| 3 | +import { ComponentProps } from 'react'; |
| 4 | + |
| 5 | +import { FragmentOf } from '~/client/graphql'; |
| 6 | + |
| 7 | +import { ScriptsFragment } from './fragment'; |
| 8 | + |
| 9 | +type ScriptsData = FragmentOf<typeof ScriptsFragment>; |
| 10 | + |
| 11 | +interface ScriptRendererProps { |
| 12 | + scripts: ScriptsData['headerScripts'] | null; |
| 13 | + strategy: ComponentProps<typeof Script>['strategy']; |
| 14 | +} |
| 15 | + |
| 16 | +export const ScriptManagerScripts = ({ scripts, strategy }: ScriptRendererProps) => { |
| 17 | + if (!scripts?.edges) return null; |
| 18 | + |
| 19 | + const scriptNodes = removeEdgesAndNodes(scripts); |
| 20 | + |
| 21 | + return ( |
| 22 | + <> |
| 23 | + {scriptNodes.map((script) => { |
| 24 | + const scriptProps: ComponentProps<typeof Script> = { |
| 25 | + strategy, |
| 26 | + }; |
| 27 | + |
| 28 | + // Handle external scripts (SrcScript) |
| 29 | + if (script.__typename === 'SrcScript' && script.src) { |
| 30 | + scriptProps.src = script.src; |
| 31 | + |
| 32 | + // Add integrity hashes if provided |
| 33 | + if (script.integrityHashes.length > 0) { |
| 34 | + scriptProps.integrity = script.integrityHashes.map((hashObj) => hashObj.hash).join(' '); |
| 35 | + scriptProps.crossOrigin = 'anonymous'; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + // Handle inline scripts (InlineScript) |
| 40 | + if (script.__typename === 'InlineScript' && script.scriptTag) { |
| 41 | + const scriptMatch = /<script[^>]*>([\s\S]*?)<\/script>/i.exec(script.scriptTag); |
| 42 | + |
| 43 | + if (scriptMatch?.[1]) { |
| 44 | + scriptProps.dangerouslySetInnerHTML = { |
| 45 | + __html: scriptMatch[1], |
| 46 | + }; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + scriptProps.id = `bc-script-${script.entityId}`; |
| 51 | + |
| 52 | + return <Script key={scriptProps.id} {...scriptProps} />; |
| 53 | + })} |
| 54 | + </> |
| 55 | + ); |
| 56 | +}; |
0 commit comments