diff --git a/docs/api/request/request.md b/docs/api/request/request.md index 1bdb5c4ad90583d01cd54af3af92f351bdf2f9a0..452077202d380af5f29795543930c7ef38185e9f 100644 --- a/docs/api/request/request.md +++ b/docs/api/request/request.md @@ -42,6 +42,7 @@ |data|Object/String/ArrayBuffer|开发者服务器返回的数据| |statusCode|Number|开发者服务器返回的 HTTP 状态码| |header|Object|开发者服务器返回的 HTTP Response Header| +|cookies|``Array.``|开发者服务器返回的 cookies,格式为字符串数组| **data 数据说明** diff --git a/lib/apis.js b/lib/apis.js index 6bccb8919faaf6965c4a2947c24dc452c61d223c..ca14f0fed08ac471e10e7b49a113e444a43faac0 100644 --- a/lib/apis.js +++ b/lib/apis.js @@ -109,7 +109,9 @@ const device = [ 'getBLEDeviceServices', 'getBLEDeviceCharacteristics', 'createBLEConnection', - 'closeBLEConnection', + 'closeBLEConnection', + 'setBLEMTU', + 'getBLEDeviceRSSI', 'onBeaconServiceChange', 'onBeaconUpdate', 'getBeacons', diff --git a/lib/modules.json b/lib/modules.json index 7d597a9e8bf7e460070717c988ee438c87f38095..740b9fa775089ba5551c12032b677a7b97de29c4 100644 --- a/lib/modules.json +++ b/lib/modules.json @@ -113,7 +113,9 @@ "uni.getBLEDeviceServices": true, "uni.getBLEDeviceCharacteristics": true, "uni.createBLEConnection": true, - "uni.closeBLEConnection": true, + "uni.closeBLEConnection": true, + "uni.setBLEMTU": true, + "uni.getBLEDeviceRSSI": true, "uni.onBeaconServiceChange": true, "uni.onBeaconUpdate": true, "uni.getBeacons": true, diff --git a/packages/uni-app-plus/template/common/__uniapppicker.js b/packages/uni-app-plus/template/common/__uniapppicker.js index ee3631e7347ce878a7d062ab9f9964f0e2c26fae..9047632c79de0c23e6b69cf03d396158803ec873 100644 --- a/packages/uni-app-plus/template/common/__uniapppicker.js +++ b/packages/uni-app-plus/template/common/__uniapppicker.js @@ -1 +1 @@ -!function(e){var t={};function n(a){if(t[a])return t[a].exports;var r=t[a]={i:a,l:!1,exports:{}};return e[a].call(r.exports,r,r.exports,n),r.l=!0,r.exports}n.m=e,n.c=t,n.d=function(e,t,a){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(n.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(a,r,function(t){return e[t]}.bind(null,r));return a},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=44)}([function(e,t){e.exports={}},function(e,t,n){"use strict";function a(e,t,n,a,r,i,o,s,u,c){var l,f="function"==typeof e?e.options:e;if(u){f.components||(f.components={});var d=Object.prototype.hasOwnProperty;for(var p in u)d.call(u,p)&&!d.call(f.components,p)&&(f.components[p]=u[p])}if(c&&((c.beforeCreate||(c.beforeCreate=[])).unshift((function(){this[c.__module]=this})),(f.mixins||(f.mixins=[])).push(c)),t&&(f.render=t,f.staticRenderFns=n,f._compiled=!0),a&&(f.functional=!0),i&&(f._scopeId="data-v-"+i),o?(l=function(e){(e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),r&&r.call(this,e),e&&e._registeredComponents&&e._registeredComponents.add(o)},f._ssrRegister=l):r&&(l=s?function(){r.call(this,this.$root.$options.shadowRoot)}:r),l)if(f.functional){f._injectStyles=l;var h=f.render;f.render=function(e,t){return l.call(t),h(e,t)}}else{var v=f.beforeCreate;f.beforeCreate=v?[].concat(v,l):[l]}return{exports:e,options:f}}n.d(t,"a",(function(){return a}))},function(e,t,n){"use strict";var a;Object.defineProperty(t,"__esModule",{value:!0}),t.weexPlus=t.default=void 0,a="function"==typeof getUni?getUni:function(){var e=function(e){return"function"==typeof e},t=function(e){return e.then((function(e){return[null,e]})).catch((function(e){return[e]}))},n=/^\$|^on|^create|Sync$|Manager$|^pause/,a=["os","getCurrentSubNVue","getSubNVueById","stopRecord","stopVoice","stopBackgroundAudio","stopPullDownRefresh","hideKeyboard","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","canIUse","navigateBack","closeSocket","pageScrollTo","drawCanvas"],i=function(e){return(!n.test(e)||"createBLEConnection"===e)&&!~a.indexOf(e)},o=function(n){return function(){for(var a=arguments.length,r=Array(a>1?a-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:{};return e(o.success)||e(o.fail)||e(o.complete)?n.apply(void 0,[o].concat(r)):t(new Promise((function(e,t){n.apply(void 0,[Object.assign({},o,{success:e,fail:t})].concat(r)),Promise.prototype.finally=function(e){var t=this.constructor;return this.then((function(n){return t.resolve(e()).then((function(){return n}))}),(function(n){return t.resolve(e()).then((function(){throw n}))}))}})))}},s=[],u=void 0;function c(e){s.forEach((function(t){return t({origin:u,data:e})}))}var l=r.webview.currentWebview().id,f=new BroadcastChannel("UNI-APP-SUBNVUE");function d(e){var t=r.webview.getWebviewById(e);return t&&!t.$processed&&function(e){e.$processed=!0;var t=r.webview.currentWebview().id===e.id,n="uniNView"===e.__uniapp_origin_type&&e.__uniapp_origin_id,a=e.id;if(e.postMessage=function(e){n?f.postMessage({data:e,to:t?n:a}):_({type:"UniAppSubNVue",data:e})},e.onMessage=function(e){s.push(e)},e.__uniapp_mask_id){u=e.__uniapp_host;var i=e.__uniapp_mask,o=r.webview.getWebviewById(e.__uniapp_mask_id);o=o.parent()||o;var c=e.show,l=e.hide,d=e.close,p=function(){o.setStyle({mask:i})},h=function(){o.setStyle({mask:"none"})};e.show=function(){p();for(var t=arguments.length,n=Array(t),a=0;a1&&void 0!==arguments[1]?arguments[1]:"GET",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"application/x-www-form-urlencoded";return"object"===(void 0===e?"undefined":L(e))?"POST"===t.toUpperCase()&&"application/json"===n.toLowerCase()?JSON.stringify(e):Object.keys(e).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(e[t])})).join("&"):e},D=weex.requireModule("plusstorage"),j=weex.requireModule("clipboard"),B=function(){if("function"==typeof getUniEmitter)return getUniEmitter;var e={$on:function(){console.warn("uni.$on failed")},$off:function(){console.warn("uni.$off failed")},$once:function(){console.warn("uni.$once failed")},$emit:function(){console.warn("uni.$emit failed")}};return function(){return e}}();function R(e,t,n){return e[t].apply(e,n)}var U=Object.freeze({loadFontFace:function(t){var n=t.family,a=t.source,r=(t.desc,t.success),i=(t.fail,t.complete);I.addRule("fontFace",{fontFamily:n,src:a.replace(/"/g,"'")});var o={errMsg:"loadFontFace:ok",status:"loaded"};e(r)&&r(o),e(i)&&i(o)},ready:V,request:function(t){var n=t.url,a=t.data,r=t.header,i=t.method,o=void 0===i?"GET":i,s=t.dataType,u=void 0===s?"json":s,c=(t.responseType,t.success),l=t.fail,f=t.complete,d=!1,p=!1,h={};if(r)for(var v in r)p||"content-type"!==v.toLowerCase()?h[v]=r[v]:(p=!0,h["Content-Type"]=r[v]);return"GET"===o&&a&&(n=n+(~n.indexOf("?")?"&"===n.substr(-1)||"?"===n.substr(-1)?"":"&":"?")+$(a)),P.fetch({url:n,method:o,headers:h,type:"json"===u?"json":"text",body:"GET"!==o?$(a,o,h["Content-Type"]):""},(function(t){var n=t.status,a=(t.ok,t.statusText,t.data),r=t.headers,i={};!n||-1===n||d?(i.errMsg="request:fail",e(l)&&l(i)):(i.data=a,i.statusCode=n,i.header=r,e(c)&&c(i)),e(f)&&f(i)})),{abort:function(){d=!0}}},getStorage:function(t){var n=t.key,a=(t.data,t.success),r=t.fail,i=t.complete;D.getItem(n+"__TYPE",(function(t){if("success"===t.result){var o=t.data;D.getItem(n,(function(t){if("success"===t.result){var n=t.data;o&&n?("String"!==o&&(n=JSON.parse(n)),e(a)&&a({errMsg:"getStorage:ok",data:n})):(t.errMsg="setStorage:fail",e(r)&&r(t))}else t.errMsg="setStorage:fail",e(r)&&r(t);e(i)&&i(t)}))}else t.errMsg="setStorage:fail",e(r)&&r(t),e(i)&&i(t)}))},setStorage:function(t){var n=t.key,a=t.data,r=t.success,i=t.fail,o=t.complete,s="String";"object"===(void 0===a?"undefined":L(a))&&(s="Object",a=JSON.stringify(a)),D.setItem(n,a,(function(t){"success"===t.result?D.setItem(n+"__TYPE",s,(function(t){"success"===t.result?e(r)&&r({errMsg:"setStorage:ok"}):(t.errMsg="setStorage:fail",e(i)&&i(t))})):(t.errMsg="setStorage:fail",e(i)&&i(t)),e(o)&&o(t)}))},removeStorage:function(t){var n=t.key,a=(t.data,t.success),r=t.fail,i=t.complete;D.removeItem(n,(function(t){"success"===t.result?e(a)&&a({errMsg:"removeStorage:ok"}):(t.errMsg="removeStorage:fail",e(r)&&r(t)),e(i)&&i(t)})),D.removeItem(n+"__TYPE")},clearStorage:function(e){e.key,e.data,e.success,e.fail,e.complete},getClipboardData:function(t){var n=t.success,a=(t.fail,t.complete);j.getString((function(t){var r={errMsg:"getClipboardData:ok",data:t.data};e(n)&&n(r),e(a)&&a(r)}))},setClipboardData:function(t){var n=t.data,a=t.success,r=(t.fail,t.complete),i={errMsg:"setClipboardData:ok"};j.setString(n),e(a)&&a(i),e(r)&&r(i)},onSubNVueMessage:c,getSubNVueById:d,getCurrentSubNVue:function(){return d(r.webview.currentWebview().id)},$on:function(){return R(B(),"$on",[].concat(Array.prototype.slice.call(arguments)))},$off:function(){return R(B(),"$off",[].concat(Array.prototype.slice.call(arguments)))},$once:function(){return R(B(),"$once",[].concat(Array.prototype.slice.call(arguments)))},$emit:function(){return R(B(),"$emit",[].concat(Array.prototype.slice.call(arguments)))}}),z={os:{nvue:!0}},F={};return"undefined"!=typeof Proxy?F=new Proxy({},{get:function(e,t){if("os"===t)return{nvue:!0};if("postMessage"===t)return _;if("requireNativePlugin"===t)return C;if("onNavigationBarButtonTap"===t)return k;if("onNavigationBarSearchInputChanged"===t)return M;if("onNavigationBarSearchInputConfirmed"===t)return E;if("onNavigationBarSearchInputClicked"===t)return x;var n=U[t];return n||(n=b(t)),i(t)?o(n):n}}):(Object.keys(z).forEach((function(e){F[e]=z[e]})),F.postMessage=_,F.requireNativePlugin=C,F.onNavigationBarButtonTap=k,F.onNavigationBarSearchInputChanged=M,F.onNavigationBarSearchInputConfirmed=E,F.onNavigationBarSearchInputClicked=x,Object.keys({uploadFile:!0,downloadFile:!0,chooseImage:!0,previewImage:!0,getImageInfo:!0,saveImageToPhotosAlbum:!0,chooseVideo:!0,saveVideoToPhotosAlbum:!0,saveFile:!0,getSavedFileList:!0,getSavedFileInfo:!0,removeSavedFile:!0,openDocument:!0,setStorage:!0,getStorage:!0,getStorageInfo:!0,removeStorage:!0,clearStorage:!0,getLocation:!0,chooseLocation:!0,openLocation:!0,getSystemInfo:!0,getNetworkType:!0,makePhoneCall:!0,scanCode:!0,setScreenBrightness:!0,getScreenBrightness:!0,setKeepScreenOn:!0,vibrateLong:!0,vibrateShort:!0,addPhoneContact:!0,showToast:!0,showLoading:!0,hideToast:!0,hideLoading:!0,showModal:!0,showActionSheet:!0,setNavigationBarTitle:!0,setNavigationBarColor:!0,navigateTo:!0,redirectTo:!0,reLaunch:!0,switchTab:!0,navigateBack:!0,getProvider:!0,login:!0,getUserInfo:!0,share:!0,requestPayment:!0,subscribePush:!0,unsubscribePush:!0,onPush:!0,offPush:!0}).forEach((function(e){var t=U[e];t||(t=b(e)),i(e)?F[e]=o(t):F[e]=t}))),F};var r=new WeexPlus(weex);t.weexPlus=r;var i=a(weex,r,BroadcastChannel);t.default=i},function(e,t,n){Vue.prototype.__$appStyle__={},Vue.prototype.__merge_style&&Vue.prototype.__merge_style(n(4).default,Vue.prototype.__$appStyle__)},function(e,t,n){"use strict";n.r(t);var a=n(0),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n={onLoad:function(){this.initMessage()},methods:{initMessage:function(){var t=this,n=e.webview.currentWebview().extras||{},a=n.from,r=(n.callback,n.runtime),i=n.data,o=void 0===i?{}:i,s=n.useGlobalEvent;this.__from=a,this.__runtime=r,this.__page=e.webview.currentWebview().id,this.__useGlobalEvent=s,this.data=JSON.parse(JSON.stringify(o)),e.key.addEventListener("backbutton",(function(){"function"==typeof t.onClose?t.onClose():e.webview.currentWebview().close("auto")}));var u=this,c=function(e){var t=e.data&&e.data.__message;t&&u.__onMessageCallback&&u.__onMessageCallback(t.data)};this.__useGlobalEvent?weex.requireModule("globalEvent").addEventListener("plusMessage",c):new BroadcastChannel(this.__page).onmessage=c},postMessage:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]&&arguments[1],a=JSON.parse(JSON.stringify({__message:{__page:this.__page,data:t,keep:n}})),r=this.__from;if("v8"===this.__runtime)if(this.__useGlobalEvent)e.webview.postMessageToUniNView(a,r);else{var i=new BroadcastChannel(r);i.postMessage(a)}else{var o=e.webview.getWebviewById(r);o&&o.evalJS("__plusMessage&&__plusMessage(".concat(JSON.stringify({data:a}),")"))}},onMessage:function(e){this.__onMessageCallback=e}}};t.default=n}).call(this,n(2).weexPlus)},,,,function(e,t,n){"use strict";var a=n(30),r=n(20),i=n(1);var o=Object(i.a)(r.default,a.b,a.c,!1,null,null,"2f5c0238",!1,a.a,void 0);(function(e){this.options.style||(this.options.style={}),Vue.prototype.__merge_style&&Vue.prototype.__$appStyle__&&Vue.prototype.__merge_style(Vue.prototype.__$appStyle__,this.options.style),Vue.prototype.__merge_style?Vue.prototype.__merge_style(n(40).default,this.options.style):Object.assign(this.options.style,n(40).default)}).call(o),t.default=o.exports},,,,,,,,,,,function(e,t,n){"use strict";var a=n(21),r=n.n(a);t.default=r.a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var a=r(n(45));function r(e){return e&&e.__esModule?e:{default:e}}var i={mixins:[r(n(5)).default],components:{picker:a.default},data:function(){return{range:[],rangeKey:"",value:0,mode:"selector",fields:"day",start:"",end:"",disabled:!1,visible:!1}},onLoad:function(){var e=this;null===this.data?this.postMessage({event:"created"},!0):this.showPicker(this.data),this.onMessage((function(t){e.showPicker(t)}))},onReady:function(){var e=this;this.$nextTick((function(){e.visible=!0}))},methods:{showPicker:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.column;for(var n in e)"column"!==n&&("number"==typeof t?this.$set(this.$data[n],t,e[n]):this.$data[n]=e[n])},close:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=n.value,r=void 0===a?-1:a;this.visible=!1,setTimeout((function(){t.postMessage({event:e,value:r})}),210)},onClose:function(){this.close("cancel")},columnchange:function(e){var t=e.column,n=e.value;this.$set(this.value,t,n),this.postMessage({event:"columnchange",column:t,value:n},!0)}}};t.default=i},function(e,t,n){"use strict";n.r(t);var a=n(23),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var a=n(46),r=o(n(35)),i=o(n(47));function o(e){return e&&e.__esModule?e:{default:e}}function s(e){return function(e){if(Array.isArray(e))return u(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||function(e,t){if(!e)return;if("string"==typeof e)return u(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return u(e,t)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,a=new Array(t);nn(i)&&this._cloneArray(a,i)}e.forEach((function(e,n){e!==t.oldValueArray[n]&&(t.oldValueArray[n]=e,t.mode===d.MULTISELECTOR&&t.$emit("columnchange",{column:n,value:e}))}))},visible:function(e){var t=this;e?this.$nextTick((function(){f.transition(t.$refs.picker,{styles:{transform:"translateY(0)"},duration:200})})):f.transition(this.$refs.picker,{styles:{transform:"translateY(".concat(283+this.safeAreaInsets.bottom,"px)")},duration:200})}},created:function(){this._createTime(),this._createDate(),this._setValueSync()},methods:{getTexts:function(e,t){var n=this,a=this.textMaxLength;return e.map((function(e){var r=("object"==typeof e?e[n.rangeKey]||"":e)+(n.units[t]||"");if(a>0&&r.length>a)for(var i=0,o=0,s=0;s127||94===u?1:.65)<=a-1&&(o=s),i>=a)return s===r.length-1?r:r.substr(0,o+1)+"…"}return r||" "})).join("\n")},_createTime:function(){var e=[],t=[];e.splice(0,e.length);for(var n=0;n<24;n++)e.push((n<10?"0":"")+n);t.splice(0,t.length);for(var a=0;a<60;a++)t.push((a<10?"0":"")+a);this.timeArray.push(e,t)},_createDate:function(){for(var e=[],t=(new Date).getFullYear(),n=t-61,a=t+61;n<=a;n++)e.push(String(n));for(var r=[],i=1;i<=12;i++)r.push((i<10?"0":"")+i);for(var o=[],s=1;s<=31;s++)o.push((s<10?"0":"")+s);this.dateArray.push(e,r,o)},_getTimeValue:function(e){return 60*e[0]+e[1]},_getDateValue:function(e){return 366*e[0]+31*(e[1]||0)+(e[2]||0)},_cloneArray:function(e,t){for(var n=0;no?0:i)}break;case d.TIME:case d.DATE:this.valueSync=String(e);break;default:this.valueSync=Number(e)||0}},_setValueArray:function(){var e,t=this.valueSync;switch(this.mode){case d.MULTISELECTOR:e=s(t);break;case d.TIME:e=this._getDateValueArray(t,(0,a.formatDateTime)({mode:d.TIME}));break;case d.DATE:e=this._getDateValueArray(t,(0,a.formatDateTime)({mode:d.DATE}));break;default:e=[t]}this.oldValueArray=s(e),this.valueArray=s(e)},_getValue:function(){var e=this,t=this.valueArray;switch(this.mode){case d.SELECTOR:return t[0];case d.MULTISELECTOR:return t.map((function(e){return e}));case d.TIME:return this.valueArray.map((function(t,n){return e.timeArray[n][t]})).join(":");case d.DATE:return this.valueArray.map((function(t,n){return e.dateArray[n][t]})).join("-")}},_getDateValueArray:function(e,t){var n=this.mode===d.DATE?"-":":",a=this.mode===d.DATE?this.dateArray:this.timeArray,r=3;switch(this.fields){case p.YEAR:r=1;break;case p.MONTH:r=2}for(var i=String(e).split(n),o=[],s=0;s=0&&(o=t?this._getDateValueArray(t):o.map((function(){return 0}))),o},_change:function(){this.$emit("change",{value:this._getValue()})},_cancel:function(){this.$emit("cancel")}}};t.default=h},function(e,t){e.exports={content:{position:"absolute",top:0,left:0,bottom:0,right:0},"uni-mask":{position:"absolute",top:0,left:0,bottom:0,right:0,backgroundColor:"rgba(0,0,0,0.4)",opacity:0,transitionProperty:"opacity",transitionDuration:200,transitionTimingFunction:"linear"},"@TRANSITION":{"uni-mask":{property:"opacity",duration:200,timingFunction:"linear"}},"uni-mask-android":{backgroundColor:"rgba(0,0,0,0.6)"},"uni-mask-visible":{opacity:1},"uni-picker":{position:"absolute",left:0,bottom:0,right:0,backgroundColor:"#ffffff",color:"#000000",flexDirection:"column",transform:"translateY(295px)"},"uni-picker-header":{height:"45",borderBottomWidth:0,backgroundColor:"#E6E6E6",fontSize:"20"},"uni-picker-action":{position:"absolute",textAlign:"center",top:0,height:"45",paddingTop:0,paddingRight:"14",paddingBottom:0,paddingLeft:"14",fontSize:"17",lineHeight:"45"},"uni-picker-action-cancel":{left:0,color:"#888888"},"uni-picker-action-confirm":{right:0,color:"#007aff"},"uni-picker-content":{flex:1},"uni-picker-item":{lineHeight:"34",textAlign:"center",color:"#000000"}}},function(e,t){e.exports={page:{flex:1}}},,,,,function(e,t,n){"use strict";var a=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("scroll-view",{staticStyle:{flexDirection:"column"},attrs:{scrollY:!0,enableBackToTop:!0,bubble:"true"}},[n("view",{staticClass:["page"]},[n("picker",{attrs:{range:e.range,rangeKey:e.rangeKey,value:e.value,mode:e.mode,fields:e.fields,start:e.start,end:e.end,disabled:e.disabled,visible:e.visible},on:{change:function(t){e.close("change",t)},cancel:function(t){e.close("cancel",t)},columnchange:e.columnchange}})],1)])},r=[];n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return r})),n.d(t,"a",(function(){}))},,,function(e,t,n){"use strict";var a=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:["content"]},[n("div",{ref:"mask",staticClass:["uni-mask"],class:{"uni-mask-visible":e.visible,"uni-mask-android":e.android},on:{click:e._cancel}}),n("div",{ref:"picker",staticClass:["uni-picker"],class:{"uni-picker-visible":e.visible},style:"padding-bottom:"+e.safeAreaInsets.bottom+"px;height:"+(e.height+e.safeAreaInsets.bottom)+"px;"},[n("div",{staticClass:["uni-picker-header"]},[n("u-text",{staticClass:["uni-picker-action","uni-picker-action-cancel"],style:"left:"+e.safeAreaInsets.left+"px",on:{click:e._cancel}},[e._v(e._s(e.localize("cancel")))]),n("u-text",{staticClass:["uni-picker-action","uni-picker-action-confirm"],style:"right:"+e.safeAreaInsets.right+"px",on:{click:e._change}},[e._v(e._s(e.localize("ok")))])]),e.visible?n("picker-view",{staticClass:["uni-picker-content"],style:"margin-left:"+e.safeAreaInsets.left+"px",attrs:{height:"216",indicatorStyle:"height: 34px;border-color:#C8C9C9;border-top-width:0.5px;border-bottom-width:0.5px;",value:e.valueArray},on:{"update:value":function(t){e.valueArray=t}}},e._l(e.rangeArray,(function(t,a){return n("picker-view-column",{key:a,attrs:{length:t.length}},[n("u-text",{staticClass:["uni-picker-item"],style:{fontSize:e.fontSize+"px"}},[e._v(e._s(e.getTexts(t,a)))])])})),1):e._e()],1)])},r=[];n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return r})),n.d(t,"a",(function(){}))},,function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n={data:function(){return{locale:{default:"en",full:"en",primary:"en"},localization:{en:{ok:"OK",cancel:"Cancel"},zh:{ok:"完成",cancel:"取消"},"zh-hans":{},"zh-hant":{}}}},onLoad:function(){this.initLocale()},created:function(){this.initLocale()},methods:{initLocale:function(){if(!this.__initLocale){this.__initLocale=!0;var t=e.os.language.toLowerCase().replace("_","-").split("-"),n=t[1];n&&(t[1]={chs:"hans",cn:"hans",sg:"hans",cht:"hant",tw:"hant",hk:"hant",mo:"hant"}[n]||n),t.length=t.length>2?2:t.length,this.locale.full=t.join("-"),this.locale.primary=t[0]}},localize:function(e){var t=this.locale,n=this.localization;function a(e){return n[e]||{}}return a(t.full)[e]||a(t.primary)[e]||a(t.default)[e]||e}}};t.default=n}).call(this,n(2).weexPlus)},,,,function(e,t,n){"use strict";n.r(t);var a=n(24),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},function(e,t,n){"use strict";n.r(t);var a=n(25),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},,,,function(e,t,n){"use strict";n.r(t);n(3);var a=n(9);a.default.mpType="page",a.default.route="template/__uniapppicker",a.default.el="#root",new Vue(a.default)},function(e,t,n){"use strict";n.r(t);var a=n(33),r=n(22);for(var i in r)"default"!==i&&function(e){n.d(t,e,(function(){return r[e]}))}(i);var o=n(1);var s=Object(o.a)(r.default,a.b,a.c,!1,null,null,"2b83bbfe",!1,a.a,void 0);(function(e){this.options.style||(this.options.style={}),Vue.prototype.__merge_style&&Vue.prototype.__$appStyle__&&Vue.prototype.__merge_style(Vue.prototype.__$appStyle__,this.options.style),Vue.prototype.__merge_style?Vue.prototype.__merge_style(n(39).default,this.options.style):Object.assign(this.options.style,n(39).default)}).call(s),t.default=s.exports},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.formatDateTime=function(e){var t=e.date,n=void 0===t?new Date:t,r=e.mode;return"time"===(void 0===r?"date":r)?a(n.getHours())+":"+a(n.getMinutes()):n.getFullYear()+"-"+a(n.getMonth()+1)+"-"+a(n.getDate())};var a=function(e){return e>9?e:"0"+e}},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n={data:function(){return{safeAreaInsets:{left:0,right:0,top:0,bottom:0}}},onLoad:function(){this.initSafeAreaInsets()},created:function(){this.initSafeAreaInsets()},methods:{initSafeAreaInsets:function(){var t=this;if(!this.__initSafeAreaInsets){this.__initSafeAreaInsets=!0;var n=e.webview.currentWebview();n.addEventListener("resize",(function(){setTimeout((function(){t.updateSafeAreaInsets(n)}),20)})),this.updateSafeAreaInsets(n)}},updateSafeAreaInsets:function(e){var t=e.getSafeAreaInsets(),n=this.safeAreaInsets;Object.keys(n).forEach((function(e){n[e]=t[e]}))}}};t.default=n}).call(this,n(2).weexPlus)}]); \ No newline at end of file +!function(e){var t={};function n(a){if(t[a])return t[a].exports;var r=t[a]={i:a,l:!1,exports:{}};return e[a].call(r.exports,r,r.exports,n),r.l=!0,r.exports}n.m=e,n.c=t,n.d=function(e,t,a){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(n.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(a,r,function(t){return e[t]}.bind(null,r));return a},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=44)}([function(e,t){e.exports={}},function(e,t,n){"use strict";function a(e,t,n,a,r,i,o,s,u,c){var l,f="function"==typeof e?e.options:e;if(u){f.components||(f.components={});var d=Object.prototype.hasOwnProperty;for(var p in u)d.call(u,p)&&!d.call(f.components,p)&&(f.components[p]=u[p])}if(c&&((c.beforeCreate||(c.beforeCreate=[])).unshift((function(){this[c.__module]=this})),(f.mixins||(f.mixins=[])).push(c)),t&&(f.render=t,f.staticRenderFns=n,f._compiled=!0),a&&(f.functional=!0),i&&(f._scopeId="data-v-"+i),o?(l=function(e){(e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),r&&r.call(this,e),e&&e._registeredComponents&&e._registeredComponents.add(o)},f._ssrRegister=l):r&&(l=s?function(){r.call(this,this.$root.$options.shadowRoot)}:r),l)if(f.functional){f._injectStyles=l;var h=f.render;f.render=function(e,t){return l.call(t),h(e,t)}}else{var v=f.beforeCreate;f.beforeCreate=v?[].concat(v,l):[l]}return{exports:e,options:f}}n.d(t,"a",(function(){return a}))},function(e,t,n){"use strict";var a;Object.defineProperty(t,"__esModule",{value:!0}),t.weexPlus=t.default=void 0,a="function"==typeof getUni?getUni:function(){var e=function(e){return"function"==typeof e},t=function(e){return e.then((function(e){return[null,e]})).catch((function(e){return[e]}))},n=/^\$|^on|^create|Sync$|Manager$|^pause/,a=["os","getCurrentSubNVue","getSubNVueById","stopRecord","stopVoice","stopBackgroundAudio","stopPullDownRefresh","hideKeyboard","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","canIUse","navigateBack","closeSocket","pageScrollTo","drawCanvas"],i=function(e){return(!n.test(e)||"createBLEConnection"===e)&&!~a.indexOf(e)},o=function(n){return function(){for(var a=arguments.length,r=Array(a>1?a-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:{};return e(o.success)||e(o.fail)||e(o.complete)?n.apply(void 0,[o].concat(r)):t(new Promise((function(e,t){n.apply(void 0,[Object.assign({},o,{success:e,fail:t})].concat(r)),Promise.prototype.finally=function(e){var t=this.constructor;return this.then((function(n){return t.resolve(e()).then((function(){return n}))}),(function(n){return t.resolve(e()).then((function(){throw n}))}))}})))}},s=[],u=void 0;function c(e){s.forEach((function(t){return t({origin:u,data:e})}))}var l=r.webview.currentWebview().id,f=new BroadcastChannel("UNI-APP-SUBNVUE");function d(e){var t=r.webview.getWebviewById(e);return t&&!t.$processed&&function(e){e.$processed=!0;var t=r.webview.currentWebview().id===e.id,n="uniNView"===e.__uniapp_origin_type&&e.__uniapp_origin_id,a=e.id;if(e.postMessage=function(e){n?f.postMessage({data:e,to:t?n:a}):_({type:"UniAppSubNVue",data:e})},e.onMessage=function(e){s.push(e)},e.__uniapp_mask_id){u=e.__uniapp_host;var i=e.__uniapp_mask,o=r.webview.getWebviewById(e.__uniapp_mask_id);o=o.parent()||o;var c=e.show,l=e.hide,d=e.close,p=function(){o.setStyle({mask:i})},h=function(){o.setStyle({mask:"none"})};e.show=function(){p();for(var t=arguments.length,n=Array(t),a=0;a1&&void 0!==arguments[1]?arguments[1]:"GET",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"application/x-www-form-urlencoded";return"object"===(void 0===e?"undefined":L(e))?"POST"===t.toUpperCase()&&"application/json"===n.toLowerCase()?JSON.stringify(e):Object.keys(e).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(e[t])})).join("&"):e},D=weex.requireModule("plusstorage"),j=weex.requireModule("clipboard"),B=function(){if("function"==typeof getUniEmitter)return getUniEmitter;var e={$on:function(){console.warn("uni.$on failed")},$off:function(){console.warn("uni.$off failed")},$once:function(){console.warn("uni.$once failed")},$emit:function(){console.warn("uni.$emit failed")}};return function(){return e}}();function R(e,t,n){return e[t].apply(e,n)}var U=Object.freeze({loadFontFace:function(t){var n=t.family,a=t.source,r=(t.desc,t.success),i=(t.fail,t.complete);I.addRule("fontFace",{fontFamily:n,src:a.replace(/"/g,"'")});var o={errMsg:"loadFontFace:ok",status:"loaded"};e(r)&&r(o),e(i)&&i(o)},ready:V,request:function(t){var n=t.url,a=t.data,r=t.header,i=t.method,o=void 0===i?"GET":i,s=t.dataType,u=void 0===s?"json":s,c=(t.responseType,t.success),l=t.fail,f=t.complete,d=!1,p=!1,h={};if(r)for(var v in r)p||"content-type"!==v.toLowerCase()?h[v]=r[v]:(p=!0,h["Content-Type"]=r[v]);return"GET"===o&&a&&(n=n+(~n.indexOf("?")?"&"===n.substr(-1)||"?"===n.substr(-1)?"":"&":"?")+$(a)),P.fetch({url:n,method:o,headers:h,type:"json"===u?"json":"text",body:"GET"!==o?$(a,o,h["Content-Type"]):""},(function(t){var n=t.status,a=(t.ok,t.statusText,t.data),r=t.headers,i={};!n||-1===n||d?(i.errMsg="request:fail",e(l)&&l(i)):(i.data=a,i.statusCode=n,i.header=r,e(c)&&c(i)),e(f)&&f(i)})),{abort:function(){d=!0}}},getStorage:function(t){var n=t.key,a=(t.data,t.success),r=t.fail,i=t.complete;D.getItem(n+"__TYPE",(function(t){if("success"===t.result){var o=t.data;D.getItem(n,(function(t){if("success"===t.result){var n=t.data;o&&n?("String"!==o&&(n=JSON.parse(n)),e(a)&&a({errMsg:"getStorage:ok",data:n})):(t.errMsg="setStorage:fail",e(r)&&r(t))}else t.errMsg="setStorage:fail",e(r)&&r(t);e(i)&&i(t)}))}else t.errMsg="setStorage:fail",e(r)&&r(t),e(i)&&i(t)}))},setStorage:function(t){var n=t.key,a=t.data,r=t.success,i=t.fail,o=t.complete,s="String";"object"===(void 0===a?"undefined":L(a))&&(s="Object",a=JSON.stringify(a)),D.setItem(n,a,(function(t){"success"===t.result?D.setItem(n+"__TYPE",s,(function(t){"success"===t.result?e(r)&&r({errMsg:"setStorage:ok"}):(t.errMsg="setStorage:fail",e(i)&&i(t))})):(t.errMsg="setStorage:fail",e(i)&&i(t)),e(o)&&o(t)}))},removeStorage:function(t){var n=t.key,a=(t.data,t.success),r=t.fail,i=t.complete;D.removeItem(n,(function(t){"success"===t.result?e(a)&&a({errMsg:"removeStorage:ok"}):(t.errMsg="removeStorage:fail",e(r)&&r(t)),e(i)&&i(t)})),D.removeItem(n+"__TYPE")},clearStorage:function(e){e.key,e.data,e.success,e.fail,e.complete},getClipboardData:function(t){var n=t.success,a=(t.fail,t.complete);j.getString((function(t){var r={errMsg:"getClipboardData:ok",data:t.data};e(n)&&n(r),e(a)&&a(r)}))},setClipboardData:function(t){var n=t.data,a=t.success,r=(t.fail,t.complete),i={errMsg:"setClipboardData:ok"};j.setString(n),e(a)&&a(i),e(r)&&r(i)},onSubNVueMessage:c,getSubNVueById:d,getCurrentSubNVue:function(){return d(r.webview.currentWebview().id)},$on:function(){return R(B(),"$on",[].concat(Array.prototype.slice.call(arguments)))},$off:function(){return R(B(),"$off",[].concat(Array.prototype.slice.call(arguments)))},$once:function(){return R(B(),"$once",[].concat(Array.prototype.slice.call(arguments)))},$emit:function(){return R(B(),"$emit",[].concat(Array.prototype.slice.call(arguments)))}}),z={os:{nvue:!0}},F={};return"undefined"!=typeof Proxy?F=new Proxy({},{get:function(e,t){if("os"===t)return{nvue:!0};if("postMessage"===t)return _;if("requireNativePlugin"===t)return C;if("onNavigationBarButtonTap"===t)return k;if("onNavigationBarSearchInputChanged"===t)return M;if("onNavigationBarSearchInputConfirmed"===t)return E;if("onNavigationBarSearchInputClicked"===t)return x;var n=U[t];return n||(n=b(t)),i(t)?o(n):n}}):(Object.keys(z).forEach((function(e){F[e]=z[e]})),F.postMessage=_,F.requireNativePlugin=C,F.onNavigationBarButtonTap=k,F.onNavigationBarSearchInputChanged=M,F.onNavigationBarSearchInputConfirmed=E,F.onNavigationBarSearchInputClicked=x,Object.keys({uploadFile:!0,downloadFile:!0,chooseImage:!0,previewImage:!0,getImageInfo:!0,saveImageToPhotosAlbum:!0,chooseVideo:!0,saveVideoToPhotosAlbum:!0,saveFile:!0,getSavedFileList:!0,getSavedFileInfo:!0,removeSavedFile:!0,openDocument:!0,setStorage:!0,getStorage:!0,getStorageInfo:!0,removeStorage:!0,clearStorage:!0,getLocation:!0,chooseLocation:!0,openLocation:!0,getSystemInfo:!0,getNetworkType:!0,makePhoneCall:!0,scanCode:!0,setScreenBrightness:!0,getScreenBrightness:!0,setKeepScreenOn:!0,vibrateLong:!0,vibrateShort:!0,addPhoneContact:!0,showToast:!0,showLoading:!0,hideToast:!0,hideLoading:!0,showModal:!0,showActionSheet:!0,setNavigationBarTitle:!0,setNavigationBarColor:!0,navigateTo:!0,redirectTo:!0,reLaunch:!0,switchTab:!0,navigateBack:!0,getProvider:!0,login:!0,getUserInfo:!0,share:!0,requestPayment:!0,subscribePush:!0,unsubscribePush:!0,onPush:!0,offPush:!0}).forEach((function(e){var t=U[e];t||(t=b(e)),i(e)?F[e]=o(t):F[e]=t}))),F};var r=new WeexPlus(weex);t.weexPlus=r;var i=a(weex,r,BroadcastChannel);t.default=i},function(e,t,n){Vue.prototype.__$appStyle__={},Vue.prototype.__merge_style&&Vue.prototype.__merge_style(n(4).default,Vue.prototype.__$appStyle__)},function(e,t,n){"use strict";n.r(t);var a=n(0),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n={onLoad:function(){this.initMessage()},methods:{initMessage:function(){var t=this,n=e.webview.currentWebview().extras||{},a=n.from,r=(n.callback,n.runtime),i=n.data,o=void 0===i?{}:i,s=n.useGlobalEvent;this.__from=a,this.__runtime=r,this.__page=e.webview.currentWebview().id,this.__useGlobalEvent=s,this.data=JSON.parse(JSON.stringify(o)),e.key.addEventListener("backbutton",(function(){"function"==typeof t.onClose?t.onClose():e.webview.currentWebview().close("auto")}));var u=this,c=function(e){var t=e.data&&e.data.__message;t&&u.__onMessageCallback&&u.__onMessageCallback(t.data)};this.__useGlobalEvent?weex.requireModule("globalEvent").addEventListener("plusMessage",c):new BroadcastChannel(this.__page).onmessage=c},postMessage:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]&&arguments[1],a=JSON.parse(JSON.stringify({__message:{__page:this.__page,data:t,keep:n}})),r=this.__from;if("v8"===this.__runtime)if(this.__useGlobalEvent)e.webview.postMessageToUniNView(a,r);else{var i=new BroadcastChannel(r);i.postMessage(a)}else{var o=e.webview.getWebviewById(r);o&&o.evalJS("__plusMessage&&__plusMessage(".concat(JSON.stringify({data:a}),")"))}},onMessage:function(e){this.__onMessageCallback=e}}};t.default=n}).call(this,n(2).weexPlus)},,,,function(e,t,n){"use strict";var a=n(30),r=n(20),i=n(1);var o=Object(i.a)(r.default,a.b,a.c,!1,null,null,"2f5c0238",!1,a.a,void 0);(function(e){this.options.style||(this.options.style={}),Vue.prototype.__merge_style&&Vue.prototype.__$appStyle__&&Vue.prototype.__merge_style(Vue.prototype.__$appStyle__,this.options.style),Vue.prototype.__merge_style?Vue.prototype.__merge_style(n(40).default,this.options.style):Object.assign(this.options.style,n(40).default)}).call(o),t.default=o.exports},,,,,,,,,,,function(e,t,n){"use strict";var a=n(21),r=n.n(a);t.default=r.a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var a=r(n(45));function r(e){return e&&e.__esModule?e:{default:e}}var i={mixins:[r(n(5)).default],components:{picker:a.default},data:function(){return{range:[],rangeKey:"",value:0,mode:"selector",fields:"day",start:"",end:"",disabled:!1,visible:!1}},onLoad:function(){var e=this;null===this.data?this.postMessage({event:"created"},!0):this.showPicker(this.data),this.onMessage((function(t){e.showPicker(t)}))},onReady:function(){var e=this;this.$nextTick((function(){e.visible=!0}))},methods:{showPicker:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.column;for(var n in e)"column"!==n&&("number"==typeof t?this.$set(this.$data[n],t,e[n]):this.$data[n]=e[n])},close:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=n.value,r=void 0===a?-1:a;this.visible=!1,setTimeout((function(){t.postMessage({event:e,value:r})}),210)},onClose:function(){this.close("cancel")},columnchange:function(e){var t=e.column,n=e.value;this.$set(this.value,t,n),this.postMessage({event:"columnchange",column:t,value:n},!0)}}};t.default=i},function(e,t,n){"use strict";n.r(t);var a=n(23),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var a=n(46),r=o(n(35)),i=o(n(47));function o(e){return e&&e.__esModule?e:{default:e}}function s(e){return function(e){if(Array.isArray(e))return u(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||function(e,t){if(!e)return;if("string"==typeof e)return u(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return u(e,t)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,a=new Array(t);nn(i)&&this._cloneArray(a,i)}e.forEach((function(e,n){e!==t.oldValueArray[n]&&(t.oldValueArray[n]=e,t.mode===d.MULTISELECTOR&&t.$emit("columnchange",{column:n,value:e}))}))},visible:function(e){var t=this;e?this.$nextTick((function(){f.transition(t.$refs.picker,{styles:{transform:"translateY(0)"},duration:200})})):f.transition(this.$refs.picker,{styles:{transform:"translateY(".concat(283+this.safeAreaInsets.bottom,"px)")},duration:200})}},created:function(){this._createTime(),this._createDate(),this._setValueSync()},methods:{getTexts:function(e,t){var n=this,a=this.textMaxLength;return e.map((function(e){var r=("object"==typeof e?e[n.rangeKey]||"":e)+(n.units[t]||"");if(a>0&&r.length>a)for(var i=0,o=0,s=0;s127||94===u?1:.65)<=a-1&&(o=s),i>=a)return s===r.length-1?r:r.substr(0,o+1)+"…"}return r||" "})).join("\n")},_createTime:function(){var e=[],t=[];e.splice(0,e.length);for(var n=0;n<24;n++)e.push((n<10?"0":"")+n);t.splice(0,t.length);for(var a=0;a<60;a++)t.push((a<10?"0":"")+a);this.timeArray.push(e,t)},_createDate:function(){for(var e=[],t=(new Date).getFullYear(),n=t-61,a=t+61;n<=a;n++)e.push(String(n));for(var r=[],i=1;i<=12;i++)r.push((i<10?"0":"")+i);for(var o=[],s=1;s<=31;s++)o.push((s<10?"0":"")+s);this.dateArray.push(e,r,o)},_getTimeValue:function(e){return 60*e[0]+e[1]},_getDateValue:function(e){return 366*e[0]+31*(e[1]||0)+(e[2]||0)},_cloneArray:function(e,t){for(var n=0;no?0:i)}break;case d.TIME:case d.DATE:this.valueSync=String(e);break;default:var s=Number(e);this.valueSync=s<0?0:s}},_setValueArray:function(){var e,t=this.valueSync;switch(this.mode){case d.MULTISELECTOR:e=s(t);break;case d.TIME:e=this._getDateValueArray(t,(0,a.formatDateTime)({mode:d.TIME}));break;case d.DATE:e=this._getDateValueArray(t,(0,a.formatDateTime)({mode:d.DATE}));break;default:e=[t]}this.oldValueArray=s(e),this.valueArray=s(e)},_getValue:function(){var e=this,t=this.valueArray;switch(this.mode){case d.SELECTOR:return t[0];case d.MULTISELECTOR:return t.map((function(e){return e}));case d.TIME:return this.valueArray.map((function(t,n){return e.timeArray[n][t]})).join(":");case d.DATE:return this.valueArray.map((function(t,n){return e.dateArray[n][t]})).join("-")}},_getDateValueArray:function(e,t){var n=this.mode===d.DATE?"-":":",a=this.mode===d.DATE?this.dateArray:this.timeArray,r=3;switch(this.fields){case p.YEAR:r=1;break;case p.MONTH:r=2}for(var i=String(e).split(n),o=[],s=0;s=0&&(o=t?this._getDateValueArray(t):o.map((function(){return 0}))),o},_change:function(){this.$emit("change",{value:this._getValue()})},_cancel:function(){this.$emit("cancel")}}};t.default=h},function(e,t){e.exports={content:{position:"absolute",top:0,left:0,bottom:0,right:0},"uni-mask":{position:"absolute",top:0,left:0,bottom:0,right:0,backgroundColor:"rgba(0,0,0,0.4)",opacity:0,transitionProperty:"opacity",transitionDuration:200,transitionTimingFunction:"linear"},"@TRANSITION":{"uni-mask":{property:"opacity",duration:200,timingFunction:"linear"}},"uni-mask-android":{backgroundColor:"rgba(0,0,0,0.6)"},"uni-mask-visible":{opacity:1},"uni-picker":{position:"absolute",left:0,bottom:0,right:0,backgroundColor:"#ffffff",color:"#000000",flexDirection:"column",transform:"translateY(295px)"},"uni-picker-header":{height:"45",borderBottomWidth:0,backgroundColor:"#E6E6E6",fontSize:"20"},"uni-picker-action":{position:"absolute",textAlign:"center",top:0,height:"45",paddingTop:0,paddingRight:"14",paddingBottom:0,paddingLeft:"14",fontSize:"17",lineHeight:"45"},"uni-picker-action-cancel":{left:0,color:"#888888"},"uni-picker-action-confirm":{right:0,color:"#007aff"},"uni-picker-content":{flex:1},"uni-picker-item":{lineHeight:"34",textAlign:"center",color:"#000000"}}},function(e,t){e.exports={page:{flex:1}}},,,,,function(e,t,n){"use strict";var a=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("scroll-view",{staticStyle:{flexDirection:"column"},attrs:{scrollY:!0,enableBackToTop:!0,bubble:"true"}},[n("view",{staticClass:["page"]},[n("picker",{attrs:{range:e.range,rangeKey:e.rangeKey,value:e.value,mode:e.mode,fields:e.fields,start:e.start,end:e.end,disabled:e.disabled,visible:e.visible},on:{change:function(t){e.close("change",t)},cancel:function(t){e.close("cancel",t)},columnchange:e.columnchange}})],1)])},r=[];n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return r})),n.d(t,"a",(function(){}))},,,function(e,t,n){"use strict";var a=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:["content"]},[n("div",{ref:"mask",staticClass:["uni-mask"],class:{"uni-mask-visible":e.visible,"uni-mask-android":e.android},on:{click:e._cancel}}),n("div",{ref:"picker",staticClass:["uni-picker"],class:{"uni-picker-visible":e.visible},style:"padding-bottom:"+e.safeAreaInsets.bottom+"px;height:"+(e.height+e.safeAreaInsets.bottom)+"px;"},[n("div",{staticClass:["uni-picker-header"]},[n("u-text",{staticClass:["uni-picker-action","uni-picker-action-cancel"],style:"left:"+e.safeAreaInsets.left+"px",on:{click:e._cancel}},[e._v(e._s(e.localize("cancel")))]),n("u-text",{staticClass:["uni-picker-action","uni-picker-action-confirm"],style:"right:"+e.safeAreaInsets.right+"px",on:{click:e._change}},[e._v(e._s(e.localize("ok")))])]),e.visible?n("picker-view",{staticClass:["uni-picker-content"],style:"margin-left:"+e.safeAreaInsets.left+"px",attrs:{height:"216",indicatorStyle:"height: 34px;border-color:#C8C9C9;border-top-width:0.5px;border-bottom-width:0.5px;",value:e.valueArray},on:{"update:value":function(t){e.valueArray=t}}},e._l(e.rangeArray,(function(t,a){return n("picker-view-column",{key:a,attrs:{length:t.length}},[n("u-text",{staticClass:["uni-picker-item"],style:{fontSize:e.fontSize+"px"}},[e._v(e._s(e.getTexts(t,a)))])])})),1):e._e()],1)])},r=[];n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return r})),n.d(t,"a",(function(){}))},,function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n={data:function(){return{locale:{default:"en",full:"en",primary:"en"},localization:{en:{ok:"OK",cancel:"Cancel"},zh:{ok:"完成",cancel:"取消"},"zh-hans":{},"zh-hant":{}}}},onLoad:function(){this.initLocale()},created:function(){this.initLocale()},methods:{initLocale:function(){if(!this.__initLocale){this.__initLocale=!0;var t=e.os.language.toLowerCase().replace("_","-").split("-"),n=t[1];n&&(t[1]={chs:"hans",cn:"hans",sg:"hans",cht:"hant",tw:"hant",hk:"hant",mo:"hant"}[n]||n),t.length=t.length>2?2:t.length,this.locale.full=t.join("-"),this.locale.primary=t[0]}},localize:function(e){var t=this.locale,n=this.localization;function a(e){return n[e]||{}}return a(t.full)[e]||a(t.primary)[e]||a(t.default)[e]||e}}};t.default=n}).call(this,n(2).weexPlus)},,,,function(e,t,n){"use strict";n.r(t);var a=n(24),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},function(e,t,n){"use strict";n.r(t);var a=n(25),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},,,,function(e,t,n){"use strict";n.r(t);n(3);var a=n(9);a.default.mpType="page",a.default.route="template/__uniapppicker",a.default.el="#root",new Vue(a.default)},function(e,t,n){"use strict";n.r(t);var a=n(33),r=n(22);for(var i in r)"default"!==i&&function(e){n.d(t,e,(function(){return r[e]}))}(i);var o=n(1);var s=Object(o.a)(r.default,a.b,a.c,!1,null,null,"2b83bbfe",!1,a.a,void 0);(function(e){this.options.style||(this.options.style={}),Vue.prototype.__merge_style&&Vue.prototype.__$appStyle__&&Vue.prototype.__merge_style(Vue.prototype.__$appStyle__,this.options.style),Vue.prototype.__merge_style?Vue.prototype.__merge_style(n(39).default,this.options.style):Object.assign(this.options.style,n(39).default)}).call(s),t.default=s.exports},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.formatDateTime=function(e){var t=e.date,n=void 0===t?new Date:t,r=e.mode;return"time"===(void 0===r?"date":r)?a(n.getHours())+":"+a(n.getMinutes()):n.getFullYear()+"-"+a(n.getMonth()+1)+"-"+a(n.getDate())};var a=function(e){return e>9?e:"0"+e}},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n={data:function(){return{safeAreaInsets:{left:0,right:0,top:0,bottom:0}}},onLoad:function(){this.initSafeAreaInsets()},created:function(){this.initSafeAreaInsets()},methods:{initSafeAreaInsets:function(){var t=this;if(!this.__initSafeAreaInsets){this.__initSafeAreaInsets=!0;var n=e.webview.currentWebview();n.addEventListener("resize",(function(){setTimeout((function(){t.updateSafeAreaInsets(n)}),20)})),this.updateSafeAreaInsets(n)}},updateSafeAreaInsets:function(e){var t=e.getSafeAreaInsets(),n=this.safeAreaInsets;Object.keys(n).forEach((function(e){n[e]=t[e]}))}}};t.default=n}).call(this,n(2).weexPlus)}]); \ No newline at end of file diff --git a/packages/uni-cli-shared/template/common/__uniapppicker.js b/packages/uni-cli-shared/template/common/__uniapppicker.js index ee3631e7347ce878a7d062ab9f9964f0e2c26fae..9047632c79de0c23e6b69cf03d396158803ec873 100644 --- a/packages/uni-cli-shared/template/common/__uniapppicker.js +++ b/packages/uni-cli-shared/template/common/__uniapppicker.js @@ -1 +1 @@ -!function(e){var t={};function n(a){if(t[a])return t[a].exports;var r=t[a]={i:a,l:!1,exports:{}};return e[a].call(r.exports,r,r.exports,n),r.l=!0,r.exports}n.m=e,n.c=t,n.d=function(e,t,a){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(n.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(a,r,function(t){return e[t]}.bind(null,r));return a},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=44)}([function(e,t){e.exports={}},function(e,t,n){"use strict";function a(e,t,n,a,r,i,o,s,u,c){var l,f="function"==typeof e?e.options:e;if(u){f.components||(f.components={});var d=Object.prototype.hasOwnProperty;for(var p in u)d.call(u,p)&&!d.call(f.components,p)&&(f.components[p]=u[p])}if(c&&((c.beforeCreate||(c.beforeCreate=[])).unshift((function(){this[c.__module]=this})),(f.mixins||(f.mixins=[])).push(c)),t&&(f.render=t,f.staticRenderFns=n,f._compiled=!0),a&&(f.functional=!0),i&&(f._scopeId="data-v-"+i),o?(l=function(e){(e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),r&&r.call(this,e),e&&e._registeredComponents&&e._registeredComponents.add(o)},f._ssrRegister=l):r&&(l=s?function(){r.call(this,this.$root.$options.shadowRoot)}:r),l)if(f.functional){f._injectStyles=l;var h=f.render;f.render=function(e,t){return l.call(t),h(e,t)}}else{var v=f.beforeCreate;f.beforeCreate=v?[].concat(v,l):[l]}return{exports:e,options:f}}n.d(t,"a",(function(){return a}))},function(e,t,n){"use strict";var a;Object.defineProperty(t,"__esModule",{value:!0}),t.weexPlus=t.default=void 0,a="function"==typeof getUni?getUni:function(){var e=function(e){return"function"==typeof e},t=function(e){return e.then((function(e){return[null,e]})).catch((function(e){return[e]}))},n=/^\$|^on|^create|Sync$|Manager$|^pause/,a=["os","getCurrentSubNVue","getSubNVueById","stopRecord","stopVoice","stopBackgroundAudio","stopPullDownRefresh","hideKeyboard","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","canIUse","navigateBack","closeSocket","pageScrollTo","drawCanvas"],i=function(e){return(!n.test(e)||"createBLEConnection"===e)&&!~a.indexOf(e)},o=function(n){return function(){for(var a=arguments.length,r=Array(a>1?a-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:{};return e(o.success)||e(o.fail)||e(o.complete)?n.apply(void 0,[o].concat(r)):t(new Promise((function(e,t){n.apply(void 0,[Object.assign({},o,{success:e,fail:t})].concat(r)),Promise.prototype.finally=function(e){var t=this.constructor;return this.then((function(n){return t.resolve(e()).then((function(){return n}))}),(function(n){return t.resolve(e()).then((function(){throw n}))}))}})))}},s=[],u=void 0;function c(e){s.forEach((function(t){return t({origin:u,data:e})}))}var l=r.webview.currentWebview().id,f=new BroadcastChannel("UNI-APP-SUBNVUE");function d(e){var t=r.webview.getWebviewById(e);return t&&!t.$processed&&function(e){e.$processed=!0;var t=r.webview.currentWebview().id===e.id,n="uniNView"===e.__uniapp_origin_type&&e.__uniapp_origin_id,a=e.id;if(e.postMessage=function(e){n?f.postMessage({data:e,to:t?n:a}):_({type:"UniAppSubNVue",data:e})},e.onMessage=function(e){s.push(e)},e.__uniapp_mask_id){u=e.__uniapp_host;var i=e.__uniapp_mask,o=r.webview.getWebviewById(e.__uniapp_mask_id);o=o.parent()||o;var c=e.show,l=e.hide,d=e.close,p=function(){o.setStyle({mask:i})},h=function(){o.setStyle({mask:"none"})};e.show=function(){p();for(var t=arguments.length,n=Array(t),a=0;a1&&void 0!==arguments[1]?arguments[1]:"GET",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"application/x-www-form-urlencoded";return"object"===(void 0===e?"undefined":L(e))?"POST"===t.toUpperCase()&&"application/json"===n.toLowerCase()?JSON.stringify(e):Object.keys(e).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(e[t])})).join("&"):e},D=weex.requireModule("plusstorage"),j=weex.requireModule("clipboard"),B=function(){if("function"==typeof getUniEmitter)return getUniEmitter;var e={$on:function(){console.warn("uni.$on failed")},$off:function(){console.warn("uni.$off failed")},$once:function(){console.warn("uni.$once failed")},$emit:function(){console.warn("uni.$emit failed")}};return function(){return e}}();function R(e,t,n){return e[t].apply(e,n)}var U=Object.freeze({loadFontFace:function(t){var n=t.family,a=t.source,r=(t.desc,t.success),i=(t.fail,t.complete);I.addRule("fontFace",{fontFamily:n,src:a.replace(/"/g,"'")});var o={errMsg:"loadFontFace:ok",status:"loaded"};e(r)&&r(o),e(i)&&i(o)},ready:V,request:function(t){var n=t.url,a=t.data,r=t.header,i=t.method,o=void 0===i?"GET":i,s=t.dataType,u=void 0===s?"json":s,c=(t.responseType,t.success),l=t.fail,f=t.complete,d=!1,p=!1,h={};if(r)for(var v in r)p||"content-type"!==v.toLowerCase()?h[v]=r[v]:(p=!0,h["Content-Type"]=r[v]);return"GET"===o&&a&&(n=n+(~n.indexOf("?")?"&"===n.substr(-1)||"?"===n.substr(-1)?"":"&":"?")+$(a)),P.fetch({url:n,method:o,headers:h,type:"json"===u?"json":"text",body:"GET"!==o?$(a,o,h["Content-Type"]):""},(function(t){var n=t.status,a=(t.ok,t.statusText,t.data),r=t.headers,i={};!n||-1===n||d?(i.errMsg="request:fail",e(l)&&l(i)):(i.data=a,i.statusCode=n,i.header=r,e(c)&&c(i)),e(f)&&f(i)})),{abort:function(){d=!0}}},getStorage:function(t){var n=t.key,a=(t.data,t.success),r=t.fail,i=t.complete;D.getItem(n+"__TYPE",(function(t){if("success"===t.result){var o=t.data;D.getItem(n,(function(t){if("success"===t.result){var n=t.data;o&&n?("String"!==o&&(n=JSON.parse(n)),e(a)&&a({errMsg:"getStorage:ok",data:n})):(t.errMsg="setStorage:fail",e(r)&&r(t))}else t.errMsg="setStorage:fail",e(r)&&r(t);e(i)&&i(t)}))}else t.errMsg="setStorage:fail",e(r)&&r(t),e(i)&&i(t)}))},setStorage:function(t){var n=t.key,a=t.data,r=t.success,i=t.fail,o=t.complete,s="String";"object"===(void 0===a?"undefined":L(a))&&(s="Object",a=JSON.stringify(a)),D.setItem(n,a,(function(t){"success"===t.result?D.setItem(n+"__TYPE",s,(function(t){"success"===t.result?e(r)&&r({errMsg:"setStorage:ok"}):(t.errMsg="setStorage:fail",e(i)&&i(t))})):(t.errMsg="setStorage:fail",e(i)&&i(t)),e(o)&&o(t)}))},removeStorage:function(t){var n=t.key,a=(t.data,t.success),r=t.fail,i=t.complete;D.removeItem(n,(function(t){"success"===t.result?e(a)&&a({errMsg:"removeStorage:ok"}):(t.errMsg="removeStorage:fail",e(r)&&r(t)),e(i)&&i(t)})),D.removeItem(n+"__TYPE")},clearStorage:function(e){e.key,e.data,e.success,e.fail,e.complete},getClipboardData:function(t){var n=t.success,a=(t.fail,t.complete);j.getString((function(t){var r={errMsg:"getClipboardData:ok",data:t.data};e(n)&&n(r),e(a)&&a(r)}))},setClipboardData:function(t){var n=t.data,a=t.success,r=(t.fail,t.complete),i={errMsg:"setClipboardData:ok"};j.setString(n),e(a)&&a(i),e(r)&&r(i)},onSubNVueMessage:c,getSubNVueById:d,getCurrentSubNVue:function(){return d(r.webview.currentWebview().id)},$on:function(){return R(B(),"$on",[].concat(Array.prototype.slice.call(arguments)))},$off:function(){return R(B(),"$off",[].concat(Array.prototype.slice.call(arguments)))},$once:function(){return R(B(),"$once",[].concat(Array.prototype.slice.call(arguments)))},$emit:function(){return R(B(),"$emit",[].concat(Array.prototype.slice.call(arguments)))}}),z={os:{nvue:!0}},F={};return"undefined"!=typeof Proxy?F=new Proxy({},{get:function(e,t){if("os"===t)return{nvue:!0};if("postMessage"===t)return _;if("requireNativePlugin"===t)return C;if("onNavigationBarButtonTap"===t)return k;if("onNavigationBarSearchInputChanged"===t)return M;if("onNavigationBarSearchInputConfirmed"===t)return E;if("onNavigationBarSearchInputClicked"===t)return x;var n=U[t];return n||(n=b(t)),i(t)?o(n):n}}):(Object.keys(z).forEach((function(e){F[e]=z[e]})),F.postMessage=_,F.requireNativePlugin=C,F.onNavigationBarButtonTap=k,F.onNavigationBarSearchInputChanged=M,F.onNavigationBarSearchInputConfirmed=E,F.onNavigationBarSearchInputClicked=x,Object.keys({uploadFile:!0,downloadFile:!0,chooseImage:!0,previewImage:!0,getImageInfo:!0,saveImageToPhotosAlbum:!0,chooseVideo:!0,saveVideoToPhotosAlbum:!0,saveFile:!0,getSavedFileList:!0,getSavedFileInfo:!0,removeSavedFile:!0,openDocument:!0,setStorage:!0,getStorage:!0,getStorageInfo:!0,removeStorage:!0,clearStorage:!0,getLocation:!0,chooseLocation:!0,openLocation:!0,getSystemInfo:!0,getNetworkType:!0,makePhoneCall:!0,scanCode:!0,setScreenBrightness:!0,getScreenBrightness:!0,setKeepScreenOn:!0,vibrateLong:!0,vibrateShort:!0,addPhoneContact:!0,showToast:!0,showLoading:!0,hideToast:!0,hideLoading:!0,showModal:!0,showActionSheet:!0,setNavigationBarTitle:!0,setNavigationBarColor:!0,navigateTo:!0,redirectTo:!0,reLaunch:!0,switchTab:!0,navigateBack:!0,getProvider:!0,login:!0,getUserInfo:!0,share:!0,requestPayment:!0,subscribePush:!0,unsubscribePush:!0,onPush:!0,offPush:!0}).forEach((function(e){var t=U[e];t||(t=b(e)),i(e)?F[e]=o(t):F[e]=t}))),F};var r=new WeexPlus(weex);t.weexPlus=r;var i=a(weex,r,BroadcastChannel);t.default=i},function(e,t,n){Vue.prototype.__$appStyle__={},Vue.prototype.__merge_style&&Vue.prototype.__merge_style(n(4).default,Vue.prototype.__$appStyle__)},function(e,t,n){"use strict";n.r(t);var a=n(0),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n={onLoad:function(){this.initMessage()},methods:{initMessage:function(){var t=this,n=e.webview.currentWebview().extras||{},a=n.from,r=(n.callback,n.runtime),i=n.data,o=void 0===i?{}:i,s=n.useGlobalEvent;this.__from=a,this.__runtime=r,this.__page=e.webview.currentWebview().id,this.__useGlobalEvent=s,this.data=JSON.parse(JSON.stringify(o)),e.key.addEventListener("backbutton",(function(){"function"==typeof t.onClose?t.onClose():e.webview.currentWebview().close("auto")}));var u=this,c=function(e){var t=e.data&&e.data.__message;t&&u.__onMessageCallback&&u.__onMessageCallback(t.data)};this.__useGlobalEvent?weex.requireModule("globalEvent").addEventListener("plusMessage",c):new BroadcastChannel(this.__page).onmessage=c},postMessage:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]&&arguments[1],a=JSON.parse(JSON.stringify({__message:{__page:this.__page,data:t,keep:n}})),r=this.__from;if("v8"===this.__runtime)if(this.__useGlobalEvent)e.webview.postMessageToUniNView(a,r);else{var i=new BroadcastChannel(r);i.postMessage(a)}else{var o=e.webview.getWebviewById(r);o&&o.evalJS("__plusMessage&&__plusMessage(".concat(JSON.stringify({data:a}),")"))}},onMessage:function(e){this.__onMessageCallback=e}}};t.default=n}).call(this,n(2).weexPlus)},,,,function(e,t,n){"use strict";var a=n(30),r=n(20),i=n(1);var o=Object(i.a)(r.default,a.b,a.c,!1,null,null,"2f5c0238",!1,a.a,void 0);(function(e){this.options.style||(this.options.style={}),Vue.prototype.__merge_style&&Vue.prototype.__$appStyle__&&Vue.prototype.__merge_style(Vue.prototype.__$appStyle__,this.options.style),Vue.prototype.__merge_style?Vue.prototype.__merge_style(n(40).default,this.options.style):Object.assign(this.options.style,n(40).default)}).call(o),t.default=o.exports},,,,,,,,,,,function(e,t,n){"use strict";var a=n(21),r=n.n(a);t.default=r.a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var a=r(n(45));function r(e){return e&&e.__esModule?e:{default:e}}var i={mixins:[r(n(5)).default],components:{picker:a.default},data:function(){return{range:[],rangeKey:"",value:0,mode:"selector",fields:"day",start:"",end:"",disabled:!1,visible:!1}},onLoad:function(){var e=this;null===this.data?this.postMessage({event:"created"},!0):this.showPicker(this.data),this.onMessage((function(t){e.showPicker(t)}))},onReady:function(){var e=this;this.$nextTick((function(){e.visible=!0}))},methods:{showPicker:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.column;for(var n in e)"column"!==n&&("number"==typeof t?this.$set(this.$data[n],t,e[n]):this.$data[n]=e[n])},close:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=n.value,r=void 0===a?-1:a;this.visible=!1,setTimeout((function(){t.postMessage({event:e,value:r})}),210)},onClose:function(){this.close("cancel")},columnchange:function(e){var t=e.column,n=e.value;this.$set(this.value,t,n),this.postMessage({event:"columnchange",column:t,value:n},!0)}}};t.default=i},function(e,t,n){"use strict";n.r(t);var a=n(23),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var a=n(46),r=o(n(35)),i=o(n(47));function o(e){return e&&e.__esModule?e:{default:e}}function s(e){return function(e){if(Array.isArray(e))return u(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||function(e,t){if(!e)return;if("string"==typeof e)return u(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return u(e,t)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,a=new Array(t);nn(i)&&this._cloneArray(a,i)}e.forEach((function(e,n){e!==t.oldValueArray[n]&&(t.oldValueArray[n]=e,t.mode===d.MULTISELECTOR&&t.$emit("columnchange",{column:n,value:e}))}))},visible:function(e){var t=this;e?this.$nextTick((function(){f.transition(t.$refs.picker,{styles:{transform:"translateY(0)"},duration:200})})):f.transition(this.$refs.picker,{styles:{transform:"translateY(".concat(283+this.safeAreaInsets.bottom,"px)")},duration:200})}},created:function(){this._createTime(),this._createDate(),this._setValueSync()},methods:{getTexts:function(e,t){var n=this,a=this.textMaxLength;return e.map((function(e){var r=("object"==typeof e?e[n.rangeKey]||"":e)+(n.units[t]||"");if(a>0&&r.length>a)for(var i=0,o=0,s=0;s127||94===u?1:.65)<=a-1&&(o=s),i>=a)return s===r.length-1?r:r.substr(0,o+1)+"…"}return r||" "})).join("\n")},_createTime:function(){var e=[],t=[];e.splice(0,e.length);for(var n=0;n<24;n++)e.push((n<10?"0":"")+n);t.splice(0,t.length);for(var a=0;a<60;a++)t.push((a<10?"0":"")+a);this.timeArray.push(e,t)},_createDate:function(){for(var e=[],t=(new Date).getFullYear(),n=t-61,a=t+61;n<=a;n++)e.push(String(n));for(var r=[],i=1;i<=12;i++)r.push((i<10?"0":"")+i);for(var o=[],s=1;s<=31;s++)o.push((s<10?"0":"")+s);this.dateArray.push(e,r,o)},_getTimeValue:function(e){return 60*e[0]+e[1]},_getDateValue:function(e){return 366*e[0]+31*(e[1]||0)+(e[2]||0)},_cloneArray:function(e,t){for(var n=0;no?0:i)}break;case d.TIME:case d.DATE:this.valueSync=String(e);break;default:this.valueSync=Number(e)||0}},_setValueArray:function(){var e,t=this.valueSync;switch(this.mode){case d.MULTISELECTOR:e=s(t);break;case d.TIME:e=this._getDateValueArray(t,(0,a.formatDateTime)({mode:d.TIME}));break;case d.DATE:e=this._getDateValueArray(t,(0,a.formatDateTime)({mode:d.DATE}));break;default:e=[t]}this.oldValueArray=s(e),this.valueArray=s(e)},_getValue:function(){var e=this,t=this.valueArray;switch(this.mode){case d.SELECTOR:return t[0];case d.MULTISELECTOR:return t.map((function(e){return e}));case d.TIME:return this.valueArray.map((function(t,n){return e.timeArray[n][t]})).join(":");case d.DATE:return this.valueArray.map((function(t,n){return e.dateArray[n][t]})).join("-")}},_getDateValueArray:function(e,t){var n=this.mode===d.DATE?"-":":",a=this.mode===d.DATE?this.dateArray:this.timeArray,r=3;switch(this.fields){case p.YEAR:r=1;break;case p.MONTH:r=2}for(var i=String(e).split(n),o=[],s=0;s=0&&(o=t?this._getDateValueArray(t):o.map((function(){return 0}))),o},_change:function(){this.$emit("change",{value:this._getValue()})},_cancel:function(){this.$emit("cancel")}}};t.default=h},function(e,t){e.exports={content:{position:"absolute",top:0,left:0,bottom:0,right:0},"uni-mask":{position:"absolute",top:0,left:0,bottom:0,right:0,backgroundColor:"rgba(0,0,0,0.4)",opacity:0,transitionProperty:"opacity",transitionDuration:200,transitionTimingFunction:"linear"},"@TRANSITION":{"uni-mask":{property:"opacity",duration:200,timingFunction:"linear"}},"uni-mask-android":{backgroundColor:"rgba(0,0,0,0.6)"},"uni-mask-visible":{opacity:1},"uni-picker":{position:"absolute",left:0,bottom:0,right:0,backgroundColor:"#ffffff",color:"#000000",flexDirection:"column",transform:"translateY(295px)"},"uni-picker-header":{height:"45",borderBottomWidth:0,backgroundColor:"#E6E6E6",fontSize:"20"},"uni-picker-action":{position:"absolute",textAlign:"center",top:0,height:"45",paddingTop:0,paddingRight:"14",paddingBottom:0,paddingLeft:"14",fontSize:"17",lineHeight:"45"},"uni-picker-action-cancel":{left:0,color:"#888888"},"uni-picker-action-confirm":{right:0,color:"#007aff"},"uni-picker-content":{flex:1},"uni-picker-item":{lineHeight:"34",textAlign:"center",color:"#000000"}}},function(e,t){e.exports={page:{flex:1}}},,,,,function(e,t,n){"use strict";var a=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("scroll-view",{staticStyle:{flexDirection:"column"},attrs:{scrollY:!0,enableBackToTop:!0,bubble:"true"}},[n("view",{staticClass:["page"]},[n("picker",{attrs:{range:e.range,rangeKey:e.rangeKey,value:e.value,mode:e.mode,fields:e.fields,start:e.start,end:e.end,disabled:e.disabled,visible:e.visible},on:{change:function(t){e.close("change",t)},cancel:function(t){e.close("cancel",t)},columnchange:e.columnchange}})],1)])},r=[];n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return r})),n.d(t,"a",(function(){}))},,,function(e,t,n){"use strict";var a=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:["content"]},[n("div",{ref:"mask",staticClass:["uni-mask"],class:{"uni-mask-visible":e.visible,"uni-mask-android":e.android},on:{click:e._cancel}}),n("div",{ref:"picker",staticClass:["uni-picker"],class:{"uni-picker-visible":e.visible},style:"padding-bottom:"+e.safeAreaInsets.bottom+"px;height:"+(e.height+e.safeAreaInsets.bottom)+"px;"},[n("div",{staticClass:["uni-picker-header"]},[n("u-text",{staticClass:["uni-picker-action","uni-picker-action-cancel"],style:"left:"+e.safeAreaInsets.left+"px",on:{click:e._cancel}},[e._v(e._s(e.localize("cancel")))]),n("u-text",{staticClass:["uni-picker-action","uni-picker-action-confirm"],style:"right:"+e.safeAreaInsets.right+"px",on:{click:e._change}},[e._v(e._s(e.localize("ok")))])]),e.visible?n("picker-view",{staticClass:["uni-picker-content"],style:"margin-left:"+e.safeAreaInsets.left+"px",attrs:{height:"216",indicatorStyle:"height: 34px;border-color:#C8C9C9;border-top-width:0.5px;border-bottom-width:0.5px;",value:e.valueArray},on:{"update:value":function(t){e.valueArray=t}}},e._l(e.rangeArray,(function(t,a){return n("picker-view-column",{key:a,attrs:{length:t.length}},[n("u-text",{staticClass:["uni-picker-item"],style:{fontSize:e.fontSize+"px"}},[e._v(e._s(e.getTexts(t,a)))])])})),1):e._e()],1)])},r=[];n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return r})),n.d(t,"a",(function(){}))},,function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n={data:function(){return{locale:{default:"en",full:"en",primary:"en"},localization:{en:{ok:"OK",cancel:"Cancel"},zh:{ok:"完成",cancel:"取消"},"zh-hans":{},"zh-hant":{}}}},onLoad:function(){this.initLocale()},created:function(){this.initLocale()},methods:{initLocale:function(){if(!this.__initLocale){this.__initLocale=!0;var t=e.os.language.toLowerCase().replace("_","-").split("-"),n=t[1];n&&(t[1]={chs:"hans",cn:"hans",sg:"hans",cht:"hant",tw:"hant",hk:"hant",mo:"hant"}[n]||n),t.length=t.length>2?2:t.length,this.locale.full=t.join("-"),this.locale.primary=t[0]}},localize:function(e){var t=this.locale,n=this.localization;function a(e){return n[e]||{}}return a(t.full)[e]||a(t.primary)[e]||a(t.default)[e]||e}}};t.default=n}).call(this,n(2).weexPlus)},,,,function(e,t,n){"use strict";n.r(t);var a=n(24),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},function(e,t,n){"use strict";n.r(t);var a=n(25),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},,,,function(e,t,n){"use strict";n.r(t);n(3);var a=n(9);a.default.mpType="page",a.default.route="template/__uniapppicker",a.default.el="#root",new Vue(a.default)},function(e,t,n){"use strict";n.r(t);var a=n(33),r=n(22);for(var i in r)"default"!==i&&function(e){n.d(t,e,(function(){return r[e]}))}(i);var o=n(1);var s=Object(o.a)(r.default,a.b,a.c,!1,null,null,"2b83bbfe",!1,a.a,void 0);(function(e){this.options.style||(this.options.style={}),Vue.prototype.__merge_style&&Vue.prototype.__$appStyle__&&Vue.prototype.__merge_style(Vue.prototype.__$appStyle__,this.options.style),Vue.prototype.__merge_style?Vue.prototype.__merge_style(n(39).default,this.options.style):Object.assign(this.options.style,n(39).default)}).call(s),t.default=s.exports},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.formatDateTime=function(e){var t=e.date,n=void 0===t?new Date:t,r=e.mode;return"time"===(void 0===r?"date":r)?a(n.getHours())+":"+a(n.getMinutes()):n.getFullYear()+"-"+a(n.getMonth()+1)+"-"+a(n.getDate())};var a=function(e){return e>9?e:"0"+e}},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n={data:function(){return{safeAreaInsets:{left:0,right:0,top:0,bottom:0}}},onLoad:function(){this.initSafeAreaInsets()},created:function(){this.initSafeAreaInsets()},methods:{initSafeAreaInsets:function(){var t=this;if(!this.__initSafeAreaInsets){this.__initSafeAreaInsets=!0;var n=e.webview.currentWebview();n.addEventListener("resize",(function(){setTimeout((function(){t.updateSafeAreaInsets(n)}),20)})),this.updateSafeAreaInsets(n)}},updateSafeAreaInsets:function(e){var t=e.getSafeAreaInsets(),n=this.safeAreaInsets;Object.keys(n).forEach((function(e){n[e]=t[e]}))}}};t.default=n}).call(this,n(2).weexPlus)}]); \ No newline at end of file +!function(e){var t={};function n(a){if(t[a])return t[a].exports;var r=t[a]={i:a,l:!1,exports:{}};return e[a].call(r.exports,r,r.exports,n),r.l=!0,r.exports}n.m=e,n.c=t,n.d=function(e,t,a){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(n.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(a,r,function(t){return e[t]}.bind(null,r));return a},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=44)}([function(e,t){e.exports={}},function(e,t,n){"use strict";function a(e,t,n,a,r,i,o,s,u,c){var l,f="function"==typeof e?e.options:e;if(u){f.components||(f.components={});var d=Object.prototype.hasOwnProperty;for(var p in u)d.call(u,p)&&!d.call(f.components,p)&&(f.components[p]=u[p])}if(c&&((c.beforeCreate||(c.beforeCreate=[])).unshift((function(){this[c.__module]=this})),(f.mixins||(f.mixins=[])).push(c)),t&&(f.render=t,f.staticRenderFns=n,f._compiled=!0),a&&(f.functional=!0),i&&(f._scopeId="data-v-"+i),o?(l=function(e){(e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),r&&r.call(this,e),e&&e._registeredComponents&&e._registeredComponents.add(o)},f._ssrRegister=l):r&&(l=s?function(){r.call(this,this.$root.$options.shadowRoot)}:r),l)if(f.functional){f._injectStyles=l;var h=f.render;f.render=function(e,t){return l.call(t),h(e,t)}}else{var v=f.beforeCreate;f.beforeCreate=v?[].concat(v,l):[l]}return{exports:e,options:f}}n.d(t,"a",(function(){return a}))},function(e,t,n){"use strict";var a;Object.defineProperty(t,"__esModule",{value:!0}),t.weexPlus=t.default=void 0,a="function"==typeof getUni?getUni:function(){var e=function(e){return"function"==typeof e},t=function(e){return e.then((function(e){return[null,e]})).catch((function(e){return[e]}))},n=/^\$|^on|^create|Sync$|Manager$|^pause/,a=["os","getCurrentSubNVue","getSubNVueById","stopRecord","stopVoice","stopBackgroundAudio","stopPullDownRefresh","hideKeyboard","hideToast","hideLoading","showNavigationBarLoading","hideNavigationBarLoading","canIUse","navigateBack","closeSocket","pageScrollTo","drawCanvas"],i=function(e){return(!n.test(e)||"createBLEConnection"===e)&&!~a.indexOf(e)},o=function(n){return function(){for(var a=arguments.length,r=Array(a>1?a-1:0),i=1;i0&&void 0!==arguments[0]?arguments[0]:{};return e(o.success)||e(o.fail)||e(o.complete)?n.apply(void 0,[o].concat(r)):t(new Promise((function(e,t){n.apply(void 0,[Object.assign({},o,{success:e,fail:t})].concat(r)),Promise.prototype.finally=function(e){var t=this.constructor;return this.then((function(n){return t.resolve(e()).then((function(){return n}))}),(function(n){return t.resolve(e()).then((function(){throw n}))}))}})))}},s=[],u=void 0;function c(e){s.forEach((function(t){return t({origin:u,data:e})}))}var l=r.webview.currentWebview().id,f=new BroadcastChannel("UNI-APP-SUBNVUE");function d(e){var t=r.webview.getWebviewById(e);return t&&!t.$processed&&function(e){e.$processed=!0;var t=r.webview.currentWebview().id===e.id,n="uniNView"===e.__uniapp_origin_type&&e.__uniapp_origin_id,a=e.id;if(e.postMessage=function(e){n?f.postMessage({data:e,to:t?n:a}):_({type:"UniAppSubNVue",data:e})},e.onMessage=function(e){s.push(e)},e.__uniapp_mask_id){u=e.__uniapp_host;var i=e.__uniapp_mask,o=r.webview.getWebviewById(e.__uniapp_mask_id);o=o.parent()||o;var c=e.show,l=e.hide,d=e.close,p=function(){o.setStyle({mask:i})},h=function(){o.setStyle({mask:"none"})};e.show=function(){p();for(var t=arguments.length,n=Array(t),a=0;a1&&void 0!==arguments[1]?arguments[1]:"GET",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"application/x-www-form-urlencoded";return"object"===(void 0===e?"undefined":L(e))?"POST"===t.toUpperCase()&&"application/json"===n.toLowerCase()?JSON.stringify(e):Object.keys(e).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(e[t])})).join("&"):e},D=weex.requireModule("plusstorage"),j=weex.requireModule("clipboard"),B=function(){if("function"==typeof getUniEmitter)return getUniEmitter;var e={$on:function(){console.warn("uni.$on failed")},$off:function(){console.warn("uni.$off failed")},$once:function(){console.warn("uni.$once failed")},$emit:function(){console.warn("uni.$emit failed")}};return function(){return e}}();function R(e,t,n){return e[t].apply(e,n)}var U=Object.freeze({loadFontFace:function(t){var n=t.family,a=t.source,r=(t.desc,t.success),i=(t.fail,t.complete);I.addRule("fontFace",{fontFamily:n,src:a.replace(/"/g,"'")});var o={errMsg:"loadFontFace:ok",status:"loaded"};e(r)&&r(o),e(i)&&i(o)},ready:V,request:function(t){var n=t.url,a=t.data,r=t.header,i=t.method,o=void 0===i?"GET":i,s=t.dataType,u=void 0===s?"json":s,c=(t.responseType,t.success),l=t.fail,f=t.complete,d=!1,p=!1,h={};if(r)for(var v in r)p||"content-type"!==v.toLowerCase()?h[v]=r[v]:(p=!0,h["Content-Type"]=r[v]);return"GET"===o&&a&&(n=n+(~n.indexOf("?")?"&"===n.substr(-1)||"?"===n.substr(-1)?"":"&":"?")+$(a)),P.fetch({url:n,method:o,headers:h,type:"json"===u?"json":"text",body:"GET"!==o?$(a,o,h["Content-Type"]):""},(function(t){var n=t.status,a=(t.ok,t.statusText,t.data),r=t.headers,i={};!n||-1===n||d?(i.errMsg="request:fail",e(l)&&l(i)):(i.data=a,i.statusCode=n,i.header=r,e(c)&&c(i)),e(f)&&f(i)})),{abort:function(){d=!0}}},getStorage:function(t){var n=t.key,a=(t.data,t.success),r=t.fail,i=t.complete;D.getItem(n+"__TYPE",(function(t){if("success"===t.result){var o=t.data;D.getItem(n,(function(t){if("success"===t.result){var n=t.data;o&&n?("String"!==o&&(n=JSON.parse(n)),e(a)&&a({errMsg:"getStorage:ok",data:n})):(t.errMsg="setStorage:fail",e(r)&&r(t))}else t.errMsg="setStorage:fail",e(r)&&r(t);e(i)&&i(t)}))}else t.errMsg="setStorage:fail",e(r)&&r(t),e(i)&&i(t)}))},setStorage:function(t){var n=t.key,a=t.data,r=t.success,i=t.fail,o=t.complete,s="String";"object"===(void 0===a?"undefined":L(a))&&(s="Object",a=JSON.stringify(a)),D.setItem(n,a,(function(t){"success"===t.result?D.setItem(n+"__TYPE",s,(function(t){"success"===t.result?e(r)&&r({errMsg:"setStorage:ok"}):(t.errMsg="setStorage:fail",e(i)&&i(t))})):(t.errMsg="setStorage:fail",e(i)&&i(t)),e(o)&&o(t)}))},removeStorage:function(t){var n=t.key,a=(t.data,t.success),r=t.fail,i=t.complete;D.removeItem(n,(function(t){"success"===t.result?e(a)&&a({errMsg:"removeStorage:ok"}):(t.errMsg="removeStorage:fail",e(r)&&r(t)),e(i)&&i(t)})),D.removeItem(n+"__TYPE")},clearStorage:function(e){e.key,e.data,e.success,e.fail,e.complete},getClipboardData:function(t){var n=t.success,a=(t.fail,t.complete);j.getString((function(t){var r={errMsg:"getClipboardData:ok",data:t.data};e(n)&&n(r),e(a)&&a(r)}))},setClipboardData:function(t){var n=t.data,a=t.success,r=(t.fail,t.complete),i={errMsg:"setClipboardData:ok"};j.setString(n),e(a)&&a(i),e(r)&&r(i)},onSubNVueMessage:c,getSubNVueById:d,getCurrentSubNVue:function(){return d(r.webview.currentWebview().id)},$on:function(){return R(B(),"$on",[].concat(Array.prototype.slice.call(arguments)))},$off:function(){return R(B(),"$off",[].concat(Array.prototype.slice.call(arguments)))},$once:function(){return R(B(),"$once",[].concat(Array.prototype.slice.call(arguments)))},$emit:function(){return R(B(),"$emit",[].concat(Array.prototype.slice.call(arguments)))}}),z={os:{nvue:!0}},F={};return"undefined"!=typeof Proxy?F=new Proxy({},{get:function(e,t){if("os"===t)return{nvue:!0};if("postMessage"===t)return _;if("requireNativePlugin"===t)return C;if("onNavigationBarButtonTap"===t)return k;if("onNavigationBarSearchInputChanged"===t)return M;if("onNavigationBarSearchInputConfirmed"===t)return E;if("onNavigationBarSearchInputClicked"===t)return x;var n=U[t];return n||(n=b(t)),i(t)?o(n):n}}):(Object.keys(z).forEach((function(e){F[e]=z[e]})),F.postMessage=_,F.requireNativePlugin=C,F.onNavigationBarButtonTap=k,F.onNavigationBarSearchInputChanged=M,F.onNavigationBarSearchInputConfirmed=E,F.onNavigationBarSearchInputClicked=x,Object.keys({uploadFile:!0,downloadFile:!0,chooseImage:!0,previewImage:!0,getImageInfo:!0,saveImageToPhotosAlbum:!0,chooseVideo:!0,saveVideoToPhotosAlbum:!0,saveFile:!0,getSavedFileList:!0,getSavedFileInfo:!0,removeSavedFile:!0,openDocument:!0,setStorage:!0,getStorage:!0,getStorageInfo:!0,removeStorage:!0,clearStorage:!0,getLocation:!0,chooseLocation:!0,openLocation:!0,getSystemInfo:!0,getNetworkType:!0,makePhoneCall:!0,scanCode:!0,setScreenBrightness:!0,getScreenBrightness:!0,setKeepScreenOn:!0,vibrateLong:!0,vibrateShort:!0,addPhoneContact:!0,showToast:!0,showLoading:!0,hideToast:!0,hideLoading:!0,showModal:!0,showActionSheet:!0,setNavigationBarTitle:!0,setNavigationBarColor:!0,navigateTo:!0,redirectTo:!0,reLaunch:!0,switchTab:!0,navigateBack:!0,getProvider:!0,login:!0,getUserInfo:!0,share:!0,requestPayment:!0,subscribePush:!0,unsubscribePush:!0,onPush:!0,offPush:!0}).forEach((function(e){var t=U[e];t||(t=b(e)),i(e)?F[e]=o(t):F[e]=t}))),F};var r=new WeexPlus(weex);t.weexPlus=r;var i=a(weex,r,BroadcastChannel);t.default=i},function(e,t,n){Vue.prototype.__$appStyle__={},Vue.prototype.__merge_style&&Vue.prototype.__merge_style(n(4).default,Vue.prototype.__$appStyle__)},function(e,t,n){"use strict";n.r(t);var a=n(0),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n={onLoad:function(){this.initMessage()},methods:{initMessage:function(){var t=this,n=e.webview.currentWebview().extras||{},a=n.from,r=(n.callback,n.runtime),i=n.data,o=void 0===i?{}:i,s=n.useGlobalEvent;this.__from=a,this.__runtime=r,this.__page=e.webview.currentWebview().id,this.__useGlobalEvent=s,this.data=JSON.parse(JSON.stringify(o)),e.key.addEventListener("backbutton",(function(){"function"==typeof t.onClose?t.onClose():e.webview.currentWebview().close("auto")}));var u=this,c=function(e){var t=e.data&&e.data.__message;t&&u.__onMessageCallback&&u.__onMessageCallback(t.data)};this.__useGlobalEvent?weex.requireModule("globalEvent").addEventListener("plusMessage",c):new BroadcastChannel(this.__page).onmessage=c},postMessage:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]&&arguments[1],a=JSON.parse(JSON.stringify({__message:{__page:this.__page,data:t,keep:n}})),r=this.__from;if("v8"===this.__runtime)if(this.__useGlobalEvent)e.webview.postMessageToUniNView(a,r);else{var i=new BroadcastChannel(r);i.postMessage(a)}else{var o=e.webview.getWebviewById(r);o&&o.evalJS("__plusMessage&&__plusMessage(".concat(JSON.stringify({data:a}),")"))}},onMessage:function(e){this.__onMessageCallback=e}}};t.default=n}).call(this,n(2).weexPlus)},,,,function(e,t,n){"use strict";var a=n(30),r=n(20),i=n(1);var o=Object(i.a)(r.default,a.b,a.c,!1,null,null,"2f5c0238",!1,a.a,void 0);(function(e){this.options.style||(this.options.style={}),Vue.prototype.__merge_style&&Vue.prototype.__$appStyle__&&Vue.prototype.__merge_style(Vue.prototype.__$appStyle__,this.options.style),Vue.prototype.__merge_style?Vue.prototype.__merge_style(n(40).default,this.options.style):Object.assign(this.options.style,n(40).default)}).call(o),t.default=o.exports},,,,,,,,,,,function(e,t,n){"use strict";var a=n(21),r=n.n(a);t.default=r.a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var a=r(n(45));function r(e){return e&&e.__esModule?e:{default:e}}var i={mixins:[r(n(5)).default],components:{picker:a.default},data:function(){return{range:[],rangeKey:"",value:0,mode:"selector",fields:"day",start:"",end:"",disabled:!1,visible:!1}},onLoad:function(){var e=this;null===this.data?this.postMessage({event:"created"},!0):this.showPicker(this.data),this.onMessage((function(t){e.showPicker(t)}))},onReady:function(){var e=this;this.$nextTick((function(){e.visible=!0}))},methods:{showPicker:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.column;for(var n in e)"column"!==n&&("number"==typeof t?this.$set(this.$data[n],t,e[n]):this.$data[n]=e[n])},close:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=n.value,r=void 0===a?-1:a;this.visible=!1,setTimeout((function(){t.postMessage({event:e,value:r})}),210)},onClose:function(){this.close("cancel")},columnchange:function(e){var t=e.column,n=e.value;this.$set(this.value,t,n),this.postMessage({event:"columnchange",column:t,value:n},!0)}}};t.default=i},function(e,t,n){"use strict";n.r(t);var a=n(23),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var a=n(46),r=o(n(35)),i=o(n(47));function o(e){return e&&e.__esModule?e:{default:e}}function s(e){return function(e){if(Array.isArray(e))return u(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||function(e,t){if(!e)return;if("string"==typeof e)return u(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return u(e,t)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,a=new Array(t);nn(i)&&this._cloneArray(a,i)}e.forEach((function(e,n){e!==t.oldValueArray[n]&&(t.oldValueArray[n]=e,t.mode===d.MULTISELECTOR&&t.$emit("columnchange",{column:n,value:e}))}))},visible:function(e){var t=this;e?this.$nextTick((function(){f.transition(t.$refs.picker,{styles:{transform:"translateY(0)"},duration:200})})):f.transition(this.$refs.picker,{styles:{transform:"translateY(".concat(283+this.safeAreaInsets.bottom,"px)")},duration:200})}},created:function(){this._createTime(),this._createDate(),this._setValueSync()},methods:{getTexts:function(e,t){var n=this,a=this.textMaxLength;return e.map((function(e){var r=("object"==typeof e?e[n.rangeKey]||"":e)+(n.units[t]||"");if(a>0&&r.length>a)for(var i=0,o=0,s=0;s127||94===u?1:.65)<=a-1&&(o=s),i>=a)return s===r.length-1?r:r.substr(0,o+1)+"…"}return r||" "})).join("\n")},_createTime:function(){var e=[],t=[];e.splice(0,e.length);for(var n=0;n<24;n++)e.push((n<10?"0":"")+n);t.splice(0,t.length);for(var a=0;a<60;a++)t.push((a<10?"0":"")+a);this.timeArray.push(e,t)},_createDate:function(){for(var e=[],t=(new Date).getFullYear(),n=t-61,a=t+61;n<=a;n++)e.push(String(n));for(var r=[],i=1;i<=12;i++)r.push((i<10?"0":"")+i);for(var o=[],s=1;s<=31;s++)o.push((s<10?"0":"")+s);this.dateArray.push(e,r,o)},_getTimeValue:function(e){return 60*e[0]+e[1]},_getDateValue:function(e){return 366*e[0]+31*(e[1]||0)+(e[2]||0)},_cloneArray:function(e,t){for(var n=0;no?0:i)}break;case d.TIME:case d.DATE:this.valueSync=String(e);break;default:var s=Number(e);this.valueSync=s<0?0:s}},_setValueArray:function(){var e,t=this.valueSync;switch(this.mode){case d.MULTISELECTOR:e=s(t);break;case d.TIME:e=this._getDateValueArray(t,(0,a.formatDateTime)({mode:d.TIME}));break;case d.DATE:e=this._getDateValueArray(t,(0,a.formatDateTime)({mode:d.DATE}));break;default:e=[t]}this.oldValueArray=s(e),this.valueArray=s(e)},_getValue:function(){var e=this,t=this.valueArray;switch(this.mode){case d.SELECTOR:return t[0];case d.MULTISELECTOR:return t.map((function(e){return e}));case d.TIME:return this.valueArray.map((function(t,n){return e.timeArray[n][t]})).join(":");case d.DATE:return this.valueArray.map((function(t,n){return e.dateArray[n][t]})).join("-")}},_getDateValueArray:function(e,t){var n=this.mode===d.DATE?"-":":",a=this.mode===d.DATE?this.dateArray:this.timeArray,r=3;switch(this.fields){case p.YEAR:r=1;break;case p.MONTH:r=2}for(var i=String(e).split(n),o=[],s=0;s=0&&(o=t?this._getDateValueArray(t):o.map((function(){return 0}))),o},_change:function(){this.$emit("change",{value:this._getValue()})},_cancel:function(){this.$emit("cancel")}}};t.default=h},function(e,t){e.exports={content:{position:"absolute",top:0,left:0,bottom:0,right:0},"uni-mask":{position:"absolute",top:0,left:0,bottom:0,right:0,backgroundColor:"rgba(0,0,0,0.4)",opacity:0,transitionProperty:"opacity",transitionDuration:200,transitionTimingFunction:"linear"},"@TRANSITION":{"uni-mask":{property:"opacity",duration:200,timingFunction:"linear"}},"uni-mask-android":{backgroundColor:"rgba(0,0,0,0.6)"},"uni-mask-visible":{opacity:1},"uni-picker":{position:"absolute",left:0,bottom:0,right:0,backgroundColor:"#ffffff",color:"#000000",flexDirection:"column",transform:"translateY(295px)"},"uni-picker-header":{height:"45",borderBottomWidth:0,backgroundColor:"#E6E6E6",fontSize:"20"},"uni-picker-action":{position:"absolute",textAlign:"center",top:0,height:"45",paddingTop:0,paddingRight:"14",paddingBottom:0,paddingLeft:"14",fontSize:"17",lineHeight:"45"},"uni-picker-action-cancel":{left:0,color:"#888888"},"uni-picker-action-confirm":{right:0,color:"#007aff"},"uni-picker-content":{flex:1},"uni-picker-item":{lineHeight:"34",textAlign:"center",color:"#000000"}}},function(e,t){e.exports={page:{flex:1}}},,,,,function(e,t,n){"use strict";var a=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("scroll-view",{staticStyle:{flexDirection:"column"},attrs:{scrollY:!0,enableBackToTop:!0,bubble:"true"}},[n("view",{staticClass:["page"]},[n("picker",{attrs:{range:e.range,rangeKey:e.rangeKey,value:e.value,mode:e.mode,fields:e.fields,start:e.start,end:e.end,disabled:e.disabled,visible:e.visible},on:{change:function(t){e.close("change",t)},cancel:function(t){e.close("cancel",t)},columnchange:e.columnchange}})],1)])},r=[];n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return r})),n.d(t,"a",(function(){}))},,,function(e,t,n){"use strict";var a=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:["content"]},[n("div",{ref:"mask",staticClass:["uni-mask"],class:{"uni-mask-visible":e.visible,"uni-mask-android":e.android},on:{click:e._cancel}}),n("div",{ref:"picker",staticClass:["uni-picker"],class:{"uni-picker-visible":e.visible},style:"padding-bottom:"+e.safeAreaInsets.bottom+"px;height:"+(e.height+e.safeAreaInsets.bottom)+"px;"},[n("div",{staticClass:["uni-picker-header"]},[n("u-text",{staticClass:["uni-picker-action","uni-picker-action-cancel"],style:"left:"+e.safeAreaInsets.left+"px",on:{click:e._cancel}},[e._v(e._s(e.localize("cancel")))]),n("u-text",{staticClass:["uni-picker-action","uni-picker-action-confirm"],style:"right:"+e.safeAreaInsets.right+"px",on:{click:e._change}},[e._v(e._s(e.localize("ok")))])]),e.visible?n("picker-view",{staticClass:["uni-picker-content"],style:"margin-left:"+e.safeAreaInsets.left+"px",attrs:{height:"216",indicatorStyle:"height: 34px;border-color:#C8C9C9;border-top-width:0.5px;border-bottom-width:0.5px;",value:e.valueArray},on:{"update:value":function(t){e.valueArray=t}}},e._l(e.rangeArray,(function(t,a){return n("picker-view-column",{key:a,attrs:{length:t.length}},[n("u-text",{staticClass:["uni-picker-item"],style:{fontSize:e.fontSize+"px"}},[e._v(e._s(e.getTexts(t,a)))])])})),1):e._e()],1)])},r=[];n.d(t,"b",(function(){return a})),n.d(t,"c",(function(){return r})),n.d(t,"a",(function(){}))},,function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n={data:function(){return{locale:{default:"en",full:"en",primary:"en"},localization:{en:{ok:"OK",cancel:"Cancel"},zh:{ok:"完成",cancel:"取消"},"zh-hans":{},"zh-hant":{}}}},onLoad:function(){this.initLocale()},created:function(){this.initLocale()},methods:{initLocale:function(){if(!this.__initLocale){this.__initLocale=!0;var t=e.os.language.toLowerCase().replace("_","-").split("-"),n=t[1];n&&(t[1]={chs:"hans",cn:"hans",sg:"hans",cht:"hant",tw:"hant",hk:"hant",mo:"hant"}[n]||n),t.length=t.length>2?2:t.length,this.locale.full=t.join("-"),this.locale.primary=t[0]}},localize:function(e){var t=this.locale,n=this.localization;function a(e){return n[e]||{}}return a(t.full)[e]||a(t.primary)[e]||a(t.default)[e]||e}}};t.default=n}).call(this,n(2).weexPlus)},,,,function(e,t,n){"use strict";n.r(t);var a=n(24),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},function(e,t,n){"use strict";n.r(t);var a=n(25),r=n.n(a);for(var i in a)"default"!==i&&function(e){n.d(t,e,(function(){return a[e]}))}(i);t.default=r.a},,,,function(e,t,n){"use strict";n.r(t);n(3);var a=n(9);a.default.mpType="page",a.default.route="template/__uniapppicker",a.default.el="#root",new Vue(a.default)},function(e,t,n){"use strict";n.r(t);var a=n(33),r=n(22);for(var i in r)"default"!==i&&function(e){n.d(t,e,(function(){return r[e]}))}(i);var o=n(1);var s=Object(o.a)(r.default,a.b,a.c,!1,null,null,"2b83bbfe",!1,a.a,void 0);(function(e){this.options.style||(this.options.style={}),Vue.prototype.__merge_style&&Vue.prototype.__$appStyle__&&Vue.prototype.__merge_style(Vue.prototype.__$appStyle__,this.options.style),Vue.prototype.__merge_style?Vue.prototype.__merge_style(n(39).default,this.options.style):Object.assign(this.options.style,n(39).default)}).call(s),t.default=s.exports},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.formatDateTime=function(e){var t=e.date,n=void 0===t?new Date:t,r=e.mode;return"time"===(void 0===r?"date":r)?a(n.getHours())+":"+a(n.getMinutes()):n.getFullYear()+"-"+a(n.getMonth()+1)+"-"+a(n.getDate())};var a=function(e){return e>9?e:"0"+e}},function(e,t,n){"use strict";(function(e){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n={data:function(){return{safeAreaInsets:{left:0,right:0,top:0,bottom:0}}},onLoad:function(){this.initSafeAreaInsets()},created:function(){this.initSafeAreaInsets()},methods:{initSafeAreaInsets:function(){var t=this;if(!this.__initSafeAreaInsets){this.__initSafeAreaInsets=!0;var n=e.webview.currentWebview();n.addEventListener("resize",(function(){setTimeout((function(){t.updateSafeAreaInsets(n)}),20)})),this.updateSafeAreaInsets(n)}},updateSafeAreaInsets:function(e){var t=e.getSafeAreaInsets(),n=this.safeAreaInsets;Object.keys(n).forEach((function(e){n[e]=t[e]}))}}};t.default=n}).call(this,n(2).weexPlus)}]); \ No newline at end of file diff --git a/packages/uni-mp-alipay/dist/uni.api.esm.js b/packages/uni-mp-alipay/dist/uni.api.esm.js new file mode 100644 index 0000000000000000000000000000000000000000..0410bd296ffc34ca2b52d7122dce7bb120f2917d --- /dev/null +++ b/packages/uni-mp-alipay/dist/uni.api.esm.js @@ -0,0 +1,1008 @@ +import { isArray, isPromise, isFunction, isPlainObject, hasOwn, isString } from '@vue/shared'; + +const EPS = 1e-4; +const BASE_DEVICE_WIDTH = 750; +let isIOS = false; +let deviceWidth = 0; +let deviceDPR = 0; +function checkDeviceWidth() { + const { platform, pixelRatio, windowWidth } = my.getSystemInfoSync(); + deviceWidth = windowWidth; + deviceDPR = pixelRatio; + isIOS = platform === 'ios'; +} +function upx2px(number, newDeviceWidth) { + if (deviceWidth === 0) { + checkDeviceWidth(); + } + number = Number(number); + if (number === 0) { + return 0; + } + let result = (number / BASE_DEVICE_WIDTH) * (newDeviceWidth || deviceWidth); + if (result < 0) { + result = -result; + } + result = Math.floor(result + EPS); + if (result === 0) { + if (deviceDPR === 1 || !isIOS) { + result = 1; + } + else { + result = 0.5; + } + } + return number < 0 ? -result : result; +} + +var HOOKS; +(function (HOOKS) { + HOOKS["INVOKE"] = "invoke"; + HOOKS["SUCCESS"] = "success"; + HOOKS["FAIL"] = "fail"; + HOOKS["COMPLETE"] = "complete"; + HOOKS["RETURN_VALUE"] = "returnValue"; +})(HOOKS || (HOOKS = {})); +const globalInterceptors = {}; +const scopedInterceptors = {}; +function wrapperHook(hook) { + return function (data) { + return hook(data) || data; + }; +} +function queue(hooks, data) { + let promise = false; + for (let i = 0; i < hooks.length; i++) { + const hook = hooks[i]; + if (promise) { + promise = Promise.resolve(wrapperHook(hook)); + } + else { + const res = hook(data); + if (isPromise(res)) { + promise = Promise.resolve(res); + } + if (res === false) { + return { + then() { }, + catch() { } + }; + } + } + } + return (promise || { + then(callback) { + return callback(data); + }, + catch() { } + }); +} +function wrapperOptions(interceptors, options = {}) { + [HOOKS.SUCCESS, HOOKS.FAIL, HOOKS.COMPLETE].forEach(name => { + const hooks = interceptors[name]; + if (!isArray(hooks)) { + return; + } + const oldCallback = options[name]; + options[name] = function callbackInterceptor(res) { + queue(hooks, res).then((res) => { + return (isFunction(oldCallback) && oldCallback(res)) || res; + }); + }; + }); + return options; +} +function wrapperReturnValue(method, returnValue) { + const returnValueHooks = []; + if (isArray(globalInterceptors.returnValue)) { + returnValueHooks.push(...globalInterceptors.returnValue); + } + const interceptor = scopedInterceptors[method]; + if (interceptor && isArray(interceptor.returnValue)) { + returnValueHooks.push(...interceptor.returnValue); + } + returnValueHooks.forEach(hook => { + returnValue = hook(returnValue) || returnValue; + }); + return returnValue; +} +function getApiInterceptorHooks(method) { + const interceptor = Object.create(null); + Object.keys(globalInterceptors).forEach(hook => { + if (hook !== 'returnValue') { + interceptor[hook] = globalInterceptors[hook].slice(); + } + }); + const scopedInterceptor = scopedInterceptors[method]; + if (scopedInterceptor) { + Object.keys(scopedInterceptor).forEach(hook => { + if (hook !== 'returnValue') { + interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]); + } + }); + } + return interceptor; +} +function invokeApi(method, api, options, ...params) { + const interceptor = getApiInterceptorHooks(method); + if (interceptor && Object.keys(interceptor).length) { + if (isArray(interceptor.invoke)) { + const res = queue(interceptor.invoke, options); + return res.then(options => { + return api(wrapperOptions(interceptor, options), ...params); + }); + } + else { + return api(wrapperOptions(interceptor, options), ...params); + } + } + return api(options, ...params); +} + +function mergeInterceptorHook(interceptors, interceptor) { + Object.keys(interceptor).forEach(hook => { + if (isFunction(interceptor[hook])) { + interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]); + } + }); +} +function removeInterceptorHook(interceptors, interceptor) { + if (!interceptors || !interceptor) { + return; + } + Object.keys(interceptor).forEach(hook => { + if (isFunction(interceptor[hook])) { + removeHook(interceptors[hook], interceptor[hook]); + } + }); +} +function mergeHook(parentVal, childVal) { + const res = childVal + ? parentVal + ? parentVal.concat(childVal) + : isArray(childVal) + ? childVal + : [childVal] + : parentVal; + return res ? dedupeHooks(res) : res; +} +function dedupeHooks(hooks) { + const res = []; + for (let i = 0; i < hooks.length; i++) { + if (res.indexOf(hooks[i]) === -1) { + res.push(hooks[i]); + } + } + return res; +} +function removeHook(hooks, hook) { + if (!hooks) { + return; + } + const index = hooks.indexOf(hook); + if (index !== -1) { + hooks.splice(index, 1); + } +} +function addInterceptor(method, interceptor) { + if (typeof method === 'string' && isPlainObject(interceptor)) { + mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); + } + else if (isPlainObject(method)) { + mergeInterceptorHook(globalInterceptors, method); + } +} +function removeInterceptor(method, interceptor) { + if (typeof method === 'string') { + if (isPlainObject(interceptor)) { + removeInterceptorHook(scopedInterceptors[method], interceptor); + } + else { + delete scopedInterceptors[method]; + } + } + else if (isPlainObject(method)) { + removeInterceptorHook(globalInterceptors, method); + } +} + +const SYNC_API_RE = /^\$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; +const CONTEXT_API_RE = /^create|Manager$/; +// Context例外情况 +const CONTEXT_API_RE_EXC = ['createBLEConnection']; +// 同步例外情况 +const ASYNC_API = ['createBLEConnection']; +const CALLBACK_API_RE = /^on|^off/; +function isContextApi(name) { + return CONTEXT_API_RE.test(name) && CONTEXT_API_RE_EXC.indexOf(name) === -1; +} +function isSyncApi(name) { + return SYNC_API_RE.test(name) && ASYNC_API.indexOf(name) === -1; +} +function isCallbackApi(name) { + return CALLBACK_API_RE.test(name) && name !== 'onPush'; +} +function handlePromise(promise) { + if (!__UNI_PROMISE_API__) { + return promise; + } + return promise + .then(data => { + return [null, data]; + }) + .catch(err => [err]); +} +function shouldPromise(name) { + if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) { + return false; + } + return true; +} +/* eslint-disable no-extend-native */ +if (!Promise.prototype.finally) { + Promise.prototype.finally = function (onfinally) { + const promise = this.constructor; + return this.then(value => promise.resolve(onfinally && onfinally()).then(() => value), reason => promise.resolve(onfinally && onfinally()).then(() => { + throw reason; + })); + }; +} +function promisify(name, api) { + if (!shouldPromise(name)) { + return api; + } + if (!isFunction(api)) { + return api; + } + return function promiseApi(options = {}, ...params) { + if (isFunction(options.success) || + isFunction(options.fail) || + isFunction(options.complete)) { + return wrapperReturnValue(name, invokeApi(name, api, options, ...params)); + } + return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => { + invokeApi(name, api, Object.assign({}, options, { + success: resolve, + fail: reject + }), ...params); + }))); + }; +} + +const CALLBACKS = ['success', 'fail', 'cancel', 'complete']; +function initWrapper(protocols) { + function processCallback(methodName, method, returnValue) { + return function (res) { + return method(processReturnValue(methodName, res, returnValue)); + }; + } + function processArgs(methodName, fromArgs, argsOption = {}, returnValue = {}, keepFromArgs = false) { + if (isPlainObject(fromArgs)) { + // 一般 api 的参数解析 + const toArgs = (keepFromArgs === true ? fromArgs : {}); // returnValue 为 false 时,说明是格式化返回值,直接在返回值对象上修改赋值 + if (isFunction(argsOption)) { + argsOption = argsOption(fromArgs, toArgs) || {}; + } + for (const key in fromArgs) { + if (hasOwn(argsOption, key)) { + let keyOption = argsOption[key]; + if (isFunction(keyOption)) { + keyOption = keyOption(fromArgs[key], fromArgs, toArgs); + } + if (!keyOption) { + // 不支持的参数 + console.warn(`支付宝小程序 ${methodName} 暂不支持 ${key}`); + } + else if (isString(keyOption)) { + // 重写参数 key + toArgs[keyOption] = fromArgs[key]; + } + else if (isPlainObject(keyOption)) { + // {name:newName,value:value}可重新指定参数 key:value + toArgs[keyOption.name ? keyOption.name : key] = keyOption.value; + } + } + else if (CALLBACKS.indexOf(key) !== -1) { + const callback = fromArgs[key]; + if (isFunction(callback)) { + toArgs[key] = processCallback(methodName, callback, returnValue); + } + } + else { + if (!keepFromArgs && !hasOwn(toArgs, key)) { + toArgs[key] = fromArgs[key]; + } + } + } + return toArgs; + } + else if (isFunction(fromArgs)) { + fromArgs = processCallback(methodName, fromArgs, returnValue); + } + return fromArgs; + } + function processReturnValue(methodName, res, returnValue, keepReturnValue = false) { + if (isFunction(protocols.returnValue)) { + // 处理通用 returnValue + res = protocols.returnValue(methodName, res); + } + return processArgs(methodName, res, returnValue, {}, keepReturnValue); + } + return function wrapper(methodName, method) { + if (!hasOwn(protocols, methodName)) { + return method; + } + const protocol = protocols[methodName]; + if (!protocol) { + // 暂不支持的 api + return function () { + console.error(`支付宝小程序 暂不支持${methodName}`); + }; + } + return function (arg1, arg2) { + // 目前 api 最多两个参数 + let options = protocol; + if (isFunction(protocol)) { + options = protocol(arg1); + } + arg1 = processArgs(methodName, arg1, options.args, options.returnValue); + const args = [arg1]; + if (typeof arg2 !== 'undefined') { + args.push(arg2); + } + const returnValue = my[options.name || methodName].apply(my, args); + if (isSyncApi(methodName)) { + // 同步 api + return processReturnValue(methodName, returnValue, options.returnValue, isContextApi(methodName)); + } + return returnValue; + }; + }; +} + +const baseApis = { upx2px, addInterceptor, removeInterceptor }; +function initUni(api, protocols) { + const wrapper = initWrapper(protocols); + const UniProxyHandlers = { + get(target, key) { + if (hasOwn(target, key)) { + return target[key]; + } + if (hasOwn(api, key)) { + return promisify(key, api[key]); + } + if (hasOwn(baseApis, key)) { + return promisify(key, baseApis[key]); + } + // event-api + // provider-api? + return promisify(key, wrapper(key, my[key])); + } + }; + return new Proxy({}, UniProxyHandlers); +} + +function initGetProvider(providers) { + return function getProvider({ service, success, fail, complete }) { + let res; + if (providers[service]) { + res = { + errMsg: 'getProvider:ok', + service, + provider: providers[service] + }; + isFunction(success) && success(res); + } + else { + res = { + errMsg: 'getProvider:fail:服务[' + service + ']不存在' + }; + isFunction(fail) && fail(res); + } + isFunction(complete) && complete(res); + }; +} + +function addSafeAreaInsets(fromRes, toRes) { + if (fromRes.safeArea) { + const safeArea = fromRes.safeArea; + toRes.safeAreaInsets = { + top: safeArea.top, + left: safeArea.left, + right: fromRes.windowWidth - safeArea.right, + bottom: fromRes.windowHeight - safeArea.bottom + }; + } +} + +const getProvider = initGetProvider({ + oauth: ['alipay'], + share: ['alipay'], + payment: ['alipay'], + push: ['alipay'] +}); +function setStorageSync(key, data) { + return my.setStorageSync({ + key, + data + }); +} +function getStorageSync(key) { + const result = my.getStorageSync({ + key + }); + // 支付宝平台会返回一个 success 值,但是目前测试的结果这个始终是 true。当没有存储数据的时候,其它平台会返回空字符串。 + return result.data !== null ? result.data : ''; +} +function removeStorageSync(key) { + return my.removeStorageSync({ + key + }); +} +function startGyroscope(args) { + if (hasOwn(args, 'interval')) { + console.warn('支付宝小程序 startGyroscope暂不支持interval'); + } + args.success && + args.success({ + errMsg: 'startGyroscope:ok' + }); + args.complete && + args.complete({ + errMsg: 'startGyroscope:ok' + }); +} +function createExecCallback(execCallback) { + return function wrapperExecCallback(res) { + this.actions.forEach((action, index) => { + (action._$callbacks || []).forEach((callback) => { + callback(res[index]); + }); + }); + if (isFunction(execCallback)) { + execCallback(res); + } + }; +} +function addCallback(callback) { + if (isFunction(callback)) { + const action = this.actions[this.actions.length - 1]; + if (action) { + (action._$callbacks || (action._$callbacks = [])).push(callback); + } + } +} +function createSelectorQuery() { + const query = my.createSelectorQuery(); + const oldExec = query.exec; + const oldScrollOffset = query.scrollOffset; + const oldBoundingClientRect = query.boundingClientRect; + query.exec = function exec(callback) { + return oldExec.call(this, createExecCallback(callback).bind(this)); + }; + query.scrollOffset = function scrollOffset(callback) { + const ret = oldScrollOffset.call(this); + addCallback.call(this, callback); + return ret; + }; + query.boundingClientRect = function boundingClientRect(callback) { + const ret = oldBoundingClientRect.call(this); + addCallback.call(this, callback); + return ret; + }; + if (!query.fields) { + query.fields = function ({ rect, size, scrollOffset }, callback) { + if (rect || size) { + this.boundingClientRect(); + } + if (scrollOffset) { + this.scrollOffset(); + } + addCallback.call(this, callback); + return this; + }; + } + if (!query.in) { + query.in = function () { + return this; + }; + } + return query; +} +function createIntersectionObserver(component, options) { + if (options && options.observeAll) { + options.selectAll = options.observeAll; + delete options.observeAll; + } + return my.createIntersectionObserver(options); +} + +var shims = /*#__PURE__*/Object.freeze({ + __proto__: null, + getProvider: getProvider, + setStorageSync: setStorageSync, + getStorageSync: getStorageSync, + removeStorageSync: removeStorageSync, + startGyroscope: startGyroscope, + createSelectorQuery: createSelectorQuery, + createIntersectionObserver: createIntersectionObserver +}); + +function handleNetworkInfo(fromRes, toRes) { + const nextworkType = fromRes.networkType; + switch (nextworkType) { + case 'NOTREACHABLE': + toRes.networkType = 'none'; + break; + case 'WWAN': + // TODO ? + toRes.networkType = '3g'; + break; + default: + toRes.networkType = fromRes.networkType.toLowerCase(); + break; + } +} +function handleSystemInfo(fromRes, toRes) { + addSafeAreaInsets(fromRes, toRes); + let platform = fromRes.platform ? fromRes.platform.toLowerCase() : 'devtools'; + if (!~['android', 'ios'].indexOf(platform)) { + platform = 'devtools'; + } + toRes.platform = platform; +} +function returnValue(methodName, res) { + // 通用 returnValue 解析 + if (res.error || res.errorMessage) { + res.errMsg = `${methodName}:fail ${res.errorMessage || res.error}`; + delete res.error; + delete res.errorMessage; + } + else { + res.errMsg = `${methodName}:ok`; + } + return res; +} +const request = { + name: my.canIUse('request') ? 'request' : 'httpRequest', + args(fromArgs) { + const method = fromArgs.method || 'GET'; + if (!fromArgs.header) { + // 默认增加 header 参数,方便格式化 content-type + fromArgs.header = {}; + } + const headers = { + 'content-type': 'application/json' + }; + Object.keys(fromArgs.header).forEach(key => { + headers[key.toLocaleLowerCase()] = fromArgs.header[key]; + }); + return { + header() { + return { + name: 'headers', + value: headers + }; + }, + data(data) { + // 钉钉小程序在content-type为application/json时需上传字符串形式data,使用my.dd在真机运行钉钉小程序时不能正确判断 + if (my.canIUse('saveFileToDingTalk') && + method.toUpperCase() === 'POST' && + headers['content-type'].indexOf('application/json') === 0 && + isPlainObject(data)) { + return { + name: 'data', + value: JSON.stringify(data) + }; + } + return { + name: 'data', + value: data + }; + }, + method: 'method', + responseType: false + }; + }, + returnValue: { + status: 'statusCode', + headers: 'header' + } +}; +const setNavigationBarColor = { + name: 'setNavigationBar', + args: { + frontColor: false, + animation: false + } +}; +const setNavigationBarTitle = { + name: 'setNavigationBar' +}; +function showModal({ showCancel = true } = {}) { + if (showCancel) { + return { + name: 'confirm', + args: { + cancelColor: false, + confirmColor: false, + cancelText: 'cancelButtonText', + confirmText: 'confirmButtonText' + }, + returnValue(fromRes, toRes) { + toRes.confirm = fromRes.confirm; + toRes.cancel = !fromRes.confirm; + } + }; + } + return { + name: 'alert', + args: { + confirmColor: false, + confirmText: 'buttonText' + }, + returnValue(fromRes, toRes) { + toRes.confirm = true; + toRes.cancel = false; + } + }; +} +function showToast({ icon = 'success' } = {}) { + const args = { + title: 'content', + icon: 'type', + duration: false, + image: false, + mask: false + }; + if (icon === 'loading') { + return { + name: 'showLoading', + args + }; + } + return { + name: 'showToast', + args + }; +} +const showActionSheet = { + name: 'showActionSheet', + args: { + itemList: 'items', + itemColor: false + }, + returnValue: { + index: 'tapIndex' + } +}; +const showLoading = { + args: { + title: 'content', + mask: false + } +}; +const uploadFile = { + args: { + name: 'fileName' + } + // 从测试结果看,是有返回对象的,文档上没有说明。 +}; +const downloadFile = { + returnValue: { + apFilePath: 'tempFilePath' + } +}; +const getFileInfo = { + args: { + filePath: 'apFilePath' + } +}; +const compressImage = { + args(fromArgs, toArgs) { + toArgs.compressLevel = 4; + if (fromArgs && fromArgs.quality) { + toArgs.compressLevel = Math.floor(fromArgs.quality / 26); + } + if (fromArgs.src) { + toArgs.apFilePaths = [fromArgs.src]; + } + }, + returnValue(fromRes, toRes) { + const apFilePaths = fromRes.apFilePaths; + if (apFilePaths && apFilePaths.length) { + toRes.tempFilePath = apFilePaths[0]; + } + } +}; +const chooseVideo = { + // 支付宝小程序文档中未找到(仅在getSetting处提及),但实际可用 + returnValue: { + apFilePath: 'tempFilePath' + } +}; +const connectSocket = { + args: { + method: false, + protocols: false + } + // TODO 有没有返回值还需要测试下 +}; +const chooseImage = { + returnValue: { + apFilePaths: 'tempFilePaths' + } +}; +const previewImage = { + args(fromArgs, toArgs) { + // 支付宝小程序的 current 是索引值,而非图片地址。 + const currentIndex = Number(fromArgs.current); + if (isNaN(currentIndex)) { + if (fromArgs.current && isArray(fromArgs.urls)) { + const index = fromArgs.urls.indexOf(fromArgs.current); + toArgs.current = ~index ? index : 0; + } + } + else { + toArgs.current = currentIndex; + } + return { + indicator: false, + loop: false + }; + } +}; +const saveFile = { + args: { + tempFilePath: 'apFilePath' + }, + returnValue: { + apFilePath: 'savedFilePath' + } +}; +const getSavedFileInfo = { + args: { + filePath: 'apFilePath' + } +}; +const getSavedFileList = { + returnValue(fromRes, toRes) { + toRes.fileList = fromRes.fileList.map(file => { + return { + filePath: file.apFilePath, + createTime: file.createTime, + size: file.size + }; + }); + } +}; +const removeSavedFile = { + args: { + filePath: 'apFilePath' + } +}; +const getLocation = { + args: { + type: false, + altitude: false + } +}; +const openLocation = { + args: { + // TODO address 参数在阿里上是必传的 + } +}; +const getNetworkType = { + returnValue: handleNetworkInfo +}; +const onNetworkStatusChange = { + returnValue: handleNetworkInfo +}; +const stopAccelerometer = { + name: 'offAccelerometerChange' +}; +const stopCompass = { + name: 'offCompassChange' +}; +const scanCode = { + name: 'scan', + args: { + onlyFromCamera: 'hideAlbum' + }, + returnValue: { + code: 'result' + } +}; +const setClipboardData = { + name: 'setClipboard', + args: { + data: 'text' + } +}; +const getClipboardData = { + name: 'getClipboard', + returnValue: { + text: 'data' + } +}; +const pageScrollTo = { + args: { + duration: false + } +}; +const login = { + name: 'getAuthCode', + returnValue: { + authCode: 'code' + } +}; +const getUserInfo = { + name: my.canIUse('getOpenUserInfo') ? 'getOpenUserInfo' : 'getAuthUserInfo', + returnValue(fromRes, toRes) { + if (my.canIUse('getOpenUserInfo')) { + let response; + try { + response = JSON.parse(fromRes.response).response; + } + catch (e) { } + if (response) { + toRes.userInfo = response; + toRes.userInfo.avatarUrl = response.avatar; + delete response.avatar; + } + } + else { + toRes.userInfo = { + openId: '', + nickName: fromRes.nickName, + avatarUrl: fromRes.avatar + }; + } + } +}; +const requestPayment = { + name: 'tradePay', + args: { + orderInfo: 'tradeNO' + } +}; +const getBLEDeviceServices = { + returnValue(fromRes, toRes) { + toRes.services = fromRes.services.map(item => { + return { + uuid: item.serviceId, + isPrimary: item.isPrimary + }; + }); + } +}; +const createBLEConnection = { + name: 'connectBLEDevice', + args: { + timeout: false + } +}; +const closeBLEConnection = { + name: 'disconnectBLEDevice' +}; +const onBLEConnectionStateChange = { + name: 'onBLEConnectionStateChanged' +}; +const makePhoneCall = { + args: { + phoneNumber: 'number' + } +}; +const stopGyroscope = { + name: 'offGyroscopeChange' +}; +const getSystemInfo = { + returnValue: handleSystemInfo +}; +const getSystemInfoSync = { + returnValue: handleSystemInfo +}; +// 文档没提到,但是实测可用。 +const canvasToTempFilePath = { + returnValue(fromRes, toRes) { + // 真机的情况下会有 tempFilePath 这个值,因此需要主动修改。 + toRes.tempFilePath = fromRes.apFilePath; + } +}; +const setScreenBrightness = { + args: { + value: 'brightness' + } +}; +const getScreenBrightness = { + returnValue: { + brightness: 'value' + } +}; +const showShareMenu = { + name: 'showSharePanel' +}; +const hideHomeButton = { + name: 'hideBackHome' +}; +const saveImageToPhotosAlbum = { + name: 'saveImage', + args: { + filePath: 'url' + } +}; +const saveVideoToPhotosAlbum = { + args: { + filePath: 'src' + } +}; +const chooseAddress = { + name: 'getAddress', + returnValue(fromRes, toRes) { + const info = fromRes.result || {}; + toRes.userName = info.fullname; + toRes.countyName = info.country; + toRes.provinceName = info.prov; + toRes.cityName = info.city; + toRes.detailInfo = info.address; + toRes.telNumber = info.mobilePhone; + toRes.errMsg = toRes.errMsg + ' ' + fromRes.resultStatus; + } +}; + +var protocols = /*#__PURE__*/Object.freeze({ + __proto__: null, + returnValue: returnValue, + request: request, + setNavigationBarColor: setNavigationBarColor, + setNavigationBarTitle: setNavigationBarTitle, + showModal: showModal, + showToast: showToast, + showActionSheet: showActionSheet, + showLoading: showLoading, + uploadFile: uploadFile, + downloadFile: downloadFile, + getFileInfo: getFileInfo, + compressImage: compressImage, + chooseVideo: chooseVideo, + connectSocket: connectSocket, + chooseImage: chooseImage, + previewImage: previewImage, + saveFile: saveFile, + getSavedFileInfo: getSavedFileInfo, + getSavedFileList: getSavedFileList, + removeSavedFile: removeSavedFile, + getLocation: getLocation, + openLocation: openLocation, + getNetworkType: getNetworkType, + onNetworkStatusChange: onNetworkStatusChange, + stopAccelerometer: stopAccelerometer, + stopCompass: stopCompass, + scanCode: scanCode, + setClipboardData: setClipboardData, + getClipboardData: getClipboardData, + pageScrollTo: pageScrollTo, + login: login, + getUserInfo: getUserInfo, + requestPayment: requestPayment, + getBLEDeviceServices: getBLEDeviceServices, + createBLEConnection: createBLEConnection, + closeBLEConnection: closeBLEConnection, + onBLEConnectionStateChange: onBLEConnectionStateChange, + makePhoneCall: makePhoneCall, + stopGyroscope: stopGyroscope, + getSystemInfo: getSystemInfo, + getSystemInfoSync: getSystemInfoSync, + canvasToTempFilePath: canvasToTempFilePath, + setScreenBrightness: setScreenBrightness, + getScreenBrightness: getScreenBrightness, + showShareMenu: showShareMenu, + hideHomeButton: hideHomeButton, + saveImageToPhotosAlbum: saveImageToPhotosAlbum, + saveVideoToPhotosAlbum: saveVideoToPhotosAlbum, + chooseAddress: chooseAddress +}); + +var index = initUni(shims, protocols); + +export default index; diff --git a/packages/uni-mp-alipay/dist/uni.mp.esm.js b/packages/uni-mp-alipay/dist/uni.mp.esm.js new file mode 100644 index 0000000000000000000000000000000000000000..ecf3041e4ca40bdde859b0556071a20b1a21f22c --- /dev/null +++ b/packages/uni-mp-alipay/dist/uni.mp.esm.js @@ -0,0 +1,1105 @@ +import { capitalize, hasOwn, isArray, toNumber, isPlainObject, isObject, isFunction, extend, NOOP, EMPTY_OBJ, camelize } from '@vue/shared'; + +function setModel(target, key, value, modifiers) { + if (isArray(modifiers)) { + if (modifiers.indexOf('trim') !== -1) { + value = value.trim(); + } + if (modifiers.indexOf('number') !== -1) { + value = toNumber(value); + } + } + if (!target) { + target = this; + } + target[key] = value; +} +function setSync(target, key, value) { + if (!target) { + target = this; + } + target[key] = value; +} +function getOrig(data) { + if (isPlainObject(data)) { + return data.$orig || data; + } + return data; +} +function map(val, iteratee) { + let ret, i, l, keys, key; + if (isArray(val)) { + ret = new Array(val.length); + for (i = 0, l = val.length; i < l; i++) { + ret[i] = iteratee(val[i], i); + } + return ret; + } + else if (isObject(val)) { + keys = Object.keys(val); + ret = Object.create(null); + for (i = 0, l = keys.length; i < l; i++) { + key = keys[i]; + ret[key] = iteratee(val[key], key, i); + } + return ret; + } + return []; +} +const MP_METHODS = [ + 'createSelectorQuery', + 'createIntersectionObserver', + 'selectAllComponents', + 'selectComponent' +]; +function hasHook(name) { + const hooks = this.$[name]; + if (hooks && hooks.length) { + return true; + } + return false; +} +function callHook(name, args) { + if (name === 'mounted') { + callHook.call(this, 'bm'); // beforeMount + this.$.isMounted = true; + name = 'm'; + } + const hooks = this.$[name]; + let ret; + if (hooks) { + for (let i = 0; i < hooks.length; i++) { + ret = hooks[i](args); + } + } + return ret; +} +function createEmitFn(oldEmit, ctx) { + return function emit(event, ...args) { + if (ctx.$scope && event) { + ctx.$scope.triggerEvent(event, { __args__: args }); + } + { + const vnode = this.$.vnode; + const props = vnode && vnode.props; + if (props && props[`on${capitalize(event)}`]) { + return; + } + } + return oldEmit.apply(this, [event, ...args]); + }; +} +function set(target, key, val) { + return (target[key] = val); +} +function initBaseInstance(instance, options) { + const ctx = instance.ctx; + // mp + ctx.mpType = options.mpType; // @deprecated + ctx.$mpType = options.mpType; + ctx.$scope = options.mpInstance; + // TODO @deprecated + ctx.$mp = {}; + ctx._self = {}; + // $vm + ctx.$scope.$vm = instance.proxy; + // slots + { + Object.defineProperty(instance, 'slots', { + get() { + return this.$scope && this.$scope.props.$slots; + } + }); + } + if (__VUE_OPTIONS_API__) { + // $set + ctx.$set = set; + } + // $emit + instance.emit = createEmitFn(instance.emit, ctx); + // $callHook + ctx.$hasHook = hasHook; + ctx.$callHook = callHook; +} +function initComponentInstance(instance, options) { + initBaseInstance(instance, options); + const ctx = instance.ctx; + MP_METHODS.forEach(method => { + ctx[method] = function (...args) { + const mpInstance = ctx.$scope; + if (mpInstance && mpInstance[method]) { + return mpInstance[method].apply(mpInstance, args); + } + { + return my[method] && my[method].apply(my, args); + } + }; + }); + // TODO other + ctx.__set_model = setModel; + ctx.__set_sync = setSync; + ctx.__get_orig = getOrig; + // TODO + // ctx.__get_style = getStyle + ctx.__map = map; +} +function initMocks(instance, mpInstance, mocks) { + const ctx = instance.ctx; + mocks.forEach(mock => { + if (hasOwn(mpInstance, mock)) { + ctx[mock] = mpInstance[mock]; + } + }); +} + +const PAGE_HOOKS = [ + 'onLoad', + 'onShow', + // 'onReady', // lifetimes.ready + 'onHide', + 'onUnload', + 'onResize', + // 'onPageScroll', // 影响性能,开发者手动注册 + 'onTabItemTap', + 'onReachBottom', + 'onPullDownRefresh', + // 'onShareTimeline', // 右上角菜单,开发者手动注册 + 'onAddToFavorites' + // 'onShareAppMessage' // 右上角菜单,开发者手动注册 +]; +function findHooks(vueOptions, hooks = new Set()) { + if (vueOptions) { + Object.keys(vueOptions).forEach(name => { + if (name.indexOf('on') === 0 && isFunction(vueOptions[name])) { + hooks.add(name); + } + }); + const { extends: extendsOptions, mixins } = vueOptions; + if (mixins) { + mixins.forEach(mixin => findHooks(mixin, hooks)); + } + if (extendsOptions) { + findHooks(extendsOptions, hooks); + } + } + return hooks; +} +function initHook(mpOptions, hook, excludes) { + if (excludes.indexOf(hook) === -1 && !hasOwn(mpOptions, hook)) { + mpOptions[hook] = function (args) { + return this.$vm && this.$vm.$callHook(hook, args); + }; + } +} +const EXCLUDE_HOOKS = ['onReady']; +function initHooks(mpOptions, hooks, excludes = EXCLUDE_HOOKS) { + hooks.forEach(hook => initHook(mpOptions, hook, excludes)); +} +function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) { + findHooks(vueOptions).forEach(hook => initHook(mpOptions, hook, excludes)); +} + +const HOOKS = [ + 'onShow', + 'onHide', + 'onError', + 'onThemeChange', + 'onPageNotFound', + 'onUnhandledRejection' +]; +function parseApp(instance, parseAppOptions) { + const internalInstance = instance.$; + const appOptions = { + globalData: (instance.$options && instance.$options.globalData) || {}, + $vm: instance, + onLaunch(options) { + const ctx = internalInstance.ctx; + if (this.$vm && ctx.$callHook) { + // 已经初始化过了,主要是为了百度,百度 onShow 在 onLaunch 之前 + return; + } + initBaseInstance(internalInstance, { + mpType: 'app', + mpInstance: this, + slots: [] + }); + ctx.globalData = this.globalData; + instance.$callHook('onLaunch', options); + } + }; + const vueOptions = instance.$.type; + initHooks(appOptions, HOOKS); + initUnknownHooks(appOptions, vueOptions); + if (__VUE_OPTIONS_API__) { + const methods = vueOptions.methods; + methods && extend(appOptions, methods); + } + if (parseAppOptions) { + parseAppOptions.parse(appOptions); + } + return appOptions; +} +function initCreateApp(parseAppOptions) { + return function createApp(vm) { + return App(parseApp(vm, parseAppOptions)); + }; +} + +function initVueIds(vueIds, mpInstance) { + if (!vueIds) { + return; + } + const ids = vueIds.split(','); + const len = ids.length; + if (len === 1) { + mpInstance._$vueId = ids[0]; + } + else if (len === 2) { + mpInstance._$vueId = ids[0]; + mpInstance._$vuePid = ids[1]; + } +} +function findVmByVueId(instance, vuePid) { + // TODO vue3 中 没有 $children + const $children = instance.$children; + // 优先查找直属(反向查找:https://github.com/dcloudio/uni-app/issues/1200) + for (let i = $children.length - 1; i >= 0; i--) { + const childVm = $children[i]; + if (childVm.$scope._$vueId === vuePid) { + return childVm; + } + } + // 反向递归查找 + let parentVm; + for (let i = $children.length - 1; i >= 0; i--) { + parentVm = findVmByVueId($children[i], vuePid); + if (parentVm) { + return parentVm; + } + } +} + +const PROP_TYPES = [String, Number, Boolean, Object, Array, null]; +function parsePropType(key, type, defaultValue) { + // [String]=>String + if (isArray(type) && type.length === 1) { + return type[0]; + } + return type; +} +function initDefaultProps(isBehavior = false) { + const properties = {}; + if (!isBehavior) { + properties.vueId = { + type: String, + value: '' + }; + // 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots + properties.vueSlots = { + type: null, + value: [], + observer: function (newVal) { + const $slots = Object.create(null); + newVal.forEach((slotName) => { + $slots[slotName] = true; + }); + this.setData({ + $slots + }); + } + }; + } + return properties; +} +function createProperty(key, prop) { + { + return prop; + } +} +function initProps(mpComponentOptions, rawProps, isBehavior = false) { + const properties = initDefaultProps(isBehavior); + if (isArray(rawProps)) { + rawProps.forEach(key => { + properties[key] = createProperty(key, { + type: null + }); + }); + } + else if (isPlainObject(rawProps)) { + Object.keys(rawProps).forEach(key => { + const opts = rawProps[key]; + if (isPlainObject(opts)) { + // title:{type:String,default:''} + let value = opts.default; + if (isFunction(value)) { + value = value(); + } + const type = opts.type; + opts.type = parsePropType(key, type); + properties[key] = createProperty(key, { + type: PROP_TYPES.indexOf(type) !== -1 ? type : null, + value + }); + } + else { + // content:String + const type = parsePropType(key, opts); + properties[key] = createProperty(key, { + type: PROP_TYPES.indexOf(type) !== -1 ? type : null + }); + } + }); + } + mpComponentOptions.properties = properties; +} + +function initData(vueOptions) { + let data = vueOptions.data || {}; + if (typeof data === 'function') { + try { + const appConfig = getApp().$vm.$.appContext + .config; + data = data.call(appConfig.globalProperties); + } + catch (e) { + if (process.env.VUE_APP_DEBUG) { + console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data, e); + } + } + } + else { + try { + // 对 data 格式化 + data = JSON.parse(JSON.stringify(data)); + } + catch (e) { } + } + if (!isPlainObject(data)) { + data = {}; + } + return data; +} +function initBehaviors(vueOptions, initBehavior) { + const vueBehaviors = vueOptions.behaviors; + const vueExtends = vueOptions.extends; + const vueMixins = vueOptions.mixins; + let vueProps = vueOptions.props; + if (!vueProps) { + vueOptions.props = vueProps = []; + } + const behaviors = []; + if (isArray(vueBehaviors)) { + vueBehaviors.forEach(behavior => { + behaviors.push(behavior.replace('uni://', `${__PLATFORM_PREFIX__}://`)); + if (behavior === 'uni://form-field') { + if (isArray(vueProps)) { + vueProps.push('name'); + vueProps.push('value'); + } + else { + vueProps.name = { + type: String, + default: '' + }; + vueProps.value = { + type: [String, Number, Boolean, Array, Object, Date], + default: '' + }; + } + } + }); + } + if (isPlainObject(vueExtends) && vueExtends.props) { + const behavior = {}; + initProps(behavior, vueExtends.props, true); + behaviors.push(initBehavior(behavior)); + } + if (isArray(vueMixins)) { + vueMixins.forEach(vueMixin => { + if (isPlainObject(vueMixin) && vueMixin.props) { + const behavior = {}; + initProps(behavior, vueMixin.props, true); + behaviors.push(initBehavior(behavior)); + } + }); + } + return behaviors; +} + +function getValue(obj, path) { + const parts = path.split('.'); + let key = parts[0]; + if (key.indexOf('__$n') === 0) { + //number index + key = parseInt(key.replace('__$n', '')); + } + if (parts.length === 1) { + return obj[key]; + } + return getValue(obj[key], parts.slice(1).join('.')); +} +function getExtraValue(instance, dataPathsArray) { + let context = instance; + dataPathsArray.forEach(dataPathArray => { + const dataPath = dataPathArray[0]; + const value = dataPathArray[2]; + if (dataPath || typeof value !== 'undefined') { + // ['','',index,'disable'] + const propPath = dataPathArray[1]; + const valuePath = dataPathArray[3]; + let vFor; + if (Number.isInteger(dataPath)) { + vFor = dataPath; + } + else if (!dataPath) { + vFor = context; + } + else if (typeof dataPath === 'string' && dataPath) { + if (dataPath.indexOf('#s#') === 0) { + vFor = dataPath.substr(3); + } + else { + vFor = getValue(context, dataPath); + } + } + if (Number.isInteger(vFor)) { + context = value; + } + else if (!propPath) { + context = vFor[value]; + } + else { + if (isArray(vFor)) { + context = vFor.find(vForItem => { + return getValue(vForItem, propPath) === value; + }); + } + else if (isPlainObject(vFor)) { + context = Object.keys(vFor).find(vForKey => { + return getValue(vFor[vForKey], propPath) === value; + }); + } + else { + console.error('v-for 暂不支持循环数据:', vFor); + } + } + if (valuePath) { + context = getValue(context, valuePath); + } + } + }); + return context; +} +function processEventExtra(instance, extra, event) { + const extraObj = {}; + if (isArray(extra) && extra.length) { + /** + *[ + * ['data.items', 'data.id', item.data.id], + * ['metas', 'id', meta.id] + *], + *[ + * ['data.items', 'data.id', item.data.id], + * ['metas', 'id', meta.id] + *], + *'test' + */ + extra.forEach((dataPath, index) => { + if (typeof dataPath === 'string') { + if (!dataPath) { + // model,prop.sync + extraObj['$' + index] = instance; + } + else { + if (dataPath === '$event') { + // $event + extraObj['$' + index] = event; + } + else if (dataPath === 'arguments') { + if (event.detail && event.detail.__args__) { + extraObj['$' + index] = event.detail.__args__; + } + else { + extraObj['$' + index] = [event]; + } + } + else if (dataPath.indexOf('$event.') === 0) { + // $event.target.value + extraObj['$' + index] = getValue(event, dataPath.replace('$event.', '')); + } + else { + extraObj['$' + index] = getValue(instance, dataPath); + } + } + } + else { + extraObj['$' + index] = getExtraValue(instance, dataPath); + } + }); + } + return extraObj; +} +function getObjByArray(arr) { + const obj = {}; + for (let i = 1; i < arr.length; i++) { + const element = arr[i]; + obj[element[0]] = element[1]; + } + return obj; +} +function processEventArgs(instance, event, args = [], extra = [], isCustom, methodName) { + let isCustomMPEvent = false; // wxcomponent 组件,传递原始 event 对象 + if (isCustom) { + // 自定义事件 + isCustomMPEvent = + event.currentTarget && + event.currentTarget.dataset && + event.currentTarget.dataset.comType === 'wx'; + if (!args.length) { + // 无参数,直接传入 event 或 detail 数组 + if (isCustomMPEvent) { + return [event]; + } + return event.detail.__args__ || event.detail; + } + } + const extraObj = processEventExtra(instance, extra, event); + const ret = []; + args.forEach(arg => { + if (arg === '$event') { + if (methodName === '__set_model' && !isCustom) { + // input v-model value + ret.push(event.target.value); + } + else { + if (isCustom && !isCustomMPEvent) { + ret.push(event.detail.__args__[0]); + } + else { + // wxcomponent 组件或内置组件 + ret.push(event); + } + } + } + else { + if (isArray(arg) && arg[0] === 'o') { + ret.push(getObjByArray(arg)); + } + else if (typeof arg === 'string' && hasOwn(extraObj, arg)) { + ret.push(extraObj[arg]); + } + else { + ret.push(arg); + } + } + }); + return ret; +} +function wrapper(event) { + event.stopPropagation = NOOP; + event.preventDefault = NOOP; + event.target = event.target || {}; + if (!hasOwn(event, 'detail')) { + event.detail = {}; + } + if (hasOwn(event, 'markerId')) { + event.detail = typeof event.detail === 'object' ? event.detail : {}; + event.detail.markerId = event.markerId; + } + if (isPlainObject(event.detail)) { + event.target = Object.assign({}, event.target, event.detail); + } + return event; +} +const ONCE = '~'; +const CUSTOM = '^'; +function matchEventType(eventType, optType) { + return (eventType === optType || + (optType === 'regionchange' && + (eventType === 'begin' || eventType === 'end'))); +} +function handleEvent(event) { + event = wrapper(event); + // [['tap',[['handle',[1,2,a]],['handle1',[1,2,a]]]]] + const dataset = (event.currentTarget || event.target).dataset; + if (!dataset) { + return console.warn('事件信息不存在'); + } + const eventOpts = (dataset.eventOpts || + dataset['event-opts']); // 支付宝 web-view 组件 dataset 非驼峰 + if (!eventOpts) { + return console.warn('事件信息不存在'); + } + // [['handle',[1,2,a]],['handle1',[1,2,a]]] + const eventType = event.type; + const ret = []; + eventOpts.forEach((eventOpt) => { + let type = eventOpt[0]; + const eventsArray = eventOpt[1]; + const isCustom = type.charAt(0) === CUSTOM; + type = isCustom ? type.slice(1) : type; + const isOnce = type.charAt(0) === ONCE; + type = isOnce ? type.slice(1) : type; + if (eventsArray && matchEventType(eventType, type)) { + eventsArray.forEach((eventArray) => { + const methodName = eventArray[0]; + if (methodName) { + let handlerCtx = this.$vm; + if (handlerCtx.$options.generic && + handlerCtx.$parent && + handlerCtx.$parent.$parent) { + // mp-weixin,mp-toutiao 抽象节点模拟 scoped slots + handlerCtx = handlerCtx.$parent.$parent; + } + if (methodName === '$emit') { + handlerCtx.$emit.apply(handlerCtx, processEventArgs(this.$vm, event, eventArray[1], eventArray[2], isCustom, methodName)); + return; + } + const handler = handlerCtx[methodName]; + if (!isFunction(handler)) { + throw new Error(` _vm.${methodName} is not a function`); + } + if (isOnce) { + if (handler.once) { + return; + } + handler.once = true; + } + ret.push(handler.apply(handlerCtx, processEventArgs(this.$vm, event, eventArray[1], eventArray[2], isCustom, methodName))); + } + }); + } + }); + if (eventType === 'input' && + ret.length === 1 && + typeof ret[0] !== 'undefined') { + return ret[0]; + } +} + +let $createComponentFn; +let $destroyComponentFn; +function $createComponent(initialVNode, options) { + if (!$createComponentFn) { + $createComponentFn = getApp().$vm.$createComponent; + } + return $createComponentFn(initialVNode, options); +} +function $destroyComponent(instance) { + if (!$destroyComponentFn) { + $destroyComponentFn = getApp().$vm.$destroyComponent; + } + return $destroyComponentFn(instance); +} + +function onAliAuthError(method, $event) { + $event.type = 'getphonenumber'; + $event.detail.errMsg = + 'getPhoneNumber:fail Error: ' + + $event.detail.errorMessage(this)[method]($event); +} +function onAliGetAuthorize(method, $event) { + my.getPhoneNumber({ + success: (res) => { + $event.type = 'getphonenumber'; + const response = JSON.parse(res.response).response; + if (response.code === '10000') { + // success + $event.detail.errMsg = 'getPhoneNumber:ok'; + $event.detail.encryptedData = res.response; + } + else { + $event.detail.errMsg = 'getPhoneNumber:fail Error: ' + res.response; + } + this[method]($event); + }, + fail: () => { + $event.type = 'getphonenumber'; + $event.detail.errMsg = 'getPhoneNumber:fail'; + this[method]($event); + } + }); +} +function parse(appOptions) { + const oldOnLaunch = appOptions.onLaunch; + appOptions.onLaunch = function onLaunch(options) { + oldOnLaunch.call(this, options); + if (!this.$vm) { + return; + } + const globalProperties = this.$vm.$app.config.globalProperties; + if (!globalProperties.$onAliAuthError) { + globalProperties.$onAliAuthError = onAliAuthError; + globalProperties.$onAliGetAuthorize = onAliGetAuthorize; + } + }; +} + +var parseAppOptions = /*#__PURE__*/Object.freeze({ + __proto__: null, + parse: parse +}); + +function handleLink(event) { + // detail 是微信,value 是百度(dipatch) + const detail = (event.detail || + event.value); + const vuePid = detail.vuePid; + let parentVm; + if (vuePid) { + parentVm = findVmByVueId(this.$vm, vuePid); + } + if (!parentVm) { + parentVm = this.$vm; + } + detail.parent = parentVm; +} + +function equal(a, b) { + if (a === b) + return true; + if (a && b && typeof a === 'object' && typeof b === 'object') { + const arrA = isArray(a); + const arrB = isArray(b); + let i, length, key; + if (arrA && arrB) { + length = a.length; + if (length !== b.length) + return false; + for (i = length; i-- !== 0;) { + if (!equal(a[i], b[i])) + return false; + } + return true; + } + if (arrA !== arrB) + return false; + const dateA = a instanceof Date; + const dateB = b instanceof Date; + if (dateA !== dateB) + return false; + if (dateA && dateB) + return a.getTime() === b.getTime(); + const regexpA = a instanceof RegExp; + const regexpB = b instanceof RegExp; + if (regexpA !== regexpB) + return false; + if (regexpA && regexpB) + return a.toString() === b.toString(); + const keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) { + return false; + } + for (i = length; i-- !== 0;) { + if (!hasOwn(b, keys[i])) + return false; + } + for (i = length; i-- !== 0;) { + key = keys[i]; + if (!equal(a[key], b[key])) + return false; + } + return true; + } + return false; +} + +const isComponent2 = my.canIUse('component2'); +const mocks = ['$id']; +const customizeRE = /:/g; +function customize(str) { + return camelize(str.replace(customizeRE, '-')); +} +function initBehavior({ properties }) { + const props = {}; + Object.keys(properties).forEach(key => { + props[key] = properties[key].value; + }); + return { + props + }; +} +function initRelation(mpInstance, detail) { + mpInstance.props.onVueInit(detail); +} +function initSpecialMethods(mpInstance) { + if (!mpInstance.$vm) { + return; + } + let path = mpInstance.is || mpInstance.route; + if (!path) { + return; + } + if (path.indexOf('/') === 0) { + path = path.substr(1); + } + const specialMethods = my.specialMethods && my.specialMethods[path]; + if (specialMethods) { + specialMethods.forEach((method) => { + if (isFunction(mpInstance.$vm[method])) { + mpInstance[method] = function (event) { + if (hasOwn(event, 'markerId')) { + event.detail = typeof event.detail === 'object' ? event.detail : {}; + event.detail.markerId = event.markerId; + } + // TODO normalizeEvent + mpInstance.$vm[method](event); + }; + } + }); + } +} +function initChildVues(mpInstance) { + // 此时需保证当前 mpInstance 已经存在 $vm + if (!mpInstance.$vm) { + return; + } + const childVues = mpInstance._$childVues; + if (childVues) { + childVues.forEach(relationOptions => { + // 父子关系 + handleLink.call(mpInstance, { + detail: relationOptions + }); + const { mpInstance: childMPInstance, createComponent } = relationOptions; + childMPInstance.$vm = createComponent(relationOptions.parent); + initSpecialMethods(childMPInstance); + if (relationOptions.parent) { + handleRef.call(relationOptions.parent.$scope, childMPInstance); + } + initChildVues(childMPInstance); + childMPInstance.$vm.$callHook('mounted'); + childMPInstance.$vm.$callHook('onReady'); + }); + } + delete mpInstance._$childVues; +} +// TODO vue3 +function handleRef(ref) { + if (!ref) { + return; + } + const refName = ref.props['data-ref']; + const refInForName = ref.props['data-ref-in-for']; + if (!refName && !refInForName) { + return; + } + const instance = this.$vm.$; + const refs = instance.refs === EMPTY_OBJ ? (instance.refs = {}) : instance.refs; + if (refName) { + refs[refName] = ref.$vm || ref; + } + else if (refInForName) { + (refs[refInForName] || (refs[refInForName] = [])).push(ref.$vm || ref); + } +} +function triggerEvent(type, detail) { + const handler = this.props[customize('on-' + type)]; + if (!handler) { + return; + } + const eventOpts = this.props['data-event-opts']; + const target = { + dataset: { + eventOpts + } + }; + handler({ + type: customize(type), + target, + currentTarget: target, + detail + }); +} +const IGNORES = ['$slots', '$scopedSlots']; +function createObserver(isDidUpdate = false) { + return function observe(props) { + const prevProps = isDidUpdate ? props : this.props; + const nextProps = isDidUpdate ? this.props : props; + if (equal(prevProps, nextProps)) { + return; + } + Object.keys(prevProps).forEach(name => { + if (IGNORES.indexOf(name) === -1) { + const prevValue = prevProps[name]; + const nextValue = nextProps[name]; + if (!isFunction(prevValue) && + !isFunction(nextValue) && + !equal(prevValue, nextValue)) { + this.$vm.$.props[name] = nextProps[name]; + } + } + }); + }; +} +const handleLink$1 = (function () { + if (isComponent2) { + return function handleLink$1(detail) { + return handleLink.call(this, { + detail + }); + }; + } + return function handleLink$1(detail) { + if (this.$vm && this.$vm.$.isMounted) { + // 父已初始化 + return handleLink.call(this, { + detail + }); + } + (this._$childVues || (this._$childVues = [])).unshift(detail); + }; +})(); +function createVueComponent(mpType, mpInstance, vueOptions, parent) { + return $createComponent({ + type: vueOptions, + props: mpInstance.props + }, { + mpType, + mpInstance, + parentComponent: parent && parent.$, + onBeforeSetup(instance, options) { + initMocks(instance, mpInstance, mocks); + initComponentInstance(instance, options); + } + }); +} + +function createPage(vueOptions) { + vueOptions = vueOptions.default || vueOptions; + const pageOptions = { + onLoad(args) { + // 初始化 vue 实例 + this.$vm = createVueComponent('page', this, vueOptions); + initSpecialMethods(this); + this.$vm.$callHook('onLoad', args); + }, + onReady() { + initChildVues(this); + this.$vm.$callHook('mounted'); + this.$vm.$callHook('onReady'); + }, + onUnload() { + if (this.$vm) { + this.$vm.$callHook('onUnload'); + $destroyComponent(this.$vm); + } + }, + events: { + // 支付宝小程序有些页面事件只能放在events下 + onBack() { + this.$vm.$callHook('onBackPress'); + } + }, + __r: handleRef, + __e: handleEvent, + __l: handleLink$1 + }; + if (__VUE_OPTIONS_API__) { + pageOptions.data = initData(vueOptions); + } + initHooks(pageOptions, PAGE_HOOKS); + initUnknownHooks(pageOptions, vueOptions); + return Page(pageOptions); +} + +function initComponentProps(rawProps) { + const propertiesOptions = { + properties: {} + }; + initProps(propertiesOptions, rawProps, false); + const properties = propertiesOptions.properties; + const props = { + onVueInit: function () { } + }; + Object.keys(properties).forEach(key => { + if (key !== 'vueSlots') { + props[key] = properties[key].value; + } + }); + return props; +} +function initVm(mpInstance, createComponent) { + if (mpInstance.$vm) { + return; + } + const properties = mpInstance.props; + initVueIds(properties.vueId, mpInstance); + const relationOptions = { + vuePid: mpInstance._$vuePid, + mpInstance, + createComponent + }; + if (isComponent2) { + // 处理父子关系 + initRelation(mpInstance, relationOptions); + // 初始化 vue 实例 + mpInstance.$vm = createComponent(relationOptions.parent); + } + else { + // 处理父子关系 + initRelation(mpInstance, relationOptions); + if (relationOptions.parent) { + // 父组件已经初始化,直接初始化子,否则放到父组件的 didMount 中处理 + // 初始化 vue 实例 + mpInstance.$vm = createComponent(relationOptions.parent); + handleRef.call(relationOptions.parent.$scope, mpInstance); + initChildVues(mpInstance); + mpInstance.$vm.$callHook('mounted'); + } + } +} +function createComponent(vueOptions) { + vueOptions = vueOptions.default || vueOptions; + const mpComponentOptions = { + props: initComponentProps(vueOptions.props), + didMount() { + const createComponent = (parent) => { + return createVueComponent('component', this, vueOptions, parent); + }; + if (my.dd) { + // 钉钉小程序底层基础库有 bug,组件嵌套使用时,在 didMount 中无法及时调用 props 中的方法 + setTimeout(() => { + initVm(this, createComponent); + }, 4); + } + else { + initVm(this, createComponent); + } + initSpecialMethods(this); + if (isComponent2) { + this.$vm.$callHook('mounted'); + } + }, + didUnmount() { + $destroyComponent(this.$vm); + }, + methods: { + __r: handleRef, + __e: handleEvent, + __l: handleLink$1, + triggerEvent + } + }; + if (__VUE_OPTIONS_API__) { + mpComponentOptions.data = initData(vueOptions); + mpComponentOptions.mixins = initBehaviors(vueOptions, initBehavior); + } + if (isComponent2) { + mpComponentOptions.onInit = function onInit() { + initVm(this, (parent) => { + return createVueComponent('component', this, vueOptions, parent); + }); + }; + mpComponentOptions.deriveDataFromProps = createObserver(); + } + else { + mpComponentOptions.didUpdate = createObserver(true); + } + return Component(mpComponentOptions); +} + +const createApp = initCreateApp(parseAppOptions); + +export { createApp, createComponent, createPage }; diff --git a/packages/uni-mp-alipay/lib/uni.compiler.js b/packages/uni-mp-alipay/lib/uni.compiler.js index ba74a36a8186caeffabb7384bfca0967deb699b9..69ebd4255ba2e973bf9f20b82b473f06a9f89d8a 100644 --- a/packages/uni-mp-alipay/lib/uni.compiler.js +++ b/packages/uni-mp-alipay/lib/uni.compiler.js @@ -126,7 +126,7 @@ module.exports = { Identifier (path) { const node = path.node const name = node.name - if (names.includes(name) && path.key !== 'key' && path.key !== 'property' && !(path.scope && path.scope.hasBinding(name))) { + if (names.includes(name) && path.key !== 'key' && (path.key !== 'property' || path.parent.computed) && !(path.scope && path.scope.hasBinding(name))) { path.replaceWithSourceString(`${paramName}.${name}`) } } diff --git a/packages/uni-mp-baidu/dist/uni.api.esm.js b/packages/uni-mp-baidu/dist/uni.api.esm.js new file mode 100644 index 0000000000000000000000000000000000000000..c4450efaaa3df468932732272a989f2d205531c6 --- /dev/null +++ b/packages/uni-mp-baidu/dist/uni.api.esm.js @@ -0,0 +1,575 @@ +import { isArray, isPromise, isFunction, isPlainObject, hasOwn, isString } from '@vue/shared'; + +const EPS = 1e-4; +const BASE_DEVICE_WIDTH = 750; +let isIOS = false; +let deviceWidth = 0; +let deviceDPR = 0; +function checkDeviceWidth() { + const { platform, pixelRatio, windowWidth } = swan.getSystemInfoSync(); + deviceWidth = windowWidth; + deviceDPR = pixelRatio; + isIOS = platform === 'ios'; +} +function upx2px(number, newDeviceWidth) { + if (deviceWidth === 0) { + checkDeviceWidth(); + } + number = Number(number); + if (number === 0) { + return 0; + } + let result = (number / BASE_DEVICE_WIDTH) * (newDeviceWidth || deviceWidth); + if (result < 0) { + result = -result; + } + result = Math.floor(result + EPS); + if (result === 0) { + if (deviceDPR === 1 || !isIOS) { + result = 1; + } + else { + result = 0.5; + } + } + return number < 0 ? -result : result; +} + +var HOOKS; +(function (HOOKS) { + HOOKS["INVOKE"] = "invoke"; + HOOKS["SUCCESS"] = "success"; + HOOKS["FAIL"] = "fail"; + HOOKS["COMPLETE"] = "complete"; + HOOKS["RETURN_VALUE"] = "returnValue"; +})(HOOKS || (HOOKS = {})); +const globalInterceptors = {}; +const scopedInterceptors = {}; +function wrapperHook(hook) { + return function (data) { + return hook(data) || data; + }; +} +function queue(hooks, data) { + let promise = false; + for (let i = 0; i < hooks.length; i++) { + const hook = hooks[i]; + if (promise) { + promise = Promise.resolve(wrapperHook(hook)); + } + else { + const res = hook(data); + if (isPromise(res)) { + promise = Promise.resolve(res); + } + if (res === false) { + return { + then() { }, + catch() { } + }; + } + } + } + return (promise || { + then(callback) { + return callback(data); + }, + catch() { } + }); +} +function wrapperOptions(interceptors, options = {}) { + [HOOKS.SUCCESS, HOOKS.FAIL, HOOKS.COMPLETE].forEach(name => { + const hooks = interceptors[name]; + if (!isArray(hooks)) { + return; + } + const oldCallback = options[name]; + options[name] = function callbackInterceptor(res) { + queue(hooks, res).then((res) => { + return (isFunction(oldCallback) && oldCallback(res)) || res; + }); + }; + }); + return options; +} +function wrapperReturnValue(method, returnValue) { + const returnValueHooks = []; + if (isArray(globalInterceptors.returnValue)) { + returnValueHooks.push(...globalInterceptors.returnValue); + } + const interceptor = scopedInterceptors[method]; + if (interceptor && isArray(interceptor.returnValue)) { + returnValueHooks.push(...interceptor.returnValue); + } + returnValueHooks.forEach(hook => { + returnValue = hook(returnValue) || returnValue; + }); + return returnValue; +} +function getApiInterceptorHooks(method) { + const interceptor = Object.create(null); + Object.keys(globalInterceptors).forEach(hook => { + if (hook !== 'returnValue') { + interceptor[hook] = globalInterceptors[hook].slice(); + } + }); + const scopedInterceptor = scopedInterceptors[method]; + if (scopedInterceptor) { + Object.keys(scopedInterceptor).forEach(hook => { + if (hook !== 'returnValue') { + interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]); + } + }); + } + return interceptor; +} +function invokeApi(method, api, options, ...params) { + const interceptor = getApiInterceptorHooks(method); + if (interceptor && Object.keys(interceptor).length) { + if (isArray(interceptor.invoke)) { + const res = queue(interceptor.invoke, options); + return res.then(options => { + return api(wrapperOptions(interceptor, options), ...params); + }); + } + else { + return api(wrapperOptions(interceptor, options), ...params); + } + } + return api(options, ...params); +} + +function mergeInterceptorHook(interceptors, interceptor) { + Object.keys(interceptor).forEach(hook => { + if (isFunction(interceptor[hook])) { + interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]); + } + }); +} +function removeInterceptorHook(interceptors, interceptor) { + if (!interceptors || !interceptor) { + return; + } + Object.keys(interceptor).forEach(hook => { + if (isFunction(interceptor[hook])) { + removeHook(interceptors[hook], interceptor[hook]); + } + }); +} +function mergeHook(parentVal, childVal) { + const res = childVal + ? parentVal + ? parentVal.concat(childVal) + : isArray(childVal) + ? childVal + : [childVal] + : parentVal; + return res ? dedupeHooks(res) : res; +} +function dedupeHooks(hooks) { + const res = []; + for (let i = 0; i < hooks.length; i++) { + if (res.indexOf(hooks[i]) === -1) { + res.push(hooks[i]); + } + } + return res; +} +function removeHook(hooks, hook) { + if (!hooks) { + return; + } + const index = hooks.indexOf(hook); + if (index !== -1) { + hooks.splice(index, 1); + } +} +function addInterceptor(method, interceptor) { + if (typeof method === 'string' && isPlainObject(interceptor)) { + mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); + } + else if (isPlainObject(method)) { + mergeInterceptorHook(globalInterceptors, method); + } +} +function removeInterceptor(method, interceptor) { + if (typeof method === 'string') { + if (isPlainObject(interceptor)) { + removeInterceptorHook(scopedInterceptors[method], interceptor); + } + else { + delete scopedInterceptors[method]; + } + } + else if (isPlainObject(method)) { + removeInterceptorHook(globalInterceptors, method); + } +} + +const SYNC_API_RE = /^\$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; +const CONTEXT_API_RE = /^create|Manager$/; +// Context例外情况 +const CONTEXT_API_RE_EXC = ['createBLEConnection']; +// 同步例外情况 +const ASYNC_API = ['createBLEConnection']; +const CALLBACK_API_RE = /^on|^off/; +function isContextApi(name) { + return CONTEXT_API_RE.test(name) && CONTEXT_API_RE_EXC.indexOf(name) === -1; +} +function isSyncApi(name) { + return SYNC_API_RE.test(name) && ASYNC_API.indexOf(name) === -1; +} +function isCallbackApi(name) { + return CALLBACK_API_RE.test(name) && name !== 'onPush'; +} +function handlePromise(promise) { + if (!__UNI_PROMISE_API__) { + return promise; + } + return promise + .then(data => { + return [null, data]; + }) + .catch(err => [err]); +} +function shouldPromise(name) { + if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) { + return false; + } + return true; +} +/* eslint-disable no-extend-native */ +if (!Promise.prototype.finally) { + Promise.prototype.finally = function (onfinally) { + const promise = this.constructor; + return this.then(value => promise.resolve(onfinally && onfinally()).then(() => value), reason => promise.resolve(onfinally && onfinally()).then(() => { + throw reason; + })); + }; +} +function promisify(name, api) { + if (!shouldPromise(name)) { + return api; + } + if (!isFunction(api)) { + return api; + } + return function promiseApi(options = {}, ...params) { + if (isFunction(options.success) || + isFunction(options.fail) || + isFunction(options.complete)) { + return wrapperReturnValue(name, invokeApi(name, api, options, ...params)); + } + return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => { + invokeApi(name, api, Object.assign({}, options, { + success: resolve, + fail: reject + }), ...params); + }))); + }; +} + +const CALLBACKS = ['success', 'fail', 'cancel', 'complete']; +function initWrapper(protocols) { + function processCallback(methodName, method, returnValue) { + return function (res) { + return method(processReturnValue(methodName, res, returnValue)); + }; + } + function processArgs(methodName, fromArgs, argsOption = {}, returnValue = {}, keepFromArgs = false) { + if (isPlainObject(fromArgs)) { + // 一般 api 的参数解析 + const toArgs = (keepFromArgs === true ? fromArgs : {}); // returnValue 为 false 时,说明是格式化返回值,直接在返回值对象上修改赋值 + if (isFunction(argsOption)) { + argsOption = argsOption(fromArgs, toArgs) || {}; + } + for (const key in fromArgs) { + if (hasOwn(argsOption, key)) { + let keyOption = argsOption[key]; + if (isFunction(keyOption)) { + keyOption = keyOption(fromArgs[key], fromArgs, toArgs); + } + if (!keyOption) { + // 不支持的参数 + console.warn(`百度小程序 ${methodName} 暂不支持 ${key}`); + } + else if (isString(keyOption)) { + // 重写参数 key + toArgs[keyOption] = fromArgs[key]; + } + else if (isPlainObject(keyOption)) { + // {name:newName,value:value}可重新指定参数 key:value + toArgs[keyOption.name ? keyOption.name : key] = keyOption.value; + } + } + else if (CALLBACKS.indexOf(key) !== -1) { + const callback = fromArgs[key]; + if (isFunction(callback)) { + toArgs[key] = processCallback(methodName, callback, returnValue); + } + } + else { + if (!keepFromArgs && !hasOwn(toArgs, key)) { + toArgs[key] = fromArgs[key]; + } + } + } + return toArgs; + } + else if (isFunction(fromArgs)) { + fromArgs = processCallback(methodName, fromArgs, returnValue); + } + return fromArgs; + } + function processReturnValue(methodName, res, returnValue, keepReturnValue = false) { + if (isFunction(protocols.returnValue)) { + // 处理通用 returnValue + res = protocols.returnValue(methodName, res); + } + return processArgs(methodName, res, returnValue, {}, keepReturnValue); + } + return function wrapper(methodName, method) { + if (!hasOwn(protocols, methodName)) { + return method; + } + const protocol = protocols[methodName]; + if (!protocol) { + // 暂不支持的 api + return function () { + console.error(`百度小程序 暂不支持${methodName}`); + }; + } + return function (arg1, arg2) { + // 目前 api 最多两个参数 + let options = protocol; + if (isFunction(protocol)) { + options = protocol(arg1); + } + arg1 = processArgs(methodName, arg1, options.args, options.returnValue); + const args = [arg1]; + if (typeof arg2 !== 'undefined') { + args.push(arg2); + } + const returnValue = swan[options.name || methodName].apply(swan, args); + if (isSyncApi(methodName)) { + // 同步 api + return processReturnValue(methodName, returnValue, options.returnValue, isContextApi(methodName)); + } + return returnValue; + }; + }; +} + +const baseApis = { upx2px, addInterceptor, removeInterceptor }; +function initUni(api, protocols) { + const wrapper = initWrapper(protocols); + const UniProxyHandlers = { + get(target, key) { + if (hasOwn(target, key)) { + return target[key]; + } + if (hasOwn(api, key)) { + return promisify(key, api[key]); + } + if (hasOwn(baseApis, key)) { + return promisify(key, baseApis[key]); + } + // event-api + // provider-api? + return promisify(key, wrapper(key, swan[key])); + } + }; + return new Proxy({}, UniProxyHandlers); +} + +function initGetProvider(providers) { + return function getProvider({ service, success, fail, complete }) { + let res; + if (providers[service]) { + res = { + errMsg: 'getProvider:ok', + service, + provider: providers[service] + }; + isFunction(success) && success(res); + } + else { + res = { + errMsg: 'getProvider:fail:服务[' + service + ']不存在' + }; + isFunction(fail) && fail(res); + } + isFunction(complete) && complete(res); + }; +} + +const previewImage = { + args(fromArgs, toArgs) { + let currentIndex = parseInt(fromArgs.current); + if (isNaN(currentIndex)) { + return; + } + const urls = fromArgs.urls; + if (!isArray(urls)) { + return; + } + const len = urls.length; + if (!len) { + return; + } + if (currentIndex < 0) { + currentIndex = 0; + } + else if (currentIndex >= len) { + currentIndex = len - 1; + } + if (currentIndex > 0) { + toArgs.current = urls[currentIndex]; + toArgs.urls = urls.filter((item, index) => index < currentIndex ? item !== urls[currentIndex] : true); + } + else { + toArgs.current = urls[0]; + } + return { + indicator: false, + loop: false + }; + } +}; +function addSafeAreaInsets(fromRes, toRes) { + if (fromRes.safeArea) { + const safeArea = fromRes.safeArea; + toRes.safeAreaInsets = { + top: safeArea.top, + left: safeArea.left, + right: fromRes.windowWidth - safeArea.right, + bottom: fromRes.windowHeight - safeArea.bottom + }; + } +} +const getSystemInfo = { + returnValue: addSafeAreaInsets +}; +const getSystemInfoSync = getSystemInfo; + +const getProvider = initGetProvider({ + oauth: ['baidu'], + share: ['baidu'], + payment: ['baidu'], + push: ['baidu'] +}); +function requestPayment(params) { + let parseError = false; + if (typeof params.orderInfo === 'string') { + try { + params.orderInfo = JSON.parse(params.orderInfo); + } + catch (e) { + parseError = true; + } + } + if (parseError) { + params.fail && + params.fail({ + errMsg: 'requestPayment:fail: 参数 orderInfo 数据结构不正确,参考:https://uniapp.dcloud.io/api/plugins/payment?id=orderinfo' + }); + } + else { + swan.requestPolymerPayment(params); + } +} + +var shims = /*#__PURE__*/Object.freeze({ + __proto__: null, + getProvider: getProvider, + requestPayment: requestPayment +}); + +function createTodoMethod(contextName, methodName) { + return function unsupported() { + console.error(`百度小程序 ${contextName}暂不支持${methodName}`); + }; +} +const request = { + args() { + // TODO + // data 不支持 ArrayBuffer + // method 不支持 TRACE, CONNECT + return { + method: 'method', + dataType(type) { + return { + name: 'dataType', + value: type === 'json' ? type : 'string' + }; + } + }; + } +}; +const connectSocket = { + args: { + method: false + } +}; +const getRecorderManager = { + returnValue(fromRes, toRes) { + toRes.onFrameRecorded = createTodoMethod('RecorderManager', 'onFrameRecorded'); + } +}; +const getBackgroundAudioManager = { + returnValue(fromRes, toRes) { + toRes.onPrev = createTodoMethod('BackgroundAudioManager', 'onPrev'); + toRes.onNext = createTodoMethod('BackgroundAudioManager', 'onNext'); + } +}; +const scanCode = { + args: { + onlyFromCamera: false, + scanType: false + } +}; +const navigateToMiniProgram = { + name: 'navigateToSmartProgram', + args: { + appId: 'appKey', + envVersion: false + } +}; +const navigateBackMiniProgram = { + name: 'navigateBackSmartProgram' +}; +const showShareMenu = { + name: 'openShare' +}; +const getAccountInfoSync = { + name: 'getEnvInfoSync', + returnValue(fromRes, toRes) { + toRes.miniProgram = { + appId: fromRes.appKey + }; + toRes.plugin = { + appId: '', + version: fromRes.sdkVersion + }; + } +}; + +var protocols = /*#__PURE__*/Object.freeze({ + __proto__: null, + request: request, + connectSocket: connectSocket, + getRecorderManager: getRecorderManager, + getBackgroundAudioManager: getBackgroundAudioManager, + scanCode: scanCode, + navigateToMiniProgram: navigateToMiniProgram, + navigateBackMiniProgram: navigateBackMiniProgram, + showShareMenu: showShareMenu, + getAccountInfoSync: getAccountInfoSync, + previewImage: previewImage, + getSystemInfo: getSystemInfo, + getSystemInfoSync: getSystemInfoSync +}); + +var index = initUni(shims, protocols); + +export default index; diff --git a/packages/uni-mp-baidu/dist/uni.mp.esm.js b/packages/uni-mp-baidu/dist/uni.mp.esm.js new file mode 100644 index 0000000000000000000000000000000000000000..d7b14cb0cd5df75b7a74f5795af3828354bed269 --- /dev/null +++ b/packages/uni-mp-baidu/dist/uni.mp.esm.js @@ -0,0 +1,1019 @@ +import { isArray, hasOwn, toNumber, isPlainObject, isObject, isFunction, extend, NOOP, camelize } from '@vue/shared'; + +function setModel(target, key, value, modifiers) { + if (isArray(modifiers)) { + if (modifiers.indexOf('trim') !== -1) { + value = value.trim(); + } + if (modifiers.indexOf('number') !== -1) { + value = toNumber(value); + } + } + if (!target) { + target = this; + } + target[key] = value; +} +function setSync(target, key, value) { + if (!target) { + target = this; + } + target[key] = value; +} +function getOrig(data) { + if (isPlainObject(data)) { + return data.$orig || data; + } + return data; +} +function map(val, iteratee) { + let ret, i, l, keys, key; + if (isArray(val)) { + ret = new Array(val.length); + for (i = 0, l = val.length; i < l; i++) { + ret[i] = iteratee(val[i], i); + } + return ret; + } + else if (isObject(val)) { + keys = Object.keys(val); + ret = Object.create(null); + for (i = 0, l = keys.length; i < l; i++) { + key = keys[i]; + ret[key] = iteratee(val[key], key, i); + } + return ret; + } + return []; +} +const MP_METHODS = [ + 'createSelectorQuery', + 'createIntersectionObserver', + 'selectAllComponents', + 'selectComponent' +]; +function hasHook(name) { + const hooks = this.$[name]; + if (hooks && hooks.length) { + return true; + } + return false; +} +function callHook(name, args) { + if (name === 'mounted') { + callHook.call(this, 'bm'); // beforeMount + this.$.isMounted = true; + name = 'm'; + } + const hooks = this.$[name]; + let ret; + if (hooks) { + for (let i = 0; i < hooks.length; i++) { + ret = hooks[i](args); + } + } + return ret; +} +function createEmitFn(oldEmit, ctx) { + return function emit(event, ...args) { + if (ctx.$scope && event) { + ctx.$scope.triggerEvent(event, { __args__: args }); + } + return oldEmit.apply(this, [event, ...args]); + }; +} +function set(target, key, val) { + return (target[key] = val); +} +function initBaseInstance(instance, options) { + const ctx = instance.ctx; + // mp + ctx.mpType = options.mpType; // @deprecated + ctx.$mpType = options.mpType; + ctx.$scope = options.mpInstance; + // TODO @deprecated + ctx.$mp = {}; + ctx._self = {}; + // $vm + ctx.$scope.$vm = instance.proxy; + // slots + { + instance.slots = {}; + if (isArray(options.slots) && options.slots.length) { + options.slots.forEach(name => { + instance.slots[name] = true; + }); + } + } + if (__VUE_OPTIONS_API__) { + // $set + ctx.$set = set; + } + // $emit + instance.emit = createEmitFn(instance.emit, ctx); + // $callHook + ctx.$hasHook = hasHook; + ctx.$callHook = callHook; +} +function initComponentInstance(instance, options) { + initBaseInstance(instance, options); + const ctx = instance.ctx; + MP_METHODS.forEach(method => { + ctx[method] = function (...args) { + const mpInstance = ctx.$scope; + if (mpInstance && mpInstance[method]) { + return mpInstance[method].apply(mpInstance, args); + } + }; + }); + // TODO other + ctx.__set_model = setModel; + ctx.__set_sync = setSync; + ctx.__get_orig = getOrig; + // TODO + // ctx.__get_style = getStyle + ctx.__map = map; +} +function initMocks(instance, mpInstance, mocks) { + const ctx = instance.ctx; + mocks.forEach(mock => { + if (hasOwn(mpInstance, mock)) { + ctx[mock] = mpInstance[mock]; + } + }); +} + +const PAGE_HOOKS = [ + 'onLoad', + 'onShow', + // 'onReady', // lifetimes.ready + 'onHide', + 'onUnload', + 'onResize', + // 'onPageScroll', // 影响性能,开发者手动注册 + 'onTabItemTap', + 'onReachBottom', + 'onPullDownRefresh', + // 'onShareTimeline', // 右上角菜单,开发者手动注册 + 'onAddToFavorites' + // 'onShareAppMessage' // 右上角菜单,开发者手动注册 +]; +function findHooks(vueOptions, hooks = new Set()) { + if (vueOptions) { + Object.keys(vueOptions).forEach(name => { + if (name.indexOf('on') === 0 && isFunction(vueOptions[name])) { + hooks.add(name); + } + }); + const { extends: extendsOptions, mixins } = vueOptions; + if (mixins) { + mixins.forEach(mixin => findHooks(mixin, hooks)); + } + if (extendsOptions) { + findHooks(extendsOptions, hooks); + } + } + return hooks; +} +function initHook(mpOptions, hook, excludes) { + if (excludes.indexOf(hook) === -1 && !hasOwn(mpOptions, hook)) { + mpOptions[hook] = function (args) { + return this.$vm && this.$vm.$callHook(hook, args); + }; + } +} +const EXCLUDE_HOOKS = ['onReady']; +function initHooks(mpOptions, hooks, excludes = EXCLUDE_HOOKS) { + hooks.forEach(hook => initHook(mpOptions, hook, excludes)); +} +function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) { + findHooks(vueOptions).forEach(hook => initHook(mpOptions, hook, excludes)); +} + +const HOOKS = [ + 'onShow', + 'onHide', + 'onError', + 'onThemeChange', + 'onPageNotFound', + 'onUnhandledRejection' +]; +function parseApp(instance, parseAppOptions) { + const internalInstance = instance.$; + const appOptions = { + globalData: (instance.$options && instance.$options.globalData) || {}, + $vm: instance, + onLaunch(options) { + const ctx = internalInstance.ctx; + if (this.$vm && ctx.$callHook) { + // 已经初始化过了,主要是为了百度,百度 onShow 在 onLaunch 之前 + return; + } + initBaseInstance(internalInstance, { + mpType: 'app', + mpInstance: this, + slots: [] + }); + ctx.globalData = this.globalData; + instance.$callHook('onLaunch', options); + } + }; + const vueOptions = instance.$.type; + initHooks(appOptions, HOOKS); + initUnknownHooks(appOptions, vueOptions); + if (__VUE_OPTIONS_API__) { + const methods = vueOptions.methods; + methods && extend(appOptions, methods); + } + if (parseAppOptions) { + parseAppOptions.parse(appOptions); + } + return appOptions; +} +function initCreateApp(parseAppOptions) { + return function createApp(vm) { + return App(parseApp(vm, parseAppOptions)); + }; +} + +function initBehavior(options) { + return Behavior(options); +} +function initVueIds(vueIds, mpInstance) { + if (!vueIds) { + return; + } + const ids = vueIds.split(','); + const len = ids.length; + if (len === 1) { + mpInstance._$vueId = ids[0]; + } + else if (len === 2) { + mpInstance._$vueId = ids[0]; + mpInstance._$vuePid = ids[1]; + } +} +const EXTRAS = ['externalClasses']; +function initExtraOptions(miniProgramComponentOptions, vueOptions) { + EXTRAS.forEach(name => { + if (hasOwn(vueOptions, name)) { + miniProgramComponentOptions[name] = vueOptions[name]; + } + }); +} +function initWxsCallMethods(methods, wxsCallMethods) { + if (!isArray(wxsCallMethods)) { + return; + } + wxsCallMethods.forEach((callMethod) => { + methods[callMethod] = function (args) { + return this.$vm[callMethod](args); + }; + }); +} +function initRefs(instance, mpInstance) { + Object.defineProperty(instance, 'refs', { + get() { + const $refs = {}; + const components = mpInstance.selectAllComponents('.vue-ref'); + components.forEach(component => { + const ref = component.dataset.ref; + $refs[ref] = component.$vm || component; + }); + const forComponents = mpInstance.selectAllComponents('.vue-ref-in-for'); + forComponents.forEach(component => { + const ref = component.dataset.ref; + if (!$refs[ref]) { + $refs[ref] = []; + } + $refs[ref].push(component.$vm || component); + }); + return $refs; + } + }); +} +function findVmByVueId(instance, vuePid) { + // TODO vue3 中 没有 $children + const $children = instance.$children; + // 优先查找直属(反向查找:https://github.com/dcloudio/uni-app/issues/1200) + for (let i = $children.length - 1; i >= 0; i--) { + const childVm = $children[i]; + if (childVm.$scope._$vueId === vuePid) { + return childVm; + } + } + // 反向递归查找 + let parentVm; + for (let i = $children.length - 1; i >= 0; i--) { + parentVm = findVmByVueId($children[i], vuePid); + if (parentVm) { + return parentVm; + } + } +} + +const PROP_TYPES = [String, Number, Boolean, Object, Array, null]; +function createObserver(name) { + return function observer(newVal) { + if (this.$vm) { + this.$vm.$.props[name] = newVal; // 为了触发其他非 render watcher + } + }; +} +function parsePropType(key, type, defaultValue) { + // [String]=>String + if (isArray(type) && type.length === 1) { + return type[0]; + } + { + if ( + // [String,Boolean]=>Boolean + defaultValue === false && + isArray(type) && + type.length === 2 && + type.indexOf(String) !== -1 && + type.indexOf(Boolean) !== -1) { + return Boolean; + } + } + return type; +} +function initDefaultProps(isBehavior = false) { + const properties = {}; + if (!isBehavior) { + properties.vueId = { + type: String, + value: '' + }; + // 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots + properties.vueSlots = { + type: null, + value: [], + observer: function (newVal) { + const $slots = Object.create(null); + newVal.forEach((slotName) => { + $slots[slotName] = true; + }); + this.setData({ + $slots + }); + } + }; + } + return properties; +} +function createProperty(key, prop) { + prop.observer = createObserver(key); + return prop; +} +function initProps(mpComponentOptions, rawProps, isBehavior = false) { + const properties = initDefaultProps(isBehavior); + if (isArray(rawProps)) { + rawProps.forEach(key => { + properties[key] = createProperty(key, { + type: null + }); + }); + } + else if (isPlainObject(rawProps)) { + Object.keys(rawProps).forEach(key => { + const opts = rawProps[key]; + if (isPlainObject(opts)) { + // title:{type:String,default:''} + let value = opts.default; + if (isFunction(value)) { + value = value(); + } + const type = opts.type; + opts.type = parsePropType(key, type, value); + properties[key] = createProperty(key, { + type: PROP_TYPES.indexOf(type) !== -1 ? type : null, + value + }); + } + else { + // content:String + const type = parsePropType(key, opts, null); + properties[key] = createProperty(key, { + type: PROP_TYPES.indexOf(type) !== -1 ? type : null + }); + } + }); + } + mpComponentOptions.properties = properties; +} + +function initData(vueOptions) { + let data = vueOptions.data || {}; + if (typeof data === 'function') { + try { + const appConfig = getApp().$vm.$.appContext + .config; + data = data.call(appConfig.globalProperties); + } + catch (e) { + if (process.env.VUE_APP_DEBUG) { + console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data, e); + } + } + } + else { + try { + // 对 data 格式化 + data = JSON.parse(JSON.stringify(data)); + } + catch (e) { } + } + if (!isPlainObject(data)) { + data = {}; + } + return data; +} +function initBehaviors(vueOptions, initBehavior) { + const vueBehaviors = vueOptions.behaviors; + const vueExtends = vueOptions.extends; + const vueMixins = vueOptions.mixins; + let vueProps = vueOptions.props; + if (!vueProps) { + vueOptions.props = vueProps = []; + } + const behaviors = []; + if (isArray(vueBehaviors)) { + vueBehaviors.forEach(behavior => { + behaviors.push(behavior.replace('uni://', `${__PLATFORM_PREFIX__}://`)); + if (behavior === 'uni://form-field') { + if (isArray(vueProps)) { + vueProps.push('name'); + vueProps.push('value'); + } + else { + vueProps.name = { + type: String, + default: '' + }; + vueProps.value = { + type: [String, Number, Boolean, Array, Object, Date], + default: '' + }; + } + } + }); + } + if (isPlainObject(vueExtends) && vueExtends.props) { + const behavior = {}; + initProps(behavior, vueExtends.props, true); + behaviors.push(initBehavior(behavior)); + } + if (isArray(vueMixins)) { + vueMixins.forEach(vueMixin => { + if (isPlainObject(vueMixin) && vueMixin.props) { + const behavior = {}; + initProps(behavior, vueMixin.props, true); + behaviors.push(initBehavior(behavior)); + } + }); + } + return behaviors; +} +function applyOptions(componentOptions, vueOptions, initBehavior) { + componentOptions.data = initData(vueOptions); + componentOptions.behaviors = initBehaviors(vueOptions, initBehavior); +} + +function getValue(obj, path) { + const parts = path.split('.'); + let key = parts[0]; + if (key.indexOf('__$n') === 0) { + //number index + key = parseInt(key.replace('__$n', '')); + } + if (parts.length === 1) { + return obj[key]; + } + return getValue(obj[key], parts.slice(1).join('.')); +} +function getExtraValue(instance, dataPathsArray) { + let context = instance; + dataPathsArray.forEach(dataPathArray => { + const dataPath = dataPathArray[0]; + const value = dataPathArray[2]; + if (dataPath || typeof value !== 'undefined') { + // ['','',index,'disable'] + const propPath = dataPathArray[1]; + const valuePath = dataPathArray[3]; + let vFor; + if (Number.isInteger(dataPath)) { + vFor = dataPath; + } + else if (!dataPath) { + vFor = context; + } + else if (typeof dataPath === 'string' && dataPath) { + if (dataPath.indexOf('#s#') === 0) { + vFor = dataPath.substr(3); + } + else { + vFor = getValue(context, dataPath); + } + } + if (Number.isInteger(vFor)) { + context = value; + } + else if (!propPath) { + context = vFor[value]; + } + else { + if (isArray(vFor)) { + context = vFor.find(vForItem => { + return getValue(vForItem, propPath) === value; + }); + } + else if (isPlainObject(vFor)) { + context = Object.keys(vFor).find(vForKey => { + return getValue(vFor[vForKey], propPath) === value; + }); + } + else { + console.error('v-for 暂不支持循环数据:', vFor); + } + } + if (valuePath) { + context = getValue(context, valuePath); + } + } + }); + return context; +} +function processEventExtra(instance, extra, event) { + const extraObj = {}; + if (isArray(extra) && extra.length) { + /** + *[ + * ['data.items', 'data.id', item.data.id], + * ['metas', 'id', meta.id] + *], + *[ + * ['data.items', 'data.id', item.data.id], + * ['metas', 'id', meta.id] + *], + *'test' + */ + extra.forEach((dataPath, index) => { + if (typeof dataPath === 'string') { + if (!dataPath) { + // model,prop.sync + extraObj['$' + index] = instance; + } + else { + if (dataPath === '$event') { + // $event + extraObj['$' + index] = event; + } + else if (dataPath === 'arguments') { + if (event.detail && event.detail.__args__) { + extraObj['$' + index] = event.detail.__args__; + } + else { + extraObj['$' + index] = [event]; + } + } + else if (dataPath.indexOf('$event.') === 0) { + // $event.target.value + extraObj['$' + index] = getValue(event, dataPath.replace('$event.', '')); + } + else { + extraObj['$' + index] = getValue(instance, dataPath); + } + } + } + else { + extraObj['$' + index] = getExtraValue(instance, dataPath); + } + }); + } + return extraObj; +} +function getObjByArray(arr) { + const obj = {}; + for (let i = 1; i < arr.length; i++) { + const element = arr[i]; + obj[element[0]] = element[1]; + } + return obj; +} +function processEventArgs(instance, event, args = [], extra = [], isCustom, methodName) { + let isCustomMPEvent = false; // wxcomponent 组件,传递原始 event 对象 + if (isCustom) { + // 自定义事件 + isCustomMPEvent = + event.currentTarget && + event.currentTarget.dataset && + event.currentTarget.dataset.comType === 'wx'; + if (!args.length) { + // 无参数,直接传入 event 或 detail 数组 + if (isCustomMPEvent) { + return [event]; + } + return event.detail.__args__ || event.detail; + } + } + const extraObj = processEventExtra(instance, extra, event); + const ret = []; + args.forEach(arg => { + if (arg === '$event') { + if (methodName === '__set_model' && !isCustom) { + // input v-model value + ret.push(event.target.value); + } + else { + if (isCustom && !isCustomMPEvent) { + ret.push(event.detail.__args__[0]); + } + else { + // wxcomponent 组件或内置组件 + ret.push(event); + } + } + } + else { + if (isArray(arg) && arg[0] === 'o') { + ret.push(getObjByArray(arg)); + } + else if (typeof arg === 'string' && hasOwn(extraObj, arg)) { + ret.push(extraObj[arg]); + } + else { + ret.push(arg); + } + } + }); + return ret; +} +function wrapper(event) { + event.stopPropagation = NOOP; + event.preventDefault = NOOP; + event.target = event.target || {}; + if (!hasOwn(event, 'detail')) { + event.detail = {}; + } + if (hasOwn(event, 'markerId')) { + event.detail = typeof event.detail === 'object' ? event.detail : {}; + event.detail.markerId = event.markerId; + } + { + // mp-baidu,checked=>value + if (isPlainObject(event.detail) && + hasOwn(event.detail, 'checked') && + !hasOwn(event.detail, 'value')) { + event.detail.value = event.detail.checked; + } + } + if (isPlainObject(event.detail)) { + event.target = Object.assign({}, event.target, event.detail); + } + return event; +} +const ONCE = '~'; +const CUSTOM = '^'; +function matchEventType(eventType, optType) { + return (eventType === optType || + (optType === 'regionchange' && + (eventType === 'begin' || eventType === 'end'))); +} +function handleEvent(event) { + event = wrapper(event); + // [['tap',[['handle',[1,2,a]],['handle1',[1,2,a]]]]] + const dataset = (event.currentTarget || event.target).dataset; + if (!dataset) { + return console.warn('事件信息不存在'); + } + const eventOpts = (dataset.eventOpts || + dataset['event-opts']); // 支付宝 web-view 组件 dataset 非驼峰 + if (!eventOpts) { + return console.warn('事件信息不存在'); + } + // [['handle',[1,2,a]],['handle1',[1,2,a]]] + const eventType = event.type; + const ret = []; + eventOpts.forEach((eventOpt) => { + let type = eventOpt[0]; + const eventsArray = eventOpt[1]; + const isCustom = type.charAt(0) === CUSTOM; + type = isCustom ? type.slice(1) : type; + const isOnce = type.charAt(0) === ONCE; + type = isOnce ? type.slice(1) : type; + if (eventsArray && matchEventType(eventType, type)) { + eventsArray.forEach((eventArray) => { + const methodName = eventArray[0]; + if (methodName) { + let handlerCtx = this.$vm; + if (handlerCtx.$options.generic && + handlerCtx.$parent && + handlerCtx.$parent.$parent) { + // mp-weixin,mp-toutiao 抽象节点模拟 scoped slots + handlerCtx = handlerCtx.$parent.$parent; + } + if (methodName === '$emit') { + handlerCtx.$emit.apply(handlerCtx, processEventArgs(this.$vm, event, eventArray[1], eventArray[2], isCustom, methodName)); + return; + } + const handler = handlerCtx[methodName]; + if (!isFunction(handler)) { + throw new Error(` _vm.${methodName} is not a function`); + } + if (isOnce) { + if (handler.once) { + return; + } + handler.once = true; + } + ret.push(handler.apply(handlerCtx, processEventArgs(this.$vm, event, eventArray[1], eventArray[2], isCustom, methodName))); + } + }); + } + }); + if (eventType === 'input' && + ret.length === 1 && + typeof ret[0] !== 'undefined') { + return ret[0]; + } +} + +function parseComponent(vueOptions, { parse, mocks, isPage, initRelation, handleLink, initLifetimes }) { + vueOptions = vueOptions.default || vueOptions; + const options = { + multipleSlots: true, + addGlobalClass: true + }; + if (vueOptions.options) { + extend(options, vueOptions.options); + } + const mpComponentOptions = { + options, + lifetimes: initLifetimes({ mocks, isPage, initRelation, vueOptions }), + pageLifetimes: { + show() { + this.$vm && this.$vm.$callHook('onPageShow'); + }, + hide() { + this.$vm && this.$vm.$callHook('onPageHide'); + }, + resize(size) { + this.$vm && this.$vm.$callHook('onPageResize', size); + } + }, + methods: { + __l: handleLink, + __e: handleEvent + } + }; + if (__VUE_OPTIONS_API__) { + applyOptions(mpComponentOptions, vueOptions, initBehavior); + } + initProps(mpComponentOptions, vueOptions.props, false); + initExtraOptions(mpComponentOptions, vueOptions); + initWxsCallMethods(mpComponentOptions.methods, vueOptions.wxsCallMethods); + if (parse) { + parse(mpComponentOptions, { handleLink }); + } + return mpComponentOptions; +} +function initCreateComponent(parseOptions) { + return function createComponent(vueComponentOptions) { + return Component(parseComponent(vueComponentOptions, parseOptions)); + }; +} +let $createComponentFn; +let $destroyComponentFn; +function $createComponent(initialVNode, options) { + if (!$createComponentFn) { + $createComponentFn = getApp().$vm.$createComponent; + } + return $createComponentFn(initialVNode, options); +} +function $destroyComponent(instance) { + if (!$destroyComponentFn) { + $destroyComponentFn = getApp().$vm.$destroyComponent; + } + return $destroyComponentFn(instance); +} + +function parsePage(vueOptions, parseOptions) { + const { parse, mocks, isPage, initRelation, handleLink, initLifetimes } = parseOptions; + const miniProgramPageOptions = parseComponent(vueOptions, { + mocks, + isPage, + initRelation, + handleLink, + initLifetimes + }); + const methods = miniProgramPageOptions.methods; + initHooks(methods, PAGE_HOOKS); + initUnknownHooks(methods, vueOptions); + parse && parse(miniProgramPageOptions, { handleLink }); + return miniProgramPageOptions; +} +function initCreatePage(parseOptions) { + return function createPage(vuePageOptions) { + return Component(parsePage(vuePageOptions, parseOptions)); + }; +} + +const MPPage = Page; +const MPComponent = Component; +const customizeRE = /:/g; +function customize(str) { + return camelize(str.replace(customizeRE, '-')); +} +function initTriggerEvent(mpInstance) { + const oldTriggerEvent = mpInstance.triggerEvent; + mpInstance.triggerEvent = function (event, ...args) { + return oldTriggerEvent.apply(mpInstance, [customize(event), ...args]); + }; +} +function initHook$1(name, options) { + const oldHook = options[name]; + if (!oldHook) { + options[name] = function () { + initTriggerEvent(this); + }; + } + else { + options[name] = function (...args) { + initTriggerEvent(this); + return oldHook.apply(this, args); + }; + } +} +Page = function (options) { + initHook$1('onLoad', options); + return MPPage(options); +}; +Component = function (options) { + initHook$1('created', options); + return MPComponent(options); +}; + +function parse(appOptions) { + // 百度 onShow 竟然会在 onLaunch 之前 + appOptions.onShow = function onShow(args) { + if (!this.$vm) { + this.onLaunch(args); + } + this.$vm.$callHook('onShow', args); + }; +} + +var parseAppOptions = /*#__PURE__*/Object.freeze({ + __proto__: null, + parse: parse +}); + +function initLifetimes({ mocks, isPage, initRelation, vueOptions }) { + return { + attached() { + const properties = this.properties; + initVueIds(properties.vueId, this); + const relationOptions = { + vuePid: this._$vuePid + }; + // 处理父子关系 + initRelation(this, relationOptions); + // 初始化 vue 实例 + const mpInstance = this; + this.$vm = $createComponent({ + type: vueOptions, + props: properties + }, { + mpType: isPage(mpInstance) ? 'page' : 'component', + mpInstance, + slots: properties.vueSlots, + parentComponent: relationOptions.parent && relationOptions.parent.$, + onBeforeSetup(instance, options) { + initRefs(instance, mpInstance); + initMocks(instance, mpInstance, mocks); + initComponentInstance(instance, options); + } + }); + }, + ready() { + // 当组件 props 默认值为 true,初始化时传入 false 会导致 created,ready 触发, 但 attached 不触发 + // https://developers.weixin.qq.com/community/develop/doc/00066ae2844cc0f8eb883e2a557800 + if (this.$vm) { + this.$vm.$callHook('mounted'); + this.$vm.$callHook('onReady'); + } + }, + detached() { + this.$vm && $destroyComponent(this.$vm); + } + }; +} + +function handleLink(event) { + // detail 是微信,value 是百度(dipatch) + const detail = (event.detail || + event.value); + const vuePid = detail.vuePid; + let parentVm; + if (vuePid) { + parentVm = findVmByVueId(this.$vm, vuePid); + } + if (!parentVm) { + parentVm = this.$vm; + } + detail.parent = parentVm; +} + +const mocks = ['nodeId', 'componentName', '_componentId', 'uniquePrefix']; +function isPage(mpInstance) { + return !mpInstance.ownerId; +} +function initRelation(mpInstance, detail) { + mpInstance.dispatch('__l', detail); +} +const newLifecycle = /*#__PURE__*/ swan.canIUse('lifecycle-2-0'); +function parse$1(componentOptions) { + const methods = componentOptions.methods; + const lifetimes = componentOptions.lifetimes; + // 关于百度小程序生命周期的说明(组件作为页面时): + // lifetimes:attached --> methods:onShow --> methods:onLoad --> methods:onReady + // 这里在强制将onShow挪到onLoad之后触发,另外一处修改在page-parser.js + const oldAttached = lifetimes.attached; + lifetimes.attached = function attached() { + oldAttached.call(this); + if (isPage(this) && this.$vm) { + // 百度 onLoad 在 attached 之前触发 + // 百度 当组件作为页面时 pageinstance 不是原来组件的 instance + const pageInstance = this.pageinstance; + pageInstance.$vm = this.$vm; + if (hasOwn(pageInstance, '_$args')) { + this.$vm.$callHook('onLoad', pageInstance._$args); + this.$vm.$callHook('onShow'); + delete pageInstance._$args; + } + } + else { + // 百度小程序组件不触发methods内的onReady + if (this.$vm) { + this.$vm.$callHook('mounted'); + } + } + }; + if (newLifecycle) { + methods.onReady = lifetimes.ready; + delete lifetimes.ready; + } + componentOptions.messages = { + __l: methods.__l + }; + delete methods.__l; +} + +var parseComponentOptions = /*#__PURE__*/Object.freeze({ + __proto__: null, + mocks: mocks, + isPage: isPage, + initRelation: initRelation, + parse: parse$1, + handleLink: handleLink, + initLifetimes: initLifetimes +}); + +function parse$2(pageOptions) { + parse$1(pageOptions); + const methods = pageOptions.methods; + // 纠正百度小程序生命周期methods:onShow在methods:onLoad之前触发的问题 + methods.onShow = function onShow() { + if (this.$vm && this._$loaded) { + this.$vm.$callHook('onShow'); + } + }; + methods.onLoad = function onLoad(args) { + // 百度 onLoad 在 attached 之前触发,先存储 args, 在 attached 里边触发 onLoad + if (this.$vm) { + this._$loaded = true; + this.$vm.$callHook('onLoad', args); + this.$vm.$callHook('onShow'); + } + else { + this.pageinstance._$args = args; + } + }; +} + +var parsePageOptions = /*#__PURE__*/Object.freeze({ + __proto__: null, + parse: parse$2, + handleLink: handleLink, + initLifetimes: initLifetimes, + mocks: mocks, + isPage: isPage, + initRelation: initRelation +}); + +const createApp = initCreateApp(parseAppOptions); +const createPage = initCreatePage(parsePageOptions); +const createComponent = initCreateComponent(parseComponentOptions); + +export { createApp, createComponent, createPage }; diff --git a/packages/uni-mp-qq/dist/uni.api.esm.js b/packages/uni-mp-qq/dist/uni.api.esm.js new file mode 100644 index 0000000000000000000000000000000000000000..9a9838e2759f3012619f585a3c2f952ef8fcecb4 --- /dev/null +++ b/packages/uni-mp-qq/dist/uni.api.esm.js @@ -0,0 +1,476 @@ +import { isArray, isPromise, isFunction, isPlainObject, hasOwn, isString } from '@vue/shared'; + +const EPS = 1e-4; +const BASE_DEVICE_WIDTH = 750; +let isIOS = false; +let deviceWidth = 0; +let deviceDPR = 0; +function checkDeviceWidth() { + const { platform, pixelRatio, windowWidth } = qq.getSystemInfoSync(); + deviceWidth = windowWidth; + deviceDPR = pixelRatio; + isIOS = platform === 'ios'; +} +function upx2px(number, newDeviceWidth) { + if (deviceWidth === 0) { + checkDeviceWidth(); + } + number = Number(number); + if (number === 0) { + return 0; + } + let result = (number / BASE_DEVICE_WIDTH) * (newDeviceWidth || deviceWidth); + if (result < 0) { + result = -result; + } + result = Math.floor(result + EPS); + if (result === 0) { + if (deviceDPR === 1 || !isIOS) { + result = 1; + } + else { + result = 0.5; + } + } + return number < 0 ? -result : result; +} + +var HOOKS; +(function (HOOKS) { + HOOKS["INVOKE"] = "invoke"; + HOOKS["SUCCESS"] = "success"; + HOOKS["FAIL"] = "fail"; + HOOKS["COMPLETE"] = "complete"; + HOOKS["RETURN_VALUE"] = "returnValue"; +})(HOOKS || (HOOKS = {})); +const globalInterceptors = {}; +const scopedInterceptors = {}; +function wrapperHook(hook) { + return function (data) { + return hook(data) || data; + }; +} +function queue(hooks, data) { + let promise = false; + for (let i = 0; i < hooks.length; i++) { + const hook = hooks[i]; + if (promise) { + promise = Promise.resolve(wrapperHook(hook)); + } + else { + const res = hook(data); + if (isPromise(res)) { + promise = Promise.resolve(res); + } + if (res === false) { + return { + then() { }, + catch() { } + }; + } + } + } + return (promise || { + then(callback) { + return callback(data); + }, + catch() { } + }); +} +function wrapperOptions(interceptors, options = {}) { + [HOOKS.SUCCESS, HOOKS.FAIL, HOOKS.COMPLETE].forEach(name => { + const hooks = interceptors[name]; + if (!isArray(hooks)) { + return; + } + const oldCallback = options[name]; + options[name] = function callbackInterceptor(res) { + queue(hooks, res).then((res) => { + return (isFunction(oldCallback) && oldCallback(res)) || res; + }); + }; + }); + return options; +} +function wrapperReturnValue(method, returnValue) { + const returnValueHooks = []; + if (isArray(globalInterceptors.returnValue)) { + returnValueHooks.push(...globalInterceptors.returnValue); + } + const interceptor = scopedInterceptors[method]; + if (interceptor && isArray(interceptor.returnValue)) { + returnValueHooks.push(...interceptor.returnValue); + } + returnValueHooks.forEach(hook => { + returnValue = hook(returnValue) || returnValue; + }); + return returnValue; +} +function getApiInterceptorHooks(method) { + const interceptor = Object.create(null); + Object.keys(globalInterceptors).forEach(hook => { + if (hook !== 'returnValue') { + interceptor[hook] = globalInterceptors[hook].slice(); + } + }); + const scopedInterceptor = scopedInterceptors[method]; + if (scopedInterceptor) { + Object.keys(scopedInterceptor).forEach(hook => { + if (hook !== 'returnValue') { + interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]); + } + }); + } + return interceptor; +} +function invokeApi(method, api, options, ...params) { + const interceptor = getApiInterceptorHooks(method); + if (interceptor && Object.keys(interceptor).length) { + if (isArray(interceptor.invoke)) { + const res = queue(interceptor.invoke, options); + return res.then(options => { + return api(wrapperOptions(interceptor, options), ...params); + }); + } + else { + return api(wrapperOptions(interceptor, options), ...params); + } + } + return api(options, ...params); +} + +function mergeInterceptorHook(interceptors, interceptor) { + Object.keys(interceptor).forEach(hook => { + if (isFunction(interceptor[hook])) { + interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]); + } + }); +} +function removeInterceptorHook(interceptors, interceptor) { + if (!interceptors || !interceptor) { + return; + } + Object.keys(interceptor).forEach(hook => { + if (isFunction(interceptor[hook])) { + removeHook(interceptors[hook], interceptor[hook]); + } + }); +} +function mergeHook(parentVal, childVal) { + const res = childVal + ? parentVal + ? parentVal.concat(childVal) + : isArray(childVal) + ? childVal + : [childVal] + : parentVal; + return res ? dedupeHooks(res) : res; +} +function dedupeHooks(hooks) { + const res = []; + for (let i = 0; i < hooks.length; i++) { + if (res.indexOf(hooks[i]) === -1) { + res.push(hooks[i]); + } + } + return res; +} +function removeHook(hooks, hook) { + if (!hooks) { + return; + } + const index = hooks.indexOf(hook); + if (index !== -1) { + hooks.splice(index, 1); + } +} +function addInterceptor(method, interceptor) { + if (typeof method === 'string' && isPlainObject(interceptor)) { + mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); + } + else if (isPlainObject(method)) { + mergeInterceptorHook(globalInterceptors, method); + } +} +function removeInterceptor(method, interceptor) { + if (typeof method === 'string') { + if (isPlainObject(interceptor)) { + removeInterceptorHook(scopedInterceptors[method], interceptor); + } + else { + delete scopedInterceptors[method]; + } + } + else if (isPlainObject(method)) { + removeInterceptorHook(globalInterceptors, method); + } +} + +const SYNC_API_RE = /^\$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; +const CONTEXT_API_RE = /^create|Manager$/; +// Context例外情况 +const CONTEXT_API_RE_EXC = ['createBLEConnection']; +// 同步例外情况 +const ASYNC_API = ['createBLEConnection']; +const CALLBACK_API_RE = /^on|^off/; +function isContextApi(name) { + return CONTEXT_API_RE.test(name) && CONTEXT_API_RE_EXC.indexOf(name) === -1; +} +function isSyncApi(name) { + return SYNC_API_RE.test(name) && ASYNC_API.indexOf(name) === -1; +} +function isCallbackApi(name) { + return CALLBACK_API_RE.test(name) && name !== 'onPush'; +} +function handlePromise(promise) { + if (!__UNI_PROMISE_API__) { + return promise; + } + return promise + .then(data => { + return [null, data]; + }) + .catch(err => [err]); +} +function shouldPromise(name) { + if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) { + return false; + } + return true; +} +/* eslint-disable no-extend-native */ +if (!Promise.prototype.finally) { + Promise.prototype.finally = function (onfinally) { + const promise = this.constructor; + return this.then(value => promise.resolve(onfinally && onfinally()).then(() => value), reason => promise.resolve(onfinally && onfinally()).then(() => { + throw reason; + })); + }; +} +function promisify(name, api) { + if (!shouldPromise(name)) { + return api; + } + if (!isFunction(api)) { + return api; + } + return function promiseApi(options = {}, ...params) { + if (isFunction(options.success) || + isFunction(options.fail) || + isFunction(options.complete)) { + return wrapperReturnValue(name, invokeApi(name, api, options, ...params)); + } + return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => { + invokeApi(name, api, Object.assign({}, options, { + success: resolve, + fail: reject + }), ...params); + }))); + }; +} + +const CALLBACKS = ['success', 'fail', 'cancel', 'complete']; +function initWrapper(protocols) { + function processCallback(methodName, method, returnValue) { + return function (res) { + return method(processReturnValue(methodName, res, returnValue)); + }; + } + function processArgs(methodName, fromArgs, argsOption = {}, returnValue = {}, keepFromArgs = false) { + if (isPlainObject(fromArgs)) { + // 一般 api 的参数解析 + const toArgs = (keepFromArgs === true ? fromArgs : {}); // returnValue 为 false 时,说明是格式化返回值,直接在返回值对象上修改赋值 + if (isFunction(argsOption)) { + argsOption = argsOption(fromArgs, toArgs) || {}; + } + for (const key in fromArgs) { + if (hasOwn(argsOption, key)) { + let keyOption = argsOption[key]; + if (isFunction(keyOption)) { + keyOption = keyOption(fromArgs[key], fromArgs, toArgs); + } + if (!keyOption) { + // 不支持的参数 + console.warn(`QQ小程序 ${methodName} 暂不支持 ${key}`); + } + else if (isString(keyOption)) { + // 重写参数 key + toArgs[keyOption] = fromArgs[key]; + } + else if (isPlainObject(keyOption)) { + // {name:newName,value:value}可重新指定参数 key:value + toArgs[keyOption.name ? keyOption.name : key] = keyOption.value; + } + } + else if (CALLBACKS.indexOf(key) !== -1) { + const callback = fromArgs[key]; + if (isFunction(callback)) { + toArgs[key] = processCallback(methodName, callback, returnValue); + } + } + else { + if (!keepFromArgs && !hasOwn(toArgs, key)) { + toArgs[key] = fromArgs[key]; + } + } + } + return toArgs; + } + else if (isFunction(fromArgs)) { + fromArgs = processCallback(methodName, fromArgs, returnValue); + } + return fromArgs; + } + function processReturnValue(methodName, res, returnValue, keepReturnValue = false) { + if (isFunction(protocols.returnValue)) { + // 处理通用 returnValue + res = protocols.returnValue(methodName, res); + } + return processArgs(methodName, res, returnValue, {}, keepReturnValue); + } + return function wrapper(methodName, method) { + if (!hasOwn(protocols, methodName)) { + return method; + } + const protocol = protocols[methodName]; + if (!protocol) { + // 暂不支持的 api + return function () { + console.error(`QQ小程序 暂不支持${methodName}`); + }; + } + return function (arg1, arg2) { + // 目前 api 最多两个参数 + let options = protocol; + if (isFunction(protocol)) { + options = protocol(arg1); + } + arg1 = processArgs(methodName, arg1, options.args, options.returnValue); + const args = [arg1]; + if (typeof arg2 !== 'undefined') { + args.push(arg2); + } + const returnValue = qq[options.name || methodName].apply(qq, args); + if (isSyncApi(methodName)) { + // 同步 api + return processReturnValue(methodName, returnValue, options.returnValue, isContextApi(methodName)); + } + return returnValue; + }; + }; +} + +const baseApis = { upx2px, addInterceptor, removeInterceptor }; +function initUni(api, protocols) { + const wrapper = initWrapper(protocols); + const UniProxyHandlers = { + get(target, key) { + if (hasOwn(target, key)) { + return target[key]; + } + if (hasOwn(api, key)) { + return promisify(key, api[key]); + } + if (hasOwn(baseApis, key)) { + return promisify(key, baseApis[key]); + } + // event-api + // provider-api? + return promisify(key, wrapper(key, qq[key])); + } + }; + return new Proxy({}, UniProxyHandlers); +} + +function initGetProvider(providers) { + return function getProvider({ service, success, fail, complete }) { + let res; + if (providers[service]) { + res = { + errMsg: 'getProvider:ok', + service, + provider: providers[service] + }; + isFunction(success) && success(res); + } + else { + res = { + errMsg: 'getProvider:fail:服务[' + service + ']不存在' + }; + isFunction(fail) && fail(res); + } + isFunction(complete) && complete(res); + }; +} + +const previewImage = { + args(fromArgs, toArgs) { + let currentIndex = parseInt(fromArgs.current); + if (isNaN(currentIndex)) { + return; + } + const urls = fromArgs.urls; + if (!isArray(urls)) { + return; + } + const len = urls.length; + if (!len) { + return; + } + if (currentIndex < 0) { + currentIndex = 0; + } + else if (currentIndex >= len) { + currentIndex = len - 1; + } + if (currentIndex > 0) { + toArgs.current = urls[currentIndex]; + toArgs.urls = urls.filter((item, index) => index < currentIndex ? item !== urls[currentIndex] : true); + } + else { + toArgs.current = urls[0]; + } + return { + indicator: false, + loop: false + }; + } +}; +function addSafeAreaInsets(fromRes, toRes) { + if (fromRes.safeArea) { + const safeArea = fromRes.safeArea; + toRes.safeAreaInsets = { + top: safeArea.top, + left: safeArea.left, + right: fromRes.windowWidth - safeArea.right, + bottom: fromRes.windowHeight - safeArea.bottom + }; + } +} +const getSystemInfo = { + returnValue: addSafeAreaInsets +}; +const getSystemInfoSync = getSystemInfo; + +const getProvider = initGetProvider({ + oauth: ['qq'], + share: ['qq'], + payment: ['qqpay'], + push: ['qq'] +}); + +var shims = /*#__PURE__*/Object.freeze({ + __proto__: null, + getProvider: getProvider +}); + +var protocols = /*#__PURE__*/Object.freeze({ + __proto__: null, + previewImage: previewImage, + getSystemInfo: getSystemInfo, + getSystemInfoSync: getSystemInfoSync +}); + +var index = initUni(shims, protocols); + +export default index; diff --git a/packages/uni-mp-qq/dist/uni.mp.esm.js b/packages/uni-mp-qq/dist/uni.mp.esm.js new file mode 100644 index 0000000000000000000000000000000000000000..d238158782953ac7c2aa4c206055c5c7824792bd --- /dev/null +++ b/packages/uni-mp-qq/dist/uni.mp.esm.js @@ -0,0 +1,914 @@ +import { isArray, hasOwn, toNumber, isPlainObject, isObject, isFunction, extend, NOOP, camelize } from '@vue/shared'; + +function setModel(target, key, value, modifiers) { + if (isArray(modifiers)) { + if (modifiers.indexOf('trim') !== -1) { + value = value.trim(); + } + if (modifiers.indexOf('number') !== -1) { + value = toNumber(value); + } + } + if (!target) { + target = this; + } + target[key] = value; +} +function setSync(target, key, value) { + if (!target) { + target = this; + } + target[key] = value; +} +function getOrig(data) { + if (isPlainObject(data)) { + return data.$orig || data; + } + return data; +} +function map(val, iteratee) { + let ret, i, l, keys, key; + if (isArray(val)) { + ret = new Array(val.length); + for (i = 0, l = val.length; i < l; i++) { + ret[i] = iteratee(val[i], i); + } + return ret; + } + else if (isObject(val)) { + keys = Object.keys(val); + ret = Object.create(null); + for (i = 0, l = keys.length; i < l; i++) { + key = keys[i]; + ret[key] = iteratee(val[key], key, i); + } + return ret; + } + return []; +} +const MP_METHODS = [ + 'createSelectorQuery', + 'createIntersectionObserver', + 'selectAllComponents', + 'selectComponent' +]; +function hasHook(name) { + const hooks = this.$[name]; + if (hooks && hooks.length) { + return true; + } + return false; +} +function callHook(name, args) { + if (name === 'mounted') { + callHook.call(this, 'bm'); // beforeMount + this.$.isMounted = true; + name = 'm'; + } + const hooks = this.$[name]; + let ret; + if (hooks) { + for (let i = 0; i < hooks.length; i++) { + ret = hooks[i](args); + } + } + return ret; +} +function createEmitFn(oldEmit, ctx) { + return function emit(event, ...args) { + if (ctx.$scope && event) { + ctx.$scope.triggerEvent(event, { __args__: args }); + } + return oldEmit.apply(this, [event, ...args]); + }; +} +function set(target, key, val) { + return (target[key] = val); +} +function initBaseInstance(instance, options) { + const ctx = instance.ctx; + // mp + ctx.mpType = options.mpType; // @deprecated + ctx.$mpType = options.mpType; + ctx.$scope = options.mpInstance; + // TODO @deprecated + ctx.$mp = {}; + ctx._self = {}; + // $vm + ctx.$scope.$vm = instance.proxy; + // slots + { + instance.slots = {}; + if (isArray(options.slots) && options.slots.length) { + options.slots.forEach(name => { + instance.slots[name] = true; + }); + } + } + if (__VUE_OPTIONS_API__) { + // $set + ctx.$set = set; + } + // $emit + instance.emit = createEmitFn(instance.emit, ctx); + // $callHook + ctx.$hasHook = hasHook; + ctx.$callHook = callHook; +} +function initComponentInstance(instance, options) { + initBaseInstance(instance, options); + const ctx = instance.ctx; + MP_METHODS.forEach(method => { + ctx[method] = function (...args) { + const mpInstance = ctx.$scope; + if (mpInstance && mpInstance[method]) { + return mpInstance[method].apply(mpInstance, args); + } + }; + }); + // TODO other + ctx.__set_model = setModel; + ctx.__set_sync = setSync; + ctx.__get_orig = getOrig; + // TODO + // ctx.__get_style = getStyle + ctx.__map = map; +} +function initMocks(instance, mpInstance, mocks) { + const ctx = instance.ctx; + mocks.forEach(mock => { + if (hasOwn(mpInstance, mock)) { + ctx[mock] = mpInstance[mock]; + } + }); +} + +const PAGE_HOOKS = [ + 'onLoad', + 'onShow', + // 'onReady', // lifetimes.ready + 'onHide', + 'onUnload', + 'onResize', + // 'onPageScroll', // 影响性能,开发者手动注册 + 'onTabItemTap', + 'onReachBottom', + 'onPullDownRefresh', + // 'onShareTimeline', // 右上角菜单,开发者手动注册 + 'onAddToFavorites' + // 'onShareAppMessage' // 右上角菜单,开发者手动注册 +]; +function findHooks(vueOptions, hooks = new Set()) { + if (vueOptions) { + Object.keys(vueOptions).forEach(name => { + if (name.indexOf('on') === 0 && isFunction(vueOptions[name])) { + hooks.add(name); + } + }); + const { extends: extendsOptions, mixins } = vueOptions; + if (mixins) { + mixins.forEach(mixin => findHooks(mixin, hooks)); + } + if (extendsOptions) { + findHooks(extendsOptions, hooks); + } + } + return hooks; +} +function initHook(mpOptions, hook, excludes) { + if (excludes.indexOf(hook) === -1 && !hasOwn(mpOptions, hook)) { + mpOptions[hook] = function (args) { + return this.$vm && this.$vm.$callHook(hook, args); + }; + } +} +const EXCLUDE_HOOKS = ['onReady']; +function initHooks(mpOptions, hooks, excludes = EXCLUDE_HOOKS) { + hooks.forEach(hook => initHook(mpOptions, hook, excludes)); +} +function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) { + findHooks(vueOptions).forEach(hook => initHook(mpOptions, hook, excludes)); +} + +const HOOKS = [ + 'onShow', + 'onHide', + 'onError', + 'onThemeChange', + 'onPageNotFound', + 'onUnhandledRejection' +]; +function parseApp(instance, parseAppOptions) { + const internalInstance = instance.$; + const appOptions = { + globalData: (instance.$options && instance.$options.globalData) || {}, + $vm: instance, + onLaunch(options) { + const ctx = internalInstance.ctx; + if (this.$vm && ctx.$callHook) { + // 已经初始化过了,主要是为了百度,百度 onShow 在 onLaunch 之前 + return; + } + initBaseInstance(internalInstance, { + mpType: 'app', + mpInstance: this, + slots: [] + }); + ctx.globalData = this.globalData; + instance.$callHook('onLaunch', options); + } + }; + const vueOptions = instance.$.type; + initHooks(appOptions, HOOKS); + initUnknownHooks(appOptions, vueOptions); + if (__VUE_OPTIONS_API__) { + const methods = vueOptions.methods; + methods && extend(appOptions, methods); + } + if (parseAppOptions) { + parseAppOptions.parse(appOptions); + } + return appOptions; +} +function initCreateApp(parseAppOptions) { + return function createApp(vm) { + return App(parseApp(vm, parseAppOptions)); + }; +} + +function initBehavior(options) { + return Behavior(options); +} +function initVueIds(vueIds, mpInstance) { + if (!vueIds) { + return; + } + const ids = vueIds.split(','); + const len = ids.length; + if (len === 1) { + mpInstance._$vueId = ids[0]; + } + else if (len === 2) { + mpInstance._$vueId = ids[0]; + mpInstance._$vuePid = ids[1]; + } +} +const EXTRAS = ['externalClasses']; +function initExtraOptions(miniProgramComponentOptions, vueOptions) { + EXTRAS.forEach(name => { + if (hasOwn(vueOptions, name)) { + miniProgramComponentOptions[name] = vueOptions[name]; + } + }); +} +function initWxsCallMethods(methods, wxsCallMethods) { + if (!isArray(wxsCallMethods)) { + return; + } + wxsCallMethods.forEach((callMethod) => { + methods[callMethod] = function (args) { + return this.$vm[callMethod](args); + }; + }); +} +function initRefs(instance, mpInstance) { + Object.defineProperty(instance, 'refs', { + get() { + const $refs = {}; + const components = mpInstance.selectAllComponents('.vue-ref'); + components.forEach(component => { + const ref = component.dataset.ref; + $refs[ref] = component.$vm || component; + }); + const forComponents = mpInstance.selectAllComponents('.vue-ref-in-for'); + forComponents.forEach(component => { + const ref = component.dataset.ref; + if (!$refs[ref]) { + $refs[ref] = []; + } + $refs[ref].push(component.$vm || component); + }); + return $refs; + } + }); +} +function findVmByVueId(instance, vuePid) { + // TODO vue3 中 没有 $children + const $children = instance.$children; + // 优先查找直属(反向查找:https://github.com/dcloudio/uni-app/issues/1200) + for (let i = $children.length - 1; i >= 0; i--) { + const childVm = $children[i]; + if (childVm.$scope._$vueId === vuePid) { + return childVm; + } + } + // 反向递归查找 + let parentVm; + for (let i = $children.length - 1; i >= 0; i--) { + parentVm = findVmByVueId($children[i], vuePid); + if (parentVm) { + return parentVm; + } + } +} + +const PROP_TYPES = [String, Number, Boolean, Object, Array, null]; +function createObserver(name) { + return function observer(newVal) { + if (this.$vm) { + this.$vm.$.props[name] = newVal; // 为了触发其他非 render watcher + } + }; +} +function parsePropType(key, type, defaultValue) { + // [String]=>String + if (isArray(type) && type.length === 1) { + return type[0]; + } + return type; +} +function initDefaultProps(isBehavior = false) { + const properties = {}; + if (!isBehavior) { + properties.vueId = { + type: String, + value: '' + }; + // 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots + properties.vueSlots = { + type: null, + value: [], + observer: function (newVal) { + const $slots = Object.create(null); + newVal.forEach((slotName) => { + $slots[slotName] = true; + }); + this.setData({ + $slots + }); + } + }; + } + return properties; +} +function createProperty(key, prop) { + prop.observer = createObserver(key); + return prop; +} +function initProps(mpComponentOptions, rawProps, isBehavior = false) { + const properties = initDefaultProps(isBehavior); + if (isArray(rawProps)) { + rawProps.forEach(key => { + properties[key] = createProperty(key, { + type: null + }); + }); + } + else if (isPlainObject(rawProps)) { + Object.keys(rawProps).forEach(key => { + const opts = rawProps[key]; + if (isPlainObject(opts)) { + // title:{type:String,default:''} + let value = opts.default; + if (isFunction(value)) { + value = value(); + } + const type = opts.type; + opts.type = parsePropType(key, type); + properties[key] = createProperty(key, { + type: PROP_TYPES.indexOf(type) !== -1 ? type : null, + value + }); + } + else { + // content:String + const type = parsePropType(key, opts); + properties[key] = createProperty(key, { + type: PROP_TYPES.indexOf(type) !== -1 ? type : null + }); + } + }); + } + mpComponentOptions.properties = properties; +} + +function initData(vueOptions) { + let data = vueOptions.data || {}; + if (typeof data === 'function') { + try { + const appConfig = getApp().$vm.$.appContext + .config; + data = data.call(appConfig.globalProperties); + } + catch (e) { + if (process.env.VUE_APP_DEBUG) { + console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data, e); + } + } + } + else { + try { + // 对 data 格式化 + data = JSON.parse(JSON.stringify(data)); + } + catch (e) { } + } + if (!isPlainObject(data)) { + data = {}; + } + return data; +} +function initBehaviors(vueOptions, initBehavior) { + const vueBehaviors = vueOptions.behaviors; + const vueExtends = vueOptions.extends; + const vueMixins = vueOptions.mixins; + let vueProps = vueOptions.props; + if (!vueProps) { + vueOptions.props = vueProps = []; + } + const behaviors = []; + if (isArray(vueBehaviors)) { + vueBehaviors.forEach(behavior => { + behaviors.push(behavior.replace('uni://', `${__PLATFORM_PREFIX__}://`)); + if (behavior === 'uni://form-field') { + if (isArray(vueProps)) { + vueProps.push('name'); + vueProps.push('value'); + } + else { + vueProps.name = { + type: String, + default: '' + }; + vueProps.value = { + type: [String, Number, Boolean, Array, Object, Date], + default: '' + }; + } + } + }); + } + if (isPlainObject(vueExtends) && vueExtends.props) { + const behavior = {}; + initProps(behavior, vueExtends.props, true); + behaviors.push(initBehavior(behavior)); + } + if (isArray(vueMixins)) { + vueMixins.forEach(vueMixin => { + if (isPlainObject(vueMixin) && vueMixin.props) { + const behavior = {}; + initProps(behavior, vueMixin.props, true); + behaviors.push(initBehavior(behavior)); + } + }); + } + return behaviors; +} +function applyOptions(componentOptions, vueOptions, initBehavior) { + componentOptions.data = initData(vueOptions); + componentOptions.behaviors = initBehaviors(vueOptions, initBehavior); +} + +function getValue(obj, path) { + const parts = path.split('.'); + let key = parts[0]; + if (key.indexOf('__$n') === 0) { + //number index + key = parseInt(key.replace('__$n', '')); + } + if (parts.length === 1) { + return obj[key]; + } + return getValue(obj[key], parts.slice(1).join('.')); +} +function getExtraValue(instance, dataPathsArray) { + let context = instance; + dataPathsArray.forEach(dataPathArray => { + const dataPath = dataPathArray[0]; + const value = dataPathArray[2]; + if (dataPath || typeof value !== 'undefined') { + // ['','',index,'disable'] + const propPath = dataPathArray[1]; + const valuePath = dataPathArray[3]; + let vFor; + if (Number.isInteger(dataPath)) { + vFor = dataPath; + } + else if (!dataPath) { + vFor = context; + } + else if (typeof dataPath === 'string' && dataPath) { + if (dataPath.indexOf('#s#') === 0) { + vFor = dataPath.substr(3); + } + else { + vFor = getValue(context, dataPath); + } + } + if (Number.isInteger(vFor)) { + context = value; + } + else if (!propPath) { + context = vFor[value]; + } + else { + if (isArray(vFor)) { + context = vFor.find(vForItem => { + return getValue(vForItem, propPath) === value; + }); + } + else if (isPlainObject(vFor)) { + context = Object.keys(vFor).find(vForKey => { + return getValue(vFor[vForKey], propPath) === value; + }); + } + else { + console.error('v-for 暂不支持循环数据:', vFor); + } + } + if (valuePath) { + context = getValue(context, valuePath); + } + } + }); + return context; +} +function processEventExtra(instance, extra, event) { + const extraObj = {}; + if (isArray(extra) && extra.length) { + /** + *[ + * ['data.items', 'data.id', item.data.id], + * ['metas', 'id', meta.id] + *], + *[ + * ['data.items', 'data.id', item.data.id], + * ['metas', 'id', meta.id] + *], + *'test' + */ + extra.forEach((dataPath, index) => { + if (typeof dataPath === 'string') { + if (!dataPath) { + // model,prop.sync + extraObj['$' + index] = instance; + } + else { + if (dataPath === '$event') { + // $event + extraObj['$' + index] = event; + } + else if (dataPath === 'arguments') { + if (event.detail && event.detail.__args__) { + extraObj['$' + index] = event.detail.__args__; + } + else { + extraObj['$' + index] = [event]; + } + } + else if (dataPath.indexOf('$event.') === 0) { + // $event.target.value + extraObj['$' + index] = getValue(event, dataPath.replace('$event.', '')); + } + else { + extraObj['$' + index] = getValue(instance, dataPath); + } + } + } + else { + extraObj['$' + index] = getExtraValue(instance, dataPath); + } + }); + } + return extraObj; +} +function getObjByArray(arr) { + const obj = {}; + for (let i = 1; i < arr.length; i++) { + const element = arr[i]; + obj[element[0]] = element[1]; + } + return obj; +} +function processEventArgs(instance, event, args = [], extra = [], isCustom, methodName) { + let isCustomMPEvent = false; // wxcomponent 组件,传递原始 event 对象 + if (isCustom) { + // 自定义事件 + isCustomMPEvent = + event.currentTarget && + event.currentTarget.dataset && + event.currentTarget.dataset.comType === 'wx'; + if (!args.length) { + // 无参数,直接传入 event 或 detail 数组 + if (isCustomMPEvent) { + return [event]; + } + return event.detail.__args__ || event.detail; + } + } + const extraObj = processEventExtra(instance, extra, event); + const ret = []; + args.forEach(arg => { + if (arg === '$event') { + if (methodName === '__set_model' && !isCustom) { + // input v-model value + ret.push(event.target.value); + } + else { + if (isCustom && !isCustomMPEvent) { + ret.push(event.detail.__args__[0]); + } + else { + // wxcomponent 组件或内置组件 + ret.push(event); + } + } + } + else { + if (isArray(arg) && arg[0] === 'o') { + ret.push(getObjByArray(arg)); + } + else if (typeof arg === 'string' && hasOwn(extraObj, arg)) { + ret.push(extraObj[arg]); + } + else { + ret.push(arg); + } + } + }); + return ret; +} +function wrapper(event) { + event.stopPropagation = NOOP; + event.preventDefault = NOOP; + event.target = event.target || {}; + if (!hasOwn(event, 'detail')) { + event.detail = {}; + } + if (hasOwn(event, 'markerId')) { + event.detail = typeof event.detail === 'object' ? event.detail : {}; + event.detail.markerId = event.markerId; + } + if (isPlainObject(event.detail)) { + event.target = Object.assign({}, event.target, event.detail); + } + return event; +} +const ONCE = '~'; +const CUSTOM = '^'; +function matchEventType(eventType, optType) { + return (eventType === optType || + (optType === 'regionchange' && + (eventType === 'begin' || eventType === 'end'))); +} +function handleEvent(event) { + event = wrapper(event); + // [['tap',[['handle',[1,2,a]],['handle1',[1,2,a]]]]] + const dataset = (event.currentTarget || event.target).dataset; + if (!dataset) { + return console.warn('事件信息不存在'); + } + const eventOpts = (dataset.eventOpts || + dataset['event-opts']); // 支付宝 web-view 组件 dataset 非驼峰 + if (!eventOpts) { + return console.warn('事件信息不存在'); + } + // [['handle',[1,2,a]],['handle1',[1,2,a]]] + const eventType = event.type; + const ret = []; + eventOpts.forEach((eventOpt) => { + let type = eventOpt[0]; + const eventsArray = eventOpt[1]; + const isCustom = type.charAt(0) === CUSTOM; + type = isCustom ? type.slice(1) : type; + const isOnce = type.charAt(0) === ONCE; + type = isOnce ? type.slice(1) : type; + if (eventsArray && matchEventType(eventType, type)) { + eventsArray.forEach((eventArray) => { + const methodName = eventArray[0]; + if (methodName) { + let handlerCtx = this.$vm; + if (handlerCtx.$options.generic && + handlerCtx.$parent && + handlerCtx.$parent.$parent) { + // mp-weixin,mp-toutiao 抽象节点模拟 scoped slots + handlerCtx = handlerCtx.$parent.$parent; + } + if (methodName === '$emit') { + handlerCtx.$emit.apply(handlerCtx, processEventArgs(this.$vm, event, eventArray[1], eventArray[2], isCustom, methodName)); + return; + } + const handler = handlerCtx[methodName]; + if (!isFunction(handler)) { + throw new Error(` _vm.${methodName} is not a function`); + } + if (isOnce) { + if (handler.once) { + return; + } + handler.once = true; + } + ret.push(handler.apply(handlerCtx, processEventArgs(this.$vm, event, eventArray[1], eventArray[2], isCustom, methodName))); + } + }); + } + }); + if (eventType === 'input' && + ret.length === 1 && + typeof ret[0] !== 'undefined') { + return ret[0]; + } +} + +function parseComponent(vueOptions, { parse, mocks, isPage, initRelation, handleLink, initLifetimes }) { + vueOptions = vueOptions.default || vueOptions; + const options = { + multipleSlots: true, + addGlobalClass: true + }; + if (vueOptions.options) { + extend(options, vueOptions.options); + } + const mpComponentOptions = { + options, + lifetimes: initLifetimes({ mocks, isPage, initRelation, vueOptions }), + pageLifetimes: { + show() { + this.$vm && this.$vm.$callHook('onPageShow'); + }, + hide() { + this.$vm && this.$vm.$callHook('onPageHide'); + }, + resize(size) { + this.$vm && this.$vm.$callHook('onPageResize', size); + } + }, + methods: { + __l: handleLink, + __e: handleEvent + } + }; + if (__VUE_OPTIONS_API__) { + applyOptions(mpComponentOptions, vueOptions, initBehavior); + } + initProps(mpComponentOptions, vueOptions.props, false); + initExtraOptions(mpComponentOptions, vueOptions); + initWxsCallMethods(mpComponentOptions.methods, vueOptions.wxsCallMethods); + if (parse) { + parse(mpComponentOptions, { handleLink }); + } + return mpComponentOptions; +} +function initCreateComponent(parseOptions) { + return function createComponent(vueComponentOptions) { + return Component(parseComponent(vueComponentOptions, parseOptions)); + }; +} +let $createComponentFn; +let $destroyComponentFn; +function $createComponent(initialVNode, options) { + if (!$createComponentFn) { + $createComponentFn = getApp().$vm.$createComponent; + } + return $createComponentFn(initialVNode, options); +} +function $destroyComponent(instance) { + if (!$destroyComponentFn) { + $destroyComponentFn = getApp().$vm.$destroyComponent; + } + return $destroyComponentFn(instance); +} + +function parsePage(vueOptions, parseOptions) { + const { parse, mocks, isPage, initRelation, handleLink, initLifetimes } = parseOptions; + const miniProgramPageOptions = parseComponent(vueOptions, { + mocks, + isPage, + initRelation, + handleLink, + initLifetimes + }); + const methods = miniProgramPageOptions.methods; + initHooks(methods, PAGE_HOOKS); + initUnknownHooks(methods, vueOptions); + parse && parse(miniProgramPageOptions, { handleLink }); + return miniProgramPageOptions; +} +function initCreatePage(parseOptions) { + return function createPage(vuePageOptions) { + return Component(parsePage(vuePageOptions, parseOptions)); + }; +} + +const MPPage = Page; +const MPComponent = Component; +const customizeRE = /:/g; +function customize(str) { + return camelize(str.replace(customizeRE, '-')); +} +function initTriggerEvent(mpInstance) { + const oldTriggerEvent = mpInstance.triggerEvent; + mpInstance.triggerEvent = function (event, ...args) { + return oldTriggerEvent.apply(mpInstance, [customize(event), ...args]); + }; +} +function initHook$1(name, options) { + const oldHook = options[name]; + if (!oldHook) { + options[name] = function () { + initTriggerEvent(this); + }; + } + else { + options[name] = function (...args) { + initTriggerEvent(this); + return oldHook.apply(this, args); + }; + } +} +Page = function (options) { + initHook$1('onLoad', options); + return MPPage(options); +}; +Component = function (options) { + initHook$1('created', options); + return MPComponent(options); +}; + +function initLifetimes({ mocks, isPage, initRelation, vueOptions }) { + return { + attached() { + const properties = this.properties; + initVueIds(properties.vueId, this); + const relationOptions = { + vuePid: this._$vuePid + }; + // 处理父子关系 + initRelation(this, relationOptions); + // 初始化 vue 实例 + const mpInstance = this; + this.$vm = $createComponent({ + type: vueOptions, + props: properties + }, { + mpType: isPage(mpInstance) ? 'page' : 'component', + mpInstance, + slots: properties.vueSlots, + parentComponent: relationOptions.parent && relationOptions.parent.$, + onBeforeSetup(instance, options) { + initRefs(instance, mpInstance); + initMocks(instance, mpInstance, mocks); + initComponentInstance(instance, options); + } + }); + }, + ready() { + // 当组件 props 默认值为 true,初始化时传入 false 会导致 created,ready 触发, 但 attached 不触发 + // https://developers.weixin.qq.com/community/develop/doc/00066ae2844cc0f8eb883e2a557800 + if (this.$vm) { + this.$vm.$callHook('mounted'); + this.$vm.$callHook('onReady'); + } + }, + detached() { + this.$vm && $destroyComponent(this.$vm); + } + }; +} + +const mocks = ['__route__', '__wxExparserNodeId__', '__wxWebviewId__']; +function isPage(mpInstance) { + return !!mpInstance.route; +} +function initRelation(mpInstance, detail) { + mpInstance.triggerEvent('__l', detail); +} +function handleLink(event) { + // detail 是微信,value 是百度(dipatch) + const detail = (event.detail || + event.value); + const vuePid = detail.vuePid; + let parentVm; + if (vuePid) { + parentVm = findVmByVueId(this.$vm, vuePid); + } + if (!parentVm) { + parentVm = this.$vm; + } + detail.parent = parentVm; +} + +var parseOptions = /*#__PURE__*/Object.freeze({ + __proto__: null, + mocks: mocks, + isPage: isPage, + initRelation: initRelation, + handleLink: handleLink, + initLifetimes: initLifetimes +}); + +const createApp = initCreateApp(); +const createPage = initCreatePage(parseOptions); +const createComponent = initCreateComponent(parseOptions); + +export { createApp, createComponent, createPage }; diff --git a/packages/uni-mp-toutiao/dist/uni.api.esm.js b/packages/uni-mp-toutiao/dist/uni.api.esm.js new file mode 100644 index 0000000000000000000000000000000000000000..be898dda11a6a44b282e761a30cb05c83b7009bc --- /dev/null +++ b/packages/uni-mp-toutiao/dist/uni.api.esm.js @@ -0,0 +1,544 @@ +import { isArray, isPromise, isFunction, isPlainObject, hasOwn, isString } from '@vue/shared'; + +const EPS = 1e-4; +const BASE_DEVICE_WIDTH = 750; +let isIOS = false; +let deviceWidth = 0; +let deviceDPR = 0; +function checkDeviceWidth() { + const { platform, pixelRatio, windowWidth } = tt.getSystemInfoSync(); + deviceWidth = windowWidth; + deviceDPR = pixelRatio; + isIOS = platform === 'ios'; +} +function upx2px(number, newDeviceWidth) { + if (deviceWidth === 0) { + checkDeviceWidth(); + } + number = Number(number); + if (number === 0) { + return 0; + } + let result = (number / BASE_DEVICE_WIDTH) * (newDeviceWidth || deviceWidth); + if (result < 0) { + result = -result; + } + result = Math.floor(result + EPS); + if (result === 0) { + if (deviceDPR === 1 || !isIOS) { + result = 1; + } + else { + result = 0.5; + } + } + return number < 0 ? -result : result; +} + +var HOOKS; +(function (HOOKS) { + HOOKS["INVOKE"] = "invoke"; + HOOKS["SUCCESS"] = "success"; + HOOKS["FAIL"] = "fail"; + HOOKS["COMPLETE"] = "complete"; + HOOKS["RETURN_VALUE"] = "returnValue"; +})(HOOKS || (HOOKS = {})); +const globalInterceptors = {}; +const scopedInterceptors = {}; +function wrapperHook(hook) { + return function (data) { + return hook(data) || data; + }; +} +function queue(hooks, data) { + let promise = false; + for (let i = 0; i < hooks.length; i++) { + const hook = hooks[i]; + if (promise) { + promise = Promise.resolve(wrapperHook(hook)); + } + else { + const res = hook(data); + if (isPromise(res)) { + promise = Promise.resolve(res); + } + if (res === false) { + return { + then() { }, + catch() { } + }; + } + } + } + return (promise || { + then(callback) { + return callback(data); + }, + catch() { } + }); +} +function wrapperOptions(interceptors, options = {}) { + [HOOKS.SUCCESS, HOOKS.FAIL, HOOKS.COMPLETE].forEach(name => { + const hooks = interceptors[name]; + if (!isArray(hooks)) { + return; + } + const oldCallback = options[name]; + options[name] = function callbackInterceptor(res) { + queue(hooks, res).then((res) => { + return (isFunction(oldCallback) && oldCallback(res)) || res; + }); + }; + }); + return options; +} +function wrapperReturnValue(method, returnValue) { + const returnValueHooks = []; + if (isArray(globalInterceptors.returnValue)) { + returnValueHooks.push(...globalInterceptors.returnValue); + } + const interceptor = scopedInterceptors[method]; + if (interceptor && isArray(interceptor.returnValue)) { + returnValueHooks.push(...interceptor.returnValue); + } + returnValueHooks.forEach(hook => { + returnValue = hook(returnValue) || returnValue; + }); + return returnValue; +} +function getApiInterceptorHooks(method) { + const interceptor = Object.create(null); + Object.keys(globalInterceptors).forEach(hook => { + if (hook !== 'returnValue') { + interceptor[hook] = globalInterceptors[hook].slice(); + } + }); + const scopedInterceptor = scopedInterceptors[method]; + if (scopedInterceptor) { + Object.keys(scopedInterceptor).forEach(hook => { + if (hook !== 'returnValue') { + interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]); + } + }); + } + return interceptor; +} +function invokeApi(method, api, options, ...params) { + const interceptor = getApiInterceptorHooks(method); + if (interceptor && Object.keys(interceptor).length) { + if (isArray(interceptor.invoke)) { + const res = queue(interceptor.invoke, options); + return res.then(options => { + return api(wrapperOptions(interceptor, options), ...params); + }); + } + else { + return api(wrapperOptions(interceptor, options), ...params); + } + } + return api(options, ...params); +} + +function mergeInterceptorHook(interceptors, interceptor) { + Object.keys(interceptor).forEach(hook => { + if (isFunction(interceptor[hook])) { + interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]); + } + }); +} +function removeInterceptorHook(interceptors, interceptor) { + if (!interceptors || !interceptor) { + return; + } + Object.keys(interceptor).forEach(hook => { + if (isFunction(interceptor[hook])) { + removeHook(interceptors[hook], interceptor[hook]); + } + }); +} +function mergeHook(parentVal, childVal) { + const res = childVal + ? parentVal + ? parentVal.concat(childVal) + : isArray(childVal) + ? childVal + : [childVal] + : parentVal; + return res ? dedupeHooks(res) : res; +} +function dedupeHooks(hooks) { + const res = []; + for (let i = 0; i < hooks.length; i++) { + if (res.indexOf(hooks[i]) === -1) { + res.push(hooks[i]); + } + } + return res; +} +function removeHook(hooks, hook) { + if (!hooks) { + return; + } + const index = hooks.indexOf(hook); + if (index !== -1) { + hooks.splice(index, 1); + } +} +function addInterceptor(method, interceptor) { + if (typeof method === 'string' && isPlainObject(interceptor)) { + mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); + } + else if (isPlainObject(method)) { + mergeInterceptorHook(globalInterceptors, method); + } +} +function removeInterceptor(method, interceptor) { + if (typeof method === 'string') { + if (isPlainObject(interceptor)) { + removeInterceptorHook(scopedInterceptors[method], interceptor); + } + else { + delete scopedInterceptors[method]; + } + } + else if (isPlainObject(method)) { + removeInterceptorHook(globalInterceptors, method); + } +} + +const SYNC_API_RE = /^\$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; +const CONTEXT_API_RE = /^create|Manager$/; +// Context例外情况 +const CONTEXT_API_RE_EXC = ['createBLEConnection']; +// 同步例外情况 +const ASYNC_API = ['createBLEConnection']; +const CALLBACK_API_RE = /^on|^off/; +function isContextApi(name) { + return CONTEXT_API_RE.test(name) && CONTEXT_API_RE_EXC.indexOf(name) === -1; +} +function isSyncApi(name) { + return SYNC_API_RE.test(name) && ASYNC_API.indexOf(name) === -1; +} +function isCallbackApi(name) { + return CALLBACK_API_RE.test(name) && name !== 'onPush'; +} +function handlePromise(promise) { + if (!__UNI_PROMISE_API__) { + return promise; + } + return promise + .then(data => { + return [null, data]; + }) + .catch(err => [err]); +} +function shouldPromise(name) { + if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) { + return false; + } + return true; +} +/* eslint-disable no-extend-native */ +if (!Promise.prototype.finally) { + Promise.prototype.finally = function (onfinally) { + const promise = this.constructor; + return this.then(value => promise.resolve(onfinally && onfinally()).then(() => value), reason => promise.resolve(onfinally && onfinally()).then(() => { + throw reason; + })); + }; +} +function promisify(name, api) { + if (!shouldPromise(name)) { + return api; + } + if (!isFunction(api)) { + return api; + } + return function promiseApi(options = {}, ...params) { + if (isFunction(options.success) || + isFunction(options.fail) || + isFunction(options.complete)) { + return wrapperReturnValue(name, invokeApi(name, api, options, ...params)); + } + return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => { + invokeApi(name, api, Object.assign({}, options, { + success: resolve, + fail: reject + }), ...params); + }))); + }; +} + +const CALLBACKS = ['success', 'fail', 'cancel', 'complete']; +function initWrapper(protocols) { + function processCallback(methodName, method, returnValue) { + return function (res) { + return method(processReturnValue(methodName, res, returnValue)); + }; + } + function processArgs(methodName, fromArgs, argsOption = {}, returnValue = {}, keepFromArgs = false) { + if (isPlainObject(fromArgs)) { + // 一般 api 的参数解析 + const toArgs = (keepFromArgs === true ? fromArgs : {}); // returnValue 为 false 时,说明是格式化返回值,直接在返回值对象上修改赋值 + if (isFunction(argsOption)) { + argsOption = argsOption(fromArgs, toArgs) || {}; + } + for (const key in fromArgs) { + if (hasOwn(argsOption, key)) { + let keyOption = argsOption[key]; + if (isFunction(keyOption)) { + keyOption = keyOption(fromArgs[key], fromArgs, toArgs); + } + if (!keyOption) { + // 不支持的参数 + console.warn(`字节跳动小程序 ${methodName} 暂不支持 ${key}`); + } + else if (isString(keyOption)) { + // 重写参数 key + toArgs[keyOption] = fromArgs[key]; + } + else if (isPlainObject(keyOption)) { + // {name:newName,value:value}可重新指定参数 key:value + toArgs[keyOption.name ? keyOption.name : key] = keyOption.value; + } + } + else if (CALLBACKS.indexOf(key) !== -1) { + const callback = fromArgs[key]; + if (isFunction(callback)) { + toArgs[key] = processCallback(methodName, callback, returnValue); + } + } + else { + if (!keepFromArgs && !hasOwn(toArgs, key)) { + toArgs[key] = fromArgs[key]; + } + } + } + return toArgs; + } + else if (isFunction(fromArgs)) { + fromArgs = processCallback(methodName, fromArgs, returnValue); + } + return fromArgs; + } + function processReturnValue(methodName, res, returnValue, keepReturnValue = false) { + if (isFunction(protocols.returnValue)) { + // 处理通用 returnValue + res = protocols.returnValue(methodName, res); + } + return processArgs(methodName, res, returnValue, {}, keepReturnValue); + } + return function wrapper(methodName, method) { + if (!hasOwn(protocols, methodName)) { + return method; + } + const protocol = protocols[methodName]; + if (!protocol) { + // 暂不支持的 api + return function () { + console.error(`字节跳动小程序 暂不支持${methodName}`); + }; + } + return function (arg1, arg2) { + // 目前 api 最多两个参数 + let options = protocol; + if (isFunction(protocol)) { + options = protocol(arg1); + } + arg1 = processArgs(methodName, arg1, options.args, options.returnValue); + const args = [arg1]; + if (typeof arg2 !== 'undefined') { + args.push(arg2); + } + const returnValue = tt[options.name || methodName].apply(tt, args); + if (isSyncApi(methodName)) { + // 同步 api + return processReturnValue(methodName, returnValue, options.returnValue, isContextApi(methodName)); + } + return returnValue; + }; + }; +} + +const baseApis = { upx2px, addInterceptor, removeInterceptor }; +function initUni(api, protocols) { + const wrapper = initWrapper(protocols); + const UniProxyHandlers = { + get(target, key) { + if (hasOwn(target, key)) { + return target[key]; + } + if (hasOwn(api, key)) { + return promisify(key, api[key]); + } + if (hasOwn(baseApis, key)) { + return promisify(key, baseApis[key]); + } + // event-api + // provider-api? + return promisify(key, wrapper(key, tt[key])); + } + }; + return new Proxy({}, UniProxyHandlers); +} + +function initGetProvider(providers) { + return function getProvider({ service, success, fail, complete }) { + let res; + if (providers[service]) { + res = { + errMsg: 'getProvider:ok', + service, + provider: providers[service] + }; + isFunction(success) && success(res); + } + else { + res = { + errMsg: 'getProvider:fail:服务[' + service + ']不存在' + }; + isFunction(fail) && fail(res); + } + isFunction(complete) && complete(res); + }; +} + +const previewImage = { + args(fromArgs, toArgs) { + let currentIndex = parseInt(fromArgs.current); + if (isNaN(currentIndex)) { + return; + } + const urls = fromArgs.urls; + if (!isArray(urls)) { + return; + } + const len = urls.length; + if (!len) { + return; + } + if (currentIndex < 0) { + currentIndex = 0; + } + else if (currentIndex >= len) { + currentIndex = len - 1; + } + if (currentIndex > 0) { + toArgs.current = urls[currentIndex]; + toArgs.urls = urls.filter((item, index) => index < currentIndex ? item !== urls[currentIndex] : true); + } + else { + toArgs.current = urls[0]; + } + return { + indicator: false, + loop: false + }; + } +}; + +const getProvider = initGetProvider({ + oauth: ['toutiao'], + share: ['toutiao'], + payment: ['toutiao'], + push: ['toutiao'] +}); + +var shims = /*#__PURE__*/Object.freeze({ + __proto__: null, + getProvider: getProvider +}); + +const chooseImage = { + args: { + sizeType: false + } +}; +const connectSocket = { + args: { + method: false + } +}; +const chooseVideo = { + args: { + camera: false + } +}; +const scanCode = { + args: { + onlyFromCamera: false, + scanType: false + } +}; +const startAccelerometer = { + args: { + interval: false + } +}; +const showToast = { + args: { + image: false, + mask: false + } +}; +const showLoading = { + args: { + mask: false + } +}; +const showModal = { + args: { + cancelColor: false, + confirmColor: false + } +}; +const showActionSheet = { + args: { + itemColor: false + } +}; +const login = { + args: { + scopes: false, + timeout: false + } +}; +const getUserInfo = { + args: { + lang: false, + timeout: false + } +}; +const requestPayment = { + name: tt.pay ? 'pay' : 'requestPayment', + args: { + orderInfo: tt.pay ? 'orderInfo' : 'data' + } +}; +const getFileInfo = { + args: { + digestAlgorithm: false + } +}; + +var protocols = /*#__PURE__*/Object.freeze({ + __proto__: null, + chooseImage: chooseImage, + connectSocket: connectSocket, + chooseVideo: chooseVideo, + scanCode: scanCode, + startAccelerometer: startAccelerometer, + showToast: showToast, + showLoading: showLoading, + showModal: showModal, + showActionSheet: showActionSheet, + login: login, + getUserInfo: getUserInfo, + requestPayment: requestPayment, + getFileInfo: getFileInfo, + previewImage: previewImage +}); + +var index = initUni(shims, protocols); + +export default index; diff --git a/packages/uni-mp-toutiao/dist/uni.mp.esm.js b/packages/uni-mp-toutiao/dist/uni.mp.esm.js new file mode 100644 index 0000000000000000000000000000000000000000..1fe01d7f0d5382e857dbf220d35b901eeaa325a6 --- /dev/null +++ b/packages/uni-mp-toutiao/dist/uni.mp.esm.js @@ -0,0 +1,1066 @@ +import { isArray, hasOwn, toNumber, isPlainObject, isObject, isFunction, extend, NOOP, camelize } from '@vue/shared'; + +function setModel(target, key, value, modifiers) { + if (isArray(modifiers)) { + if (modifiers.indexOf('trim') !== -1) { + value = value.trim(); + } + if (modifiers.indexOf('number') !== -1) { + value = toNumber(value); + } + } + if (!target) { + target = this; + } + target[key] = value; +} +function setSync(target, key, value) { + if (!target) { + target = this; + } + target[key] = value; +} +function getOrig(data) { + if (isPlainObject(data)) { + return data.$orig || data; + } + return data; +} +function map(val, iteratee) { + let ret, i, l, keys, key; + if (isArray(val)) { + ret = new Array(val.length); + for (i = 0, l = val.length; i < l; i++) { + ret[i] = iteratee(val[i], i); + } + return ret; + } + else if (isObject(val)) { + keys = Object.keys(val); + ret = Object.create(null); + for (i = 0, l = keys.length; i < l; i++) { + key = keys[i]; + ret[key] = iteratee(val[key], key, i); + } + return ret; + } + return []; +} +const MP_METHODS = [ + 'createSelectorQuery', + 'createIntersectionObserver', + 'selectAllComponents', + 'selectComponent' +]; +function hasHook(name) { + const hooks = this.$[name]; + if (hooks && hooks.length) { + return true; + } + return false; +} +function callHook(name, args) { + if (name === 'mounted') { + callHook.call(this, 'bm'); // beforeMount + this.$.isMounted = true; + name = 'm'; + } + const hooks = this.$[name]; + let ret; + if (hooks) { + for (let i = 0; i < hooks.length; i++) { + ret = hooks[i](args); + } + } + return ret; +} +function createEmitFn(oldEmit, ctx) { + return function emit(event, ...args) { + if (ctx.$scope && event) { + ctx.$scope.triggerEvent(event, { __args__: args }); + } + return oldEmit.apply(this, [event, ...args]); + }; +} +function set(target, key, val) { + return (target[key] = val); +} +function initBaseInstance(instance, options) { + const ctx = instance.ctx; + // mp + ctx.mpType = options.mpType; // @deprecated + ctx.$mpType = options.mpType; + ctx.$scope = options.mpInstance; + // TODO @deprecated + ctx.$mp = {}; + ctx._self = {}; + // $vm + ctx.$scope.$vm = instance.proxy; + // slots + { + instance.slots = {}; + if (isArray(options.slots) && options.slots.length) { + options.slots.forEach(name => { + instance.slots[name] = true; + }); + } + } + if (__VUE_OPTIONS_API__) { + // $set + ctx.$set = set; + } + // $emit + instance.emit = createEmitFn(instance.emit, ctx); + // $callHook + ctx.$hasHook = hasHook; + ctx.$callHook = callHook; +} +function initComponentInstance(instance, options) { + initBaseInstance(instance, options); + const ctx = instance.ctx; + MP_METHODS.forEach(method => { + ctx[method] = function (...args) { + const mpInstance = ctx.$scope; + if (mpInstance && mpInstance[method]) { + return mpInstance[method].apply(mpInstance, args); + } + }; + }); + // TODO other + ctx.__set_model = setModel; + ctx.__set_sync = setSync; + ctx.__get_orig = getOrig; + // TODO + // ctx.__get_style = getStyle + ctx.__map = map; +} +function initMocks(instance, mpInstance, mocks) { + const ctx = instance.ctx; + mocks.forEach(mock => { + if (hasOwn(mpInstance, mock)) { + ctx[mock] = mpInstance[mock]; + } + }); +} + +const PAGE_HOOKS = [ + 'onLoad', + 'onShow', + // 'onReady', // lifetimes.ready + 'onHide', + 'onUnload', + 'onResize', + // 'onPageScroll', // 影响性能,开发者手动注册 + 'onTabItemTap', + 'onReachBottom', + 'onPullDownRefresh', + // 'onShareTimeline', // 右上角菜单,开发者手动注册 + 'onAddToFavorites' + // 'onShareAppMessage' // 右上角菜单,开发者手动注册 +]; +function findHooks(vueOptions, hooks = new Set()) { + if (vueOptions) { + Object.keys(vueOptions).forEach(name => { + if (name.indexOf('on') === 0 && isFunction(vueOptions[name])) { + hooks.add(name); + } + }); + const { extends: extendsOptions, mixins } = vueOptions; + if (mixins) { + mixins.forEach(mixin => findHooks(mixin, hooks)); + } + if (extendsOptions) { + findHooks(extendsOptions, hooks); + } + } + return hooks; +} +function initHook(mpOptions, hook, excludes) { + if (excludes.indexOf(hook) === -1 && !hasOwn(mpOptions, hook)) { + mpOptions[hook] = function (args) { + if ( hook === 'onError') { + return getApp().$vm.$callHook(hook, args); + } + return this.$vm && this.$vm.$callHook(hook, args); + }; + } +} +const EXCLUDE_HOOKS = ['onReady']; +function initHooks(mpOptions, hooks, excludes = EXCLUDE_HOOKS) { + hooks.forEach(hook => initHook(mpOptions, hook, excludes)); +} +function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) { + findHooks(vueOptions).forEach(hook => initHook(mpOptions, hook, excludes)); +} + +const HOOKS = [ + 'onShow', + 'onHide', + 'onError', + 'onThemeChange', + 'onPageNotFound', + 'onUnhandledRejection' +]; +function parseApp(instance, parseAppOptions) { + const internalInstance = instance.$; + const appOptions = { + globalData: (instance.$options && instance.$options.globalData) || {}, + $vm: instance, + onLaunch(options) { + const ctx = internalInstance.ctx; + if (this.$vm && ctx.$callHook) { + // 已经初始化过了,主要是为了百度,百度 onShow 在 onLaunch 之前 + return; + } + initBaseInstance(internalInstance, { + mpType: 'app', + mpInstance: this, + slots: [] + }); + ctx.globalData = this.globalData; + instance.$callHook('onLaunch', options); + } + }; + const vueOptions = instance.$.type; + initHooks(appOptions, HOOKS); + initUnknownHooks(appOptions, vueOptions); + if (__VUE_OPTIONS_API__) { + const methods = vueOptions.methods; + methods && extend(appOptions, methods); + } + if (parseAppOptions) { + parseAppOptions.parse(appOptions); + } + return appOptions; +} +function initCreateApp(parseAppOptions) { + return function createApp(vm) { + return App(parseApp(vm, parseAppOptions)); + }; +} + +function initBehavior(options) { + return Behavior(options); +} +function initVueIds(vueIds, mpInstance) { + if (!vueIds) { + return; + } + const ids = vueIds.split(','); + const len = ids.length; + if (len === 1) { + mpInstance._$vueId = ids[0]; + } + else if (len === 2) { + mpInstance._$vueId = ids[0]; + mpInstance._$vuePid = ids[1]; + } +} +const EXTRAS = ['externalClasses']; +function initExtraOptions(miniProgramComponentOptions, vueOptions) { + EXTRAS.forEach(name => { + if (hasOwn(vueOptions, name)) { + miniProgramComponentOptions[name] = vueOptions[name]; + } + }); +} +function initWxsCallMethods(methods, wxsCallMethods) { + if (!isArray(wxsCallMethods)) { + return; + } + wxsCallMethods.forEach((callMethod) => { + methods[callMethod] = function (args) { + return this.$vm[callMethod](args); + }; + }); +} +function initRefs(instance, mpInstance) { + Object.defineProperty(instance, 'refs', { + get() { + const $refs = {}; + const components = mpInstance.selectAllComponents('.vue-ref'); + components.forEach(component => { + const ref = component.dataset.ref; + $refs[ref] = component.$vm || component; + }); + const forComponents = mpInstance.selectAllComponents('.vue-ref-in-for'); + forComponents.forEach(component => { + const ref = component.dataset.ref; + if (!$refs[ref]) { + $refs[ref] = []; + } + $refs[ref].push(component.$vm || component); + }); + return $refs; + } + }); +} +function findVmByVueId(instance, vuePid) { + // TODO vue3 中 没有 $children + const $children = instance.$children; + // 优先查找直属(反向查找:https://github.com/dcloudio/uni-app/issues/1200) + for (let i = $children.length - 1; i >= 0; i--) { + const childVm = $children[i]; + if (childVm.$scope._$vueId === vuePid) { + return childVm; + } + } + // 反向递归查找 + let parentVm; + for (let i = $children.length - 1; i >= 0; i--) { + parentVm = findVmByVueId($children[i], vuePid); + if (parentVm) { + return parentVm; + } + } +} + +const PROP_TYPES = [String, Number, Boolean, Object, Array, null]; +function createObserver(name) { + return function observer(newVal) { + if (this.$vm) { + this.$vm.$.props[name] = newVal; // 为了触发其他非 render watcher + } + }; +} +function parsePropType(key, type, defaultValue) { + // [String]=>String + if (isArray(type) && type.length === 1) { + return type[0]; + } + return type; +} +function initDefaultProps(isBehavior = false) { + const properties = {}; + if (!isBehavior) { + properties.vueId = { + type: String, + value: '' + }; + { + // 用于字节跳动小程序模拟抽象节点 + properties.generic = { + type: Object + }; + } + // 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots + properties.vueSlots = { + type: null, + value: [], + observer: function (newVal) { + const $slots = Object.create(null); + newVal.forEach((slotName) => { + $slots[slotName] = true; + }); + this.setData({ + $slots + }); + } + }; + } + return properties; +} +function createProperty(key, prop) { + prop.observer = createObserver(key); + return prop; +} +function initProps(mpComponentOptions, rawProps, isBehavior = false) { + const properties = initDefaultProps(isBehavior); + if (isArray(rawProps)) { + rawProps.forEach(key => { + properties[key] = createProperty(key, { + type: null + }); + }); + } + else if (isPlainObject(rawProps)) { + Object.keys(rawProps).forEach(key => { + const opts = rawProps[key]; + if (isPlainObject(opts)) { + // title:{type:String,default:''} + let value = opts.default; + if (isFunction(value)) { + value = value(); + } + const type = opts.type; + opts.type = parsePropType(key, type); + properties[key] = createProperty(key, { + type: PROP_TYPES.indexOf(type) !== -1 ? type : null, + value + }); + } + else { + // content:String + const type = parsePropType(key, opts); + properties[key] = createProperty(key, { + type: PROP_TYPES.indexOf(type) !== -1 ? type : null + }); + } + }); + } + mpComponentOptions.properties = properties; +} + +function initData(vueOptions) { + let data = vueOptions.data || {}; + if (typeof data === 'function') { + try { + const appConfig = getApp().$vm.$.appContext + .config; + data = data.call(appConfig.globalProperties); + } + catch (e) { + if (process.env.VUE_APP_DEBUG) { + console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data, e); + } + } + } + else { + try { + // 对 data 格式化 + data = JSON.parse(JSON.stringify(data)); + } + catch (e) { } + } + if (!isPlainObject(data)) { + data = {}; + } + return data; +} +function initBehaviors(vueOptions, initBehavior) { + const vueBehaviors = vueOptions.behaviors; + const vueExtends = vueOptions.extends; + const vueMixins = vueOptions.mixins; + let vueProps = vueOptions.props; + if (!vueProps) { + vueOptions.props = vueProps = []; + } + const behaviors = []; + if (isArray(vueBehaviors)) { + vueBehaviors.forEach(behavior => { + behaviors.push(behavior.replace('uni://', `${__PLATFORM_PREFIX__}://`)); + if (behavior === 'uni://form-field') { + if (isArray(vueProps)) { + vueProps.push('name'); + vueProps.push('value'); + } + else { + vueProps.name = { + type: String, + default: '' + }; + vueProps.value = { + type: [String, Number, Boolean, Array, Object, Date], + default: '' + }; + } + } + }); + } + if (isPlainObject(vueExtends) && vueExtends.props) { + const behavior = {}; + initProps(behavior, vueExtends.props, true); + behaviors.push(initBehavior(behavior)); + } + if (isArray(vueMixins)) { + vueMixins.forEach(vueMixin => { + if (isPlainObject(vueMixin) && vueMixin.props) { + const behavior = {}; + initProps(behavior, vueMixin.props, true); + behaviors.push(initBehavior(behavior)); + } + }); + } + return behaviors; +} +function applyOptions(componentOptions, vueOptions, initBehavior) { + componentOptions.data = initData(vueOptions); + componentOptions.behaviors = initBehaviors(vueOptions, initBehavior); +} + +function getValue(obj, path) { + const parts = path.split('.'); + let key = parts[0]; + if (key.indexOf('__$n') === 0) { + //number index + key = parseInt(key.replace('__$n', '')); + } + if (parts.length === 1) { + return obj[key]; + } + return getValue(obj[key], parts.slice(1).join('.')); +} +function getExtraValue(instance, dataPathsArray) { + let context = instance; + dataPathsArray.forEach(dataPathArray => { + const dataPath = dataPathArray[0]; + const value = dataPathArray[2]; + if (dataPath || typeof value !== 'undefined') { + // ['','',index,'disable'] + const propPath = dataPathArray[1]; + const valuePath = dataPathArray[3]; + let vFor; + if (Number.isInteger(dataPath)) { + vFor = dataPath; + } + else if (!dataPath) { + vFor = context; + } + else if (typeof dataPath === 'string' && dataPath) { + if (dataPath.indexOf('#s#') === 0) { + vFor = dataPath.substr(3); + } + else { + vFor = getValue(context, dataPath); + } + } + if (Number.isInteger(vFor)) { + context = value; + } + else if (!propPath) { + context = vFor[value]; + } + else { + if (isArray(vFor)) { + context = vFor.find(vForItem => { + return getValue(vForItem, propPath) === value; + }); + } + else if (isPlainObject(vFor)) { + context = Object.keys(vFor).find(vForKey => { + return getValue(vFor[vForKey], propPath) === value; + }); + } + else { + console.error('v-for 暂不支持循环数据:', vFor); + } + } + if (valuePath) { + context = getValue(context, valuePath); + } + } + }); + return context; +} +function processEventExtra(instance, extra, event) { + const extraObj = {}; + if (isArray(extra) && extra.length) { + /** + *[ + * ['data.items', 'data.id', item.data.id], + * ['metas', 'id', meta.id] + *], + *[ + * ['data.items', 'data.id', item.data.id], + * ['metas', 'id', meta.id] + *], + *'test' + */ + extra.forEach((dataPath, index) => { + if (typeof dataPath === 'string') { + if (!dataPath) { + // model,prop.sync + extraObj['$' + index] = instance; + } + else { + if (dataPath === '$event') { + // $event + extraObj['$' + index] = event; + } + else if (dataPath === 'arguments') { + if (event.detail && event.detail.__args__) { + extraObj['$' + index] = event.detail.__args__; + } + else { + extraObj['$' + index] = [event]; + } + } + else if (dataPath.indexOf('$event.') === 0) { + // $event.target.value + extraObj['$' + index] = getValue(event, dataPath.replace('$event.', '')); + } + else { + extraObj['$' + index] = getValue(instance, dataPath); + } + } + } + else { + extraObj['$' + index] = getExtraValue(instance, dataPath); + } + }); + } + return extraObj; +} +function getObjByArray(arr) { + const obj = {}; + for (let i = 1; i < arr.length; i++) { + const element = arr[i]; + obj[element[0]] = element[1]; + } + return obj; +} +function processEventArgs(instance, event, args = [], extra = [], isCustom, methodName) { + let isCustomMPEvent = false; // wxcomponent 组件,传递原始 event 对象 + if (isCustom) { + // 自定义事件 + isCustomMPEvent = + event.currentTarget && + event.currentTarget.dataset && + event.currentTarget.dataset.comType === 'wx'; + if (!args.length) { + // 无参数,直接传入 event 或 detail 数组 + if (isCustomMPEvent) { + return [event]; + } + return event.detail.__args__ || event.detail; + } + } + const extraObj = processEventExtra(instance, extra, event); + const ret = []; + args.forEach(arg => { + if (arg === '$event') { + if (methodName === '__set_model' && !isCustom) { + // input v-model value + ret.push(event.target.value); + } + else { + if (isCustom && !isCustomMPEvent) { + ret.push(event.detail.__args__[0]); + } + else { + // wxcomponent 组件或内置组件 + ret.push(event); + } + } + } + else { + if (isArray(arg) && arg[0] === 'o') { + ret.push(getObjByArray(arg)); + } + else if (typeof arg === 'string' && hasOwn(extraObj, arg)) { + ret.push(extraObj[arg]); + } + else { + ret.push(arg); + } + } + }); + return ret; +} +function wrapper(event) { + event.stopPropagation = NOOP; + event.preventDefault = NOOP; + event.target = event.target || {}; + if (!hasOwn(event, 'detail')) { + event.detail = {}; + } + if (hasOwn(event, 'markerId')) { + event.detail = typeof event.detail === 'object' ? event.detail : {}; + event.detail.markerId = event.markerId; + } + if (isPlainObject(event.detail)) { + event.target = Object.assign({}, event.target, event.detail); + } + return event; +} +const ONCE = '~'; +const CUSTOM = '^'; +function matchEventType(eventType, optType) { + return (eventType === optType || + (optType === 'regionchange' && + (eventType === 'begin' || eventType === 'end'))); +} +function handleEvent(event) { + event = wrapper(event); + // [['tap',[['handle',[1,2,a]],['handle1',[1,2,a]]]]] + const dataset = (event.currentTarget || event.target).dataset; + if (!dataset) { + return console.warn('事件信息不存在'); + } + const eventOpts = (dataset.eventOpts || + dataset['event-opts']); // 支付宝 web-view 组件 dataset 非驼峰 + if (!eventOpts) { + return console.warn('事件信息不存在'); + } + // [['handle',[1,2,a]],['handle1',[1,2,a]]] + const eventType = event.type; + const ret = []; + eventOpts.forEach((eventOpt) => { + let type = eventOpt[0]; + const eventsArray = eventOpt[1]; + const isCustom = type.charAt(0) === CUSTOM; + type = isCustom ? type.slice(1) : type; + const isOnce = type.charAt(0) === ONCE; + type = isOnce ? type.slice(1) : type; + if (eventsArray && matchEventType(eventType, type)) { + eventsArray.forEach((eventArray) => { + const methodName = eventArray[0]; + if (methodName) { + let handlerCtx = this.$vm; + if (handlerCtx.$options.generic && + handlerCtx.$parent && + handlerCtx.$parent.$parent) { + // mp-weixin,mp-toutiao 抽象节点模拟 scoped slots + handlerCtx = handlerCtx.$parent.$parent; + } + if (methodName === '$emit') { + handlerCtx.$emit.apply(handlerCtx, processEventArgs(this.$vm, event, eventArray[1], eventArray[2], isCustom, methodName)); + return; + } + const handler = handlerCtx[methodName]; + if (!isFunction(handler)) { + throw new Error(` _vm.${methodName} is not a function`); + } + if (isOnce) { + if (handler.once) { + return; + } + handler.once = true; + } + ret.push(handler.apply(handlerCtx, processEventArgs(this.$vm, event, eventArray[1], eventArray[2], isCustom, methodName))); + } + }); + } + }); + if (eventType === 'input' && + ret.length === 1 && + typeof ret[0] !== 'undefined') { + return ret[0]; + } +} + +function parseComponent(vueOptions, { parse, mocks, isPage, initRelation, handleLink, initLifetimes }) { + vueOptions = vueOptions.default || vueOptions; + const options = { + multipleSlots: true, + addGlobalClass: true + }; + if (vueOptions.options) { + extend(options, vueOptions.options); + } + const mpComponentOptions = { + options, + lifetimes: initLifetimes({ mocks, isPage, initRelation, vueOptions }), + pageLifetimes: { + show() { + this.$vm && this.$vm.$callHook('onPageShow'); + }, + hide() { + this.$vm && this.$vm.$callHook('onPageHide'); + }, + resize(size) { + this.$vm && this.$vm.$callHook('onPageResize', size); + } + }, + methods: { + __l: handleLink, + __e: handleEvent + } + }; + if (__VUE_OPTIONS_API__) { + applyOptions(mpComponentOptions, vueOptions, initBehavior); + } + initProps(mpComponentOptions, vueOptions.props, false); + initExtraOptions(mpComponentOptions, vueOptions); + initWxsCallMethods(mpComponentOptions.methods, vueOptions.wxsCallMethods); + if (parse) { + parse(mpComponentOptions, { handleLink }); + } + return mpComponentOptions; +} +function initCreateComponent(parseOptions) { + return function createComponent(vueComponentOptions) { + return Component(parseComponent(vueComponentOptions, parseOptions)); + }; +} +let $createComponentFn; +let $destroyComponentFn; +function $createComponent(initialVNode, options) { + if (!$createComponentFn) { + $createComponentFn = getApp().$vm.$createComponent; + } + return $createComponentFn(initialVNode, options); +} +function $destroyComponent(instance) { + if (!$destroyComponentFn) { + $destroyComponentFn = getApp().$vm.$destroyComponent; + } + return $destroyComponentFn(instance); +} + +function parsePage(vueOptions, parseOptions) { + const { parse, mocks, isPage, initRelation, handleLink, initLifetimes } = parseOptions; + const miniProgramPageOptions = parseComponent(vueOptions, { + mocks, + isPage, + initRelation, + handleLink, + initLifetimes + }); + const methods = miniProgramPageOptions.methods; + initHooks(methods, PAGE_HOOKS); + initUnknownHooks(methods, vueOptions); + parse && parse(miniProgramPageOptions, { handleLink }); + return miniProgramPageOptions; +} +function initCreatePage(parseOptions) { + return function createPage(vuePageOptions) { + return Component(parsePage(vuePageOptions, parseOptions)); + }; +} + +const MPPage = Page; +const MPComponent = Component; +const customizeRE = /:/g; +function customize(str) { + return camelize(str.replace(customizeRE, '-')); +} +function initTriggerEvent(mpInstance) { + const oldTriggerEvent = mpInstance.triggerEvent; + mpInstance.triggerEvent = function (event, ...args) { + return oldTriggerEvent.apply(mpInstance, [customize(event), ...args]); + }; +} +function initHook$1(name, options) { + const oldHook = options[name]; + if (!oldHook) { + options[name] = function () { + initTriggerEvent(this); + }; + } + else { + options[name] = function (...args) { + initTriggerEvent(this); + return oldHook.apply(this, args); + }; + } +} +Page = function (options) { + initHook$1('onLoad', options); + return MPPage(options); +}; +Component = function (options) { + initHook$1('created', options); + return MPComponent(options); +}; + +function provide(instance, key, value) { + if (!instance) { + if ((process.env.NODE_ENV !== 'production')) { + console.warn(`provide() can only be used inside setup().`); + } + } + else { + let provides = instance.provides; + // by default an instance inherits its parent's provides object + // but when it needs to provide values of its own, it creates its + // own provides object using parent provides object as prototype. + // this way in `inject` we can simply look up injections from direct + // parent and let the prototype chain do the work. + const parentProvides = instance.parent && instance.parent.provides; + if (parentProvides === provides) { + provides = instance.provides = Object.create(parentProvides); + } + // TS doesn't allow symbol as index type + provides[key] = value; + } +} +function initProvide(instance) { + const provideOptions = instance.$options.provide; + if (!provideOptions) { + return; + } + const provides = isFunction(provideOptions) + ? provideOptions.call(instance) + : provideOptions; + const internalInstance = instance.$; + for (const key in provides) { + provide(internalInstance, key, provides[key]); + } +} +function inject(instance, key, defaultValue) { + if (instance) { + const provides = instance.provides; + if (key in provides) { + // TS doesn't allow symbol as index type + return provides[key]; + } + else if (arguments.length > 1) { + return defaultValue; + } + else if ((process.env.NODE_ENV !== 'production')) { + console.warn(`injection "${String(key)}" not found.`); + } + } + else if ((process.env.NODE_ENV !== 'production')) { + console.warn(`inject() can only be used inside setup() or functional components.`); + } +} +function initInjections(instance) { + const injectOptions = instance.$options.inject; + if (!injectOptions) { + return; + } + const internalInstance = instance.$; + const ctx = internalInstance.ctx; + if (isArray(injectOptions)) { + for (let i = 0; i < injectOptions.length; i++) { + const key = injectOptions[i]; + ctx[key] = inject(internalInstance, key); + } + } + else { + for (const key in injectOptions) { + const opt = injectOptions[key]; + if (isObject(opt)) { + ctx[key] = inject(internalInstance, opt.from, opt.default); + } + else { + ctx[key] = inject(internalInstance, opt); + } + } + } +} + +function initLifetimes({ mocks, isPage, initRelation, vueOptions }) { + return { + attached() { + const properties = this.properties; + initVueIds(properties.vueId, this); + const relationOptions = { + vuePid: this._$vuePid + }; + // 初始化 vue 实例 + const mpInstance = this; + const mpType = isPage(mpInstance) ? 'page' : 'component'; + if (mpType === 'page' && !mpInstance.route && mpInstance.__route__) { + mpInstance.route = mpInstance.__route__; + } + this.$vm = $createComponent({ + type: vueOptions, + props: properties + }, { + mpType, + mpInstance, + slots: properties.vueSlots, + parentComponent: relationOptions.parent && relationOptions.parent.$, + onBeforeSetup(instance, options) { + initRefs(instance, mpInstance); + initMocks(instance, mpInstance, mocks); + initComponentInstance(instance, options); + } + }); + // 处理父子关系 + initRelation(this, relationOptions); + }, + detached() { + this.$vm && $destroyComponent(this.$vm); + } + }; +} + +const mocks = [ + '__route__', + '__webviewId__', + '__nodeId__', + '__nodeid__' /* @Deprecated */ +]; +function isPage(mpInstance) { + return (mpInstance.__nodeId__ === 0 || mpInstance.__nodeid__ === 0); +} +const instances = Object.create(null); +function initRelation(mpInstance, detail) { + // 头条 triggerEvent 后,接收事件时机特别晚,已经到了 ready 之后 + const nodeId = hasOwn(mpInstance, '__nodeId__') + ? mpInstance.__nodeId__ + : mpInstance.__nodeid__; + const webviewId = mpInstance.__webviewId__ + ''; + instances[webviewId + '_' + nodeId] = mpInstance.$vm; + mpInstance.triggerEvent('__l', { + vuePid: detail.vuePid, + nodeId, + webviewId + }); +} +function handleLink({ detail: { vuePid, nodeId, webviewId } }) { + const vm = instances[webviewId + '_' + nodeId]; + if (!vm) { + return; + } + let parentVm; + if (vuePid) { + parentVm = findVmByVueId(this.$vm, vuePid); + } + if (!parentVm) { + parentVm = this.$vm; + } + vm.$.parent = parentVm.$; + if (__VUE_OPTIONS_API__) { + parentVm.$children.push(vm); + const parent = parentVm.$; + vm.$.provides = parent + ? parent.provides + : Object.create(parent.appContext.provides); + initInjections(vm); + initProvide(vm); + } + vm.$callSyncHook('created'); + vm.$callHook('mounted'); + vm.$callHook('onReady'); +} +function parse(componentOptions, { handleLink }) { + componentOptions.methods.__l = handleLink; +} + +var parseComponentOptions = /*#__PURE__*/Object.freeze({ + __proto__: null, + mocks: mocks, + isPage: isPage, + instances: instances, + initRelation: initRelation, + handleLink: handleLink, + parse: parse, + initLifetimes: initLifetimes +}); + +function initLifetimes$1(lifetimesOptions) { + return extend(initLifetimes(lifetimesOptions), { + ready() { + if (this.$vm && lifetimesOptions.isPage(this)) { + this.$vm.$callSyncHook('created'); + this.$vm.$callHook('mounted'); + this.$vm.$callHook('onReady'); + } + else { + this.is && console.warn(this.is + ' is not ready'); + } + }, + detached() { + this.$vm && $destroyComponent(this.$vm); + // 清理 + const webviewId = this.__webviewId__; + webviewId && + Object.keys(instances).forEach(key => { + if (key.indexOf(webviewId + '_') === 0) { + delete instances[key]; + } + }); + } + }); +} + +var parsePageOptions = /*#__PURE__*/Object.freeze({ + __proto__: null, + mocks: mocks, + isPage: isPage, + initRelation: initRelation, + handleLink: handleLink, + parse: parse, + initLifetimes: initLifetimes$1 +}); + +const createApp = initCreateApp(); +const createPage = initCreatePage(parsePageOptions); +const createComponent = initCreateComponent(parseComponentOptions); + +export { createApp, createComponent, createPage }; diff --git a/packages/uni-mp-vue/dist/vue.runtime.esm.js b/packages/uni-mp-vue/dist/vue.runtime.esm.js index fefb78aecf05e611ad78abb8be3c411598685914..f5735ef548a5d74c654242c5125c02f37439d83d 100644 --- a/packages/uni-mp-vue/dist/vue.runtime.esm.js +++ b/packages/uni-mp-vue/dist/vue.runtime.esm.js @@ -277,7 +277,9 @@ function deleteProperty(target, key) { } function has(target, key) { const result = Reflect.has(target, key); - track(target, "has" /* HAS */, key); + if (!isSymbol(key) || !builtInSymbols.has(key)) { + track(target, "has" /* HAS */, key); + } return result; } function ownKeys(target) { @@ -608,17 +610,18 @@ function createReactiveObject(target, isReadonly, baseHandlers, collectionHandle return target; } // target already has corresponding Proxy - if (hasOwn(target, isReadonly ? "__v_readonly" /* READONLY */ : "__v_reactive" /* REACTIVE */)) { - return isReadonly - ? target["__v_readonly" /* READONLY */] - : target["__v_reactive" /* REACTIVE */]; + const reactiveFlag = isReadonly + ? "__v_readonly" /* READONLY */ + : "__v_reactive" /* REACTIVE */; + if (hasOwn(target, reactiveFlag)) { + return target[reactiveFlag]; } // only a whitelist of value types can be observed. if (!canObserve(target)) { return target; } const observed = new Proxy(target, collectionTypes.has(target.constructor) ? collectionHandlers : baseHandlers); - def(target, isReadonly ? "__v_readonly" /* READONLY */ : "__v_reactive" /* REACTIVE */, observed); + def(target, reactiveFlag, observed); return observed; } function isReactive(value) { @@ -742,6 +745,7 @@ function computed(getterOrOptions) { }); computed = { __v_isRef: true, + ["__v_isReadonly" /* IS_READONLY */]: isFunction(getterOrOptions) || !getterOrOptions.set, // expose effect so computed can be stopped effect: runner, get value() { @@ -1145,7 +1149,7 @@ function normalizeEmitsOptions(comp) { let normalized = {}; // apply mixin/extends props let hasExtends = false; - if (__FEATURE_OPTIONS__ && !isFunction(comp)) { + if (__VUE_OPTIONS_API__ && !isFunction(comp)) { if (comp.extends) { hasExtends = true; extend(normalized, normalizeEmitsOptions(comp.extends)); @@ -1271,7 +1275,7 @@ function normalizePropsOptions(comp) { const needCastKeys = []; // apply mixin/extends props let hasExtends = false; - if (__FEATURE_OPTIONS__ && !isFunction(comp)) { + if (__VUE_OPTIONS_API__ && !isFunction(comp)) { const extendProps = (raw) => { const [props, keys] = normalizePropsOptions(raw); extend(normalized, props); @@ -1611,9 +1615,9 @@ function validateDirectiveName(name) { function createAppContext() { return { + app: null, config: { isNativeTag: NO, - devtools: true, performance: false, globalProperties: {}, optionMergeStrategies: {}, @@ -1638,7 +1642,7 @@ function createAppAPI() { const installedPlugins = new Set(); // fixed by xxxxxx // let isMounted = false - const app = { + const app = (context.app = { _component: rootComponent, _props: rootProps, _container: null, @@ -1671,7 +1675,7 @@ function createAppAPI() { return app; }, mixin(mixin) { - if (__FEATURE_OPTIONS__) { + if (__VUE_OPTIONS_API__) { if (!context.mixins.includes(mixin)) { context.mixins.push(mixin); } @@ -1725,29 +1729,11 @@ function createAppAPI() { context.provides[key] = value; return app; } - }; - context.__app = app; + }); return app; }; } -var DevtoolsHooks; -(function (DevtoolsHooks) { - DevtoolsHooks["APP_INIT"] = "app:init"; - DevtoolsHooks["APP_UNMOUNT"] = "app:unmount"; - DevtoolsHooks["COMPONENT_UPDATED"] = "component:updated"; - DevtoolsHooks["COMPONENT_ADDED"] = "component:added"; - DevtoolsHooks["COMPONENT_REMOVED"] = "component:removed"; -})(DevtoolsHooks || (DevtoolsHooks = {})); -const componentAdded = createDevtoolsHook(DevtoolsHooks.COMPONENT_ADDED); -const componentUpdated = createDevtoolsHook(DevtoolsHooks.COMPONENT_UPDATED); -const componentRemoved = createDevtoolsHook(DevtoolsHooks.COMPONENT_REMOVED); -function createDevtoolsHook(hook) { - return (component) => { - return; - }; -} - const queuePostRenderEffect = queuePostFlushCb; // Simple effect. @@ -1781,7 +1767,14 @@ function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EM `a reactive object, or an array of these types.`); }; let getter; - if (isArray(source)) { + if (isRef(source)) { + getter = () => source.value; + } + else if (isReactive(source)) { + getter = () => source; + deep = true; + } + else if (isArray(source)) { getter = () => source.map(s => { if (isRef(s)) { return s.value; @@ -1797,13 +1790,6 @@ function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EM } }); } - else if (isRef(source)) { - getter = () => source.value; - } - else if (isReactive(source)) { - getter = () => source; - deep = true; - } else if (isFunction(source)) { if (cb) { // getter with cb @@ -2007,8 +1993,6 @@ function applyOptions(instance, options, deferredData = [], deferredWatch = [], mixins, extends: extendsOptions, // state data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions, - // assets - components, directives, // lifecycle beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeUnmount, unmounted, renderTracked, renderTriggered, errorCaptured } = options; const publicThis = instance.proxy; @@ -2045,7 +2029,8 @@ function applyOptions(instance, options, deferredData = [], deferredWatch = [], // - data (deferred since it relies on `this` access) // - computed // - watch (deferred since it relies on `this` access) - if (injectOptions) { + // fixed by xxxxxx + if (!__VUE_CREATED_DEFERRED__ && injectOptions) { if (isArray(injectOptions)) { for (let i = 0; i < injectOptions.length; i++) { const key = injectOptions[i]; @@ -2160,7 +2145,8 @@ function applyOptions(instance, options, deferredData = [], deferredWatch = [], } }); } - if (provideOptions) { + // fixed by xxxxxx + if (!__VUE_CREATED_DEFERRED__ && provideOptions) { const provides = isFunction(provideOptions) ? provideOptions.call(publicThis) : provideOptions; @@ -2168,15 +2154,14 @@ function applyOptions(instance, options, deferredData = [], deferredWatch = [], provide(key, provides[key]); } } - // asset options - if (components) { - extend(instance.components, components); - } - if (directives) { - extend(instance.directives, directives); - } + // fixed by xxxxxx // lifecycle options - if (!asMixin) { + if (__VUE_CREATED_DEFERRED__) { + ctx.$callSyncHook = function (name) { + return callSyncHook(name, options, publicThis, globalMixins); + }; + } + else if (!asMixin) { callSyncHook('created', options, publicThis, globalMixins); } if (beforeMount) { @@ -2323,14 +2308,14 @@ const publicPropertiesMap = extend(Object.create(null), { $props: i => ((process.env.NODE_ENV !== 'production') ? shallowReadonly(i.props) : i.props), $attrs: i => ((process.env.NODE_ENV !== 'production') ? shallowReadonly(i.attrs) : i.attrs), $slots: i => ((process.env.NODE_ENV !== 'production') ? shallowReadonly(i.slots) : i.slots), - // $refs: i => ((process.env.NODE_ENV !== 'production') ? shallowReadonly(i.refs) : i.refs), // fixed by xxxxxx + $refs: i => ((process.env.NODE_ENV !== 'production') ? shallowReadonly(i.refs) : i.refs), $parent: i => i.parent && i.parent.proxy, $root: i => i.root && i.root.proxy, $emit: i => i.emit, - $options: i => (__FEATURE_OPTIONS__ ? resolveMergedOptions(i) : i.type), + $options: i => (__VUE_OPTIONS_API__ ? resolveMergedOptions(i) : i.type), $forceUpdate: i => () => queueJob(i.update), // $nextTick: () => nextTick, // fixed by xxxxxx - $watch: __FEATURE_OPTIONS__ ? i => instanceWatch.bind(i) : NOOP + $watch: i => (__VUE_OPTIONS_API__ ? instanceWatch.bind(i) : NOOP) }); const PublicInstanceProxyHandlers = { get({ _: instance }, key) { @@ -2560,14 +2545,15 @@ function exposeSetupStateOnRenderContext(instance) { const emptyAppContext = createAppContext(); let uid$1 = 0; function createComponentInstance(vnode, parent, suspense) { + const type = vnode.type; // inherit parent app context - or - if root, adopt from root vnode const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext; const instance = { uid: uid$1++, vnode, + type, parent, appContext, - type: vnode.type, root: null, next: null, subTree: null, @@ -2588,9 +2574,6 @@ function createComponentInstance(vnode, parent, suspense) { refs: EMPTY_OBJ, setupState: EMPTY_OBJ, setupContext: null, - // per-instance asset storage (mutable during options resolution) - components: Object.create(appContext.components), - directives: Object.create(appContext.directives), // suspense related suspense, asyncDep: null, @@ -2624,7 +2607,7 @@ function createComponentInstance(vnode, parent, suspense) { } instance.root = parent ? parent.root : instance; instance.emit = emit.bind(null, instance); - (process.env.NODE_ENV !== 'production') && componentAdded(instance); + if ((process.env.NODE_ENV !== 'production') || false) ; return instance; } let currentInstance = null; @@ -2757,7 +2740,7 @@ function finishComponentSetup(instance, isSSR) { } } // support for 2.x options - if (__FEATURE_OPTIONS__) { + if (__VUE_OPTIONS_API__) { currentInstance = instance; applyOptions(instance, Component); currentInstance = null; @@ -2822,14 +2805,16 @@ function formatComponentName(instance, Component, isRoot = false) { } } if (!name && instance && instance.parent) { - // try to infer the name based on local resolution - const registry = instance.parent.components; - for (const key in registry) { - if (registry[key] === Component) { - name = key; - break; + // try to infer the name based on reverse resolution + const inferFromRegistry = (registry) => { + for (const key in registry) { + if (registry[key] === Component) { + return key; + } } - } + }; + name = + inferFromRegistry(instance.parent.type.components) || inferFromRegistry(instance.appContext.components); } return name ? classify(name) : isRoot ? `App` : `Anonymous`; } @@ -2841,7 +2826,7 @@ function computed$1(getterOrOptions) { } // Core API ------------------------------------------------------------------ -const version = "3.0.0-rc.2"; +const version = "3.0.0-rc.4"; // import deepCopy from './deepCopy' /** @@ -2994,7 +2979,7 @@ function nextTick$1(instance, fn) { instance.uid + ']:nextVueTick'); } - return nextTick(fn); + return nextTick(fn && fn.bind(instance.proxy)); } if (process.env.VUE_APP_DEBUG) { const mpInstance = ctx.$scope; @@ -3012,7 +2997,7 @@ function nextTick$1(instance, fn) { } ctx.__next_tick_callbacks.push(() => { if (fn) { - callWithErrorHandling(fn, instance, 14 /* SCHEDULER */); + callWithErrorHandling(fn.bind(instance.proxy), instance, 14 /* SCHEDULER */); } else if (_resolve) { _resolve(instance.proxy); @@ -3048,7 +3033,7 @@ function getVueInstanceData(instance) { } }); } - if (__FEATURE_OPTIONS__) { + if (__VUE_OPTIONS_API__) { if (ctx.$computedKeys) { ctx.$computedKeys.forEach((key) => { if (!keys.has(key)) { @@ -3058,6 +3043,11 @@ function getVueInstanceData(instance) { }); } } + if (ctx.$mp) { + // TODO + extend(ret, ctx.$mp.data || {}); + } + // TODO form-field // track return { keys, data: JSON.parse(JSON.stringify(ret)) }; } @@ -3143,7 +3133,7 @@ var MPType; const queuePostRenderEffect$1 = queuePostFlushCb; function mountComponent(initialVNode, options) { const instance = (initialVNode.component = createComponentInstance(initialVNode, options.parentComponent, null)); - if (__FEATURE_OPTIONS__) { + if (__VUE_OPTIONS_API__) { instance.ctx.$onApplyOptions = onApplyOptions; instance.ctx.$children = []; } @@ -3157,7 +3147,7 @@ function mountComponent(initialVNode, options) { pushWarningContext(initialVNode); } setupComponent(instance); - if (__FEATURE_OPTIONS__) { + if (__VUE_OPTIONS_API__) { // $children if (options.parentComponent && instance.proxy) { options.parentComponent.ctx @@ -3184,15 +3174,11 @@ function setupRenderEffect(instance) { // create reactive effect for rendering instance.update = effect(function componentEffect() { if (!instance.isMounted) { - const { bm } = instance; - // beforeMount hook - if (bm) { - invokeArrayFns(bm); - } + instance.render && instance.render.call(instance.proxy); patch(instance); - instance.isMounted = true; } else { + instance.render && instance.render.call(instance.proxy); // updateComponent const { bu, u } = instance; // beforeUpdate hook diff --git a/packages/uni-mp-weixin/dist/uni.api.esm.js b/packages/uni-mp-weixin/dist/uni.api.esm.js index da6a9b1944a8d741afe88a89e73ddce4dda2173d..ce82670af3c5b5c3a503a8497b3af9735c987413 100644 --- a/packages/uni-mp-weixin/dist/uni.api.esm.js +++ b/packages/uni-mp-weixin/dist/uni.api.esm.js @@ -223,6 +223,9 @@ function isCallbackApi(name) { return CALLBACK_API_RE.test(name) && name !== 'onPush'; } function handlePromise(promise) { + if (!__UNI_PROMISE_API__) { + return promise; + } return promise .then(data => { return [null, data]; @@ -288,7 +291,7 @@ function initWrapper(protocols) { } if (!keyOption) { // 不支持的参数 - console.warn(`__MP_TITLE__ ${methodName}暂不支持${key}`); + console.warn(`微信小程序 ${methodName} 暂不支持 ${key}`); } else if (isString(keyOption)) { // 重写参数 key @@ -306,7 +309,7 @@ function initWrapper(protocols) { } } else { - if (!keepFromArgs) { + if (!keepFromArgs && !hasOwn(toArgs, key)) { toArgs[key] = fromArgs[key]; } } @@ -333,7 +336,7 @@ function initWrapper(protocols) { if (!protocol) { // 暂不支持的 api return function () { - console.error(`__MP_TITLE__ 暂不支持${methodName}`); + console.error(`微信小程序 暂不支持${methodName}`); }; } return function (arg1, arg2) { @@ -379,8 +382,29 @@ function initUni(api, protocols) { return new Proxy({}, UniProxyHandlers); } +function initGetProvider(providers) { + return function getProvider({ service, success, fail, complete }) { + let res; + if (providers[service]) { + res = { + errMsg: 'getProvider:ok', + service, + provider: providers[service] + }; + isFunction(success) && success(res); + } + else { + res = { + errMsg: 'getProvider:fail:服务[' + service + ']不存在' + }; + isFunction(fail) && fail(res); + } + isFunction(complete) && complete(res); + }; +} + const previewImage = { - args(fromArgs) { + args(fromArgs, toArgs) { let currentIndex = parseInt(fromArgs.current); if (isNaN(currentIndex)) { return; @@ -400,27 +424,26 @@ const previewImage = { currentIndex = len - 1; } if (currentIndex > 0) { - fromArgs.current = urls[currentIndex]; - fromArgs.urls = urls.filter((item, index) => index < currentIndex ? item !== urls[currentIndex] : true); + toArgs.current = urls[currentIndex]; + toArgs.urls = urls.filter((item, index) => index < currentIndex ? item !== urls[currentIndex] : true); } else { - fromArgs.current = urls[0]; + toArgs.current = urls[0]; } return { indicator: false, loop: false }; } -}; - -function addSafeAreaInsets(result) { - if (result.safeArea) { - const safeArea = result.safeArea; - result.safeAreaInsets = { +}; +function addSafeAreaInsets(fromRes, toRes) { + if (fromRes.safeArea) { + const safeArea = fromRes.safeArea; + toRes.safeAreaInsets = { top: safeArea.top, left: safeArea.left, - right: result.windowWidth - safeArea.right, - bottom: result.windowHeight - safeArea.bottom + right: fromRes.windowWidth - safeArea.right, + bottom: fromRes.windowHeight - safeArea.bottom }; } } @@ -429,13 +452,25 @@ const getSystemInfo = { }; const getSystemInfoSync = getSystemInfo; +const getProvider = initGetProvider({ + oauth: ['weixin'], + share: ['weixin'], + payment: ['wxpay'], + push: ['weixin'] +}); + +var shims = /*#__PURE__*/Object.freeze({ + __proto__: null, + getProvider: getProvider +}); + var protocols = /*#__PURE__*/Object.freeze({ __proto__: null, + previewImage: previewImage, getSystemInfo: getSystemInfo, - getSystemInfoSync: getSystemInfoSync, - previewImage: previewImage + getSystemInfoSync: getSystemInfoSync }); -var index = initUni({}, protocols); +var index = initUni(shims, protocols); export default index; diff --git a/packages/uni-mp-weixin/dist/uni.mp.esm.js b/packages/uni-mp-weixin/dist/uni.mp.esm.js index daf7371b6d3a15124acdb8e3818ea73b5042b037..d238158782953ac7c2aa4c206055c5c7824792bd 100644 --- a/packages/uni-mp-weixin/dist/uni.mp.esm.js +++ b/packages/uni-mp-weixin/dist/uni.mp.esm.js @@ -1,77 +1,4 @@ -import { hasOwn, isArray, isFunction, toNumber, isPlainObject, isObject, extend, NOOP } from '@vue/shared'; - -function findHooks(vueOptions, hooks = new Set()) { - if (vueOptions) { - Object.keys(vueOptions).forEach(name => { - if (name.indexOf('on') === 0 && isFunction(vueOptions[name])) { - hooks.add(name); - } - }); - const { extends: extendsOptions, mixins } = vueOptions; - if (mixins) { - mixins.forEach(mixin => findHooks(mixin, hooks)); - } - if (extendsOptions) { - findHooks(extendsOptions, hooks); - } - } - return hooks; -} -function initHook(mpOptions, hook) { - mpOptions[hook] = function (args) { - return this.$vm && this.$vm.$callHook(hook, args); - }; -} -function initHooks(mpOptions, hooks) { - hooks.forEach(hook => initHook(mpOptions, hook)); -} -function initUnknownHooks(mpOptions, vueOptions) { - findHooks(vueOptions).forEach(hook => { - if (!mpOptions[hook]) { - initHook(mpOptions, hook); - } - }); -} -function initVueIds(vueIds, mpInstance) { - if (!vueIds) { - return; - } - const ids = vueIds.split(','); - const len = ids.length; - if (len === 1) { - mpInstance._$vueId = ids[0]; - } - else if (len === 2) { - mpInstance._$vueId = ids[0]; - mpInstance._$vuePid = ids[1]; - } -} -function initMocks(instance, mpInstance, mocks) { - const ctx = instance.ctx; - mocks.forEach(mock => { - if (hasOwn(mpInstance, mock)) { - ctx[mock] = mpInstance[mock]; - } - }); -} -const EXTRAS = ['externalClasses']; -function initExtraOptions(miniProgramComponentOptions, vueOptions) { - EXTRAS.forEach(name => { - if (hasOwn(vueOptions, name)) { - miniProgramComponentOptions[name] = vueOptions[name]; - } - }); -} -function initWxsCallMethods(methods, wxsCallMethods) { - if (!isArray(wxsCallMethods)) { - return; - } - wxsCallMethods.forEach((callMethod) => { - methods[callMethod] = function (args) { - return this.$vm[callMethod](args); - }; - }); -} +import { isArray, hasOwn, toNumber, isPlainObject, isObject, isFunction, extend, NOOP, camelize } from '@vue/shared'; function setModel(target, key, value, modifiers) { if (isArray(modifiers)) { @@ -134,6 +61,8 @@ function hasHook(name) { } function callHook(name, args) { if (name === 'mounted') { + callHook.call(this, 'bm'); // beforeMount + this.$.isMounted = true; name = 'm'; } const hooks = this.$[name]; @@ -162,16 +91,21 @@ function initBaseInstance(instance, options) { ctx.mpType = options.mpType; // @deprecated ctx.$mpType = options.mpType; ctx.$scope = options.mpInstance; + // TODO @deprecated + ctx.$mp = {}; + ctx._self = {}; // $vm ctx.$scope.$vm = instance.proxy; // slots - instance.slots = {}; - if (isArray(options.slots) && options.slots.length) { - options.slots.forEach(name => { - instance.slots[name] = true; - }); + { + instance.slots = {}; + if (isArray(options.slots) && options.slots.length) { + options.slots.forEach(name => { + instance.slots[name] = true; + }); + } } - if (__FEATURE_OPTIONS__) { + if (__VUE_OPTIONS_API__) { // $set ctx.$set = set; } @@ -199,6 +133,61 @@ function initComponentInstance(instance, options) { // TODO // ctx.__get_style = getStyle ctx.__map = map; +} +function initMocks(instance, mpInstance, mocks) { + const ctx = instance.ctx; + mocks.forEach(mock => { + if (hasOwn(mpInstance, mock)) { + ctx[mock] = mpInstance[mock]; + } + }); +} + +const PAGE_HOOKS = [ + 'onLoad', + 'onShow', + // 'onReady', // lifetimes.ready + 'onHide', + 'onUnload', + 'onResize', + // 'onPageScroll', // 影响性能,开发者手动注册 + 'onTabItemTap', + 'onReachBottom', + 'onPullDownRefresh', + // 'onShareTimeline', // 右上角菜单,开发者手动注册 + 'onAddToFavorites' + // 'onShareAppMessage' // 右上角菜单,开发者手动注册 +]; +function findHooks(vueOptions, hooks = new Set()) { + if (vueOptions) { + Object.keys(vueOptions).forEach(name => { + if (name.indexOf('on') === 0 && isFunction(vueOptions[name])) { + hooks.add(name); + } + }); + const { extends: extendsOptions, mixins } = vueOptions; + if (mixins) { + mixins.forEach(mixin => findHooks(mixin, hooks)); + } + if (extendsOptions) { + findHooks(extendsOptions, hooks); + } + } + return hooks; +} +function initHook(mpOptions, hook, excludes) { + if (excludes.indexOf(hook) === -1 && !hasOwn(mpOptions, hook)) { + mpOptions[hook] = function (args) { + return this.$vm && this.$vm.$callHook(hook, args); + }; + } +} +const EXCLUDE_HOOKS = ['onReady']; +function initHooks(mpOptions, hooks, excludes = EXCLUDE_HOOKS) { + hooks.forEach(hook => initHook(mpOptions, hook, excludes)); +} +function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) { + findHooks(vueOptions).forEach(hook => initHook(mpOptions, hook, excludes)); } const HOOKS = [ @@ -209,12 +198,14 @@ const HOOKS = [ 'onPageNotFound', 'onUnhandledRejection' ]; -function parseApp(instance) { +function parseApp(instance, parseAppOptions) { const internalInstance = instance.$; const appOptions = { globalData: (instance.$options && instance.$options.globalData) || {}, + $vm: instance, onLaunch(options) { - if (this.$vm) { + const ctx = internalInstance.ctx; + if (this.$vm && ctx.$callHook) { // 已经初始化过了,主要是为了百度,百度 onShow 在 onLaunch 之前 return; } @@ -223,7 +214,6 @@ function parseApp(instance) { mpInstance: this, slots: [] }); - const ctx = internalInstance.ctx; ctx.globalData = this.globalData; instance.$callHook('onLaunch', options); } @@ -231,16 +221,100 @@ function parseApp(instance) { const vueOptions = instance.$.type; initHooks(appOptions, HOOKS); initUnknownHooks(appOptions, vueOptions); - if (__FEATURE_OPTIONS__) { + if (__VUE_OPTIONS_API__) { const methods = vueOptions.methods; methods && extend(appOptions, methods); } + if (parseAppOptions) { + parseAppOptions.parse(appOptions); + } return appOptions; +} +function initCreateApp(parseAppOptions) { + return function createApp(vm) { + return App(parseApp(vm, parseAppOptions)); + }; +} + +function initBehavior(options) { + return Behavior(options); +} +function initVueIds(vueIds, mpInstance) { + if (!vueIds) { + return; + } + const ids = vueIds.split(','); + const len = ids.length; + if (len === 1) { + mpInstance._$vueId = ids[0]; + } + else if (len === 2) { + mpInstance._$vueId = ids[0]; + mpInstance._$vuePid = ids[1]; + } +} +const EXTRAS = ['externalClasses']; +function initExtraOptions(miniProgramComponentOptions, vueOptions) { + EXTRAS.forEach(name => { + if (hasOwn(vueOptions, name)) { + miniProgramComponentOptions[name] = vueOptions[name]; + } + }); +} +function initWxsCallMethods(methods, wxsCallMethods) { + if (!isArray(wxsCallMethods)) { + return; + } + wxsCallMethods.forEach((callMethod) => { + methods[callMethod] = function (args) { + return this.$vm[callMethod](args); + }; + }); +} +function initRefs(instance, mpInstance) { + Object.defineProperty(instance, 'refs', { + get() { + const $refs = {}; + const components = mpInstance.selectAllComponents('.vue-ref'); + components.forEach(component => { + const ref = component.dataset.ref; + $refs[ref] = component.$vm || component; + }); + const forComponents = mpInstance.selectAllComponents('.vue-ref-in-for'); + forComponents.forEach(component => { + const ref = component.dataset.ref; + if (!$refs[ref]) { + $refs[ref] = []; + } + $refs[ref].push(component.$vm || component); + }); + return $refs; + } + }); +} +function findVmByVueId(instance, vuePid) { + // TODO vue3 中 没有 $children + const $children = instance.$children; + // 优先查找直属(反向查找:https://github.com/dcloudio/uni-app/issues/1200) + for (let i = $children.length - 1; i >= 0; i--) { + const childVm = $children[i]; + if (childVm.$scope._$vueId === vuePid) { + return childVm; + } + } + // 反向递归查找 + let parentVm; + for (let i = $children.length - 1; i >= 0; i--) { + parentVm = findVmByVueId($children[i], vuePid); + if (parentVm) { + return parentVm; + } + } } const PROP_TYPES = [String, Number, Boolean, Object, Array, null]; function createObserver(name) { - return function observer(newVal, oldVal) { + return function observer(newVal) { if (this.$vm) { this.$vm.$.props[name] = newVal; // 为了触发其他非 render watcher } @@ -264,7 +338,7 @@ function initDefaultProps(isBehavior = false) { properties.vueSlots = { type: null, value: [], - observer: function (newVal, oldVal) { + observer: function (newVal) { const $slots = Object.create(null); newVal.forEach((slotName) => { $slots[slotName] = true; @@ -277,14 +351,17 @@ function initDefaultProps(isBehavior = false) { } return properties; } -function initProps(miniProgramComponentOptions, rawProps, isBehavior = false) { +function createProperty(key, prop) { + prop.observer = createObserver(key); + return prop; +} +function initProps(mpComponentOptions, rawProps, isBehavior = false) { const properties = initDefaultProps(isBehavior); if (isArray(rawProps)) { rawProps.forEach(key => { - properties[key] = { - type: null, - observer: createObserver(key) - }; + properties[key] = createProperty(key, { + type: null + }); }); } else if (isPlainObject(rawProps)) { @@ -298,36 +375,34 @@ function initProps(miniProgramComponentOptions, rawProps, isBehavior = false) { } const type = opts.type; opts.type = parsePropType(key, type); - properties[key] = { + properties[key] = createProperty(key, { type: PROP_TYPES.indexOf(type) !== -1 ? type : null, - value, - observer: createObserver(key) - }; + value + }); } else { // content:String const type = parsePropType(key, opts); - properties[key] = { - type: PROP_TYPES.indexOf(type) !== -1 ? type : null, - observer: createObserver(key) - }; + properties[key] = createProperty(key, { + type: PROP_TYPES.indexOf(type) !== -1 ? type : null + }); } }); } - miniProgramComponentOptions.properties = properties; + mpComponentOptions.properties = properties; } function initData(vueOptions) { let data = vueOptions.data || {}; if (typeof data === 'function') { try { - const appConfig = getApp() - .$vm.$.appContext.config; + const appConfig = getApp().$vm.$.appContext + .config; data = data.call(appConfig.globalProperties); } catch (e) { if (process.env.VUE_APP_DEBUG) { - console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data); + console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data, e); } } } @@ -389,9 +464,9 @@ function initBehaviors(vueOptions, initBehavior) { } return behaviors; } -function applyOptions(miniProgramComponentOptions, vueOptions, initBehavior) { - miniProgramComponentOptions.data = initData(vueOptions); - miniProgramComponentOptions.behaviors = initBehaviors(vueOptions, initBehavior); +function applyOptions(componentOptions, vueOptions, initBehavior) { + componentOptions.data = initData(vueOptions); + componentOptions.behaviors = initBehaviors(vueOptions, initBehavior); } function getValue(obj, path) { @@ -645,7 +720,7 @@ function handleEvent(event) { } } -function parseComponent(vueOptions, { mocks, isPage, initRefs, initRelation, initBehavior, handleLink }) { +function parseComponent(vueOptions, { parse, mocks, isPage, initRelation, handleLink, initLifetimes }) { vueOptions = vueOptions.default || vueOptions; const options = { multipleSlots: true, @@ -654,47 +729,9 @@ function parseComponent(vueOptions, { mocks, isPage, initRefs, initRelation, ini if (vueOptions.options) { extend(options, vueOptions.options); } - const miniProgramComponentOptions = { + const mpComponentOptions = { options, - lifetimes: { - attached() { - const properties = this.properties; - initVueIds(properties.vueId, this); - const relationOptions = { - vuePid: this._$vuePid - }; - // 处理父子关系 - initRelation(this, relationOptions); - // TODO mp-toutiao - // 初始化 vue 实例 - const mpInstance = this; - this.$vm = getApp().$vm.$createComponent({ - type: vueOptions, - props: properties - }, { - mpType: isPage(mpInstance) ? 'page' : 'component', - mpInstance, - slots: properties.vueSlots, - parentComponent: relationOptions.parent && relationOptions.parent.$, - onBeforeSetup(instance, options) { - initRefs(instance, mpInstance); - initMocks(instance, mpInstance, mocks); - initComponentInstance(instance, options); - } - }); - }, - ready() { - // 当组件 props 默认值为 true,初始化时传入 false 会导致 created,ready 触发, 但 attached 不触发 - // https://developers.weixin.qq.com/community/develop/doc/00066ae2844cc0f8eb883e2a557800 - if (this.$vm) { - this.$vm.$callHook('mounted'); - this.$vm.$callHook('onReady'); - } - }, - detached() { - getApp().$vm.$destroyComponent(this.$vm); - } - }, + lifetimes: initLifetimes({ mocks, isPage, initRelation, vueOptions }), pageLifetimes: { show() { this.$vm && this.$vm.$callHook('onPageShow'); @@ -711,92 +748,141 @@ function parseComponent(vueOptions, { mocks, isPage, initRefs, initRelation, ini __e: handleEvent } }; - if (__FEATURE_OPTIONS__) { - applyOptions(miniProgramComponentOptions, vueOptions, initBehavior); + if (__VUE_OPTIONS_API__) { + applyOptions(mpComponentOptions, vueOptions, initBehavior); + } + initProps(mpComponentOptions, vueOptions.props, false); + initExtraOptions(mpComponentOptions, vueOptions); + initWxsCallMethods(mpComponentOptions.methods, vueOptions.wxsCallMethods); + if (parse) { + parse(mpComponentOptions, { handleLink }); + } + return mpComponentOptions; +} +function initCreateComponent(parseOptions) { + return function createComponent(vueComponentOptions) { + return Component(parseComponent(vueComponentOptions, parseOptions)); + }; +} +let $createComponentFn; +let $destroyComponentFn; +function $createComponent(initialVNode, options) { + if (!$createComponentFn) { + $createComponentFn = getApp().$vm.$createComponent; } - initProps(miniProgramComponentOptions, vueOptions.props, false); - initExtraOptions(miniProgramComponentOptions, vueOptions); - initWxsCallMethods(miniProgramComponentOptions.methods, vueOptions.wxsCallMethods); - return miniProgramComponentOptions; + return $createComponentFn(initialVNode, options); +} +function $destroyComponent(instance) { + if (!$destroyComponentFn) { + $destroyComponentFn = getApp().$vm.$destroyComponent; + } + return $destroyComponentFn(instance); } -const HOOKS$1 = [ - 'onLoad', - 'onShow', - 'onReady', - 'onHide', - 'onUnload', - 'onResize', - // 'onPageScroll', // 影响性能,开发者手动注册 - 'onTabItemTap', - 'onReachBottom', - 'onPullDownRefresh', - // 'onShareTimeline', // 右上角菜单,开发者手动注册 - 'onAddToFavorites' - // 'onShareAppMessage' // 右上角菜单,开发者手动注册 -]; function parsePage(vueOptions, parseOptions) { - const miniProgramPageOptions = parseComponent(vueOptions, parseOptions); - initHooks(miniProgramPageOptions.methods, HOOKS$1); - initUnknownHooks(miniProgramPageOptions.methods, vueOptions); + const { parse, mocks, isPage, initRelation, handleLink, initLifetimes } = parseOptions; + const miniProgramPageOptions = parseComponent(vueOptions, { + mocks, + isPage, + initRelation, + handleLink, + initLifetimes + }); + const methods = miniProgramPageOptions.methods; + initHooks(methods, PAGE_HOOKS); + initUnknownHooks(methods, vueOptions); + parse && parse(miniProgramPageOptions, { handleLink }); return miniProgramPageOptions; +} +function initCreatePage(parseOptions) { + return function createPage(vuePageOptions) { + return Component(parsePage(vuePageOptions, parseOptions)); + }; } -function createApp(vm) { - return App(parseApp(vm)); -} - -const mocks = ['__route__', '__wxExparserNodeId__', '__wxWebviewId__']; -function findVmByVueId(instance, vuePid) { - // TODO vue3 中 没有 $children - const $children = instance.$children; - // 优先查找直属(反向查找:https://github.com/dcloudio/uni-app/issues/1200) - for (let i = $children.length - 1; i >= 0; i--) { - const childVm = $children[i]; - if (childVm.$scope._$vueId === vuePid) { - return childVm; - } +const MPPage = Page; +const MPComponent = Component; +const customizeRE = /:/g; +function customize(str) { + return camelize(str.replace(customizeRE, '-')); +} +function initTriggerEvent(mpInstance) { + const oldTriggerEvent = mpInstance.triggerEvent; + mpInstance.triggerEvent = function (event, ...args) { + return oldTriggerEvent.apply(mpInstance, [customize(event), ...args]); + }; +} +function initHook$1(name, options) { + const oldHook = options[name]; + if (!oldHook) { + options[name] = function () { + initTriggerEvent(this); + }; } - // 反向递归查找 - let parentVm; - for (let i = $children.length - 1; i >= 0; i--) { - parentVm = findVmByVueId($children[i], vuePid); - if (parentVm) { - return parentVm; - } + else { + options[name] = function (...args) { + initTriggerEvent(this); + return oldHook.apply(this, args); + }; } } -function initBehavior(options) { - return Behavior(options); -} +Page = function (options) { + initHook$1('onLoad', options); + return MPPage(options); +}; +Component = function (options) { + initHook$1('created', options); + return MPComponent(options); +}; + +function initLifetimes({ mocks, isPage, initRelation, vueOptions }) { + return { + attached() { + const properties = this.properties; + initVueIds(properties.vueId, this); + const relationOptions = { + vuePid: this._$vuePid + }; + // 处理父子关系 + initRelation(this, relationOptions); + // 初始化 vue 实例 + const mpInstance = this; + this.$vm = $createComponent({ + type: vueOptions, + props: properties + }, { + mpType: isPage(mpInstance) ? 'page' : 'component', + mpInstance, + slots: properties.vueSlots, + parentComponent: relationOptions.parent && relationOptions.parent.$, + onBeforeSetup(instance, options) { + initRefs(instance, mpInstance); + initMocks(instance, mpInstance, mocks); + initComponentInstance(instance, options); + } + }); + }, + ready() { + // 当组件 props 默认值为 true,初始化时传入 false 会导致 created,ready 触发, 但 attached 不触发 + // https://developers.weixin.qq.com/community/develop/doc/00066ae2844cc0f8eb883e2a557800 + if (this.$vm) { + this.$vm.$callHook('mounted'); + this.$vm.$callHook('onReady'); + } + }, + detached() { + this.$vm && $destroyComponent(this.$vm); + } + }; +} + +const mocks = ['__route__', '__wxExparserNodeId__', '__wxWebviewId__']; function isPage(mpInstance) { return !!mpInstance.route; } function initRelation(mpInstance, detail) { mpInstance.triggerEvent('__l', detail); } -function initRefs(instance, mpInstance) { - // TODO - Object.defineProperty(instance.ctx, '$refs', { - get() { - const $refs = {}; - const components = mpInstance.selectAllComponents('.vue-ref'); - components.forEach(component => { - const ref = component.dataset.ref; - $refs[ref] = component.$vm || component; - }); - const forComponents = mpInstance.selectAllComponents('.vue-ref-in-for'); - forComponents.forEach(component => { - const ref = component.dataset.ref; - if (!$refs[ref]) { - $refs[ref] = []; - } - $refs[ref].push(component.$vm || component); - }); - return $refs; - } - }); -} function handleLink(event) { // detail 是微信,value 是百度(dipatch) const detail = (event.detail || @@ -815,19 +901,14 @@ function handleLink(event) { var parseOptions = /*#__PURE__*/Object.freeze({ __proto__: null, mocks: mocks, - initBehavior: initBehavior, isPage: isPage, initRelation: initRelation, - initRefs: initRefs, - handleLink: handleLink + handleLink: handleLink, + initLifetimes: initLifetimes }); -function createPage(vuePageOptions) { - return Component(parsePage(vuePageOptions, parseOptions)); -} - -function createComponent(vueComponentOptions) { - return Component(parseComponent(vueComponentOptions, parseOptions)); -} +const createApp = initCreateApp(); +const createPage = initCreatePage(parseOptions); +const createComponent = initCreateComponent(parseOptions); export { createApp, createComponent, createPage }; diff --git a/packages/uni-quickapp-webview/dist/uni.api.esm.js b/packages/uni-quickapp-webview/dist/uni.api.esm.js new file mode 100644 index 0000000000000000000000000000000000000000..d83a858811994113e9c988170ce808488a5f71e4 --- /dev/null +++ b/packages/uni-quickapp-webview/dist/uni.api.esm.js @@ -0,0 +1,483 @@ +import { isArray, isPromise, isFunction, isPlainObject, hasOwn, isString } from '@vue/shared'; + +const EPS = 1e-4; +const BASE_DEVICE_WIDTH = 750; +let isIOS = false; +let deviceWidth = 0; +let deviceDPR = 0; +function checkDeviceWidth() { + const { platform, pixelRatio, windowWidth } = qa.getSystemInfoSync(); + deviceWidth = windowWidth; + deviceDPR = pixelRatio; + isIOS = platform === 'ios'; +} +function upx2px(number, newDeviceWidth) { + if (deviceWidth === 0) { + checkDeviceWidth(); + } + number = Number(number); + if (number === 0) { + return 0; + } + let result = (number / BASE_DEVICE_WIDTH) * (newDeviceWidth || deviceWidth); + if (result < 0) { + result = -result; + } + result = Math.floor(result + EPS); + if (result === 0) { + if (deviceDPR === 1 || !isIOS) { + result = 1; + } + else { + result = 0.5; + } + } + return number < 0 ? -result : result; +} + +var HOOKS; +(function (HOOKS) { + HOOKS["INVOKE"] = "invoke"; + HOOKS["SUCCESS"] = "success"; + HOOKS["FAIL"] = "fail"; + HOOKS["COMPLETE"] = "complete"; + HOOKS["RETURN_VALUE"] = "returnValue"; +})(HOOKS || (HOOKS = {})); +const globalInterceptors = {}; +const scopedInterceptors = {}; +function wrapperHook(hook) { + return function (data) { + return hook(data) || data; + }; +} +function queue(hooks, data) { + let promise = false; + for (let i = 0; i < hooks.length; i++) { + const hook = hooks[i]; + if (promise) { + promise = Promise.resolve(wrapperHook(hook)); + } + else { + const res = hook(data); + if (isPromise(res)) { + promise = Promise.resolve(res); + } + if (res === false) { + return { + then() { }, + catch() { } + }; + } + } + } + return (promise || { + then(callback) { + return callback(data); + }, + catch() { } + }); +} +function wrapperOptions(interceptors, options = {}) { + [HOOKS.SUCCESS, HOOKS.FAIL, HOOKS.COMPLETE].forEach(name => { + const hooks = interceptors[name]; + if (!isArray(hooks)) { + return; + } + const oldCallback = options[name]; + options[name] = function callbackInterceptor(res) { + queue(hooks, res).then((res) => { + return (isFunction(oldCallback) && oldCallback(res)) || res; + }); + }; + }); + return options; +} +function wrapperReturnValue(method, returnValue) { + const returnValueHooks = []; + if (isArray(globalInterceptors.returnValue)) { + returnValueHooks.push(...globalInterceptors.returnValue); + } + const interceptor = scopedInterceptors[method]; + if (interceptor && isArray(interceptor.returnValue)) { + returnValueHooks.push(...interceptor.returnValue); + } + returnValueHooks.forEach(hook => { + returnValue = hook(returnValue) || returnValue; + }); + return returnValue; +} +function getApiInterceptorHooks(method) { + const interceptor = Object.create(null); + Object.keys(globalInterceptors).forEach(hook => { + if (hook !== 'returnValue') { + interceptor[hook] = globalInterceptors[hook].slice(); + } + }); + const scopedInterceptor = scopedInterceptors[method]; + if (scopedInterceptor) { + Object.keys(scopedInterceptor).forEach(hook => { + if (hook !== 'returnValue') { + interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]); + } + }); + } + return interceptor; +} +function invokeApi(method, api, options, ...params) { + const interceptor = getApiInterceptorHooks(method); + if (interceptor && Object.keys(interceptor).length) { + if (isArray(interceptor.invoke)) { + const res = queue(interceptor.invoke, options); + return res.then(options => { + return api(wrapperOptions(interceptor, options), ...params); + }); + } + else { + return api(wrapperOptions(interceptor, options), ...params); + } + } + return api(options, ...params); +} + +function mergeInterceptorHook(interceptors, interceptor) { + Object.keys(interceptor).forEach(hook => { + if (isFunction(interceptor[hook])) { + interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]); + } + }); +} +function removeInterceptorHook(interceptors, interceptor) { + if (!interceptors || !interceptor) { + return; + } + Object.keys(interceptor).forEach(hook => { + if (isFunction(interceptor[hook])) { + removeHook(interceptors[hook], interceptor[hook]); + } + }); +} +function mergeHook(parentVal, childVal) { + const res = childVal + ? parentVal + ? parentVal.concat(childVal) + : isArray(childVal) + ? childVal + : [childVal] + : parentVal; + return res ? dedupeHooks(res) : res; +} +function dedupeHooks(hooks) { + const res = []; + for (let i = 0; i < hooks.length; i++) { + if (res.indexOf(hooks[i]) === -1) { + res.push(hooks[i]); + } + } + return res; +} +function removeHook(hooks, hook) { + if (!hooks) { + return; + } + const index = hooks.indexOf(hook); + if (index !== -1) { + hooks.splice(index, 1); + } +} +function addInterceptor(method, interceptor) { + if (typeof method === 'string' && isPlainObject(interceptor)) { + mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); + } + else if (isPlainObject(method)) { + mergeInterceptorHook(globalInterceptors, method); + } +} +function removeInterceptor(method, interceptor) { + if (typeof method === 'string') { + if (isPlainObject(interceptor)) { + removeInterceptorHook(scopedInterceptors[method], interceptor); + } + else { + delete scopedInterceptors[method]; + } + } + else if (isPlainObject(method)) { + removeInterceptorHook(globalInterceptors, method); + } +} + +const SYNC_API_RE = /^\$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/; +const CONTEXT_API_RE = /^create|Manager$/; +// Context例外情况 +const CONTEXT_API_RE_EXC = ['createBLEConnection']; +// 同步例外情况 +const ASYNC_API = ['createBLEConnection']; +const CALLBACK_API_RE = /^on|^off/; +function isContextApi(name) { + return CONTEXT_API_RE.test(name) && CONTEXT_API_RE_EXC.indexOf(name) === -1; +} +function isSyncApi(name) { + return SYNC_API_RE.test(name) && ASYNC_API.indexOf(name) === -1; +} +function isCallbackApi(name) { + return CALLBACK_API_RE.test(name) && name !== 'onPush'; +} +function handlePromise(promise) { + if (!__UNI_PROMISE_API__) { + return promise; + } + return promise + .then(data => { + return [null, data]; + }) + .catch(err => [err]); +} +function shouldPromise(name) { + if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) { + return false; + } + return true; +} +/* eslint-disable no-extend-native */ +if (!Promise.prototype.finally) { + Promise.prototype.finally = function (onfinally) { + const promise = this.constructor; + return this.then(value => promise.resolve(onfinally && onfinally()).then(() => value), reason => promise.resolve(onfinally && onfinally()).then(() => { + throw reason; + })); + }; +} +function promisify(name, api) { + if (!shouldPromise(name)) { + return api; + } + if (!isFunction(api)) { + return api; + } + return function promiseApi(options = {}, ...params) { + if (isFunction(options.success) || + isFunction(options.fail) || + isFunction(options.complete)) { + return wrapperReturnValue(name, invokeApi(name, api, options, ...params)); + } + return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => { + invokeApi(name, api, Object.assign({}, options, { + success: resolve, + fail: reject + }), ...params); + }))); + }; +} + +const CALLBACKS = ['success', 'fail', 'cancel', 'complete']; +function initWrapper(protocols) { + function processCallback(methodName, method, returnValue) { + return function (res) { + return method(processReturnValue(methodName, res, returnValue)); + }; + } + function processArgs(methodName, fromArgs, argsOption = {}, returnValue = {}, keepFromArgs = false) { + if (isPlainObject(fromArgs)) { + // 一般 api 的参数解析 + const toArgs = (keepFromArgs === true ? fromArgs : {}); // returnValue 为 false 时,说明是格式化返回值,直接在返回值对象上修改赋值 + if (isFunction(argsOption)) { + argsOption = argsOption(fromArgs, toArgs) || {}; + } + for (const key in fromArgs) { + if (hasOwn(argsOption, key)) { + let keyOption = argsOption[key]; + if (isFunction(keyOption)) { + keyOption = keyOption(fromArgs[key], fromArgs, toArgs); + } + if (!keyOption) { + // 不支持的参数 + console.warn(`快应用(Webview)版 ${methodName} 暂不支持 ${key}`); + } + else if (isString(keyOption)) { + // 重写参数 key + toArgs[keyOption] = fromArgs[key]; + } + else if (isPlainObject(keyOption)) { + // {name:newName,value:value}可重新指定参数 key:value + toArgs[keyOption.name ? keyOption.name : key] = keyOption.value; + } + } + else if (CALLBACKS.indexOf(key) !== -1) { + const callback = fromArgs[key]; + if (isFunction(callback)) { + toArgs[key] = processCallback(methodName, callback, returnValue); + } + } + else { + if (!keepFromArgs && !hasOwn(toArgs, key)) { + toArgs[key] = fromArgs[key]; + } + } + } + return toArgs; + } + else if (isFunction(fromArgs)) { + fromArgs = processCallback(methodName, fromArgs, returnValue); + } + return fromArgs; + } + function processReturnValue(methodName, res, returnValue, keepReturnValue = false) { + if (isFunction(protocols.returnValue)) { + // 处理通用 returnValue + res = protocols.returnValue(methodName, res); + } + return processArgs(methodName, res, returnValue, {}, keepReturnValue); + } + return function wrapper(methodName, method) { + if (!hasOwn(protocols, methodName)) { + return method; + } + const protocol = protocols[methodName]; + if (!protocol) { + // 暂不支持的 api + return function () { + console.error(`快应用(Webview)版 暂不支持${methodName}`); + }; + } + return function (arg1, arg2) { + // 目前 api 最多两个参数 + let options = protocol; + if (isFunction(protocol)) { + options = protocol(arg1); + } + arg1 = processArgs(methodName, arg1, options.args, options.returnValue); + const args = [arg1]; + if (typeof arg2 !== 'undefined') { + args.push(arg2); + } + const returnValue = qa[options.name || methodName].apply(qa, args); + if (isSyncApi(methodName)) { + // 同步 api + return processReturnValue(methodName, returnValue, options.returnValue, isContextApi(methodName)); + } + return returnValue; + }; + }; +} + +const baseApis = { upx2px, addInterceptor, removeInterceptor }; +function initUni(api, protocols) { + const wrapper = initWrapper(protocols); + const UniProxyHandlers = { + get(target, key) { + if (hasOwn(target, key)) { + return target[key]; + } + if (hasOwn(api, key)) { + return promisify(key, api[key]); + } + if (hasOwn(baseApis, key)) { + return promisify(key, baseApis[key]); + } + // event-api + // provider-api? + return promisify(key, wrapper(key, qa[key])); + } + }; + return new Proxy({}, UniProxyHandlers); +} + +function initGetProvider(providers) { + return function getProvider({ service, success, fail, complete }) { + let res; + if (providers[service]) { + res = { + errMsg: 'getProvider:ok', + service, + provider: providers[service] + }; + isFunction(success) && success(res); + } + else { + res = { + errMsg: 'getProvider:fail:服务[' + service + ']不存在' + }; + isFunction(fail) && fail(res); + } + isFunction(complete) && complete(res); + }; +} + +const previewImage = { + args(fromArgs, toArgs) { + let currentIndex = parseInt(fromArgs.current); + if (isNaN(currentIndex)) { + return; + } + const urls = fromArgs.urls; + if (!isArray(urls)) { + return; + } + const len = urls.length; + if (!len) { + return; + } + if (currentIndex < 0) { + currentIndex = 0; + } + else if (currentIndex >= len) { + currentIndex = len - 1; + } + if (currentIndex > 0) { + toArgs.current = urls[currentIndex]; + toArgs.urls = urls.filter((item, index) => index < currentIndex ? item !== urls[currentIndex] : true); + } + else { + toArgs.current = urls[0]; + } + return { + indicator: false, + loop: false + }; + } +}; +function addSafeAreaInsets(fromRes, toRes) { + if (fromRes.safeArea) { + const safeArea = fromRes.safeArea; + toRes.safeAreaInsets = { + top: safeArea.top, + left: safeArea.left, + right: fromRes.windowWidth - safeArea.right, + bottom: fromRes.windowHeight - safeArea.bottom + }; + } +} +const getSystemInfo = { + returnValue: addSafeAreaInsets +}; +const getSystemInfoSync = getSystemInfo; + +const providers = { + oauth: [], + share: [], + payment: [], + push: [] +}; +if (qa.canIUse('getAccountProvider')) { + providers.oauth.push(qa.getAccountProvider()); +} +if (qa.canIUse('getVendorPaymentProvider')) { + providers.payment.push(qa.getVendorPaymentProvider()); +} +const getProvider = initGetProvider(providers); + +var shims = /*#__PURE__*/Object.freeze({ + __proto__: null, + getProvider: getProvider +}); + +var protocols = /*#__PURE__*/Object.freeze({ + __proto__: null, + previewImage: previewImage, + getSystemInfo: getSystemInfo, + getSystemInfoSync: getSystemInfoSync +}); + +var index = initUni(shims, protocols); + +export default index; diff --git a/packages/uni-quickapp-webview/dist/uni.mp.esm.js b/packages/uni-quickapp-webview/dist/uni.mp.esm.js new file mode 100644 index 0000000000000000000000000000000000000000..e2d498c25d96e4dc24e31ae7c7bbffefb5dfa30d --- /dev/null +++ b/packages/uni-quickapp-webview/dist/uni.mp.esm.js @@ -0,0 +1,1052 @@ +import { isArray, hasOwn, toNumber, isPlainObject, isObject, isFunction, extend, NOOP, camelize } from '@vue/shared'; + +function setModel(target, key, value, modifiers) { + if (isArray(modifiers)) { + if (modifiers.indexOf('trim') !== -1) { + value = value.trim(); + } + if (modifiers.indexOf('number') !== -1) { + value = toNumber(value); + } + } + if (!target) { + target = this; + } + target[key] = value; +} +function setSync(target, key, value) { + if (!target) { + target = this; + } + target[key] = value; +} +function getOrig(data) { + if (isPlainObject(data)) { + return data.$orig || data; + } + return data; +} +function map(val, iteratee) { + let ret, i, l, keys, key; + if (isArray(val)) { + ret = new Array(val.length); + for (i = 0, l = val.length; i < l; i++) { + ret[i] = iteratee(val[i], i); + } + return ret; + } + else if (isObject(val)) { + keys = Object.keys(val); + ret = Object.create(null); + for (i = 0, l = keys.length; i < l; i++) { + key = keys[i]; + ret[key] = iteratee(val[key], key, i); + } + return ret; + } + return []; +} +const MP_METHODS = [ + 'createSelectorQuery', + 'createIntersectionObserver', + 'selectAllComponents', + 'selectComponent' +]; +function hasHook(name) { + const hooks = this.$[name]; + if (hooks && hooks.length) { + return true; + } + return false; +} +function callHook(name, args) { + if (name === 'mounted') { + callHook.call(this, 'bm'); // beforeMount + this.$.isMounted = true; + name = 'm'; + } + const hooks = this.$[name]; + let ret; + if (hooks) { + for (let i = 0; i < hooks.length; i++) { + ret = hooks[i](args); + } + } + return ret; +} +function createEmitFn(oldEmit, ctx) { + return function emit(event, ...args) { + if (ctx.$scope && event) { + ctx.$scope.triggerEvent(event, { __args__: args }); + } + return oldEmit.apply(this, [event, ...args]); + }; +} +function set(target, key, val) { + return (target[key] = val); +} +function initBaseInstance(instance, options) { + const ctx = instance.ctx; + // mp + ctx.mpType = options.mpType; // @deprecated + ctx.$mpType = options.mpType; + ctx.$scope = options.mpInstance; + // TODO @deprecated + ctx.$mp = {}; + ctx._self = {}; + // $vm + ctx.$scope.$vm = instance.proxy; + // slots + { + instance.slots = {}; + if (isArray(options.slots) && options.slots.length) { + options.slots.forEach(name => { + instance.slots[name] = true; + }); + } + } + if (__VUE_OPTIONS_API__) { + // $set + ctx.$set = set; + } + // $emit + instance.emit = createEmitFn(instance.emit, ctx); + // $callHook + ctx.$hasHook = hasHook; + ctx.$callHook = callHook; +} +function initComponentInstance(instance, options) { + initBaseInstance(instance, options); + const ctx = instance.ctx; + MP_METHODS.forEach(method => { + ctx[method] = function (...args) { + const mpInstance = ctx.$scope; + if (mpInstance && mpInstance[method]) { + return mpInstance[method].apply(mpInstance, args); + } + }; + }); + // TODO other + ctx.__set_model = setModel; + ctx.__set_sync = setSync; + ctx.__get_orig = getOrig; + // TODO + // ctx.__get_style = getStyle + ctx.__map = map; +} +function initMocks(instance, mpInstance, mocks) { + const ctx = instance.ctx; + mocks.forEach(mock => { + if (hasOwn(mpInstance, mock)) { + ctx[mock] = mpInstance[mock]; + } + }); +} + +const PAGE_HOOKS = [ + 'onLoad', + 'onShow', + // 'onReady', // lifetimes.ready + 'onHide', + 'onUnload', + 'onResize', + // 'onPageScroll', // 影响性能,开发者手动注册 + 'onTabItemTap', + 'onReachBottom', + 'onPullDownRefresh', + // 'onShareTimeline', // 右上角菜单,开发者手动注册 + 'onAddToFavorites' + // 'onShareAppMessage' // 右上角菜单,开发者手动注册 +]; +function findHooks(vueOptions, hooks = new Set()) { + if (vueOptions) { + Object.keys(vueOptions).forEach(name => { + if (name.indexOf('on') === 0 && isFunction(vueOptions[name])) { + hooks.add(name); + } + }); + const { extends: extendsOptions, mixins } = vueOptions; + if (mixins) { + mixins.forEach(mixin => findHooks(mixin, hooks)); + } + if (extendsOptions) { + findHooks(extendsOptions, hooks); + } + } + return hooks; +} +function initHook(mpOptions, hook, excludes) { + if (excludes.indexOf(hook) === -1 && !hasOwn(mpOptions, hook)) { + mpOptions[hook] = function (args) { + return this.$vm && this.$vm.$callHook(hook, args); + }; + } +} +const EXCLUDE_HOOKS = ['onReady']; +function initHooks(mpOptions, hooks, excludes = EXCLUDE_HOOKS) { + hooks.forEach(hook => initHook(mpOptions, hook, excludes)); +} +function initUnknownHooks(mpOptions, vueOptions, excludes = EXCLUDE_HOOKS) { + findHooks(vueOptions).forEach(hook => initHook(mpOptions, hook, excludes)); +} + +const HOOKS = [ + 'onShow', + 'onHide', + 'onError', + 'onThemeChange', + 'onPageNotFound', + 'onUnhandledRejection' +]; +function parseApp(instance, parseAppOptions) { + const internalInstance = instance.$; + const appOptions = { + globalData: (instance.$options && instance.$options.globalData) || {}, + $vm: instance, + onLaunch(options) { + const ctx = internalInstance.ctx; + if (this.$vm && ctx.$callHook) { + // 已经初始化过了,主要是为了百度,百度 onShow 在 onLaunch 之前 + return; + } + initBaseInstance(internalInstance, { + mpType: 'app', + mpInstance: this, + slots: [] + }); + ctx.globalData = this.globalData; + instance.$callHook('onLaunch', options); + } + }; + const vueOptions = instance.$.type; + initHooks(appOptions, HOOKS); + initUnknownHooks(appOptions, vueOptions); + if (__VUE_OPTIONS_API__) { + const methods = vueOptions.methods; + methods && extend(appOptions, methods); + } + if (parseAppOptions) { + parseAppOptions.parse(appOptions); + } + return appOptions; +} +function initCreateApp(parseAppOptions) { + return function createApp(vm) { + return App(parseApp(vm, parseAppOptions)); + }; +} + +function initBehavior(options) { + return Behavior(options); +} +function initVueIds(vueIds, mpInstance) { + if (!vueIds) { + return; + } + const ids = vueIds.split(','); + const len = ids.length; + if (len === 1) { + mpInstance._$vueId = ids[0]; + } + else if (len === 2) { + mpInstance._$vueId = ids[0]; + mpInstance._$vuePid = ids[1]; + } +} +const EXTRAS = ['externalClasses']; +function initExtraOptions(miniProgramComponentOptions, vueOptions) { + EXTRAS.forEach(name => { + if (hasOwn(vueOptions, name)) { + miniProgramComponentOptions[name] = vueOptions[name]; + } + }); +} +function initWxsCallMethods(methods, wxsCallMethods) { + if (!isArray(wxsCallMethods)) { + return; + } + wxsCallMethods.forEach((callMethod) => { + methods[callMethod] = function (args) { + return this.$vm[callMethod](args); + }; + }); +} +function initRefs(instance, mpInstance) { + Object.defineProperty(instance, 'refs', { + get() { + const $refs = {}; + const components = mpInstance.selectAllComponents('.vue-ref'); + components.forEach(component => { + const ref = component.dataset.ref; + $refs[ref] = component.$vm || component; + }); + const forComponents = mpInstance.selectAllComponents('.vue-ref-in-for'); + forComponents.forEach(component => { + const ref = component.dataset.ref; + if (!$refs[ref]) { + $refs[ref] = []; + } + $refs[ref].push(component.$vm || component); + }); + return $refs; + } + }); +} + +const PROP_TYPES = [String, Number, Boolean, Object, Array, null]; +function createObserver(name) { + return function observer(newVal) { + if (this.$vm) { + this.$vm.$.props[name] = newVal; // 为了触发其他非 render watcher + } + }; +} +function parsePropType(key, type, defaultValue) { + // [String]=>String + if (isArray(type) && type.length === 1) { + return type[0]; + } + return type; +} +function initDefaultProps(isBehavior = false) { + const properties = {}; + if (!isBehavior) { + properties.vueId = { + type: String, + value: '' + }; + // 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots + properties.vueSlots = { + type: null, + value: [], + observer: function (newVal) { + const $slots = Object.create(null); + newVal.forEach((slotName) => { + $slots[slotName] = true; + }); + this.setData({ + $slots + }); + } + }; + } + return properties; +} +function createProperty(key, prop) { + prop.observer = createObserver(key); + return prop; +} +function initProps(mpComponentOptions, rawProps, isBehavior = false) { + const properties = initDefaultProps(isBehavior); + if (isArray(rawProps)) { + rawProps.forEach(key => { + properties[key] = createProperty(key, { + type: null + }); + }); + } + else if (isPlainObject(rawProps)) { + Object.keys(rawProps).forEach(key => { + const opts = rawProps[key]; + if (isPlainObject(opts)) { + // title:{type:String,default:''} + let value = opts.default; + if (isFunction(value)) { + value = value(); + } + const type = opts.type; + opts.type = parsePropType(key, type); + properties[key] = createProperty(key, { + type: PROP_TYPES.indexOf(type) !== -1 ? type : null, + value + }); + } + else { + // content:String + const type = parsePropType(key, opts); + properties[key] = createProperty(key, { + type: PROP_TYPES.indexOf(type) !== -1 ? type : null + }); + } + }); + } + mpComponentOptions.properties = properties; +} + +function initData(vueOptions) { + let data = vueOptions.data || {}; + if (typeof data === 'function') { + try { + const appConfig = getApp().$vm.$.appContext + .config; + data = data.call(appConfig.globalProperties); + } + catch (e) { + if (process.env.VUE_APP_DEBUG) { + console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data, e); + } + } + } + else { + try { + // 对 data 格式化 + data = JSON.parse(JSON.stringify(data)); + } + catch (e) { } + } + if (!isPlainObject(data)) { + data = {}; + } + return data; +} +function initBehaviors(vueOptions, initBehavior) { + const vueBehaviors = vueOptions.behaviors; + const vueExtends = vueOptions.extends; + const vueMixins = vueOptions.mixins; + let vueProps = vueOptions.props; + if (!vueProps) { + vueOptions.props = vueProps = []; + } + const behaviors = []; + if (isArray(vueBehaviors)) { + vueBehaviors.forEach(behavior => { + behaviors.push(behavior.replace('uni://', `${__PLATFORM_PREFIX__}://`)); + if (behavior === 'uni://form-field') { + if (isArray(vueProps)) { + vueProps.push('name'); + vueProps.push('value'); + } + else { + vueProps.name = { + type: String, + default: '' + }; + vueProps.value = { + type: [String, Number, Boolean, Array, Object, Date], + default: '' + }; + } + } + }); + } + if (isPlainObject(vueExtends) && vueExtends.props) { + const behavior = {}; + initProps(behavior, vueExtends.props, true); + behaviors.push(initBehavior(behavior)); + } + if (isArray(vueMixins)) { + vueMixins.forEach(vueMixin => { + if (isPlainObject(vueMixin) && vueMixin.props) { + const behavior = {}; + initProps(behavior, vueMixin.props, true); + behaviors.push(initBehavior(behavior)); + } + }); + } + return behaviors; +} +function applyOptions(componentOptions, vueOptions, initBehavior) { + componentOptions.data = initData(vueOptions); + componentOptions.behaviors = initBehaviors(vueOptions, initBehavior); +} + +function getValue(obj, path) { + const parts = path.split('.'); + let key = parts[0]; + if (key.indexOf('__$n') === 0) { + //number index + key = parseInt(key.replace('__$n', '')); + } + if (parts.length === 1) { + return obj[key]; + } + return getValue(obj[key], parts.slice(1).join('.')); +} +function getExtraValue(instance, dataPathsArray) { + let context = instance; + dataPathsArray.forEach(dataPathArray => { + const dataPath = dataPathArray[0]; + const value = dataPathArray[2]; + if (dataPath || typeof value !== 'undefined') { + // ['','',index,'disable'] + const propPath = dataPathArray[1]; + const valuePath = dataPathArray[3]; + let vFor; + if (Number.isInteger(dataPath)) { + vFor = dataPath; + } + else if (!dataPath) { + vFor = context; + } + else if (typeof dataPath === 'string' && dataPath) { + if (dataPath.indexOf('#s#') === 0) { + vFor = dataPath.substr(3); + } + else { + vFor = getValue(context, dataPath); + } + } + if (Number.isInteger(vFor)) { + context = value; + } + else if (!propPath) { + context = vFor[value]; + } + else { + if (isArray(vFor)) { + context = vFor.find(vForItem => { + return getValue(vForItem, propPath) === value; + }); + } + else if (isPlainObject(vFor)) { + context = Object.keys(vFor).find(vForKey => { + return getValue(vFor[vForKey], propPath) === value; + }); + } + else { + console.error('v-for 暂不支持循环数据:', vFor); + } + } + if (valuePath) { + context = getValue(context, valuePath); + } + } + }); + return context; +} +function processEventExtra(instance, extra, event) { + const extraObj = {}; + if (isArray(extra) && extra.length) { + /** + *[ + * ['data.items', 'data.id', item.data.id], + * ['metas', 'id', meta.id] + *], + *[ + * ['data.items', 'data.id', item.data.id], + * ['metas', 'id', meta.id] + *], + *'test' + */ + extra.forEach((dataPath, index) => { + if (typeof dataPath === 'string') { + if (!dataPath) { + // model,prop.sync + extraObj['$' + index] = instance; + } + else { + if (dataPath === '$event') { + // $event + extraObj['$' + index] = event; + } + else if (dataPath === 'arguments') { + if (event.detail && event.detail.__args__) { + extraObj['$' + index] = event.detail.__args__; + } + else { + extraObj['$' + index] = [event]; + } + } + else if (dataPath.indexOf('$event.') === 0) { + // $event.target.value + extraObj['$' + index] = getValue(event, dataPath.replace('$event.', '')); + } + else { + extraObj['$' + index] = getValue(instance, dataPath); + } + } + } + else { + extraObj['$' + index] = getExtraValue(instance, dataPath); + } + }); + } + return extraObj; +} +function getObjByArray(arr) { + const obj = {}; + for (let i = 1; i < arr.length; i++) { + const element = arr[i]; + obj[element[0]] = element[1]; + } + return obj; +} +function processEventArgs(instance, event, args = [], extra = [], isCustom, methodName) { + let isCustomMPEvent = false; // wxcomponent 组件,传递原始 event 对象 + if (isCustom) { + // 自定义事件 + isCustomMPEvent = + event.currentTarget && + event.currentTarget.dataset && + event.currentTarget.dataset.comType === 'wx'; + if (!args.length) { + // 无参数,直接传入 event 或 detail 数组 + if (isCustomMPEvent) { + return [event]; + } + return event.detail.__args__ || event.detail; + } + } + const extraObj = processEventExtra(instance, extra, event); + const ret = []; + args.forEach(arg => { + if (arg === '$event') { + if (methodName === '__set_model' && !isCustom) { + // input v-model value + ret.push(event.target.value); + } + else { + if (isCustom && !isCustomMPEvent) { + ret.push(event.detail.__args__[0]); + } + else { + // wxcomponent 组件或内置组件 + ret.push(event); + } + } + } + else { + if (isArray(arg) && arg[0] === 'o') { + ret.push(getObjByArray(arg)); + } + else if (typeof arg === 'string' && hasOwn(extraObj, arg)) { + ret.push(extraObj[arg]); + } + else { + ret.push(arg); + } + } + }); + return ret; +} +function wrapper(event) { + event.stopPropagation = NOOP; + event.preventDefault = NOOP; + event.target = event.target || {}; + if (!hasOwn(event, 'detail')) { + event.detail = {}; + } + if (hasOwn(event, 'markerId')) { + event.detail = typeof event.detail === 'object' ? event.detail : {}; + event.detail.markerId = event.markerId; + } + if (isPlainObject(event.detail)) { + event.target = Object.assign({}, event.target, event.detail); + } + return event; +} +const ONCE = '~'; +const CUSTOM = '^'; +function matchEventType(eventType, optType) { + return (eventType === optType || + (optType === 'regionchange' && + (eventType === 'begin' || eventType === 'end'))); +} +function handleEvent(event) { + event = wrapper(event); + // [['tap',[['handle',[1,2,a]],['handle1',[1,2,a]]]]] + const dataset = (event.currentTarget || event.target).dataset; + if (!dataset) { + return console.warn('事件信息不存在'); + } + const eventOpts = (dataset.eventOpts || + dataset['event-opts']); // 支付宝 web-view 组件 dataset 非驼峰 + if (!eventOpts) { + return console.warn('事件信息不存在'); + } + // [['handle',[1,2,a]],['handle1',[1,2,a]]] + const eventType = event.type; + const ret = []; + eventOpts.forEach((eventOpt) => { + let type = eventOpt[0]; + const eventsArray = eventOpt[1]; + const isCustom = type.charAt(0) === CUSTOM; + type = isCustom ? type.slice(1) : type; + const isOnce = type.charAt(0) === ONCE; + type = isOnce ? type.slice(1) : type; + if (eventsArray && matchEventType(eventType, type)) { + eventsArray.forEach((eventArray) => { + const methodName = eventArray[0]; + if (methodName) { + let handlerCtx = this.$vm; + if (handlerCtx.$options.generic && + handlerCtx.$parent && + handlerCtx.$parent.$parent) { + // mp-weixin,mp-toutiao 抽象节点模拟 scoped slots + handlerCtx = handlerCtx.$parent.$parent; + } + if (methodName === '$emit') { + handlerCtx.$emit.apply(handlerCtx, processEventArgs(this.$vm, event, eventArray[1], eventArray[2], isCustom, methodName)); + return; + } + const handler = handlerCtx[methodName]; + if (!isFunction(handler)) { + throw new Error(` _vm.${methodName} is not a function`); + } + if (isOnce) { + if (handler.once) { + return; + } + handler.once = true; + } + ret.push(handler.apply(handlerCtx, processEventArgs(this.$vm, event, eventArray[1], eventArray[2], isCustom, methodName))); + } + }); + } + }); + if (eventType === 'input' && + ret.length === 1 && + typeof ret[0] !== 'undefined') { + return ret[0]; + } +} + +function parseComponent(vueOptions, { parse, mocks, isPage, initRelation, handleLink, initLifetimes }) { + vueOptions = vueOptions.default || vueOptions; + const options = { + multipleSlots: true, + addGlobalClass: true + }; + if (vueOptions.options) { + extend(options, vueOptions.options); + } + const mpComponentOptions = { + options, + lifetimes: initLifetimes({ mocks, isPage, initRelation, vueOptions }), + pageLifetimes: { + show() { + this.$vm && this.$vm.$callHook('onPageShow'); + }, + hide() { + this.$vm && this.$vm.$callHook('onPageHide'); + }, + resize(size) { + this.$vm && this.$vm.$callHook('onPageResize', size); + } + }, + methods: { + __l: handleLink, + __e: handleEvent + } + }; + if (__VUE_OPTIONS_API__) { + applyOptions(mpComponentOptions, vueOptions, initBehavior); + } + initProps(mpComponentOptions, vueOptions.props, false); + initExtraOptions(mpComponentOptions, vueOptions); + initWxsCallMethods(mpComponentOptions.methods, vueOptions.wxsCallMethods); + if (parse) { + parse(mpComponentOptions, { handleLink }); + } + return mpComponentOptions; +} +function initCreateComponent(parseOptions) { + return function createComponent(vueComponentOptions) { + return Component(parseComponent(vueComponentOptions, parseOptions)); + }; +} +let $createComponentFn; +let $destroyComponentFn; +function $createComponent(initialVNode, options) { + if (!$createComponentFn) { + $createComponentFn = getApp().$vm.$createComponent; + } + return $createComponentFn(initialVNode, options); +} +function $destroyComponent(instance) { + if (!$destroyComponentFn) { + $destroyComponentFn = getApp().$vm.$destroyComponent; + } + return $destroyComponentFn(instance); +} + +function parsePage(vueOptions, parseOptions) { + const { parse, mocks, isPage, initRelation, handleLink, initLifetimes } = parseOptions; + const miniProgramPageOptions = parseComponent(vueOptions, { + mocks, + isPage, + initRelation, + handleLink, + initLifetimes + }); + const methods = miniProgramPageOptions.methods; + initHooks(methods, PAGE_HOOKS); + initUnknownHooks(methods, vueOptions); + parse && parse(miniProgramPageOptions, { handleLink }); + return miniProgramPageOptions; +} +function initCreatePage(parseOptions) { + return function createPage(vuePageOptions) { + return Component(parsePage(vuePageOptions, parseOptions)); + }; +} + +const MPPage = Page; +const MPComponent = Component; +const customizeRE = /:/g; +function customize(str) { + return camelize(str.replace(customizeRE, '-')); +} +function initTriggerEvent(mpInstance) { + const oldTriggerEvent = mpInstance.triggerEvent; + mpInstance.triggerEvent = function (event, ...args) { + return oldTriggerEvent.apply(mpInstance, [customize(event), ...args]); + }; +} +function initHook$1(name, options) { + const oldHook = options[name]; + if (!oldHook) { + options[name] = function () { + initTriggerEvent(this); + }; + } + else { + options[name] = function (...args) { + initTriggerEvent(this); + return oldHook.apply(this, args); + }; + } +} +Page = function (options) { + initHook$1('onLoad', options); + return MPPage(options); +}; +Component = function (options) { + initHook$1('created', options); + return MPComponent(options); +}; + +function provide(instance, key, value) { + if (!instance) { + if ((process.env.NODE_ENV !== 'production')) { + console.warn(`provide() can only be used inside setup().`); + } + } + else { + let provides = instance.provides; + // by default an instance inherits its parent's provides object + // but when it needs to provide values of its own, it creates its + // own provides object using parent provides object as prototype. + // this way in `inject` we can simply look up injections from direct + // parent and let the prototype chain do the work. + const parentProvides = instance.parent && instance.parent.provides; + if (parentProvides === provides) { + provides = instance.provides = Object.create(parentProvides); + } + // TS doesn't allow symbol as index type + provides[key] = value; + } +} +function initProvide(instance) { + const provideOptions = instance.$options.provide; + if (!provideOptions) { + return; + } + const provides = isFunction(provideOptions) + ? provideOptions.call(instance) + : provideOptions; + const internalInstance = instance.$; + for (const key in provides) { + provide(internalInstance, key, provides[key]); + } +} +function inject(instance, key, defaultValue) { + if (instance) { + const provides = instance.provides; + if (key in provides) { + // TS doesn't allow symbol as index type + return provides[key]; + } + else if (arguments.length > 1) { + return defaultValue; + } + else if ((process.env.NODE_ENV !== 'production')) { + console.warn(`injection "${String(key)}" not found.`); + } + } + else if ((process.env.NODE_ENV !== 'production')) { + console.warn(`inject() can only be used inside setup() or functional components.`); + } +} +function initInjections(instance) { + const injectOptions = instance.$options.inject; + if (!injectOptions) { + return; + } + const internalInstance = instance.$; + const ctx = internalInstance.ctx; + if (isArray(injectOptions)) { + for (let i = 0; i < injectOptions.length; i++) { + const key = injectOptions[i]; + ctx[key] = inject(internalInstance, key); + } + } + else { + for (const key in injectOptions) { + const opt = injectOptions[key]; + if (isObject(opt)) { + ctx[key] = inject(internalInstance, opt.from, opt.default); + } + else { + ctx[key] = inject(internalInstance, opt); + } + } + } +} + +function initLifetimes({ mocks, isPage, initRelation, vueOptions }) { + return { + attached() { + const properties = this.properties; + initVueIds(properties.vueId, this); + const relationOptions = { + vuePid: this._$vuePid + }; + // 初始化 vue 实例 + const mpInstance = this; + const mpType = isPage(mpInstance) ? 'page' : 'component'; + if (mpType === 'page' && !mpInstance.route && mpInstance.__route__) { + mpInstance.route = mpInstance.__route__; + } + this.$vm = $createComponent({ + type: vueOptions, + props: properties + }, { + mpType, + mpInstance, + slots: properties.vueSlots, + parentComponent: relationOptions.parent && relationOptions.parent.$, + onBeforeSetup(instance, options) { + initRefs(instance, mpInstance); + initMocks(instance, mpInstance, mocks); + initComponentInstance(instance, options); + } + }); + // 处理父子关系 + initRelation(this, relationOptions); + }, + detached() { + this.$vm && $destroyComponent(this.$vm); + } + }; +} + +const instances = Object.create(null); +function parse(componentOptions, { handleLink }) { + componentOptions.methods.__l = handleLink; +} + +function initLifetimes$1(lifetimesOptions) { + return extend(initLifetimes(lifetimesOptions), { + ready() { + if (this.$vm && lifetimesOptions.isPage(this)) { + if ( this.pageinstance) { + this.__webviewId__ = this.pageinstance.__pageId__; + } + this.$vm.$callSyncHook('created'); + this.$vm.$callHook('mounted'); + this.$vm.$callHook('onReady'); + } + else { + this.is && console.warn(this.is + ' is not ready'); + } + }, + detached() { + this.$vm && $destroyComponent(this.$vm); + // 清理 + const webviewId = this.__webviewId__; + webviewId && + Object.keys(instances).forEach(key => { + if (key.indexOf(webviewId + '_') === 0) { + delete instances[key]; + } + }); + } + }); +} + +const mocks = ['nodeId', 'componentName', '_componentId', 'uniquePrefix']; +function isPage(mpInstance) { + return !mpInstance.ownerId; +} + +function initRelation(mpInstance) { + // triggerEvent 后,接收事件时机特别晚,已经到了 ready 之后 + const nodeId = mpInstance.nodeId + ''; + const webviewId = mpInstance.pageinstance.__pageId__ + ''; + instances[webviewId + '_' + nodeId] = mpInstance.$vm; + mpInstance.triggerEvent('__l', { + nodeId, + webviewId + }); +} +function handleLink({ detail: { nodeId, webviewId } }) { + const vm = instances[webviewId + '_' + nodeId]; + if (!vm) { + return; + } + let parentVm = instances[webviewId + '_' + vm.$scope.ownerId]; + if (!parentVm) { + parentVm = this.$vm; + } + vm.$.parent = parentVm.$; + const createdVm = function () { + if (__VUE_OPTIONS_API__) { + parentVm.$children.push(vm); + const parent = parentVm.$; + vm.$.provides = parent + ? parent.provides + : Object.create(parent.appContext.provides); + initInjections(vm); + initProvide(vm); + } + vm.$callSyncHook('created'); + }; + const mountedVm = function () { + // 处理当前 vm 子 + if (vm._$childVues) { + vm._$childVues.forEach(([createdVm]) => createdVm()); + vm._$childVues.forEach(([, mountedVm]) => mountedVm()); + delete vm._$childVues; + } + vm.$callHook('mounted'); + vm.$callHook('onReady'); + }; + // 当 parentVm 已经 mounted 时,直接触发,否则延迟 + if (!parentVm || parentVm.$.isMounted) { + createdVm(); + mountedVm(); + } + else { + (parentVm._$childVues || (parentVm._$childVues = [])).push([ + createdVm, + mountedVm + ]); + } +} + +var parseComponentOptions = /*#__PURE__*/Object.freeze({ + __proto__: null, + initRelation: initRelation, + handleLink: handleLink, + mocks: mocks, + isPage: isPage, + parse: parse, + initLifetimes: initLifetimes +}); + +var parsePageOptions = /*#__PURE__*/Object.freeze({ + __proto__: null, + mocks: mocks, + isPage: isPage, + initRelation: initRelation, + handleLink: handleLink, + parse: parse, + initLifetimes: initLifetimes$1 +}); + +const createApp = initCreateApp(); +const createPage = initCreatePage(parsePageOptions); +const createComponent = initCreateComponent(parseComponentOptions); + +export { createApp, createComponent, createPage }; diff --git a/packages/uni-template-compiler/__tests__/compiler.spec.js b/packages/uni-template-compiler/__tests__/compiler.spec.js index ffe3352f7d72ec8869e989478761069a83a46887..dc9dc5aac9a0cefdefd7ff1bd323ec648055e9a1 100644 --- a/packages/uni-template-compiler/__tests__/compiler.spec.js +++ b/packages/uni-template-compiler/__tests__/compiler.spec.js @@ -326,6 +326,12 @@ describe('mp:compiler', () => { '', '' ) + // v-for + assertCodegen( + 'test', + 'test', + 'with(this){if(!_isMounted){e0=function($event,item){var _temp=arguments[arguments.length-1].currentTarget.dataset,_temp2=(_temp.eventParams||_temp["event-params"])[0],item=_temp2.item;var _temp,_temp2;return $test.test(item)}}}' + ) // tricky symbols in args // assertCodegen( // ``, diff --git a/packages/uni-template-compiler/lib/constants.js b/packages/uni-template-compiler/lib/constants.js index 4597c3a33f28c5ab1454155ed8269e6b553e89b7..885ee953b3049c402e397edd5e3798a1564fa313 100644 --- a/packages/uni-template-compiler/lib/constants.js +++ b/packages/uni-template-compiler/lib/constants.js @@ -62,6 +62,7 @@ module.exports = { VAR_FILTER: 'F', ATTR_DATA_EVENT_OPTS: 'data-event-opts', ATTR_DATA_COM_TYPE: 'data-com-type', + ATTR_DATA_EVENT_PARAMS: 'data-event-params', INTERNAL_GET_ORIG, INTERNAL_GET_CLASS, INTERNAL_GET_STYLE, @@ -120,4 +121,4 @@ module.exports = { IDENTIFIER_STYLE: '__$$style$$__', IDENTIFIER_EVENT: '__$$event$$__', IDENTIFIER_GLOBAL: '__$$global$$__' -} +} diff --git a/packages/uni-template-compiler/lib/script/traverse/data/event.js b/packages/uni-template-compiler/lib/script/traverse/data/event.js index c1dccb98a83d8847ea38ad9d033dca8a95953264..12760adf673f8d0e450937efcd4f651b5b7c06b6 100644 --- a/packages/uni-template-compiler/lib/script/traverse/data/event.js +++ b/packages/uni-template-compiler/lib/script/traverse/data/event.js @@ -1,10 +1,12 @@ const t = require('@babel/types') +const parser = require('@babel/parser') const { IDENTIFIER_EVENT, VUE_EVENT_MODIFIERS, INTERNAL_EVENT_PROXY, ATTR_DATA_EVENT_OPTS, + ATTR_DATA_EVENT_PARAMS, INTERNAL_SET_SYNC } = require('../../../constants') @@ -212,8 +214,9 @@ function parseEvent (keyPath, valuePath, state, isComponent, isNativeOn = false, let isOnce = false const methods = [] + const params = [] - if (type) { + if (type) { isPassive = type.charAt(0) === VUE_EVENT_MODIFIERS.passive type = isPassive ? type.slice(1) : type @@ -318,7 +321,7 @@ function parseEvent (keyPath, valuePath, state, isComponent, isNativeOn = false, ReturnStatement (path) { const argument = path.node.argument if (t.isCallExpression(argument)) { - if (t.isIdentifier(argument.callee)) { + if (t.isIdentifier(argument.callee)) { // || t.isMemberExpression(argument.callee) anonymous = false parseEventByCallExpression(argument, methods) } @@ -326,6 +329,27 @@ function parseEvent (keyPath, valuePath, state, isComponent, isNativeOn = false, } }) if (anonymous) { + // 处理复杂表达式中使用的局部变量(主要在v-for中定义) + funcPath.traverse({ + Identifier (path) { + const scope = path.scope + const node = path.node + const name = node.name + if (path.key !== 'key' && (path.key !== 'property' || path.parent.computed) && scope && !scope.hasOwnBinding(name) && scope.hasBinding(name)) { + params.push(name) + } + } + }) + params.forEach(name => { + funcPath.node.params.push(t.identifier(name)) + }) + if (params.length) { + const datasetUid = funcPath.scope.generateDeclaredUidIdentifier().name + const paramsUid = funcPath.scope.generateDeclaredUidIdentifier().name + const dataset = ATTR_DATA_EVENT_PARAMS.substring(5) + const code = `var ${datasetUid}=arguments[arguments.length-1].currentTarget.dataset,${paramsUid}=(${datasetUid}.${dataset.replace(/-([a-z])/, (_, str) => str.toUpperCase())}||${datasetUid}['${dataset}'])[0],${params.map(item => `${item}=${paramsUid}.${item}`).join(',')}` + funcPath.node.body.body.unshift(parser.parse(code).program.body[0]) + } methods.push(addEventExpressionStatement(funcPath, state, isComponent, isNativeOn)) } } @@ -334,6 +358,7 @@ function parseEvent (keyPath, valuePath, state, isComponent, isNativeOn = false, return { type, + params, methods, modifiers: { isCatch, @@ -358,6 +383,7 @@ function _processEvent (path, state, isComponent, isNativeOn = false, tagName, r const valuePath = propertyPath.get('value') const { type, + params, methods, modifiers: { isCatch, @@ -393,12 +419,13 @@ function _processEvent (path, state, isComponent, isNativeOn = false, tagName, r if (isCustom) { optType = VUE_EVENT_MODIFIERS.custom + optType } - opts.push( - t.arrayExpression([ + opts.push({ + opt: t.arrayExpression([ t.stringLiteral(optType), t.arrayExpression(methods) - ]) - ) + ]), + params + }) keyPath.replaceWith( t.stringLiteral( @@ -422,15 +449,18 @@ module.exports = function processEvent (paths, path, state, isComponent, tagName const ret = [] const opts = [] + const params = [] if (onPath) { - _processEvent(onPath, state, isComponent, false, tagName, ret).forEach(opt => { + _processEvent(onPath, state, isComponent, false, tagName, ret).forEach(({ opt, params: array }) => { opts.push(opt) + params.push(...array) }) } if (nativeOnPath) { - _processEvent(nativeOnPath, state, isComponent, true, tagName, ret).forEach(opt => { + _processEvent(nativeOnPath, state, isComponent, true, tagName, ret).forEach(({ opt, params: array }) => { opts.push(opt) + params.push(...array) }) } if (!opts.length) { @@ -444,5 +474,15 @@ module.exports = function processEvent (paths, path, state, isComponent, tagName ) ) + if (params.length) { + ret.push( + t.objectProperty( + t.stringLiteral(ATTR_DATA_EVENT_PARAMS), + // 使用数组格式,直接使用对象格式微信小程序编译会报错 + t.stringLiteral(`{{[{${params.join(',')}}]}}`) + ) + ) + } + return ret } diff --git a/packages/uni-template-compiler/lib/script/traverse/member-expr.js b/packages/uni-template-compiler/lib/script/traverse/member-expr.js index e6cd4b36d3d6a8064ef57dc27244a8a62a67b4a3..9678461d8e57cef35bc66c65e7ce2949dda44300 100644 --- a/packages/uni-template-compiler/lib/script/traverse/member-expr.js +++ b/packages/uni-template-compiler/lib/script/traverse/member-expr.js @@ -4,15 +4,6 @@ function isMatch (name, forItem, forIndex) { return name === forItem || name === forIndex } -function getIdentifierName (element) { - if (t.isMemberExpression(element)) { - return getIdentifierName(element.object) - } else if (t.isCallExpression(element)) { - return getIdentifierName(element.callee) - } - return element.name && element.name.split('.')[0] -} - function findScoped (path, state) { if (!path) { return state @@ -23,30 +14,17 @@ function findScoped (path, state) { forIndex } = scoped let match = false - if (path.isIdentifier() || path.isMemberExpression()) { - match = isMatch(getIdentifierName(path.node), forItem, forIndex) - } else { - path.traverse({ - noScope: true, - Identifier (path) { - if (!match) { - match = isMatch(path.node.name, forItem, forIndex) - if (match) { - path.stop() - } - } - }, - MemberExpression (path) { - if (!match) { - match = isMatch(getIdentifierName(path.node), forItem, forIndex) - if (match) { - path.stop() - } - path.skip() + path.traverse({ + noScope: true, + Identifier (path) { + if (!match && path.key !== 'key' && (path.key !== 'property' || path.parent.computed)) { + match = isMatch(path.node.name, forItem, forIndex) + if (match) { + path.stop() } } - }) - } + } + }) return match }) if (!scoped && state.scoped.length > 1) { @@ -75,4 +53,4 @@ module.exports = function getMemberExpr (path, name, init, state, variableDeclar const contextIdentifier = t.identifier(scoped.context) contextIdentifier.$mpProcessed = true return t.memberExpression(contextIdentifier, identifier) -} +} diff --git a/packages/uni-template-compiler/lib/script/traverse/visitor.js b/packages/uni-template-compiler/lib/script/traverse/visitor.js index 5a81060f39a7e20260f23a87d92fa04569d17cff..6f41068ccc289be09072a2c27e4ed880c5f51c8f 100644 --- a/packages/uni-template-compiler/lib/script/traverse/visitor.js +++ b/packages/uni-template-compiler/lib/script/traverse/visitor.js @@ -132,7 +132,7 @@ function checkUsingGlobalComponents (name, globalUsingComponents, state) { } module.exports = { - noScope: true, + noScope: false, MemberExpression (path) { if ( // t.m(123) t.isIdentifier(path.node.object) && diff --git a/packages/vue-cli-plugin-uni/lib/chain-webpack.js b/packages/vue-cli-plugin-uni/lib/chain-webpack.js index be41cd1febd67044b4cdb2c24bd822f2ca6a5404..a98982e18237551825b1fd8efbd9998b554770f2 100644 --- a/packages/vue-cli-plugin-uni/lib/chain-webpack.js +++ b/packages/vue-cli-plugin-uni/lib/chain-webpack.js @@ -90,8 +90,12 @@ module.exports = function chainWebpack (platformOptions, vueOptions, api) { platformOptions.chainWebpack(webpackConfig, vueOptions, api) // define + const deferredCreated = process.env.UNI_PLATFORM === 'mp-toutiao' || + process.env.UNI_PLATFORM === 'quickapp-webview' const defines = { - __FEATURE_OPTIONS__: JSON.stringify(process.env.UNI_USING_VUE3_OPTIONS === 'true'), + __UNI_PROMISE_API__: JSON.stringify(process.env.UNI_USING_PROMISE_API === 'true'), + __VUE_OPTIONS_API__: JSON.stringify(process.env.UNI_USING_VUE3_OPTIONS_API === 'true'), + __VUE_CREATED_DEFERRED__: JSON.stringify(deferredCreated), 'process.env.UNI_ENV': JSON.stringify(process.env.UNI_PLATFORM), 'process.env.UNI_CLOUD_PROVIDER': process.env.UNI_CLOUD_PROVIDER, 'process.env.HBX_USER_TOKEN': JSON.stringify(process.env.HBX_USER_TOKEN || ''), diff --git a/packages/webpack-uni-pages-loader/lib/platforms/h5.js b/packages/webpack-uni-pages-loader/lib/platforms/h5.js index 4d2fdc744232d78e3c855c5583a8f0d0db546861..445849f72911f0d03a8732bcbbf238f8d933dd8f 100644 --- a/packages/webpack-uni-pages-loader/lib/platforms/h5.js +++ b/packages/webpack-uni-pages-loader/lib/platforms/h5.js @@ -12,7 +12,9 @@ const { const { addPageUsingComponents -} = require('@dcloudio/uni-cli-shared/lib/pages') +} = require('@dcloudio/uni-cli-shared/lib/pages') + +const compilerVersion = require('@dcloudio/webpack-uni-pages-loader/package.json')['uni-app'].compilerVersion const PLATFORMS = getPlatforms() @@ -400,7 +402,8 @@ module.exports = function (pagesJson, manifestJson, loader) { import Vue from 'vue' global['____${h5.appid}____'] = true; delete global['____${h5.appid}____']; -global.__uniConfig = ${JSON.stringify(pagesJson)}; +global.__uniConfig = ${JSON.stringify(pagesJson)}; +global.__uniConfig.compilerVersion = '${compilerVersion}'; global.__uniConfig.router = ${JSON.stringify(h5.router)}; global.__uniConfig.publicPath = ${JSON.stringify(h5.publicPath)}; global.__uniConfig['async'] = ${JSON.stringify(h5.async)}; diff --git a/src/core/runtime/wrapper/util.js b/src/core/runtime/wrapper/util.js index be9f757528e5bbc21e566d0eeae91a5cc0eebf00..f826a183effbf7f83315ffb1817a50bf095b52e5 100644 --- a/src/core/runtime/wrapper/util.js +++ b/src/core/runtime/wrapper/util.js @@ -542,14 +542,17 @@ export function handleEvent (event) { } handler.once = true } - ret.push(handler.apply(handlerCtx, processEventArgs( + const params = processEventArgs( this.$vm, event, eventArray[1], eventArray[2], isCustom, methodName - ))) + ) || [] + // 参数尾部增加原始事件对象用于复杂表达式内获取额外数据 + // eslint-disable-next-line no-sparse-arrays + ret.push(handler.apply(handlerCtx, params.concat([, , , , , , , , , , event]))) } }) } diff --git a/src/platforms/app-plus/service/api/device/bluetooth.js b/src/platforms/app-plus/service/api/device/bluetooth.js index d0c692ca2fefa05cf4d6fa4f4495d4306366036d..55b90c0e4fa80cec23cdf77a34b9ad801adc2ade 100644 --- a/src/platforms/app-plus/service/api/device/bluetooth.js +++ b/src/platforms/app-plus/service/api/device/bluetooth.js @@ -121,3 +121,11 @@ export function readBLECharacteristicValue (data, callbackId) { export function writeBLECharacteristicValue (data, callbackId) { bluetoothExec('writeBLECharacteristicValue', callbackId, data) } + +export function setBLEMTU (data, callbackId) { + bluetoothExec('setBLEMTU', callbackId, data) +} + +export function getBLEDeviceRSSI (data, callbackId) { + bluetoothExec('getBLEDeviceRSSI', callbackId, data) +} diff --git a/src/platforms/app-plus/service/framework/page.js b/src/platforms/app-plus/service/framework/page.js index cd66f97c0e789dcf506710c147192890a9ab222d..aafa4a2a1e8f1a6c9a654031e03c39225bbfb727 100644 --- a/src/platforms/app-plus/service/framework/page.js +++ b/src/platforms/app-plus/service/framework/page.js @@ -125,7 +125,7 @@ export function registerPage ({ routeOptions.meta.visible = true } - if (routeOptions.meta.isTabBar && webview.id !== '1') { + if (routeOptions.meta.isTabBar) { tabBar.append(webview) } @@ -209,4 +209,4 @@ export function registerPage ({ } return webview -} +} diff --git a/src/platforms/app-plus/view/components/picker/index.vue b/src/platforms/app-plus/view/components/picker/index.vue index 74837ff82d2f4842bc668f3ce3b2feb013e94665..0ee4a82dbf0039bbda373f9e5206b60d643bb66b 100644 --- a/src/platforms/app-plus/view/components/picker/index.vue +++ b/src/platforms/app-plus/view/components/picker/index.vue @@ -182,7 +182,8 @@ export default { for (let index = 0; index < length; index++) { const val0 = Number(val[index]) const val1 = Number(this.valueSync[index]) - this.valueSync.splice(index, 1, isNaN(val0) ? (isNaN(val1) ? 0 : val1) : val0) + const val2 = isNaN(val0) ? (isNaN(val1) ? 0 : val1) : val0 + this.valueSync.splice(index, 1, val2 < 0 ? 0 : val2) } } break @@ -190,16 +191,20 @@ export default { case mode.DATE: this.valueSync = String(val) break - default: - this.valueSync = Number(val) || 0 + default: { + const valueSync = Number(val) + this.valueSync = valueSync < 0 ? 0 : valueSync break + } } }, _show () { if (this.disabled) { return } - this._showPicker(Object.assign({}, this.$props)) + this._showPicker(Object.assign({}, this.$props, { + value: this.valueSync + })) }, _showPicker (data) { if ((data.mode === mode.TIME || data.mode === mode.DATE) && !data.fields) { @@ -276,7 +281,7 @@ export default { _resetFormData () { switch (this.mode) { case mode.SELECTOR: - this.valueSync = -1 + this.valueSync = 0 break case mode.MULTISELECTOR: this.valueSync = this.value.map(val => 0) diff --git a/src/platforms/h5/view/components/ad/index.vue b/src/platforms/h5/view/components/ad/index.vue index 058e81dd5fbc44d1b1dababdba0d6489e68b7e7e..f3c9514a4321a0552e28be0354cf8737227fb48a 100644 --- a/src/platforms/h5/view/components/ad/index.vue +++ b/src/platforms/h5/view/components/ad/index.vue @@ -6,7 +6,7 @@
@@ -36,14 +36,20 @@ class AdConfig { return this._adConfig } + get isExpired () { + if (this._adConfig == null) { + return true + } + return (Math.abs(Date.now() - this._adConfig.last) > this.CACHE_TIME) + } + _init () { var config = this._getConfig() if (config === null || !config.last) { return } - var td = Math.abs(Date.now() - config.last) - if (td < this.CACHE_TIME) { + if (!this.isExpired) { this._adConfig = config.data } } @@ -51,6 +57,9 @@ class AdConfig { get (adpid, success, fail) { if (this._adConfig != null) { this._doCallback(adpid, success, fail) + if (this.isExpired) { + this._loadAdConfig(adpid) + } return } @@ -65,8 +74,8 @@ class AdConfig { _doCallback (adpid, success, fail) { var data = this._adConfig - if (data.adpids[adpid]) { - success(data.adpids[adpid]) + if (data[adpid]) { + success(data[adpid]) } else { fail(this.ERROR_INVALID_ADPID) } @@ -76,15 +85,15 @@ class AdConfig { if (this._isLoading === true) { return } - this._isLoading = true uni.request({ url: this.URL, method: 'GET', - timeout: 3000, + timeout: 5000, data: { - adpid: adpid + d: location.hostname, + a: adpid }, dataType: 'json', success: (res) => { @@ -100,14 +109,14 @@ class AdConfig { }) } else { this._callbacks.forEach((i) => { - i.fail(rd.message) + i.fail({ errCode: rd.ret, errMsg: rd.msg }) }) } this._callbacks = [] }, fail: (err) => { this._callbacks.forEach((i) => { - i.fail(err.errMsg) + i.fail(err) }) this._callbacks = [] }, @@ -136,7 +145,7 @@ class AdConfig { } } Object.assign(AdConfig.prototype, { - URL: '//stream.dcloud.net.cn/dcloud/H5Config', + URL: '//qy5y9ee9ch8r87pg72w5.dcloud.net.cn/hcs', KEY: 'uni_app_ad_config', CACHE_TIME: 1000 * 60 * 10, ERROR_INVALID_ADPID: { @@ -144,9 +153,89 @@ Object.assign(AdConfig.prototype, { } }) +class AdReport { + static get instance () { + if (this._instance == null) { + this._instance = new AdReport() + this._instance._init() + } + return this._instance + } + + constructor () { + this._instance = null + this._adConfig = null + this._guid = null + } + + _init () { + var config = this._getConfig() + if (config !== null && config.guid) { + this._guid = config.guid + return + } + + this._guid = this._newGUID() + this._setConfig(this._guid) + } + + get (data) { + this._process(Object.assign(data, { + d: location.hostname, + i: this._guid + })) + } + + _process (data) { + uni.request({ + url: this.URL, + method: 'GET', + data: data, + dataType: 'json', + success: () => { + } + }) + } + + _newGUID () { + let guid = '' + const format = 'xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx' + for (let i = 0; i < format.length; i++) { + if (format[i] === 'x') { + guid += (Math.random() * 16 | 0).toString(16) + } else { + guid += format[i] + } + } + return guid.toUpperCase() + } + + _getConfig () { + if (!navigator.cookieEnabled || !window.localStorage) { + return null + } + var data = localStorage.getItem(this.KEY) + return data ? JSON.parse(data) : null + } + + _setConfig (guid) { + if (!navigator.cookieEnabled || !window.localStorage) { + return null + } + localStorage.setItem(this.KEY, JSON.stringify({ + last: Date.now(), + guid: guid + })) + } +} +Object.assign(AdReport.prototype, { + URL: '//hp66hwpyev7yx2hfughh.dcloud.net.cn/ahl', + KEY: 'uni_app_ad_guid' +}) + const adProvider = { - hx: 'hx', - ky: 'ky' + hx: 'zswx_hx', + ky: 'zswx_ky' } const CHECK_RENDER_DELAY = 1000 @@ -175,21 +264,35 @@ export default { this._checkTimer = null this._checkTimerCount = 0 this._loadData() + AdReport.instance.get({ + h: __uniConfig.compilerVersion, + a: this.adpid, + at: 30 + }) }, beforeDestroy () { + this._clearCheckTimer() this.$refs.container.innerHTML = '' }, methods: { - onhandle (e) { - console.log('onhandle') + _onhandle (e) { + this._report(41) + }, + _reset () { + this._pl = [] + this._pd = {} + this._pi = 0 + this._clearCheckTimer() + this.$refs.container.innerHTML = '' }, _loadData (adpid) { + this._reset() AdConfig.instance.get(adpid || this.adpid, (data) => { this._pd = data this._pl = data.psp.split(',') this._renderAd() }, (err) => { - this.$trigger('error', {}, { message: err }) + this.$trigger('error', {}, err) }) }, _renderAd () { @@ -208,12 +311,29 @@ export default { break } }, + _renderNext () { + if (this._pi >= this._pl.length - 1) { + return + } + + this._pi++ + this._renderAd() + }, _renderHX (data) { + if (document.querySelector('#' + adProvider.hx)) { + this._renderNext() + return + } + var ad = document.createElement('script') ad.src = data.src || data.url + var adView = document.createElement('div') + adView.setAttribute('id', adProvider.hx) + adView.appendChild(ad) + this.$refs.container.innerHTML = '' - this.$refs.container.append(ad) + this.$refs.container.append(adView) this._startCheckTimer() }, @@ -226,31 +346,25 @@ export default { this._startCheckTimer() }, - _renderNext () { - if (this._pi >= this._pl.length - 1) { - return - } - - this._pi++ - this._renderAd() - }, _checkRender () { - var hasContent = (this.$refs.container.clientHeight > 40) + var hasContent = (this.$refs.container.children.length > 0 && this.$refs.container.clientHeight > 40) + if (hasContent) { + this._report(40) + } return hasContent }, _startCheckTimer () { this._clearCheckTimer() this._checkTimer = setInterval(() => { - if (this._checkRender()) { + this._checkTimerCount++ + if (this._checkTimerCount >= CHECK_RENDER_RETRY) { this._clearCheckTimer() + this._renderNext() return } - this._checkTimerCount++ - - if (this._checkTimerCount >= CHECK_RENDER_RETRY) { + if (this._checkRender()) { this._clearCheckTimer() - this._renderNext() } }, CHECK_RENDER_DELAY) }, @@ -260,6 +374,22 @@ export default { window.clearInterval(this._checkTimer) this._checkTimer = null } + }, + _report (type) { + var taskId = '' + if (this._pl.length > 0 && this._pi < this._pl.length) { + var data = this._pd[this._pl[this._pi]] + if (data) { + taskId = data.task_id + } + } + + AdReport.instance.get({ + h: __uniConfig.compilerVersion, + a: this.adpid, + t: taskId, + at: type + }) } } } diff --git a/src/platforms/h5/view/components/picker/index.vue b/src/platforms/h5/view/components/picker/index.vue index e7bc76f4e9ad8d3dbb527a4b20d2a6e2348252c0..5d2a0b3620a5bb4006ce7ba13a199d033f476b20 100644 --- a/src/platforms/h5/view/components/picker/index.vue +++ b/src/platforms/h5/view/components/picker/index.vue @@ -79,7 +79,7 @@ function getDefaultStartValue () { const year = new Date().getFullYear() - 100 switch (this.fields) { case fields.YEAR: - return year + return year.toString() case fields.MONTH: return year + '-01' case fields.DAY: @@ -97,7 +97,7 @@ function getDefaultEndValue () { const year = new Date().getFullYear() + 100 switch (this.fields) { case fields.YEAR: - return year + return year.toString() case fields.MONTH: return year + '-12' case fields.DAY: @@ -248,7 +248,7 @@ export default { const day = Number(dateArray[2][valueArray[2]]) || 1 const realDay = new Date( `${dateArray[0][valueArray[0]]}/${ - dateArray[1][valueArray[1]] + dateArray[1][valueArray[1]] }/${day}` ).getDate() if (realDay < day) { @@ -314,7 +314,7 @@ export default { _resetFormData () { switch (this.mode) { case mode.SELECTOR: - this.valueSync = -1 + this.valueSync = 0 break case mode.MULTISELECTOR: this.valueSync = this.value.map(val => 0) @@ -387,7 +387,7 @@ export default { const val1 = Number(this.valueSync[index]) const val2 = isNaN(val0) ? (isNaN(val1) ? 0 : val1) : val0 const maxVal = this.range[index] ? this.range[index].length - 1 : 0 - this.valueSync.splice(index, 1, val2 > maxVal ? 0 : val2) + this.valueSync.splice(index, 1, (val2 < 0 || val2 > maxVal) ? 0 : val2) } } break @@ -395,9 +395,11 @@ export default { case mode.DATE: this.valueSync = String(val) break - default: - this.valueSync = Number(val) || 0 + default: { + const valueSync = Number(val) + this.valueSync = valueSync < 0 ? 0 : valueSync break + } } }, _setValueArray () {