提交 5a3cc6b9 编写于 作者: Z zhongjianfei

zhongjianfei@huawei.com

Signed-off-by: Nzhongjianfei <zhongjianfei@huawei.com>
Change-Id: Ibff364a32cbad07eab4a8151ffbe1805e1f74090
上级 8b3b888f
{
"presets": [
[
"env",
{
"modules": false
}
]
],
"plugins": [
"external-helpers"
]
}
\ No newline at end of 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": {
......
......@@ -15,27 +15,40 @@ 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 ]
}
......
......@@ -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,17 @@ 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 configOutput = {
......
#!/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
此差异已折叠。
#!/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/
......@@ -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 || {};
......
......@@ -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;
......@@ -99,7 +100,7 @@ export function appCreate(page: Page, options: Options, data: object, services:
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.
......
......@@ -16,16 +16,18 @@
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)*]+\)/
};
/**
......@@ -181,6 +183,14 @@ 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 {
Log.debug('Illegal condition');
failReason.type = MEDIAERROR.SYNTAX;
......@@ -357,6 +367,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 +456,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 +472,8 @@ function calculateExpression(leftValue: number | string, relationship: string,
return lvalue <= rvalue;
case '<':
return lvalue < rvalue;
case '==':
return lvalue === rvalue;
default:
failReason.type = MEDIAERROR.SYNTAX;
}
......
......@@ -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);
......
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 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)
})
}
},
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;
}
}
}
\ No newline at end of file
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)
}
}
}
\ No newline at end of file
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"
}
}
\ No newline at end of file
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
}
}
}
\ No newline at end of file
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)
}
}
}
\ No newline at end of file
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)
}
}
}
\ No newline at end of file
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()
})
}
}
}
}
\ No newline at end of file
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'
}
}
\ No newline at end of file
import { paramMock } from "./utils"
export function mockDocument() {
global.systemplugin.document = {
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();
})
}
}
}
}
\ No newline at end of file
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(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(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(ResultMock);
})
}
}
return FeatureAbility
}
}
global.FeatureAbility = FeatureAbilityObject.getFeatureAbility();
}
\ No newline at end of file
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();
}
\ No newline at end of file
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)
}
}
}
\ No newline at end of file
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 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 DirMock = {
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
},
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.")
}
};
const ReadOutMock = {
bytesRead: "[PC Preview]: unknow bytesRead",
offset: "[PC Preview]: unknow offset",
buffer: "[PC Preview]: unknow buffer"
};
global.systemplugin.fileio = {
Dir: DirMock,
Dirent: DirentMock,
Stat: StatMock,
ReadOut: ReadOutMock,
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);
})
}
},
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;
},
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;
},
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.")
},
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.")
},
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.")
},
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;
},
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;
},
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.")
},
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;
}
}
}
\ No newline at end of file
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
}
}
}
\ No newline at end of file
import regeneratorRuntime from 'babel-runtime/regenerator'
import { mockAbilityFeatureAbility } 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 { mockDocument } from './document'
import { mockFetch } from './fetch'
import { mockFeatureAbility } from './featureAbility'
import { mockFile } from './file'
import { mockFileio } from './fileio'
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 { 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'
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()
mockFileio()
mockDocument()
mockPasteBoard()
mockInputmethod()
mockOhosRequest()
mockMultimediaImage()
mockMultimediaMedia()
mockMultimediaMedialibrary()
mockCall()
mockWebSocket()
mockHttp()
mockDeviceInfo()
mockWifi()
mockNfcCardEmulation()
mockDataStorage()
mockWindow()
mockAbilityFeatureAbility()
}
\ No newline at end of file
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;
}
}
}
\ No newline at end of file
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;
}
}
}
\ No newline at end of file
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;
}
}
}
\ No newline at end of file
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
}
}
}
\ No newline at end of file
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;
}
}
}
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.")
}
}
}
\ No newline at end of file
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 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') {
args[len - 1].call(this, paramMock.paramNumberMock, 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') {
args[len - 1].call(this, paramMock.paramNumberMock, 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);
})
}
}
}
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') {
args[len - 1].call(this, paramMock.paramNumberMock, paramMock.paramNumberMock);
}
},
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') {
args[len - 1].call(this, paramMock.paramNumberMock, paramMock.paramNumberMock);
}
},
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
}
}
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;
}
}
}
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 () {
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 () {
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)
}
}
}
\ No newline at end of file
import { getRandomArbitrary } 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
}
}
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
}
}
\ No newline at end of file
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)
}
}
}
\ No newline at end of file
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)
}
}
}
\ No newline at end of file
/*
* 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;
}
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);
})
}
}
}
}
\ No newline at end of file
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;
}
}
}
\ No newline at end of file
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"
}
\ No newline at end of file
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)
}
}
}
\ No newline at end of file
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)
})
}
}
}
}
\ No newline at end of file
import { paramMock } from "./utils"
export function mockWindow() {
const windowPropertiesMock = {
brightness: '[PC preview] unknow brightness',
isFullScreen: '[PC preview] unknow isFullScreen',
isKeepScreenOn: '[PC preview] unknow isKeepScreenOn'
}
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)
}
}
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)
})
}
}
}
}
\ No newline at end of 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 };
......@@ -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}'.`);
}
......
......@@ -218,6 +218,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;
}
......
......@@ -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) {
......
此差异已折叠。
......@@ -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);
}
......
此差异已折叠。
......@@ -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)}.`);
......
......@@ -52,5 +52,6 @@ export interface MediaStatusInterface<T, K> {
'aspect-ratio': T,
'device-width': T,
'device-height': T,
'dark-mode': T,
'round-screen': K
}
......@@ -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 => {
......
......@@ -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();
});
}
}
}
......@@ -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;
......
此差异已折叠。
此差异已折叠。
......@@ -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
};
此差异已折叠。
此差异已折叠。
......@@ -50,6 +50,7 @@ describe('receiveTasks', () => {
height: '0',
isInit: true,
pcPreview: 'disable',
darkMode: 'false',
appInstanceId: '10002',
packageName: 'com.example.helloworld',
resourcesConfiguration: [],
......
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册