1/* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, 13 * software distributed under the License is distributed on an 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 * KIND, either express or implied. See the License for the 16 * specific language governing permissions and limitations 17 * under the License. 18 */ 19/* 20 * 2021.01.08 - Add fireEventSync event to eventHandlers and page.destroyed judgment to 'receiveTasks'. 21 * Copyright (c) 2021 Huawei Device Co., Ltd. 22 */ 23 24import { Log } from '../../../utils/index'; 25import { App } from '../../app/App'; 26import Page from '../../page'; 27import { 28 fireEvent, 29 callback, 30 fireEventSync, 31 destroy 32} from '../../page/api/index'; 33 34const pageMap: Map<string, Page> = App.pageMap; 35 36const eventHandlers = { 37 /** 38 * Invoke the fireEvent function. 39 * @param {string} id - Page id. 40 * @param {*} args - Args. 41 */ 42 fireEvent: (id: string, ...args: any[]) => { 43 return fireEvent(pageMap.get(id), ...args); 44 }, 45 46 /** 47 * Invoke the callback function. 48 * @param {string} id - Page id. 49 * @param {*} args - Args 50 */ 51 callback: (id: string, ...args: any[]) => { 52 return callback(pageMap.get(id), ...args); 53 }, 54 55 /** 56 * Invoke the fireEventSync function. 57 * @param {string} id - Page id. 58 * @param {*} args - Args. 59 */ 60 fireEventSync: (id: string, ...args: any[]) => { 61 return fireEventSync(pageMap.get(id), ...args); 62 } 63}; 64 65/** 66 * Accept calls from native (event or callback). 67 * @param {string} id - Page id. 68 * @param {*} tasks list with `method` and `args`. 69 * @return {*} 70 */ 71export function receiveTasks(id: string, tasks: any[]): any[] | Error { 72 id = id.toString(); 73 Log.debug(`ReceiveTasks id ${id}, tasks: ${JSON.stringify(tasks)}`); 74 const page: Page = pageMap.get(id); 75 if (page && Array.isArray(tasks)) { 76 const results = []; 77 tasks.forEach((task) => { 78 const handler = eventHandlers[task.method]; 79 const args = [...task.args]; 80 if (typeof handler === 'function') { 81 args.unshift(id); 82 results.push(handler(...args)); 83 } 84 }); 85 if (page.destroyed && page.doc.taskCenter.callbackIsEmpty()) { 86 page.callTasks([{ 87 module: 'internal.jsResult', 88 method: 'appDestroyFinish', 89 args: [] 90 }]); 91 destroy(page); 92 pageMap.delete(id); 93 } 94 return results; 95 } 96 return new Error(`Invalid page id '${id}' or tasks.`); 97} 98