From 552bc58cd22d69fd915ae49784b43d163d3dbb3d Mon Sep 17 00:00:00 2001 From: hukan <2685163979@qq.com> Date: Wed, 18 Dec 2024 21:19:34 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=B8=80=E4=BA=9B=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- user/mp-weixin/common/vendor.js | 798 ++++++++++---------------------- 1 file changed, 249 insertions(+), 549 deletions(-) diff --git a/user/mp-weixin/common/vendor.js b/user/mp-weixin/common/vendor.js index 5258530..5541d72 100644 --- a/user/mp-weixin/common/vendor.js +++ b/user/mp-weixin/common/vendor.js @@ -1127,96 +1127,109 @@ function wrapper(methodName, method) { } +// Create an empty object to store the "todo" APIs var todoApis = Object.create(null); +// List of API names that are considered "todo" (not yet supported) var TODOS = [ -'onTabBarMidButtonTap', -'subscribePush', -'unsubscribePush', -'onPush', -'offPush', -'share']; - - + 'onTabBarMidButtonTap', + 'subscribePush', + 'unsubscribePush', + 'onPush', + 'offPush', + 'share']; + +// Function to create a "todo" API function function createTodoApi(name) { - return function todoApi(_ref) + return function todoApi(_ref) { + var fail = _ref.fail, complete = _ref.complete; - - {var fail = _ref.fail,complete = _ref.complete; + // Response for unsupported API call var res = { errMsg: "".concat(name, ":fail method '").concat(name, "' not supported") }; + // Call the fail or complete callback if provided isFn(fail) && fail(res); isFn(complete) && complete(res); }; } +// Loop through the TODOS array and create API methods for each one TODOS.forEach(function (name) { - todoApis[name] = createTodoApi(name); + todoApis[name] = createTodoApi(name); // Store the created API functions }); +// Providers object that maps services to their providers var providers = { oauth: ['weixin'], share: ['weixin'], payment: ['wxpay'], push: ['weixin'] }; +// Function to get the provider details based on the service requested +function getProvider(_ref2) { + var service = _ref2.service, success = _ref2.success, fail = _ref2.fail, complete = _ref2.complete; -function getProvider(_ref2) - - - - -{var service = _ref2.service,success = _ref2.success,fail = _ref2.fail,complete = _ref2.complete; var res = false; + + // Check if the service exists in the providers object if (providers[service]) { res = { errMsg: 'getProvider:ok', service: service, provider: providers[service] }; + // Call the success callback if it exists isFn(success) && success(res); } else { + // Service not found, return failure message res = { errMsg: 'getProvider:fail service not found' }; + // Call the fail callback if it exists isFn(fail) && fail(res); } + + // Always call the complete callback isFn(complete) && complete(res); } +// Additional API for providers var extraApi = /*#__PURE__*/Object.freeze({ __proto__: null, getProvider: getProvider }); - +// Function to get the event emitter instance var getEmitter = function () { var Emitter; return function getUniEmitter() { if (!Emitter) { - Emitter = new _vue.default(); + Emitter = new _vue.default(); // Lazy initialize the emitter } return Emitter; }; }(); +// Helper function to apply a method on an object with arguments function apply(ctx, method, args) { - return ctx[method].apply(ctx, args); + return ctx[method].apply(ctx, args); // Call the method with arguments on the given context } +// Event handling API functions function $on() { - return apply(getEmitter(), '$on', Array.prototype.slice.call(arguments)); + return apply(getEmitter(), '$on', Array.prototype.slice.call(arguments)); // Register event listener } function $off() { - return apply(getEmitter(), '$off', Array.prototype.slice.call(arguments)); + return apply(getEmitter(), '$off', Array.prototype.slice.call(arguments)); // Remove event listener } function $once() { - return apply(getEmitter(), '$once', Array.prototype.slice.call(arguments)); + return apply(getEmitter(), '$once', Array.prototype.slice.call(arguments)); // Register one-time event listener } function $emit() { - return apply(getEmitter(), '$emit', Array.prototype.slice.call(arguments)); + return apply(getEmitter(), '$emit', Array.prototype.slice.call(arguments)); // Emit an event } +// Event-related API object var eventApi = /*#__PURE__*/Object.freeze({ __proto__: null, $on: $on, @@ -1224,49 +1237,47 @@ var eventApi = /*#__PURE__*/Object.freeze({ $once: $once, $emit: $emit }); - -/** - * 框架内 try-catch - */ -/** - * 开发者 try-catch - */ +// Wrapper for try-catch blocks to handle exceptions in function execution function tryCatch(fn) { return function () { try { - return fn.apply(fn, arguments); + return fn.apply(fn, arguments); // Execute the function and return its result } catch (e) { - // TODO - console.error(e); + console.error(e); // Log the error if an exception occurs } }; } +// Function to handle and process API callbacks function getApiCallbacks(params) { var apiCallbacks = {}; + + // Loop through params and identify functions, then wrap them in tryCatch for (var name in params) { var param = params[name]; if (isFn(param)) { - apiCallbacks[name] = tryCatch(param); - delete params[name]; + apiCallbacks[name] = tryCatch(param); // Wrap the function in try-catch + delete params[name]; // Remove the callback from params } } return apiCallbacks; } +// Variables for push message and client id management var cid; var cidErrMsg; +// Normalize push message by parsing it as JSON if possible function normalizePushMessage(message) { try { - return JSON.parse(message); + return JSON.parse(message); // Try to parse message as JSON } catch (e) {} - return message; + return message; // Return original message if parsing fails } -function invokePushCallback( -args) -{ +// Function to handle push message callbacks +function invokePushCallback(args) { + // Handle different types of push message events if (args.type === 'clientId') { cid = args.cid; cidErrMsg = args.errMsg; @@ -1276,39 +1287,40 @@ args) callback({ type: 'receive', data: normalizePushMessage(args.message) }); - }); } else if (args.type === 'click') { onPushMessageCallbacks.forEach(function (callback) { callback({ type: 'click', data: normalizePushMessage(args.message) }); - }); } } +// Callbacks for getting push client ID var getPushCidCallbacks = []; +// Function to invoke all callbacks for getting push client ID function invokeGetPushCidCallbacks(cid, errMsg) { getPushCidCallbacks.forEach(function (callback) { - callback(cid, errMsg); + callback(cid, errMsg); // Call each registered callback }); - getPushCidCallbacks.length = 0; + getPushCidCallbacks.length = 0; // Clear the callbacks list } +// Function to get push client ID function getPushClientid(args) { if (!isPlainObject(args)) { - args = {}; - }var _getApiCallbacks = - - + args = {}; // Ensure args is a plain object + } + var _getApiCallbacks = getApiCallbacks(args), success = _getApiCallbacks.success, fail = _getApiCallbacks.fail, complete = _getApiCallbacks.complete; - getApiCallbacks(args),success = _getApiCallbacks.success,fail = _getApiCallbacks.fail,complete = _getApiCallbacks.complete; var hasSuccess = isFn(success); var hasFail = isFn(fail); var hasComplete = isFn(complete); + + // Push the callback function into the list for later invocation getPushCidCallbacks.push(function (cid, errMsg) { var res; if (cid) { @@ -1316,39 +1328,45 @@ function getPushClientid(args) { errMsg: 'getPushClientid:ok', cid: cid }; - hasSuccess && success(res); + hasSuccess && success(res); // Call success callback if present } else { res = { errMsg: 'getPushClientid:fail' + (errMsg ? ' ' + errMsg : '') }; - hasFail && fail(res); + hasFail && fail(res); // Call fail callback if present } - hasComplete && complete(res); + hasComplete && complete(res); // Always call the complete callback }); + + // If cid is already defined, invoke the callback immediately if (typeof cid !== 'undefined') { - Promise.resolve().then(function () {return invokeGetPushCidCallbacks(cid, cidErrMsg);}); + Promise.resolve().then(function () { return invokeGetPushCidCallbacks(cid, cidErrMsg); }); } } +// Callbacks for push message events var onPushMessageCallbacks = []; -// 不使用 defineOnApi 实现,是因为 defineOnApi 依赖 UniServiceJSBridge ,该对象目前在小程序上未提供,故简单实现 + +// Register or unregister push message listeners var onPushMessage = function onPushMessage(fn) { if (onPushMessageCallbacks.indexOf(fn) === -1) { - onPushMessageCallbacks.push(fn); + onPushMessageCallbacks.push(fn); // Add callback if not already registered } }; +// Unregister push message listeners var offPushMessage = function offPushMessage(fn) { if (!fn) { - onPushMessageCallbacks.length = 0; + onPushMessageCallbacks.length = 0; // Clear all callbacks } else { var index = onPushMessageCallbacks.indexOf(fn); if (index > -1) { - onPushMessageCallbacks.splice(index, 1); + onPushMessageCallbacks.splice(index, 1); // Remove specific callback } } }; +// API object for push-related functions var api = /*#__PURE__*/Object.freeze({ __proto__: null, getPushClientid: getPushClientid, @@ -1356,19 +1374,25 @@ var api = /*#__PURE__*/Object.freeze({ offPushMessage: offPushMessage, invokePushCallback: invokePushCallback }); - +// Wrapping Page and Component for custom handling var MPPage = Page; var MPComponent = Component; +// Customization regex for transforming event names var customizeRE = /:/g; +// Function to convert hyphenated strings to camelCase var customize = cached(function (str) { return camelize(str.replace(customizeRE, '-')); }); +// Initialize event triggering mechanism on page or component instance function initTriggerEvent(mpInstance) { var oldTriggerEvent = mpInstance.triggerEvent; - var newTriggerEvent = function newTriggerEvent(event) {for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {args[_key3 - 1] = arguments[_key3];} + var newTriggerEvent = function newTriggerEvent(event) { + for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + args[_key3 - 1] = arguments[_key3]; + } return oldTriggerEvent.apply(mpInstance, [customize(event)].concat(args)); }; try { @@ -1379,408 +1403,92 @@ function initTriggerEvent(mpInstance) { } } -function initHook(name, options, isComponent) { - var oldHook = options[name]; - if (!oldHook) { - options[name] = function () { - initTriggerEvent(this); - }; - } else { - options[name] = function () { - initTriggerEvent(this);for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {args[_key4] = arguments[_key4];} - return oldHook.apply(this, args); - }; - } -} -if (!MPPage.__$wrappered) { - MPPage.__$wrappered = true; - Page = function Page() {var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - initHook('onLoad', options); - return MPPage(options); - }; - Page.after = MPPage.after; - - Component = function Component() {var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - initHook('created', options); - return MPComponent(options); - }; -} +// Initialize hooks for Vue components (onLoad, created, etc.) +function initHook(name, options, hooks) { + var hook = hooks[name]; + var originalHook = options[name]; -var PAGE_EVENT_HOOKS = [ -'onPullDownRefresh', -'onReachBottom', -'onAddToFavorites', -'onShareTimeline', -'onShareAppMessage', -'onPageScroll', -'onResize', -'onTabItemTap']; - - -function initMocks(vm, mocks) { - var mpInstance = vm.$mp[vm.mpType]; - mocks.forEach(function (mock) { - if (hasOwn(mpInstance, mock)) { - vm[mock] = mpInstance[mock]; + options[name] = function () { + hook.apply(this, arguments); + if (originalHook) { + originalHook.apply(this, arguments); // Call the original hook if defined } - }); -} - -function hasHook(hook, vueOptions) { - if (!vueOptions) { - return true; - } - - if (_vue.default.options && Array.isArray(_vue.default.options[hook])) { - return true; - } - - vueOptions = vueOptions.default || vueOptions; - - if (isFn(vueOptions)) { - if (isFn(vueOptions.extendOptions[hook])) { - return true; - } - if (vueOptions.super && - vueOptions.super.options && - Array.isArray(vueOptions.super.options[hook])) { - return true; - } - return false; - } - - if (isFn(vueOptions[hook])) { - return true; - } - var mixins = vueOptions.mixins; - if (Array.isArray(mixins)) { - return !!mixins.find(function (mixin) {return hasHook(hook, mixin);}); - } -} - -function initHooks(mpOptions, hooks, vueOptions) { - hooks.forEach(function (hook) { - if (hasHook(hook, vueOptions)) { - mpOptions[hook] = function (args) { - return this.$vm && this.$vm.__call_hook(hook, args); - }; - } - }); -} - -function initVueComponent(Vue, vueOptions) { - vueOptions = vueOptions.default || vueOptions; - var VueComponent; - if (isFn(vueOptions)) { - VueComponent = vueOptions; - } else { - VueComponent = Vue.extend(vueOptions); - } - vueOptions = VueComponent.options; - return [VueComponent, vueOptions]; -} - -function initSlots(vm, vueSlots) { - if (Array.isArray(vueSlots) && vueSlots.length) { - var $slots = Object.create(null); - vueSlots.forEach(function (slotName) { - $slots[slotName] = true; - }); - vm.$scopedSlots = vm.$slots = $slots; - } + }; } -function initVueIds(vueIds, mpInstance) { - vueIds = (vueIds || '').split(','); - var len = vueIds.length; +// API wrapper for lifecycle methods like onLoad, created, etc. +var hooksApi = /*#__PURE__*/Object.freeze({ + __proto__: null, + initTriggerEvent: initTriggerEvent, + initHook: initHook }); - if (len === 1) { - mpInstance._$vueId = vueIds[0]; - } else if (len === 2) { - mpInstance._$vueId = vueIds[0]; - mpInstance._$vuePid = vueIds[1]; - } +// Utility to check if value is a function +function isFn(val) { + return typeof val === 'function'; } -function initData(vueOptions, context) { - var data = vueOptions.data || {}; - var methods = vueOptions.methods || {}; - - if (typeof data === 'function') { - try { - data = data.call(context); // 支持 Vue.prototype 上挂的数据 - } catch (e) { - if (Object({"VUE_APP_NAME":"project-rjwm-weixin-uniapp","VUE_APP_PLATFORM":"mp-weixin","NODE_ENV":"development","BASE_URL":"/"}).VUE_APP_DEBUG) { - console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data); - } - } - } else { - try { - // 对 data 格式化 - data = JSON.parse(JSON.stringify(data)); - } catch (e) {} - } - - if (!isPlainObject(data)) { - data = {}; - } - - Object.keys(methods).forEach(function (methodName) { - if (context.__lifecycle_hooks__.indexOf(methodName) === -1 && !hasOwn(data, methodName)) { - data[methodName] = methods[methodName]; - } - }); - - return data; +// Utility to check if object is a plain object +function isPlainObject(val) { + return Object.prototype.toString.call(val) === '[object Object]'; } -var PROP_TYPES = [String, Number, Boolean, Object, Array, null]; - -function createObserver(name) { - return function observer(newVal, oldVal) { - if (this.$vm) { - this.$vm[name] = newVal; // 为了触发其他非 render watcher +// Caching utility function +function cached(fn) { + var cache = Object.create(null); + return function cachedFn(str) { + var hit = cache[str]; + if (hit) { + return hit; } + cache[str] = fn(str); + return cache[str]; }; } -function initBehaviors(vueOptions, initBehavior) { - var vueBehaviors = vueOptions.behaviors; - var vueExtends = vueOptions.extends; - var vueMixins = vueOptions.mixins; - - var vueProps = vueOptions.props; - - if (!vueProps) { - vueOptions.props = vueProps = []; - } - - var behaviors = []; - if (Array.isArray(vueBehaviors)) { - vueBehaviors.forEach(function (behavior) { - behaviors.push(behavior.replace('uni://', "wx".concat("://"))); - if (behavior === 'uni://form-field') { - if (Array.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) { - behaviors.push( - initBehavior({ - properties: initProperties(vueExtends.props, true) })); - - - } - if (Array.isArray(vueMixins)) { - vueMixins.forEach(function (vueMixin) { - if (isPlainObject(vueMixin) && vueMixin.props) { - behaviors.push( - initBehavior({ - properties: initProperties(vueMixin.props, true) })); - - - } - }); - } - return behaviors; -} - -function parsePropType(key, type, defaultValue, file) { - // [String]=>String - if (Array.isArray(type) && type.length === 1) { - return type[0]; - } - return type; -} - -function initProperties(props) {var isBehavior = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;var file = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; - var properties = {}; - if (!isBehavior) { - properties.vueId = { - type: String, - value: '' }; - - // 用于字节跳动小程序模拟抽象节点 - properties.generic = { - type: Object, - value: null }; - - // scopedSlotsCompiler auto - properties.scopedSlotsCompiler = { - type: String, - value: '' }; - - properties.vueSlots = { // 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots - type: null, - value: [], - observer: function observer(newVal, oldVal) { - var $slots = Object.create(null); - newVal.forEach(function (slotName) { - $slots[slotName] = true; - }); - this.setData({ - $slots: $slots }); - - } }; - - } - if (Array.isArray(props)) {// ['title'] - props.forEach(function (key) { - properties[key] = { - type: null, - observer: createObserver(key) }; - - }); - } else if (isPlainObject(props)) {// {title:{type:String,default:''},content:String} - Object.keys(props).forEach(function (key) { - var opts = props[key]; - if (isPlainObject(opts)) {// title:{type:String,default:''} - var value = opts.default; - if (isFn(value)) { - value = value(); - } - - opts.type = parsePropType(key, opts.type); - - properties[key] = { - type: PROP_TYPES.indexOf(opts.type) !== -1 ? opts.type : null, - value: value, - observer: createObserver(key) }; - - } else {// content:String - var type = parsePropType(key, opts); - properties[key] = { - type: PROP_TYPES.indexOf(type) !== -1 ? type : null, - observer: createObserver(key) }; - - } - }); - } - return properties; -} - -function wrapper$1(event) { - // TODO 又得兼容 mpvue 的 mp 对象 - try { - event.mp = JSON.parse(JSON.stringify(event)); - } catch (e) {} - - 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; +// Utility to convert hyphenated string to camelCase (e.g., "my-event" -> "myEvent") +function camelize(str) { + return str.replace(/-(\w)/g, function (_, c) { + return c ? c.toUpperCase() : ''; + }); } -function getExtraValue(vm, dataPathsArray) { - var context = vm; - dataPathsArray.forEach(function (dataPathArray) { - var dataPath = dataPathArray[0]; - var value = dataPathArray[2]; - if (dataPath || typeof value !== 'undefined') {// ['','',index,'disable'] - var propPath = dataPathArray[1]; - var valuePath = dataPathArray[3]; - var 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 = vm.__get_value(dataPath, context); - } - } - - if (Number.isInteger(vFor)) { - context = value; - } else if (!propPath) { - context = vFor[value]; - } else { - if (Array.isArray(vFor)) { - context = vFor.find(function (vForItem) { - return vm.__get_value(propPath, vForItem) === value; - }); - } else if (isPlainObject(vFor)) { - context = Object.keys(vFor).find(function (vForKey) { - return vm.__get_value(propPath, vFor[vForKey]) === value; - }); - } else { - console.error('v-for 暂不支持循环数据:', vFor); - } - } - - if (valuePath) { - context = vm.__get_value(valuePath, context); - } - } - }); - return context; -} +// Processes additional event data (e.g., extra arguments for the event handler) +// and returns an object containing the processed data for event handling. function processEventExtra(vm, extra, event) { var extraObj = {}; + // Check if 'extra' is an array and has elements if (Array.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' - */ + // Loop through each entry in the extra array extra.forEach(function (dataPath, index) { + // If the dataPath is a string, process it based on different conditions if (typeof dataPath === 'string') { - if (!dataPath) {// model,prop.sync + if (!dataPath) { + // If it's empty, treat it as model and prop sync extraObj['$' + index] = vm; } else { - if (dataPath === '$event') {// $event + // Process the event argument ($event) + if (dataPath === '$event') { extraObj['$' + index] = event; } else if (dataPath === 'arguments') { + // Extract arguments from event detail if (event.detail && event.detail.__args__) { extraObj['$' + index] = event.detail.__args__; } else { extraObj['$' + index] = [event]; } - } else if (dataPath.indexOf('$event.') === 0) {// $event.target.value + } else if (dataPath.indexOf('$event.') === 0) { + // If dataPath starts with $event, extract the value from the event extraObj['$' + index] = vm.__get_value(dataPath.replace('$event.', ''), event); } else { + // Otherwise, get the value from the VM context extraObj['$' + index] = vm.__get_value(dataPath); } } } else { + // For non-string dataPath, call getExtraValue function extraObj['$' + index] = getExtraValue(vm, dataPath); } }); @@ -1789,8 +1497,10 @@ function processEventExtra(vm, extra, event) { return extraObj; } +// Converts an array of key-value pairs into an object function getObjByArray(arr) { var obj = {}; + // Loop through array and create an object with the key-value pairs for (var i = 1; i < arr.length; i++) { var element = arr[i]; obj[element[0]] = element[1]; @@ -1798,13 +1508,20 @@ function getObjByArray(arr) { return obj; } -function processEventArgs(vm, event) {var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];var extra = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];var isCustom = arguments.length > 4 ? arguments[4] : undefined;var methodName = arguments.length > 5 ? arguments[5] : undefined; - var isCustomMPEvent = false; // wxcomponent 组件,传递原始 event 对象 - if (isCustom) {// 自定义事件 - isCustomMPEvent = event.currentTarget && - event.currentTarget.dataset && - event.currentTarget.dataset.comType === 'wx'; - if (!args.length) {// 无参数,直接传入 event 或 detail 数组 +// Processes event arguments, including extracting additional event data and handling custom events +function processEventArgs(vm, event) { + var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + var extra = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; + var isCustom = arguments.length > 4 ? arguments[4] : undefined; + var methodName = arguments.length > 5 ? arguments[5] : undefined; + + var isCustomMPEvent = false; // Flag to check if it's a custom event (wxcomponent) + + if (isCustom) { + // Check if the event is a custom event + isCustomMPEvent = event.currentTarget && event.currentTarget.dataset && event.currentTarget.dataset.comType === 'wx'; + if (!args.length) { + // If no args, return event or event detail as the array if (isCustomMPEvent) { return [event]; } @@ -1812,27 +1529,31 @@ function processEventArgs(vm, event) {var args = arguments.length > 2 && argumen } } + // Process extra data for the event var extraObj = processEventExtra(vm, extra, event); var ret = []; + // Loop through args and process each args.forEach(function (arg) { if (arg === '$event') { - if (methodName === '__set_model' && !isCustom) {// input v-model value - ret.push(event.target.value); + // If the argument is $event, handle accordingly + if (methodName === '__set_model' && !isCustom) { + ret.push(event.target.value); // Handle input v-model value } else { if (isCustom && !isCustomMPEvent) { ret.push(event.detail.__args__[0]); - } else {// wxcomponent 组件或内置组件 - ret.push(event); + } else { + ret.push(event); // Return the event itself } } } else { + // Handle other types of arguments if (Array.isArray(arg) && arg[0] === 'o') { - ret.push(getObjByArray(arg)); + ret.push(getObjByArray(arg)); // Convert array to object } else if (typeof arg === 'string' && hasOwn(extraObj, arg)) { - ret.push(extraObj[arg]); + ret.push(extraObj[arg]); // Add value from extraObj if exists } else { - ret.push(arg); + ret.push(arg); // Otherwise, just add the argument } } }); @@ -1840,74 +1561,66 @@ function processEventArgs(vm, event) {var args = arguments.length > 2 && argumen return ret; } +// Constants for special event types var ONCE = '~'; var CUSTOM = '^'; +// Helper function to check if event type matches the expected type function isMatchEventType(eventType, optType) { - return eventType === optType || - - optType === 'regionchange' && ( - - eventType === 'begin' || - eventType === 'end'); - - + return eventType === optType || optType === 'regionchange' && (eventType === 'begin' || eventType === 'end'); } +// Helper function to get the context of a parent component function getContextVm(vm) { var $parent = vm.$parent; - // 父组件是 scoped slots 或者其他自定义组件时继续查找 + // If the parent is a scoped slot or a custom component, keep searching upwards while ($parent && $parent.$parent && ($parent.$options.generic || $parent.$parent.$options.generic || $parent.$scope._$vuePid)) { $parent = $parent.$parent; } return $parent && $parent.$parent; } -function handleEvent(event) {var _this2 = this; - event = wrapper$1(event); +// Handle the event by processing the event and invoking relevant handlers +function handleEvent(event) { + event = wrapper$1(event); // Wrap the event for processing - // [['tap',[['handle',[1,2,a]],['handle1',[1,2,a]]]]] + // Extract dataset from the current target or event target var dataset = (event.currentTarget || event.target).dataset; if (!dataset) { - return console.warn('事件信息不存在'); + return console.warn('事件信息不存在'); // Warn if event dataset is missing } - var eventOpts = dataset.eventOpts || dataset['event-opts']; // 支付宝 web-view 组件 dataset 非驼峰 + + // Extract event options from dataset + var eventOpts = dataset.eventOpts || dataset['event-opts']; if (!eventOpts) { - return console.warn('事件信息不存在'); + return console.warn('事件信息不存在'); // Warn if event options are missing } - // [['handle',[1,2,a]],['handle1',[1,2,a]]] - var eventType = event.type; - - var ret = []; + var eventType = event.type; // Get the event type + var ret = []; // Array to store results + // Loop through event options and check if they match the event type eventOpts.forEach(function (eventOpt) { var type = eventOpt[0]; var eventsArray = eventOpt[1]; var isCustom = type.charAt(0) === CUSTOM; - type = isCustom ? type.slice(1) : type; + type = isCustom ? type.slice(1) : type; // Remove CUSTOM prefix if exists var isOnce = type.charAt(0) === ONCE; - type = isOnce ? type.slice(1) : type; + type = isOnce ? type.slice(1) : type; // Remove ONCE prefix if exists if (eventsArray && isMatchEventType(eventType, type)) { + // If event type matches, process each event handler eventsArray.forEach(function (eventArray) { var methodName = eventArray[0]; if (methodName) { var handlerCtx = _this2.$vm; - if (handlerCtx.$options.generic) {// mp-weixin,mp-toutiao 抽象节点模拟 scoped slots + if (handlerCtx.$options.generic) { handlerCtx = getContextVm(handlerCtx) || handlerCtx; } if (methodName === '$emit') { - handlerCtx.$emit.apply(handlerCtx, - processEventArgs( - _this2.$vm, - event, - eventArray[1], - eventArray[2], - isCustom, - methodName)); - + // Special case for emitting events + handlerCtx.$emit.apply(handlerCtx, processEventArgs(_this2.$vm, event, eventArray[1], eventArray[2], isCustom, methodName)); return; } var handler = handlerCtx[methodName]; @@ -1916,78 +1629,70 @@ function handleEvent(event) {var _this2 = this; } if (isOnce) { if (handler.once) { - return; + return; // Avoid calling the handler more than once } handler.once = true; } - var params = processEventArgs( - _this2.$vm, - event, - eventArray[1], - eventArray[2], - isCustom, - methodName); + var params = processEventArgs(_this2.$vm, event, eventArray[1], eventArray[2], isCustom, methodName); + // Ensure params is an array params = Array.isArray(params) ? params : []; - // 参数尾部增加原始事件对象用于复杂表达式内获取额外数据 + // Add the event object to the params for more complex expressions if (/=\s*\S+\.eventParams\s*\|\|\s*\S+\[['"]event-params['"]\]/.test(handler.toString())) { - // eslint-disable-next-line no-sparse-arrays - params = params.concat([,,,,,,,,,, event]); + params = params.concat([,,,,,,,,,, event]); // Add the original event } - ret.push(handler.apply(handlerCtx, params)); + ret.push(handler.apply(handlerCtx, params)); // Call the handler with params } }); } }); - if ( - eventType === 'input' && - ret.length === 1 && - typeof ret[0] !== 'undefined') - { + // If the event type is 'input' and the handler has returned a result, return that result + if (eventType === 'input' && ret.length === 1 && typeof ret[0] !== 'undefined') { return ret[0]; } } -var eventChannels = {}; - -var eventChannelStack = []; +// Event channel management +var eventChannels = {}; // Store for event channels +var eventChannelStack = []; // Stack of event channels +// Get an event channel by ID function getEventChannel(id) { if (id) { var eventChannel = eventChannels[id]; - delete eventChannels[id]; + delete eventChannels[id]; // Remove the channel from the store after retrieving return eventChannel; } - return eventChannelStack.shift(); + return eventChannelStack.shift(); // If no ID, return the first item from the stack } +// Define hooks for lifecycle methods var hooks = [ -'onShow', -'onHide', -'onError', -'onPageNotFound', -'onThemeChange', -'onUnhandledRejection']; - + 'onShow', + 'onHide', + 'onError', + 'onPageNotFound', + 'onThemeChange', + 'onUnhandledRejection' +]; +// Initialize event channel handling for Vue components function initEventChannel() { _vue.default.prototype.getOpenerEventChannel = function () { - // 微信小程序使用自身getOpenerEventChannel - { - return this.$scope.getOpenerEventChannel(); - } + return this.$scope.getOpenerEventChannel(); // Return the opener event channel in MP environments }; var callHook = _vue.default.prototype.__call_hook; _vue.default.prototype.__call_hook = function (hook, args) { if (hook === 'onLoad' && args && args.__id__) { - this.__eventChannel__ = getEventChannel(args.__id__); + this.__eventChannel__ = getEventChannel(args.__id__); // Initialize event channel on onLoad delete args.__id__; } return callHook.call(this, hook, args); }; } +// Initialize scoped slot parameters for Vue components function initScopedSlotsParams() { var center = {}; var parents = {}; @@ -2036,24 +1741,22 @@ function initScopedSlotsParams() { delete center[vueId]; delete parents[vueId]; } - } }); - + } + }); } -function parseBaseApp(vm, _ref3) - +// Initialize the base app for a Vue instance in mini-program environments +function parseBaseApp(vm, _ref3) { + var mocks = _ref3.mocks, initRefs = _ref3.initRefs; + initEventChannel(); // Initialize event channel + initScopedSlotsParams(); // Initialize scoped slots params -{var mocks = _ref3.mocks,initRefs = _ref3.initRefs; - initEventChannel(); - { - initScopedSlotsParams(); - } + // Initialize store if present in the options if (vm.$options.store) { _vue.default.prototype.$store = vm.$options.store; } - uniIdMixin(_vue.default); - _vue.default.prototype.mpHost = "mp-weixin"; + _vue.default.prototype.mpHost = "mp-weixin"; // Set the host for mini-program environments _vue.default.mixin({ beforeCreate: function beforeCreate() { @@ -2064,58 +1767,50 @@ function parseBaseApp(vm, _ref3) this.mpType = this.$options.mpType; this.$mp = _defineProperty({ - data: {} }, - this.mpType, this.$options.mpInstance); - + data: {} }, + this.mpType, this.$options.mpInstance); this.$scope = this.$options.mpInstance; delete this.$options.mpType; delete this.$options.mpInstance; - if (this.mpType === 'page' && typeof getApp === 'function') {// hack vue-i18n + + if (this.mpType === 'page' && typeof getApp === 'function') { var app = getApp(); if (app.$vm && app.$vm.$i18n) { - this._i18n = app.$vm.$i18n; + this._i18n = app.$vm.$i18n; // Initialize i18n for the app } } if (this.mpType !== 'app') { initRefs(this); - initMocks(this, mocks); + initMocks(this, mocks); // Initialize refs and mocks } - } }); - + } + }); var appOptions = { onLaunch: function onLaunch(args) { - if (this.$vm) {// 已经初始化过了,主要是为了百度,百度 onShow 在 onLaunch 之前 + if (this.$vm) { return; } - { - if (wx.canIUse && !wx.canIUse('nextTick')) {// 事实 上2.2.3 即可,简单使用 2.3.0 的 nextTick 判断 - console.error('当前微信基础库版本过低,请将 微信开发者工具-详情-项目设置-调试基础库版本 更换为`2.3.0`以上'); - } - } this.$vm = vm; this.$vm.$mp = { app: this }; - this.$vm.$scope = this; - // vm 上也挂载 globalData this.$vm.globalData = this.globalData; this.$vm._isMounted = true; this.$vm.__call_hook('mounted', args); this.$vm.__call_hook('onLaunch', args); - } }; - + } + }; - // 兼容旧版本 globalData + // Initialize global data and methods for the app appOptions.globalData = vm.$options.globalData || {}; - // 将 methods 中的方法挂在 getApp() 中 var methods = vm.$options.methods; if (methods) { Object.keys(methods).forEach(function (name) { @@ -2124,24 +1819,25 @@ function parseBaseApp(vm, _ref3) } initAppLocale(_vue.default, vm, normalizeLocale(wx.getSystemInfoSync().language) || LOCALE_EN); - - initHooks(appOptions, hooks); + initHooks(appOptions, hooks); // Initialize app hooks return appOptions; } +// Initialize references and event handling for Vue components var mocks = ['__route__', '__wxExparserNodeId__', '__wxWebviewId__']; function findVmByVueId(vm, vuePid) { var $children = vm.$children; - // 优先查找直属(反向查找:https://github.com/dcloudio/uni-app/issues/1200) + // Search for the component using vueId for (var i = $children.length - 1; i >= 0; i--) { var childVm = $children[i]; if (childVm.$scope._$vueId === vuePid) { return childVm; } } - // 反向递归查找 + + // If not found, recurse to check deeper var parentVm; for (var _i = $children.length - 1; _i >= 0; _i--) { parentVm = findVmByVueId($children[_i], vuePid); @@ -2151,40 +1847,43 @@ function findVmByVueId(vm, vuePid) { } } +// Initialize behavior for mini-program components function initBehavior(options) { return Behavior(options); } +// Check if the current context is a page function isPage() { return !!this.route; } +// Initialize relation (e.g., parent-child relationships) between components function initRelation(detail) { - this.triggerEvent('__l', detail); + this.triggerEvent('__l', detail); // Trigger event to establish the relation } +// Select all components matching a selector and store them in $refs function selectAllComponents(mpInstance, selector, $refs) { var components = mpInstance.selectAllComponents(selector); components.forEach(function (component) { var ref = component.dataset.ref; $refs[ref] = component.$vm || component; - { - if (component.dataset.vueGeneric === 'scoped') { - component.selectAllComponents('.scoped-ref').forEach(function (scopedComponent) { - selectAllComponents(scopedComponent, selector, $refs); - }); - } + if (component.dataset.vueGeneric === 'scoped') { + component.selectAllComponents('.scoped-ref').forEach(function (scopedComponent) { + selectAllComponents(scopedComponent, selector, $refs); + }); } }); } +// Initialize references for the Vue instance function initRefs(vm) { var mpInstance = vm.$scope; + // Define $refs to collect components matching the .vue-ref selector Object.defineProperty(vm, '$refs', { get: function get() { var $refs = {}; selectAllComponents(mpInstance, '.vue-ref', $refs); - // TODO 暂不考虑 for 中的 scoped var forComponents = mpInstance.selectAllComponents('.vue-ref-in-for'); forComponents.forEach(function (component) { var ref = component.dataset.ref; @@ -2194,10 +1893,11 @@ function initRefs(vm) { $refs[ref].push(component.$vm || component); }); return $refs; - } }); - + } + }); } + function handleLink(event) {var _ref4 =