|
| 1 | +// Copyright 2023 The Lynx Authors. All rights reserved. |
| 2 | +// Licensed under the Apache License Version 2.0 that can be found in the |
| 3 | +// LICENSE file in the root directory of this source tree. |
| 4 | + |
| 5 | +import type { dispatchCoreContextOnBackgroundEndpoint } from './endpoints.js'; |
| 6 | +import type { LynxContextEventTarget } from '@types'; |
| 7 | +import type { Rpc } from '@lynx-js/web-worker-rpc'; |
| 8 | + |
| 9 | +export const DispatchEventResult = { |
| 10 | + // Event was not canceled by event handler or default event handler. |
| 11 | + NotCanceled: 0, |
| 12 | + // Event was canceled by event handler; i.e. a script handler calling |
| 13 | + // preventDefault. |
| 14 | + CanceledByEventHandler: 1, |
| 15 | + // Event was canceled by the default event handler; i.e. executing the default |
| 16 | + // action. This result should be used sparingly as it deviates from the DOM |
| 17 | + // Event Dispatch model. Default event handlers really shouldn't be invoked |
| 18 | + // inside of dispatch. |
| 19 | + CanceledByDefaultEventHandler: 2, |
| 20 | + // Event was canceled but suppressed before dispatched to event handler. This |
| 21 | + // result should be used sparingly; and its usage likely indicates there is |
| 22 | + // potential for a bug. Trusted events may return this code; but untrusted |
| 23 | + // events likely should always execute the event handler the developer intends |
| 24 | + // to execute. |
| 25 | + CanceledBeforeDispatch: 3, |
| 26 | +} as const; |
| 27 | + |
| 28 | +export class LynxCrossThreadContext extends EventTarget |
| 29 | + implements LynxContextEventTarget |
| 30 | +{ |
| 31 | + constructor( |
| 32 | + private _config: { |
| 33 | + rpc: Rpc; |
| 34 | + receiveEventEndpoint: typeof dispatchCoreContextOnBackgroundEndpoint; |
| 35 | + sendEventEndpoint: typeof dispatchCoreContextOnBackgroundEndpoint; |
| 36 | + }, |
| 37 | + ) { |
| 38 | + super(); |
| 39 | + } |
| 40 | + postMessage(...args: any[]) { |
| 41 | + console.error('[lynx-web] postMessage not implemented, args:', ...args); |
| 42 | + } |
| 43 | + // @ts-expect-error |
| 44 | + override dispatchEvent(event: ContextCrossThreadEvent) { |
| 45 | + const { rpc, sendEventEndpoint } = this._config; |
| 46 | + rpc.invoke(sendEventEndpoint, [event]); |
| 47 | + return DispatchEventResult.CanceledBeforeDispatch; |
| 48 | + } |
| 49 | + __start() { |
| 50 | + const { rpc, receiveEventEndpoint } = this._config; |
| 51 | + rpc.registerHandler(receiveEventEndpoint, ({ type, data }) => { |
| 52 | + super.dispatchEvent(new MessageEvent(type, { data: data ?? {} })); |
| 53 | + }); |
| 54 | + } |
| 55 | +} |
0 commit comments