|
| 1 | +'use strict' |
| 2 | + |
| 3 | +class InterfaceHelper { |
| 4 | + static #initiated = false |
| 5 | + |
| 6 | + static preInit() { |
| 7 | + if (InterfaceHelper.#initiated) { |
| 8 | + console.error('InterfaceHelper is already initiated.') |
| 9 | + return |
| 10 | + } |
| 11 | + InterfaceHelper.#initiated = true |
| 12 | + |
| 13 | + const globalStyle = document.createElement('link') |
| 14 | + globalStyle.rel = 'stylesheet' |
| 15 | + globalStyle.href = '/global.css' |
| 16 | + document.head.prepend(globalStyle) |
| 17 | + |
| 18 | + const fallbackStyle = document.createElement('style') |
| 19 | + fallbackStyle.textContent = 'html { background-color: var(--main-background-color); }' |
| 20 | + document.head.prepend(fallbackStyle) |
| 21 | + } |
| 22 | + |
| 23 | + /** Coordinator shell: popup opener or `/join` parent. */ |
| 24 | + static #target() { |
| 25 | + return globalThis.opener ?? globalThis.parent |
| 26 | + } |
| 27 | + |
| 28 | + /** First ping after init is applied (same as legacy `postMessage(null)`; coordinator accepts `Arena-Interface-Ready` too). */ |
| 29 | + static signalReady() { |
| 30 | + const t = InterfaceHelper.#target() |
| 31 | + if (t) { |
| 32 | + t.postMessage(null, '*') |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Send a normal interface reply to the arena coordinator. |
| 38 | + * @param {object} payload |
| 39 | + * @param {unknown} payload.value |
| 40 | + * @param {{ toRespond: number, toTerminate: number }} [payload.executionSteps] |
| 41 | + * @param {unknown} [payload.console] |
| 42 | + */ |
| 43 | + static respond(payload) { |
| 44 | + const t = InterfaceHelper.#target() |
| 45 | + if (!t) { |
| 46 | + return |
| 47 | + } |
| 48 | + const executionSteps = payload.executionSteps ?? { toRespond: 0, toTerminate: 0 } |
| 49 | + t.postMessage({ |
| 50 | + type: 'Response', |
| 51 | + response: { |
| 52 | + value: payload.value, |
| 53 | + executionSteps, |
| 54 | + ...(payload.console ? { console: payload.console } : {}), |
| 55 | + }, |
| 56 | + }, '*') |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +globalThis.InterfaceHelper = InterfaceHelper |
| 61 | +InterfaceHelper.preInit() |
0 commit comments