AIChatContentChild.sys.mjs (2345B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 const lazy = {}; 6 ChromeUtils.defineESModuleGetters(lazy, {}); 7 8 /** 9 * Represents a child actor for getting page data from the browser. 10 */ 11 export class AIChatContentChild extends JSWindowActorChild { 12 static #EVENT_MAPPINGS_FROM_PARENT = { 13 "AIChatContent:DispatchMessage": { 14 event: "aiChatContentActor:message", 15 }, 16 }; 17 18 static #VALID_EVENTS_FROM_CONTENT = new Set(["AIChatContent:DispatchSearch"]); 19 20 /** 21 * Receives event from the content process and sends to the parent. 22 * 23 * @param {CustomEvent} event 24 */ 25 handleEvent(event) { 26 if (!AIChatContentChild.#VALID_EVENTS_FROM_CONTENT.has(event.type)) { 27 console.warn(`AIChatContentChild received unknown event: ${event.type}`); 28 return; 29 } 30 31 switch (event.type) { 32 case "AIChatContent:DispatchSearch": 33 this.#handleSearchDispatch(event); 34 break; 35 36 default: 37 console.warn( 38 `AIChatContentChild received unknown event: ${event.type}` 39 ); 40 } 41 } 42 43 #handleSearchDispatch(event) { 44 this.sendAsyncMessage("aiChatContentActor:search", event.detail); 45 } 46 47 async receiveMessage(message) { 48 const mapping = 49 AIChatContentChild.#EVENT_MAPPINGS_FROM_PARENT[message.name]; 50 51 if (!mapping) { 52 console.warn( 53 `AIChatContentChild received unknown message: ${message.name}` 54 ); 55 return undefined; 56 } 57 58 const payload = message.data; 59 return this.#dispatchToChatContent(mapping.event, payload); 60 } 61 62 #dispatchToChatContent(eventName, payload) { 63 try { 64 const chatContent = this.document.querySelector("ai-chat-content"); 65 66 if (!chatContent) { 67 console.error(`No ai-chat-content element found for ${eventName}`); 68 return false; 69 } 70 71 const clonedPayload = Cu.cloneInto(payload, this.contentWindow); 72 73 const event = new this.contentWindow.CustomEvent(eventName, { 74 detail: clonedPayload, 75 bubbles: true, 76 }); 77 78 chatContent.dispatchEvent(event); 79 return true; 80 } catch (error) { 81 console.error(`Error dispatching ${eventName} to chat content:`, error); 82 return false; 83 } 84 } 85 }