|
| 1 | +import { |
| 2 | + APP_MESSAGE_TYPE, |
| 3 | + HOST_MESSAGE_TYPE, |
| 4 | + type ThemePayload, |
| 5 | +} from '@lemoncode/quickmock-bridge-protocol'; |
| 6 | + |
| 7 | +const readVar = (style: CSSStyleDeclaration, name: string): string => |
| 8 | + style.getPropertyValue(name).trim(); |
| 9 | + |
| 10 | +export const extractTheme = (): ThemePayload => { |
| 11 | + const style = getComputedStyle(document.documentElement); |
| 12 | + return { |
| 13 | + background: readVar(style, '--vscode-editor-background'), |
| 14 | + backgroundSecondary: readVar(style, '--vscode-sideBar-background'), |
| 15 | + foreground: readVar(style, '--vscode-editor-foreground'), |
| 16 | + }; |
| 17 | +}; |
| 18 | + |
| 19 | +const IFRAME_READY_TYPES: ReadonlySet<string> = new Set([ |
| 20 | + APP_MESSAGE_TYPE.WEBVIEW_READY, |
| 21 | + APP_MESSAGE_TYPE.READY, |
| 22 | +]); |
| 23 | + |
| 24 | +export const setupThemeSync = ( |
| 25 | + iframe: HTMLIFrameElement, |
| 26 | + appOrigin: string |
| 27 | +): void => { |
| 28 | + const sendTheme = (): void => { |
| 29 | + iframe.contentWindow?.postMessage( |
| 30 | + { type: HOST_MESSAGE_TYPE.THEME, payload: extractTheme() }, |
| 31 | + appOrigin |
| 32 | + ); |
| 33 | + }; |
| 34 | + |
| 35 | + const onIframeReady = (event: MessageEvent): void => { |
| 36 | + if (event.origin !== appOrigin) return; |
| 37 | + const type = (event.data as { type?: string } | undefined)?.type; |
| 38 | + if (type && IFRAME_READY_TYPES.has(type)) sendTheme(); |
| 39 | + }; |
| 40 | + window.addEventListener('message', onIframeReady); |
| 41 | + |
| 42 | + let rafId = 0; |
| 43 | + const sendThemeDebounced = (): void => { |
| 44 | + cancelAnimationFrame(rafId); |
| 45 | + rafId = requestAnimationFrame(sendTheme); |
| 46 | + }; |
| 47 | + |
| 48 | + const observer = new MutationObserver(sendThemeDebounced); |
| 49 | + observer.observe(document.body, { |
| 50 | + attributes: true, |
| 51 | + attributeFilter: ['class', 'style'], |
| 52 | + }); |
| 53 | +}; |
0 commit comments