|
| 1 | +import StackBlitzSDK, { EmbedOptions } from '@stackblitz/sdk'; |
| 2 | +import { useCallback } from 'react'; |
| 3 | +import React from 'react'; |
| 4 | + |
| 5 | +interface Props { |
| 6 | + embedId: 'string'; |
| 7 | +} |
| 8 | + |
| 9 | +const cache: Record<string, HTMLDivElement> = {}; |
| 10 | + |
| 11 | +const elRoot = document.createElement('div'); |
| 12 | +elRoot.style.visibility = 'hidden'; |
| 13 | +elRoot.style.pointerEvents = 'none'; |
| 14 | +elRoot.style.width = '0px'; |
| 15 | +elRoot.style.height = '0px'; |
| 16 | +elRoot.style.position = 'absolute'; |
| 17 | + |
| 18 | +document.body.appendChild(elRoot); |
| 19 | + |
| 20 | +function getStackblitzEl(projectId: string) { |
| 21 | + const existing = cache[projectId]; |
| 22 | + if (existing) return existing; |
| 23 | + |
| 24 | + const elParent = document.createElement('div'); |
| 25 | + elParent.style.display = 'contents'; |
| 26 | + elRoot.appendChild(elParent); |
| 27 | + |
| 28 | + const el = document.createElement('div'); |
| 29 | + elParent.appendChild(el); |
| 30 | + |
| 31 | + const opts: EmbedOptions = { |
| 32 | + forceEmbedLayout: true, |
| 33 | + view: 'preview', |
| 34 | + height: '100%', |
| 35 | + hideNavigation: true, |
| 36 | + hideExplorer: true, |
| 37 | + }; |
| 38 | + |
| 39 | + const isGithub = projectId.startsWith('KurtGokhan'); |
| 40 | + const promise = isGithub ? StackBlitzSDK.embedGithubProject(el, projectId, opts) : StackBlitzSDK.embedProjectId(el, projectId, opts); |
| 41 | + |
| 42 | + promise.then(() => { |
| 43 | + const iframe = elParent.querySelector('iframe'); |
| 44 | + // if (!iframe) return; |
| 45 | + // iframe.style.width = '100%'; |
| 46 | + // iframe.style.height = '100%'; |
| 47 | + }); |
| 48 | + |
| 49 | + cache[projectId] = elParent; |
| 50 | + return elParent; |
| 51 | +} |
| 52 | + |
| 53 | +export function Stackblitz({ embedId }: Props) { |
| 54 | + const el = getStackblitzEl(embedId); |
| 55 | + |
| 56 | + const ref = useCallback( |
| 57 | + (node) => { |
| 58 | + node?.appendChild(el); |
| 59 | + }, |
| 60 | + [el], |
| 61 | + ); |
| 62 | + |
| 63 | + return <div ref={ref} key={embedId} style={{ height: 600 }} />; |
| 64 | +} |
0 commit comments