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 { PageLinkedMap } from '../../app/map'; 27import Page from '../../page'; 28import { 29 fireEvent, 30 callback, 31 fireEventSync, 32 destroy 33} from '../../page/api/index'; 34 35const pageMap: PageLinkedMap = App.pageMap; 36 37const eventHandlers = { 38 /** 39 * Invoke the fireEvent function. 40 * @param {string} id - Page id. 41 * @param {*} args - Args. 42 */ 43 fireEvent: (id: string, ...args: any[]) => { 44 return fireEvent(pageMap[id], ...args); 45 }, 46 47 /** 48 * Invoke the callback function. 49 * @param {string} id - Page id. 50 * @param {*} args - Args 51 */ 52 callback: (id: string, ...args: any[]) => { 53 return callback(pageMap[id], ...args); 54 }, 55 56 /** 57 * Invoke the fireEventSync function. 58 * @param {string} id - Page id. 59 * @param {*} args - Args. 60 */ 61 fireEventSync: (id: string, ...args: any[]) => { 62 return fireEventSync(pageMap[id], ...args); 63 } 64}; 65 66/** 67 * Accept calls from native (event or callback). 68 * @param {string} id - Page id. 69 * @param {*} tasks list with `method` and `args`. 70 * @return {*} 71 */ 72export function receiveTasks(id: string, tasks: any[]): any[] | Error { 73 id = id.toString(); 74 Log.debug(`ReceiveTasks id ${id}, tasks: ${JSON.stringify(tasks)}`); 75 const page: Page = pageMap[id]; 76 if (page && Array.isArray(tasks)) { 77 const results = []; 78 tasks.forEach((task) => { 79 const handler = eventHandlers[task.method]; 80 const args = [...task.args]; 81 if (typeof handler === 'function') { 82 args.unshift(id); 83 results.push(handler(...args)); 84 } 85 }); 86 if (page.destroyed && page.doc.taskCenter.callbackIsEmpty()) { 87 page.callTasks([{ 88 module: 'internal.jsResult', 89 method: 'appDestroyFinish', 90 args: [] 91 }]); 92 destroy(page); 93 pageMap.remove(page); 94 } 95 return results; 96 } 97 return new Error(`Invalid page id '${id}' or tasks.`); 98} 99