|
| 1 | +// rocket-bridge.js |
| 2 | +(function () { |
| 3 | + const parentWin = window.parent; |
| 4 | + |
| 5 | + const handlers = { |
| 6 | + setTreeData: async (payload) => { |
| 7 | + console.log("[rocketPreview] setTreeData", payload); |
| 8 | + // TODO |
| 9 | + return { |
| 10 | + ok: true |
| 11 | + }; |
| 12 | + }, |
| 13 | + setExtraData: async (payload) => { |
| 14 | + console.log("[rocketPreview] setExtraData", payload); |
| 15 | + // TODO |
| 16 | + return { |
| 17 | + ok: true |
| 18 | + }; |
| 19 | + }, |
| 20 | + setImage: async (payload) => { |
| 21 | + console.log("[rocketPreview] setImage", payload); |
| 22 | + // TODO |
| 23 | + return { |
| 24 | + ok: true |
| 25 | + }; |
| 26 | + }, |
| 27 | + getState: async () => { |
| 28 | + return { |
| 29 | + status: "ready" |
| 30 | + }; |
| 31 | + }, |
| 32 | + ping: async (payload) => { |
| 33 | + return { |
| 34 | + pong: true, |
| 35 | + t: payload?.t |
| 36 | + }; |
| 37 | + } |
| 38 | + }; |
| 39 | + |
| 40 | + function reply(id, ok, resultOrError) { |
| 41 | + parentWin.postMessage({ |
| 42 | + type: "osparc:rpc:result", |
| 43 | + id, |
| 44 | + ok, |
| 45 | + result: ok ? resultOrError : undefined, |
| 46 | + error: ok ? undefined : String(resultOrError) |
| 47 | + }, "*"); |
| 48 | + } |
| 49 | + |
| 50 | + window.addEventListener("message", async (ev) => { |
| 51 | + const data = ev.data; |
| 52 | + if (!data || data.type !== "osparc:rpc") { |
| 53 | + return; |
| 54 | + } |
| 55 | + const { id, action, payload, expectReply } = data; |
| 56 | + try { |
| 57 | + const fn = handlers[action]; |
| 58 | + if (typeof fn !== "function") { |
| 59 | + throw new Error(`Unknown action '${action}'`); |
| 60 | + } |
| 61 | + const result = await fn(payload); |
| 62 | + if (expectReply) { |
| 63 | + reply(id, true, result); |
| 64 | + } |
| 65 | + } catch (err) { |
| 66 | + if (expectReply) { |
| 67 | + reply(id, false, err); |
| 68 | + } |
| 69 | + } |
| 70 | + }); |
| 71 | + |
| 72 | + // Tell osparc we’re ready |
| 73 | + window.addEventListener("DOMContentLoaded", () => { |
| 74 | + parentWin.postMessage({ |
| 75 | + type: "osparc:ready", |
| 76 | + version: "1.0.0" |
| 77 | + }, "*"); |
| 78 | + }); |
| 79 | +})(); |
0 commit comments