|
| 1 | +import type { QwikSymbolEvent } from '@builder.io/qwik'; |
| 2 | +import type { ReplEvent } from '../types'; |
| 3 | + |
| 4 | +(() => { |
| 5 | + const replId = location.pathname.split('/')[2]; |
| 6 | + const origConsole: Record<string, any> = {}; |
| 7 | + |
| 8 | + const sendToServerWindow = (data: Omit<ReplEvent, 'start'>) => { |
| 9 | + try { |
| 10 | + parent.postMessage({ |
| 11 | + type: 'event', |
| 12 | + replId, |
| 13 | + event: { ...data, start: performance.now() }, |
| 14 | + }); |
| 15 | + } catch { |
| 16 | + // ignore |
| 17 | + } |
| 18 | + }; |
| 19 | + |
| 20 | + const wrapConsole = (kind: 'log' | 'warn' | 'error' | 'debug') => { |
| 21 | + origConsole[kind] = console[kind]; |
| 22 | + console[kind] = (...args: any[]) => { |
| 23 | + sendToServerWindow({ |
| 24 | + kind: `console-${kind}` as any, |
| 25 | + scope: 'client', |
| 26 | + message: args.map((a) => String(a)), |
| 27 | + }); |
| 28 | + origConsole[kind](...args); |
| 29 | + }; |
| 30 | + }; |
| 31 | + wrapConsole('log'); |
| 32 | + wrapConsole('warn'); |
| 33 | + wrapConsole('error'); |
| 34 | + // wrapConsole('debug'); |
| 35 | + |
| 36 | + document.addEventListener('qsymbol', (ev) => { |
| 37 | + const customEv: QwikSymbolEvent = ev as any; |
| 38 | + const symbolName = customEv.detail?.symbol; |
| 39 | + sendToServerWindow({ |
| 40 | + kind: 'symbol', |
| 41 | + scope: 'client', |
| 42 | + message: [symbolName], |
| 43 | + }); |
| 44 | + }); |
| 45 | + |
| 46 | + document.addEventListener('qresume', () => { |
| 47 | + sendToServerWindow({ |
| 48 | + kind: 'resume', |
| 49 | + scope: 'client', |
| 50 | + message: [''], |
| 51 | + }); |
| 52 | + }); |
| 53 | + |
| 54 | + // Ensure all external links open in a new tab |
| 55 | + document.addEventListener( |
| 56 | + 'click', |
| 57 | + (ev) => { |
| 58 | + try { |
| 59 | + if (ev.target && (ev.target as Element).tagName === 'A') { |
| 60 | + const anchor = ev.target as HTMLAnchorElement; |
| 61 | + const href = anchor.href; |
| 62 | + if (href && href !== '#') { |
| 63 | + const url = new URL(anchor.href, origin); |
| 64 | + if (url.origin !== origin) { |
| 65 | + anchor.setAttribute('target', '_blank'); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + } catch (e) { |
| 70 | + console.error('repl-request-handler', e); |
| 71 | + } |
| 72 | + }, |
| 73 | + true |
| 74 | + ); |
| 75 | +})(); |
0 commit comments