Signed-off-by: zhongjianfei <zhongjianfei@huawei.com>
Change-Id: I8f85afce8872ae510c2819979d8930db8a3e3519
This commit is contained in:
zhongjianfei 2021-09-14 15:37:45 +08:00
parent e95d05a23f
commit 707783f3a0
87 changed files with 9116 additions and 686 deletions

14
.babelrc Normal file
View File

@ -0,0 +1,14 @@
{
"presets": [
[
"env",
{
"modules": false
}
]
],
"plugins": [
"external-helpers"
]
}

View File

@ -90,7 +90,8 @@
"wrap-iife": [2, "any"],
"no-var": 2,
"prefer-const": 2,
"array-bracket-spacing": 2
"array-bracket-spacing": 2,
"no-useless-escape": 0
},
"settings": {

146
BUILD.gn
View File

@ -11,31 +11,44 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import("//ark/ts2abc/ts2panda/ts2abc_config.gni")
import("//build/ohos.gni")
import("//foundation/ace/ace_engine/ace_config.gni")
prebuilt_js_path =
get_label_info(":gen_jsf_c", "root_out_dir") + "/dist/strip.native.min.js"
get_label_info(":gen_jsf_c", "target_out_dir") + "/dist/strip.native.min.js"
snapshot_path =
get_label_info(":gen_snapshot", "target_out_dir") + "/strip.native.min.js"
#snapshot_path =
# get_label_info(":gen_snapshot", "target_out_dir") + "/strip.native.min.js"
action("gen_node_modules") {
script = "//third_party/jsframework/prebuild_env.sh"
args = []
inputs = [
"package.json",
"package-lock.json",
]
outputs = [ "$root_out_dir/jsframework/node_modules" ]
}
action("gen_snapshot") {
script = "//third_party/jsframework/js_framework_build.sh"
deps = [ ":gen_node_modules" ]
js_framework = "//third_party/jsframework/runtime"
is_mac = "false"
node_modules = "//prebuilts/build-tools/common/js-framework/node_modules"
nodejs_path = "//prebuilts/build-tools/common/nodejs/node-v12.18.4-linux-x64"
buildfile = "//third_party/jsframework/build.js"
package_file = "//third_party/jsframework/package.json"
tsconfig = "//third_party/jsframework/tsconfig.json"
eslint = "//third_party/jsframework/.eslintrc"
babel = "//third_party/jsframework/.babelrc"
test_file = "//third_party/jsframework/test"
nodejs_path =
"//prebuilts/build-tools/common/nodejs/node-v12.18.4-linux-x64/bin/node"
args = [
rebase_path(buildfile, root_build_dir),
rebase_path(nodejs_path, root_build_dir),
@ -45,9 +58,107 @@ action("gen_snapshot") {
rebase_path(tsconfig, root_build_dir),
rebase_path(eslint, root_build_dir),
rebase_path(test_file, root_build_dir),
rebase_path(target_out_dir, root_build_dir),
rebase_path(babel, root_build_dir),
is_mac,
]
outputs = [ snapshot_path ]
inputs = [
# app
"runtime/main/app/App.ts",
"runtime/main/app/bundle.ts",
"runtime/main/app/helper.ts",
"runtime/main/app/index.ts",
"runtime/main/app/map.ts",
# plugin
"runtime/main/extend/dpi/Dpi.ts",
"runtime/main/extend/dpi/index.ts",
"runtime/main/extend/i18n/I18n.ts",
"runtime/main/extend/i18n/index.ts",
"runtime/main/extend/mediaquery/mediaQuery.ts",
"runtime/main/extend/mediaquery/pluginMediaQuery.ts",
"runtime/main/extend/mediaquery/plugins.ts",
# manage event
"runtime/main/manage/event/bridge.ts",
"runtime/main/manage/event/callbackIntercept.ts",
"runtime/main/manage/event/CallbackManager.ts",
"runtime/main/manage/event/TaskCenter.ts",
# manage instance
"runtime/main/manage/instance/life.ts",
"runtime/main/manage/instance/misc.ts",
"runtime/main/manage/instance/register.ts",
# vdom
"runtime/main/model/compiler.ts",
"runtime/main/model/directive.ts",
"runtime/main/model/domHelper.ts",
"runtime/main/model/events.ts",
"runtime/main/model/index.ts",
"runtime/main/model/pageLife.ts",
"runtime/main/model/selector.ts",
"runtime/main/model/vmOptions.ts",
# page
"runtime/main/page/api/Differ.ts",
"runtime/main/page/api/index.ts",
"runtime/main/page/api/misc.ts",
"runtime/main/page/entry/bundle.ts",
"runtime/main/page/entry/init.ts",
"runtime/main/page/Image.ts",
"runtime/main/page/index.ts",
"runtime/main/page/Page.ts",
"runtime/main/page/register.ts",
# third reactivity
"runtime/main/reactivity/array.js",
"runtime/main/reactivity/dep.js",
"runtime/main/reactivity/object.js",
"runtime/main/reactivity/observer.js",
"runtime/main/reactivity/state.js",
"runtime/main/reactivity/watcher.js",
# third util
"runtime/main/util/index.js",
"runtime/main/util/props.js",
"runtime/main/util/shared.js",
# framework expose
"runtime/main/config.ts",
"runtime/main/index.ts",
# preparation of init framework
"runtime/preparation/index.ts",
"runtime/preparation/init.ts",
"runtime/preparation/methods.ts",
"runtime/preparation/service.ts",
# utils
"runtime/utils/index.ts",
"runtime/utils/utils.ts",
# vdom
"runtime/vdom/Comment.ts",
"runtime/vdom/Document.ts",
"runtime/vdom/DocumentElement.ts",
"runtime/vdom/Element.ts",
"runtime/vdom/index.ts",
"runtime/vdom/NativeElementClassFactory.ts",
"runtime/vdom/Node.ts",
# global
"runtime/lib.d.ts",
# config of compiler
".babelrc",
".eslintrc",
"build.js",
"tsconfig.json",
"tslint.json",
]
outputs = [ prebuilt_js_path ]
}
jsfc_path = get_label_info(":jsf", "target_out_dir") + "/src/jsf.c"
@ -70,7 +181,7 @@ action("gen_jsf_c") {
rebase_path(prebuilt_js_path),
]
inputs = [ snapshot_path ]
inputs = [ prebuilt_js_path ]
outputs = [ jsfc_path ]
}
@ -78,3 +189,22 @@ ohos_static_library("jsf") {
deps = [ ":gen_jsf_c" ]
sources = [ jsfc_path ]
}
ark_abc_path =
get_label_info(":ark_build", "target_out_dir") + "/strip.native.min.abc"
ts2abc_gen_abc("ark_jsf") {
extra_visibility = [ ":*" ] # Only targets in this file can depend on this
extra_dependencies = [ ":gen_snapshot" ]
src_js = rebase_path(prebuilt_js_path)
dst_file = rebase_path(ark_abc_path)
in_puts = [ prebuilt_js_path ]
out_puts = [ ark_abc_path ]
}
ohos_prebuilt_etc("ark_built") {
deps = [ ":ark_jsf" ]
source = ark_abc_path
}

View File

@ -25,7 +25,7 @@ const commonjs = require('rollup-plugin-commonjs');
const json = require('rollup-plugin-json');
const buble = require('rollup-plugin-buble');
const babel = require('rollup-plugin-babel');
const typescript = require('rollup-plugin-typescript2');
@ -58,7 +58,32 @@ const esPlugin = eslint({
const configInput = {
input: path.resolve(__dirname, 'runtime/preparation/index.ts'),
onwarn,
plugins: [esPlugin, tsPlugin, json(), resolve(), commonjs(), buble(), uglify()]
plugins: [
esPlugin,
tsPlugin,
json(),
resolve(),
commonjs(),
babel({
exclude: 'node_moduels/**'
}),
uglify()
]
};
const configJSAPIMockInput = {
input: path.resolve(__dirname, 'runtime/main/extend/systemplugin/entry.js'),
onwarn,
plugins: [
esPlugin,
tsPlugin,
json(),
resolve(),
commonjs(),
babel({
exclude: 'node_moduels/**'
})
]
};
const configOutput = {
@ -67,12 +92,23 @@ const configOutput = {
banner: frameworkBanner
};
const configJSAPIMockOutput = {
file: path.resolve(__dirname, 'dist/jsMockSystemPlugin.js'),
format: 'umd'
};
rollup.rollup(configInput).then(bundle => {
bundle.write(configOutput).then(() => {
countSize(configOutput.file);
});
});
rollup.rollup(configJSAPIMockInput).then(bundle => {
bundle.write(configJSAPIMockOutput).then(() => {
countSize(configJSAPIMockOutput.file);
});
});
function countSize(filePath) {
const file = path.relative(__dirname, filePath);
fs.stat(filePath, function(error, stats) {

17
gen_snapshot.sh Normal file
View File

@ -0,0 +1,17 @@
#!/bin/bash
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
rm -rf ./gen/third_party/jsframework/snapshot
LD_LIBRARY_PATH=./clang_x64/ark/ark:./clang_x64/global/i18n:./../../libs/android_libs/ndk/libcxx/linux_x86:./../../libs/android_libs/ndk/libcxx/linux_x86_64:./../../libs/android_libs/ndk/libcxx/aosp_x86_64:./../../prebuilts/clang/ohos/linux-x86_64/llvm/lib/:$LD_LIBRARY_PATH $@
echo "general snapshot file"

View File

@ -1,3 +1,4 @@
#!/bin/bash
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -11,37 +12,51 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#! /bin/bash
set -e
echo "copy source code..."
prebuiltsPath="../../prebuilts"
prebuilts_path="../../prebuilts"
# copy dependency file to generate dir of gn
# the params come from .gn
# $2 => node $4 => node_modules
cp -r $3 ./
cp -f $5 ./
cp -r $3 $9
cp -f $5 $9
if [ -d "$prebuiltsPath" ]; then
if [ -d "$prebuilts_path" ]; then
echo "copy node_modules..."
cp -r $4 ./
if [ "${11}" == 'true' ];then
cp -R $4 $9
else
cp -r $4 $9
fi
else
echo "download node_modules..."
npm install
cp -r ./node_modules ../../third_party/jsframework
fi
cp -f $6 ./
cp -f $7 ./
cp -f $1 ./
cp -r $8 ./
cp -f $6 $9
cp -f $7 $9
cp -f ${10} $9
cp -f $1 $9
cp -r $8 $9
if [ -d "$prebuiltsPath" ]; then
if [ -d "$prebuilts_path" ]; then
echo "prebuilts exists"
$2 build.js
# run unit test
$2 ./node_modules/.bin/mocha -r ts-node/register test/lib.ts test/ut/**/*.ts test/ut/*.ts
# address problme of parallzing compile
rm -rf "$9/node-v12.18.4-linux-x64"
rm -rf "$9/node-v12.18.4-darwin-x64"
cp -r $2 $9
cd $9
if [ "${11}" == 'true' ];then
./node-v12.18.4-darwin-x64/bin/node build.js
# run unit test
./node-v12.18.4-darwin-x64/bin/node node_modules/.bin/mocha -r ts-node/register test/lib.ts test/ut/**/*.ts test/ut/*.ts
else
./node-v12.18.4-linux-x64/bin/node build.js
# run unit test
./node-v12.18.4-linux-x64/bin/node node_modules/.bin/mocha -r ts-node/register test/lib.ts test/ut/**/*.ts test/ut/*.ts
fi
else
npm run build
# run unit test
@ -50,9 +65,15 @@ fi
# after running, remove dependency file
rm -rf ./node_modules
if [ "${11}" == 'true' ];then
rm -rf ./node-v12.18.4-darwin-x64
else
rm -rf ./node-v12.18.4-linux-x64
fi
rm -rf ./runtime
rm -rf ./tsconfig.json
rm -rf ./build.js
rm -rf ./test
rm -rf ./.eslintrc
rm -rf ./.babelrc
rm -rf ./package.json

4109
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -20,24 +20,28 @@
"css-what": "2.1.3"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "4.8.2",
"@typescript-eslint/parser": "4.8.2",
"buble": "0.20.0",
"chai": "4.2.0",
"eslint": "7.14.0",
"mocha": "8.2.1",
"rollup": "2.32.1",
"rollup-plugin-buble": "0.19.8",
"rollup-plugin-commonjs": "10.1.0",
"rollup-plugin-eslint": "7.0.0",
"rollup-plugin-json": "4.0.0",
"rollup-plugin-node-resolve": "5.2.0",
"rollup-plugin-tslint": "0.2.2",
"rollup-plugin-typescript2": "0.9.0",
"rollup-plugin-uglify": "6.0.4",
"sinon": "9.2.2",
"ts-node": "9.0.0",
"tslib": "2.0.3",
"typescript": "4.1.2"
"@typescript-eslint/eslint-plugin": "^4.8.2",
"@typescript-eslint/parser": "^4.8.2",
"babel-core": "^6.26.3",
"babel-loader": "^6.4.1",
"babel-plugin-external-helpers": "^6.22.0",
"babel-preset-env": "^1.7.0",
"babel-runtime": "^6.26.0",
"chai": "^4.2.0",
"eslint": "^7.14.0",
"mocha": "^8.2.1",
"rollup": "^2.32.1",
"rollup-plugin-babel": "^3.0.7",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-eslint": "^7.0.0",
"rollup-plugin-json": "^4.0.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-tslint": "^0.2.2",
"rollup-plugin-typescript2": "^0.9.0",
"rollup-plugin-uglify": "^6.0.4",
"sinon": "^9.2.2",
"ts-node": "^9.0.0",
"tslib": "^2.0.3",
"typescript": "^4.1.2"
}
}

34
prebuild_env.sh Executable file
View File

@ -0,0 +1,34 @@
#!/bin/bash
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -e
script_path=$(cd $(dirname $0);pwd)
code_dir=$(dirname ${script_path})/../
cd ${code_dir}/third_party/jsframework/
export PATH=${code_dir}/prebuilts/build-tools/common/nodejs/node-v12.18.4-linux-x64/bin:$PATH
npm config set registry http://registry.npm.taobao.org
npm install
cd ${code_dir}
if [ -d "${code_dir}/prebuilts/build-tools/common/js-framework" ]; then
echo -e "\n"
echo "${code_dir}/prebuilts/build-tools/common/js-framework already exist, it will be replaced with node-${node_js_ver}"
/bin/rm -rf ${code_dir}/prebuilts/build-tools/common/js-framework
echo -e "\n"
fi
mkdir -p ${code_dir}/prebuilts/build-tools/common/js-framework
/bin/cp -rf ${code_dir}/third_party/jsframework/node_modules ${code_dir}/prebuilts/build-tools/common/js-framework/

View File

@ -37,7 +37,7 @@ import { updateLocale, updateDpi } from './index';
import Page from '../page/index';
import { App } from './App';
const APP_LIFE_CYCLE_TYPES: string[] = ['onCreate', 'onError', 'onDestroy'];
const APP_LIFE_CYCLE_TYPES: string[] = ['onCreate', 'onError', 'onDestroy', 'onShow', 'onHide'];
/**
* Parse app page code.
@ -98,6 +98,10 @@ export function bootstrap(page: Page, packageName: string, name: string, config:
// Init global data when page first load,
// global.aceapp.$data means config.data in manifest.json, can add new data by this.$app.$data api.
if (page.options && page.options.appCreate) {
const getApp = function() {
return global.aceapp;
};
global.getApp = getApp;
global.aceapp = {};
global.aceapp.$data = page.options.appGlobalData || {};

View File

@ -24,7 +24,7 @@ import { getPageGlobal } from './helper';
import { App } from './App';
import Page from '../page/index';
import { destroy } from '../page/api/index';
import { mockSystemPlugin } from '../extend/systemplugin/systemPlugins';
import { mockSystemPlugin } from '../extend/systemplugin/index';
import { compileBundle } from '../page/entry/init';
import { removePrefix } from '../util/index';
import { requireModule } from '../page/register';
@ -43,6 +43,7 @@ export interface MediaQueryInfo {
'isInit': boolean;
'resolution': string;
'aspectRatio': string;
'darkMode': string;
}
/**
@ -52,7 +53,7 @@ export interface Options extends MediaQueryInfo {
'appInstanceId': string;
'packageName': string;
'appCreate': boolean;
'appCode': string;
'appCode': string | Function;
'pcPreview': string;
'resourcesConfiguration': object;
'i18n': object;
@ -93,13 +94,13 @@ export function appCreate(page: Page, options: Options, data: object, services:
mockSystemPlugin();
}
const packageName: string = page.packageName;
const appPage: Page = new Page(options.appInstanceId, options, packageName);
const appPage: Page = new Page(options.appInstanceId, options, packageName, data);
pageMap.set(appPage.id, appPage);
Log.debug(`Create a page with: ${packageName}.`);
appMap[packageName] = new App(packageName, options.appInstanceId);
const timerAPIs: object = genTimerAPI(appPage);
appMap[packageName].setTimer(timerAPIs);
const code: string = options.appCode;
const code = options.appCode;
global.__appProto__ = getPageGlobal(packageName);
// prepare page env methods
@ -117,11 +118,15 @@ export function appCreate(page: Page, options: Options, data: object, services:
$app_require$: appRequireModule
};
// Function with code and use strict mode.
const functionCode: string = `(function(global){\n\n"use strict";\n\n ${code} \n\n})(this.__appProto__)`;
// Compile js bundle code and get result.
compileBundle(functionCode, 'app.js', parseOptions, timerAPIs, services);
if (typeof code === 'function') {
Log.info('call Function directly when appCreate');
code.call(global, parseOptions);
} else {
// Function with code and use strict mode.
const functionCode: string = `(function(global){\n\n"use strict";\n\n ${code} \n\n})(this.__appProto__)`;
compileBundle(functionCode, 'app.js', parseOptions, timerAPIs, services);
}
}
/**
@ -140,6 +145,34 @@ export function appError(packageName: string, errors: any): void {
app.emitEvent('hook:onError', errors);
}
/**
* Emit onShow event.
* @param {string} packageName - Package name.
*/
export function appShow(packageName: string): void {
Log.debug(`Show an app with: ${packageName}.`);
const app: App = appMap[packageName];
if (!app) {
Log.debug(`Show an app error ${packageName}.`);
return;
}
app.emitEvent('hook:onShow');
}
/**
* Emit onHide event.
* @param {string} packageName - Package name.
*/
export function appHide(packageName: string): void {
Log.debug(`Hide an app with: ${packageName}.`);
const app: App = appMap[packageName];
if (!app) {
Log.debug(`Hide an app error ${packageName}.`);
return;
}
app.emitEvent('hook:onHide');
}
/**
* Emit onDestroy event.
* @param {string} packageName - Package name.

View File

@ -16,16 +16,19 @@
import { Log } from '../../../utils/index';
const MEDIA_QUERY_RULE = {
CONDITION_WITH_SCREEN: /^(((only|not)screen)|screen)((and|or|,)\([\w.:><=-]+\))*$/,
CONDITION_WITHOUT_SCREEN: /^\([\w.:><=-]+\)((and|or|,)\([\w.:><=-]+\))*$/,
CONDITION_WITH_AND: /^\([.a-z0-9:>=<-]+\)(and\([.a-z0-9:>=<-]+\))+/,
CSS_LEVEL4_MULTI: /^\(([\d.]+(dpi|dppx|dpcm|px)?)(>|<|>=|<=)[a-z0-9:-]+(>|<|>=|<=)([\d.]+(dpi|dppx|dpcm|px)?)\)$/,
CSS_LEVEL4_LEFT: /^\([^m][a-z-]+(>|<|>=|<=)[\d.]+(dpi|dppx|dpcm|px)?\)$/,
CSS_LEVEL4_RIGHT: /^\([\d.]+(dpi|dppx|dpcm|px)?(>|<|>=|<=)[^m][a-z-]+\)$/,
CSS_LEVEL3_RULE: /^\((min|max)-[a-z-]+:[\d.]+(dpi|dppx|dpcm)?\)$/,
CONDITION_WITH_SCREEN: /^(((only|not)screen)|screen)((and|or|,)\([\w\/\.:><=-]+\))*$/,
CONDITION_WITHOUT_SCREEN: /^\([\w\/\.:><=-]+\)((and|or|,)\([\w\/\.:><=-]+\))*$/,
CONDITION_WITH_AND: /^\([\/\.a-z0-9:>=<-]+\)(and\([\/\.a-z0-9:>=<-]+\))+/,
CSS_LEVEL4_MULTI: /^\(([\d\.]+(dpi|dppx|dpcm|px)?)(>|<|>=|<=)[a-z0-9:-]+(>|<|>=|<=)([\d\.]+(dpi|dppx|dpcm|px)?)\)$/,
CSS_LEVEL4_LEFT: /^\([^m][a-z-]+(>|<|>=|<=)[\d\.]+(dpi|dppx|dpcm|px)?\)$/,
CSS_LEVEL4_RIGHT: /^\([\d\.]+(dpi|dppx|dpcm|px)?(>|<|>=|<=)[^m][a-z-]+\)$/,
CSS_LEVEL3_RULE: /^\((min|max)-[a-z-]+:[\d\.]+(dpi|dppx|dpcm|px)?\)$/,
ORIENTATION_RULE: /^\(orientation:[a-z]+\)/,
DEVICETYPE_RULE: /^\(device-type:[a-z]+\)/,
SCREEN_SHAPE_RULE: /^\(round-screen:[a-z]+\)/
SCREEN_SHAPE_RULE: /^\(round-screen:[a-z]+\)/,
DARK_MODE: /^\(dark-mode:[a-z]+\)/,
ASPECT_RATIO: /^\((min|max)?-?(device)?-?aspect-ratio:[\d(\/)?(\d)*]+\)/,
PATTERN: /^\(pattern:[a-z]+\)/
};
/**
@ -181,6 +184,18 @@ function parseSingleCondition(condition: string, mediaStatus: object, failReason
if (parseScreenShapeCondition(condition, mediaStatus, failReason)) {
return true;
}
} else if (MEDIA_QUERY_RULE.DARK_MODE.exec(condition)) {
if (parseDarkModeCondition(condition, mediaStatus, failReason)) {
return true;
}
} else if (MEDIA_QUERY_RULE.ASPECT_RATIO.exec(condition)) {
if (parseAspectRatioCondition(condition, mediaStatus, failReason)) {
return true;
}
} else if (MEDIA_QUERY_RULE.PATTERN.exec(condition)) {
if (parsePatternCondition(condition, mediaStatus, failReason)) {
return true;
}
} else {
Log.debug('Illegal condition');
failReason.type = MEDIAERROR.SYNTAX;
@ -309,6 +324,42 @@ function parseCss3Condition(condition: string, mediaStatus: object, failReason:
return calculateExpression(statusValue, relationship, conditionValue, failReason);
}
/**
* Parse paatern style condition, such as: (pattern: normal).
* @param {String} condition - pattern style condition.
* @param {Object} mediaStatus - Device info.
* @param {FailReason} failReason - Parse fail reason.
* @return {boolean}
*/
function parsePatternCondition(condition: string, mediaStatus: object, failReason: FailReason): boolean {
const pattern = condition.match(/[a-z-]+/g);
if (!pattern || pattern.length !== 2) {
failReason.type = MEDIAERROR.SYNTAX;
return false;
}
return getVpType(mediaStatus['resolution'], mediaStatus['width']) === pattern[1];
}
/**
* get the type of vp.
* @param {number} resolution - the resolution of device.
* @param {number} width - the width of view page.
*/
function getVpType(resolution: number, width: number): string {
const value = width / resolution;
if (value > 0 && value < 320) {
return 'small';
} else if (value >= 320 && value < 600) {
return 'normal';
} else if (value >= 600 && value < 840) {
return 'large';
} else if (value >= 840) {
return 'xLarge';
} else {
return '';
}
}
/**
* Parse screen orientation condition, such as: (orientation: portrait).
* @param {string} condition - Orientation type condition.
@ -357,6 +408,56 @@ function parseScreenShapeCondition(condition: string, mediaStatus: object, failR
return shape[1] === mediaStatus['round-screen'].toString();
}
/**
* parse dark mode condition, such as: (dark-mode: true)
* @param {String} condition: dark condition
* @param {Object} mediaStatus: device info
* @param {Object} failReason: parse fail reason
*/
function parseDarkModeCondition(condition: string, mediaStatus: object, failReason: FailReason): boolean {
const darkMode = condition.match(/[a-z-]+/g);
if (!darkMode || darkMode.length !== 2) {
failReason.type = MEDIAERROR.SYNTAX;
return false;
}
return darkMode[1] === mediaStatus['dark-mode'].toString();
}
/**
* parse aspect ratio condition, such as: (aspect-ratio: 8/3)
* @param {String} condition: (device)?-aspect-ratio condition
* @param {Object} mediaStatus: aspect-ratio, device-width, device-height
* @param {Object} failReason: parse fail reason
*/
function parseAspectRatioCondition(condition: string, mediaStatus: object, failReason: FailReason): boolean {
let conditionValue;
const aspectRatio = condition.match(/[a-z-\d-\/]+/g);
let relationship;
if (aspectRatio[0].match(/^(max-)/)) {
relationship = '<=';
} else if (aspectRatio[0].match(/^(min-)/)) {
relationship = '>=';
} else {
relationship = '==';
}
let statusValue;
if (aspectRatio[0].match(/device/)) {
Log.info('query device status');
statusValue = mediaStatus['device-width'] / mediaStatus['device-height'];
} else {
Log.info('query page status');
statusValue = mediaStatus['aspect-ratio'];
}
const numbers = aspectRatio[1].split('/');
if (numbers.length === 2) {
conditionValue = parseInt(numbers[0]) / parseInt(numbers[1]);
} else {
failReason.type = MEDIAERROR.SYNTAX;
return false;
}
return calculateExpression(statusValue, relationship, conditionValue, failReason);
}
/**
* Transfer unit the same with condition value unit.
* @param {number} value - Device value should be transfer unit the same with condition value.
@ -396,6 +497,9 @@ function calculateExpression(leftValue: number | string, relationship: string,
} else if (typeof rightValue === 'string') {
lvalue = leftValue;
rvalue = rightValue.match(/[\d]+\.[\d]+/) ? parseFloat(rightValue) : parseInt(rightValue);
} else if (typeof rightValue === 'number') {
lvalue = leftValue;
rvalue = rightValue;
} else {
failReason.type = MEDIAERROR.SYNTAX;
return false;
@ -409,6 +513,8 @@ function calculateExpression(leftValue: number | string, relationship: string,
return lvalue <= rvalue;
case '<':
return lvalue < rvalue;
case '==':
return lvalue === rvalue;
default:
failReason.type = MEDIAERROR.SYNTAX;
}

View File

@ -95,6 +95,7 @@ export class MediaQueryApi {
data['device-width'] = data.deviceWidth;
data['device-height'] = data.deviceHeight;
data['round-screen'] = data.roundScreen;
data['dark-mode'] = data.darkMode;
for (let i = 0; i < this._mqlArray.length; i++) {
const mediaQueryList:MediaQueryList = this._mqlArray[i];
const result: boolean = matchMediaQueryCondition(mediaQueryList.condition, data, true);

View File

@ -0,0 +1,336 @@
import { paramMock } from "./utils"
export function mockAbilityFeatureAbility() {
global.systemplugin.ability = {}
const WantMock = {
deviceId: "[PC Preview] unknow deviceId",
bundleName: "[PC Preview] unknow bundleName",
abilityName: "[PC Preview] unknow abilityName",
uri: "[PC Preview] unknow uri",
type: "[PC Preview] unknow type",
flag: "[PC Preview] unknow flag",
action: "[PC Preview] unknow action",
parameters: "[PC Preview] unknow parameters",
entities: "[PC Preview] unknow entities"
}
const AbilityResultMock = {
resultCode: "[PC Preview] unknow resultCode",
want: WantMock
}
const DataAbilityHelperMock = {
openFile: function (...args) {
console.warn("DataAbilityHelper.openFile interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramNumberMock)
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramNumberMock);
})
}
},
on: function (...args) {
console.warn("DataAbilityHelper.on interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
}
},
off: function (...args) {
console.warn("DataAbilityHelper.off interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
}
},
call: function (...args) {
console.warn("DataAbilityHelper.call interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramObjectMock)
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramObjectMock);
})
}
}
}
const ContextMock = {
getCacheDir: function (...args) {
console.warn("Context.getCacheDir interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock)
} else {
return new Promise((resolve) => {
resolve("[PC Preview] unknow string")
})
}
},
getFilesDir: function (...args) {
console.warn("Context.getFilesDir interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock)
} else {
return new Promise((resolve) => {
resolve("[PC Preview] unknow string")
})
}
},
getExternalCacheDir: function (...args) {
console.warn("Context.getExternalCacheDir interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock)
} else {
return new Promise((resolve) => {
resolve("[PC Preview] unknow string")
})
}
}
}
global.systemplugin.ability.featureAbility = {
getWant: function (...args) {
console.warn("ability.featureAbility.getWant interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, WantMock)
} else {
return new Promise((resolve) => {
resolve(WantMock)
})
}
},
startAbility: function (...args) {
console.warn("ability.featureAbility.startAbility interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramNumberMock)
} else {
return new Promise((resolve) => {
resolve(paramMock.paramNumberMock)
})
}
},
startAbilityForResult: function (...args) {
console.warn("ability.featureAbility.startAbilityForResult interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, AbilityResultMock)
} else {
return new Promise((resolve) => {
resolve(AbilityResultMock)
})
}
},
terminateSelfWithResult: function (...args) {
console.warn("ability.featureAbility.terminateSelfWithResult interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
terminateSelf: function (...args) {
console.warn("ability.featureAbility.terminateSelf interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
acquireDataAbilityHelper: function (...args) {
console.warn("ability.featureAbility.acquireDataAbilityHelper mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
return DataAbilityHelperMock;
},
getContext: function () {
console.warn("ability.featureAbility.getContext interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
return ContextMock;
}
}
}
export function mockAbilityParticleAbility() {
global.systemplugin.ability.particleAbility = {
startAbility: function (...args) {
console.warn("ability.particleAbility.startAbility interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramNumberMock)
} else {
return new Promise((resolve) => {
resolve(paramMock.paramNumberMock)
})
}
}
}
}
export function mockAbilityFormManager() {
const FormInfoMock = {
bundleName: "[PC Preview] unknow bundleName",
moduleName: "[PC Preview] unknow moduleName",
abilityName: "[PC Preview] unknow abilityName",
name: "[PC Preview] unknow name",
description: "[PC Preview] unknow description",
type: "[PC Preview] unknow type",
jsComponentName: "[PC Preview] unknow jsComponentName",
colorMode: "[PC Preview] unknow colorMode",
isDefault: "[PC Preview] unknow isDefault",
updateEnabled: "[PC Preview] unknow updateEnabled",
formVisibleNotify: "[PC Preview] unknow formVisibleNotify",
relatedBundleName: "[PC Preview] unknow relatedBundleName",
scheduledUpdateTime: "[PC Preview] unknow scheduledUpdateTime",
formConfigAbility: "[PC Preview] unknow formConfigAbility",
updateDuration: "[PC Preview] unknow updateDuration",
defaultDimension: "[PC Preview] unknow defaultDimension",
supportDimensions: "[PC Preview] unknow supportDimensions",
customizeDatas: "[PC Preview] unknow customizeDatas",
jsonObject: "[PC Preview] unknow jsonObject"
}
const FormInfoArrayMock = [
FormInfoMock
]
global.systemplugin.ability.formManager = {
requestForm: function (...args) {
console.warn("ability.formManager.requestForm interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
deleteForm: function (...args) {
console.warn("ability.formManager.deleteForm interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
releaseForm: function (...args) {
console.warn("ability.formManager.releaseForm interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve) => {
resolve()
})
}
},
notifyVisibleForms: function (...args) {
console.warn("ability.formManager.notifyVisibleForms interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
notifyInvisibleForms: function (...args) {
console.warn("ability.formManager.notifyInvisibleForms interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
enableFormsUpdate: function (...args) {
console.warn("ability.formManager.enableFormsUpdate interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
disableFormsUpdate: function (...args) {
console.warn("ability.formManager.disableFormsUpdate interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
getAllFormsInfo: function (...args) {
console.warn("ability.formManager.getAllFormsInfo interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, FormInfoArrayMock)
} else {
return new Promise((resolve) => {
resolve(FormInfoArrayMock)
})
}
},
getFormsInfoByApp: function (...args) {
console.warn("ability.formManager.getFormsInfoByApp interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, FormInfoArrayMock)
} else {
return new Promise((resolve) => {
resolve(FormInfoArrayMock)
})
}
},
getFormsInfoByModule: function (...args) {
console.warn("ability.formManager.getFormsInfoByModule interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, FormInfoArrayMock)
} else {
return new Promise((resolve) => {
resolve(FormInfoArrayMock)
})
}
}
}
}

View File

@ -0,0 +1,30 @@
import { paramMock } from "./utils"
export function mockAccessibility() {
global.systemplugin.accessibility = {
isOpenAccessibility: function (...args) {
console.warn("accessibility.isOpenAccessibility interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock)
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramBooleanMock);
})
}
},
isOpenTouchExploration: function (...args) {
console.warn("accessibility.isOpenTouchExploration interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock)
} else {
return new Promise((resolve) => {
resolve(paramMock.paramBooleanMock);
})
}
}
}
}

View File

@ -0,0 +1,87 @@
import {paramMock} from "./utils"
export function mockAI() {
const TTSCallBackMock = {
key: "[PC preview] unknow key"
};
global.systemplugin.ai = {};
global.systemplugin.ai.TTS = {
getTTSClient: function () {
console.warn("ai.TTS.getTTSClient interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return TTSClient
},
};
const TTSClient = {
init: function (...args) {
console.warn("TTSClient.init interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramBooleanMock
},
isSpeaking: function () {
console.warn("TTSClient.isSpeaking interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramBooleanMock
},
setAudioType: function (...args) {
console.warn("TTSClient.setAudioType interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramBooleanMock
},
setParams: function (...args) {
console.warn("TTSClient.setParams interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramBooleanMock
},
connectService: function () {
console.warn("TTSClient.connectService interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
},
setIsSaveTtsData: function (...args) {
console.warn("TTSClient.setIsSaveTtsData interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
args[0].success()
hasComplete(args[0].complete)
},
release: function () {
console.warn("TTSClient.release interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
},
speakLongText: function (...args) {
console.warn("TTSClient.speakLongText interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
args[0].success()
hasComplete(args[0].complete)
},
speakText: function (...args) {
console.warn("TTSClient.speakText interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
args[0].success()
hasComplete(args[0].complete)
},
stopSpeak: function () {
console.warn("TTSClient.stopSpeak interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
},
destroy: function () {
console.warn("TTSClient.destroy interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
},
on: function (...args) {
console.warn("TTSClient.on interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
args[len - 1].call(this, TTSCallBackMock)
},
getSupportMaxLength: function () {
console.warn("TTSClient.getSupportMaxLength interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramNumberMock
},
getVersion: function () {
console.warn("TTSClient.getVersion interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramStringMock
},
};
}

View File

@ -0,0 +1,15 @@
import { hasComplete } from "./utils"
export function mockBattery() {
global.systemplugin.battery = {
getStatus: function (...args) {
console.warn("battery.getStatus interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
args[0].success.call(this, {
level: 1,
charging: false
})
hasComplete(args[0].complete)
}
}
}

View File

@ -0,0 +1,12 @@
export function mockOhosBatteryinfo() {
global.systemplugin.batteryInfo = {
batterySOC: "[PC Preview] unknow batterySOC",
chargingStatus: "[PC Preview] unknow chargingStatus",
healthStatus: "[PC Preview] unknow healthStatus",
pluggedType: "[PC Preview] unknow pluggedType",
voltage: "[PC Preview] unknow voltage",
technology: "[PC Preview] unknow technology",
batteryTemperature: "[PC Preview] unknow batteryTemperature",
isBatteryPresent: "[PC Preview] unknow isBatteryPresent"
}
}

View File

@ -0,0 +1,45 @@
import { hasComplete } from "./utils"
export function mockBluetooth() {
global.systemplugin.bluetooth = {
startBLEScan: function (...args) {
console.warn("bluetooth.startBLEScan interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
args[0].success()
hasComplete(args[0].complete)
},
stopBLEScan: function (...args) {
console.warn("bluetooth.stopBLEScan interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
args[0].success()
hasComplete(args[0].complete)
},
subscribeBLEFound: function (...args) {
console.warn("bluetooth.subscribeBLEFound interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const options = {
addrType: 'public',
addr: 'xx:xx:xx:xx',
rssi: 123,
txpower: 'xxx',
data: 'xxx'
}
const min = 1
const max = 6
clearInterval(this.unsubscribeBLE)
delete this.unsubscribeBLE
this.unsubscribeBLE = setInterval(() => {
const randomAddr = Math.floor(Math.random() * (max - min)) + min
const optionsArr = Array(randomAddr).fill(options)
args[0].success(optionsArr)
}, 1000)
},
unsubscribeBLEFound: function () {
console.warn("bluetooth.unsubscribeBLEFound interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
clearInterval(this.unsubscribeBLE)
delete this.unsubscribeBLE
}
}
}

View File

@ -0,0 +1,46 @@
import { hasComplete } from "./utils"
export function mockBrightness() {
global.systemplugin.brightness = {
argsV: {
value: 80
},
argsM: {
mode: 0
},
getValue: function (...args) {
console.warn("brightness.getValue interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
args[0].success(this.argsV)
hasComplete(args[0].complete)
},
setValue: function (...args) {
console.warn("brightness.setValue interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
if (args[0].value) {
this.argsV.value = args[0].value
args[0].success("brightness setValue successfully")
hasComplete(args[0].complete)
}
},
getMode: function (...args) {
console.warn("brightness.getMode interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
args[0].success(this.argsM)
hasComplete(args[0].complete)
},
setMode: function (...args) {
console.warn("brightness.setMode interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
this.argsM.mode = args[0].mode
args[0].success("brightness setMode successfully")
hasComplete(args[0].complete)
},
setKeepScreenOn: function (...args) {
console.warn("brightness.setKeepScreenOn interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
args[0].success("brightness setKeepScreenOn successfully")
hasComplete(args[0].complete)
}
}
}

View File

@ -0,0 +1,20 @@
import { hasComplete } from "./utils"
export function mockCipher() {
global.systemplugin.cipher = {
rsa: function(...args) {
console.warn("cipher.rsa interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const result = '[PC preview] rsa xxxxxxxxxxxxx'
args[0].success(result)
hasComplete(args[0].complete)
},
aes: function(...args) {
console.warn("cipher.aes interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const result = '[PC preview] aes xxxxxxxxxxxxx'
args[0].success(result)
hasComplete(args[0].complete)
}
}
}

View File

@ -0,0 +1,173 @@
import { paramMock } from "./utils"
export function mockDataStorage() {
global.systemplugin.data = {}
const paramValueTypeMock = '[PC Preview] unknow ValueType'
const storageObserverMock = {
key: "[PC preview] unknow key"
}
const storageMock = {
getSync: function () {
console.warn("Storage.getSync interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramValueTypeMock
},
get: function (...args) {
console.warn("Storage.get interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramValueTypeMock)
} else {
return new Promise((resolve) => {
resolve(paramValueTypeMock)
})
}
},
hasSync: function () {
console.warn("Storage.hasSync interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramBooleanMock
},
has: function (...args) {
console.warn("Storage.has interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock)
} else {
return new Promise((resolve) => {
resolve(paramMock.paramBooleanMock)
})
}
},
putSync: function () {
console.warn("Storage.putSync interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
},
put: function (...args) {
console.warn("Storage.put interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
deleteSync: function () {
console.warn("Storage.deleteSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
delete: function (...args) {
console.warn("Storage.delete interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
clearSync: function () {
console.warn("Storage.clearSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
clear: function (...args) {
console.warn("Storage.clear interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
flushSync: function () {
console.warn("Storage.flushSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
flush: function (...args) {
console.warn("Storage.flush interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
on: function (...args) {
console.warn("Storage.on interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
args[len - 1].call(this, storageObserverMock)
},
off: function (...args) {
console.warn("Storage.off interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
args[len - 1].call(this, storageObserverMock)
}
}
global.systemplugin.data.storage = {
getStorageSync: function () {
console.warn("data.storage.getStorageSync interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return storageMock
},
getStorage: function (...args) {
console.warn("data.storage.getStorage interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, storageMock)
} else {
return new Promise((resolve) => {
resolve(storageMock)
})
}
},
deleteStorageSync: function () {
console.warn("data.storage.deleteStorageSync interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
},
deleteStorage: function (...args) {
console.warn("data.storage.deleteStorage interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
removeStorageFromCacheSync: function () {
console.warn("data.storage.removeStorageFromCacheSync interface mocked in the Previewer. How this interface" +
" works on the Previewer may be different from that on a real device.")
},
removeStorageFromCache: function (...args) {
console.warn("data.storage.removeStorageFromCache interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
}
}
}

View File

@ -0,0 +1,33 @@
export function mockDeviceInfo() {
global.systemplugin.deviceInfo = {
deviceType: '[PC preview] unknow type',
manufacture: '[PC preview] unknow manufacture',
brand: '[PC preview] unknow brand',
marketName: '[PC preview] unknow market nanme',
productSeries: '[PC preview] unknow product series',
productModel: '[PC preview] unknow product model',
softwareModel: '[PC preview] unknow software model',
hardwareModel: '[PC preview] unknow hardware model',
hardwareProfile: '[PC preview] unknow hardware profile',
serial: '[PC preview] unknow serial',
bootloaderVersion: '[PC preview] unknow bootloader version',
abiList: '[PC preview] unknow ablity list',
securityPatchTag: '[PC preview] unknow security patch tag',
displayVersion: '[PC preview] unknow display version',
incrementalVersion: '[PC preview] unknow incremental version',
osReleaseType: '[PC preview] unknow os release type',
osFullName: '[PC preview] unknow os full name',
majorVersion: '[PC preview] unknow security major version',
seniorVersion: '[PC preview] unknow senior version',
featureVersion: '[PC preview] unknow feature version',
buildVersion: '[PC preview] unknow build version',
sdkApiVersion: '[PC preview] unknow sdk api version',
firstApiVersion: '[PC preview] unknow first api version',
versionId: '[PC preview] unknow version id',
buildType: '[PC preview] unknow build type',
buildUser: '[PC preview] unknow build user',
buildHost: '[PC preview] unknow build host',
buildTime: '[PC preview] unknow build time',
buildRootHash: '[PC preview] unknow build root hash'
}
}

View File

@ -0,0 +1,85 @@
import {paramMock} from "./utils"
export function mockDeviceManager() {
const deviceInfoMock = {
deviceId: "[PC Preview] unknow mNetworkId",
deviceName: "[PC Preview] unknow mDeviceName",
deviceType: 0x0E
}
const deviceStateChangeMock = {
action: 0,
device: deviceInfoMock
}
const deviceManagerMock = {
release: function () {
console.warn("DeviceManager.release interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
getTrustedDeviceListSync: function () {
console.warn("DeviceManager.getTrustedDeviceListSync interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
var array = new Array();
array.push(deviceInfoMock);
return array ;
},
getTrustedDeviceList: function (...args) {
console.warn("DeviceManager.getTrustedDeviceList interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
var array = new Array();
array.push(deviceInfoMock);
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, array);
} else {
return new Promise((resolve, reject) => {
resolve(array);
})
}
},
getLocalDeviceInfoSync: function () {
console.warn("DeviceManager.getLocalDeviceInfoSync interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return deviceInfoMock;
},
getLocalDeviceInfo: function (...args) {
console.warn("DeviceManager.getLocalDeviceInfo interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, deviceInfoMock);
} else {
return new Promise((resolve, reject) => {
resolve(deviceInfoMock);
})
}
},
on: function (...args) {
console.warn("DeviceManager.on interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
if (args[0] == 'deviceStateChange') {
args[len - 1].call(this, paramMock.businessErrorMock, deviceStateChangeMock);
} else {
args[len - 1].call(this);
}
}
},
off: function (...args) {
console.warn("DeviceManager.off interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
}
}
global.systemplugin.distributedHardware = global.systemplugin.distributedHardware || {};
global.systemplugin.distributedHardware.deviceManager = {
createDeviceManager: function (...args) {
console.warn("distributedHardware.deviceManager.createDeviceManager interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, deviceManagerMock)
}
}
}
}

View File

@ -0,0 +1,72 @@
import { paramMock } from "./utils"
export function mockDisplay() {
const displayMock = {
densityDPI: '[PC preview] unknow densityDPI',
densityPixels: '[PC preview] unknow densityPixels',
scaledDensity: '[PC preview] unknow scaledDensity',
xDPI: '[PC preview] unknow xDPI',
yDPI: '[PC preview] unknow yDPI',
width: '[PC preview] unknow width',
height: '[PC preview] unknow height',
alive: '[PC preview] unknow alive',
refreshRate: '[PC preview] unknow refreshRate',
id: '[PC preview] unknow id',
state: '[PC preview] unknow state',
rotation: '[PC preview] unknow rotation',
name: '[PC preview] unknow name'
}
const allDisplayMock = [{
densityDPI: '[PC preview] unknow densityDPI',
densityPixels: '[PC preview] unknow densityPixels',
scaledDensity: '[PC preview] unknow scaledDensity',
xDPI: '[PC preview] unknow xDPI',
yDPI: '[PC preview] unknow yDPI',
width: '[PC preview] unknow width',
height: '[PC preview] unknow height',
alive: '[PC preview] unknow alive',
refreshRate: '[PC preview] unknow refreshRate',
id: '[PC preview] unknow id',
state: '[PC preview] unknow state',
rotation: '[PC preview] unknow rotation',
name: '[PC preview] unknow name'
}]
global.systemplugin.display = {
getDefaultDisplay: function (...args) {
console.warn("display.getDefaultDisplay interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, displayMock)
} else {
return new Promise((resolve, reject) => {
resolve(displayMock)
})
}
},
getAllDisplay: function (...args) {
console.warn("display.getAllDisplay interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, allDisplayMock)
} else {
return new Promise((resolve, reject) => {
resolve(allDisplayMock)
})
}
},
on: function (...args) {
console.warn("display.on interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramNumberMock)
},
off: function (...args) {
console.warn("display.off interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramNumberMock)
},
}
}

View File

@ -0,0 +1,47 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { paramMock } from "./utils"
export function mockDistributedSchedule() {
global.systemplugin.distributedSchedule = {
stopDistributedService: function (...args) {
console.warn("distributedSchedule.stopDistributedService interface mocked in the Previewer. " +
"How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock)
} else {
return new Promise((resolve) => {
resolve(paramMock.paramStringMock)
})
}
},
startDistributedService: function (...args) {
console.warn("distributedSchedule.startDistributedService interface mocked in the Previewer. " +
"How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock)
} else {
return new Promise((resolve) => {
resolve(paramMock.paramStringMock)
})
}
}
}
}

View File

@ -0,0 +1,42 @@
import { paramMock } from "./utils"
export function mockDocument() {
global.systemplugin.document = {
create: function (...args) {
console.warn("document.create interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock)
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramStringMock);
})
}
},
choose: function (...args) {
console.warn("document.choose interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock)
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramStringMock);
})
}
},
show: function (...args) {
console.warn("document.show interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
}
}
}

View File

@ -0,0 +1,3 @@
import { mockSystemPlugin } from './index';
mockSystemPlugin()

View File

@ -0,0 +1,70 @@
export function mockFeatureAbility() {
let FeatureAbilityObject = {
getFeatureAbility: function () {
const ResultMock = {
code: '[PC preview] unknow code',
data: '[PC preview] unknow data'
}
const FeatureAbility = {
startAbility: function (...args) {
console.warn("Unable to use the FeatureAbility.startAbility method to start another ability in the" +
" Previewer. Perform this operation on the emulator or a real device instead.")
return new Promise((resolve, reject) => {
resolve(ResultMock);
})
},
startAbilityForResult: function (...args) {
console.warn("Unable to use the FeatureAbility.startAbilityForResult method to start another ability in" +
" the Previewer. Perform this operation on the emulator or a real device instead.")
return new Promise((resolve, reject) => {
resolve(ResultMock);
})
},
finishWithResult: function (...args) {
console.warn("FeatureAbility.finishWithResult interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
return new Promise((resolve, reject) => {
resolve(ResultMock);
})
},
callAbility: function (...args) {
console.warn("FeatureAbility.callAbility interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
return new Promise((resolve, reject) => {
resolve(JSON.stringify(ResultMock));
})
},
continueAbility: function (...args) {
console.warn("FeatureAbility.continueAbility interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
return new Promise((resolve, reject) => {
resolve(ResultMock);
})
},
subscribeAbilityEvent: function (...args) {
console.warn("FeatureAbility.subscribeAbilityEvent interface mocked in the Previewer. How this interface" +
" works on the Previewer may be different from that on a real device.")
return new Promise((resolve, reject) => {
resolve(JSON.stringify(ResultMock));
})
},
unsubscribeAbilityEvent: function (...args) {
console.warn("FeatureAbility.unsubscribeAbilityEvent interface mocked in the Previewer. How this interface" +
" works on the Previewer may be different from that on a real device.")
return new Promise((resolve, reject) => {
resolve(JSON.stringify(ResultMock));
})
}
}
return FeatureAbility
}
}
global.createLocalParticleAbility = function (...args) {
console.warn("createLocalParticleAbility interface mocked in the Previewer. How this interface" +
" works on the Previewer may be different from that on a real device.")
return new Promise((resolve, reject) => {
resolve(paramMock.paramObjectMock);
})
}
global.FeatureAbility = FeatureAbilityObject.getFeatureAbility();
}

View File

@ -0,0 +1,118 @@
export function mockFetch() {
global.sendGroupMessage = global.group.sendGroupMessage;
let GroupMessenger = {
create: function () {
let messenger = {};
messenger.send = function (groupName, functionName, ...args) {
return new Promise(function (resolve, reject) {
let params = messenger.prepareArgs(...args);
sendGroupMessage(function (result) {
resolve(messenger.parseJsonResult(result));
}, function (error) {
reject(messenger.parseJsonResult(error));
}, groupName, functionName, ...params);
})
};
messenger.parseJsonResult = function (data) {
if (data && data.constructor == String) {
try {
data = JSON.parse(data);
} catch (jsonParseErr) {
console.warn("parse result exception: " + JSON.stringify(jsonParseErr));
}
}
return data;
};
messenger.prepareArgs = function (...args) {
let result = [...args];
for (let i = 0; i < result.length; i++) {
if (typeof result[i] === 'function') {
result[i] = messenger.packageCallback(result[i]);
}
}
return result;
};
messenger.packageCallback = function (func) {
return function (data) {
data = messenger.parseJsonResult(data);
if (!Array.isArray(data)) {
func(data);
} else {
func(...data);
}
};
};
return messenger;
}
};
let CommonCallback = {
commonCallback: function commonCallback(callback, flag, data, code) {
if (typeof callback === 'function') {
switch (flag) {
case 'success':
callback(data);
break;
case 'fail':
callback(data, code);
break;
case 'cancel':
callback(data);
break;
case 'complete':
callback();
break;
default:
break;
}
} else {
console.warn('callback.' + flag + ' is not function or not present');
}
}
};
global.commonCallback = CommonCallback.commonCallback;
let CommonCallbackEx = {
commonCallbackEx: function commonCallbackEx(callback, result, pluginError) {
if ((callback === undefined) || ((callback.success === undefined) && (callback.fail === undefined) && (callback.complete === undefined))) {
return CommonCallbackEx.promiseMethod(result, pluginError);
} else {
return CommonCallbackEx.callbackMethod(callback, result, pluginError);
}
},
promiseMethod: function promiseMethod(result, pluginError) {
if (pluginError != undefined) {
throw pluginError;
}
return result;
},
callbackMethod: function callbackMethod(callback, result, pluginError) {
if (pluginError != undefined) {
commonCallback(callback.fail, 'fail', pluginError.data, pluginError.code);
commonCallback(callback.complete, 'complete');
throw pluginError;
}
commonCallback(callback.success, 'success', result.data);
commonCallback(callback.complete, 'complete');
return result;
},
catching: function catching(promise, param) {
return promise.then(ret => commonCallbackEx(param, ret))
.catch(err => commonCallbackEx(param, null, err));
}
};
global.commonCallbackEx = CommonCallbackEx.commonCallbackEx;
global.systemplugin.catching = CommonCallbackEx.catching;
let FetchObject = {
getFetch: function () {
let fetch = {}
fetch.messenger = GroupMessenger.create();
fetch.fetch = async function (param) {
return await CommonCallbackEx.catching(this.messenger.send("groupName", "fetch", param), param);
}
return fetch
}
}
global.systemplugin.fetch = FetchObject.getFetch();
}

View File

@ -0,0 +1,95 @@
import { hasComplete } from "./utils"
export function mockFile() {
global.systemplugin.file = {
move: function(...args) {
console.warn("file.move interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
args[0].success(args[0].dstUri)
hasComplete(args[0].complete)
},
copy: function(...args) {
console.warn("file.copy interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
args[0].success(args[0].dstUri)
hasComplete(args[0].complete)
},
list: function(...args) {
console.warn("file.list interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const data = {
fileList: [{
uri: '[PC Preview]: no file',
lastModifiedTime: "[PC Preview]: no file",
length: "[PC Preview]: no file",
type: 'file'
}]
}
args[0].success(data)
hasComplete(args[0].complete)
},
get: function(...args) {
console.warn("file.get interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const data = {
uri: '[PC Preview]: no file',
lastModifiedTime: "[PC Preview]: no file",
length: "[PC Preview]: no file",
type: 'file',
subFiles: ["[PC Preview]: no file", "[PC Preview]: no file"]
}
args[0].success(data)
hasComplete(args[0].complete)
},
delete: function(...args) {
console.warn("file.delete interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
args[0].success()
hasComplete(args[0].complete)
},
writeText: function(...args) {
console.warn("file.writeText interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
args[0].success()
hasComplete(args[0].complete)
},
writeArrayBuffer: function(...args) {
console.warn("file.writeArrayBuffer interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
args[0].success()
hasComplete(args[0].complete)
},
readText: function(...args) {
console.warn("file.readText interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const data = {text: "[PC Preview]: success default"}
args[0].success(data)
hasComplete(args[0].complete)
},
readArrayBuffer: function(...args) {
console.warn("file.readArrayBuffer interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const data = {buffer: ["[PC Preview]: default", "[PC Preview]: default", "[PC Preview]: default"]}
args[0].success(data)
hasComplete(args[0].complete)
},
access: function(...args) {
console.warn("file.access interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
args[0].success()
hasComplete(args[0].complete)
},
mkdir: function(...args) {
console.warn("file.mkdir interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
args[0].success()
hasComplete(args[0].complete)
},
rmdir: function(...args) {
console.warn("file.rmdir interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
args[0].success()
hasComplete(args[0].complete)
}
}
}

View File

@ -0,0 +1,48 @@
import { hasComplete } from "./utils"
export function mockGeolocation() {
const data = {
latitude: '121.61934',
longitude: '31.257907',
accuracy: '15',
time: '160332896544'
}
global.systemplugin.geolocation = {
getLocation: function (...args) {
console.warn("geolocation.getLocation interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
args[0].success(data)
hasComplete(args[0].complete)
},
getLocationType: function(...args) {
console.warn("geolocation.getLocationType interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const info = {types: ['gps', 'network']}
args[0].success(info)
hasComplete(args[0].complete)
},
getSupportedCoordTypes() {
console.warn("geolocation.getSupportedCoordTypes interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
return ["wgs84"]
},
subscribe: function(...args) {
console.warn("geolocation.subscribe interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
if (!this.unsubscribeLocation) {
this.unsubscribeLocation = setInterval(() => {
data.latitude = getRandomArbitrary(121, 122)
data.longitude = getRandomArbitrary(31, 32)
data.accuracy = getRandomArbitrary(14, 18)
args[0].success(data)
}, 1000)
}
},
unsubscribe: function() {
console.warn("geolocation.unsubscribe interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
clearInterval(this.unsubscribeLocation)
delete this.unsubscribeLocation
}
}
}

View File

@ -0,0 +1,104 @@
import regeneratorRuntime from 'babel-runtime/regenerator'
import {
mockAbilityFeatureAbility,
mockAbilityParticleAbility,
mockAbilityFormManager
} from './ability'
import { mockBattery } from './battery'
import { mockBrightness } from './brightness'
import { mockBluetooth } from './bluetooth'
import { mockCall } from './telephony'
import { mockCipher } from './cipher'
import { mockDataStorage } from './data'
import { mockDeviceInfo } from './deviceInfo'
import { mockDistributedSchedule } from './distributedSchedule'
import { mockDocument } from './document'
import { mockFetch } from './fetch'
import { mockFeatureAbility } from './featureAbility'
import { mockFile } from './file'
import { mockGeolocation } from './geolocation'
import { mockInputmethod } from './inputmethod'
import {
mockMultimediaImage,
mockMultimediaMedia,
mockMultimediaMedialibrary
} from './multimedia'
import { mockNetwork } from './network'
import { mockNfcCardEmulation } from './nfc'
import { mockNotification } from './notification'
import { mockOhosBatteryinfo } from './batteryinfo'
import { mockOhosRequest } from './ohos/request'
import { mockPasteBoard } from './pasteboard'
import { mockReminderAgent } from './ohos/reminderAgent'
import { mockRequest } from './request'
import { mockSensor } from './sensor'
import { mockStorage } from './storage'
import { mockSystemPackage } from './systemPackage'
import { mockUserauth } from './userIAM'
import { mockVibrator } from './vibrator'
import { mockWebSocket, mockHttp } from './net'
import { mockWifi } from './wifi'
import { mockWindow } from './window'
import { mockRequireNapiFun } from './napi'
import { mockAccessibility } from './accessibility'
import { mockAI } from './ai'
import { mockDisplay } from './display'
import { mockDeviceManager } from './deviceManager'
export function mockSystemPlugin() {
global.regeneratorRuntime = regeneratorRuntime
global.systemplugin = {}
global.ohosplugin = {}
mockNotification()
mockFetch()
mockRequest()
mockStorage()
mockFile()
mockVibrator()
mockSensor()
mockGeolocation()
mockNetwork()
mockBrightness()
mockBattery()
mockSystemPackage()
mockFeatureAbility()
mockBluetooth()
mockCipher()
mockOhosBatteryinfo()
mockUserauth()
mockDistributedSchedule()
mockDocument()
mockPasteBoard()
mockInputmethod()
mockOhosRequest()
mockMultimediaImage()
mockMultimediaMedia()
mockMultimediaMedialibrary()
mockCall()
mockWebSocket()
mockHttp()
mockDeviceInfo()
mockWifi()
mockNfcCardEmulation()
mockDataStorage()
mockWindow()
mockAbilityFeatureAbility()
mockReminderAgent()
mockRequireNapiFun()
mockAccessibility()
mockAbilityParticleAbility()
mockAbilityFormManager()
mockAI()
mockDisplay()
mockDeviceManager()
}

View File

@ -0,0 +1,25 @@
import { paramMock } from "./utils"
export function mockInputmethod() {
const InputMethodControllerMock = {
stopInput: function (...args) {
console.warn("InputMethodController.stopInput interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramBooleanMock);
})
}
}
}
global.systemplugin.inputmethod = {
getInputMethodController: function () {
console.warn("inputmethod.getInputMethodController interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
return InputMethodControllerMock;
}
}
}

View File

@ -0,0 +1,237 @@
import { paramMock } from "./utils"
export function mockMultimediaImage() {
global.systemplugin.multimedia = {}
const sizeMock = {
height: "[PC Preview] unknow height",
width: "[PC Preview] unknow width"
}
const imageInfoMock = {
size: sizeMock,
pixelFortmat: "[PC Preview] unknow pixelFortmat",
colorSpace: "[PC Preview] unknow colorSpace",
alphaType: "[PC Preview] unknow alphaType"
}
const imageSourceMock = {
getImageInfo: function (...args) {
console.warn("ImageSource.getImageInfo interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, imageInfoMock);
} else {
return new Promise((resolve, reject) => {
resolve(imageInfoMock);
})
}
},
release: function (...args) {
console.warn("ImageSource.release interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
supportedFormats: "[PC Preview] unknow supportedFormats"
}
const imagePackerMock = {
packing: function (...args) {
console.warn("ImagePacker.packing interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramArrayMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramArrayMock);
})
}
},
release: function (...args) {
console.warn("ImagePacker.release interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
supportedFormats: "[PC Preview] unknow supportedFormats"
}
global.systemplugin.multimedia.image = {
createImageSource: function () {
console.warn("multimedia.image.createImageSource interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
return imageSourceMock;
},
createImagePacker: function () {
console.warn("multimedia.image.createImagePacker interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
return imagePackerMock;
}
}
}
export function mockMultimediaMedia() {
const audioPlayerMock = {
play: function () {
console.warn("AudioPlayer.play interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
pause: function () {
console.warn("AudioPlayer.pause interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
stop: function () {
console.warn("AudioPlayer.stop interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
seek: function (...args) {
console.warn("AudioPlayer.seek interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
setVolume: function (...args) {
console.warn("AudioPlayer.setVolume interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return
},
release: function () {
console.warn("AudioPlayer.release interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
src: "[PC Preview] unknow src",
loop: "[PC Preview] unknow loop",
currentTime: "[PC Preview] unknow currentTime",
duration: "[PC Preview] unknow duration",
state: "[PC Preview] unknow state",
on: function (...args) {
console.warn("AudioPlayer.on interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
if (args[0] == 'error') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else if (args[0] == 'timeUpdate') {
args[len - 1].call(this, paramMock.paramNumberMock);
} else {
args[len - 1].call(this);
}
}
}
}
const audioRecorderMock = {
prepare: function () {
console.warn("AudioRecorder.prepare interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
},
start: function () {
console.warn("AudioRecorder.start interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
pause: function () {
console.warn("AudioRecorder.pause interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
resume: function () {
console.warn("AudioRecorder.resume interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
},
stop: function () {
console.warn("AudioRecorder.stop interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
release: function () {
console.warn("AudioRecorder.release interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
},
reset: function () {
console.warn("AudioRecorder.reset interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
on: function (...args) {
console.warn("AudioRecorder.on interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
if (args[0] == 'error') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
args[len - 1].call(this);
}
}
}
}
global.systemplugin.multimedia.media = {
createAudioPlayer: function () {
console.warn("multimedia.media.createAudioPlayer interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
return audioPlayerMock;
},
createAudioRecorder: function () {
console.warn("multimedia.media.createAudioRecorder interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
return audioRecorderMock;
}
}
}
export function mockMultimediaMedialibrary() {
const MediaLibraryMock = {
storeMediaAsset: function (...args) {
console.warn("MediaLibrary.storeMediaAsset interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramStringMock);
})
}
},
startImagePreview: function (...args) {
console.warn("MediaLibrary.startImagePreview interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
startMediaSelect: function (...args) {
console.warn("MediaLibrary.startMediaSelect interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramArrayMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramArrayMock);
})
}
}
}
global.systemplugin.multimedia.mediaLibrary = {
getMediaLibrary: function () {
console.warn("multimedia.mediaLibrary.getMediaLibrary interface mocked in the Previewer. How this interface" +
" works on the Previewer may be different from that on a real device.")
return MediaLibraryMock;
}
}
}

View File

@ -0,0 +1,708 @@
import { paramMock } from "../utils"
export function mockFileio() {
const StatMock = {
dev: '[PC preview] unknow dev',
ino: '[PC preview] unknow ino',
mode: '[PC preview] unknow mode',
nlink: '[PC preview] unknow nlink',
uid: '[PC preview] unknow uid',
gid: '[PC preview] unknow gid',
rdev: '[PC preview] unknow rdev',
size: '[PC preview] unknow size',
blocks: '[PC preview] unknow blocks',
atime: '[PC preview] unknow atime',
mtime: '[PC preview] unknow mtime',
ctime: '[PC preview] unknow ctime',
isBlockDevice: function () {
console.warn("Stat.isBlockDevice interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return paramMock.paramBooleanMock
},
isCharacterDevice: function () {
console.warn("Stat.isCharacterDevice interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return paramMock.paramBooleanMock
},
isDirectory: function () {
console.warn("Stat.isDirectory interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return paramMock.paramBooleanMock
},
isFIFO: function () {
console.warn("Stat.isFIFO interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
return paramMock.paramBooleanMock
},
isFile: function () {
console.warn("Stat.isFile interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
return paramMock.paramBooleanMock
},
isSocket: function () {
console.warn("Stat.isSocket interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramBooleanMock
},
isSymbolicLink: function () {
console.warn("Stat.isSymbolicLink interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return paramMock.paramBooleanMock
}
};
const DirMock = {
close: function (...args) {
console.warn("Dir.close interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
closeSync: function (...args) {
console.warn("Dir.closeSync interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
},
read: function (...args) {
console.warn("Dir.read interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, DirentMock);
} else {
return new Promise((resolve, reject) => {
resolve(DirentMock);
})
}
},
readSync: function (...args) {
console.warn("Dir.readSync interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
return DirentMock
}
};
const StreamMock = {
close: function (...args) {
console.warn("Stream.close interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
closeSync: function (...args) {
console.warn("Stream.closeSync interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
},
flush: function (...args) {
console.warn("Stream.flush interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
flushSync: function (...args) {
console.warn("Stream.flushSync interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
},
read: function (...args) {
console.warn("Stream.read interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, ReadOutMock)
} else {
return new Promise((resolve, reject) => {
resolve(ReadOutMock);
})
}
},
readSync: function (...args) {
console.warn("Stream.readSync interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramNumberMock;
},
write: function (...args) {
console.warn("Stream.write interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramNumberMock)
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramNumberMock);
})
}
},
writeSync: function (...args) {
console.warn("Stream.writeSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return paramMock.paramNumberMock;
}
};
const DirentMock = {
name: "[PC Preview]: unknow name",
isBlockDevice: function () {
console.warn("Dirent.isBlockDevice interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return paramMock.paramBooleanMock
},
isCharacterDevice: function () {
console.warn("Dirent.isCharacterDevice interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return paramMock.paramBooleanMock
},
isDirectory: function () {
console.warn("Dirent.isDirectory interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return paramMock.paramBooleanMock
},
isFIFO: function () {
console.warn("Dirent.isFIFO interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramBooleanMock
},
isFile: function () {
console.warn("Dirent.isFile interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramBooleanMock
},
isSocket: function () {
console.warn("Dirent.isSocket interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramBooleanMock
},
isSymbolicLink: function () {
console.warn("Dirent.isSymbolicLink interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return paramMock.paramBooleanMock
}
};
const ReadOutMock = {
bytesRead: "[PC Preview]: unknow bytesRead",
offset: "[PC Preview]: unknow offset",
buffer: "[PC Preview]: unknow buffer"
};
const WatcherMock = {
stop: function () {
console.warn("Watcher.stop interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
}
};
const fileioMock = {
Dir: DirMock,
Dirent: DirentMock,
Stat: StatMock,
Stream: StreamMock,
ReadOut: ReadOutMock,
Watcher: WatcherMock,
access: function (...args) {
console.warn("fileio.access interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
accessSync: function (...args) {
console.warn("fileio.accessSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
chmod: function (...args) {
console.warn("fileio.chmod interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
chmodSync: function (...args) {
console.warn("fileio.chmodSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
chown: function (...args) {
console.warn("fileio.chown interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
chownSync: function (...args) {
console.warn("fileio.chownSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
close: function (...args) {
console.warn("fileio.close interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
closeSync: function (...args) {
console.warn("fileio.closeSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
copyFile: function (...args) {
console.warn("fileio.copyFile interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
copyFileSync: function (...args) {
console.warn("fileio.copyFileSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
createStream: function (...args) {
console.warn("fileio.createStream interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, StreamMock)
} else {
return new Promise((resolve, reject) => {
resolve(StreamMock);
})
}
},
createStreamSync: function (...args) {
console.warn("fileio.createStreamSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return StreamMock;
},
createWatcher: function (...args) {
console.warn("fileio.createWatcher interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramNumberMock)
} else {
return WatcherMock;
}
},
fchmod: function (...args) {
console.warn("fileio.fchmod interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
fchmodSync: function (...args) {
console.warn("fileio.fchmodSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
fchown: function (...args) {
console.warn("fileio.fchown interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
fchownSync: function (...args) {
console.warn("fileio.fchownSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
fdatasync: function (...args) {
console.warn("fileio.fdatasync interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
fdatasyncSync: function (...args) {
console.warn("fileio.fdatasyncSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
fdopenStream: function (...args) {
console.warn("fileio.fdopenStream interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, StreamMock)
} else {
return new Promise((resolve, reject) => {
resolve(StreamMock);
})
}
},
fdopenStreamSync: function (...args) {
console.warn("fileio.fdopenStreamSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return StreamMock;
},
fstat: function (...args) {
console.warn("fileio.fstat interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, StatMock)
} else {
return new Promise((resolve, reject) => {
resolve(StatMock);
})
}
},
fstatSync: function (...args) {
console.warn("fileio.fstatSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return StatMock;
},
fsync: function (...args) {
console.warn("fileio.fsync interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
fsyncSync: function (...args) {
console.warn("fileio.fsyncSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
ftruncate: function (...args) {
console.warn("fileio.ftruncate interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
ftruncateSync: function (...args) {
console.warn("fileio.ftruncateSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
hash: function (...args) {
console.warn("fileio.hash interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock)
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramStringMock);
})
}
},
lchown: function (...args) {
console.warn("fileio.lchown interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
lchownSync: function (...args) {
console.warn("fileio.lchownSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
lstat: function (...args) {
console.warn("fileio.lstat interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, StatMock)
} else {
return new Promise((resolve, reject) => {
resolve(StatMock);
})
}
},
lstatSync: function (...args) {
console.warn("fileio.lstatSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return StatMock;
},
mkdir: function (...args) {
console.warn("fileio.mkdir interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
mkdirSync: function (...args) {
console.warn("fileio.mkdirSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
mkdtemp: function (...args) {
console.warn("fileio.mkdtemp interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock)
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramStringMock);
})
}
},
mkdtempSync: function (...args) {
console.warn("fileio.mkdtempSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return paramMock.paramStringMock;
},
open: function (...args) {
console.warn("fileio.open interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramNumberMock)
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramNumberMock);
})
}
},
openSync: function (...args) {
console.warn("fileio.openSync interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramNumberMock;
},
opendir: function (...args) {
console.warn("fileio.opendir interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, DirMock)
} else {
return new Promise((resolve, reject) => {
resolve(DirMock);
})
}
},
opendirSync: function (...args) {
console.warn("fileio.opendirSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return DirMock;
},
read: function (...args) {
console.warn("fileio.read interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, ReadOutMock)
} else {
return new Promise((resolve, reject) => {
resolve(ReadOutMock);
})
}
},
readSync: function (...args) {
console.warn("fileio.readSync interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return paramMock.paramNumberMock;
},
readText: function (...args) {
console.warn("fileio.readText interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramStringMock);
})
}
},
readTextSync: function (...args) {
console.warn("fileio.readTextSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return paramMock.paramStringMock;
},
rename: function (...args) {
console.warn("fileio.rename interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
renameSync: function (...args) {
console.warn("fileio.renameSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
rmdir: function (...args) {
console.warn("fileio.rmdir interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
rmdirSync: function (...args) {
console.warn("fileio.rmdirSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
stat: function (...args) {
console.warn("fileio.stat interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, StatMock)
} else {
return new Promise((resolve, reject) => {
resolve(StatMock);
})
}
},
statSync: function (...args) {
console.warn("fileio.statSync interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
return StatMock;
},
symlink: function (...args) {
console.warn("fileio.symlink interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
symlinkSync: function (...args) {
console.warn("fileio.symlinkSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
truncate: function (...args) {
console.warn("fileio.truncate interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
truncateSync: function (...args) {
console.warn("fileio.truncateSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return
},
unlink: function (...args) {
console.warn("fileio.unlink interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
unlinkSync: function (...args) {
console.warn("fileio.unlinkSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
write: function (...args) {
console.warn("fileio.write interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramNumberMock)
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramNumberMock);
})
}
},
writeSync: function (...args) {
console.warn("fileio.writeSync interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return paramMock.paramNumberMock;
}
}
return fileioMock
}

View File

@ -0,0 +1,25 @@
import { mockSystemParameter } from './systemParameter'
import { mockFileio } from './fileio'
import { mockWorker } from './worker'
import { mockUtil } from './util'
import { mockPower } from './power'
import { mockRunningLock } from './runningLock'
export function mockRequireNapiFun() {
global.requireNapi = function (...args) {
switch (args[0]) {
case "systemParameter":
return mockSystemParameter();
case "fileio":
return mockFileio();
case "worker" :
return mockWorker();
case "util":
return mockUtil();
case "power":
return mockPower();
case "runningLock":
return mockRunningLock();
}
}
}

View File

@ -0,0 +1,27 @@
import { paramMock } from "../utils"
export function mockPower() {
const power = {
shutdownDevice: function (...args) {
console.warn("power.shutdownDevice interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
},
rebootDevice: function (...args) {
console.warn("power.rebootDevice interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
},
isScreenOn: function (...args) {
console.warn("power.isScreenOn interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramBooleanMock);
})
}
}
}
return power
}

View File

@ -0,0 +1,46 @@
import { paramMock } from "../utils"
export function mockRunningLock() {
const RunningLockMock = {
lock: function (...args) {
console.warn("RunningLock.lock interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
isUsed: function () {
console.warn("RunningLock.isUsed interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return paramMock.paramBooleanMock
},
unlock: function () {
console.warn("RunningLock.unlock interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
}
};
const runningLock = {
isRunningLockTypeSupported: function (...args) {
console.warn("runningLock.isRunningLockTypeSupported interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramBooleanMock);
})
}
},
createRunningLock: function (...args) {
console.warn("runningLock.createRunningLock interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, RunningLockMock);
} else {
return new Promise((resolve, reject) => {
resolve(RunningLockMock);
})
}
}
}
return runningLock
}

View File

@ -0,0 +1,40 @@
import { paramMock } from "../utils"
export function mockSystemParameter() {
const systemParameter = {
getSync: function (...args) {
console.warn("systemParameter.getSync interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return paramMock.paramStringMock
},
get: function (...args) {
console.warn("systemParameter.get interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramStringMock);
})
}
},
setSync: function (...args) {
console.warn("systemParameter.setSync interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
},
set: function (...args) {
console.warn("systemParameter.set interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
}
}
return systemParameter
}

View File

@ -0,0 +1,40 @@
import { paramMock } from "../utils"
export function mockUtil() {
const result = {
TextDecoder: function(...args) {
console.warn("util.TextDecoder interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return TextDecoderMock;
},
TextEncoder: function(...args) {
console.warn("util.TextEncoder interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return TextEncoderMock;
}
}
const TextDecoderMock = {
encoding: '[PC preview] unknow encoding',
fatal: '[PC preview] unknow fatal',
ignoreBOM: '[PC preview] unknow ignoreBOM',
decode: function (...args) {
console.warn("TextDecoder.decode interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return paramMock.paramStringMock;
},
}
const TextEncoderMock = {
encoding: '[PC preview] unknow encoding',
encode: function(...args) {
console.warn("TextEncoder.encode interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return paramMock.paramArrayMock;
},
encodeInto: function(...args) {
console.warn("TextEncoder.encodeInto interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return paramMock.paramObjectMock;
}
}
return result;
}

View File

@ -0,0 +1,71 @@
import { paramMock } from "../utils"
export function mockWorker() {
const result = {
Worker: function (params) {
console.warn("worker.Worker interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return WorkerMock;
}
}
const WorkerMock = {
postMessage: function (...args) {
console.warn("Worker.postMessage interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
terminate: function (...args) {
console.warn("Worker.terminate interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
on: function (...args) {
console.warn("Worker.on interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
once: function (...args) {
console.warn("Worker.once interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
off: function (...args) {
console.warn("Worker.off interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
addEventListener: function (...args) {
console.warn("Worker.addEventListener interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
},
dispatchEvent: function (...args) {
console.warn("Worker.dispatchEvent interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return paramMock.paramBooleanMock;
},
removeEventListener: function (...args) {
console.warn("Worker.removeEventListener interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
},
removeAllListener: function (...args) {
console.warn("Worker.removeAllListener interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
},
onmessage: function (...args) {
console.warn("Worker.onmessage interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
onmessageerror: function (...agrs) {
console.warn("Worker.onmessageerror interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
},
onerror: function (...args) {
console.warn("Worker.onerror interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
onclose: function (...args) {
console.warn("Worker.onclose interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
onexit: function (...args) {
console.warn("Worker.onexit interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
}
}
return result;
}

View File

@ -0,0 +1,137 @@
import { paramMock } from "./utils"
export function mockWebSocket() {
global.systemplugin.net = {}
const WebSocketMock = {
connect: function (...args) {
console.warn("WebSocket.connect interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramBooleanMock);
})
}
},
send: function (...args) {
console.warn("WebSocket.send interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramBooleanMock);
})
}
},
close: function (...args) {
console.warn("WebSocket.close interface mocked in the Previewer. How this interface works on the Previewer " +
"may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramBooleanMock);
})
}
},
on: function (...args) {
console.warn("WebSocket.on interface mocked in the Previewer. How this interface works on the Previewer may " +
"be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
if (args[0] == 'open') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramObjectMock);
} else if (args[0] == 'message') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock);
} else if (args[0] == 'close') {
args[len - 1].call(this, {
code: "[PC Preview] unknow code",
reason: "[PC Preview] unknow reason"
});
} else if (args[0] == 'error') {
args[len - 1].call(this, paramMock.businessErrorMock);
}
}
},
off: function (...args) {
console.warn("WebSocket.off interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
if (args[0] == 'open') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramObjectMock);
} else if (args[0] == 'message') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock);
} else if (args[0] == 'close') {
args[len - 1].call(this, {
code: "[PC Preview] unknow code",
reason: "[PC Preview] unknow reason"
});
} else if (args[0] == 'error') {
args[len - 1].call(this, paramMock.businessErrorMock);
}
}
}
}
global.systemplugin.net.webSocket = {
createWebSocket: function () {
console.warn("net.webSocket.createWebSocket interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return WebSocketMock;
}
}
}
export function mockHttp() {
const HttpResponseMock = {
result: "[PC Preview] unknow result",
responseCode: "[PC Preview] unknow responseCode",
header: "[PC Preview] unknow header"
}
const HttpRequestMock = {
request: function (...args) {
console.warn("HttpRequest.request interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, HttpResponseMock);
} else {
return new Promise((resolve, reject) => {
resolve(HttpResponseMock);
})
}
},
destroy: function () {
console.warn("HttpRequest.destroy interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
},
on: function (...args) {
console.warn("HttpRequest.on interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramObjectMock);
}
},
off: function (...args) {
console.warn("HttpRequest.off interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramObjectMock);
}
}
}
global.systemplugin.net.http = {
createHttp: function () {
console.warn("net.http.createHttp interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
return HttpRequestMock;
}
}
}

View File

@ -0,0 +1,29 @@
export function mockNetwork() {
const data = {
metered: true,
type: "5g"
}
global.systemplugin.network = {
getType: function (...args) {
console.warn("network.getType interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
args[0].success(data)
args[0].complete()
},
subscribe: function (...args) {
console.warn("network.subscribe interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
if (!this.unsubscribeNetwork) {
this.unsubscribeNetwork = setInterval(() => {
args[0].success(data)
}, 3000)
}
},
unsubscribe: function () {
console.warn("network.unsubscribe interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
clearInterval(this.unsubscribeNetwork)
delete this.unsubscribeNetwork
}
}
}

View File

@ -0,0 +1,12 @@
import { paramMock } from "./utils"
export function mockNfcCardEmulation() {
global.systemplugin.nfc = {}
global.systemplugin.nfc.cardEmulation = {
isSupported: function (...args) {
console.warn("nfc.cardEmulation.isSupported interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return paramMock.paramBooleanMock;
}
}
}

View File

@ -0,0 +1,8 @@
export function mockNotification() {
global.systemplugin.notification = {
show: function () {
console.warn("notification.show interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
}
}
}

View File

@ -0,0 +1,111 @@
import { paramMock } from "../utils"
export function mockReminderAgent() {
const infoMock = {
reminderId: 1,
info: "[PC preview] unknown info"
}
const reminderReq = {
reminderType: 1,
actionButton: [
{
title: "[PC preview] unknown title",
type: 0
}
],
wantAgent: {
pkgName: "[PC preview] unknown pkg nam",
abilityName: "[PC preview] unknown ability name"
},
maxScreenWantAgent: {
pkgName: "[PC preview] unknown pkg name",
abilityName: "[PC preview] unknown ability name"
},
ringDuration: 1,
snoozeTimes: 1,
timeInterval: 1,
title: "[PC preview] unknown title",
content: "[PC preview] unknown content",
expiredContent: "[PC preview] unknown expiredContent",
snoozeContent: "[PC preview] unknown snoozeContent",
notificationId: 1,
slotType: 3
}
const reminderReqs = [
reminderReq
]
global.ohosplugin.reminderAgent = {
publishReminder: function (...args) {
console.warn("reminderAgent.publishReminder interface mocked in the Previewer." +
"How this interface works on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, infoMock.reminderId)
} else {
return new Promise((resolve) => {
resolve(infoMock.reminderId)
});
}
},
getValidReminders: function (...args) {
console.warn("reminderAgent.getValidReminders interface mocked in the Previewer." +
"How this interface works on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, reminderReqs)
} else {
return new Promise((resolve) => {
resolve(reminderReqs)
});
}
},
cancelReminder: function (...args) {
console.warn("reminderAgent.cancelReminder interface mocked in the Previewer." +
"How this interface works on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
});
}
},
cancelAllReminders: function (...args) {
console.warn("reminderAgent.cancelAllReminders interface mocked in the Previewer." +
"How this interface works on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
});
}
},
addNotificationSlot: function (...args) {
console.warn("reminderAgent.addNotificationSlot interface mocked in the Previewer." +
"How this interface works on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
});
}
},
removeNotificationSlot: function (...args) {
console.warn("reminderAgent.removeNotificationSlot interface mocked in the Previewer." +
"How this interface works on the Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
});
}
}
}
}

View File

@ -0,0 +1,198 @@
import {paramMock} from "../utils";
const NOTIFY = "[PC Preview] unknow"
const Properties = [
'NETWORK_MOBILE',
'NETWORK_WIFI',
'ERROR_CANNOT_RESUME',
'ERROR_DEVICE_NOT_FOUND',
'ERROR_FILE_ALREADY_EXISTS',
'ERROR_FILE_ERROR',
'ERROR_HTTP_DATA_ERROR',
'ERROR_INSUFFICIENT_SPACE',
'ERROR_TOO_MANY_REDIRECTS',
'ERROR_UNHANDLED_HTTP_CODE',
'ERROR_UNKNOWN',
'PAUSED_QUEUED_FOR_WIFI',
'PAUSED_UNKNOWN',
'PAUSED_WAITING_FOR_NETWORK',
'PAUSED_WAITING_TO_RETRY',
'SESSION_FAILED',
'SESSION_PAUSED',
'SESSION_PENDING',
'SESSION_RUNNING',
'SESSION_SUCCESSFUL'
]
export function mockOhosRequest() {
const downloadInfo = {
downloadId: 1,
failedReason: 16,
fileName: "[PC preview] unknown file name",
filePath: "[PC preview] unknown file path",
pausedReason: 1,
status: 1,
targetURI: "[PC preview] unknown targetURI",
downloadTitle: "[PC preview] unknown download title",
downloadTotalBytes: 1024,
description: "[PC preview] unknown description",
downloadedBytes: 1
}
const DownloadTaskMock = {
on: function(...args) {
console.warn("DownloadTask.on interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
if (args[0] == 'progress') {
args[len - 1].call(this, paramMock.paramNumberMock, paramMock.paramNumberMock);
} else if (args[0] == 'complete' || args[0] == 'pause' || args[0] == 'remove') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else if (args[0] == 'fail') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramNumberMock);
}
}
},
off: function(...args) {
console.warn("DownloadTask.off interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
if (args[0] == 'progress') {
args[len - 1].call(this, paramMock.paramNumberMock, paramMock.paramNumberMock);
} else if (args[0] == 'complete' || args[0] == 'pause' || args[0] == 'remove') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else if (args[0] == 'fail') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramNumberMock);
}
}
},
remove: function(...args) {
console.warn("DownloadTask.remove interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramBooleanMock);
})
}
},
pause: function(...args) {
console.warn("DownloadTask.pause interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
resume: function(...args) {
console.warn("DownloadTask.resume interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
},
queryMimeType: function(...args) {
console.warn("DownloadTask.queryMimeType interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramStringMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramStringMock);
})
}
},
query: function(...args) {
console.warn("DownloadTask.query interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, downloadInfo);
} else {
return new Promise((resolve, reject) => {
resolve(downloadInfo);
})
}
}
}
const UploadTaskMock = {
on: function(...args) {
console.warn("UploadTask.on interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
if (args[0] == 'progress') {
args[len - 1].call(this, paramMock.paramNumberMock, paramMock.paramNumberMock);
} else if (args[0] == 'headerReceive') {
args[len - 1].call(this, paramMock.paramObjectMock);
}
}
},
off: function(...args) {
console.warn("UploadTask.off interface mocked in the Previewer. How this interface works on the Previewer may" +
" be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
if (args[0] == 'progress') {
args[len - 1].call(this, paramMock.paramNumberMock, paramMock.paramNumberMock);
} else if (args[0] == 'headerReceive') {
args[len - 1].call(this, paramMock.paramObjectMock);
}
}
},
remove: function(...args) {
console.warn("UploadTask.remove interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramBooleanMock);
})
}
}
}
global.ohosplugin.request = {
download: function (...args) {
console.warn("ohos.request.download interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, DownloadTaskMock);
} else {
return new Promise((resolve, reject) => {
resolve(DownloadTaskMock);
})
}
},
upload: function (...args) {
console.warn("ohos.request.upload interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, UploadTaskMock);
} else {
return new Promise((resolve, reject) => {
resolve(UploadTaskMock);
})
}
}
}
for(let property of Properties) {
global.ohosplugin.request[property] = NOTIFY + " " + property
}
}

View File

@ -0,0 +1,49 @@
import { paramMock } from "./utils"
export function mockPasteBoard() {
const PasteDataMock = {
getPrimaryText: function () {
console.warn("PasteData.getPrimaryText interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
return "[PC Preview] unknow primarytext"
}
}
const SystemPasteboardMock = {
getPasteData: function (...args) {
console.warn("SystemPasteboard.getPasteData interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, PasteDataMock)
} else {
return new Promise((resolve, reject) => {
resolve(PasteDataMock);
})
}
},
setPasteData: function (...args) {
console.warn("SystemPasteboard.setPasteData interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock);
} else {
return new Promise((resolve, reject) => {
resolve();
})
}
}
}
global.systemplugin.pasteboard = {
createPlainTextData: function () {
console.warn("pasteboard.createPlainTextData interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
return PasteDataMock;
},
getSystemPasteboard: function () {
console.warn("pasteboard.getSystemPasteboard interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
return SystemPasteboardMock;
}
}
}

View File

@ -0,0 +1,35 @@
import { hasComplete } from "./utils"
export function mockRequest() {
const uploadResponseMock = {
code: "[PC Preview]: unknow code",
data: "[PC Preview]: unknow data",
headers: "[PC Preview]: unknow headers"
}
const downloadResponse = {
token: "[PC Preview]: unknow token"
}
const onDownloadCompleteMock = {
uri: "[PC Preview]: unknow uri"
}
global.systemplugin.request = {
upload: function (...args) {
console.warn("system.request.upload interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
args[0].success(uploadResponseMock)
hasComplete(args[0].complete)
},
download: function (...args) {
console.warn("system.request.download interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
args[0].success(downloadResponse)
hasComplete(args[0].complete)
},
onDownloadComplete: function (...args) {
console.warn("system.request.onDownloadComplete interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
args[0].success(onDownloadCompleteMock)
hasComplete(args[0].complete)
}
}
}

View File

@ -0,0 +1,263 @@
import {getRandomArbitrary, hasComplete, paramMock} from './utils'
export function mockSensor() {
global.systemplugin.sensor = {}
mockAccelerometer()
mockBarometer()
mockCompass()
mockDeviceOrientation()
mockGyroscope()
mockHeartRate()
mockLight()
mockOnBodyState()
mockProximity()
mockStepCounter()
}
function mockAccelerometer() {
global.systemplugin.sensor.subscribeAccelerometer = function(...args) {
console.warn("sensor.subscribeAccelerometer interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const time = {
normal: 200,
game: 20,
ui: 60
}
let ret = {}
let timer = 0
if (!args[0].interval) {
timer = time.normal
} else {
timer = time[args[0].interval]
}
clearInterval(this.unsubscribeAcc)
delete this.unsubscribeAcc
this.unsubscribeAcc = setInterval(() => {
ret.x = Math.ceil(Math.random() * 10)
ret.y = Math.ceil(Math.random() * 10)
ret.z = Math.ceil(Math.random() * 10)
args[0].success(ret)
}, timer)
}
global.systemplugin.sensor.unsubscribeAccelerometer = function() {
console.warn("sensor.unsubscribeAccelerometer interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
clearInterval(this.unsubscribeAcc)
delete this.unsubscribeAcc
}
}
function mockBarometer() {
global.systemplugin.sensor.subscribeBarometer = function(...args) {
console.warn("sensor.subscribeBarometer interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
if (!this.unsubscribePressure) {
let ret = {}
this.unsubscribePressure = setInterval(() => {
ret.pressure = getRandomArbitrary(1110, 1111)
args[0].success(ret)
}, 500)
}
}
global.systemplugin.sensor.unsubscribeBarometer = function() {
console.warn("sensor.unsubscribeBarometer interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
clearInterval(this.unsubscribePressure)
delete this.unsubscribePressure
}
}
function mockCompass() {
global.systemplugin.sensor.subscribeCompass = function(...args) {
console.warn("sensor.subscribeCompass interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
if (!this.unsubscribeDirection) {
let ret = {}
this.unsubscribeDirection = setInterval(() => {
ret.direction = getRandomArbitrary(49, 50)
args[0].success(ret)
}, 100)
}
}
global.systemplugin.sensor.unsubscribeCompass = function() {
console.warn("sensor.unsubscribeCompass interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
clearInterval(this.unsubscribeDirection)
delete this.unsubscribeDirection
}
}
function mockGyroscope() {
global.systemplugin.sensor.subscribeGyroscope = function(...args) {
console.warn("sensor.subscribeGyroscope interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const time = {
normal: 200,
game: 20,
ui: 60
}
let ret = {}
let timer = 0
if (!args[0].interval) {
timer = time.normal
} else {
timer = time[args[0].interval]
}
clearInterval(this.unsubscribeGyr)
delete this.unsubscribeGyr
this.unsubscribeGyr = setInterval(() => {
ret.x = Math.ceil(Math.random() * 10)
ret.y = Math.ceil(Math.random() * 10)
ret.z = Math.ceil(Math.random() * 10)
args[0].success(ret)
}, timer)
}
global.systemplugin.sensor.unsubscribeGyroscope = function() {
console.warn("sensor.unsubscribeGyroscope interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
clearInterval(this.unsubscribeGyr)
delete this.unsubscribeGyr
}
}
function mockDeviceOrientation() {
global.systemplugin.sensor.subscribeDeviceOrientation = function(...args) {
console.warn("sensor.subscribeDeviceOrientation interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
const time = {
normal: 200,
game: 20,
ui: 60
}
let ret = {}
let timer = 0
if (!args[0].interval) {
timer = time.normal
} else {
timer = time[args[0].interval]
}
clearInterval(this.unsubscribeDevOri)
delete this.unsubscribeDevOri
this.unsubscribeDevOri = setInterval(() => {
ret.alpha = Math.ceil(Math.random() * 10)
ret.beta = Math.ceil(Math.random() * 10)
ret.gamma = Math.ceil(Math.random() * 10)
args[0].success(ret)
}, timer)
}
global.systemplugin.sensor.unsubscribeDeviceOrientation = function() {
console.warn("sensor.unsubscribeDeviceOrientation interface mocked in the Previewer. How this interface works" +
" on the Previewer may be different from that on a real device.")
clearInterval(this.unsubscribeDevOri)
delete this.unsubscribeDevOri
}
}
function mockHeartRate() {
global.systemplugin.sensor.subscribeHeartRate = function(...args) {
console.warn("sensor.subscribeHeartRate interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
if (!this.unsubscribeRate) {
let ret = {}
this.unsubscribeRate = setInterval(() => {
ret.heartRate = Math.ceil(Math.random() * 30)
args[0].success(ret)
}, 500)
}
},
global.systemplugin.sensor.unsubscribeHeartRate = function() {
console.warn("sensor.unsubscribeHeartRate interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
clearInterval(this.unsubscribeRate)
delete this.unsubscribeRate
}
}
function mockLight() {
global.systemplugin.sensor.subscribeLight = function(...args) {
console.warn("sensor.subscribeLight interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
if (!this.unsubscribeIntensity) {
let ret = {}
this.unsubscribeIntensity = setInterval(() => {
ret.intensity = getRandomArbitrary(660, 680)
args[0].success(ret)
}, 500)
}
}
global.systemplugin.sensor.unsubscribeLight = function() {
console.warn("sensor.unsubscribeLight interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
clearInterval(this.unsubscribeIntensity)
delete this.unsubscribeIntensity
}
}
function mockOnBodyState() {
global.systemplugin.sensor.subscribeOnBodyState = function(...args) {
console.warn("sensor.subscribeOnBodyState interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
if (!this.unsubscribeBodyState) {
let ret = {}
this.unsubscribeBodyState = setInterval(() => {
ret.value = Math.ceil(Math.random() * 20)
args[0].success(ret)
}, 500)
}
}
global.systemplugin.sensor.unsubscribeOnBodyState = function() {
console.warn("sensor.unsubscribeOnBodyState interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
clearInterval(this.unsubscribeBodyState)
delete this.unsubscribeBodyState
}
global.systemplugin.sensor.getOnBodyState = function (...args) {
console.warn("sensor.getOnBodyState interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
let OnBodyStateResponseMock = {
value: paramMock.paramBooleanMock
}
args[0].success(OnBodyStateResponseMock)
hasComplete(args[0].complete)
}
}
function mockProximity() {
global.systemplugin.sensor.subscribeProximity = function(...args) {
console.warn("sensor.subscribeProximity interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
if (!this.unsubscribeDistance) {
let ret = {}
this.unsubscribeDistance = setInterval(() => {
ret.distance = Math.ceil(Math.random() * 100)
args[0].success(ret)
}, 1000)
}
}
global.systemplugin.sensor.unsubscribeProximity = function() {
console.warn("sensor.unsubscribeProximity interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
clearInterval(this.unsubscribeDistance)
delete this.unsubscribeDistance
}
}
function mockStepCounter() {
global.systemplugin.sensor.subscribeStepCounter = function(...args) {
console.warn("sensor.subscribeStepCounter interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
if (!this.unsubscribeSteps) {
let ret = {steps: 0}
this.unsubscribeSteps = setInterval(() => {
ret.steps += 1
args[0].success(ret)
}, 1000)
}
}
global.systemplugin.sensor.unsubscribeStepCounter = function() {
console.warn("sensor.unsubscribeStepCounter interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
clearInterval(this.unsubscribeSteps)
delete this.unsubscribeSteps
}
}

View File

@ -0,0 +1,30 @@
import { hasComplete } from "./utils"
export function mockStorage() {
global.systemplugin.storage = {
get: function(...args) {
console.warn("storage.get interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
args[0].success("[PC Preview]: no system")
hasComplete(args[0].complete)
},
set: function(...args) {
console.warn("storage.set interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
args[0].success("[PC Preview]: no system")
hasComplete(args[0].complete)
},
clear: function(...args) {
console.warn("storage.clear interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
args[0].success("[PC Preview]: no system")
hasComplete(args[0].complete)
},
delete: function(...args) {
console.warn("storage.delete interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
args[0].success("[PC Preview]: no system")
hasComplete(args[0].complete)
}
}
}

View File

@ -0,0 +1,12 @@
import { hasComplete } from "./utils"
export function mockSystemPackage() {
global.systemplugin.package = {
hasInstalled: function (...args) {
console.warn("package.hasInstalled interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
args[0].success(true)
isComplete(args[0].complete)
}
}
}

View File

@ -1,502 +0,0 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export function mockSystemPlugin () {
global.systemplugin = {
notification:{},
vibrator: {},
sensor: {},
geolocation: {},
network: {},
brightness: {
argsV: {
value: 80
},
argsM: {
mode: 0
}
},
volume: {
args: {value: 0.5}
},
battery: {},
systemPackage: {},
wifi: {},
bluetooth: {},
tts: {},
alarm: {},
request: {},
fetch: {},
storage: {},
file: {}
}
mockNotification()
mockFetch()
mockRequest()
mockStorage()
mockFile()
mockVibrator()
mockSensor()
mockGeolocation()
mockNetwork()
mockBrightness()
mockVolume()
mockBattery()
mockSystemPackage()
}
function mockNotification () {
global.systemplugin.notification = {
show: function () {}
}
}
function mockVibrator () {
global.systemplugin.vibrator = {
vibrate: function () {
arguments[0].success()
isComplete(arguments[0].complete)
}
}
}
function mockSensor () {
mockAccelerometer()
mockCompass()
mockProximity()
mockLight()
mockStepCounter()
mockBarometer()
mockHeartRate()
mockOnBodyState()
}
function mockAccelerometer () {
Object.assign(global.systemplugin.sensor, {
subscribeAccelerometer: function () {
const time = {
normal: 200,
game: 20,
ui: 60
}
let ret = {}
let timer = 0
if(!arguments[0].interval) {
timer = time.normal
} else {
timer = time[arguments[0].interval]
}
this.unsubscribeAccelerometer()
this.unsubscribeAcc = setInterval(() => {
ret.x = Math.ceil(Math.random() * 10)
ret.y = Math.ceil(Math.random() * 10)
ret.z = Math.ceil(Math.random() * 10)
arguments[0].success(ret)
}, timer)
},
unsubscribeAccelerometer: function () {
clearInterval(this.unsubscribeAcc)
delete this.unsubscribeAcc
}
})
}
function mockCompass () {
Object.assign(global.systemplugin.sensor, {
subscribeCompass: function () {
if(!this.unsubscribeDirection) {
let ret = {}
this.unsubscribeDirection = setInterval(() => {
ret.direction = getRandomArbitrary(49, 50)
arguments[0].success(ret)
}, 100)
}
},
unsubscribeCompass: function () {
clearInterval(this.unsubscribeDirection)
delete this.unsubscribeDirection
}
})
}
function mockProximity() {
Object.assign(global.systemplugin.sensor, {
subscribeProximity: function () {
if(!this.unsubscribeDistance) {
let ret = {}
this.unsubscribeDistance = setInterval(() => {
ret.distance = Math.ceil(Math.random() * 100)
arguments[0].success(ret)
}, 1000)
}
},
unsubscribeProximity: function () {
clearInterval(this.unsubscribeDistance)
delete this.unsubscribeDistance
}
})
}
function mockLight () {
Object.assign(global.systemplugin.sensor, {
subscribeLight: function () {
if(!this.unsubscribeIntensity) {
let ret = {}
this.unsubscribeIntensity = setInterval(() => {
ret.intensity = getRandomArbitrary(660, 680)
arguments[0].success(ret)
}, 500)
}
},
unsubscribeLight: function () {
clearInterval(this.unsubscribeIntensity)
delete this.unsubscribeIntensity
},
})
}
function mockStepCounter() {
Object.assign(global.systemplugin.sensor, {
subscribeStepCounter: function () {
if(!this.unsubscribeSteps) {
let ret = { steps: 0 }
this.unsubscribeSteps = setInterval(() => {
ret.steps += 1
arguments[0].success(ret)
}, 1000)
}
},
unsubscribeStepCounter: function () {
clearInterval(this.unsubscribeSteps)
delete this.unsubscribeSteps
}
})
}
function mockBarometer() {
Object.assign(global.systemplugin.sensor, {
subscribeBarometer: function () {
if(!this.unsubscribePressure) {
let ret = {}
this.unsubscribePressure = setInterval(() => {
ret.pressure = getRandomArbitrary(1110, 1111)
arguments[0].success(ret)
}, 500)
}
},
unsubscribeBarometer: function () {
clearInterval(this.unsubscribePressure)
delete this.unsubscribePressure
}
})
}
function mockHeartRate() {
Object.assign(global.systemplugin.sensor, {
subscribeHeartRate: function () {
if(!this.unsubscribeRate) {
let ret = {}
this.unsubscribeRate = setInterval(() => {
ret.heartRate = Math.ceil(Math.random() * 30)
arguments[0].success(ret)
}, 500)
}
},
unsubscribeHeartRate: function () {
clearInterval(this.unsubscribeRate)
delete this.unsubscribeRate
},
})
}
function mockOnBodyState () {
Object.assign(global.systemplugin.sensor, {
subscribeOnBodyState: function () {
if(!this.unsubscribeBodyState) {
let ret = {}
this.unsubscribeBodyState = setInterval(() => {
ret.value = Math.ceil(Math.random() * 20)
arguments[0].success(ret)
}, 500)
}
},
unsubscribeOnBodyState: function () {
clearInterval(this.unsubscribeBodyState)
delete this.unsubscribeBodyState
}
})
}
function mockGeolocation () {
const data = {
latitude: '121.61934',
longitude: '31.257907',
accuracy: '15',
time: '160332896544'
}
global.systemplugin.geolocation = {
getLocation: function () {
arguments[0].success(data)
isComplete(arguments[0].complete)
},
getLocationType: function () {
let args = {types: ['gps', 'network']}
arguments[0].success(args)
isComplete(arguments[0].complete)
},
getSupportedCoordTypes() {
return ["wgs84"]
},
subscribe: function () {
if(!this.unsubscribeLocation) {
this.unsubscribeLocation = setInterval(() => {
data.latitude = getRandomArbitrary(121, 122)
data.longitude = getRandomArbitrary(31, 32)
data.accuracy = getRandomArbitrary(14, 18)
arguments[0].success(data)
}, 1000)
}
},
unsubscribe: function () {
clearInterval(this.unsubscribeLocation)
delete this.unsubscribeLocation
}
}
}
function mockNetwork () {
const data = {
metered: true,
type: "5g"
}
global.systemplugin.network = {
getType: function () {
arguments[0].success(data)
arguments[0].complete()
},
subscribe: function () {
if(!this.unsubscribeNetwork) {
this.unsubscribeNetwork = setInterval(() => {
arguments[0].success(data)
}, 3000)
}
},
unsubscribe: function () {
clearInterval(this.unsubscribeNetwork)
delete this.unsubscribeNetwork
}
}
}
function mockBrightness () {
Object.assign(global.systemplugin.brightness, {
getValue: function () {
arguments[0].success(this.argsV)
isComplete(arguments[0].complete)
},
setValue: function () {
if(arguments[0].value) {
this.argsV.value = arguments[0].value
arguments[0].success("brightness setValue successfully")
isComplete(arguments[0].complete)
}
},
getMode: function () {
arguments[0].success(this.argsM)
isComplete(arguments[0].complete)
},
setMode: function () {
this.argsM.mode = arguments[0].mode
arguments[0].success("brightness setMode successfully")
isComplete(arguments[0].complete)
},
setKeepScreenOn: function () {
arguments[0].success("brightness setKeepScreenOn successfully")
isComplete(arguments[0].complete)
}
})
}
function mockVolume () {
Object.assign(global.systemplugin.volume, {
getMediaValue: function () {
arguments[0].success(this.args)
isComplete(arguments[0].complete)
},
setMediaValue: function () {
if(arguments[0].value) {
this.args.value = arguments[0].value
arguments[0].success("set volume successfully")
isComplete(arguments[0].complete)
}
}
})
}
function mockBattery () {
global.systemplugin.battery = {
getStatus: function () {
arguments[0].success.call(this, { level: 1, charging: false} )
isComplete(arguments[0].complete)
}
}
}
function mockSystemPackage () {
global.systemplugin.package = {
hasInstalled: function () {
arguments[0].success(true)
isComplete(arguments[0].complete)
}
}
}
function mockRequest () {
const data = {
code: "[pc Preview]: no internet",
data: "[pc Preview]: no internet",
headers: "[pc Preview]: no internet",
token: "[pc Preview]: no internet",
uri: "[pc Preview]: no internet",
}
global.systemplugin.request = {
upload: function () {
arguments[0].success(data)
isComplete(arguments[0].complete)
},
download: function () {
arguments[0].success(data)
isComplete(arguments[0].complete)
},
onDownloadComplete: function () {
arguments[0].success(data)
isComplete(arguments[0].complete)
}
}
}
function mockFetch () {
const data = {
code: "[pc Preview]: no internet",
data: "[pc Preview]: no internet"
}
global.systemplugin.fetch = {
fetch: function () {
arguments[0].success(data)
isComplete(arguments[0].complete)
}
}
}
function mockStorage () {
global.systemplugin.storage = {
get: function () {
arguments[0].success("[pc Preview]: no system")
isComplete(arguments[0].complete)
},
set: function () {
arguments[0].success("[pc Preview]: no system")
isComplete(arguments[0].complete)
},
clear: function () {
arguments[0].success("[pc Preview]: no system")
isComplete(arguments[0].complete)
},
delete: function () {
arguments[0].success("[pc Preview]: no system")
isComplete(arguments[0].complete)
}
}
}
function mockFile () {
global.systemplugin.file = {
move: function () {
arguments[0].success(arguments[0].dstUri)
isComplete(arguments[0].complete)
},
copy: function () {
arguments[0].success(arguments[0].dstUri)
isComplete(arguments[0].complete)
},
list: function () {
const data = {
fileList: [{
uri:'[pc Preview]: no file',
lastModifiedTime:"[pc Preview]: no file",
length:"[pc Preview]: no file",
type: 'file'}]
}
arguments[0].success(data)
isComplete(arguments[0].complete)
},
get: function () {
const data = {
uri:'[pc Preview]: no file',
lastModifiedTime:"[pc Preview]: no file",
length:"[pc Preview]: no file",
type: 'file',
subFiles: ["[pc Preview]: no file", "[pc Preview]: no file"]
}
arguments[0].success(data)
isComplete(arguments[0].complete)
},
delete: function () {
arguments[0].success()
isComplete(arguments[0].complete)
},
writeText: function () {
arguments[0].success()
isComplete(arguments[0].complete)
},
writeArrayBuffer: function () {
arguments[0].success()
isComplete(arguments[0].complete)
},
readText: function () {
const data = {text: "[pc Preview]: success default"}
arguments[0].success(data)
isComplete(arguments[0].complete)
},
readArrayBuffer: function () {
const data = {buffer: ["[pc Preview]: default", "[pc Preview]: default", "[pc Preview]: default"]}
arguments[0].success(data)
isComplete(arguments[0].complete)
},
access: function () {
arguments[0].success()
isComplete(arguments[0].complete)
},
mkdir: function () {
arguments[0].success()
isComplete(arguments[0].complete)
},
rmdir: function () {
arguments[0].success()
isComplete(arguments[0].complete)
}
}
}
function isComplete() {
if(arguments[0] === undefined) {
return
}
arguments[0].call(this)
}
function getRandomArbitrary(min, max) {
return Math.random().toFixed(6) * (max - min) + min;
}

View File

@ -0,0 +1,19 @@
import { paramMock } from "./utils"
export function mockCall() {
global.systemplugin.telephony = {}
global.systemplugin.telephony.call = {
dial: function (...args) {
console.warn("telephony.call.dial interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramBooleanMock);
})
}
}
}
}

View File

@ -0,0 +1,26 @@
import { paramMock } from "./utils"
export function mockUserauth() {
global.systemplugin.userIAM = {}
const AuthenticatorMock = {
execuate: function (...args) {
console.warn("Authenticator.execuate interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock);
} else {
return new Promise((resolve, reject) => {
resolve(paramMock.paramNumberMock);
})
}
}
}
global.systemplugin.userIAM.userAuth = {
getAuthenticator: function (...args) {
console.warn("userIAM.userAuth.getAuthenticator interface mocked in the Previewer. How this interface works on" +
" the Previewer may be different from that on a real device.")
return AuthenticatorMock;
}
}
}

View File

@ -0,0 +1,24 @@
export function hasComplete(...args) {
if (args[0] === undefined) {
return
}
args[0].call(this)
}
export function getRandomArbitrary(min, max) {
return Math.random().toFixed(6) * (max - min) + min;
}
export const paramMock = {
businessErrorMock: {
code: '[PC Preview]: unknow code',
name: '[PC Preview]: unknow name',
message: '[PC Preview]: unknow message',
stack: '[PC Preview]: unknow stack'
},
paramNumberMock: "[PC Preview] unknow number",
paramStringMock: "[PC Preview] unknow string",
paramBooleanMock: "[PC Preview] unknow boolean",
paramObjectMock: "[PC Preview] unknow object",
paramArrayMock: "[PC Preview] unknow Array"
}

View File

@ -0,0 +1,12 @@
import { hasComplete } from "./utils"
export function mockVibrator() {
global.systemplugin.vibrator = {
vibrate: function (...args) {
console.warn("vibrator.vibrate interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
args[0].success()
hasComplete(args[0].complete)
}
}
}

View File

@ -0,0 +1,35 @@
import { paramMock } from "./utils"
export function mockWifi() {
const linkedInfoMock = {
ssid: '[PC preview] unknow ssid',
bssid: '[PC preview] unknow bssid',
networkId: '[PC preview] unknow networkId',
rssi: '[PC preview] unknow rssi',
band: '[PC preview] unknow band',
linkSpeed: '[PC preview] unknow linkSpeed',
frequency: '[PC preview] unknow frequency',
isHidden: '[PC preview] unknow isHidden',
isRestricted: '[PC preview] unknow isRestricted',
chload: '[PC preview] unknow chload',
snr: '[PC preview] unknow snr',
macAddress: '[PC preview] unknow macAddress',
ipAddress: '[PC preview] unknow ipAddress',
suppState: '[PC preview] unknow suppState',
connState: '[PC preview] unknow connState'
}
global.systemplugin.wifi = {
getLinkedInfo: function (...args) {
console.warn("wifi.getLinkedInfo interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, linkedInfoMock)
} else {
return new Promise((resolve) => {
resolve(linkedInfoMock)
})
}
}
}
}

View File

@ -0,0 +1,327 @@
import { paramMock } from "./utils"
export function mockWindow() {
const windowPropertiesMock = {
brightness: '[PC preview] unknow brightness',
isFullScreen: '[PC preview] unknow isFullScreen',
isKeepScreenOn: '[PC preview] unknow isKeepScreenOn',
isPrivacyMode: '[PC preview] unknow isPrivacyMode',
touchable: '[PC preview] unknow touchable',
focusable: '[PC preview] unknow focusable',
isLayoutFullScreen: '[PC preview] unknow isLayoutFullScreen',
isDimBehind: '[PC preview] unknow isDimBehind',
isTransparent: '[PC preview] unknow isTransparent',
isRoundCorner: '[PC preview] unknow isRoundCorner'
}
const AvoidAreaMock = {
left: '[PC preview] unknow Rect.left Rect.top Rect.right Rect.bottom',
top: '[PC preview] unknow Rect.left Rect.top Rect.right Rect.bottom',
right: '[PC preview] unknow Rect.left Rect.top Rect.right Rect.bottom',
bottom: '[PC preview] unknow Rect.left Rect.top Rect.right Rect.bottom'
}
const windowMock = {
setBrightness: function (...args) {
console.warn("Window.setBrightness interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
setBackgroundColor: function (...args) {
console.warn("Window.setBackgroundColor interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
setFullScreen: function (...args) {
console.warn("Window.setFullScreen interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
setKeepScreenOn: function (...args) {
console.warn("Window.setKeepScreenOn interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
setSystemBarProperties: function (...args) {
console.warn("Window.setSystemBarProperties interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
getProperties: function (...args) {
console.warn("Window.getProperties interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, windowPropertiesMock)
} else {
return new Promise((resolve) => {
resolve(windowPropertiesMock)
})
}
},
on: function (...args) {
console.warn("Window.on interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramNumberMock)
},
off: function (...args) {
console.warn("Window.off interface mocked in the Previewer. How this interface works on the Previewer may be" +
" different from that on a real device.")
const len = args.length
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramNumberMock)
},
setSystemBarEnable: function (...args) {
console.warn("Window.setSystemBarEnable interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
setTransparent: function (...args) {
console.warn("Window.setTransparent interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
setWindowType: function (...args) {
console.warn("Window.setWindowType interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
setPrivacyMode: function (...args) {
console.warn("Window.setPrivacyMode interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
setTouchable: function (...args) {
console.warn("Window.setTouchable interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
setFocusable: function (...args) {
console.warn("Window.setFocusable interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
setLayoutFullScreen: function (...args) {
console.warn("Window.setLayoutFullScreen interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
getAvoidArea: function (...args) {
console.warn("Window.getAvoidArea interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, AvoidAreaMock)
} else {
return new Promise((resolve) => {
resolve(AvoidAreaMock)
})
}
},
setDimBehind: function (...args) {
console.warn("Window.setDimBehind interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
loadContent: function (...args) {
console.warn("Window.loadContent interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
hide: function (...args) {
console.warn("Window.hide interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
show: function (...args) {
console.warn("Window.show interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
isShowing: function (...args) {
console.warn("Window.isShowing interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, paramMock.paramBooleanMock)
} else {
return new Promise((resolve) => {
resolve(paramMock.paramBooleanMock)
})
}
},
destroy: function (...args) {
console.warn("Window.destroy interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
setOutsideTouchable: function (...args) {
console.warn("Window.setOutsideTouchable interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock)
} else {
return new Promise((resolve) => {
resolve()
})
}
},
}
global.systemplugin.window = {
getTopWindow: function (...args) {
console.warn("window.getTopWindow interface mocked in the Previewer. How this interface works on the Previewer" +
" may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, windowMock)
} else {
return new Promise((resolve, reject) => {
resolve(windowMock)
})
}
},
create: function (...args) {
console.warn("Window.create interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, windowMock)
} else {
return new Promise((resolve, reject) => {
resolve(windowMock)
})
}
},
find: function (...args) {
console.warn("Window.find interface mocked in the Previewer. How this interface works on the" +
" Previewer may be different from that on a real device.")
const len = args.length
if (typeof args[len - 1] === 'function') {
args[len - 1].call(this, paramMock.businessErrorMock, windowMock)
} else {
return new Promise((resolve, reject) => {
resolve(windowMock)
})
}
},
}
}

View File

@ -22,12 +22,16 @@ export { createInstance, destroyInstance } from './manage/instance/life';
import { registerModules } from './manage/instance/register';
export { receiveTasks } from './manage/event/bridge';
export { getRoot } from './manage/instance/misc';
import { appDestroy } from './app/index';
import { appError } from './app/index';
import {
appDestroy,
appError,
appShow,
appHide
} from './app/index';
/**
* Prevent modification of Vm and Vm.prototype.
*/
Object.freeze(Vm);
export { registerModules, appDestroy, appError };
export { registerModules, appDestroy, appError, appShow, appHide };

View File

@ -17,8 +17,6 @@
* under the License.
*/
import { Log } from '../../../utils/index';
export interface callbackObjInterface {
[key: string]: Function;
}
@ -73,12 +71,7 @@ export default class CallbackManager {
delete this.callbackMap[callbackId];
}
if (typeof callback === 'function') {
try {
return callback.call(null, data);
} catch (error) {
Log.error(`Failed to execute the callback function:\n ${error.toString()}`);
throw error;
}
return callback.call(null, data);
}
return new Error(`Invalid callback id '${callbackId}'.`);
}

View File

@ -210,6 +210,8 @@ export class TaskCenter {
return ace.callNative(JSON.stringify(options), args);
case 'timer':
return ace.callNative(JSON.stringify(options), args);
case 'system.offscreenCanvas':
return ace.callNative(JSON.stringify(options), JSON.stringify(args[0]));
case 'system.image':
return ace.callNative(JSON.stringify(options), JSON.stringify(args[0]));
case 'system.mediaquery':
@ -218,6 +220,8 @@ export class TaskCenter {
return ace.callNative(JSON.stringify(options), args[0]);
case 'system.resource':
return ace.callNative(JSON.stringify(options), args);
case 'ohos.animator':
return ace.callNative(JSON.stringify(options), JSON.stringify(args[0]));
default:
break;
}

View File

@ -43,7 +43,7 @@ export function createInstance(id: string, code: string, options: Options, data:
let page: Page = pageMap.get(id);
let result: object;
if (!page) {
page = new Page(id, options, options.packageName);
page = new Page(id, options, options.packageName, data);
page.i18nService = I18n;
page.dpiService = dpi;
appCreate(page, options, data, services);

View File

@ -78,7 +78,8 @@ export interface AttrInterface {
tid: number;
append: string;
slot: string;
name: string
name: string;
data: () => any | string;
}
export interface TemplateInterface {
@ -221,8 +222,7 @@ function targetIsComposed(vm: Vm, type: string): VmOptions {
if (!component.initObjectData) {
component.initObjectData = component.data;
}
const str = JSON.stringify(component.initObjectData);
component.data = JSON.parse(str);
component.data = Object.assign({}, component.initObjectData);
}
}
return component;
@ -272,7 +272,7 @@ function compileRepeat(vm: Vm, target: TemplateInterface, dest: Element): void {
if (isRepeat(repeat)) {
getter = repeat.exp;
key = repeat.key;
key = repeat.key || '$idx';
value = repeat.value;
trackBy = repeat.tid;
} else {
@ -406,7 +406,10 @@ function compileCustomComponent(
* @param {Element} element - To be reset.
*/
function resetElementStyle(vm: Vm, element: Element): void {
// Add judgment statements to avoid repeatedly calling 'setClass' function.
const len = element.children.length;
const css = vm.css || {};
const mqArr = css['@MEDIA'];
for (let ii = 0; ii < len; ii++) {
const el = element.children[ii] as Element;
resetElementStyle(vm, el);
@ -417,8 +420,15 @@ function resetElementStyle(vm: Vm, element: Element): void {
if (element.id) {
setIdStyle(vm, element, element.id);
}
if (element.classList) {
setClass(vm, element, element.classList);
if (element.classList && mqArr) {
for (let i = 0; i < element.classList.length; i++) {
for (let m = 0; m < mqArr.length; m++) {
const clsKey = '.' + element.classList[i];
if (hasOwn(mqArr[m], clsKey)) {
setClass(vm, element, element.classList);
}
}
}
}
}
@ -444,6 +454,7 @@ function compileNativeComponent(vm: Vm, template: TemplateInterface, dest: FragB
vm.mediaStatus['device-width'] = e.deviceWidth;
vm.mediaStatus['device-height'] = e.deviceHeight;
vm.mediaStatus['round-screen'] = e.roundScreen;
vm.mediaStatus['dark-mode'] = e.darkMode;
const css = vm.vmOptions && vm.vmOptions.style || {};
const mqArr = css['@MEDIA'];
if (!mqArr) {
@ -501,8 +512,8 @@ function compileNativeComponent(vm: Vm, template: TemplateInterface, dest: FragB
// Dest is parent element.
bindElement(vm, element, template, dest);
if (element.event && element.event['appear']) {
element.fireEvent('appear', {});
if (element.event && element.event['attached']) {
element.fireEvent('attached', {});
}
if (template.attr && template.attr.append) {

View File

@ -52,6 +52,7 @@ import Element from '../../vdom/Element';
const SETTERS = {
attr: 'setAttr',
style: 'setStyle',
data: 'setData',
event: 'addEvent',
idStyle: 'setIdStyle',
tagStyle: 'setTagStyle'
@ -65,14 +66,6 @@ const SETTERS = {
* @param {Element | FragBlockInterface} parentElement - Parent element of current element.
*/
export function bindElement(vm: Vm, el: Element, template: TemplateInterface, parentElement: Element | FragBlockInterface): void {
setId(vm, el, template.id, vm);
setAttr(vm, el, template.attr);
setStyle(vm, el, template.style);
setIdStyle(vm, el, template.id);
setClass(vm, el, template.classList);
setTagStyle(vm, el, template.type);
applyStyle(vm, el);
// Set descendant style.
setDescendantStyle(
vm.selector,
@ -93,11 +86,36 @@ export function bindElement(vm: Vm, el: Element, template: TemplateInterface, pa
setStyle(vm, el, style);
}
);
// inherit 'show' attribute of custom component
if (el.isCustomComponent) {
const value = vm['show'];
if (template.attr && value !== undefined) {
if (typeof value === 'function') {
// vm['show'] is assigned to this.show in initPropsToData()
template.attr['show'] = function() {
return this.show;
};
} else {
template.attr['show'] = value;
}
}
}
setId(vm, el, template.id, vm);
setAttr(vm, el, template.attr);
setStyle(vm, el, template.style);
setIdStyle(vm, el, template.id);
setClass(vm, el, template.classList);
setTagStyle(vm, el, template.type);
applyStyle(vm, el);
bindEvents(vm, el, template.events);
bindEvents(vm, el, template.onBubbleEvents, '');
bindEvents(vm, el, template.onCaptureEvents, 'capture');
bindEvents(vm, el, template.catchBubbleEvents, 'catchbubble');
bindEvents(vm, el, template.catchCaptureEvents, 'catchcapture');
if (!vm.isHide && !vm.init) {
el.addEvent('hide');
vm.isHide = true;
@ -196,7 +214,12 @@ function mergePropsObject(key: string, value: any, vm: Vm, subVm: Vm): any {
const returnValue = watch(vm, value, function(v) {
subVm[key] = v;
});
subVm[key] = returnValue;
// 'show' attribute will be inherited by elements in custom component
if (key === 'show') {
subVm[key] = value;
} else {
subVm[key] = returnValue;
}
} else {
const realValue =
value && value.__hasDefault ? value.__isDefaultValue : value;
@ -217,14 +240,19 @@ function mergeProps(target: object, props: any, vm: Vm, subVm: Vm): void {
return;
}
for (const key in target) {
if (!props || props[key]) {
if (!props || props[key] || key === 'show') {
subVm.props.push(key);
const value = target[key];
if (typeof value === 'function') {
const returnValue = watch(vm, value, function(v) {
subVm[key] = v;
});
subVm[key] = returnValue;
// 'show' attribute will be inherited by elements in custom component
if (key === 'show') {
subVm[key] = value;
} else {
subVm[key] = returnValue;
}
} else {
subVm[key] = value;
}
@ -351,6 +379,10 @@ function setElementId(el: Element, id: string): void {
* @param {AttrInterface} attr - Attr to bind.
*/
function setAttr(vm: Vm, el: Element, attr: Partial<AttrInterface>): void {
if (attr && attr.data) {
// address data independently
bindDir(vm, el, 'data', attr.data);
}
bindDir(vm, el, 'attr', attr);
}
@ -538,6 +570,7 @@ function setClassStyle(el: Element, css: object, classList: string[], vm?: Vm):
const animationName = classStyle['animationName'];
if (animationName) {
classStyle['animationName'] = keyframes[animationName];
classStyle['animationName'].push({'animationName': animationName});
}
const transitionEnter = classStyle['transitionEnter'];
if (transitionEnter) {
@ -648,6 +681,7 @@ function setAnimation(style: any, css: any): void {
const keyframes = css['@KEYFRAMES'];
if (animationName && keyframes) {
style['animationName'] = keyframes[animationName];
style['animationName'].push({'animationName': animationName});
}
}

View File

@ -234,9 +234,6 @@ export function removeTarget(target: Element | FragBlockInterface, preserveBlock
*/
function removeElement(target: Element | Comment): void {
const parent = target.parentNode as Element;
if (target instanceof Element && target.event && target.event['disappear']) {
target.fireEvent('disappear', {});
}
if (parent) {
parent.removeChild(target);
}

65
runtime/main/model/index.ts Executable file → Normal file
View File

@ -64,6 +64,9 @@ import {
MediaStatusInterface,
ExternalBindingInterface
} from './vmOptions';
import {
hasOwn
} from '../util/shared';
/**
* VM constructor.
@ -142,8 +145,8 @@ export default class Vm {
`'_innerInit' lifecycle in Vm(${this._type}) and mergedData = ${JSON.stringify(mergedData)}.`
);
this.$emit('hook:_innerInit');
this._data = typeof data === 'function' ? data.apply(this) : data;
this._shareData = typeof shareData === 'function' ? shareData.apply(this) : shareData;
this._data = (typeof data === 'function' ? data.apply(this) : data) || {};
this._shareData = (typeof shareData === 'function' ? shareData.apply(this) : shareData) || {};
this._descriptor = options._descriptor;
if (global.aceapp && global.aceapp.i18n && global.aceapp.i18n.extend) {
global.aceapp.i18n.extend(this);
@ -154,14 +157,30 @@ export default class Vm {
// MergedData means extras params.
if (mergedData) {
dataAccessControl(this, mergedData, this._app.options && this._app.options.appCreate);
extend(this._data, mergedData);
if (hasOwn(mergedData, 'paramsData') && hasOwn(mergedData, 'dontOverwrite') && mergedData['dontOverwrite'] === false) {
dataAccessControl(this, mergedData['paramsData'], this._app.options && this._app.options.appCreate);
extend(this._data, mergedData['paramsData']);
} else {
dataAccessControl(this, mergedData, this._app.options && this._app.options.appCreate);
extend(this._data, mergedData);
}
}
initPropsToData(this);
initState(this);
initBases(this);
Log.debug(`"onInit" lifecycle in Vm(${this._type})`);
this.$emit('hook:onInit');
if (mergedData && hasOwn(mergedData, 'paramsData') && hasOwn(mergedData, 'dontOverwrite')) {
if (mergedData['dontOverwrite'] === false) {
this.$emit('hook:onInit');
} else {
this.$emitDirect('hook:onInit', mergedData['paramsData']);
}
} else {
this.$emit('hook:onInit');
}
if (!this._app.doc) {
return;
}
@ -175,6 +194,7 @@ export default class Vm {
this.mediaStatus['device-width'] = this._app.options.deviceWidth;
this.mediaStatus['device-height'] = this._app.options.deviceHeight;
this.mediaStatus['round-screen'] = this._app.options.roundScreen;
this.mediaStatus['dark-mode'] = this._app.options.darkMode;
// If there is no parentElement, specify the documentElement.
this._parentEl = parentEl || this._app.doc.documentElement;
@ -404,15 +424,15 @@ export default class Vm {
/**
* Watch a calc function and callback if the calc value changes.
* @param {string} data - Data that needed.
* @param {Function} callback - Callback function.
* @param {Function | string} callback - Callback function.
*/
public $watch(data: string, callback: (...args: any) => any): void {
public $watch(data: string, callback: ((...args: any) => any) | string): void {
if (typeof data !== 'string') {
Log.warn(`Invalid parameter type: The type of 'data' should be string, not ${typeof data}.`);
return;
}
if (typeof callback !== 'function') {
Log.warn(`Invalid parameter type: The type of 'callback' should be function, not ${typeof callback}.`);
if (typeof callback !== 'function' && typeof callback !== 'string') {
Log.warn(`Invalid parameter type: The type of 'callback' should be function or string, not ${typeof callback}.`);
return;
}
watch(this, data, callback);
@ -446,12 +466,12 @@ export default class Vm {
/**
* Delete Vm object.
* @param {Vm} vm - Vm object.
*/
public destroyVm(vm: Vm): void {
Log.debug(`[JS Framework] "onDestroy" lifecycle in Vm(${vm.type})`);
public destroy(): void {
Log.debug(`[JS Framework] "onDestroy" lifecycle in Vm(${this.type})`);
this.$emit('hook:onDestroy');
vm.$emit('hook:onDetached');
this.$emit('hook:onDetached');
fireNodeDetached(this._rootEl);
this._valid = false;
delete this._app;
@ -469,7 +489,7 @@ export default class Vm {
if (this._childrenVms) {
let vmCount: number = this._childrenVms.length;
while (vmCount--) {
this.destroyVm.call(this._childrenVms[vmCount], this._childrenVms[vmCount]);
this.destroy.call(this._childrenVms[vmCount], this._childrenVms[vmCount]);
}
delete this._childrenVms;
}
@ -833,7 +853,7 @@ function _proxySet(data: object, key: string, value: any): void {
* @param {boolean} external - If has external data.
*/
function dataAccessControl(vm: any, mergedData: object, external: boolean): void {
if (vm._descriptor) {
if (vm._descriptor && Object.keys(vm._descriptor).length !== 0) {
const keys = Object.keys(mergedData);
keys.forEach(key => {
const desc = vm._descriptor[key];
@ -860,3 +880,18 @@ function getRoot(vm: any): Vm {
}
return getRoot(parent);
}
/**
* order node and fire detached event.
* @param {Element} el - Element object.
*/
function fireNodeDetached(el: Element) {
if (el.event && el.event['detached']) {
el.fireEvent('detached', {});
}
if (el.children && el.children.length !== 0) {
for (const child of el.children) {
fireNodeDetached(child as Element);
}
}
}

View File

@ -171,7 +171,7 @@ export function bindPageLifeCycle(vm: Vm, element: Element): void {
emitSubVmLife(vm, 'onPageHide');
vm.visible = false;
} else if (type === PageLifecycleHooks.ONCONFIGURATIONUPDATED) {
return vm.$emitDirect('hook:${type}', ...args);
return vm.$emitDirect(`hook:${type}`, ...args);
}
Log.debug(`EventHandle: isEmitEvent = ${isEmitEvent}, event = ${event}, args = ${JSON.stringify(args)}.`);
@ -233,10 +233,10 @@ export function bindPageLifeCycle(vm: Vm, element: Element): void {
* Watch a calc function and callback if the calc value changes.
* @param {Vm} vm - Vm object.
* @param {string} data - Data that needed.
* @param {Function} callback - Callback function.
* @param {Function | string} callback - Callback function.
* @return {*}
*/
export function watch(vm: Vm, data: string, callback: (...args: any) => any): any {
export function watch(vm: Vm, data: string, callback: ((...args: any) => any) | string): any {
function calc() {
let arr = [];
arr = data.split('.');

View File

@ -52,5 +52,6 @@ export interface MediaStatusInterface<T, K> {
'aspect-ratio': T,
'device-width': T,
'device-height': T,
'dark-mode': T,
'round-screen': K
}

View File

@ -51,10 +51,8 @@ export class Image {
width: this._width,
height: this._height,
success: data => {
this._width = data.width;
this._height = data.height;
if (this.onload && typeof this.onload === 'function') {
this.onload();
this.onload(data);
}
},
fail: data => {

View File

@ -0,0 +1,75 @@
import Page from './index';
let offscreenCanvas;
export class OffscreenCanvas {
private _bridge: OffscreenCanvasBridge;
private _width: number;
private _height: number;
constructor(page: Page, width: number, height: number) {
offscreenCanvas = page.requireModule('system.offscreenCanvas');
this._height = height;
this._width = width;
this._bridge = offscreenCanvas.create({
width: this._width,
height: this._height
});
}
public getContext(contextId: '2d', options?: CanvasRenderingContext2DSettings): OffscreenCanvasRenderingContext2D {
return this._bridge.getContext('2d');
}
public transferToImageBitmap(): ImageBitmap {
return this._bridge.transferToImageBitmap();
}
public toDataURL(type?: string, quality?: number): string {
return this._bridge.toDataURL(type, quality);
}
public get width() {
return this._width;
}
public set width(width) {
this._width = width;
}
public get height() {
return this._height;
}
public set height(height) {
this._height = height;
}
}
export interface OffscreenCanvasRenderingContext2D {
}
export interface OffscreenCanvasBridge {
getContext: (contextId: '2d', options?: CanvasRenderingContext2DSettings)=>OffscreenCanvasRenderingContext2D;
transferToImageBitmap: ()=>ImageBitmap;
toDataURL:(type?: string, quality?: number)=>string;
}
export interface CanvasRenderingContext2DSettings {
alpha?: boolean;
desynchronized?: boolean;
}
export class ImageBitmap {
readonly height: number;
readonly width: number;
private _bridgeId: number;
constructor(bridgeId: number) {
this._bridgeId = bridgeId;
}
public get bridgeId() {
return this._bridgeId;
}
public set bridgeId(bridgeId) {
this._bridgeId = bridgeId;
}
}

View File

@ -57,8 +57,9 @@ export default class Page {
private _dpiService: object;
private _lastSignal: number;
private _destroyed: boolean;
private readonly _routerParams: any;
constructor(id: string, options: Options, packageName: string) {
constructor(id: string, options: Options, packageName: string, data: object) {
this._packageName = packageName || 'notset';
this._id = id;
this._options = options || null;
@ -67,6 +68,7 @@ export default class Page {
this._commonModules = {};
this._doc = new Document(id, this._options.bundleUrl);
this._differ = new Differ(id);
this._routerParams = data;
}
/**
@ -234,4 +236,12 @@ export default class Page {
public callTasks(tasks: Task[] | Task): any {
return callTasks(this, tasks);
}
/**
* get params from other page.
* @type {Object}
*/
get routerParams() {
return this._routerParams;
}
}

View File

@ -17,6 +17,8 @@
* under the License.
*/
import { hasOwn } from '../../../utils/index';
/**
* This class provides action for page refresh.
*/
@ -121,9 +123,11 @@ function callTypeMap(group: any, type: string): void {
function callTypeList(group: any, type: string): void {
const map: any = group[type];
for (const ref in map) {
const list: Function[] = map[ref];
list.forEach((handler) => {
handler();
});
if (hasOwn(map, ref)) {
const list: Function[] = map[ref];
list.forEach((handler) => {
handler();
});
}
}
}

View File

@ -44,7 +44,7 @@ export function destroy(page: Page): void {
Log.debug(`Destroy a page(${page.id}).`);
if (page.vm) {
page.vm.destroyVm(page.vm);
page.vm.destroy();
}
page.id = null;

View File

@ -34,6 +34,7 @@ import {
import { appMap } from '../../app/map';
import Vm from '../../model/index';
import Page from '../index';
import {updateDpi, updateLocale} from '../../app';
/**
* Parse page code.
@ -95,6 +96,14 @@ export function bootstrap(page: Page, name: string, data: any): any {
return new Error(`Wrong component name: ${name}.`);
}
// Set i18n and dpi data.
if (global && global.aceapp && page.options && page.options.i18n) {
updateLocale(page.options.i18n);
}
if (global && global.aceapp && page.options && page.options.resourcesConfiguration) {
updateDpi(page.options.resourcesConfiguration);
}
// Start i18n service.
if (global && global.aceapp && global.aceapp._i18n_data_ && page.i18nService) {
const I18nService: any = page.i18nService;

View File

@ -37,6 +37,7 @@ import {
import { updateActions } from '../api/misc';
import { getPageGlobal } from '../../app/helper';
import { Image } from '../Image';
import { OffscreenCanvas } from '../OffscreenCanvas';
import Page from '../index';
import { Services } from '../../app/index';
import { requireModule } from '../register';
@ -47,6 +48,7 @@ interface ParseOptions {
$app_bootstrap$(name: string): void; // eslint-disable-line camelcase
$app_require$(name: string): void; // eslint-disable-line camelcase
Image(): void;
OffscreenCanvas(width, height): void;
}
/**
@ -88,11 +90,15 @@ export function init(page: Page, code: string | Function, data: object, services
const imageObj: () => Image = function() {
return new Image(page);
};
const offscreenCanvasObj: (width, height) => OffscreenCanvas = function(width, height) {
return new OffscreenCanvas(page, width, height);
};
const options: ParseOptions = {
$app_define$: pageDefine,
$app_bootstrap$: pageBoot,
$app_require$: pageRequireModule,
Image: imageObj
Image: imageObj,
OffscreenCanvas: offscreenCanvasObj
};
// Support page global and init language.

View File

@ -163,6 +163,11 @@ function bind(app: Page | Function, target: object, methods: object, moduleName:
promise = needPromise ? ret.promise : undefined;
}
const appInstance: Page = typeof app === 'function' ? app() : app;
if (moduleName === 'system.router' && methodName === 'getParams') {
if (appInstance.routerParams) {
return appInstance.routerParams.paramsData;
}
}
const ret: any = appInstance.callTasks({
module: moduleName,
method: methodName,

View File

@ -95,3 +95,31 @@ def(
}
}
)
/**
* Support includes for panda.
* @param {Number} index
* @param {*} val
* @return {Boolean}
*/
def(
arrayProto,
'includes',
function includes(param, start = 0) {
if (start >= this.length) return false
if (start < 0) {
start = start + this.length < 0 ? 0 : start + this.length;
}
if (Number.isNaN(param)) {
for (let i = start; i < this.length; i++) {
if (Number.isNaN(this[i])) return true;
}
} else {
for (let i = start; i < this.length; i++) {
if (this[i] === param) return true;
}
}
return false
}
)

View File

@ -33,6 +33,8 @@ export interface GlobalInterface {
createInstance: (id: string, code: string, config: Options, data: object) => any | Error;
registerModules: (modules: object) => void;
appDestroy: (packageName: string) => void;
appShow: (packageName: string) => void;
appHide: (packageName: string) => void;
appError: (packageName: string, errors: any) => void;
destroyInstance: (pageId: string) => any | Error;
getRoot: (...args: any[]) => any | Error;
@ -55,6 +57,8 @@ export function initFramework(): void {
'registerModules': globalApi.registerModules,
'appDestroy': globalApi.appDestroy,
'appError': globalApi.appError,
'appShow': globalApi.appShow,
'appHide': globalApi.appHide,
'destroyInstance': globalApi.destroyInstance,
'getRoot': globalApi.getRoot,
'callJS': globalApi.callJS
@ -86,17 +90,19 @@ export function initFramework(): void {
}
const ModulesInfo: Record<string, string[]>[] = [
{'system.router': ['push', 'replace', 'back', 'clear', 'getLength', 'getState']},
{'system.router': ['push', 'replace', 'back', 'clear', 'getLength', 'getState', 'enableAlertBeforeBackPage', 'disableAlertBeforeBackPage', 'getParams']},
{'system.app': ['getInfo', 'getPackageInfo', 'terminate', 'requestFullWindow', 'screenOnVisible', 'setSwipeToDismiss']},
{'system.prompt': ['showToast', 'showDialog']},
{'system.prompt': ['showToast', 'showDialog', 'showActionMenu']},
{'system.configuration': ['getLocale']},
{'timer': ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval']},
{'system.image': ['getImage']},
{'system.offscreenCanvas': ['create']},
{'system.device': ['getInfo']},
{'system.grid': ['getSystemLayoutInfo']},
{'system.mediaquery': ['addListener', 'getDeviceType']},
{'animation': ['requestAnimationFrame', 'cancelAnimationFrame']},
{'system.resource': ['readText']}
{'system.resource': ['readText']},
{'ohos.animator': ['createAnimator']}
];
type components<T> = {
@ -105,90 +111,91 @@ type components<T> = {
}
const ComponentsInfo: components<string>[] = [
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'clock'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'image'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'label'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'list-item'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'list-item-group'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'progress'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'rating'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'select'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'switch'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'tabs'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'tab-bar'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'tab-content'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'text'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'clock'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'image'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'label'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'list-item'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'list-item-group'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'progress'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'rating'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'select'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'switch'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'tabs'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'tab-bar'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'tab-content'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'text'},
{'methods': ['focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'div'},
{
'methods': ['setProgress', 'focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'],
'methods': ['setProgress', 'focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'],
'type': 'button'
},
{'methods': ['append', 'focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'chart'},
{'methods': ['goto', 'focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'calendar'},
{'methods': ['append', 'focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'chart'},
{'methods': ['goto', 'focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'calendar'},
{
'methods': ['getContext', 'toDataURL', 'animate', 'focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'],
'methods': ['getContext', 'toDataURL', 'focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'],
'type': 'canvas'
},
{'methods': ['show', 'close', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'dialog'},
{'methods': ['focus', 'animate', 'getScrollOffset', 'scrollBy', 'getBoundingClientRect'], 'type': 'div'},
{'methods': ['animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'divider'},
{
'methods': ['getColumns', 'getColumnWidth', 'getGutterWidth', 'getSizeType', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'],
'methods': ['getXComponentContext', 'createIntersectionObserver'],
'type': 'xcomponent'
},
{'methods': ['show', 'close', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'dialog'},
{'methods': ['animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'divider'},
{
'methods': ['getColumns', 'getColumnWidth', 'getGutterWidth', 'getSizeType', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'],
'type': 'grid-container'
},
{
'methods': ['start', 'stop', 'pause', 'resume', 'getState', 'animate', 'focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'],
'methods': ['start', 'stop', 'pause', 'resume', 'getState', 'focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'],
'type': 'image-animator'
},
{
'methods': ['showError', 'focus', 'animate', 'delete', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'],
'methods': ['showError', 'delete', 'focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'],
'type': 'input'
},
{
'methods': ['scrollTo', 'scrollBy', 'focus', 'scrollArrow', 'scrollTop', 'scrollBottom', 'scrollPage', 'collapseGroup', 'expandGroup', 'currentOffset', 'rotation', 'animate', 'chainanimation', 'getBoundingClientRect', 'getScrollOffset'],
'methods': ['scrollTo', 'scrollBy', 'focus', 'scrollArrow', 'scrollTop', 'scrollBottom', 'scrollPage', 'collapseGroup', 'expandGroup', 'currentOffset', 'rotation', 'animate', 'chainanimation', 'getBoundingClientRect', 'getScrollOffset', 'createIntersectionObserver'],
'type': 'list'
},
{
'methods': ['start', 'stop', 'focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'],
'methods': ['start', 'stop', 'focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'],
'type': 'marquee'
},
{'methods': ['show', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'menu'},
{'methods': ['focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'option'},
{'methods': ['show', 'close', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'panel'},
{'methods': ['show', 'animate', 'focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'picker'},
{'methods': ['show', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'menu'},
{'methods': ['focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'option'},
{'methods': ['show', 'close', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'panel'},
{'methods': ['show', 'animate', 'focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'picker'},
{
'methods': ['rotation', 'animate', 'focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'],
'methods': ['rotation', 'animate', 'focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'],
'type': 'picker-view'
},
{'methods': ['focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'piece'},
{'methods': ['focus', 'show', 'hide', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'popup'},
{'methods': ['animate', 'focus', 'delete', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'], 'type': 'search'},
{'methods': ['focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'piece'},
{'methods': ['focus', 'show', 'hide', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'popup'},
{'methods': ['animate', 'focus', 'delete', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'], 'type': 'search'},
{
'methods': ['rotation', 'focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'],
'methods': ['rotation', 'focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'],
'type': 'slider'
},
{'methods': ['focus', 'animate', 'getScrollOffset', 'scrollBy', 'getBoundingClientRect'], 'type': 'stack'},
{'methods': ['focus', 'animate', 'getScrollOffset', 'scrollBy', 'getBoundingClientRect', 'scrollTo', 'createIntersectionObserver'], 'type': 'stack'},
{
'methods': ['swipeTo', 'focus', 'showPrevious', 'showNext', 'rotation', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'],
'methods': ['swipeTo', 'focus', 'showPrevious', 'showNext', 'rotation', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'],
'type': 'swiper'
},
{
'methods': ['start', 'pause', 'setCurrentTime', 'requestFullscreen', 'exitFullscreen', 'focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'],
'methods': ['start', 'pause', 'stop', 'setCurrentTime', 'requestFullscreen', 'exitFullscreen', 'focus', 'animate', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'],
'type': 'video'
},
{
'methods': ['setNextButtonStatus', 'focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'],
'methods': ['setNextButtonStatus', 'focus', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'],
'type': 'stepper'
},
{
'methods': ['focus', 'animate', 'delete', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'],
'methods': ['focus', 'animate', 'delete', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset', 'scrollTo', 'createIntersectionObserver'],
'type': 'textarea'
},
{'methods': ['reload', 'createIntersectionObserver'], 'type': 'web'},
{
'methods': ['reload', 'getBoundingClientRect', 'scrollBy', 'getScrollOffset'],
'type': 'web'
},
{
'methods': ['takePhoto', 'startRecorder', 'closeRecorder'],
'methods': ['takePhoto', 'scrollTo', 'createIntersectionObserver'],
'type': 'camera'
}
];

View File

@ -57,9 +57,7 @@ const pageMap: pageMapInterface = {};
function createInstance(id: string, code: string, config: Options, data: object): any | Error {
const page = pageMap[id];
if (!page) {
config = JSON.parse(JSON.stringify(config || {}));
Log.debug(`Create a page.`);
const env: EnvInterface = {
config,
created: Date.now(),
@ -158,5 +156,7 @@ export default {
destroyInstance: destroyInstance,
appError: framework.appError,
appDestroy: framework.appDestroy,
appHide: framework.appHide,
appShow: framework.appShow,
registerModules: framework.registerModules
};

View File

@ -99,7 +99,7 @@ export class Log {
* Log.debug('This is a debug message.');
*/
public static debug(...message: any[]): void {
aceConsole.info('[JS Framework] (debug) ', message);
aceConsole.debug('[JS Framework] (debug) %s', message);
}
/**
@ -109,7 +109,7 @@ export class Log {
* Log.info('This is an info message.');
*/
public static info(...message: any[]): void {
aceConsole.info('[JS Framework] (info) ', message);
aceConsole.info('[JS Framework] (info) %s', message);
}
/**
@ -119,7 +119,7 @@ export class Log {
* Log.warn('This is a warn message.');
*/
public static warn(...message: any[]): void {
aceConsole.warn('[JS Framework] (warn) ', message);
aceConsole.warn('[JS Framework] (warn) %s', message);
}
/**
@ -129,6 +129,6 @@ export class Log {
* Log.error('This is an error message.');
*/
public static error(...message: any[]): void {
aceConsole.error('[JS Framework] (error) ', message);
aceConsole.error('[JS Framework] (error) %s', message);
}
}

View File

@ -29,6 +29,8 @@ import { TaskCenter } from '../main/manage/event/TaskCenter';
import { FragBlockInterface } from '../main/model/compiler';
import Vm from '../main/model';
const CSS_INHERITANCE: string[] = ['fontFamily', 'fontWeight', 'fontSize', 'fontStyle', 'textAlign', 'lineHeight', 'letterSpacing', 'color', 'visibility'];
/**
* Element is a basic class to describe a tree node in vdom.
* @extends Node
@ -44,11 +46,13 @@ class Element extends Node {
private _block: FragBlockInterface;
private _vm: Vm;
private _isCustomComponent: boolean;
private _inheritedStyle: object;
protected _children: Node[];
protected _pureChildren: Element[];
protected _role: string;
protected _attr: any;
protected _dataSet: any;
constructor(type = 'div', props:any = {}, isExtended: boolean = false) {
super();
@ -70,6 +74,20 @@ class Element extends Node {
this._children = [];
this._pureChildren = [];
this._isCustomComponent = false;
this._inheritedStyle = {};
this._dataSet = {};
}
/**
* inherit sytle from parent
* @type {Object}
*/
public set inheritedStyle(inheritedStyle: object) {
this._inheritedStyle = inheritedStyle;
}
public get inheritedStyle() {
return this._inheritedStyle;
}
/**
@ -184,6 +202,18 @@ class Element extends Node {
return this._attr;
}
/**
* DataSet object of this Element.
* @type {Object}
*/
public set dataSet(dataSet: any) {
this._dataSet = dataSet;
}
public get dataSet() {
return this._dataSet;
}
/**
* Flag of whether the element is the root of customeComponent.
* @param {bollean}
@ -381,6 +411,7 @@ class Element extends Node {
if (node.nodeType === Node.NodeType.Element) {
const element = node as Element;
this.insertIndex(element, this.pureChildren.length, { isInPureChildren: true });
this.inheritStyle(node, true);
const taskCenter = this.getTaskCenter(this.docId);
if (taskCenter) {
return taskCenter.send(
@ -439,6 +470,7 @@ class Element extends Node {
: this.pureChildren.length,
{ isInPureChildren: true }
);
this.inheritStyle(node);
const taskCenter = this.getTaskCenter(this.docId);
if (taskCenter) {
return taskCenter.send(
@ -498,8 +530,8 @@ class Element extends Node {
this.pureChildren.indexOf(this.previousElement(after)) + 1,
{ isInPureChildren: true }
);
this.inheritStyle(node);
const taskCenter = this.getTaskCenter(this.docId);
if (taskCenter) {
return taskCenter.send(
'dom',
@ -570,6 +602,15 @@ class Element extends Node {
this._pureChildren.length = 0;
}
/**
* Set dataSet for an element.
* @param {string} key - dataSet name.
* @param {string} value - dataSet value.
*/
public setData(key: string, value: string): void {
this.dataSet[key] = value;
}
/**
* Set an attribute, and decide whether the task should be send to native.
* @param {string} key - Arribute name.
@ -580,6 +621,10 @@ class Element extends Node {
if (this.attr[key] === value && silent !== false) {
return;
}
// Because the data has been addressed in SetData
if (key === 'data') {
return;
}
this.attr[key] = value;
const taskCenter = this.getTaskCenter(this.docId);
if (!silent && taskCenter) {
@ -605,6 +650,9 @@ class Element extends Node {
const result = {};
result[key] = value;
taskCenter.send('dom', { action: 'updateStyle' }, [this.ref, this.toStyle()]);
if (CSS_INHERITANCE.includes(key)) {
this.broadcastStyle();
}
}
}
@ -613,14 +661,25 @@ class Element extends Node {
* @param {object} classStyle - Style properties.
*/
public setClassStyle(classStyle: any): void {
let canUpdate: boolean = false;
const taskCenter = this.getTaskCenter(this.docId);
Object.keys(classStyle).forEach(key => {
if (CSS_INHERITANCE.includes(key) && taskCenter) {
if (!this.isSameStyle(this.classStyle[key], classStyle[key], key)) {
canUpdate = true;
}
}
});
for (const key in this._classStyle) {
this._classStyle[key] = '';
}
Object.assign(this._classStyle, classStyle);
const taskCenter = this.getTaskCenter(this.docId);
if (taskCenter) {
taskCenter.send('dom', { action: 'updateStyle' }, [this.ref, this.toStyle()]);
if (canUpdate) {
this.broadcastStyle();
}
}
}
@ -652,6 +711,9 @@ class Element extends Node {
const result = {};
result[key] = value;
taskCenter.send('dom', { action: 'updateStyle' }, [this.ref, result]);
if (CSS_INHERITANCE.includes(key)) {
this.broadcastStyle();
}
}
}
@ -765,9 +827,9 @@ class Element extends Node {
* @return {object} style
*/
public toStyle(): any {
// Selector Specificity inline > #id > .class > tag.
// Return Object.assign({}, this._tagStyle,this.classStyle, this._idStyle,this.style).
const style = Object.assign({}, this._tagStyle);
// Selector Specificity inline > #id > .class > tag > inheritance.
const style = Object.assign({}, this._inheritedStyle);
this.assignStyle(style, this._tagStyle);
this.assignStyle(style, this._classStyle);
this.assignStyle(style, this._idStyle);
this.assignStyle(style, this.style);
@ -859,6 +921,9 @@ class Element extends Node {
*/
public destroy() {
Log.debug(`Element#destroy this._type = ${this._type}.`);
if (this._event && this._event['detached']) {
this.fireEvent('detached', {});
}
this._attr = null;
this._style = null;
this._classStyle = {};
@ -886,6 +951,87 @@ class Element extends Node {
super.destroy();
}
/**
* the judgement of whether the inherited style should update
* @param {string | Array} oldClassStyle
* @param {string | Array} newClassStyle
* @param {string} key
* @returns {boolean}
*/
isSameStyle(oldClassStyle: string | any[], newClassStyle: string | any[], key: string) {
if (key === 'fontFamily') {
if (oldClassStyle[0].fontFamily === newClassStyle[0].fontFamily) {
return true;
}
} else {
if (oldClassStyle === newClassStyle) {
return true;
}
}
return false;
}
/**
* iterate child node for updating inheritedstyle
*/
broadcastStyle() {
if (this.pureChildren) {
for (const child in this.pureChildren) {
this.pureChildren[child].setInheritedStyle();
this.pureChildren[child].broadcastStyle();
}
}
}
/**
* before update inherited style
* clear up the inherited style
*/
resetInheritedStyle() {
this.inheritedStyle = {};
}
/**
* inherited style from parent
*/
public setInheritedStyle() {
this.resetInheritedStyle();
const parentNode: Element = this.parentNode as Element;
parentNode.inheritStyle(this);
const taskCenter = this.getTaskCenter(this.docId);
if (taskCenter) {
taskCenter.send(
'dom',
{ action: 'updateStyle' },
[this.ref, this.toStyle()]
);
}
}
/**
* inherit style of parent.
* @return {object} element
*/
public inheritStyle(node, isFirst = false) {
// for first render, save time
const allStyle = this.toStyle();
this.setChildStyle(allStyle, node._inheritedStyle);
}
/**
* set inherited style to child
* @param {object} parentStyle
* @param {object} childStyle
* @param {object} node
*/
public setChildStyle(parentStyle, childStyle) {
Object.keys(parentStyle).forEach(key => {
if (CSS_INHERITANCE.includes(key)) {
childStyle[key] = parentStyle[key];
}
});
}
private registerNode(node) {
const doc = this._ownerDocument;
doc.nodeMap[node.nodeId] = node;

View File

@ -57,6 +57,9 @@ class NativeElementClassFactory {
if (taskCenter) {
// support aceapp callback style
args = interceptCallback(args);
if (methodName === 'scrollTo' && args[0].id) {
args[0].id = findEl(this, args[0].id);
}
const ret = taskCenter.send('component', {
ref: this.ref,
component: tagName,
@ -74,4 +77,21 @@ class NativeElementClassFactory {
}
}
function findEl(parent, id) {
if (!parent) {
return;
}
if (parent.id === id) {
return parent.ref;
}
let ans;
const children = parent.children;
if (children) {
for (const child in children) {
ans = ans || findEl(children[child], id);
}
}
return ans;
}
export default NativeElementClassFactory;

View File

@ -50,6 +50,7 @@ describe('receiveTasks', () => {
height: '0',
isInit: true,
pcPreview: 'disable',
darkMode: 'false',
appInstanceId: '10002',
packageName: 'com.example.helloworld',
resourcesConfiguration: [],

View File

@ -37,7 +37,6 @@ import {
} from '../../runtime/main/page/register';
import { App } from '../../runtime/main/app/App';
import Page from '../../runtime/main/page';
import config from '../../runtime/main/config';
const expect = chai.expect;
@ -64,6 +63,7 @@ describe('framework entry', () => {
width: '0',
height: '0',
isInit: true,
darkMode: 'false',
pcPreview: 'disable',
appInstanceId: '10002',
packageName: 'com.example.helloworld',
@ -81,7 +81,6 @@ describe('framework entry', () => {
appCode: '',
bundleUrl: ''
};
const { nativeComponentMap } = config;
before(() => {
initFramework();

8
tslint.json Normal file
View File

@ -0,0 +1,8 @@
{
"rules": {
"no-non-null-assertion": true,
"typedef-whitespace": true,
"no-eval": true,
"no-consecutive-blank-lines": true
}
}