UNPKG

windmill-module-api

Version:

Standard module APIs of windmill.

1,518 lines (1,409 loc) 64.1 kB
/* windmill-module-api (0.3.8), build at 2019-06-05 18:17. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global['windmill-module-api'] = factory()); }(this, (function () { 'use strict'; // 挂载到全局环境上的 windmill runtime api var RUNTIME_API = '__WINDMILL_WORKER_RUNTIME_APIS__'; // webview 组件和小程序之间通信的事件名 var WEBVIEW_MESSAGE = '__WEBVIEW_MESSAGE_EVENT_NAME__'; // storage 对于自动 JSON 序列化添加的标记 var STORAGE_JSON_FLAG = '[[JSON]]'; var STORAGE_JSON_FLAG_REGEXP = /^\[\[JSON\]\].*/; /** * Get current runtime context object */ function getContextObject() { return typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : (new Function('return this'))(); // tslint:disable-line } // windmill worker framework 环境里获取模块的全局变量 var getterMethod = '__WINDMILL_MODULE_GETTER__'; function moduleGetter(name) { var context = getContextObject(); // 兼容小程序 worker framework 环境 if (context && typeof context[getterMethod] === 'function') { return context[getterMethod](name); } // 兼容 rax 和三方 dsl 的业务代码环境 if (context && typeof context.require === 'function') { return context.require(("@core/" + name)); } else { console.error("Can't find available \"require\" function."); } // 兼容小程序 vue worker 环境 if (context && context && typeof context.requireModule === 'function') { return context.requireModule(name); } // 兼容 weex 页面环境 if (context && context.weex && typeof context.weex.requireModule === 'function') { return context.weex.requireModule(("@windmill/" + name)); } } /** * Event Emitter * Partially implement the events module of Node.js. * https://nodejs.org/api/events.html#events_class_eventemitter */ var eventMapKey = '[[EVENT_MAP]]'; function initListeners(emitter, eventName) { var events = emitter[eventMapKey]; if (!Array.isArray(events[eventName])) { events[eventName] = []; } return events[eventName]; } var EventEmitter = function EventEmitter() { Object.defineProperty(this, eventMapKey, { configurable: false, enumerable: false, writable: false, value: {} }); }; EventEmitter.prototype.on = function on (eventName, listener) { var listeners = initListeners(this, eventName); listeners.push({ listener: listener, once: false, callCount: 0 }); return this; }; EventEmitter.prototype.once = function once (eventName, listener) { var listeners = initListeners(this, eventName); listeners.push({ listener: listener, once: true, callCount: 0 }); return this; }; EventEmitter.prototype.off = function off (eventName, listener) { var events = this[eventMapKey]; if (listener) { var listeners = events[eventName]; if (Array.isArray(listeners)) { var index = listeners.findIndex(function (x) { return x.listener === listener; }); if (index !== -1) { listeners.splice(index, 1); } } } else { delete events[eventName]; } return this; }; EventEmitter.prototype.emit = function emit (eventName) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; var events = this[eventMapKey]; var listeners = events[eventName]; if (Array.isArray(listeners)) { // invoke event listeners events[eventName] = listeners.filter(function (desc) { try { desc.listener.apply(null, args); desc.callCount += 1; } catch (e) { return true; } return !desc.once; }); } return this; }; function hasOwn(object, key) { return Object.prototype.hasOwnProperty.call(object, key); } function getType(value) { return Object.prototype.toString.call(value).slice(8, -1); } function isPlainObject(value) { return getType(value) === 'Object'; } function isArray(value) { return getType(value) === 'Array'; } function isFunction(value) { return typeof value === 'function'; } function getEnv() { return typeof __windmill_environment__ === 'object' ? __windmill_environment__ : typeof wmlEnv === 'object' ? wmlEnv : typeof windmillEnv === 'object' ? windmillEnv : {}; } var currentRuntime; function getRuntime() { if (!currentRuntime) { var context = getContextObject(); currentRuntime = context[RUNTIME_API]; } return currentRuntime; } // 获取当前显示的页面的 client id function getCurrentPageId() { return getRuntime().$getCurrentActivePageId(); } /** * 拦截并预处理模块的参数 */ var preprocessorMap = {}; function preprocess(api, options) { var processor = preprocessorMap[api]; if (isFunction(processor) && isPlainObject(options)) { return processor(options); } else { return options; } } /** * 注册模块参数的预处理器,用于注入特殊的处理逻辑 */ function registerPreprocessor(my, map) { if (isPlainObject(my) && isPlainObject(map)) { for (var api in map) { if (hasOwn(my, api) && typeof map[api] === 'function') { preprocessorMap[api] = map[api]; } } } } /** * Generate uniqueId */ var uniqueId = (function () { var start = 100000; return function getUniqueId() { var id = String(start); start += 1; return id; }; })(); /** * 派发一个事件到 render 中当前显示的页面 * @param type 事件的类型 * @param data 事件传递的数据 */ function emitModuleAPIEvent(type, data) { var pageId = getCurrentPageId(); var eventName = "[[ModuleAPIEvent]]@" + pageId; getRuntime().$emit(eventName, { type: type, data: data }, pageId); } var renderEventEmitter = new EventEmitter(); /** * 监听来自 render 的事件 */ function listenModuleAPIEvent() { var eventName = '[[ModuleAPIEvent]]'; getRuntime().$on(eventName, function (ref) { var type = ref.type; if ( type === void 0 ) type = ''; var data = ref.data; if ( data === void 0 ) data = {}; var name = type; if (data.event && data.event.name) { name += "." + (data.event.name); } renderEventEmitter.emit(name, data); }); } /** * Set a global API to current context */ function setGlobalAPI(name, value, readonly) { if ( readonly === void 0 ) readonly = true; var context = getContextObject(); try { Object.defineProperty(context, name, { value: value, configurable: true, enumerable: true, writable: !readonly }); } catch (e) { context[name] = value; } } var ignoreMethods = ['success', 'fail', 'complete']; function omitMethod(rawOptions) { var options = {}; for (var key in rawOptions) { if (ignoreMethods.indexOf(key) === -1) { options[key] = rawOptions[key]; } } return options; } // 获取某个模块中的方法 function getMethod(methodPath, sync) { // 使用 worker framework 提供的 runtime api (可以绕过白名单) var runtime = getRuntime(); if (runtime) { if (sync && typeof runtime.$callSync === 'function') { return function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return runtime.$callSync.apply(runtime, [ methodPath ].concat( args )); }; } else if (!sync && typeof runtime.$call === 'function') { return function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return runtime.$call.apply(runtime, [ methodPath ].concat( args )); }; } } // 使用默认的 moduleGetter 获取模块接口 var ref = methodPath.split(/\s*\.\s*/i); var module = ref[0]; var method = ref[1]; if (module && method) { var mod = moduleGetter(module); if (mod && typeof mod[method] === 'function') { return mod[method]; } } return function () { }; } // 用于安全执行内部的回调函数 function saveCall(method, args) { if (typeof method === 'function') { try { return method.apply(null, args); } catch (error) { console.error(("Failed to execute internal method: " + (error.toString()))); } } } /** * 可以注入错误处理函数,处理执行用户传递的回调函数时的错误 */ var errorHandler = function (methodPath, error) { console.error(("Failed to execute callback of \"" + methodPath + "\": " + (error.toString()))); }; function registerErrorHandler(handler) { if (typeof handler === 'function') { errorHandler = handler; } } // 执行用户传递的回调函数,捕获错误并输出 function invokeCallback(methodPath, callback, args) { if (typeof callback === 'function') { try { return callback.apply(null, args); } catch (error) { errorHandler(methodPath, error); } } } var modifier = {}; /** * 真实调用原生模块(异步) * @param methodPath 模块调用的字符串,形如 "modal.toast" * @param rawOptions 三方 API 对外透出的 options * @param options 传递给原生模块的 options * @param onSuccess * @param onFail */ function callModule(methodPath, rawOptions, options, onSuccess, onFail) { if ( rawOptions === void 0 ) rawOptions = {}; if ( options === void 0 ) options = rawOptions; if ( onSuccess === void 0 ) onSuccess = function (x) { return x; }; if ( onFail === void 0 ) onFail = function (x) { return x; }; var method = getMethod(methodPath); var isComplete = false; return method(omitMethod(options), function (result) { var formattedResult = saveCall(onSuccess, [result]); invokeCallback(methodPath, rawOptions.success, [formattedResult]); if (!isComplete) { invokeCallback(methodPath, rawOptions.complete, [formattedResult]); isComplete = true; } }, function (error) { var formattedError = saveCall(onFail, [error]); invokeCallback(methodPath, rawOptions.fail, [formattedError]); if (!isComplete) { invokeCallback(methodPath, rawOptions.complete, [formattedError]); isComplete = true; } }, modifier); } /** * 真实调用原生模块(同步) * @param methodPath 模块调用的字符串,形如 "modal.toast" * @param options 传递给原生模块的 options */ function callModuleSync(methodPath, options) { if ( options === void 0 ) options = {}; var method = getMethod(methodPath, true); return method(omitMethod(options), modifier); } function showActionSheet(options) { callModule('actionSheet.showActionSheet', options); } function chooseAddress(options) { callModule('address.choose', options); } function tradePay(options) { if ( options === void 0 ) options = {}; options = preprocess('tradePay', options); callModule('alipay.tradePay', options); } var ACTION_LIST = ["opacity", "backgroundColor", "width", "height", "top", "left", "bottom", "right", "rotate", "rotateX", "rotateY", "rotateZ", "rotate3d", "skew", "skewX", "skewY", "scale", "scaleX", "scaleY", "scaleZ", "scale3d", "translate", "translateX", "translateY", "translateZ", "translate3d", "matrix", "matrix3d"]; var AnimationActions = function AnimationActions() { var this$1 = this; this.animations = []; this.currentAnimation = []; this.config = {}; ACTION_LIST.forEach(function (action) { this$1[action] = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; this$1.currentAnimation.push([action, args]); return this$1; }; }); }; AnimationActions.prototype.step = function step (config) { // 合并 config this.animations.push({ config: Object.assign({}, this.config, config), animation: this.currentAnimation, }); // 调用 step 之后将 currentAnimation 置空 this.currentAnimation = []; return this; }; AnimationActions.prototype.export = function export$1 () { var temp = this.animations; this.animations = []; return temp; }; var Animation = /*@__PURE__*/(function (AnimationActions) { function Animation(config) { AnimationActions.call(this); this.config = Object.assign({ transformOrigin: "50% 50% 0", duration: 400, timeFunction: "linear", delay: 0, }, config); } if ( AnimationActions ) Animation.__proto__ = AnimationActions; Animation.prototype = Object.create( AnimationActions && AnimationActions.prototype ); Animation.prototype.constructor = Animation; return Animation; }(AnimationActions)); function createAnimation(config) { return new Animation(config); } var InnerAudioConext = function InnerAudioConext(options) { if ( options === void 0 ) options = {}; this._instanceId = uniqueId(); this._emitter = new EventEmitter(); this.src = options.src; }; InnerAudioConext.prototype.play = function play (options) { var this$1 = this; callModule('audioPlayer.playVoice', options, { src: this.src, instanceId: this._instanceId }, function (res) { if (res.isComplete === 1) { // 音频自然播放结束以后,再次触发回调,返回 isComplete = 1 this$1._emitter.emit('stop'); } else { this$1.duration = res.duration; this$1._emitter.emit('play'); } return res; }, function (err) { this$1._emitter.emit('error', err); return err; }); }; InnerAudioConext.prototype.pause = function pause (options) { var this$1 = this; callModule('audioPlayer.pauseVoice', options, { instanceId: this._instanceId }, function (res) { this$1._emitter.emit('pause'); return res; }, function (err) { this$1._emitter.emit('error', err); return err; }); }; InnerAudioConext.prototype.stop = function stop (options) { var this$1 = this; callModule('audioPlayer.stopVoice', options, { instanceId: this._instanceId }, function (res) { this$1._emitter.emit('stop'); return res; }, function (err) { this$1._emitter.emit('error', err); return err; }); }; InnerAudioConext.prototype.onPlay = function onPlay (callBack) { this._emitter.on('play', callBack); }; InnerAudioConext.prototype.onPause = function onPause (callBack) { this._emitter.on('pause', callBack); }; InnerAudioConext.prototype.onStop = function onStop (callBack) { this._emitter.on('stop', callBack); }; InnerAudioConext.prototype.onError = function onError (callBack) { this._emitter.on('error', callBack); }; InnerAudioConext.prototype.offPlay = function offPlay (callBack) { this._emitter.off('play', callBack); }; InnerAudioConext.prototype.offPause = function offPause (callBack) { this._emitter.off('pause', callBack); }; InnerAudioConext.prototype.offStop = function offStop (callBack) { this._emitter.off('stop', callBack); }; InnerAudioConext.prototype.offError = function offError (callBack) { this._emitter.off('error', callBack); }; function createInnerAudioContext(options) { return new InnerAudioConext(options); } var defaultExport = function defaultExport() { this._startEmitted = false; // 开始回调,Native 会调多次,封装后只调一次 this._emitter = new EventEmitter(); }; defaultExport.prototype.start = function start (options) { var this$1 = this; if ( options === void 0 ) options = {}; this._startEmitted = false; callModule('audioRecord.startRecord', options, { maxDuration: options.duration / 1000, minDuration: 1 // 对前端隐藏这个入参,传一个默认值 }, function (res) { // onStart // 第一次回调返回平均声音强度 if (res.averagePower && !this$1._startEmitted) { this$1._emitter.emit('start', {}); this$1._startEmitted = true; } // onStop // 最后一次回调返回文件路径 if (res.apFilePath) { this$1._emitter.emit('stop', { tempFilePath: res.apFilePath, duration: res.duration //不推荐使用,文档里已删除 }); } return res; }, function (err) { this$1._emitter.emit('error', err); return err; }); }; defaultExport.prototype.stop = function stop (options) { var this$1 = this; if ( options === void 0 ) options = {}; callModule('audioRecord.stopRecord', options, options, function (res) { this$1._emitter.emit('stop', { tempFilePath: res.apFilePath, duration: res.duration //不推荐使用,文档里已删除 }); return res; }, function (err) { this$1._emitter.emit('error', err); return err; }); }; // 与支付宝不一致,屏蔽 // cancel (options: PlainObject = {}) { // callModule('audioRecord.cancelRecord', options, options, res => { // this._emitter.emit('cancel', res) // return res // }, err => { // this._emitter.emit('error', err) // return err // }) // } defaultExport.prototype.onStart = function onStart (callback) { this._emitter.on('start', callback); }; defaultExport.prototype.onStop = function onStop (callback) { this._emitter.on('stop', callback); }; // 与支付宝不一致,屏蔽 // onCancel (callback: AnyFunction) { // this._emitter.on('cancel', callback) // } defaultExport.prototype.onError = function onError (callback) { this._emitter.on('error', callback); }; defaultExport.prototype.offStart = function offStart (callback) { this._emitter.off('start', callback); }; defaultExport.prototype.offStop = function offStop (callback) { this._emitter.off('stop', callback); }; defaultExport.prototype.offError = function offError (callback) { this._emitter.off('error', callback); }; var recordManger; function getRecorderManager(options) { if (!recordManger) { recordManger = new defaultExport(); } return recordManger; } var ACTION_LIST$1 = [ 'setTextAlign', 'setTextBaseline', 'setFillStyle', 'setStrokeStyle', 'setShadow', 'createLinearGradient', 'createCircularGradient', 'addColorStop', 'setLineWidth', 'setLineCap', 'setLineJoin', 'setMiterLimit', 'rect', 'fillRect', 'strokeRect', 'clearRect', 'fill', 'stroke', 'beginPath', 'closePath', 'moveTo', 'lineTo', 'arc', 'bezierCurveTo', 'clip', 'quadraticCurveTo', 'scale', 'rotate', 'translate', 'setFontSize', 'fillText', 'drawImage', 'setGlobalAlpha', 'setLineDash', 'transform', 'setTransform', 'getImageData', 'p​utImageData', 'save', 'restore', 'measureText' ]; var CanvasContext = function CanvasContext(canvasId) { var this$1 = this; this._canvasId = canvasId; this._actions = []; ACTION_LIST$1.forEach(function (action) { this$1[action] = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; this$1._actions.push({ method: action, args: args }); }; }); }; CanvasContext.prototype.draw = function draw () { emitModuleAPIEvent('canvas', { canvasId: this._canvasId, actions: this._actions }); this._actions = []; }; function createCanvasContext(canvasId) { return new CanvasContext(canvasId); } function openChat(options) { callModule('chat.open', options); } function getClipboard(options) { callModule('clipboard.readText', options); } function setClipboard(options) { if ( options === void 0 ) options = {}; callModule('clipboard.writeText', options, { text: options.text }); } function getNetworkType(options) { options = preprocess('getNetworkType', options); callModule('connection.getType', options, {}, function (res) { var type = res.type || ''; return { networkType: type.toUpperCase() }; }); } var bus; function onNetworkStatusChange(cb) { if (!bus) { bus = new EventEmitter(); var connection = moduleGetter('connection'); connection.onChange({}, function (res) { var type = res.type || ''; bus.emit('networkStatusChange', { networkType: type.toUpperCase() }); }); } bus.on('networkStatusChange', cb); } function offNetworkStatusChange() { bus.off('networkStatusChange'); } function choosePhoneContact(options) { options = preprocess('choosePhoneContact', options); callModule('contact.choosePhoneContact', options, {}, function (res) { return { name: res.name, mobile: res.phone }; }); } function watchShake(options) { callModule('device.onShake', options, { on: true }); } function vibrate(options) { callModule('device.vibrate', options); } function vibrateShort(options) { callModule('device.vibrateShort', options); } function onUserCaptureScreen(callback) { callModule('device.onUserCaptureScreen', { success: callback }); } function offUserCaptureScreen() { callModule('device.offUserCaptureScreen'); } function scan(options) { callModule('device.scan', options); } /** * https://yuque.antfin-inc.com/taobaoapp/design/xdr23y * https://docs.alipay.com/mini/api/file */ function getPath(options) { return isPlainObject(options) ? (options.apFilePath || options.filePath) : ''; } function saveFile(options) { return callModule('file.saveFile', options, { filePath: getPath(options) }, function (result) { return ({ apFilePath: result.savedFilePath }); }); } function getFileInfo(options) { return callModule('file.getFileInfo', options, { filePath: getPath(options) }, function (result) { return ({ size: result.size }); }); } function getSavedFileInfo(options) { return callModule('file.getFileInfo', options, { filePath: getPath(options) }); } function getSavedFileList(options) { return callModule('file.getFileList', options, {}, function (result) { var fileList = []; if (isArray(result.fileList)) { fileList = result.fileList.map(function (f) { return ({ size: f.size, createTime: f.createTime, apFilePath: f.filePath }); }); } return { fileList: fileList }; }); } function removeSavedFile(options) { return callModule('file.removeFile', options, { filePath: getPath(options) }); } function chooseImage(options) { callModule('image.chooseImage', options); } function compressImage(options) { callModule('image.compressImage', options); } function previewImage(options) { callModule('image.previewImage', options); } function saveImage(options) { callModule('image.saveImage', options); } function getImageInfo(options) { callModule('image.getImageInfo', options); } function hideKeyboard() { callModule('keyboard.hideKeyboard'); } function getLocation(options) { var type = options.type; callModule('location.getLocation', options, options, function (res) { var result = { longitude: res.coords.longitude, latitude: res.coords.latitude, accuracy: res.coords.accuracy }; if (type > 0 && res.address) { result.country = res.address.country; result.province = res.address.province; result.city = res.address.city; result.cityAdcode = res.address.cityCode; result.district = res.address.area; result.districtAdcode = res.address.areaCode; // 修复线上接口返回值参数问题 @清屿 var env = getEnv(); if (env && env.platform === 'iOS' && env.appVersion === '8.8.0') { result.cityAdcode = res.address.areaCode; } } return result; }); } var ACTION_LIST$2 = ['play', 'stop', 'pause', 'setSpeed', 'goToAndStop', 'goToAndPlay', 'getDuration', 'setDirection', 'playSegments', 'destroy']; var EVENT_LIST = ['onAnimationEnd', 'onAnimationRepeat', 'onDataReady', 'onDataFailed', 'onAnimationStart', 'onAnimationCancel']; var LottieContext = function LottieContext(id) { var this$1 = this; ACTION_LIST$2.forEach(function (action) { this$1[action] = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; emitModuleAPIEvent('lottie', { lottieId: id, action: { method: action, args: args } }); }; }); EVENT_LIST.forEach(function (event) { this$1[event] = function (callback) { renderEventEmitter.on(("lottie." + event), function (data) { var args = []; if (data.event && data.event.args) { args = data.event.args; } if (data.lottieId === id) { callback.apply(this$1, args); } }); }; }); }; function createLottieContext(id) { return new LottieContext(id); } function setBackgroundImage(options) { callModule('miniApp.setWebViewBackgroundImage', options); } function removeBackgroundImage(options) { callModule('miniApp.setWebViewBackgroundImage', options, { color: '', imgUrl: '' }); } function setViewTop(options) { callModule('miniApp.setWebViewTop', options); } function setCanPullDown(options) { callModule('miniApp.setWebViewParams', options); } function setShareAppMessage(options) { if ( options === void 0 ) options = {}; var title = options.title; var desc = options.desc; var imageUrl = options.imageUrl; var extraParams = options.extraParams; var type = options.type; callModule('miniApp.setAppShareInfo', options, { type: type, title: title, imageUrl: imageUrl, extraParams: extraParams, description: desc, }); } function startPullDownRefresh(options) { callModule('miniApp.startPullDownRefresh', options); } function stopPullDownRefresh(options) { callModule('miniApp.stopPullDownRefresh', options); } function setBackgroundTextStyle(options) { callModule('miniApp.setBackgroundTextStyle', options); } function setBackgroundColor(options) { callModule('miniApp.setBackgroundColor', options); } function reLaunch(options) { callModule('miniApp.reLaunch', options); } function hideLauncherLoading(options) { callModule('miniApp.hideLauncherLoading', options); } function pageScrollTo(options) { if ( options === void 0 ) options = {}; emitModuleAPIEvent('pageScrollTo', { scrollTop: options.scrollTop }); } function alert(options) { if ( options === void 0 ) options = {}; callModule('modal.alert', options, { title: options.title, message: options.content, okTitle: options.buttonText }); } function confirm(options) { if ( options === void 0 ) options = {}; var confirmButtonText = options.confirmButtonText || '确定'; var cancelButtonText = options.cancelButtonText || '取消'; callModule('modal.confirm', options, { title: options.title, message: options.content, okTitle: confirmButtonText, cancelTitle: cancelButtonText }, function (res) { return { confirm: res.data === confirmButtonText }; }); } function showToast(options) { if ( options === void 0 ) options = {}; if (!options.duration) { options.duration = 2000; } callModule('modal.toast', options, { message: options.content, duration: options.duration / 1000 }); } function hideToast(options) { callModule('modal.hideToast', options); } function prompt(options) { callModule('modal.prompt', options); } function showLoading(options) { callModule('modal.showLoading', options); } function hideLoading(options) { callModule('modal.hideLoading', options); } function sendMtop(options) { callModule('sendMtop.request', preprocess('sendMtop', options)); } function isAbsolute(pathname) { return pathname.charAt(0) === '/'; } // About 1.5x faster than the two-arg version of Array#splice() function spliceOne(list, index) { for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) { list[i] = list[k]; } list.pop(); } // This implementation is based heavily on node's url.parse function resolvePathname(to) { var from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var toParts = to && to.split('/') || []; var fromParts = from && from.split('/') || []; var isToAbs = to && isAbsolute(to); var isFromAbs = from && isAbsolute(from); var mustEndAbs = isToAbs || isFromAbs; if (to && isAbsolute(to)) { // to is absolute fromParts = toParts; } else if (toParts.length) { // to is relative, drop the filename fromParts.pop(); fromParts = fromParts.concat(toParts); } if (!fromParts.length) { return '/'; } var hasTrailingSlash = void 0; if (fromParts.length) { var last = fromParts[fromParts.length - 1]; hasTrailingSlash = last === '.' || last === '..' || last === ''; } else { hasTrailingSlash = false; } var up = 0; for (var i = fromParts.length; i >= 0; i--) { var part = fromParts[i]; if (part === '.') { spliceOne(fromParts, i); } else if (part === '..') { spliceOne(fromParts, i); up++; } else if (up) { spliceOne(fromParts, i); up--; } } if (!mustEndAbs) { for (; up--; up) { fromParts.unshift('..'); } }if (mustEndAbs && fromParts[0] !== '' && (!fromParts[0] || !isAbsolute(fromParts[0]))) { fromParts.unshift(''); } var result = fromParts.join('/'); if (hasTrailingSlash && result.substr(-1) !== '/') { result += '/'; } return result; } /// <reference path="../../types/resolve-pathname.d.ts" /> function formatPath(url) { if ( url === void 0 ) url = ''; // process absolute path return url[0] === '/' ? url.slice(1) : url; } function navigateTo(options, basePath) { if ( options === void 0 ) options = {}; if ( basePath === void 0 ) basePath = ''; options = preprocess('navigateTo', options); var url = resolvePathname(options.url, basePath) || ''; callModule('navigator.push', options, { url: formatPath(url) }); } function navigateBack(options) { callModule('navigator.pop', preprocess('navigateBack', options)); } function redirectTo(options) { if ( options === void 0 ) options = {}; options = preprocess('redirectTo', options); callModule('navigator.redirectTo', options, { url: formatPath(options.url) }); } function switchTab(options) { if ( options === void 0 ) options = {}; options = preprocess('switchTab', options); callModule('navigator.switchTab', options, { url: formatPath(options.url) }); } function navigateToMiniProgram(options) { callModule('navigator.navigateToMiniProgram', options); } function navigateBackMiniProgram(options) { callModule('navigator.navigateBackMiniProgram', options); } // only for PC function onPageNotify(callback) { callModule('navigator.pc_onPageNotify', { success: callback }); } // only for PC function offPageNotify() { callModule('navigator.pc_offPageNotify'); } // only for PC function setPageNotifyConfig(options) { callModule('navigator.pc_setPageNotifyConfig', options); } function getBackStack(options) { callModule('navigator.getBackStack', options); } function popToHome(options) { callModule('navigator.popToHome', options); } function reloadPage(options) { callModule('navigator.reloadPage', options); } function setNavigationBar(options) { callModule('navigatorBar.setNavigationBar', options); } function getStatusBarHeight(options) { callModule('navigatorBar.getStatusBarHeight', options, options, function (res) { return { height: parseInt(res.data) }; }); } function getNavigationBarHeight(options) { callModule('navigatorBar.getHeight', options, options, function (res) { return { height: parseInt(res.data) }; }); } function showNavigationBarLoading(options) { callModule('navigatorBar.showNavigationBarLoading', options); } function hideNavigationBarLoading(options) { callModule('navigatorBar.hideNavigationBarLoading', options); } function setNavigationBarDrawer(options) { callModule('navigatorBar.setDrawer', options); } function openNavigationBarDrawer(options) { callModule('navigatorBar.openDrawer', options); } function closeNavigationBarDrawer(options) { callModule('navigatorBar.closeDrawer', options); } function setNavigationBarSheet(options) { callModule('navigatorBar.setActionSheet', options); } function showNavigatorBar(options) { callModule('navigatorBar.show', options); } function hideNavigatorBar(options) { callModule('navigatorBar.hide', options); } function setNavigatorBarRightItem(options) { callModule('navigatorBar.setRightItem', options); } function hasBackHomeBadge(options) { callModule('navigatorBar.hasIndexBadge', options); } function scaleBackHomeBadge(options) { callModule('navigatorBar.scaleIndexBadge', options); } function resetBackHomeBadge(options) { callModule('navigatorBar.resetIndexBadge', options); } function httpRequest(options) { if ( options === void 0 ) options = {}; options = preprocess('httpRequest', options); var method = options.method || 'GET'; // GET 请求不支持 body 方式传递参数,需要使用 url 传参。 if (method === 'GET' && isPlainObject(options.data)) { var query = []; Object.keys(options.data).forEach(function (key) { var data = options.data[key]; var value = typeof data === 'object' ? JSON.stringify(data) : data; query.push((key + "=" + (encodeURIComponent(value)))); }); var queryString = query.join('&'); if (options.url.indexOf('?') >= 0) { options.url += queryString; } else { options.url += ('?' + queryString); } } callModule('network.request', options, { method: method, url: options.url, headers: options.headers || { 'Content-Type': 'application/x-www-form-urlencoded' }, dataType: options.dataType || 'json', body: options.data, }, function (res) { return { data: res.data, status: res.status, headers: res.headers }; }); } function uploadFile(options) { callModule('network.uploadFile', options); } function downloadFile(options) { callModule('network.downloadFile', options); } function makePhoneCall(options) { if ( options === void 0 ) options = {}; callModule('phone.makePhoneCall', options, { phoneNumber: options.number }); } function chooseCity(options) { if ( options === void 0 ) options = {}; if (options.cities && Array.isArray(options.cities)) { options.cities = options.cities.map(function (city) { return { cityName: city.city, cityCode: city.adCode, spell: city.spell }; }); } if (options.hotCities && Array.isArray(options.hotCities)) { options.hotCities = options.hotCities.map(function (city) { return { cityName: city.city, cityCode: city.adCode, spell: city.spell }; }); } callModule('picker.chooseCity', options, options, function (res) { return { city: res.cityName, adCode: res.cityCode }; }); } function datePicker(options) { if ( options === void 0 ) options = {}; callModule('picker.pickDate', options, { format: options.format, value: options.currentDate, min: options.startDate, max: options.endDate }, function (result) { return ({ date: result.data }); }); } function setScreenBrightness(options) { if ( options === void 0 ) options = {}; callModule('screen.setBrightness', options, { brightness: options.brightness }); } function getScreenBrightness(options) { callModule('screen.getScreenBrightness', options, options, function (res) { return { brightness: res.value }; }); } function setKeepScreenOn(options) { if ( options === void 0 ) options = {}; callModule('screen.setAlwaysOn', options, { on: options.keepScreenOn }); } function shareTinyAppMsg(options) { callModule('share.doShare', options); } function showSku(options) { callModule('sku.show', options); } function hideSku(options) { callModule('sku.hide', options); } function proccessSetStorageValue(options) { return STORAGE_JSON_FLAG + JSON.stringify(options.data); } function setStorage(options) { if ( options === void 0 ) options = {}; callModule('storage.setItem', options, { key: options.key, value: proccessSetStorageValue(options) }); } function setStorageSync(options) { return callModuleSync('storage.setItemSync', { key: options.key, value: proccessSetStorageValue(options) }); } function proccessGetStorageRes(res) { var data; if (STORAGE_JSON_FLAG_REGEXP.test(res.value)) { data = JSON.parse(res.value.substr(STORAGE_JSON_FLAG.length)); } else { data = res.value; } return { data: data }; } function getStorage(options) { if ( options === void 0 ) options = {}; callModule('storage.getItem', options, options, proccessGetStorageRes); } function getStorageSync(options) { return proccessGetStorageRes(callModuleSync('storage.getItemSync', options)); } function removeStorage(options) { if ( options === void 0 ) options = {}; callModule('storage.removeItem', options); } function removeStorageSync(options) { if ( options === void 0 ) options = {}; return callModuleSync('storage.removeItemSync', options); } function clearStorage(options) { callModule('storage.clearStorage', options); } function clearStorageSync(options) { return callModuleSync('storage.clearStorageSync', options); } function getStorageInfo(options) { callModule('storage.getStorageInfo', options); } function getStorageInfoSync(options) { return callModuleSync('storage.getStorageInfoSync', options); } /** * 获取系统环境信息 * * https://docs.alipay.com/mini/api/system-info * https://lark.alipay.com/taobaoapp/design/app_worker#%E6%B3%A8%E5%85%A5%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F */ function getSystemInfoSync() { var env = getEnv(); return { model: env.model, pixelRatio: env.pixelRatio, windowWidth: env.screenWidth, windowHeight: env.screenHeight, language: env.language, version: env.appVersion, storage: null, currentBattery: null, system: env.systemVersion, platform: env.platform, screenWidth: env.screenWidth, screenHeight: env.screenHeight, brand: env.brand, fontSizeSetting: 14, app: env.appName, SDKVersion: env.version, frameworkType: env.frameworkType, frameworkVersion: env.frameworkVersion, userAgent: env.userAgent, screenDensity: env.screenDensity // 屏幕像素密度(number),Only Android }; } function getSystemInfo(params) { if ( params === void 0 ) params = {}; try { if (typeof params.success === 'function') { params.success.call(this, getSystemInfoSync()); } } catch (err) { if (typeof params.fail === 'function') { params.fail.call(this, err); } } finally { if (typeof params.complete === 'function') { params.complete.call(this); } } } var SDKVersion = getEnv().version || ''; function showTabBar(options) { callModule('tabBar.show', options); } function hideTabBar(options) { callModule('tabBar.hide', options); } function setTabBarStyle(options) { callModule('tabBar.setTabBarStyle', options); } function setTabBarItem(options) { callModule('tabBar.setTabBarItem', options); } function setTabBarBadge(options) { callModule('tabBar.setTabBarBadge', options); } function removeTabBarBadge(options) { callModule('tabBar.removeTabBarBadge', options); } function showTabBarRedDot(options) { callModule('tabBar.showTabBarRedDot', options); } function hideTabBarRedDot(options) { callModule('tabBar.hideTabBarRedDot', options); } function addTabBarItem(options) { callModule('tabBar.addTabBarItem', options); } function removeTabBarItem(options) { callModule('tabBar.removeTabBarItem', options); } function uccBind(options) { callModule('ucc.uccBind', options); } function uccTrustLogin(options) { callModule('ucc.uccTrustLogin', options); } function uccUnbind(options) { callModule('ucc.uccUnbind', options); } function reportAnalytics(eventName, data) { if ( data === void 0 ) data = {}; if (eventName === 'click' || eventName === 'enter' || eventName === 'expose') { var commitut = getMethod('userTrack.commitut'); commitut({ type: eventName, eventId: data.eventId, name: data.name, comName: data.comName, arg1: data.arg1, arg2: data.arg2, arg3: data.arg3, param: data.param }); } else { var customAdvance = getMethod('userTrack.customAdvance'); customAdvance({ eventId: data.eventId, name: data.name, comName: data.comName, arg1: data.arg1, arg2: data.arg2, arg3: data.arg3, param: data.param }); } } /** * @params {String} utMethodName * 枚举值: commit, commitut, commitEvent, customAdvance, pageAppear, * pageDisappear, skipPage, updatePageUtparam, updateNextPageUtparam * @params {Object} data */ function callUserTrack(utMethodName, data) { if ( data === void 0 ) data = {}; var utMethod = getMethod('userTrack.' + utMethodName); if (typeof utMethod === 'function') { utMethod(data); } } var ACTION_LIST$3 = ['play', 'pause', 'stop', 'requestFullScreen', 'exitFullScreen', 'showControls', 'hideControls', 'enableLoop', 'disableLoop']; var VideoContext = function VideoContext(id) { var this$1 = this; ACTION_LIST$3.forEach(function (action) { this$1[action] = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var pageId = getCurrentPageId(); var eventName = "[[VideoContextAction]]@" + pageId; getRuntime().$emit(eventName, { action: action, id: id, args: args }, pageId); }; }); }; function createVideoContext(id) { return new VideoContext(id); } function chooseVideo(opitons) { callModule('video.chooseVideo', opitons, opitons, function (res) { if (res.apFilePath) { res.tempFilePath = res.apFilePath; delete res.apFilePath; } return res; }); } function saveVideoToPhotosAlbum(opitons) { callModule('video.saveVideoToPhotosAlbum', opitons); } function getAuthUserInfo(options) { callModule('sendMtop.request', options, { api: 'mtop.taobao.openlink.openinfo.user.get', v: '1.0', type: 'GET' }, function (res) { var result = { nickName: res.data.mixNick, userId: res.data.openId }; if (res.data.avatar) { result.avatar = res.data.avatar; } if (res.data.unionId) { result.unionId = res.data.unionId; } return result; }); } function getTBCode(options) { callModule('sendMtop.request', options, { api: 'mtop.taobao.openlink.basic.login.auth.code', v: '1.0', type: 'GET' }, func