diff --git a/package.json b/package.json index 7d28799b4cc52dbdc022b5bb9c8f2e1573d93573..d8f7d0fb9bd1bfd2ee30ecaff6a1e3c3f979a689 100644 --- a/package.json +++ b/package.json @@ -51,16 +51,20 @@ "@rollup/plugin-node-resolve": "^11.0.1", "@rollup/plugin-replace": "^2.3.4", "@rollup/plugin-strip": "^2.0.0", + "@types/clean-css": "^4.2.5", "@types/css-font-loading-module": "^0.0.4", "@types/debug": "^4.1.5", "@types/es-module-lexer": "^0.3.0", "@types/fs-extra": "^9.0.6", "@types/jest": "^26.0.23", + "@types/less": "^3.0.3", "@types/node": "^14.14.20", "@types/pako": "^1.0.1", + "@types/postcss-import": "^12.0.1", "@types/puppeteer": "^5.4.2", "@types/quill": "^1.3.7", "@types/resolve": "^1.20.0", + "@types/stylus": "^0.48.36", "@typescript-eslint/parser": "^4.12.0", "@vitejs/plugin-legacy": "^1.4.4", "@vitejs/plugin-vue": "^1.2.5", @@ -75,6 +79,7 @@ "mini-types": "^0.1.4", "miniprogram-api-typings": "^3.4.0", "module-alias": "^2.2.2", + "postcss-load-config": "^3.1.0", "prettier": "^2.2.1", "rollup": "^2.35.1", "rollup-plugin-jscc": "^2.0.0", @@ -85,7 +90,7 @@ "rollup-plugin-vue": "^6.0.0", "semver": "^7.3.4", "ts-jest": "^27.0.3", - "typescript": "~4.1.3", + "typescript": "^4.3.5", "vite": "^2.4.2", "vue": "^3.1.4", "yorkie": "^2.0.0" diff --git a/packages/uni-app-plus/dist/uni-app-service.es.js b/packages/uni-app-plus/dist/uni-app-service.es.js index 40446862814db75578b5371247d1a5de12b9ca5f..8ce8266b46efa3e693bb44fe606dbf592d5edb16 100644 --- a/packages/uni-app-plus/dist/uni-app-service.es.js +++ b/packages/uni-app-plus/dist/uni-app-service.es.js @@ -9,79 +9,79 @@ const __uniRoutes = instanceContext.__uniRoutes; var serviceContext = (function (vue) { 'use strict'; - /* - * base64-arraybuffer - * https://github.com/niklasvh/base64-arraybuffer - * - * Copyright (c) 2012 Niklas von Hertzen - * Licensed under the MIT license. - */ - - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - - // Use a lookup table to find the index. - var lookup = /*#__PURE__*/ (function () { - const lookup = new Uint8Array(256); - for (var i = 0; i < chars.length; i++) { - lookup[chars.charCodeAt(i)] = i; - } - return lookup - })(); - - function encode$3(arraybuffer) { - var bytes = new Uint8Array(arraybuffer), - i, - len = bytes.length, - base64 = ''; - - for (i = 0; i < len; i += 3) { - base64 += chars[bytes[i] >> 2]; - base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; - base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; - base64 += chars[bytes[i + 2] & 63]; - } - - if (len % 3 === 2) { - base64 = base64.substring(0, base64.length - 1) + '='; - } else if (len % 3 === 1) { - base64 = base64.substring(0, base64.length - 2) + '=='; - } - - return base64 - } - - function decode$1(base64) { - var bufferLength = base64.length * 0.75, - len = base64.length, - i, - p = 0, - encoded1, - encoded2, - encoded3, - encoded4; - - if (base64[base64.length - 1] === '=') { - bufferLength--; - if (base64[base64.length - 2] === '=') { - bufferLength--; - } - } - - var arraybuffer = new ArrayBuffer(bufferLength), - bytes = new Uint8Array(arraybuffer); - - for (i = 0; i < len; i += 4) { - encoded1 = lookup[base64.charCodeAt(i)]; - encoded2 = lookup[base64.charCodeAt(i + 1)]; - encoded3 = lookup[base64.charCodeAt(i + 2)]; - encoded4 = lookup[base64.charCodeAt(i + 3)]; - - bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); - bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); - bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); - } - - return arraybuffer + /* + * base64-arraybuffer + * https://github.com/niklasvh/base64-arraybuffer + * + * Copyright (c) 2012 Niklas von Hertzen + * Licensed under the MIT license. + */ + + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + + // Use a lookup table to find the index. + var lookup = /*#__PURE__*/ (function () { + const lookup = new Uint8Array(256); + for (var i = 0; i < chars.length; i++) { + lookup[chars.charCodeAt(i)] = i; + } + return lookup + })(); + + function encode$3(arraybuffer) { + var bytes = new Uint8Array(arraybuffer), + i, + len = bytes.length, + base64 = ''; + + for (i = 0; i < len; i += 3) { + base64 += chars[bytes[i] >> 2]; + base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; + base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; + base64 += chars[bytes[i + 2] & 63]; + } + + if (len % 3 === 2) { + base64 = base64.substring(0, base64.length - 1) + '='; + } else if (len % 3 === 1) { + base64 = base64.substring(0, base64.length - 2) + '=='; + } + + return base64 + } + + function decode$1(base64) { + var bufferLength = base64.length * 0.75, + len = base64.length, + i, + p = 0, + encoded1, + encoded2, + encoded3, + encoded4; + + if (base64[base64.length - 1] === '=') { + bufferLength--; + if (base64[base64.length - 2] === '=') { + bufferLength--; + } + } + + var arraybuffer = new ArrayBuffer(bufferLength), + bytes = new Uint8Array(arraybuffer); + + for (i = 0; i < len; i += 4) { + encoded1 = lookup[base64.charCodeAt(i)]; + encoded2 = lookup[base64.charCodeAt(i + 1)]; + encoded3 = lookup[base64.charCodeAt(i + 2)]; + encoded4 = lookup[base64.charCodeAt(i + 3)]; + + bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); + } + + return arraybuffer } /** @@ -735,11 +735,14 @@ var serviceContext = (function (vue) { return `on${capitalize(camelize(type))}`; } class UniEvent { + type; + bubbles; + cancelable; + defaultPrevented = false; + timeStamp = Date.now(); + _stop = false; + _end = false; constructor(type, opts) { - this.defaultPrevented = false; - this.timeStamp = Date.now(); - this._stop = false; - this._end = false; this.type = type; this.bubbles = !!opts.bubbles; this.cancelable = !!opts.cancelable; @@ -767,9 +770,7 @@ var serviceContext = (function (vue) { return uniEvent; } class UniEventTarget { - constructor() { - this.listeners = Object.create(null); - } + listeners = Object.create(null); dispatchEvent(evt) { const listeners = this.listeners[evt.type]; if (!listeners) { @@ -842,11 +843,15 @@ var serviceContext = (function (vue) { } // 为优化性能,各平台不使用proxy来实现node的操作拦截,而是直接通过pageNode定制 class UniNode extends UniEventTarget { + nodeId; + nodeType; + nodeName; + childNodes; + pageNode = null; + parentNode = null; + _text = null; constructor(nodeType, nodeName, container) { super(); - this.pageNode = null; - this.parentNode = null; - this._text = null; if (container) { const { pageNode } = container; if (pageNode) { @@ -1034,6 +1039,7 @@ var serviceContext = (function (vue) { const isObject = (val) => val !== null && typeof val === 'object'; class BaseFormatter { + _caches; constructor() { this._caches = Object.create(null); } @@ -1171,12 +1177,13 @@ var serviceContext = (function (vue) { } } class I18n { + locale = LOCALE_EN; + fallbackLocale = LOCALE_EN; + message = {}; + messages = {}; + watchers = []; + formater; constructor({ locale, fallbackLocale, messages, watcher, formater, }) { - this.locale = LOCALE_EN; - this.fallbackLocale = LOCALE_EN; - this.message = {}; - this.messages = {}; - this.watchers = []; if (fallbackLocale) { this.fallbackLocale = fallbackLocale; } @@ -2093,12 +2100,15 @@ var serviceContext = (function (vue) { if (!isPromise(res)) { return res; } - return res - .then((res) => { - return res[1]; - }) - .catch((res) => { - return res[0]; + return new Promise((resolve, reject) => { + res.then((res) => { + if (res[0]) { + reject(res[0]); + } + else { + resolve(res[1]); + } + }); }); }, }; @@ -2188,6 +2198,8 @@ var serviceContext = (function (vue) { const API_CREATE_INNER_AUDIO_CONTEXT = 'createInnerAudioContext'; class VideoContext { + id; + pageId; constructor(id, pageId) { this.id = id; this.pageId = pageId; @@ -2231,6 +2243,8 @@ var serviceContext = (function (vue) { }); class MapContext { + id; + pageId; constructor(id, pageId) { this.id = id; this.pageId = pageId; @@ -2631,6 +2645,9 @@ var serviceContext = (function (vue) { //#endregion //#region Class class CanvasGradient { + type; + data; + colorStop; constructor(type, data) { this.type = type; this.data = data; @@ -2641,17 +2658,27 @@ var serviceContext = (function (vue) { } } class Pattern { + image; + repetition; constructor(image, repetition) { this.image = image; this.repetition = repetition; } } class TextMetrics { + width; constructor(width) { this.width = width; } } class CanvasContext { + id; + pageId; + actions; + path; + subpath; + state; + drawingState; constructor(id, pageId) { this.id = id; this.pageId = pageId; @@ -2981,6 +3008,31 @@ var serviceContext = (function (vue) { data: [type], }); } + 'setFillStyle'; + 'setStrokeStyle'; + 'setGlobalAlpha'; + 'setShadow'; + 'addColorStop'; + 'setLineWidth'; + 'setLineCap'; + 'setLineJoin'; + 'setLineDash'; + 'setMiterLimit'; + 'fillRect'; + 'strokeRect'; + 'clearRect'; + 'fill'; + 'stroke'; + 'scale'; + 'rotate'; + 'translate'; + 'setFontSize'; + 'fillText'; + 'setTextAlign'; + 'setTextBaseline'; + 'drawImage'; + 'strokeText'; + 'setTransform'; } const initCanvasContextProperty = /*#__PURE__*/ once(() => { [...methods1, ...methods2].forEach(function (method) { @@ -3314,6 +3366,10 @@ var serviceContext = (function (vue) { return MARGINS.map((name) => `${Number(margins[name]) || 0}px`).join(' '); } class ServiceIntersectionObserver { + _reqId; + _pageId; + _component; + _options; constructor(component, options) { this._pageId = getPageIdByVm(component); this._component = component; @@ -3360,6 +3416,9 @@ var serviceContext = (function (vue) { let reqComponentObserverId = 1; class ServiceMediaQueryObserver { + _reqId; + _pageId; + _component; constructor(component) { this._pageId = component.$page && component.$page.id; this._component = component; @@ -3420,6 +3479,8 @@ var serviceContext = (function (vue) { }, pageId); } class EditorContext { + id; + pageId; constructor(id, pageId) { this.id = id; this.pageId = pageId; @@ -3486,6 +3547,10 @@ var serviceContext = (function (vue) { } } class NodesRef { + _selectorQuery; + _component; + _selector; + _single; constructor(selectorQuery, component, selector, single) { this._selectorQuery = selectorQuery; this._component = component; @@ -3521,8 +3586,12 @@ var serviceContext = (function (vue) { } } class SelectorQuery { + _page; + _queue; + _component = undefined; + _queueCb; + _nodesRef; constructor(page) { - this._component = undefined; this._page = page; this._queue = []; this._queueCb = []; @@ -3616,6 +3685,10 @@ var serviceContext = (function (vue) { transformOrigin: '50% 50% 0', }; class MPAnimation { + actions; + currentTransform; + currentStepAnimates; + option; constructor(option) { this.actions = []; this.currentTransform = {}; @@ -3668,6 +3741,34 @@ var serviceContext = (function (vue) { this.currentStepAnimates = []; return this; } + 'matrix'; + 'matrix3d'; + 'rotate'; + 'rotate3d'; + 'rotateX'; + 'rotateY'; + 'rotateZ'; + 'scale'; + 'scale3d'; + 'scaleX'; + 'scaleY'; + 'scaleZ'; + 'skew'; + 'skewX'; + 'skewY'; + 'translate'; + 'translate3d'; + 'translateX'; + 'translateY'; + 'translateZ'; + 'opacity'; + 'backgroundColor'; + 'width'; + 'height'; + 'right'; + 'top'; + 'bottom'; + 'left'; } const initAnimationProperty = /*#__PURE__*/ once(() => { const animateTypes1 = [ @@ -5789,7 +5890,9 @@ var serviceContext = (function (vue) { }, res)); }; const Recorder = { - start({ duration = 60000, sampleRate, numberOfChannels, encodeBitRate, format = 'mp3', frameSize, }) { + start({ duration = 60000, sampleRate, numberOfChannels, encodeBitRate, format = 'mp3', frameSize, + // audioSource = 'auto', + }) { if (recording) { return publishRecorderStateChange('start'); } @@ -6157,8 +6260,9 @@ var serviceContext = (function (vue) { }); class DownloadTask { + _downloader; + _callbacks = []; constructor(downloader) { - this._callbacks = []; this._downloader = downloader; downloader.addEventListener('statechanged', (download, status) => { if (download.downloadedSize && download.totalSize) { @@ -6277,6 +6381,7 @@ var serviceContext = (function (vue) { * 请求任务类 */ class RequestTask { + _requestTask; constructor(requestTask) { this._requestTask = requestTask; } @@ -6451,6 +6556,14 @@ var serviceContext = (function (vue) { }); } class SocketTask { + _callbacks; + _socket; + id; + CLOSED; + CLOSING; + CONNECTING; + OPEN; + readyState; constructor(socket, socketId) { this.id = socketId; this._socket = socket; @@ -6606,8 +6719,9 @@ var serviceContext = (function (vue) { const onSocketClose = /*#__PURE__*/ on('close'); class UploadTask { + _uploader; + _callbacks = []; constructor(uploader) { - this._callbacks = []; this._uploader = uploader; uploader.addEventListener('statechanged', (upload, status) => { if (upload.uploadedSize && upload.totalSize) { @@ -6861,6 +6975,61 @@ var serviceContext = (function (vue) { }, ]; class InnerAudioContext { + /** + * 当前音频的长度(单位:s),只有在当前有合法的 src 时返回 + */ + 'duration'; + /** + * 音频开始播放的位置(单位:s) + */ + 'startTime'; + /** + * 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回 + */ + 'currentTime'; + /** + * 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放 + */ + 'paused'; + /** + * 音频的数据链接,用于直接播放。 + */ + 'src'; + /** + * 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲 + */ + 'buffered'; + /** + * 是否自动开始播放,默认 false + */ + 'autoplay'; + /** + * 是否循环播放,默认 false + */ + 'loop'; + /** + * 是否遵循系统静音开关,当此参数为 false 时,即使用户打开了静音开关,也能继续发出声音,默认值 true + */ + 'obeyMuteSwitch'; + /** + * 音量。范围 0~1。 + */ + 'volume'; + /** + * 事件监听 + */ + _callbacks; + /** + * + * @param id 当前Audio示例id + */ + id; + /** + * + * @param __timing 当前Audio所使用的timer + */ + __timing; + _options; constructor(id) { this.id = id; this._callbacks = {}; @@ -6923,6 +7092,26 @@ var serviceContext = (function (vue) { operationType: type, })); } + 'onCanplay'; + 'onPlay'; + 'onPause'; + 'onStop'; + 'onEnded'; + 'onTimeUpdate'; + 'onError'; + 'onWaiting'; + 'onSeeking'; + 'onSeeked'; + 'offCanplay'; + 'offPlay'; + 'offPause'; + 'offStop'; + 'offEnded'; + 'offTimeUpdate'; + 'offError'; + 'offWaiting'; + 'offSeeking'; + 'offSeeked'; } const initInnerAudioContextEventOnce = /*#__PURE__*/ once(() => { // 批量设置音频上下文事件监听方法 @@ -7230,6 +7419,19 @@ var serviceContext = (function (vue) { }, ]; class BackgroundAudioManager { + 'duration'; + 'startTime'; + 'currentTime'; + 'paused'; + 'src'; + 'buffered'; + 'title'; + 'epname'; + 'singer'; + 'coverImgUrl'; + 'webUrl'; + 'protocol'; + _options; constructor() { this._options = {}; props.forEach((item) => { @@ -7268,6 +7470,16 @@ var serviceContext = (function (vue) { operationType: type, })); } + 'onCanplay'; + 'onPlay'; + 'onPause'; + 'onStop'; + 'onEnded'; + 'onTimeUpdate'; + 'onWaiting'; + 'onPrev'; + 'onNext'; + 'onError'; } let backgroundAudioManager; const getBackgroundAudioManager = defineSyncApi(API_GET_BACKGROUND_AUDIO_MANAGER, () => backgroundAudioManager || @@ -7446,6 +7658,7 @@ var serviceContext = (function (vue) { callbacks[pageId] = callback; } class Page { + webview; constructor(webview) { this.webview = webview; } @@ -7671,7 +7884,7 @@ var serviceContext = (function (vue) { modal: mask, back: 'transmit', padding: '10px', - size: '16px', + size: '16px', // 固定字体大小 }; if (!image && (!icon || icon === 'none')) { // 无图 @@ -8904,6 +9117,7 @@ var serviceContext = (function (vue) { adClicked: 'adClicked', }; class AdEventHandler { + _callbacks; constructor() { this._callbacks = {}; } @@ -8945,15 +9159,16 @@ var serviceContext = (function (vue) { } } class AdBase extends AdEventHandler { + _isLoaded = false; + _isLoading = false; + _preload = true; + _loadPromiseResolve = null; + _loadPromiseReject = null; + _showPromiseResolve = null; + _showPromiseReject = null; + _adInstance; constructor(adInstance, options) { super(); - this._isLoaded = false; - this._isLoading = false; - this._preload = true; - this._loadPromiseResolve = null; - this._loadPromiseReject = null; - this._showPromiseResolve = null; - this._showPromiseReject = null; this._preload = options.preload !== undefined ? options.preload : false; const ad = (this._adInstance = adInstance); ad.onLoad(() => { @@ -9131,19 +9346,19 @@ var serviceContext = (function (vue) { }); } class InteractiveAd extends AdEventHandler { + _adpid = ''; + _provider = ''; + _userData = null; + _isLoaded = false; + _isLoading = false; + _loadPromiseResolve = null; + _loadPromiseReject = null; + _showPromiseResolve = null; + _showPromiseReject = null; + _adInstance = null; + _adError = ''; constructor(options) { super(); - this._adpid = ''; - this._provider = ''; - this._userData = null; - this._isLoaded = false; - this._isLoading = false; - this._loadPromiseResolve = null; - this._loadPromiseReject = null; - this._showPromiseResolve = null; - this._showPromiseReject = null; - this._adInstance = null; - this._adError = ''; this._adpid = options.adpid; this._provider = options.provider; this._userData = options.userData; @@ -9573,13 +9788,19 @@ var serviceContext = (function (vue) { } class UniPageNode extends UniNode { + pageId; + _id = 1; + _created = false; + createAction; + createdAction; + _createActionMap = new Map(); + updateActions = []; + dicts = []; + normalizeDict; + isUnmounted; + _update; constructor(pageId, options, setup = false) { super(NODE_TYPE_PAGE, '#page', null); - this._id = 1; - this._created = false; - this._createActionMap = new Map(); - this.updateActions = []; - this.dicts = []; this.nodeId = 0; this.pageId = pageId; this.pageNode = this; @@ -9822,22 +10043,33 @@ var serviceContext = (function (vue) { return vm; } + function isVuePageAsyncComponent(component) { + return isFunction(component); + } const pagesMap = new Map(); - function definePage(pagePath, component) { - pagesMap.set(pagePath, once(createFactory(component))); + function definePage(pagePath, asyncComponent) { + pagesMap.set(pagePath, once(createFactory(asyncComponent))); } function createPage(__pageId, __pagePath, __pageQuery, __pageInstance, pageOptions) { const pageNode = createPageNode(__pageId, pageOptions, true); const app = getVueApp(); - return app.mountPage(pagesMap.get(__pagePath)(), { + const component = pagesMap.get(__pagePath)(); + const mountPage = (component) => app.mountPage(component, { __pageId, __pagePath, __pageQuery, __pageInstance, }, pageNode); + if (isPromise(component)) { + return component.then((component) => mountPage(component)); + } + return mountPage(component); } function createFactory(component) { return () => { + if (isVuePageAsyncComponent(component)) { + return component().then((component) => setupPage(component)); + } return setupPage(component); }; } diff --git a/packages/uni-app-plus/dist/uni-app-view.umd.js b/packages/uni-app-plus/dist/uni-app-view.umd.js index 9d5e08861659a780e3647550cc35c41138846c39..0224b3b67ce012d84351074f38fe8b56691831a6 100644 --- a/packages/uni-app-plus/dist/uni-app-view.umd.js +++ b/packages/uni-app-plus/dist/uni-app-view.umd.js @@ -1,9 +1,15 @@ +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; (function(factory) { typeof define === "function" && define.amd ? define(factory) : factory(); })(function() { "use strict"; - var base = "* {\r\n margin: 0;\r\n -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\r\n -webkit-tap-highlight-color: transparent;\r\n}\r\n\r\nhtml,\r\nbody {\r\n -webkit-user-select: none;\r\n user-select: none;\r\n width: 100%;\r\n}\r\n\r\nhtml {\r\n height: 100%;\r\n height: 100vh;\r\n width: 100%;\r\n width: 100vw;\r\n}\r\n\r\nbody {\r\n overflow-x: hidden;\r\n background-color: white;\r\n}\r\n\r\ninput[type='search']::-webkit-search-cancel-button {\r\n display: none;\r\n}\r\n\r\n.uni-loading,\r\nuni-button[loading]:before {\r\n background: transparent\r\n url('data:image/svg+xml;base64, PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgMTAwIDEwMCI+PHBhdGggZmlsbD0ibm9uZSIgZD0iTTAgMGgxMDB2MTAwSDB6Ii8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjRTlFOUU5IiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAgLTMwKSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iIzk4OTY5NyIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgzMCAxMDUuOTggNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjOUI5OTlBIiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKDYwIDc1Ljk4IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0EzQTFBMiIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSg5MCA2NSA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNBQkE5QUEiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoMTIwIDU4LjY2IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0IyQjJCMiIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgxNTAgNTQuMDIgNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjQkFCOEI5IiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKDE4MCA1MCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNDMkMwQzEiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTE1MCA0NS45OCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNDQkNCQ0IiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTEyMCA0MS4zNCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNEMkQyRDIiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTkwIDM1IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0RBREFEQSIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgtNjAgMjQuMDIgNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjRTJFMkUyIiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKC0zMCAtNS45OCA2NSkiLz48L3N2Zz4=')\r\n no-repeat;\r\n}\r\n\r\n.uni-loading {\r\n width: 20px;\r\n height: 20px;\r\n display: inline-block;\r\n vertical-align: middle;\r\n animation: uni-loading 1s steps(12, end) infinite;\r\n background-size: 100%;\r\n}\r\n\r\n@keyframes uni-loading {\r\n 0% {\r\n transform: rotate3d(0, 0, 1, 0deg);\r\n }\r\n\r\n 100% {\r\n transform: rotate3d(0, 0, 1, 360deg);\r\n }\r\n}\r\n"; - var nvue = "[nvue] uni-view,\r\n[nvue] uni-label,\r\n[nvue] uni-swiper-item,\r\n[nvue] uni-scroll-view {\r\n display: flex;\r\n flex-shrink: 0;\r\n flex-grow: 0;\r\n flex-basis: auto;\r\n align-items: stretch;\r\n align-content: flex-start;\r\n}\r\n\r\n[nvue] uni-button {\r\n margin: 0;\r\n}\r\n\r\n[nvue-dir-row] uni-view,\r\n[nvue-dir-row] uni-label,\r\n[nvue-dir-row] uni-swiper-item {\r\n flex-direction: row;\r\n}\r\n\r\n[nvue-dir-column] uni-view,\r\n[nvue-dir-column] uni-label,\r\n[nvue-dir-column] uni-swiper-item {\r\n flex-direction: column;\r\n}\r\n\r\n[nvue-dir-row-reverse] uni-view,\r\n[nvue-dir-row-reverse] uni-label,\r\n[nvue-dir-row-reverse] uni-swiper-item {\r\n flex-direction: row-reverse;\r\n}\r\n\r\n[nvue-dir-column-reverse] uni-view,\r\n[nvue-dir-column-reverse] uni-label,\r\n[nvue-dir-column-reverse] uni-swiper-item {\r\n flex-direction: column-reverse;\r\n}\r\n\r\n[nvue] uni-view,\r\n[nvue] uni-image,\r\n[nvue] uni-input,\r\n[nvue] uni-scroll-view,\r\n[nvue] uni-swiper,\r\n[nvue] uni-swiper-item,\r\n[nvue] uni-text,\r\n[nvue] uni-textarea,\r\n[nvue] uni-video {\r\n position: relative;\r\n border: 0px solid #000000;\r\n box-sizing: border-box;\r\n}\r\n\r\n[nvue] uni-swiper-item {\r\n position: absolute;\r\n}\r\n"; + var base = "* {\n margin: 0;\n -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n -webkit-tap-highlight-color: transparent;\n}\n\nhtml,\nbody {\n -webkit-user-select: none;\n user-select: none;\n width: 100%;\n}\n\nhtml {\n height: 100%;\n height: 100vh;\n width: 100%;\n width: 100vw;\n}\n\nbody {\n overflow-x: hidden;\n background-color: white;\n}\n\ninput[type='search']::-webkit-search-cancel-button {\n display: none;\n}\n\n.uni-loading,\nuni-button[loading]:before {\n background: transparent\n url('data:image/svg+xml;base64, PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgMTAwIDEwMCI+PHBhdGggZmlsbD0ibm9uZSIgZD0iTTAgMGgxMDB2MTAwSDB6Ii8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjRTlFOUU5IiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAgLTMwKSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iIzk4OTY5NyIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgzMCAxMDUuOTggNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjOUI5OTlBIiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKDYwIDc1Ljk4IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0EzQTFBMiIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSg5MCA2NSA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNBQkE5QUEiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoMTIwIDU4LjY2IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0IyQjJCMiIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgxNTAgNTQuMDIgNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjQkFCOEI5IiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKDE4MCA1MCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNDMkMwQzEiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTE1MCA0NS45OCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNDQkNCQ0IiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTEyMCA0MS4zNCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNEMkQyRDIiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTkwIDM1IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0RBREFEQSIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgtNjAgMjQuMDIgNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjRTJFMkUyIiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKC0zMCAtNS45OCA2NSkiLz48L3N2Zz4=')\n no-repeat;\n}\n\n.uni-loading {\n width: 20px;\n height: 20px;\n display: inline-block;\n vertical-align: middle;\n animation: uni-loading 1s steps(12, end) infinite;\n background-size: 100%;\n}\n\n@keyframes uni-loading {\n 0% {\n transform: rotate3d(0, 0, 1, 0deg);\n }\n\n 100% {\n transform: rotate3d(0, 0, 1, 360deg);\n }\n}\n"; + var nvue = "[nvue] uni-view,\n[nvue] uni-label,\n[nvue] uni-swiper-item,\n[nvue] uni-scroll-view {\n display: flex;\n flex-shrink: 0;\n flex-grow: 0;\n flex-basis: auto;\n align-items: stretch;\n align-content: flex-start;\n}\n\n[nvue] uni-button {\n margin: 0;\n}\n\n[nvue-dir-row] uni-view,\n[nvue-dir-row] uni-label,\n[nvue-dir-row] uni-swiper-item {\n flex-direction: row;\n}\n\n[nvue-dir-column] uni-view,\n[nvue-dir-column] uni-label,\n[nvue-dir-column] uni-swiper-item {\n flex-direction: column;\n}\n\n[nvue-dir-row-reverse] uni-view,\n[nvue-dir-row-reverse] uni-label,\n[nvue-dir-row-reverse] uni-swiper-item {\n flex-direction: row-reverse;\n}\n\n[nvue-dir-column-reverse] uni-view,\n[nvue-dir-column-reverse] uni-label,\n[nvue-dir-column-reverse] uni-swiper-item {\n flex-direction: column-reverse;\n}\n\n[nvue] uni-view,\n[nvue] uni-image,\n[nvue] uni-input,\n[nvue] uni-scroll-view,\n[nvue] uni-swiper,\n[nvue] uni-swiper-item,\n[nvue] uni-text,\n[nvue] uni-textarea,\n[nvue] uni-video {\n position: relative;\n border: 0px solid #000000;\n box-sizing: border-box;\n}\n\n[nvue] uni-swiper-item {\n position: absolute;\n}\n"; function makeMap$1(str, expectsLowerCase) { const map = Object.create(null); const list2 = str.split(","); @@ -265,6 +271,7 @@ const isObject = (val) => val !== null && typeof val === "object"; class BaseFormatter { constructor() { + __publicField(this, "_caches"); this._caches = Object.create(null); } interpolate(message, values) { @@ -380,11 +387,12 @@ } class I18n { constructor({ locale, fallbackLocale, messages, watcher, formater }) { - this.locale = LOCALE_EN; - this.fallbackLocale = LOCALE_EN; - this.message = {}; - this.messages = {}; - this.watchers = []; + __publicField(this, "locale", LOCALE_EN); + __publicField(this, "fallbackLocale", LOCALE_EN); + __publicField(this, "message", {}); + __publicField(this, "messages", {}); + __publicField(this, "watchers", []); + __publicField(this, "formater"); if (fallbackLocale) { this.fallbackLocale = fallbackLocale; } @@ -517,6 +525,24 @@ return res; }, {}); } + const initI18nShowModalMsgsOnce = /* @__PURE__ */ once(() => { + const name = "uni.showModal."; + { + useI18n().add(LOCALE_EN, normalizeMessages(name, { cancel: "Cancel", confirm: "OK" })); + } + { + useI18n().add(LOCALE_ES, normalizeMessages(name, { cancel: "Cancelar", confirm: "OK" })); + } + { + useI18n().add(LOCALE_FR, normalizeMessages(name, { cancel: "Annuler", confirm: "OK" })); + } + { + useI18n().add(LOCALE_ZH_HANS, normalizeMessages(name, { cancel: "\u53D6\u6D88", confirm: "\u786E\u5B9A" })); + } + { + useI18n().add(LOCALE_ZH_HANT, normalizeMessages(name, { cancel: "\u53D6\u6D88", confirm: "\u78BA\u5B9A" })); + } + }); const initI18nButtonMsgsOnce = /* @__PURE__ */ once(() => { const name = "uni.button."; { @@ -5115,7 +5141,7 @@ onChange, offChange }; - var D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out = safeAreaInsets; + var out = safeAreaInsets; const onEventPrevent = /* @__PURE__ */ withModifiers(() => { }, ["prevent"]); function getWindowOffset() { @@ -5125,10 +5151,10 @@ const left = parseInt(style.getPropertyValue("--window-left")); const right = parseInt(style.getPropertyValue("--window-right")); return { - top: top ? top + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.top : 0, - bottom: bottom ? bottom + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.bottom : 0, - left: left ? left + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.left : 0, - right: right ? right + D__DCloud_local_git_uniAppNext_node_modules_safeAreaInsets_out.right : 0 + top: top ? top + out.top : 0, + bottom: bottom ? bottom + out.bottom : 0, + left: left ? left + out.left : 0, + right: right ? right + out.right : 0 }; } function updateCssVar(cssVars) { @@ -5379,6 +5405,7 @@ } return res; } + [ON_PAGE_SCROLL, ON_REACH_BOTTOM]; const VD_SYNC = "vdSync"; const ON_WEBVIEW_READY = "onWebviewReady"; const INVOKE_VIEW_API = "invokeViewApi"; @@ -5681,6 +5708,30 @@ }, Upx2pxProtocol); createCallbacks("canvasEvent"); createCallbacks("getSelectedTextRangeEvent"); + ({ + beforeInvoke() { + initI18nShowModalMsgsOnce(); + }, + formatArgs: { + title: "", + content: "", + showCancel: true, + cancelText(_value, params) { + if (!hasOwn$1(params, "cancelText")) { + const { t: t2 } = useI18n(); + params.cancelText = t2("uni.showModal.cancel"); + } + }, + cancelColor: "#000", + confirmText(_value, params) { + if (!hasOwn$1(params, "confirmText")) { + const { t: t2 } = useI18n(); + params.confirmText = t2("uni.showModal.confirm"); + } + }, + confirmColor: PRIMARY_COLOR + } + }); function invokeServiceApi(method, args = {}) { UniViewJSBridge.publishHandler(INVOKE_SERVICE_API, { data: { @@ -6010,7 +6061,7 @@ super(id2, "#comment", parentNodeId, document.createComment("")); } } - var text$1 = "uni-text[selectable] {\r\n cursor: auto;\r\n -webkit-user-select: text;\r\n user-select: text;\r\n}\r\n"; + var text$1 = "uni-text[selectable] {\n cursor: auto;\n -webkit-user-select: text;\n user-select: text;\n}\n"; var subscriber = { mounted() { this._toggleListeners("subscribe", this.id); @@ -14145,7 +14196,7 @@ this.init(nodeJson); } } - var view = "uni-view {\r\n display: block;\r\n}\r\nuni-view[hidden] {\r\n display: none;\r\n}\r\n"; + var view = "uni-view {\n display: block;\n}\nuni-view[hidden] {\n display: none;\n}\n"; const PROP_NAMES_HOVER = [ "hover-class", "hover-stop-propagation", @@ -14376,13 +14427,13 @@ super(id2, "uni-ad", Ad, parentNodeId, nodeJson); } } - var audio = "uni-audio {\r\n display: none;\r\n}\r\n\r\nuni-audio[controls] {\r\n display: inline-block;\r\n}\r\n\r\nuni-audio[hidden] {\r\n display: none;\r\n}\r\n\r\n.uni-audio-default {\r\n max-width: 100%;\r\n min-width: 302px;\r\n height: 65px;\r\n background: #fcfcfc;\r\n border: 1px solid #e0e0e0;\r\n border-radius: 2.5px;\r\n display: inline-block;\r\n overflow: hidden;\r\n}\r\n\r\n.uni-audio-left {\r\n width: 65px;\r\n height: 65px;\r\n float: left;\r\n background-color: #e6e6e6;\r\n background-size: 100% 100%;\r\n background-position: 50% 50%;\r\n}\r\n\r\n.uni-audio-button {\r\n width: 24px;\r\n height: 24px;\r\n margin: 20.5px;\r\n background-size: cover;\r\n}\r\n\r\n.uni-audio-button.play {\r\n background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAAB4dJREFUaAXNWg1MlVUYvpcfIRCJ+MnCaOBl8dOcOCEQZ9kmI5cQG5Yb6MifKbMaGVobOtlibTWHDpgpxBUwF07826iFsMkYJhg559JdGiQSkUzSBA0QkZ7n4/u+nXsvwf3jwru99/y/3/N+3znvec97rlbjABofH38GYtaAV4MjwDqwH9gHTBoE3wd3gA3gi+B6rVY7hHR2CKD9wFngs+BHYGuJYziWMqiscwgP8wLvBQ+AHUWURZle1mqhtXQAhLui7xZwPvgFsBENDg7+Drp069at2z09Pf03b978u6mpqZ+dVq1aFRAVFeW/aNGigNDQ0JfDwsISfXx8wowETBT+QpIPLsf0GpuomvrXIgUAPhhizoGXi+II+tq1az/o9fpLFRUVd8S26fJZWVkLN2/enBgTE/PW/PnzF5v0b0P5HSjxp0m9WXFaBQD+NYw6C1bf+vDwcF9DQ4N+/fr19ciPm0m1osLT01N76tSpNaD3PTw8FgpD+TXSoESrUGeWnVIBgM/EiDKwJ0eiPNrS0nJsw4YNNd3d3aOscxSFhIS4V1dXpyckJGRB5jxZ7jDSbVDiW7lslriY1cgVMvjjKErgR0dH/zl06NCuFStWfOdo8HwkZVL2wYMHP3ny5AlNLonPPi5jkSpMfyb9AhjAadMIlsBjrndmZ2fnnThxos9UwEyUMzIynj9y5EgB1gb3ExK/xBuTTSczBQCeC/ZnsDTnCR6f9YMbN25QiNMoOjras7W1tcjb2ztcfijXRKzpwjaaQgBPU0lrI4HntOGbdzZ4AuYzt2/fvm9sbOweyyBiOidjlCr4Y6QAyrTzkqlEx9GSkpJ9zpo2BGNKfHZRUdF+1D+W24iNGFVSpxAAcxekryK9/cuXLx/FoqpWe85iBlPpvbi4uB0yBE4lHabSvyyLX2AXyhJ42nmYytPsMBcI+80ZWKZeGQsxEqtEkgJ4+3Sm9sh1Gm5SM2EqFfnWpsRSV1dXIYzbI2NWv0AqGiXXl+4Bd1ihs0XZu3fvHhgYGNBXVVUlWDTAyk7p6ekNIyMj7fIwYiVmIwWkNvo2trgHAQEBy+CghW7cuPGLvr6+L3fu3PmSJNBBP8R09erVHwVxEwrgU/AwkqQ00DFT8lamqkEICgqKKy4u1sMU7li6dKnVLvL/Pbe0tLRFaEsidi1+UlB5ng3ctBYsWLBV6GRxFnJ4yjIj7CX36uvrS1NTU+uwEM3ara3Al/gaTl+EPC6Vi/hNRUhHR8dPSt5Rqbu7+3Nr1679rL+//3BBQYHyYJvFd3V1iTNkNRV4RZF2G6TkHZ36+vpG5uXlHcah59Pk5GSbj5AY3y1gi6ACisOk4UlKaJyJrBYnsuTa2trjzc3N7/r7+9N1sYo6OzsfCAN0VEB9GzwGCo0zlnV1dfVOTEzMhn3Xl5eXx1rzIBOMflRAsv8UopxhrRFoT18vL68QHCu/am9vz7FUjglGHyow6xQcHBxjKwgqwKCTRIweKHlnpZhGDfC7LP4CJhgH3QCUxzd/AmboA0kP8zNNcDt+w8ZUvHv37l+tedaSJUueFfrfpwJ0oSVLxLiN0DgjWWxsDxobG79JSUn53haXRafT+QrAOjiFDEoFg05K3tEpduoxg8FweuXKlRlJSUm1toAnpvDwcB55FTJQAdUFYMRMaXFkil34l9zc3K2RkZElV65ceWSPbCz414XxF6kAXWfpdMNwHyNmQge7skNDQ3dOnjy5PzAwMLewsLDLLmEYDJMb5ObmFiXLIeZ6FxzNGOK+IFeyk91f4enTpyNtbW3HIiIiNsHCNCmy7U1zcnKWCTIuEDu/AOn8RKLRMFbJcJ9StjRlBIN94Y40ZmZmboqNja3iScrS8dP1IyaEWt4W+kmYaYVILHA/8GGglbHKdevWqV+FHaYjOGofw811hcfZOV1fW9pxzE1wcXGJlscSq6SA+qZhJfai8nN2wNHtDhb0pt7eXoe9Qcq1lRg3hRvNkLtyytuHfAHlKVOI+UIwQxYaRolramrSmZ8LhLefJIAnRmKVSFUAHbiq8yeqNRpGiWE5XlXKs5WWlZUthu3/SHh+voxVqlKnEEuYRvTPee5czjKjxDCr2bMVnYNF9IO7fRRQAokHxIuPeCig3t4YKcAeUCIYiRrcffjwYUd8fPyHzo6PwuJ4XL9+/QAWrjILOHWmDu5SAWjHa500sBSNZoibUWKGvNnuDOKbNwFPLLytITYjUteAWIuOvNbZptQxxF1ZWXnYGWuCc57TRnjzhMFbGmIyI7MpJPbAdMpEuQzsKdc/hi+jT0tLO+NoE0tTSWsjL9h58vP45qe8YppSAQqBEmaXfAy0MlbJcJ+tXqUMUMMdlpsUIuE78JYVO89mznn7LvmUh8gL+xzKknVS6hmrZLiPETNrr1npmNG3oXsg7LCKaFobx1yzKhKhBE3sFnA+mCFuI4IyBuyWzYjb/MHQh+lFN09SPIxgirxIlxhepeIWiHL41vPBFl90i4MtykOROfVXA4tAT9YJisyJP3tMu4gnA29aB2UY4V4DXg1m/FMH9gMrMSd6jwwe8PxtAPMU6JC/2/wHuyI2cMsNBRIAAAAASUVORK5CYII=);\r\n}\r\n\r\n.uni-audio-button.pause {\r\n background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAABatJREFUaAXVWl1IpFUYnllZGUf3wlz6MXER1ES7s83VUDJw6KpdaSTDwMnYFSK6KNirooHullKQCNzQRjZ/wom1u9ALQ0mT1ktFdEBWXLdibaH1jwmx5zme83W+z2Hm+7bZmc8X3jl/73vO837n/z3j9aSBjo6O8lBNC7gZXAUuBxeCz4FJj8APwTHwCngaPOX1evcRZocAuhAcAt8G74KdEnWoyzpobGYIjfnBn4D/BqeLWBfr9Du1wmtXAZXnQPY9cBj8HNhEe3t7sbW1tfn19fW7m5ubD5aXl7dnZmYeUKipqel8dXV1UUlJyfmysrILFRUV9X6/n8PMSveREQYPYHgdWgsTpW0ZAPDPQ3kC/JJeCUEvLi7+NDg4+EskEvldL0sVD4VCz3Z1db1SW1v7egJj7kD/Coy4l6qelAYAfB0quQ02vno8Hr8/OTkZaWtrmzo4ODhK1Uiycp/P5x0fH28JBAKh3Nxcow3osDdaYcRCMv2kBgD8O1D+BuyTlcTn5+cj7e3t0Y2NjX+SVey0rLS09OzY2Fiwvr4+BN1cqX+A8CqM+E6mTwRnTuTIDAn+FpIC/OHh4V+9vb0fNzQ0jKYbPJtknaybbbAtCYNt35JYZJY5SNgDctj8DFEBfnd3d627u/vT4eHhP8zqTybV0dHxTH9//+f5+fkVsgX2xKuJhtMJAwCeE/Y3sBiPBF9XV/fh0tISK8kY1dTU+BYWFvo0IzgnLlontmkIATyXSq42Ajy7kl8+0+D5ldgm29aGEzFNSIwUEWQyADlc59VSGe/r6/ssU8PmGI75l20TA3LjsoTYiNEgYwjBMu6CPKuIr4/Vph+TasyQzGJkbm7ubaxO1yQEDqVyDKU9pvUe+AhpAZ7rPJbKHyjgBuKyTUwSCzESqyBhAL4+D1PXZZ6Hm9STWCpV/U5DYiEmTe+6xOwRQwiJEAq/pQCPB0VFRdf+7w7LutJJ3LG3t7dvaseOdzGMImoIXVaN8WzjNvDERkzEpnAiFJjP4OvzMhJQBTyYqbjdEDov7+/vf4+6pu0wZQcGBi7arV/JWbAFiN2Lnzcg8COFuGkVFBSo2a70UoYEhC5+OqWgJoAv+mdeXt5bWpat6M7Ozk1tc7vMIfSa0lxdXf1VxZ2ETsGz7sfRoV4sFtMxNtOAF1hAugs6jrn3lxcmDV0VDTBuRrxJaYWujFowltMA40LNa6ArUWugLBgLaYByfXjUHVaTd13UgvEcDTjVRAPodBJE74GKuzW0YHxEA+gxE0TXh4q7NbRgfEgDeIQWRL+Nirs1tGCM0YAVBZZOJxV3a2jBuEIDphVYesxU3EnIY4ETeco+jg71LBinacAUWNxueFSlx4yCTmh0dPRLJ4AoOzIy8oWTNihLbNpxmpin1H2AnrcrFJqdnf0KM901tzFiUoQ94M3GxsYPZHoC94FW9gBJnEYZoa8SBy1hGNNuIWIiNg2PwKwbIPYDdhF9lZqgK6LEpA0fYv3PAHQF94IbCikdrcXFxWdVOtsh/abEpOG4ITGbvBI9EBA3f3qJo9FoUFPIapROX81zTYzEKkgNIQ8s4qwOH2d7PPQS9/T0vKjS2QqJQXqsFYSwxCrSpsmK6yVdi7zx0APmoVuvs7Pz/Wx55+jkHRoa+jonJ+cp4gHdAV+CAcbrjckASsCI0+vcpQGw7h6CVrDwRvMCTS8xvwbLM0Fsy+KZJha+1hCbiYw5oOdCkM86V1UejWBXZmJOsA22pXkeCIOvNAmfmk4MIQWaIYZTwiemYDAY3dracsUTU1IDpBGn95FP9Yac2KfzmVUzgkssHxfCYOGGR2gQvXp0jNG3lOyh+wKosrLykmWMq3q4SYXBth+6laLtEL3hqr8a2AZuFYQhrvizR8pJbAWeKA1j6OFuATeDq8D09hWClc+Jp0ceGHn/5hWWt8C0/N3mX15C4bDnCIuAAAAAAElFTkSuQmCC);\r\n}\r\n\r\n.uni-audio-right {\r\n box-sizing: border-box;\r\n height: 65px;\r\n margin-left: 65px;\r\n padding: 11px 16.5px 13.5px 15px;\r\n overflow: hidden;\r\n}\r\n\r\n.uni-audio-time {\r\n margin-top: 3.5px;\r\n height: 16.5px;\r\n font-size: 12px;\r\n color: #888888;\r\n float: right;\r\n}\r\n\r\n.uni-audio-info {\r\n margin-right: 70px;\r\n overflow: hidden;\r\n}\r\n\r\n.uni-audio-name {\r\n height: 22.5px;\r\n line-height: 22.5px;\r\n margin-bottom: 3.5px;\r\n font-size: 14px;\r\n color: #353535;\r\n overflow: hidden;\r\n white-space: nowrap;\r\n text-overflow: ellipsis;\r\n}\r\n\r\n.uni-audio-author {\r\n height: 14.5px;\r\n line-height: 14.5px;\r\n font-size: 12px;\r\n color: #888888;\r\n overflow: hidden;\r\n white-space: nowrap;\r\n text-overflow: ellipsis;\r\n}\r\n"; + var audio = "uni-audio {\n display: none;\n}\n\nuni-audio[controls] {\n display: inline-block;\n}\n\nuni-audio[hidden] {\n display: none;\n}\n\n.uni-audio-default {\n max-width: 100%;\n min-width: 302px;\n height: 65px;\n background: #fcfcfc;\n border: 1px solid #e0e0e0;\n border-radius: 2.5px;\n display: inline-block;\n overflow: hidden;\n}\n\n.uni-audio-left {\n width: 65px;\n height: 65px;\n float: left;\n background-color: #e6e6e6;\n background-size: 100% 100%;\n background-position: 50% 50%;\n}\n\n.uni-audio-button {\n width: 24px;\n height: 24px;\n margin: 20.5px;\n background-size: cover;\n}\n\n.uni-audio-button.play {\n background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAAB4dJREFUaAXNWg1MlVUYvpcfIRCJ+MnCaOBl8dOcOCEQZ9kmI5cQG5Yb6MifKbMaGVobOtlibTWHDpgpxBUwF07826iFsMkYJhg559JdGiQSkUzSBA0QkZ7n4/u+nXsvwf3jwru99/y/3/N+3znvec97rlbjABofH38GYtaAV4MjwDqwH9gHTBoE3wd3gA3gi+B6rVY7hHR2CKD9wFngs+BHYGuJYziWMqiscwgP8wLvBQ+AHUWURZle1mqhtXQAhLui7xZwPvgFsBENDg7+Drp069at2z09Pf03b978u6mpqZ+dVq1aFRAVFeW/aNGigNDQ0JfDwsISfXx8wowETBT+QpIPLsf0GpuomvrXIgUAPhhizoGXi+II+tq1az/o9fpLFRUVd8S26fJZWVkLN2/enBgTE/PW/PnzF5v0b0P5HSjxp0m9WXFaBQD+NYw6C1bf+vDwcF9DQ4N+/fr19ciPm0m1osLT01N76tSpNaD3PTw8FgpD+TXSoESrUGeWnVIBgM/EiDKwJ0eiPNrS0nJsw4YNNd3d3aOscxSFhIS4V1dXpyckJGRB5jxZ7jDSbVDiW7lslriY1cgVMvjjKErgR0dH/zl06NCuFStWfOdo8HwkZVL2wYMHP3ny5AlNLonPPi5jkSpMfyb9AhjAadMIlsBjrndmZ2fnnThxos9UwEyUMzIynj9y5EgB1gb3ExK/xBuTTSczBQCeC/ZnsDTnCR6f9YMbN25QiNMoOjras7W1tcjb2ztcfijXRKzpwjaaQgBPU0lrI4HntOGbdzZ4AuYzt2/fvm9sbOweyyBiOidjlCr4Y6QAyrTzkqlEx9GSkpJ9zpo2BGNKfHZRUdF+1D+W24iNGFVSpxAAcxekryK9/cuXLx/FoqpWe85iBlPpvbi4uB0yBE4lHabSvyyLX2AXyhJ42nmYytPsMBcI+80ZWKZeGQsxEqtEkgJ4+3Sm9sh1Gm5SM2EqFfnWpsRSV1dXIYzbI2NWv0AqGiXXl+4Bd1ihs0XZu3fvHhgYGNBXVVUlWDTAyk7p6ekNIyMj7fIwYiVmIwWkNvo2trgHAQEBy+CghW7cuPGLvr6+L3fu3PmSJNBBP8R09erVHwVxEwrgU/AwkqQ00DFT8lamqkEICgqKKy4u1sMU7li6dKnVLvL/Pbe0tLRFaEsidi1+UlB5ng3ctBYsWLBV6GRxFnJ4yjIj7CX36uvrS1NTU+uwEM3ara3Al/gaTl+EPC6Vi/hNRUhHR8dPSt5Rqbu7+3Nr1679rL+//3BBQYHyYJvFd3V1iTNkNRV4RZF2G6TkHZ36+vpG5uXlHcah59Pk5GSbj5AY3y1gi6ACisOk4UlKaJyJrBYnsuTa2trjzc3N7/r7+9N1sYo6OzsfCAN0VEB9GzwGCo0zlnV1dfVOTEzMhn3Xl5eXx1rzIBOMflRAsv8UopxhrRFoT18vL68QHCu/am9vz7FUjglGHyow6xQcHBxjKwgqwKCTRIweKHlnpZhGDfC7LP4CJhgH3QCUxzd/AmboA0kP8zNNcDt+w8ZUvHv37l+tedaSJUueFfrfpwJ0oSVLxLiN0DgjWWxsDxobG79JSUn53haXRafT+QrAOjiFDEoFg05K3tEpduoxg8FweuXKlRlJSUm1toAnpvDwcB55FTJQAdUFYMRMaXFkil34l9zc3K2RkZElV65ceWSPbCz414XxF6kAXWfpdMNwHyNmQge7skNDQ3dOnjy5PzAwMLewsLDLLmEYDJMb5ObmFiXLIeZ6FxzNGOK+IFeyk91f4enTpyNtbW3HIiIiNsHCNCmy7U1zcnKWCTIuEDu/AOn8RKLRMFbJcJ9StjRlBIN94Y40ZmZmboqNja3iScrS8dP1IyaEWt4W+kmYaYVILHA/8GGglbHKdevWqV+FHaYjOGofw811hcfZOV1fW9pxzE1wcXGJlscSq6SA+qZhJfai8nN2wNHtDhb0pt7eXoe9Qcq1lRg3hRvNkLtyytuHfAHlKVOI+UIwQxYaRolramrSmZ8LhLefJIAnRmKVSFUAHbiq8yeqNRpGiWE5XlXKs5WWlZUthu3/SHh+voxVqlKnEEuYRvTPee5czjKjxDCr2bMVnYNF9IO7fRRQAokHxIuPeCig3t4YKcAeUCIYiRrcffjwYUd8fPyHzo6PwuJ4XL9+/QAWrjILOHWmDu5SAWjHa500sBSNZoibUWKGvNnuDOKbNwFPLLytITYjUteAWIuOvNbZptQxxF1ZWXnYGWuCc57TRnjzhMFbGmIyI7MpJPbAdMpEuQzsKdc/hi+jT0tLO+NoE0tTSWsjL9h58vP45qe8YppSAQqBEmaXfAy0MlbJcJ+tXqUMUMMdlpsUIuE78JYVO89mznn7LvmUh8gL+xzKknVS6hmrZLiPETNrr1npmNG3oXsg7LCKaFobx1yzKhKhBE3sFnA+mCFuI4IyBuyWzYjb/MHQh+lFN09SPIxgirxIlxhepeIWiHL41vPBFl90i4MtykOROfVXA4tAT9YJisyJP3tMu4gnA29aB2UY4V4DXg1m/FMH9gMrMSd6jwwe8PxtAPMU6JC/2/wHuyI2cMsNBRIAAAAASUVORK5CYII=);\n}\n\n.uni-audio-button.pause {\n background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAABatJREFUaAXVWl1IpFUYnllZGUf3wlz6MXER1ES7s83VUDJw6KpdaSTDwMnYFSK6KNirooHullKQCNzQRjZ/wom1u9ALQ0mT1ktFdEBWXLdibaH1jwmx5zme83W+z2Hm+7bZmc8X3jl/73vO837n/z3j9aSBjo6O8lBNC7gZXAUuBxeCz4FJj8APwTHwCngaPOX1evcRZocAuhAcAt8G74KdEnWoyzpobGYIjfnBn4D/BqeLWBfr9Du1wmtXAZXnQPY9cBj8HNhEe3t7sbW1tfn19fW7m5ubD5aXl7dnZmYeUKipqel8dXV1UUlJyfmysrILFRUV9X6/n8PMSveREQYPYHgdWgsTpW0ZAPDPQ3kC/JJeCUEvLi7+NDg4+EskEvldL0sVD4VCz3Z1db1SW1v7egJj7kD/Coy4l6qelAYAfB0quQ02vno8Hr8/OTkZaWtrmzo4ODhK1Uiycp/P5x0fH28JBAKh3Nxcow3osDdaYcRCMv2kBgD8O1D+BuyTlcTn5+cj7e3t0Y2NjX+SVey0rLS09OzY2Fiwvr4+BN1cqX+A8CqM+E6mTwRnTuTIDAn+FpIC/OHh4V+9vb0fNzQ0jKYbPJtknaybbbAtCYNt35JYZJY5SNgDctj8DFEBfnd3d627u/vT4eHhP8zqTybV0dHxTH9//+f5+fkVsgX2xKuJhtMJAwCeE/Y3sBiPBF9XV/fh0tISK8kY1dTU+BYWFvo0IzgnLlontmkIATyXSq42Ajy7kl8+0+D5ldgm29aGEzFNSIwUEWQyADlc59VSGe/r6/ssU8PmGI75l20TA3LjsoTYiNEgYwjBMu6CPKuIr4/Vph+TasyQzGJkbm7ubaxO1yQEDqVyDKU9pvUe+AhpAZ7rPJbKHyjgBuKyTUwSCzESqyBhAL4+D1PXZZ6Hm9STWCpV/U5DYiEmTe+6xOwRQwiJEAq/pQCPB0VFRdf+7w7LutJJ3LG3t7dvaseOdzGMImoIXVaN8WzjNvDERkzEpnAiFJjP4OvzMhJQBTyYqbjdEDov7+/vf4+6pu0wZQcGBi7arV/JWbAFiN2Lnzcg8COFuGkVFBSo2a70UoYEhC5+OqWgJoAv+mdeXt5bWpat6M7Ozk1tc7vMIfSa0lxdXf1VxZ2ETsGz7sfRoV4sFtMxNtOAF1hAugs6jrn3lxcmDV0VDTBuRrxJaYWujFowltMA40LNa6ArUWugLBgLaYByfXjUHVaTd13UgvEcDTjVRAPodBJE74GKuzW0YHxEA+gxE0TXh4q7NbRgfEgDeIQWRL+Nirs1tGCM0YAVBZZOJxV3a2jBuEIDphVYesxU3EnIY4ETeco+jg71LBinacAUWNxueFSlx4yCTmh0dPRLJ4AoOzIy8oWTNihLbNpxmpin1H2AnrcrFJqdnf0KM901tzFiUoQ94M3GxsYPZHoC94FW9gBJnEYZoa8SBy1hGNNuIWIiNg2PwKwbIPYDdhF9lZqgK6LEpA0fYv3PAHQF94IbCikdrcXFxWdVOtsh/abEpOG4ITGbvBI9EBA3f3qJo9FoUFPIapROX81zTYzEKkgNIQ8s4qwOH2d7PPQS9/T0vKjS2QqJQXqsFYSwxCrSpsmK6yVdi7zx0APmoVuvs7Pz/Wx55+jkHRoa+jonJ+cp4gHdAV+CAcbrjckASsCI0+vcpQGw7h6CVrDwRvMCTS8xvwbLM0Fsy+KZJha+1hCbiYw5oOdCkM86V1UejWBXZmJOsA22pXkeCIOvNAmfmk4MIQWaIYZTwiemYDAY3dracsUTU1IDpBGn95FP9Yac2KfzmVUzgkssHxfCYOGGR2gQvXp0jNG3lOyh+wKosrLykmWMq3q4SYXBth+6laLtEL3hqr8a2AZuFYQhrvizR8pJbAWeKA1j6OFuATeDq8D09hWClc+Jp0ceGHn/5hWWt8C0/N3mX15C4bDnCIuAAAAAAElFTkSuQmCC);\n}\n\n.uni-audio-right {\n box-sizing: border-box;\n height: 65px;\n margin-left: 65px;\n padding: 11px 16.5px 13.5px 15px;\n overflow: hidden;\n}\n\n.uni-audio-time {\n margin-top: 3.5px;\n height: 16.5px;\n font-size: 12px;\n color: #888888;\n float: right;\n}\n\n.uni-audio-info {\n margin-right: 70px;\n overflow: hidden;\n}\n\n.uni-audio-name {\n height: 22.5px;\n line-height: 22.5px;\n margin-bottom: 3.5px;\n font-size: 14px;\n color: #353535;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n\n.uni-audio-author {\n height: 14.5px;\n line-height: 14.5px;\n font-size: 12px;\n color: #888888;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n"; class UniAudio extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-audio", _sfc_main, parentNodeId, nodeJson); } } - var button = "uni-button {\r\n position: relative;\r\n display: block;\r\n margin-left: auto;\r\n margin-right: auto;\r\n padding-left: 14px;\r\n padding-right: 14px;\r\n box-sizing: border-box;\r\n font-size: 18px;\r\n text-align: center;\r\n text-decoration: none;\r\n line-height: 2.55555556;\r\n border-radius: 5px;\r\n -webkit-tap-highlight-color: transparent;\r\n overflow: hidden;\r\n color: #000000;\r\n background-color: #f8f8f8;\r\n cursor: pointer;\r\n}\r\n\r\nuni-button[hidden] {\r\n display: none !important;\r\n}\r\n\r\nuni-button:after {\r\n content: ' ';\r\n width: 200%;\r\n height: 200%;\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n border: 1px solid rgba(0, 0, 0, 0.2);\r\n transform: scale(0.5);\r\n transform-origin: 0 0;\r\n box-sizing: border-box;\r\n border-radius: 10px;\r\n}\r\n\r\nuni-button[native] {\r\n padding-left: 0;\r\n padding-right: 0;\r\n}\r\n\r\nuni-button[native] .uni-button-cover-view-wrapper {\r\n border: inherit;\r\n border-color: inherit;\r\n border-radius: inherit;\r\n background-color: inherit;\r\n}\r\n\r\nuni-button[native] .uni-button-cover-view-inner {\r\n padding-left: 14px;\r\n padding-right: 14px;\r\n}\r\n\r\nuni-button uni-cover-view {\r\n line-height: inherit;\r\n white-space: inherit;\r\n}\r\n\r\nuni-button[type='default'] {\r\n color: #000000;\r\n background-color: #f8f8f8;\r\n}\r\n\r\nuni-button[type='primary'] {\r\n color: #ffffff;\r\n background-color: #007aff;\r\n}\r\n\r\nuni-button[type='warn'] {\r\n color: #ffffff;\r\n background-color: #e64340;\r\n}\r\n\r\nuni-button[disabled] {\r\n color: rgba(255, 255, 255, 0.6);\r\n cursor: not-allowed;\r\n}\r\n\r\nuni-button[disabled][type='default'],\r\nuni-button[disabled]:not([type]) {\r\n color: rgba(0, 0, 0, 0.3);\r\n background-color: #f7f7f7;\r\n}\r\n\r\nuni-button[disabled][type='primary'] {\r\n background-color: rgba(0, 122, 255, 0.6);\r\n}\r\n\r\nuni-button[disabled][type='warn'] {\r\n background-color: #ec8b89;\r\n}\r\n\r\nuni-button[type='primary'][plain] {\r\n color: #007aff;\r\n border: 1px solid #007aff;\r\n background-color: transparent;\r\n}\r\n\r\nuni-button[type='primary'][plain][disabled] {\r\n color: rgba(0, 0, 0, 0.2);\r\n border-color: rgba(0, 0, 0, 0.2);\r\n}\r\n\r\nuni-button[type='primary'][plain]:after {\r\n border-width: 0;\r\n}\r\n\r\nuni-button[type='default'][plain] {\r\n color: #353535;\r\n border: 1px solid #353535;\r\n background-color: transparent;\r\n}\r\n\r\nuni-button[type='default'][plain][disabled] {\r\n color: rgba(0, 0, 0, 0.2);\r\n border-color: rgba(0, 0, 0, 0.2);\r\n}\r\n\r\nuni-button[type='default'][plain]:after {\r\n border-width: 0;\r\n}\r\n\r\nuni-button[plain] {\r\n color: #353535;\r\n border: 1px solid #353535;\r\n background-color: transparent;\r\n}\r\n\r\nuni-button[plain][disabled] {\r\n color: rgba(0, 0, 0, 0.2);\r\n border-color: rgba(0, 0, 0, 0.2);\r\n}\r\n\r\nuni-button[plain]:after {\r\n border-width: 0;\r\n}\r\n\r\nuni-button[plain][native] .uni-button-cover-view-inner {\r\n padding: 0;\r\n}\r\n\r\nuni-button[type='warn'][plain] {\r\n color: #e64340;\r\n border: 1px solid #e64340;\r\n background-color: transparent;\r\n}\r\n\r\nuni-button[type='warn'][plain][disabled] {\r\n color: rgba(0, 0, 0, 0.2);\r\n border-color: rgba(0, 0, 0, 0.2);\r\n}\r\n\r\nuni-button[type='warn'][plain]:after {\r\n border-width: 0;\r\n}\r\n\r\nuni-button[size='mini'] {\r\n display: inline-block;\r\n line-height: 2.3;\r\n font-size: 13px;\r\n padding: 0 1.34em;\r\n}\r\n\r\nuni-button[size='mini'][native] {\r\n padding: 0;\r\n}\r\n\r\nuni-button[size='mini'][native] .uni-button-cover-view-inner {\r\n padding: 0 1.34em;\r\n}\r\n\r\nuni-button[loading]:not([disabled]) {\r\n cursor: progress;\r\n}\r\n\r\nuni-button[loading]:before {\r\n content: ' ';\r\n display: inline-block;\r\n width: 18px;\r\n height: 18px;\r\n vertical-align: middle;\r\n animation: uni-loading 1s steps(12, end) infinite;\r\n background-size: 100%;\r\n}\r\n\r\nuni-button[loading][type='primary'] {\r\n color: rgba(255, 255, 255, 0.6);\r\n background-color: #0062cc;\r\n}\r\n\r\nuni-button[loading][type='primary'][plain] {\r\n color: #007aff;\r\n background-color: transparent;\r\n}\r\n\r\nuni-button[loading][type='default'] {\r\n color: rgba(0, 0, 0, 0.6);\r\n background-color: #dedede;\r\n}\r\n\r\nuni-button[loading][type='default'][plain] {\r\n color: #353535;\r\n background-color: transparent;\r\n}\r\n\r\nuni-button[loading][type='warn'] {\r\n color: rgba(255, 255, 255, 0.6);\r\n background-color: #ce3c39;\r\n}\r\n\r\nuni-button[loading][type='warn'][plain] {\r\n color: #e64340;\r\n background-color: transparent;\r\n}\r\n\r\nuni-button[loading][native]:before {\r\n content: none;\r\n}\r\n\r\n.button-hover {\r\n color: rgba(0, 0, 0, 0.6);\r\n background-color: #dedede;\r\n}\r\n\r\n.button-hover[plain] {\r\n color: rgba(53, 53, 53, 0.6);\r\n border-color: rgba(53, 53, 53, 0.6);\r\n background-color: transparent;\r\n}\r\n\r\n.button-hover[type='primary'] {\r\n color: rgba(255, 255, 255, 0.6);\r\n background-color: #0062cc;\r\n}\r\n\r\n.button-hover[type='primary'][plain] {\r\n color: rgba(26, 173, 25, 0.6);\r\n border-color: rgba(26, 173, 25, 0.6);\r\n background-color: transparent;\r\n}\r\n\r\n.button-hover[type='default'] {\r\n color: rgba(0, 0, 0, 0.6);\r\n background-color: #dedede;\r\n}\r\n\r\n.button-hover[type='default'][plain] {\r\n color: rgba(53, 53, 53, 0.6);\r\n border-color: rgba(53, 53, 53, 0.6);\r\n background-color: transparent;\r\n}\r\n\r\n.button-hover[type='warn'] {\r\n color: rgba(255, 255, 255, 0.6);\r\n background-color: #ce3c39;\r\n}\r\n\r\n.button-hover[type='warn'][plain] {\r\n color: rgba(230, 67, 64, 0.6);\r\n border-color: rgba(230, 67, 64, 0.6);\r\n background-color: transparent;\r\n}\r\n"; + var button = "uni-button {\n position: relative;\n display: block;\n margin-left: auto;\n margin-right: auto;\n padding-left: 14px;\n padding-right: 14px;\n box-sizing: border-box;\n font-size: 18px;\n text-align: center;\n text-decoration: none;\n line-height: 2.55555556;\n border-radius: 5px;\n -webkit-tap-highlight-color: transparent;\n overflow: hidden;\n color: #000000;\n background-color: #f8f8f8;\n cursor: pointer;\n}\n\nuni-button[hidden] {\n display: none !important;\n}\n\nuni-button:after {\n content: ' ';\n width: 200%;\n height: 200%;\n position: absolute;\n top: 0;\n left: 0;\n border: 1px solid rgba(0, 0, 0, 0.2);\n transform: scale(0.5);\n transform-origin: 0 0;\n box-sizing: border-box;\n border-radius: 10px;\n}\n\nuni-button[native] {\n padding-left: 0;\n padding-right: 0;\n}\n\nuni-button[native] .uni-button-cover-view-wrapper {\n border: inherit;\n border-color: inherit;\n border-radius: inherit;\n background-color: inherit;\n}\n\nuni-button[native] .uni-button-cover-view-inner {\n padding-left: 14px;\n padding-right: 14px;\n}\n\nuni-button uni-cover-view {\n line-height: inherit;\n white-space: inherit;\n}\n\nuni-button[type='default'] {\n color: #000000;\n background-color: #f8f8f8;\n}\n\nuni-button[type='primary'] {\n color: #ffffff;\n background-color: #007aff;\n}\n\nuni-button[type='warn'] {\n color: #ffffff;\n background-color: #e64340;\n}\n\nuni-button[disabled] {\n color: rgba(255, 255, 255, 0.6);\n cursor: not-allowed;\n}\n\nuni-button[disabled][type='default'],\nuni-button[disabled]:not([type]) {\n color: rgba(0, 0, 0, 0.3);\n background-color: #f7f7f7;\n}\n\nuni-button[disabled][type='primary'] {\n background-color: rgba(0, 122, 255, 0.6);\n}\n\nuni-button[disabled][type='warn'] {\n background-color: #ec8b89;\n}\n\nuni-button[type='primary'][plain] {\n color: #007aff;\n border: 1px solid #007aff;\n background-color: transparent;\n}\n\nuni-button[type='primary'][plain][disabled] {\n color: rgba(0, 0, 0, 0.2);\n border-color: rgba(0, 0, 0, 0.2);\n}\n\nuni-button[type='primary'][plain]:after {\n border-width: 0;\n}\n\nuni-button[type='default'][plain] {\n color: #353535;\n border: 1px solid #353535;\n background-color: transparent;\n}\n\nuni-button[type='default'][plain][disabled] {\n color: rgba(0, 0, 0, 0.2);\n border-color: rgba(0, 0, 0, 0.2);\n}\n\nuni-button[type='default'][plain]:after {\n border-width: 0;\n}\n\nuni-button[plain] {\n color: #353535;\n border: 1px solid #353535;\n background-color: transparent;\n}\n\nuni-button[plain][disabled] {\n color: rgba(0, 0, 0, 0.2);\n border-color: rgba(0, 0, 0, 0.2);\n}\n\nuni-button[plain]:after {\n border-width: 0;\n}\n\nuni-button[plain][native] .uni-button-cover-view-inner {\n padding: 0;\n}\n\nuni-button[type='warn'][plain] {\n color: #e64340;\n border: 1px solid #e64340;\n background-color: transparent;\n}\n\nuni-button[type='warn'][plain][disabled] {\n color: rgba(0, 0, 0, 0.2);\n border-color: rgba(0, 0, 0, 0.2);\n}\n\nuni-button[type='warn'][plain]:after {\n border-width: 0;\n}\n\nuni-button[size='mini'] {\n display: inline-block;\n line-height: 2.3;\n font-size: 13px;\n padding: 0 1.34em;\n}\n\nuni-button[size='mini'][native] {\n padding: 0;\n}\n\nuni-button[size='mini'][native] .uni-button-cover-view-inner {\n padding: 0 1.34em;\n}\n\nuni-button[loading]:not([disabled]) {\n cursor: progress;\n}\n\nuni-button[loading]:before {\n content: ' ';\n display: inline-block;\n width: 18px;\n height: 18px;\n vertical-align: middle;\n animation: uni-loading 1s steps(12, end) infinite;\n background-size: 100%;\n}\n\nuni-button[loading][type='primary'] {\n color: rgba(255, 255, 255, 0.6);\n background-color: #0062cc;\n}\n\nuni-button[loading][type='primary'][plain] {\n color: #007aff;\n background-color: transparent;\n}\n\nuni-button[loading][type='default'] {\n color: rgba(0, 0, 0, 0.6);\n background-color: #dedede;\n}\n\nuni-button[loading][type='default'][plain] {\n color: #353535;\n background-color: transparent;\n}\n\nuni-button[loading][type='warn'] {\n color: rgba(255, 255, 255, 0.6);\n background-color: #ce3c39;\n}\n\nuni-button[loading][type='warn'][plain] {\n color: #e64340;\n background-color: transparent;\n}\n\nuni-button[loading][native]:before {\n content: none;\n}\n\n.button-hover {\n color: rgba(0, 0, 0, 0.6);\n background-color: #dedede;\n}\n\n.button-hover[plain] {\n color: rgba(53, 53, 53, 0.6);\n border-color: rgba(53, 53, 53, 0.6);\n background-color: transparent;\n}\n\n.button-hover[type='primary'] {\n color: rgba(255, 255, 255, 0.6);\n background-color: #0062cc;\n}\n\n.button-hover[type='primary'][plain] {\n color: rgba(26, 173, 25, 0.6);\n border-color: rgba(26, 173, 25, 0.6);\n background-color: transparent;\n}\n\n.button-hover[type='default'] {\n color: rgba(0, 0, 0, 0.6);\n background-color: #dedede;\n}\n\n.button-hover[type='default'][plain] {\n color: rgba(53, 53, 53, 0.6);\n border-color: rgba(53, 53, 53, 0.6);\n background-color: transparent;\n}\n\n.button-hover[type='warn'] {\n color: rgba(255, 255, 255, 0.6);\n background-color: #ce3c39;\n}\n\n.button-hover[type='warn'][plain] {\n color: rgba(230, 67, 64, 0.6);\n border-color: rgba(230, 67, 64, 0.6);\n background-color: transparent;\n}\n"; class UniButton extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-button", Button, parentNodeId, nodeJson); @@ -14398,13 +14449,13 @@ super(id2, "uni-camera", parentNodeId); } } - var canvas = "uni-canvas {\r\n width: 300px;\r\n height: 150px;\r\n display: block;\r\n position: relative;\r\n}\r\n\r\nuni-canvas > .uni-canvas-canvas {\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n width: 100%;\r\n height: 100%;\r\n}\r\n"; + var canvas = "uni-canvas {\n width: 300px;\n height: 150px;\n display: block;\n position: relative;\n}\n\nuni-canvas > .uni-canvas-canvas {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n}\n"; class UniCanvas extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-canvas", Canvas, parentNodeId, nodeJson, "canvas > div"); } } - var checkbox = "uni-checkbox {\r\n -webkit-tap-highlight-color: transparent;\r\n display: inline-block;\r\n cursor: pointer;\r\n}\r\n\r\nuni-checkbox[hidden] {\r\n display: none;\r\n}\r\n\r\nuni-checkbox[disabled] {\r\n cursor: not-allowed;\r\n}\r\n\r\n.uni-checkbox-wrapper {\r\n display: inline-flex;\r\n align-items: center;\r\n vertical-align: middle;\r\n}\r\n\r\n.uni-checkbox-input {\r\n margin-right: 5px;\r\n -webkit-appearance: none;\r\n appearance: none;\r\n outline: 0;\r\n border: 1px solid #d1d1d1;\r\n background-color: #ffffff;\r\n border-radius: 3px;\r\n width: 22px;\r\n height: 22px;\r\n position: relative;\r\n}\r\n\r\n.uni-checkbox-input svg {\r\n color: #007aff;\r\n font-size: 22px;\r\n position: absolute;\r\n top: 50%;\r\n left: 50%;\r\n transform: translate(-50%, -48%) scale(0.73);\r\n}\r\n\r\nuni-checkbox:not([disabled]) .uni-checkbox-input:hover {\r\n border-color: #007aff;\r\n}\r\n\r\n.uni-checkbox-input.uni-checkbox-input-disabled {\r\n background-color: #e1e1e1;\r\n}\r\n\r\n.uni-checkbox-input.uni-checkbox-input-disabled:before {\r\n color: #adadad;\r\n}\r\n\r\nuni-checkbox-group {\r\n display: block;\r\n}\r\n"; + var checkbox = "uni-checkbox {\n -webkit-tap-highlight-color: transparent;\n display: inline-block;\n cursor: pointer;\n}\n\nuni-checkbox[hidden] {\n display: none;\n}\n\nuni-checkbox[disabled] {\n cursor: not-allowed;\n}\n\n.uni-checkbox-wrapper {\n display: inline-flex;\n align-items: center;\n vertical-align: middle;\n}\n\n.uni-checkbox-input {\n margin-right: 5px;\n -webkit-appearance: none;\n appearance: none;\n outline: 0;\n border: 1px solid #d1d1d1;\n background-color: #ffffff;\n border-radius: 3px;\n width: 22px;\n height: 22px;\n position: relative;\n}\n\n.uni-checkbox-input svg {\n color: #007aff;\n font-size: 22px;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -48%) scale(0.73);\n}\n\nuni-checkbox:not([disabled]) .uni-checkbox-input:hover {\n border-color: #007aff;\n}\n\n.uni-checkbox-input.uni-checkbox-input-disabled {\n background-color: #e1e1e1;\n}\n\n.uni-checkbox-input.uni-checkbox-input-disabled:before {\n color: #adadad;\n}\n\nuni-checkbox-group {\n display: block;\n}\n"; class UniCheckbox extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-checkbox", Checkbox, parentNodeId, nodeJson, ".uni-checkbox-wrapper"); @@ -14413,7 +14464,7 @@ setHolderText(this.$holder, "uni-checkbox-input", text2); } } - var checkboxGroup = "uni-checkbox-group {\r\n display: block;\r\n}\r\n\r\nuni-checkbox-group[hidden] {\r\n display: none;\r\n}\r\n"; + var checkboxGroup = "uni-checkbox-group {\n display: block;\n}\n\nuni-checkbox-group[hidden] {\n display: none;\n}\n"; class UniCheckboxGroup extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-checkbox-group", CheckboxGroup, parentNodeId, nodeJson); @@ -14811,7 +14862,7 @@ super(id2, "uni-cover-view", CoverView, parentNodeId, nodeJson); } } - var editor = ".ql-container {\r\n display: block;\r\n position: relative;\r\n box-sizing: border-box;\r\n -webkit-user-select: text;\r\n user-select: text;\r\n outline: none;\r\n overflow: hidden;\r\n width: 100%;\r\n height: 200px;\r\n min-height: 200px;\r\n}\r\n.ql-container[hidden] {\r\n display: none;\r\n}\r\n.ql-container .ql-editor {\r\n position: relative;\r\n font-size: inherit;\r\n line-height: inherit;\r\n font-family: inherit;\r\n min-height: inherit;\r\n width: 100%;\r\n height: 100%;\r\n padding: 0;\r\n overflow-x: hidden;\r\n overflow-y: auto;\r\n -webkit-tap-highlight-color: transparent;\r\n -webkit-touch-callout: none;\r\n -webkit-overflow-scrolling: touch;\r\n}\r\n.ql-container .ql-editor::-webkit-scrollbar {\r\n width: 0 !important;\r\n}\r\n.ql-container .ql-editor.scroll-disabled {\r\n overflow: hidden;\r\n}\r\n.ql-container .ql-image-overlay {\r\n display: flex;\r\n position: absolute;\r\n box-sizing: border-box;\r\n border: 1px dashed #ccc;\r\n justify-content: center;\r\n align-items: center;\r\n -webkit-user-select: none;\r\n user-select: none;\r\n}\r\n.ql-container .ql-image-overlay .ql-image-size {\r\n position: absolute;\r\n padding: 4px 8px;\r\n text-align: center;\r\n background-color: #fff;\r\n color: #888;\r\n border: 1px solid #ccc;\r\n box-sizing: border-box;\r\n opacity: 0.8;\r\n right: 4px;\r\n top: 4px;\r\n font-size: 12px;\r\n display: inline-block;\r\n width: auto;\r\n}\r\n.ql-container .ql-image-overlay .ql-image-toolbar {\r\n position: relative;\r\n text-align: center;\r\n box-sizing: border-box;\r\n background: #000;\r\n border-radius: 5px;\r\n color: #fff;\r\n font-size: 0;\r\n min-height: 24px;\r\n z-index: 100;\r\n}\r\n.ql-container .ql-image-overlay .ql-image-toolbar span {\r\n display: inline-block;\r\n cursor: pointer;\r\n padding: 5px;\r\n font-size: 12px;\r\n border-right: 1px solid #fff;\r\n}\r\n.ql-container .ql-image-overlay .ql-image-toolbar span:last-child {\r\n border-right: 0;\r\n}\r\n.ql-container .ql-image-overlay .ql-image-toolbar span.triangle-up {\r\n padding: 0;\r\n position: absolute;\r\n top: -12px;\r\n left: 50%;\r\n transform: translatex(-50%);\r\n width: 0;\r\n height: 0;\r\n border-width: 6px;\r\n border-style: solid;\r\n border-color: transparent transparent black transparent;\r\n}\r\n.ql-container .ql-image-overlay .ql-image-handle {\r\n position: absolute;\r\n height: 12px;\r\n width: 12px;\r\n border-radius: 50%;\r\n border: 1px solid #ccc;\r\n box-sizing: border-box;\r\n background: #fff;\r\n}\r\n.ql-container img {\r\n display: inline-block;\r\n max-width: 100%;\r\n}\r\n.ql-clipboard p {\r\n margin: 0;\r\n padding: 0;\r\n}\r\n.ql-editor {\r\n box-sizing: border-box;\r\n height: 100%;\r\n outline: none;\r\n overflow-y: auto;\r\n tab-size: 4;\r\n -moz-tab-size: 4;\r\n text-align: left;\r\n white-space: pre-wrap;\r\n word-wrap: break-word;\r\n}\r\n.ql-editor > * {\r\n cursor: text;\r\n}\r\n.ql-editor p,\r\n.ql-editor ol,\r\n.ql-editor ul,\r\n.ql-editor pre,\r\n.ql-editor blockquote,\r\n.ql-editor h1,\r\n.ql-editor h2,\r\n.ql-editor h3,\r\n.ql-editor h4,\r\n.ql-editor h5,\r\n.ql-editor h6 {\r\n margin: 0;\r\n padding: 0;\r\n counter-reset: list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;\r\n}\r\n.ql-editor ol > li,\r\n.ql-editor ul > li {\r\n list-style-type: none;\r\n}\r\n.ql-editor ul > li::before {\r\n content: '\\2022';\r\n}\r\n.ql-editor ul[data-checked=true],\r\n.ql-editor ul[data-checked=false] {\r\n pointer-events: none;\r\n}\r\n.ql-editor ul[data-checked=true] > li *,\r\n.ql-editor ul[data-checked=false] > li * {\r\n pointer-events: all;\r\n}\r\n.ql-editor ul[data-checked=true] > li::before,\r\n.ql-editor ul[data-checked=false] > li::before {\r\n color: #777;\r\n cursor: pointer;\r\n pointer-events: all;\r\n}\r\n.ql-editor ul[data-checked=true] > li::before {\r\n content: '\\2611';\r\n}\r\n.ql-editor ul[data-checked=false] > li::before {\r\n content: '\\2610';\r\n}\r\n.ql-editor li::before {\r\n display: inline-block;\r\n white-space: nowrap;\r\n width: 2em;\r\n}\r\n.ql-editor ol li {\r\n counter-reset: list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;\r\n counter-increment: list-0;\r\n}\r\n.ql-editor ol li:before {\r\n content: counter(list-0, decimal) '. ';\r\n}\r\n.ql-editor ol li.ql-indent-1 {\r\n counter-increment: list-1;\r\n}\r\n.ql-editor ol li.ql-indent-1:before {\r\n content: counter(list-1, lower-alpha) '. ';\r\n}\r\n.ql-editor ol li.ql-indent-1 {\r\n counter-reset: list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;\r\n}\r\n.ql-editor ol li.ql-indent-2 {\r\n counter-increment: list-2;\r\n}\r\n.ql-editor ol li.ql-indent-2:before {\r\n content: counter(list-2, lower-roman) '. ';\r\n}\r\n.ql-editor ol li.ql-indent-2 {\r\n counter-reset: list-3 list-4 list-5 list-6 list-7 list-8 list-9;\r\n}\r\n.ql-editor ol li.ql-indent-3 {\r\n counter-increment: list-3;\r\n}\r\n.ql-editor ol li.ql-indent-3:before {\r\n content: counter(list-3, decimal) '. ';\r\n}\r\n.ql-editor ol li.ql-indent-3 {\r\n counter-reset: list-4 list-5 list-6 list-7 list-8 list-9;\r\n}\r\n.ql-editor ol li.ql-indent-4 {\r\n counter-increment: list-4;\r\n}\r\n.ql-editor ol li.ql-indent-4:before {\r\n content: counter(list-4, lower-alpha) '. ';\r\n}\r\n.ql-editor ol li.ql-indent-4 {\r\n counter-reset: list-5 list-6 list-7 list-8 list-9;\r\n}\r\n.ql-editor ol li.ql-indent-5 {\r\n counter-increment: list-5;\r\n}\r\n.ql-editor ol li.ql-indent-5:before {\r\n content: counter(list-5, lower-roman) '. ';\r\n}\r\n.ql-editor ol li.ql-indent-5 {\r\n counter-reset: list-6 list-7 list-8 list-9;\r\n}\r\n.ql-editor ol li.ql-indent-6 {\r\n counter-increment: list-6;\r\n}\r\n.ql-editor ol li.ql-indent-6:before {\r\n content: counter(list-6, decimal) '. ';\r\n}\r\n.ql-editor ol li.ql-indent-6 {\r\n counter-reset: list-7 list-8 list-9;\r\n}\r\n.ql-editor ol li.ql-indent-7 {\r\n counter-increment: list-7;\r\n}\r\n.ql-editor ol li.ql-indent-7:before {\r\n content: counter(list-7, lower-alpha) '. ';\r\n}\r\n.ql-editor ol li.ql-indent-7 {\r\n counter-reset: list-8 list-9;\r\n}\r\n.ql-editor ol li.ql-indent-8 {\r\n counter-increment: list-8;\r\n}\r\n.ql-editor ol li.ql-indent-8:before {\r\n content: counter(list-8, lower-roman) '. ';\r\n}\r\n.ql-editor ol li.ql-indent-8 {\r\n counter-reset: list-9;\r\n}\r\n.ql-editor ol li.ql-indent-9 {\r\n counter-increment: list-9;\r\n}\r\n.ql-editor ol li.ql-indent-9:before {\r\n content: counter(list-9, decimal) '. ';\r\n}\r\n.ql-editor .ql-indent-1:not(.ql-direction-rtl) {\r\n padding-left: 2em;\r\n}\r\n.ql-editor li.ql-indent-1:not(.ql-direction-rtl) {\r\n padding-left: 2em;\r\n}\r\n.ql-editor .ql-indent-1.ql-direction-rtl.ql-align-right {\r\n padding-right: 2em;\r\n}\r\n.ql-editor li.ql-indent-1.ql-direction-rtl.ql-align-right {\r\n padding-right: 2em;\r\n}\r\n.ql-editor .ql-indent-2:not(.ql-direction-rtl) {\r\n padding-left: 4em;\r\n}\r\n.ql-editor li.ql-indent-2:not(.ql-direction-rtl) {\r\n padding-left: 4em;\r\n}\r\n.ql-editor .ql-indent-2.ql-direction-rtl.ql-align-right {\r\n padding-right: 4em;\r\n}\r\n.ql-editor li.ql-indent-2.ql-direction-rtl.ql-align-right {\r\n padding-right: 4em;\r\n}\r\n.ql-editor .ql-indent-3:not(.ql-direction-rtl) {\r\n padding-left: 6em;\r\n}\r\n.ql-editor li.ql-indent-3:not(.ql-direction-rtl) {\r\n padding-left: 6em;\r\n}\r\n.ql-editor .ql-indent-3.ql-direction-rtl.ql-align-right {\r\n padding-right: 6em;\r\n}\r\n.ql-editor li.ql-indent-3.ql-direction-rtl.ql-align-right {\r\n padding-right: 6em;\r\n}\r\n.ql-editor .ql-indent-4:not(.ql-direction-rtl) {\r\n padding-left: 8em;\r\n}\r\n.ql-editor li.ql-indent-4:not(.ql-direction-rtl) {\r\n padding-left: 8em;\r\n}\r\n.ql-editor .ql-indent-4.ql-direction-rtl.ql-align-right {\r\n padding-right: 8em;\r\n}\r\n.ql-editor li.ql-indent-4.ql-direction-rtl.ql-align-right {\r\n padding-right: 8em;\r\n}\r\n.ql-editor .ql-indent-5:not(.ql-direction-rtl) {\r\n padding-left: 10em;\r\n}\r\n.ql-editor li.ql-indent-5:not(.ql-direction-rtl) {\r\n padding-left: 10em;\r\n}\r\n.ql-editor .ql-indent-5.ql-direction-rtl.ql-align-right {\r\n padding-right: 10em;\r\n}\r\n.ql-editor li.ql-indent-5.ql-direction-rtl.ql-align-right {\r\n padding-right: 10em;\r\n}\r\n.ql-editor .ql-indent-6:not(.ql-direction-rtl) {\r\n padding-left: 12em;\r\n}\r\n.ql-editor li.ql-indent-6:not(.ql-direction-rtl) {\r\n padding-left: 12em;\r\n}\r\n.ql-editor .ql-indent-6.ql-direction-rtl.ql-align-right {\r\n padding-right: 12em;\r\n}\r\n.ql-editor li.ql-indent-6.ql-direction-rtl.ql-align-right {\r\n padding-right: 12em;\r\n}\r\n.ql-editor .ql-indent-7:not(.ql-direction-rtl) {\r\n padding-left: 14em;\r\n}\r\n.ql-editor li.ql-indent-7:not(.ql-direction-rtl) {\r\n padding-left: 14em;\r\n}\r\n.ql-editor .ql-indent-7.ql-direction-rtl.ql-align-right {\r\n padding-right: 14em;\r\n}\r\n.ql-editor li.ql-indent-7.ql-direction-rtl.ql-align-right {\r\n padding-right: 14em;\r\n}\r\n.ql-editor .ql-indent-8:not(.ql-direction-rtl) {\r\n padding-left: 16em;\r\n}\r\n.ql-editor li.ql-indent-8:not(.ql-direction-rtl) {\r\n padding-left: 16em;\r\n}\r\n.ql-editor .ql-indent-8.ql-direction-rtl.ql-align-right {\r\n padding-right: 16em;\r\n}\r\n.ql-editor li.ql-indent-8.ql-direction-rtl.ql-align-right {\r\n padding-right: 16em;\r\n}\r\n.ql-editor .ql-indent-9:not(.ql-direction-rtl) {\r\n padding-left: 18em;\r\n}\r\n.ql-editor li.ql-indent-9:not(.ql-direction-rtl) {\r\n padding-left: 18em;\r\n}\r\n.ql-editor .ql-indent-9.ql-direction-rtl.ql-align-right {\r\n padding-right: 18em;\r\n}\r\n.ql-editor li.ql-indent-9.ql-direction-rtl.ql-align-right {\r\n padding-right: 18em;\r\n}\r\n.ql-editor .ql-direction-rtl {\r\n direction: rtl;\r\n text-align: inherit;\r\n}\r\n.ql-editor .ql-align-center {\r\n text-align: center;\r\n}\r\n.ql-editor .ql-align-justify {\r\n text-align: justify;\r\n}\r\n.ql-editor .ql-align-right {\r\n text-align: right;\r\n}\r\n.ql-editor.ql-blank::before {\r\n color: rgba(0, 0, 0, 0.6);\r\n content: attr(data-placeholder);\r\n font-style: italic;\r\n pointer-events: none;\r\n position: absolute;\r\n}\r\n.ql-container.ql-disabled .ql-editor ul[data-checked] > li::before {\r\n pointer-events: none;\r\n}\r\n.ql-clipboard {\r\n left: -100000px;\r\n height: 1px;\r\n overflow-y: hidden;\r\n position: absolute;\r\n top: 50%;\r\n}\r\n"; + var editor = ".ql-container {\n display: block;\n position: relative;\n box-sizing: border-box;\n -webkit-user-select: text;\n user-select: text;\n outline: none;\n overflow: hidden;\n width: 100%;\n height: 200px;\n min-height: 200px;\n}\n.ql-container[hidden] {\n display: none;\n}\n.ql-container .ql-editor {\n position: relative;\n font-size: inherit;\n line-height: inherit;\n font-family: inherit;\n min-height: inherit;\n width: 100%;\n height: 100%;\n padding: 0;\n overflow-x: hidden;\n overflow-y: auto;\n -webkit-tap-highlight-color: transparent;\n -webkit-touch-callout: none;\n -webkit-overflow-scrolling: touch;\n}\n.ql-container .ql-editor::-webkit-scrollbar {\n width: 0 !important;\n}\n.ql-container .ql-editor.scroll-disabled {\n overflow: hidden;\n}\n.ql-container .ql-image-overlay {\n display: flex;\n position: absolute;\n box-sizing: border-box;\n border: 1px dashed #ccc;\n justify-content: center;\n align-items: center;\n -webkit-user-select: none;\n user-select: none;\n}\n.ql-container .ql-image-overlay .ql-image-size {\n position: absolute;\n padding: 4px 8px;\n text-align: center;\n background-color: #fff;\n color: #888;\n border: 1px solid #ccc;\n box-sizing: border-box;\n opacity: 0.8;\n right: 4px;\n top: 4px;\n font-size: 12px;\n display: inline-block;\n width: auto;\n}\n.ql-container .ql-image-overlay .ql-image-toolbar {\n position: relative;\n text-align: center;\n box-sizing: border-box;\n background: #000;\n border-radius: 5px;\n color: #fff;\n font-size: 0;\n min-height: 24px;\n z-index: 100;\n}\n.ql-container .ql-image-overlay .ql-image-toolbar span {\n display: inline-block;\n cursor: pointer;\n padding: 5px;\n font-size: 12px;\n border-right: 1px solid #fff;\n}\n.ql-container .ql-image-overlay .ql-image-toolbar span:last-child {\n border-right: 0;\n}\n.ql-container .ql-image-overlay .ql-image-toolbar span.triangle-up {\n padding: 0;\n position: absolute;\n top: -12px;\n left: 50%;\n transform: translatex(-50%);\n width: 0;\n height: 0;\n border-width: 6px;\n border-style: solid;\n border-color: transparent transparent black transparent;\n}\n.ql-container .ql-image-overlay .ql-image-handle {\n position: absolute;\n height: 12px;\n width: 12px;\n border-radius: 50%;\n border: 1px solid #ccc;\n box-sizing: border-box;\n background: #fff;\n}\n.ql-container img {\n display: inline-block;\n max-width: 100%;\n}\n.ql-clipboard p {\n margin: 0;\n padding: 0;\n}\n.ql-editor {\n box-sizing: border-box;\n height: 100%;\n outline: none;\n overflow-y: auto;\n tab-size: 4;\n -moz-tab-size: 4;\n text-align: left;\n white-space: pre-wrap;\n word-wrap: break-word;\n}\n.ql-editor > * {\n cursor: text;\n}\n.ql-editor p,\n.ql-editor ol,\n.ql-editor ul,\n.ql-editor pre,\n.ql-editor blockquote,\n.ql-editor h1,\n.ql-editor h2,\n.ql-editor h3,\n.ql-editor h4,\n.ql-editor h5,\n.ql-editor h6 {\n margin: 0;\n padding: 0;\n counter-reset: list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;\n}\n.ql-editor ol > li,\n.ql-editor ul > li {\n list-style-type: none;\n}\n.ql-editor ul > li::before {\n content: '\\2022';\n}\n.ql-editor ul[data-checked=true],\n.ql-editor ul[data-checked=false] {\n pointer-events: none;\n}\n.ql-editor ul[data-checked=true] > li *,\n.ql-editor ul[data-checked=false] > li * {\n pointer-events: all;\n}\n.ql-editor ul[data-checked=true] > li::before,\n.ql-editor ul[data-checked=false] > li::before {\n color: #777;\n cursor: pointer;\n pointer-events: all;\n}\n.ql-editor ul[data-checked=true] > li::before {\n content: '\\2611';\n}\n.ql-editor ul[data-checked=false] > li::before {\n content: '\\2610';\n}\n.ql-editor li::before {\n display: inline-block;\n white-space: nowrap;\n width: 2em;\n}\n.ql-editor ol li {\n counter-reset: list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;\n counter-increment: list-0;\n}\n.ql-editor ol li:before {\n content: counter(list-0, decimal) '. ';\n}\n.ql-editor ol li.ql-indent-1 {\n counter-increment: list-1;\n}\n.ql-editor ol li.ql-indent-1:before {\n content: counter(list-1, lower-alpha) '. ';\n}\n.ql-editor ol li.ql-indent-1 {\n counter-reset: list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;\n}\n.ql-editor ol li.ql-indent-2 {\n counter-increment: list-2;\n}\n.ql-editor ol li.ql-indent-2:before {\n content: counter(list-2, lower-roman) '. ';\n}\n.ql-editor ol li.ql-indent-2 {\n counter-reset: list-3 list-4 list-5 list-6 list-7 list-8 list-9;\n}\n.ql-editor ol li.ql-indent-3 {\n counter-increment: list-3;\n}\n.ql-editor ol li.ql-indent-3:before {\n content: counter(list-3, decimal) '. ';\n}\n.ql-editor ol li.ql-indent-3 {\n counter-reset: list-4 list-5 list-6 list-7 list-8 list-9;\n}\n.ql-editor ol li.ql-indent-4 {\n counter-increment: list-4;\n}\n.ql-editor ol li.ql-indent-4:before {\n content: counter(list-4, lower-alpha) '. ';\n}\n.ql-editor ol li.ql-indent-4 {\n counter-reset: list-5 list-6 list-7 list-8 list-9;\n}\n.ql-editor ol li.ql-indent-5 {\n counter-increment: list-5;\n}\n.ql-editor ol li.ql-indent-5:before {\n content: counter(list-5, lower-roman) '. ';\n}\n.ql-editor ol li.ql-indent-5 {\n counter-reset: list-6 list-7 list-8 list-9;\n}\n.ql-editor ol li.ql-indent-6 {\n counter-increment: list-6;\n}\n.ql-editor ol li.ql-indent-6:before {\n content: counter(list-6, decimal) '. ';\n}\n.ql-editor ol li.ql-indent-6 {\n counter-reset: list-7 list-8 list-9;\n}\n.ql-editor ol li.ql-indent-7 {\n counter-increment: list-7;\n}\n.ql-editor ol li.ql-indent-7:before {\n content: counter(list-7, lower-alpha) '. ';\n}\n.ql-editor ol li.ql-indent-7 {\n counter-reset: list-8 list-9;\n}\n.ql-editor ol li.ql-indent-8 {\n counter-increment: list-8;\n}\n.ql-editor ol li.ql-indent-8:before {\n content: counter(list-8, lower-roman) '. ';\n}\n.ql-editor ol li.ql-indent-8 {\n counter-reset: list-9;\n}\n.ql-editor ol li.ql-indent-9 {\n counter-increment: list-9;\n}\n.ql-editor ol li.ql-indent-9:before {\n content: counter(list-9, decimal) '. ';\n}\n.ql-editor .ql-indent-1:not(.ql-direction-rtl) {\n padding-left: 2em;\n}\n.ql-editor li.ql-indent-1:not(.ql-direction-rtl) {\n padding-left: 2em;\n}\n.ql-editor .ql-indent-1.ql-direction-rtl.ql-align-right {\n padding-right: 2em;\n}\n.ql-editor li.ql-indent-1.ql-direction-rtl.ql-align-right {\n padding-right: 2em;\n}\n.ql-editor .ql-indent-2:not(.ql-direction-rtl) {\n padding-left: 4em;\n}\n.ql-editor li.ql-indent-2:not(.ql-direction-rtl) {\n padding-left: 4em;\n}\n.ql-editor .ql-indent-2.ql-direction-rtl.ql-align-right {\n padding-right: 4em;\n}\n.ql-editor li.ql-indent-2.ql-direction-rtl.ql-align-right {\n padding-right: 4em;\n}\n.ql-editor .ql-indent-3:not(.ql-direction-rtl) {\n padding-left: 6em;\n}\n.ql-editor li.ql-indent-3:not(.ql-direction-rtl) {\n padding-left: 6em;\n}\n.ql-editor .ql-indent-3.ql-direction-rtl.ql-align-right {\n padding-right: 6em;\n}\n.ql-editor li.ql-indent-3.ql-direction-rtl.ql-align-right {\n padding-right: 6em;\n}\n.ql-editor .ql-indent-4:not(.ql-direction-rtl) {\n padding-left: 8em;\n}\n.ql-editor li.ql-indent-4:not(.ql-direction-rtl) {\n padding-left: 8em;\n}\n.ql-editor .ql-indent-4.ql-direction-rtl.ql-align-right {\n padding-right: 8em;\n}\n.ql-editor li.ql-indent-4.ql-direction-rtl.ql-align-right {\n padding-right: 8em;\n}\n.ql-editor .ql-indent-5:not(.ql-direction-rtl) {\n padding-left: 10em;\n}\n.ql-editor li.ql-indent-5:not(.ql-direction-rtl) {\n padding-left: 10em;\n}\n.ql-editor .ql-indent-5.ql-direction-rtl.ql-align-right {\n padding-right: 10em;\n}\n.ql-editor li.ql-indent-5.ql-direction-rtl.ql-align-right {\n padding-right: 10em;\n}\n.ql-editor .ql-indent-6:not(.ql-direction-rtl) {\n padding-left: 12em;\n}\n.ql-editor li.ql-indent-6:not(.ql-direction-rtl) {\n padding-left: 12em;\n}\n.ql-editor .ql-indent-6.ql-direction-rtl.ql-align-right {\n padding-right: 12em;\n}\n.ql-editor li.ql-indent-6.ql-direction-rtl.ql-align-right {\n padding-right: 12em;\n}\n.ql-editor .ql-indent-7:not(.ql-direction-rtl) {\n padding-left: 14em;\n}\n.ql-editor li.ql-indent-7:not(.ql-direction-rtl) {\n padding-left: 14em;\n}\n.ql-editor .ql-indent-7.ql-direction-rtl.ql-align-right {\n padding-right: 14em;\n}\n.ql-editor li.ql-indent-7.ql-direction-rtl.ql-align-right {\n padding-right: 14em;\n}\n.ql-editor .ql-indent-8:not(.ql-direction-rtl) {\n padding-left: 16em;\n}\n.ql-editor li.ql-indent-8:not(.ql-direction-rtl) {\n padding-left: 16em;\n}\n.ql-editor .ql-indent-8.ql-direction-rtl.ql-align-right {\n padding-right: 16em;\n}\n.ql-editor li.ql-indent-8.ql-direction-rtl.ql-align-right {\n padding-right: 16em;\n}\n.ql-editor .ql-indent-9:not(.ql-direction-rtl) {\n padding-left: 18em;\n}\n.ql-editor li.ql-indent-9:not(.ql-direction-rtl) {\n padding-left: 18em;\n}\n.ql-editor .ql-indent-9.ql-direction-rtl.ql-align-right {\n padding-right: 18em;\n}\n.ql-editor li.ql-indent-9.ql-direction-rtl.ql-align-right {\n padding-right: 18em;\n}\n.ql-editor .ql-direction-rtl {\n direction: rtl;\n text-align: inherit;\n}\n.ql-editor .ql-align-center {\n text-align: center;\n}\n.ql-editor .ql-align-justify {\n text-align: justify;\n}\n.ql-editor .ql-align-right {\n text-align: right;\n}\n.ql-editor.ql-blank::before {\n color: rgba(0, 0, 0, 0.6);\n content: attr(data-placeholder);\n font-style: italic;\n pointer-events: none;\n position: absolute;\n}\n.ql-container.ql-disabled .ql-editor ul[data-checked] > li::before {\n pointer-events: none;\n}\n.ql-clipboard {\n left: -100000px;\n height: 1px;\n overflow-y: hidden;\n position: absolute;\n top: 50%;\n}\n"; class UniEditor extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-editor", Editor, parentNodeId, nodeJson); @@ -14828,25 +14879,25 @@ super(id2, "uni-functional-page-navigator", parentNodeId); } } - var icon = "uni-icon {\r\n display: inline-block;\r\n font-size: 0;\r\n box-sizing: border-box;\r\n}\r\n\r\nuni-icon[hidden] {\r\n display: none;\r\n}\r\n"; + var icon = "uni-icon {\n display: inline-block;\n font-size: 0;\n box-sizing: border-box;\n}\n\nuni-icon[hidden] {\n display: none;\n}\n"; class UniIcon extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-icon", Icon, parentNodeId, nodeJson); } } - var image = "uni-image {\r\n width: 320px;\r\n height: 240px;\r\n display: inline-block;\r\n overflow: hidden;\r\n position: relative;\r\n}\r\n\r\nuni-image[hidden] {\r\n display: none;\r\n}\r\n\r\nuni-image > div {\r\n width: 100%;\r\n height: 100%;\r\n}\r\n\r\nuni-image > img {\r\n -webkit-touch-callout: none;\r\n -webkit-user-select: none;\r\n user-select: none;\r\n display: block;\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n width: 100%;\r\n height: 100%;\r\n opacity: 0;\r\n}\r\n\r\nuni-image > .uni-image-will-change {\r\n will-change: transform;\r\n}\r\n"; + var image = "uni-image {\n width: 320px;\n height: 240px;\n display: inline-block;\n overflow: hidden;\n position: relative;\n}\n\nuni-image[hidden] {\n display: none;\n}\n\nuni-image > div {\n width: 100%;\n height: 100%;\n}\n\nuni-image > img {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n user-select: none;\n display: block;\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n opacity: 0;\n}\n\nuni-image > .uni-image-will-change {\n will-change: transform;\n}\n"; class UniImage extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-image", Image$1, parentNodeId, nodeJson); } } - var input = "uni-input {\r\n display: block;\r\n font-size: 16px;\r\n line-height: 1.4em;\r\n height: 1.4em;\r\n min-height: 1.4em;\r\n overflow: hidden;\r\n}\r\n\r\nuni-input[hidden] {\r\n display: none;\r\n}\r\n\r\n.uni-input-wrapper,\r\n.uni-input-placeholder,\r\n.uni-input-form,\r\n.uni-input-input {\r\n outline: none;\r\n border: none;\r\n padding: 0;\r\n margin: 0;\r\n text-decoration: inherit;\r\n}\r\n\r\n.uni-input-wrapper,\r\n.uni-input-form {\r\n display: flex;\r\n position: relative;\r\n width: 100%;\r\n height: 100%;\r\n flex-direction: column;\r\n justify-content: center;\r\n}\r\n\r\n.uni-input-placeholder,\r\n.uni-input-input {\r\n width: 100%;\r\n}\r\n\r\n.uni-input-placeholder {\r\n position: absolute;\r\n top: auto !important;\r\n left: 0;\r\n color: gray;\r\n overflow: hidden;\r\n text-overflow: clip;\r\n white-space: pre;\r\n word-break: keep-all;\r\n pointer-events: none;\r\n line-height: inherit;\r\n}\r\n\r\n.uni-input-input {\r\n position: relative;\r\n display: block;\r\n height: 100%;\r\n background: none;\r\n color: inherit;\r\n opacity: 1;\r\n font: inherit;\r\n line-height: inherit;\r\n letter-spacing: inherit;\r\n text-align: inherit;\r\n text-indent: inherit;\r\n text-transform: inherit;\r\n text-shadow: inherit;\r\n}\r\n\r\n.uni-input-input[type='search']::-webkit-search-cancel-button {\r\n display: none;\r\n}\r\n\r\n.uni-input-input::-webkit-outer-spin-button,\r\n.uni-input-input::-webkit-inner-spin-button {\r\n -webkit-appearance: none;\r\n appearance: none;\r\n margin: 0;\r\n}\r\n\r\n.uni-input-input[type='number'] {\r\n -moz-appearance: textfield;\r\n}\r\n\r\n.uni-input-input:disabled {\r\n /* \u7528\u4E8E\u91CD\u7F6EiOS14\u4EE5\u4E0B\u7981\u7528\u72B6\u6001\u6587\u5B57\u989C\u8272 */\r\n -webkit-text-fill-color: currentcolor;\r\n}\r\n"; + var input = "uni-input {\n display: block;\n font-size: 16px;\n line-height: 1.4em;\n height: 1.4em;\n min-height: 1.4em;\n overflow: hidden;\n}\n\nuni-input[hidden] {\n display: none;\n}\n\n.uni-input-wrapper,\n.uni-input-placeholder,\n.uni-input-form,\n.uni-input-input {\n outline: none;\n border: none;\n padding: 0;\n margin: 0;\n text-decoration: inherit;\n}\n\n.uni-input-wrapper,\n.uni-input-form {\n display: flex;\n position: relative;\n width: 100%;\n height: 100%;\n flex-direction: column;\n justify-content: center;\n}\n\n.uni-input-placeholder,\n.uni-input-input {\n width: 100%;\n}\n\n.uni-input-placeholder {\n position: absolute;\n top: auto !important;\n left: 0;\n color: gray;\n overflow: hidden;\n text-overflow: clip;\n white-space: pre;\n word-break: keep-all;\n pointer-events: none;\n line-height: inherit;\n}\n\n.uni-input-input {\n position: relative;\n display: block;\n height: 100%;\n background: none;\n color: inherit;\n opacity: 1;\n font: inherit;\n line-height: inherit;\n letter-spacing: inherit;\n text-align: inherit;\n text-indent: inherit;\n text-transform: inherit;\n text-shadow: inherit;\n}\n\n.uni-input-input[type='search']::-webkit-search-cancel-button {\n display: none;\n}\n\n.uni-input-input::-webkit-outer-spin-button,\n.uni-input-input::-webkit-inner-spin-button {\n -webkit-appearance: none;\n appearance: none;\n margin: 0;\n}\n\n.uni-input-input[type='number'] {\n -moz-appearance: textfield;\n}\n\n.uni-input-input:disabled {\n /* \u7528\u4E8E\u91CD\u7F6EiOS14\u4EE5\u4E0B\u7981\u7528\u72B6\u6001\u6587\u5B57\u989C\u8272 */\n -webkit-text-fill-color: currentcolor;\n}\n"; class UniInput extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-input", Input, parentNodeId, nodeJson); } } - var label = ".uni-label-pointer {\r\n cursor: pointer;\r\n}\r\n"; + var label = ".uni-label-pointer {\n cursor: pointer;\n}\n"; class UniLabel extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-label", Label, parentNodeId, nodeJson); @@ -14870,19 +14921,19 @@ super(id2, "uni-map", Map$1, parentNodeId, nodeJson); } } - var movableArea = "uni-movable-area {\r\n display: block;\r\n position: relative;\r\n width: 10px;\r\n height: 10px;\r\n}\r\n\r\nuni-movable-area[hidden] {\r\n display: none;\r\n}\r\n"; + var movableArea = "uni-movable-area {\n display: block;\n position: relative;\n width: 10px;\n height: 10px;\n}\n\nuni-movable-area[hidden] {\n display: none;\n}\n"; class UniMovableArea extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-movable-area", MovableArea, parentNodeId, nodeJson); } } - var movableView = "uni-movable-view {\r\n display: inline-block;\r\n width: 10px;\r\n height: 10px;\r\n top: 0px;\r\n left: 0px;\r\n position: absolute;\r\n cursor: grab;\r\n}\r\n\r\nuni-movable-view[hidden] {\r\n display: none;\r\n}\r\n"; + var movableView = "uni-movable-view {\n display: inline-block;\n width: 10px;\n height: 10px;\n top: 0px;\n left: 0px;\n position: absolute;\n cursor: grab;\n}\n\nuni-movable-view[hidden] {\n display: none;\n}\n"; class UniMovableView extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-movable-view", MovableView, parentNodeId, nodeJson); } } - var navigator$1 = "uni-navigator {\r\n height: auto;\r\n width: auto;\r\n display: block;\r\n cursor: pointer;\r\n}\r\n\r\nuni-navigator[hidden] {\r\n display: none;\r\n}\r\n\r\n.navigator-hover {\r\n background-color: rgba(0, 0, 0, 0.1);\r\n opacity: 0.7;\r\n}\r\n"; + var navigator$1 = "uni-navigator {\n height: auto;\n width: auto;\n display: block;\n cursor: pointer;\n}\n\nuni-navigator[hidden] {\n display: none;\n}\n\n.navigator-hover {\n background-color: rgba(0, 0, 0, 0.1);\n opacity: 0.7;\n}\n"; class UniNavigator extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-navigator", Navigator, parentNodeId, nodeJson); @@ -14906,25 +14957,25 @@ super(id2, "uni-picker", Picker, parentNodeId, nodeJson); } } - var pickerView = "uni-picker-view {\r\n display: block;\r\n}\r\n\r\n.uni-picker-view-wrapper {\r\n display: flex;\r\n position: relative;\r\n overflow: hidden;\r\n height: 100%;\r\n}\r\n\r\nuni-picker-view[hidden] {\r\n display: none;\r\n}\r\n"; + var pickerView = "uni-picker-view {\n display: block;\n}\n\n.uni-picker-view-wrapper {\n display: flex;\n position: relative;\n overflow: hidden;\n height: 100%;\n}\n\nuni-picker-view[hidden] {\n display: none;\n}\n"; class UniPickerView extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-picker-view", PickerView, parentNodeId, nodeJson, ".uni-picker-view-wrapper"); } } - var pickerViewColumn = "uni-picker-view-column {\r\n flex: 1;\r\n position: relative;\r\n height: 100%;\r\n overflow: hidden;\r\n}\r\n\r\nuni-picker-view-column[hidden] {\r\n display: none;\r\n}\r\n\r\n.uni-picker-view-group {\r\n height: 100%;\r\n overflow: hidden;\r\n}\r\n\r\n.uni-picker-view-mask {\r\n transform: translateZ(0);\r\n}\r\n\r\n.uni-picker-view-indicator,\r\n.uni-picker-view-mask {\r\n position: absolute;\r\n left: 0;\r\n width: 100%;\r\n z-index: 3;\r\n pointer-events: none;\r\n}\r\n\r\n.uni-picker-view-mask {\r\n top: 0;\r\n height: 100%;\r\n margin: 0 auto;\r\n background: linear-gradient(\r\n 180deg,\r\n hsla(0, 0%, 100%, 0.95),\r\n hsla(0, 0%, 100%, 0.6)\r\n ),\r\n linear-gradient(0deg, hsla(0, 0%, 100%, 0.95), hsla(0, 0%, 100%, 0.6));\r\n background-position: top, bottom;\r\n background-size: 100% 102px;\r\n background-repeat: no-repeat;\r\n}\r\n\r\n.uni-picker-view-indicator {\r\n height: 34px;\r\n /* top: 102px; */\r\n top: 50%;\r\n transform: translateY(-50%);\r\n}\r\n\r\n.uni-picker-view-content {\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n width: 100%;\r\n will-change: transform;\r\n padding: 102px 0;\r\n cursor: pointer;\r\n}\r\n\r\n.uni-picker-view-content > * {\r\n height: 34px;\r\n overflow: hidden;\r\n}\r\n\r\n.uni-picker-view-indicator:after,\r\n.uni-picker-view-indicator:before {\r\n content: ' ';\r\n position: absolute;\r\n left: 0;\r\n right: 0;\r\n height: 1px;\r\n color: #e5e5e5;\r\n}\r\n\r\n.uni-picker-view-indicator:before {\r\n top: 0;\r\n border-top: 1px solid #e5e5e5;\r\n transform-origin: 0 0;\r\n transform: scaleY(0.5);\r\n}\r\n\r\n.uni-picker-view-indicator:after {\r\n bottom: 0;\r\n border-bottom: 1px solid #e5e5e5;\r\n transform-origin: 0 100%;\r\n transform: scaleY(0.5);\r\n}\r\n\r\n.uni-picker-view-indicator:after,\r\n.uni-picker-view-indicator:before {\r\n content: ' ';\r\n position: absolute;\r\n left: 0;\r\n right: 0;\r\n height: 1px;\r\n color: #e5e5e5;\r\n}\r\n"; + var pickerViewColumn = "uni-picker-view-column {\n flex: 1;\n position: relative;\n height: 100%;\n overflow: hidden;\n}\n\nuni-picker-view-column[hidden] {\n display: none;\n}\n\n.uni-picker-view-group {\n height: 100%;\n overflow: hidden;\n}\n\n.uni-picker-view-mask {\n transform: translateZ(0);\n}\n\n.uni-picker-view-indicator,\n.uni-picker-view-mask {\n position: absolute;\n left: 0;\n width: 100%;\n z-index: 3;\n pointer-events: none;\n}\n\n.uni-picker-view-mask {\n top: 0;\n height: 100%;\n margin: 0 auto;\n background: linear-gradient(\n 180deg,\n hsla(0, 0%, 100%, 0.95),\n hsla(0, 0%, 100%, 0.6)\n ),\n linear-gradient(0deg, hsla(0, 0%, 100%, 0.95), hsla(0, 0%, 100%, 0.6));\n background-position: top, bottom;\n background-size: 100% 102px;\n background-repeat: no-repeat;\n}\n\n.uni-picker-view-indicator {\n height: 34px;\n /* top: 102px; */\n top: 50%;\n transform: translateY(-50%);\n}\n\n.uni-picker-view-content {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n will-change: transform;\n padding: 102px 0;\n cursor: pointer;\n}\n\n.uni-picker-view-content > * {\n height: 34px;\n overflow: hidden;\n}\n\n.uni-picker-view-indicator:after,\n.uni-picker-view-indicator:before {\n content: ' ';\n position: absolute;\n left: 0;\n right: 0;\n height: 1px;\n color: #e5e5e5;\n}\n\n.uni-picker-view-indicator:before {\n top: 0;\n border-top: 1px solid #e5e5e5;\n transform-origin: 0 0;\n transform: scaleY(0.5);\n}\n\n.uni-picker-view-indicator:after {\n bottom: 0;\n border-bottom: 1px solid #e5e5e5;\n transform-origin: 0 100%;\n transform: scaleY(0.5);\n}\n\n.uni-picker-view-indicator:after,\n.uni-picker-view-indicator:before {\n content: ' ';\n position: absolute;\n left: 0;\n right: 0;\n height: 1px;\n color: #e5e5e5;\n}\n"; class UniPickerViewColumn extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-picker-view-column", PickerViewColumn, parentNodeId, nodeJson, ".uni-picker-view-content"); } } - var progress = "uni-progress {\r\n display: flex;\r\n align-items: center;\r\n}\r\n\r\nuni-progress[hidden] {\r\n display: none;\r\n}\r\n\r\n.uni-progress-bar {\r\n flex: 1;\r\n}\r\n\r\n.uni-progress-inner-bar {\r\n width: 0;\r\n height: 100%;\r\n}\r\n\r\n.uni-progress-info {\r\n margin-top: 0;\r\n margin-bottom: 0;\r\n min-width: 2em;\r\n margin-left: 15px;\r\n font-size: 16px;\r\n}\r\n"; + var progress = "uni-progress {\n display: flex;\n align-items: center;\n}\n\nuni-progress[hidden] {\n display: none;\n}\n\n.uni-progress-bar {\n flex: 1;\n}\n\n.uni-progress-inner-bar {\n width: 0;\n height: 100%;\n}\n\n.uni-progress-info {\n margin-top: 0;\n margin-bottom: 0;\n min-width: 2em;\n margin-left: 15px;\n font-size: 16px;\n}\n"; class UniProgress extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-progress", Progress, parentNodeId, nodeJson); } } - var radio = "uni-radio {\r\n -webkit-tap-highlight-color: transparent;\r\n display: inline-block;\r\n cursor: pointer;\r\n}\r\n\r\nuni-radio[hidden] {\r\n display: none;\r\n}\r\n\r\nuni-radio[disabled] {\r\n cursor: not-allowed;\r\n}\r\n\r\n.uni-radio-wrapper {\r\n display: inline-flex;\r\n align-items: center;\r\n vertical-align: middle;\r\n}\r\n\r\n.uni-radio-input {\r\n -webkit-appearance: none;\r\n appearance: none;\r\n margin-right: 5px;\r\n outline: 0;\r\n border: 1px solid #d1d1d1;\r\n background-color: #ffffff;\r\n border-radius: 50%;\r\n width: 22px;\r\n height: 22px;\r\n position: relative;\r\n}\r\n\r\nuni-radio:not([disabled]) .uni-radio-input:hover {\r\n border-color: #007aff;\r\n}\r\n\r\n.uni-radio-input svg {\r\n color: #ffffff;\r\n font-size: 18px;\r\n position: absolute;\r\n top: 50%;\r\n left: 50%;\r\n transform: translate(-50%, -48%) scale(0.73);\r\n}\r\n\r\n.uni-radio-input.uni-radio-input-disabled {\r\n background-color: #e1e1e1;\r\n border-color: #d1d1d1;\r\n}\r\n\r\n.uni-radio-input.uni-radio-input-disabled:before {\r\n color: #adadad;\r\n}\r\n"; + var radio = "uni-radio {\n -webkit-tap-highlight-color: transparent;\n display: inline-block;\n cursor: pointer;\n}\n\nuni-radio[hidden] {\n display: none;\n}\n\nuni-radio[disabled] {\n cursor: not-allowed;\n}\n\n.uni-radio-wrapper {\n display: inline-flex;\n align-items: center;\n vertical-align: middle;\n}\n\n.uni-radio-input {\n -webkit-appearance: none;\n appearance: none;\n margin-right: 5px;\n outline: 0;\n border: 1px solid #d1d1d1;\n background-color: #ffffff;\n border-radius: 50%;\n width: 22px;\n height: 22px;\n position: relative;\n}\n\nuni-radio:not([disabled]) .uni-radio-input:hover {\n border-color: #007aff;\n}\n\n.uni-radio-input svg {\n color: #ffffff;\n font-size: 18px;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -48%) scale(0.73);\n}\n\n.uni-radio-input.uni-radio-input-disabled {\n background-color: #e1e1e1;\n border-color: #d1d1d1;\n}\n\n.uni-radio-input.uni-radio-input-disabled:before {\n color: #adadad;\n}\n"; class UniRadio extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-radio", Radio, parentNodeId, nodeJson, ".uni-radio-wrapper"); @@ -14933,7 +14984,7 @@ setHolderText(this.$holder, "uni-radio-input", text2); } } - var radioGroup = "uni-radio-group {\r\n display: block;\r\n}\r\nuni-radio-group[hidden] {\r\n display: none;\r\n}\r\n"; + var radioGroup = "uni-radio-group {\n display: block;\n}\nuni-radio-group[hidden] {\n display: none;\n}\n"; class UniRadioGroup extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-radio-group", RadioGroup, parentNodeId, nodeJson); @@ -14945,7 +14996,7 @@ super(id2, "uni-rich-text", RichText, parentNodeId, nodeJson); } } - var scrollView = "uni-scroll-view {\r\n display: block;\r\n width: 100%;\r\n}\r\n\r\nuni-scroll-view[hidden] {\r\n display: none;\r\n}\r\n\r\n.uni-scroll-view {\r\n position: relative;\r\n -webkit-overflow-scrolling: touch;\r\n width: 100%;\r\n /* display: flex; \u65F6\u5728\u5B89\u5353\u4E0B\u4F1A\u5BFC\u81F4scrollWidth\u548CoffsetWidth\u4E00\u6837 */\r\n height: 100%;\r\n max-height: inherit;\r\n}\r\n\r\n.uni-scroll-view-content {\r\n width: 100%;\r\n height: 100%;\r\n}\r\n\r\n.uni-scroll-view-refresher {\r\n position: relative;\r\n overflow: hidden;\r\n}\r\n\r\n.uni-scroll-view-refresh {\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n right: 0;\r\n bottom: 0;\r\n display: flex;\r\n flex-direction: row;\r\n justify-content: center;\r\n align-items: center;\r\n}\r\n\r\n.uni-scroll-view-refresh-inner {\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n line-height: 0;\r\n width: 40px;\r\n height: 40px;\r\n border-radius: 50%;\r\n background-color: #fff;\r\n box-shadow: 0 1px 6px rgba(0, 0, 0, 0.117647),\r\n 0 1px 4px rgba(0, 0, 0, 0.117647);\r\n}\r\n\r\n.uni-scroll-view-refresh__spinner {\r\n transform-origin: center center;\r\n animation: uni-scroll-view-refresh-rotate 2s linear infinite;\r\n}\r\n\r\n.uni-scroll-view-refresh__spinner > circle {\r\n stroke: currentColor;\r\n stroke-linecap: round;\r\n animation: uni-scroll-view-refresh-dash 2s linear infinite;\r\n}\r\n\r\n@keyframes uni-scroll-view-refresh-rotate {\r\n 0% {\r\n transform: rotate(0deg);\r\n }\r\n\r\n 100% {\r\n transform: rotate(360deg);\r\n }\r\n}\r\n\r\n@keyframes uni-scroll-view-refresh-dash {\r\n 0% {\r\n stroke-dasharray: 1, 200;\r\n stroke-dashoffset: 0;\r\n }\r\n\r\n 50% {\r\n stroke-dasharray: 89, 200;\r\n stroke-dashoffset: -35px;\r\n }\r\n\r\n 100% {\r\n stroke-dasharray: 89, 200;\r\n stroke-dashoffset: -124px;\r\n }\r\n}\r\n"; + var scrollView = "uni-scroll-view {\n display: block;\n width: 100%;\n}\n\nuni-scroll-view[hidden] {\n display: none;\n}\n\n.uni-scroll-view {\n position: relative;\n -webkit-overflow-scrolling: touch;\n width: 100%;\n /* display: flex; \u65F6\u5728\u5B89\u5353\u4E0B\u4F1A\u5BFC\u81F4scrollWidth\u548CoffsetWidth\u4E00\u6837 */\n height: 100%;\n max-height: inherit;\n}\n\n.uni-scroll-view-content {\n width: 100%;\n height: 100%;\n}\n\n.uni-scroll-view-refresher {\n position: relative;\n overflow: hidden;\n}\n\n.uni-scroll-view-refresh {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n display: flex;\n flex-direction: row;\n justify-content: center;\n align-items: center;\n}\n\n.uni-scroll-view-refresh-inner {\n display: flex;\n align-items: center;\n justify-content: center;\n line-height: 0;\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background-color: #fff;\n box-shadow: 0 1px 6px rgba(0, 0, 0, 0.117647),\n 0 1px 4px rgba(0, 0, 0, 0.117647);\n}\n\n.uni-scroll-view-refresh__spinner {\n transform-origin: center center;\n animation: uni-scroll-view-refresh-rotate 2s linear infinite;\n}\n\n.uni-scroll-view-refresh__spinner > circle {\n stroke: currentColor;\n stroke-linecap: round;\n animation: uni-scroll-view-refresh-dash 2s linear infinite;\n}\n\n@keyframes uni-scroll-view-refresh-rotate {\n 0% {\n transform: rotate(0deg);\n }\n\n 100% {\n transform: rotate(360deg);\n }\n}\n\n@keyframes uni-scroll-view-refresh-dash {\n 0% {\n stroke-dasharray: 1, 200;\n stroke-dashoffset: 0;\n }\n\n 50% {\n stroke-dasharray: 89, 200;\n stroke-dashoffset: -35px;\n }\n\n 100% {\n stroke-dasharray: 89, 200;\n stroke-dashoffset: -124px;\n }\n}\n"; class UniScrollView extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-scroll-view", ScrollView, parentNodeId, nodeJson, ".uni-scroll-view-content"); @@ -14954,37 +15005,37 @@ setHolderText(this.$holder, "uni-scroll-view-refresher", text2); } } - var slider = "uni-slider {\r\n margin: 10px 18px;\r\n padding: 0;\r\n display: block;\r\n}\r\n\r\nuni-slider[hidden] {\r\n display: none;\r\n}\r\n\r\nuni-slider .uni-slider-wrapper {\r\n display: flex;\r\n align-items: center;\r\n min-height: 16px;\r\n}\r\n\r\nuni-slider .uni-slider-tap-area {\r\n flex: 1;\r\n padding: 8px 0;\r\n}\r\n\r\nuni-slider .uni-slider-handle-wrapper {\r\n position: relative;\r\n height: 2px;\r\n border-radius: 5px;\r\n background-color: #e9e9e9;\r\n cursor: pointer;\r\n transition: background-color 0.3s ease;\r\n -webkit-tap-highlight-color: transparent;\r\n}\r\n\r\nuni-slider .uni-slider-track {\r\n height: 100%;\r\n border-radius: 6px;\r\n background-color: #007aff;\r\n transition: background-color 0.3s ease;\r\n}\r\n\r\nuni-slider .uni-slider-handle,\r\nuni-slider .uni-slider-thumb {\r\n position: absolute;\r\n left: 50%;\r\n top: 50%;\r\n cursor: pointer;\r\n border-radius: 50%;\r\n transition: border-color 0.3s ease;\r\n}\r\n\r\nuni-slider .uni-slider-handle {\r\n width: 28px;\r\n height: 28px;\r\n margin-top: -14px;\r\n margin-left: -14px;\r\n background-color: transparent;\r\n z-index: 3;\r\n cursor: grab;\r\n}\r\n\r\nuni-slider .uni-slider-thumb {\r\n z-index: 2;\r\n box-shadow: 0 0 4px rgba(0, 0, 0, 0.2);\r\n}\r\n\r\nuni-slider .uni-slider-step {\r\n position: absolute;\r\n width: 100%;\r\n height: 2px;\r\n background: transparent;\r\n z-index: 1;\r\n}\r\n\r\nuni-slider .uni-slider-value {\r\n width: 3ch;\r\n color: #888;\r\n font-size: 14px;\r\n margin-left: 1em;\r\n}\r\n\r\nuni-slider .uni-slider-disabled .uni-slider-track {\r\n background-color: #ccc;\r\n}\r\n\r\nuni-slider .uni-slider-disabled .uni-slider-thumb {\r\n background-color: #fff;\r\n border-color: #ccc;\r\n}\r\n"; + var slider = "uni-slider {\n margin: 10px 18px;\n padding: 0;\n display: block;\n}\n\nuni-slider[hidden] {\n display: none;\n}\n\nuni-slider .uni-slider-wrapper {\n display: flex;\n align-items: center;\n min-height: 16px;\n}\n\nuni-slider .uni-slider-tap-area {\n flex: 1;\n padding: 8px 0;\n}\n\nuni-slider .uni-slider-handle-wrapper {\n position: relative;\n height: 2px;\n border-radius: 5px;\n background-color: #e9e9e9;\n cursor: pointer;\n transition: background-color 0.3s ease;\n -webkit-tap-highlight-color: transparent;\n}\n\nuni-slider .uni-slider-track {\n height: 100%;\n border-radius: 6px;\n background-color: #007aff;\n transition: background-color 0.3s ease;\n}\n\nuni-slider .uni-slider-handle,\nuni-slider .uni-slider-thumb {\n position: absolute;\n left: 50%;\n top: 50%;\n cursor: pointer;\n border-radius: 50%;\n transition: border-color 0.3s ease;\n}\n\nuni-slider .uni-slider-handle {\n width: 28px;\n height: 28px;\n margin-top: -14px;\n margin-left: -14px;\n background-color: transparent;\n z-index: 3;\n cursor: grab;\n}\n\nuni-slider .uni-slider-thumb {\n z-index: 2;\n box-shadow: 0 0 4px rgba(0, 0, 0, 0.2);\n}\n\nuni-slider .uni-slider-step {\n position: absolute;\n width: 100%;\n height: 2px;\n background: transparent;\n z-index: 1;\n}\n\nuni-slider .uni-slider-value {\n width: 3ch;\n color: #888;\n font-size: 14px;\n margin-left: 1em;\n}\n\nuni-slider .uni-slider-disabled .uni-slider-track {\n background-color: #ccc;\n}\n\nuni-slider .uni-slider-disabled .uni-slider-thumb {\n background-color: #fff;\n border-color: #ccc;\n}\n"; class UniSlider extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-slider", Slider, parentNodeId, nodeJson); } } - var swiper = "uni-swiper {\r\n display: block;\r\n height: 150px;\r\n}\r\n\r\nuni-swiper[hidden] {\r\n display: none;\r\n}\r\n\r\n.uni-swiper-wrapper {\r\n overflow: hidden;\r\n position: relative;\r\n width: 100%;\r\n height: 100%;\r\n transform: translateZ(0);\r\n}\r\n\r\n.uni-swiper-slides {\r\n position: absolute;\r\n left: 0;\r\n top: 0;\r\n right: 0;\r\n bottom: 0;\r\n}\r\n\r\n.uni-swiper-slide-frame {\r\n position: absolute;\r\n left: 0;\r\n top: 0;\r\n width: 100%;\r\n height: 100%;\r\n will-change: transform;\r\n}\r\n\r\n.uni-swiper-dots {\r\n position: absolute;\r\n font-size: 0;\r\n}\r\n\r\n.uni-swiper-dots-horizontal {\r\n left: 50%;\r\n bottom: 10px;\r\n text-align: center;\r\n white-space: nowrap;\r\n transform: translate(-50%, 0);\r\n}\r\n\r\n.uni-swiper-dots-horizontal .uni-swiper-dot {\r\n margin-right: 8px;\r\n}\r\n\r\n.uni-swiper-dots-horizontal .uni-swiper-dot:last-child {\r\n margin-right: 0;\r\n}\r\n\r\n.uni-swiper-dots-vertical {\r\n right: 10px;\r\n top: 50%;\r\n text-align: right;\r\n transform: translate(0, -50%);\r\n}\r\n\r\n.uni-swiper-dots-vertical .uni-swiper-dot {\r\n display: block;\r\n margin-bottom: 9px;\r\n}\r\n\r\n.uni-swiper-dots-vertical .uni-swiper-dot:last-child {\r\n margin-bottom: 0;\r\n}\r\n\r\n.uni-swiper-dot {\r\n display: inline-block;\r\n width: 8px;\r\n height: 8px;\r\n cursor: pointer;\r\n transition-property: background-color;\r\n transition-timing-function: ease;\r\n background: rgba(0, 0, 0, 0.3);\r\n border-radius: 50%;\r\n}\r\n\r\n.uni-swiper-dot-active {\r\n background-color: #000000;\r\n}\r\n"; + var swiper = "uni-swiper {\n display: block;\n height: 150px;\n}\n\nuni-swiper[hidden] {\n display: none;\n}\n\n.uni-swiper-wrapper {\n overflow: hidden;\n position: relative;\n width: 100%;\n height: 100%;\n transform: translateZ(0);\n}\n\n.uni-swiper-slides {\n position: absolute;\n left: 0;\n top: 0;\n right: 0;\n bottom: 0;\n}\n\n.uni-swiper-slide-frame {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n will-change: transform;\n}\n\n.uni-swiper-dots {\n position: absolute;\n font-size: 0;\n}\n\n.uni-swiper-dots-horizontal {\n left: 50%;\n bottom: 10px;\n text-align: center;\n white-space: nowrap;\n transform: translate(-50%, 0);\n}\n\n.uni-swiper-dots-horizontal .uni-swiper-dot {\n margin-right: 8px;\n}\n\n.uni-swiper-dots-horizontal .uni-swiper-dot:last-child {\n margin-right: 0;\n}\n\n.uni-swiper-dots-vertical {\n right: 10px;\n top: 50%;\n text-align: right;\n transform: translate(0, -50%);\n}\n\n.uni-swiper-dots-vertical .uni-swiper-dot {\n display: block;\n margin-bottom: 9px;\n}\n\n.uni-swiper-dots-vertical .uni-swiper-dot:last-child {\n margin-bottom: 0;\n}\n\n.uni-swiper-dot {\n display: inline-block;\n width: 8px;\n height: 8px;\n cursor: pointer;\n transition-property: background-color;\n transition-timing-function: ease;\n background: rgba(0, 0, 0, 0.3);\n border-radius: 50%;\n}\n\n.uni-swiper-dot-active {\n background-color: #000000;\n}\n"; class UniSwiper extends UniContainerComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-swiper", Swiper, parentNodeId, nodeJson, ".uni-swiper-slide-frame"); } } - var swiperItem = "uni-swiper-item {\r\n display: block;\r\n overflow: hidden;\r\n will-change: transform;\r\n position: absolute;\r\n width: 100%;\r\n height: 100%;\r\n cursor: grab;\r\n}\r\n\r\nuni-swiper-item[hidden] {\r\n display: none;\r\n}\r\n"; + var swiperItem = "uni-swiper-item {\n display: block;\n overflow: hidden;\n will-change: transform;\n position: absolute;\n width: 100%;\n height: 100%;\n cursor: grab;\n}\n\nuni-swiper-item[hidden] {\n display: none;\n}\n"; class UniSwiperItem extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-swiper-item", SwiperItem, parentNodeId, nodeJson); } } - var _switch = "uni-switch {\r\n -webkit-tap-highlight-color: transparent;\r\n display: inline-block;\r\n cursor: pointer;\r\n}\r\n\r\nuni-switch[hidden] {\r\n display: none;\r\n}\r\n\r\nuni-switch[disabled] {\r\n cursor: not-allowed;\r\n}\r\n\r\n.uni-switch-wrapper {\r\n display: inline-flex;\r\n align-items: center;\r\n vertical-align: middle;\r\n}\r\n\r\n.uni-switch-input {\r\n -webkit-appearance: none;\r\n appearance: none;\r\n position: relative;\r\n width: 52px;\r\n height: 32px;\r\n margin-right: 5px;\r\n border: 1px solid #dfdfdf;\r\n outline: 0;\r\n border-radius: 16px;\r\n box-sizing: border-box;\r\n background-color: #dfdfdf;\r\n transition: background-color 0.1s, border 0.1s;\r\n}\r\n\r\nuni-switch[disabled] .uni-switch-input {\r\n opacity: 0.7;\r\n}\r\n\r\n.uni-switch-input:before {\r\n content: ' ';\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n width: 50px;\r\n height: 30px;\r\n border-radius: 15px;\r\n background-color: #fdfdfd;\r\n transition: transform 0.3s;\r\n}\r\n\r\n.uni-switch-input:after {\r\n content: ' ';\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n width: 30px;\r\n height: 30px;\r\n border-radius: 15px;\r\n background-color: #ffffff;\r\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);\r\n transition: transform 0.3s;\r\n}\r\n\r\n.uni-switch-input.uni-switch-input-checked {\r\n border-color: #007aff;\r\n background-color: #007aff;\r\n}\r\n\r\n.uni-switch-input.uni-switch-input-checked:before {\r\n transform: scale(0);\r\n}\r\n\r\n.uni-switch-input.uni-switch-input-checked:after {\r\n transform: translateX(20px);\r\n}\r\n\r\nuni-switch .uni-checkbox-input {\r\n margin-right: 5px;\r\n -webkit-appearance: none;\r\n appearance: none;\r\n outline: 0;\r\n border: 1px solid #d1d1d1;\r\n background-color: #ffffff;\r\n border-radius: 3px;\r\n width: 22px;\r\n height: 22px;\r\n position: relative;\r\n color: #007aff;\r\n}\r\n\r\nuni-switch:not([disabled]) .uni-checkbox-input:hover {\r\n border-color: #007aff;\r\n}\r\n\r\nuni-switch .uni-checkbox-input svg {\r\n color: inherit;\r\n font-size: 22px;\r\n position: absolute;\r\n top: 50%;\r\n left: 50%;\r\n transform: translate(-50%, -48%) scale(0.73);\r\n}\r\n\r\n.uni-checkbox-input.uni-checkbox-input-disabled {\r\n background-color: #e1e1e1;\r\n}\r\n\r\n.uni-checkbox-input.uni-checkbox-input-disabled:before {\r\n color: #adadad;\r\n}\r\n"; + var _switch = "uni-switch {\n -webkit-tap-highlight-color: transparent;\n display: inline-block;\n cursor: pointer;\n}\n\nuni-switch[hidden] {\n display: none;\n}\n\nuni-switch[disabled] {\n cursor: not-allowed;\n}\n\n.uni-switch-wrapper {\n display: inline-flex;\n align-items: center;\n vertical-align: middle;\n}\n\n.uni-switch-input {\n -webkit-appearance: none;\n appearance: none;\n position: relative;\n width: 52px;\n height: 32px;\n margin-right: 5px;\n border: 1px solid #dfdfdf;\n outline: 0;\n border-radius: 16px;\n box-sizing: border-box;\n background-color: #dfdfdf;\n transition: background-color 0.1s, border 0.1s;\n}\n\nuni-switch[disabled] .uni-switch-input {\n opacity: 0.7;\n}\n\n.uni-switch-input:before {\n content: ' ';\n position: absolute;\n top: 0;\n left: 0;\n width: 50px;\n height: 30px;\n border-radius: 15px;\n background-color: #fdfdfd;\n transition: transform 0.3s;\n}\n\n.uni-switch-input:after {\n content: ' ';\n position: absolute;\n top: 0;\n left: 0;\n width: 30px;\n height: 30px;\n border-radius: 15px;\n background-color: #ffffff;\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);\n transition: transform 0.3s;\n}\n\n.uni-switch-input.uni-switch-input-checked {\n border-color: #007aff;\n background-color: #007aff;\n}\n\n.uni-switch-input.uni-switch-input-checked:before {\n transform: scale(0);\n}\n\n.uni-switch-input.uni-switch-input-checked:after {\n transform: translateX(20px);\n}\n\nuni-switch .uni-checkbox-input {\n margin-right: 5px;\n -webkit-appearance: none;\n appearance: none;\n outline: 0;\n border: 1px solid #d1d1d1;\n background-color: #ffffff;\n border-radius: 3px;\n width: 22px;\n height: 22px;\n position: relative;\n color: #007aff;\n}\n\nuni-switch:not([disabled]) .uni-checkbox-input:hover {\n border-color: #007aff;\n}\n\nuni-switch .uni-checkbox-input svg {\n color: inherit;\n font-size: 22px;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -48%) scale(0.73);\n}\n\n.uni-checkbox-input.uni-checkbox-input-disabled {\n background-color: #e1e1e1;\n}\n\n.uni-checkbox-input.uni-checkbox-input-disabled:before {\n color: #adadad;\n}\n"; class UniSwitch extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-switch", Switch, parentNodeId, nodeJson); } } - var textarea = "uni-textarea {\r\n width: 300px;\r\n height: 150px;\r\n display: block;\r\n position: relative;\r\n font-size: 16px;\r\n line-height: normal;\r\n white-space: pre-wrap;\r\n word-break: break-all;\r\n box-sizing: content-box !important;\r\n}\r\nuni-textarea[hidden] {\r\n display: none;\r\n}\r\n.uni-textarea-wrapper,\r\n.uni-textarea-placeholder,\r\n.uni-textarea-line,\r\n.uni-textarea-compute,\r\n.uni-textarea-textarea {\r\n outline: none;\r\n border: none;\r\n padding: 0;\r\n margin: 0;\r\n text-decoration: inherit;\r\n}\r\n.uni-textarea-wrapper {\r\n display: block;\r\n position: relative;\r\n width: 100%;\r\n height: 100%;\r\n min-height: inherit;\r\n}\r\n.uni-textarea-placeholder,\r\n.uni-textarea-line,\r\n.uni-textarea-compute,\r\n.uni-textarea-textarea {\r\n position: absolute;\r\n width: 100%;\r\n height: 100%;\r\n left: 0;\r\n top: 0;\r\n white-space: inherit;\r\n word-break: inherit;\r\n}\r\n.uni-textarea-placeholder {\r\n color: grey;\r\n overflow: hidden;\r\n}\r\n.uni-textarea-line,\r\n.uni-textarea-compute {\r\n visibility: hidden;\r\n height: auto;\r\n}\r\n.uni-textarea-line {\r\n width: 1em;\r\n}\r\n.uni-textarea-textarea {\r\n resize: none;\r\n background: none;\r\n color: inherit;\r\n opacity: 1;\r\n font: inherit;\r\n line-height: inherit;\r\n letter-spacing: inherit;\r\n text-align: inherit;\r\n text-indent: inherit;\r\n text-transform: inherit;\r\n text-shadow: inherit;\r\n}\r\n/* \u7528\u4E8E\u89E3\u51B3 iOS textarea \u5185\u90E8\u9ED8\u8BA4\u8FB9\u8DDD */\r\n.uni-textarea-textarea-fix-margin {\r\n width: auto;\r\n right: 0;\r\n margin: 0 -3px;\r\n}\r\n.uni-textarea-textarea:disabled {\r\n /* \u7528\u4E8E\u91CD\u7F6EiOS14\u4EE5\u4E0B\u7981\u7528\u72B6\u6001\u6587\u5B57\u989C\u8272 */\r\n -webkit-text-fill-color: currentcolor;\r\n}\r\n"; + var textarea = "uni-textarea {\n width: 300px;\n height: 150px;\n display: block;\n position: relative;\n font-size: 16px;\n line-height: normal;\n white-space: pre-wrap;\n word-break: break-all;\n box-sizing: content-box !important;\n}\nuni-textarea[hidden] {\n display: none;\n}\n.uni-textarea-wrapper,\n.uni-textarea-placeholder,\n.uni-textarea-line,\n.uni-textarea-compute,\n.uni-textarea-textarea {\n outline: none;\n border: none;\n padding: 0;\n margin: 0;\n text-decoration: inherit;\n}\n.uni-textarea-wrapper {\n display: block;\n position: relative;\n width: 100%;\n height: 100%;\n min-height: inherit;\n}\n.uni-textarea-placeholder,\n.uni-textarea-line,\n.uni-textarea-compute,\n.uni-textarea-textarea {\n position: absolute;\n width: 100%;\n height: 100%;\n left: 0;\n top: 0;\n white-space: inherit;\n word-break: inherit;\n}\n.uni-textarea-placeholder {\n color: grey;\n overflow: hidden;\n}\n.uni-textarea-line,\n.uni-textarea-compute {\n visibility: hidden;\n height: auto;\n}\n.uni-textarea-line {\n width: 1em;\n}\n.uni-textarea-textarea {\n resize: none;\n background: none;\n color: inherit;\n opacity: 1;\n font: inherit;\n line-height: inherit;\n letter-spacing: inherit;\n text-align: inherit;\n text-indent: inherit;\n text-transform: inherit;\n text-shadow: inherit;\n}\n/* \u7528\u4E8E\u89E3\u51B3 iOS textarea \u5185\u90E8\u9ED8\u8BA4\u8FB9\u8DDD */\n.uni-textarea-textarea-fix-margin {\n width: auto;\n right: 0;\n margin: 0 -3px;\n}\n.uni-textarea-textarea:disabled {\n /* \u7528\u4E8E\u91CD\u7F6EiOS14\u4EE5\u4E0B\u7981\u7528\u72B6\u6001\u6587\u5B57\u989C\u8272 */\n -webkit-text-fill-color: currentcolor;\n}\n"; class UniTextarea extends UniComponent { constructor(id2, parentNodeId, nodeJson) { super(id2, "uni-textarea", Textarea, parentNodeId, nodeJson); } } - var video = "uni-video {\r\n width: 300px;\r\n height: 225px;\r\n display: inline-block;\r\n line-height: 0;\r\n overflow: hidden;\r\n position: relative;\r\n}\r\n\r\nuni-video[hidden] {\r\n display: none;\r\n}\r\n\r\n.uni-video-container {\r\n width: 100%;\r\n height: 100%;\r\n position: absolute;\r\n top: 0;\r\n left: 0;\r\n overflow: hidden;\r\n background-color: black;\r\n}\r\n\r\n.uni-video-slot {\r\n position: absolute;\r\n top: 0;\r\n width: 100%;\r\n height: 100%;\r\n overflow: hidden;\r\n pointer-events: none;\r\n}\r\n"; + var video = "uni-video {\n width: 300px;\n height: 225px;\n display: inline-block;\n line-height: 0;\n overflow: hidden;\n position: relative;\n}\n\nuni-video[hidden] {\n display: none;\n}\n\n.uni-video-container {\n width: 100%;\n height: 100%;\n position: absolute;\n top: 0;\n left: 0;\n overflow: hidden;\n background-color: black;\n}\n\n.uni-video-slot {\n position: absolute;\n top: 0;\n width: 100%;\n height: 100%;\n overflow: hidden;\n pointer-events: none;\n}\n"; const props = { id: { type: String, diff --git a/packages/uni-app-plus/src/service/framework/page/define.ts b/packages/uni-app-plus/src/service/framework/page/define.ts index 3c9ab283f9d2abc90cf95e258dbecadc4a87df67..b95734bcccb442d181de433aa272f397d84e91dd 100644 --- a/packages/uni-app-plus/src/service/framework/page/define.ts +++ b/packages/uni-app-plus/src/service/framework/page/define.ts @@ -1,3 +1,4 @@ +import { isFunction, isPromise } from '@vue/shared' import { once, PageNodeOptions } from '@dcloudio/uni-shared' import { DefineComponent } from 'vue' import { createPageNode } from '../dom/Page' @@ -7,10 +8,21 @@ import { getVueApp } from '../app' export type VuePageComponent = DefineComponent +type VuePageAsyncComponent = () => Promise + +function isVuePageAsyncComponent( + component: unknown +): component is VuePageAsyncComponent { + return isFunction(component) +} + const pagesMap = new Map>() -export function definePage(pagePath: string, component: VuePageComponent) { - pagesMap.set(pagePath, once(createFactory(component))) +export function definePage( + pagePath: string, + asyncComponent: VuePageAsyncComponent | VuePageComponent +) { + pagesMap.set(pagePath, once(createFactory(asyncComponent))) } interface PageProps { @@ -29,20 +41,29 @@ export function createPage( ) { const pageNode = createPageNode(__pageId, pageOptions, true) const app = getVueApp() - return app.mountPage( - pagesMap.get(__pagePath)!(), - { - __pageId, - __pagePath, - __pageQuery, - __pageInstance, - }, - pageNode - ) + const component = pagesMap.get(__pagePath)!() + const mountPage = (component: VuePageComponent) => + app.mountPage( + component, + { + __pageId, + __pagePath, + __pageQuery, + __pageInstance, + }, + pageNode + ) + if (isPromise(component)) { + return component.then((component) => mountPage(component)) + } + return mountPage(component) } -function createFactory(component: VuePageComponent) { +function createFactory(component: VuePageAsyncComponent | VuePageComponent) { return () => { + if (isVuePageAsyncComponent(component)) { + return component().then((component) => setupPage(component)) + } return setupPage(component) } } diff --git a/packages/uni-app-vite/dist/index.js b/packages/uni-app-vite/dist/index.js index 18411ab37ff5b52784d2f88c109baa68f875fc46..69b88d0bd4207e3909eeeb03a1dad978fdc73d1c 100644 --- a/packages/uni-app-vite/dist/index.js +++ b/packages/uni-app-vite/dist/index.js @@ -11,14 +11,17 @@ const mainJs_1 = require("./plugins/mainJs"); const manifestJson_1 = require("./plugins/manifestJson"); const pagesJson_1 = require("./plugins/pagesJson"); const resolveId_1 = require("./plugins/resolveId"); -exports.default = [ +const plugins = [ resolveId_1.uniResolveIdPlugin(), copy_1.uniCopyPlugin(), mainJs_1.uniMainJsPlugin(), manifestJson_1.uniManifestJsonPlugin(), pagesJson_1.uniPagesJsonPlugin(), plugin_1.UniAppPlugin, - uni_cli_shared_1.uniCssPlugin({ - app: fs_1.default.readFileSync(require.resolve('@dcloudio/uni-app-plus/dist/style.css'), 'utf8'), - }), ]; +if (!process.env.UNI_APP_CODE_SPLITING) { + plugins.push(uni_cli_shared_1.uniCssPlugin({ + app: fs_1.default.readFileSync(require.resolve('@dcloudio/uni-app-plus/dist/style.css'), 'utf8'), + })); +} +exports.default = plugins; diff --git a/packages/uni-app-vite/dist/plugin.js b/packages/uni-app-vite/dist/plugin.js deleted file mode 100644 index fe037fcf7430ab882581e51fbcfc2a98c9f7a588..0000000000000000000000000000000000000000 --- a/packages/uni-app-vite/dist/plugin.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.UniAppPlugin = void 0; -const uni_shared_1 = require("@dcloudio/uni-shared"); -const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared"); -exports.UniAppPlugin = { - name: 'vite:uni-app', - uni: { - compilerOptions: { - isNativeTag: uni_shared_1.isServiceNativeTag, - isCustomElement: uni_shared_1.isServiceCustomElement, - }, - transformEvent: { - tap: 'click', - }, - }, - config() { - return { - build: { - rollupOptions: { - input: uni_cli_shared_1.resolveMainPathOnce(process.env.UNI_INPUT_DIR), - external: ['vue'], - output: { - name: 'AppService', - format: 'iife', - entryFileNames: 'app-service.js', - manualChunks: undefined, - globals: { - vue: 'Vue', - }, - }, - }, - }, - }; - }, - configResolved(config) { - const manifestJson = uni_cli_shared_1.parseManifestJsonOnce(process.env.UNI_INPUT_DIR); - if (uni_cli_shared_1.getNVueCompiler(manifestJson) === 'uni-app') { - process.env.UNI_USING_NVUE_COMPILER = 'uni-app'; - } - if (uni_cli_shared_1.getNVueStyleCompiler(manifestJson) === 'uni-app') { - process.env.UNI_USING_NVUE_STYLE_COMPILER = 'uni-app'; - } - // 移除 vite 内置的 css post 处理 - const index = config.plugins.findIndex((p) => p.name === 'vite:css-post'); - if (index > -1) { - ; - config.plugins.splice(index, 1); - } - }, - resolveId(id) { - if (id === 'vue') { - return uni_cli_shared_1.resolveBuiltIn('@dcloudio/uni-app-vue'); - } - }, -}; diff --git a/packages/uni-app-vite/dist/plugin/build.js b/packages/uni-app-vite/dist/plugin/build.js new file mode 100644 index 0000000000000000000000000000000000000000..342100622259c3af7b6f44a91349c72a8cdef9ba --- /dev/null +++ b/packages/uni-app-vite/dist/plugin/build.js @@ -0,0 +1,32 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.buildOptions = void 0; +const path_1 = __importDefault(require("path")); +const slash_1 = __importDefault(require("slash")); +const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared"); +exports.buildOptions = { + rollupOptions: { + input: uni_cli_shared_1.resolveMainPathOnce(process.env.UNI_INPUT_DIR), + external: ['vue'], + output: { + name: 'AppService', + format: process.env.UNI_APP_CODE_SPLITING ? 'amd' : 'iife', + entryFileNames: 'app-service.js', + manualChunks: {}, + chunkFileNames(chunk) { + if (chunk.isDynamicEntry && chunk.facadeModuleId) { + const filepath = path_1.default.relative(process.env.UNI_INPUT_DIR, chunk.facadeModuleId); + return slash_1.default(filepath.replace(path_1.default.extname(filepath), '.js')); + } + return '[name].js'; + }, + assetFileNames: '[name][extname]', + globals: { + vue: 'Vue', + }, + }, + }, +}; diff --git a/packages/uni-app-vite/dist/plugin/configResolved.js b/packages/uni-app-vite/dist/plugin/configResolved.js new file mode 100644 index 0000000000000000000000000000000000000000..ffee16f40637b7658105b3deca273f6d75f78b65 --- /dev/null +++ b/packages/uni-app-vite/dist/plugin/configResolved.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.configResolved = void 0; +const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared"); +const asset_1 = require("../plugins/vitejs/plugins/asset"); +const css_1 = require("../plugins/vitejs/plugins/css"); +const configResolved = (config) => { + const manifestJson = uni_cli_shared_1.parseManifestJsonOnce(process.env.UNI_INPUT_DIR); + if (uni_cli_shared_1.getNVueCompiler(manifestJson) === 'uni-app') { + process.env.UNI_USING_NVUE_COMPILER = 'uni-app'; + } + if (uni_cli_shared_1.getNVueStyleCompiler(manifestJson) === 'uni-app') { + process.env.UNI_USING_NVUE_STYLE_COMPILER = 'uni-app'; + } + if (process.env.UNI_APP_CODE_SPLITING) { + initCodeSpliting(config); + } + else { + // 移除 vite 内置的 css post 处理,交由 @dcloudio/uni-cli-shared 的 uniCssPlugin 实现 + const index = config.plugins.findIndex((p) => p.name === 'vite:css-post'); + if (index > -1) { + ; + config.plugins.splice(index, 1); + } + } +}; +exports.configResolved = configResolved; +function initCodeSpliting(config) { + // 替换内置插件 + const replacedPlugins = [ + asset_1.assetPlugin(config), + css_1.cssPlugin(config), + css_1.cssPostPlugin(config), + ]; + replacedPlugins.forEach((plugin) => { + const index = config.plugins.findIndex((p) => p.name === plugin.name); + if (index > -1) { + ; + config.plugins.splice(index, 1, plugin); + } + }); + const removedPlugins = ['vite:import-analysis']; + removedPlugins.forEach((name) => { + const index = config.plugins.findIndex((p) => p.name === name); + if (index > -1) { + ; + config.plugins.splice(index, 1); + } + }); +} diff --git a/packages/uni-app-vite/dist/plugin/index.js b/packages/uni-app-vite/dist/plugin/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d8b5131b88c2a2635b1dd6a050551b79ebc50701 --- /dev/null +++ b/packages/uni-app-vite/dist/plugin/index.js @@ -0,0 +1,22 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UniAppPlugin = void 0; +const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared"); +const uni_1 = require("./uni"); +const build_1 = require("./build"); +const configResolved_1 = require("./configResolved"); +exports.UniAppPlugin = { + name: 'vite:uni-app', + uni: uni_1.uniOptions, + config() { + return { + build: build_1.buildOptions, + }; + }, + configResolved: configResolved_1.configResolved, + resolveId(id) { + if (id === 'vue') { + return uni_cli_shared_1.resolveBuiltIn('@dcloudio/uni-app-vue'); + } + }, +}; diff --git a/packages/uni-app-vite/dist/plugin/uni.js b/packages/uni-app-vite/dist/plugin/uni.js new file mode 100644 index 0000000000000000000000000000000000000000..0d80fee2a3e3488ea729328eb166bc82a9821c96 --- /dev/null +++ b/packages/uni-app-vite/dist/plugin/uni.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.uniOptions = void 0; +const uni_shared_1 = require("@dcloudio/uni-shared"); +exports.uniOptions = { + compilerOptions: { + isNativeTag: uni_shared_1.isServiceNativeTag, + isCustomElement: uni_shared_1.isServiceCustomElement, + }, + transformEvent: { + tap: 'click', + }, +}; diff --git a/packages/uni-app-vite/dist/plugins/vitejs/constants.js b/packages/uni-app-vite/dist/plugins/vitejs/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..bcc9d34a27355c0a173fab0f5e49c1fa3f08306d --- /dev/null +++ b/packages/uni-app-vite/dist/plugins/vitejs/constants.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CLIENT_PUBLIC_PATH = exports.FS_PREFIX = void 0; +/** + * https://github.com/vitejs/vite/blob/main/packages/vite/src/node/constants.ts + */ +/** + * Prefix for resolved fs paths, since windows paths may not be valid as URLs. + */ +exports.FS_PREFIX = `/@fs/`; +exports.CLIENT_PUBLIC_PATH = `/@vite/client`; diff --git a/packages/uni-app-vite/dist/plugins/vitejs/plugins/asset.js b/packages/uni-app-vite/dist/plugins/vitejs/plugins/asset.js new file mode 100644 index 0000000000000000000000000000000000000000..c33580a38702e2315deb38f168b8a5f6c39aae21 --- /dev/null +++ b/packages/uni-app-vite/dist/plugins/vitejs/plugins/asset.js @@ -0,0 +1,266 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.urlToBuiltUrl = exports.getAssetHash = exports.getAssetFilename = exports.fileToUrl = exports.checkPublicFile = exports.registerAssetToChunk = exports.assetPlugin = exports.chunkToEmittedAssetsMap = exports.assetUrlRE = void 0; +/** + * https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/asset.ts + */ +const path_1 = __importDefault(require("path")); +const url_1 = require("url"); +const fs_1 = __importStar(require("fs")); +const lite_1 = __importDefault(require("mime/lite")); +const utils_1 = require("../utils"); +const constants_1 = require("../constants"); +const magic_string_1 = __importDefault(require("magic-string")); +const crypto_1 = require("crypto"); +exports.assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g; +// urls in JS must be quoted as strings, so when replacing them we need +// a different regex +const assetUrlQuotedRE = /"__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?"/g; +const rawRE = /(\?|&)raw(?:&|$)/; +const urlRE = /(\?|&)url(?:&|$)/; +exports.chunkToEmittedAssetsMap = new WeakMap(); +const assetCache = new WeakMap(); +const assetHashToFilenameMap = new WeakMap(); +// save hashes of the files that has been emitted in build watch +const emittedHashMap = new WeakMap(); +/** + * Also supports loading plain strings with import text from './foo.txt?raw' + */ +function assetPlugin(config) { + // assetHashToFilenameMap initialization in buildStart causes getAssetFilename to return undefined + assetHashToFilenameMap.set(config, new Map()); + return { + name: 'vite:asset', + buildStart() { + assetCache.set(config, new Map()); + emittedHashMap.set(config, new Set()); + }, + resolveId(id) { + if (!config.assetsInclude(utils_1.cleanUrl(id))) { + return; + } + // imports to absolute urls pointing to files in /public + // will fail to resolve in the main resolver. handle them here. + const publicFile = checkPublicFile(id, config); + if (publicFile) { + return id; + } + }, + load(id) { + return __awaiter(this, void 0, void 0, function* () { + if (id.startsWith('\0')) { + // Rollup convention, this id should be handled by the + // plugin that marked it with \0 + return; + } + // raw requests, read from disk + if (rawRE.test(id)) { + const file = checkPublicFile(id, config) || utils_1.cleanUrl(id); + // raw query, read file and return as string + return `export default ${JSON.stringify(yield fs_1.promises.readFile(file, 'utf-8'))}`; + } + if (!config.assetsInclude(utils_1.cleanUrl(id)) && !urlRE.test(id)) { + return; + } + id = id.replace(urlRE, '$1').replace(/[\?&]$/, ''); + const url = yield fileToUrl(id, config, this); + return `export default ${JSON.stringify(url)}`; + }); + }, + renderChunk(code, chunk) { + let match; + let s; + while ((match = assetUrlQuotedRE.exec(code))) { + s = s || (s = new magic_string_1.default(code)); + const [full, hash, postfix = ''] = match; + // some internal plugins may still need to emit chunks (e.g. worker) so + // fallback to this.getFileName for that. + const file = getAssetFilename(hash, config) || this.getFileName(hash); + registerAssetToChunk(chunk, file); + const outputFilepath = config.base + file + postfix; + s.overwrite(match.index, match.index + full.length, JSON.stringify(outputFilepath)); + } + if (s) { + return { + code: s.toString(), + map: config.build.sourcemap ? s.generateMap({ hires: true }) : null, + }; + } + else { + return null; + } + }, + generateBundle(_, bundle) { + // do not emit assets for SSR build + if (config.command === 'build' && config.build.ssr) { + for (const file in bundle) { + if (bundle[file].type === 'asset' && + !file.includes('ssr-manifest.json')) { + delete bundle[file]; + } + } + } + }, + }; +} +exports.assetPlugin = assetPlugin; +function registerAssetToChunk(chunk, file) { + let emitted = exports.chunkToEmittedAssetsMap.get(chunk); + if (!emitted) { + emitted = new Set(); + exports.chunkToEmittedAssetsMap.set(chunk, emitted); + } + emitted.add(utils_1.cleanUrl(file)); +} +exports.registerAssetToChunk = registerAssetToChunk; +function checkPublicFile(url, { publicDir }) { + // note if the file is in /public, the resolver would have returned it + // as-is so it's not going to be a fully resolved path. + if (!publicDir || !url.startsWith('/')) { + return; + } + const publicFile = path_1.default.join(publicDir, utils_1.cleanUrl(url)); + if (fs_1.default.existsSync(publicFile)) { + return publicFile; + } + else { + return; + } +} +exports.checkPublicFile = checkPublicFile; +function fileToUrl(id, config, ctx) { + if (config.command === 'serve') { + return fileToDevUrl(id, config); + } + else { + return fileToBuiltUrl(id, config, ctx); + } +} +exports.fileToUrl = fileToUrl; +function fileToDevUrl(id, config) { + let rtn; + if (checkPublicFile(id, config)) { + // in public dir, keep the url as-is + rtn = id; + } + else if (id.startsWith(config.root)) { + // in project root, infer short public path + rtn = '/' + path_1.default.posix.relative(config.root, id); + } + else { + // outside of project root, use absolute fs path + // (this is special handled by the serve static middleware + rtn = path_1.default.posix.join(constants_1.FS_PREFIX + id); + } + return config.base + rtn.replace(/^\//, ''); +} +function getAssetFilename(hash, config) { + var _a; + return (_a = assetHashToFilenameMap.get(config)) === null || _a === void 0 ? void 0 : _a.get(hash); +} +exports.getAssetFilename = getAssetFilename; +/** + * Register an asset to be emitted as part of the bundle (if necessary) + * and returns the resolved public URL + */ +function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false) { + return __awaiter(this, void 0, void 0, function* () { + if (!skipPublicCheck && checkPublicFile(id, config)) { + return config.base + id.slice(1); + } + const cache = assetCache.get(config); + const cached = cache.get(id); + if (cached) { + return cached; + } + const file = utils_1.cleanUrl(id); + const content = yield fs_1.promises.readFile(file); + let url; + if (config.build.lib || + (!file.endsWith('.svg') && + content.length < Number(config.build.assetsInlineLimit))) { + // base64 inlined as a string + url = `data:${lite_1.default.getType(file)};base64,${content.toString('base64')}`; + } + else { + // emit as asset + // rollup supports `import.meta.ROLLUP_FILE_URL_*`, but it generates code + // that uses runtime url sniffing and it can be verbose when targeting + // non-module format. It also fails to cascade the asset content change + // into the chunk's hash, so we have to do our own content hashing here. + // https://bundlers.tooling.report/hashing/asset-cascade/ + // https://github.com/rollup/rollup/issues/3415 + const map = assetHashToFilenameMap.get(config); + const contentHash = getAssetHash(content); + const { search, hash } = url_1.parse(id); + const postfix = (search || '') + (hash || ''); + const basename = path_1.default.basename(file); + const ext = path_1.default.extname(basename); + const fileName = path_1.default.posix.join(config.build.assetsDir, `${basename.slice(0, -ext.length)}.${contentHash}${ext}`); + if (!map.has(contentHash)) { + map.set(contentHash, fileName); + } + const emittedSet = emittedHashMap.get(config); + if (!emittedSet.has(contentHash)) { + pluginContext.emitFile({ + fileName, + type: 'asset', + source: content, + }); + emittedSet.add(contentHash); + } + url = `__VITE_ASSET__${contentHash}__${postfix ? `$_${postfix}__` : ``}`; + } + cache.set(id, url); + return url; + }); +} +function getAssetHash(content) { + return crypto_1.createHash('sha256').update(content).digest('hex').slice(0, 8); +} +exports.getAssetHash = getAssetHash; +function urlToBuiltUrl(url, importer, config, pluginContext) { + return __awaiter(this, void 0, void 0, function* () { + if (checkPublicFile(url, config)) { + return config.base + url.slice(1); + } + const file = url.startsWith('/') + ? path_1.default.join(config.root, url) + : path_1.default.join(path_1.default.dirname(importer), url); + return fileToBuiltUrl(file, config, pluginContext, + // skip public check since we just did it above + true); + }); +} +exports.urlToBuiltUrl = urlToBuiltUrl; diff --git a/packages/uni-app-vite/dist/plugins/vitejs/plugins/css.js b/packages/uni-app-vite/dist/plugins/vitejs/plugins/css.js new file mode 100644 index 0000000000000000000000000000000000000000..f8052823a0c3d49e4f7c8b390bcaca5fd2e2dcb3 --- /dev/null +++ b/packages/uni-app-vite/dist/plugins/vitejs/plugins/css.js @@ -0,0 +1,891 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.cssUrlRE = exports.cssPostPlugin = exports.cssPlugin = exports.chunkToEmittedCssFileMap = exports.isDirectCSSRequest = exports.isCSSRequest = exports.cssLangRE = void 0; +/** + * https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/css.ts + */ +const fs_1 = __importDefault(require("fs")); +const path_1 = __importDefault(require("path")); +const fast_glob_1 = __importDefault(require("fast-glob")); +const utils_1 = require("../utils"); +const postcss_load_config_1 = __importDefault(require("postcss-load-config")); +const pluginutils_1 = require("@rollup/pluginutils"); +const chalk_1 = __importDefault(require("chalk")); +const constants_1 = require("../constants"); +const asset_1 = require("./asset"); +const magic_string_1 = __importDefault(require("magic-string")); +const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`; +exports.cssLangRE = new RegExp(cssLangs); +const cssModuleRE = new RegExp(`\\.module${cssLangs}`); +const directRequestRE = /(\?|&)direct\b/; +const commonjsProxyRE = /\?commonjs-proxy/; +const isCSSRequest = (request) => exports.cssLangRE.test(request) && !directRequestRE.test(request); +exports.isCSSRequest = isCSSRequest; +const isDirectCSSRequest = (request) => exports.cssLangRE.test(request) && directRequestRE.test(request); +exports.isDirectCSSRequest = isDirectCSSRequest; +const cssModulesCache = new WeakMap(); +exports.chunkToEmittedCssFileMap = new WeakMap(); +/** + * Plugin applied before user plugins + */ +function cssPlugin(config) { + let server; + let moduleCache; + const resolveUrl = config.createResolver({ + preferRelative: true, + tryIndex: false, + extensions: [], + }); + const atImportResolvers = createCSSResolvers(config); + return { + name: 'vite:css', + configureServer(_server) { + server = _server; + }, + buildStart() { + // Ensure a new cache for every build (i.e. rebuilding in watch mode) + moduleCache = new Map(); + cssModulesCache.set(config, moduleCache); + }, + transform(raw, id) { + return __awaiter(this, void 0, void 0, function* () { + if (!exports.cssLangRE.test(id) || commonjsProxyRE.test(id)) { + return; + } + const urlReplacer = (url, importer) => __awaiter(this, void 0, void 0, function* () { + if (asset_1.checkPublicFile(url, config)) { + return config.base + url.slice(1); + } + const resolved = yield resolveUrl(url, importer); + if (resolved) { + return asset_1.fileToUrl(resolved, config, this); + } + return url; + }); + const { code: css, modules, deps, } = yield compileCSS(id, raw, config, urlReplacer, atImportResolvers, server); + if (modules) { + moduleCache.set(id, modules); + } + // track deps for build watch mode + if (config.command === 'build' && config.build.watch && deps) { + for (const file of deps) { + this.addWatchFile(file); + } + } + // dev + if (server) { + // server only logic for handling CSS @import dependency hmr + const { moduleGraph } = server; + const thisModule = moduleGraph.getModuleById(id); + // CSS modules cannot self-accept since it exports values + const isSelfAccepting = !modules; + if (deps) { + // record deps in the module graph so edits to @import css can trigger + // main import to hot update + const depModules = new Set([...deps].map((file) => moduleGraph.createFileOnlyEntry(file))); + moduleGraph.updateModuleInfo(thisModule, depModules, + // The root CSS proxy module is self-accepting and should not + // have an explicit accept list + new Set(), isSelfAccepting); + for (const file of deps) { + this.addWatchFile(file); + } + } + else { + thisModule.isSelfAccepting = isSelfAccepting; + } + } + return { + code: css, + // TODO CSS source map + map: { mappings: '' }, + }; + }); + }, + }; +} +exports.cssPlugin = cssPlugin; +/** + * Plugin applied after user plugins + */ +function cssPostPlugin(config) { + // styles initialization in buildStart causes a styling loss in watch + const styles = new Map(); + let pureCssChunks; + // when there are multiple rollup outputs and extracting CSS, only emit once, + // since output formats have no effect on the generated CSS. + let outputToExtractedCSSMap; + let hasEmitted = false; + return { + name: 'vite:css-post', + buildStart() { + // Ensure new caches for every build (i.e. rebuilding in watch mode) + pureCssChunks = new Set(); + outputToExtractedCSSMap = new Map(); + hasEmitted = false; + }, + transform(css, id, ssr) { + if (!exports.cssLangRE.test(id) || commonjsProxyRE.test(id)) { + return; + } + const modules = cssModulesCache.get(config).get(id); + const modulesCode = modules && pluginutils_1.dataToEsm(modules, { namedExports: true, preferConst: true }); + if (config.command === 'serve') { + if (exports.isDirectCSSRequest(id)) { + return css; + } + else { + // server only + if (ssr) { + return modulesCode || `export default ${JSON.stringify(css)}`; + } + return [ + `import { updateStyle, removeStyle } from ${JSON.stringify(path_1.default.posix.join(config.base, constants_1.CLIENT_PUBLIC_PATH))}`, + `const id = ${JSON.stringify(id)}`, + `const css = ${JSON.stringify(css)}`, + `updateStyle(id, css)`, + // css modules exports change on edit so it can't self accept + `${modulesCode || `import.meta.hot.accept()\nexport default css`}`, + `import.meta.hot.prune(() => removeStyle(id))`, + ].join('\n'); + } + } + // build CSS handling ---------------------------------------------------- + // record css + styles.set(id, css); + return { + code: '', + map: { mappings: '' }, + // avoid the css module from being tree-shaken so that we can retrieve + // it in renderChunk() + moduleSideEffects: 'no-treeshake', + }; + }, + renderChunk(code, chunk, opts) { + return __awaiter(this, void 0, void 0, function* () { + let chunkCSS = ''; + let isPureCssChunk = true; + const ids = Object.keys(chunk.modules); + for (const id of ids) { + if (!exports.isCSSRequest(id) || + cssModuleRE.test(id) || + commonjsProxyRE.test(id)) { + isPureCssChunk = false; + } + if (styles.has(id)) { + chunkCSS += styles.get(id); + } + } + if (!chunkCSS) { + return null; + } + // resolve asset URL placeholders to their built file URLs and perform + // minification if necessary + const processChunkCSS = (css, { inlined, minify, }) => __awaiter(this, void 0, void 0, function* () { + // replace asset url references with resolved url. + const isRelativeBase = config.base === '' || config.base.startsWith('.'); + css = css.replace(asset_1.assetUrlRE, (_, fileHash, postfix = '') => { + const filename = asset_1.getAssetFilename(fileHash, config) + postfix; + asset_1.registerAssetToChunk(chunk, filename); + if (!isRelativeBase || inlined) { + // absolute base or relative base but inlined (injected as style tag into + // index.html) use the base as-is + return config.base + filename; + } + else { + // relative base + extracted CSS - asset file will be in the same dir + return `./${path_1.default.posix.basename(filename)}`; + } + }); + // only external @imports should exist at this point - and they need to + // be hoisted to the top of the CSS chunk per spec (#1845) + if (css.includes('@import')) { + css = yield hoistAtImports(css); + } + if (minify && config.build.minify) { + css = yield minifyCSS(css, config); + } + return css; + }); + if (config.build.cssCodeSplit) { + if (isPureCssChunk) { + // this is a shared CSS-only chunk that is empty. + pureCssChunks.add(chunk.fileName); + } + if ( + // fixed by xxxxxx support amd + opts.format === 'es' || + opts.format === 'cjs' || + opts.format === 'amd') { + chunkCSS = yield processChunkCSS(chunkCSS, { + inlined: false, + minify: true, + }); + const name = chunk.isDynamicEntry && chunk.fileName + ? chunk.fileName.replace('.js', '') + : chunk.name; + // emit corresponding css file + const fileHandle = this.emitFile({ + name: name + '.css', + type: 'asset', + source: chunkCSS, + }); + exports.chunkToEmittedCssFileMap.set(chunk, new Set([this.getFileName(fileHandle)])); + } + else if (!config.build.ssr) { + // legacy build, inline css + chunkCSS = yield processChunkCSS(chunkCSS, { + inlined: true, + minify: true, + }); + const style = `__vite_style__`; + const injectCode = `var ${style} = document.createElement('style');` + + `${style}.innerHTML = ${JSON.stringify(chunkCSS)};` + + `document.head.appendChild(${style});`; + if (config.build.sourcemap) { + const s = new magic_string_1.default(code); + s.prepend(injectCode); + return { + code: s.toString(), + map: s.generateMap({ hires: true }), + }; + } + else { + return { code: injectCode + code }; + } + } + } + else { + // non-split extracted CSS will be minified together + chunkCSS = yield processChunkCSS(chunkCSS, { + inlined: false, + minify: false, + }); + outputToExtractedCSSMap.set(opts, (outputToExtractedCSSMap.get(opts) || '') + chunkCSS); + } + return null; + }); + }, + generateBundle(opts, bundle) { + return __awaiter(this, void 0, void 0, function* () { + // remove empty css chunks and their imports + if (pureCssChunks.size) { + const emptyChunkFiles = [...pureCssChunks] + .map((file) => path_1.default.basename(file)) + .join('|') + .replace(/\./g, '\\.'); + const emptyChunkRE = new RegExp(opts.format === 'es' + ? `\\bimport\\s*"[^"]*(?:${emptyChunkFiles})";\n?` + : `\\brequire\\(\\s*"[^"]*(?:${emptyChunkFiles})"\\);\n?`, 'g'); + for (const file in bundle) { + const chunk = bundle[file]; + if (chunk.type === 'chunk') { + // remove pure css chunk from other chunk's imports, + // and also register the emitted CSS files under the importer + // chunks instead. + chunk.imports = chunk.imports.filter((file) => { + if (pureCssChunks.has(file)) { + const css = exports.chunkToEmittedCssFileMap.get(bundle[file]); + if (css) { + let existing = exports.chunkToEmittedCssFileMap.get(chunk); + if (!existing) { + existing = new Set(); + } + css.forEach((file) => existing.add(file)); + exports.chunkToEmittedCssFileMap.set(chunk, existing); + } + return false; + } + return true; + }); + chunk.code = chunk.code.replace(emptyChunkRE, + // remove css import while preserving source map location + (m) => `/* empty css ${''.padEnd(m.length - 15)}*/`); + } + } + pureCssChunks.forEach((fileName) => { + delete bundle[fileName]; + }); + } + let extractedCss = outputToExtractedCSSMap.get(opts); + if (extractedCss && !hasEmitted) { + hasEmitted = true; + // minify css + if (config.build.minify) { + extractedCss = yield minifyCSS(extractedCss, config); + } + this.emitFile({ + name: 'style.css', + type: 'asset', + source: extractedCss, + }); + } + }); + }, + }; +} +exports.cssPostPlugin = cssPostPlugin; +function createCSSResolvers(config) { + let cssResolve; + let sassResolve; + let lessResolve; + return { + get css() { + return (cssResolve || + (cssResolve = config.createResolver({ + extensions: ['.css'], + mainFields: ['style'], + tryIndex: false, + preferRelative: true, + }))); + }, + get sass() { + return (sassResolve || + (sassResolve = config.createResolver({ + extensions: ['.scss', '.sass', '.css'], + mainFields: ['sass', 'style'], + tryIndex: true, + tryPrefix: '_', + preferRelative: true, + }))); + }, + get less() { + return (lessResolve || + (lessResolve = config.createResolver({ + extensions: ['.less', '.css'], + mainFields: ['less', 'style'], + tryIndex: false, + preferRelative: true, + }))); + }, + }; +} +function compileCSS(id, code, config, urlReplacer, atImportResolvers, server) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const { modules: modulesOptions, preprocessorOptions } = config.css || {}; + const isModule = modulesOptions !== false && cssModuleRE.test(id); + // although at serve time it can work without processing, we do need to + // crawl them in order to register watch dependencies. + const needInlineImport = code.includes('@import'); + const hasUrl = exports.cssUrlRE.test(code) || cssImageSetRE.test(code); + const postcssConfig = yield resolvePostcssConfig(config); + const lang = (_a = id.match(exports.cssLangRE)) === null || _a === void 0 ? void 0 : _a[1]; + // 1. plain css that needs no processing + if (lang === 'css' && + !postcssConfig && + !isModule && + !needInlineImport && + !hasUrl) { + return { code }; + } + let map; + let modules; + const deps = new Set(); + // 2. pre-processors: sass etc. + if (isPreProcessor(lang)) { + const preProcessor = preProcessors[lang]; + let opts = (preprocessorOptions && preprocessorOptions[lang]) || {}; + // support @import from node dependencies by default + switch (lang) { + case "scss" /* scss */: + case "sass" /* sass */: + opts = Object.assign({ includePaths: ['node_modules'], alias: config.resolve.alias }, opts); + break; + case "less" /* less */: + case "styl" /* styl */: + case "stylus" /* stylus */: + opts = Object.assign({ paths: ['node_modules'], alias: config.resolve.alias }, opts); + } + // important: set this for relative import resolving + opts.filename = utils_1.cleanUrl(id); + const preprocessResult = yield preProcessor(code, config.root, opts, atImportResolvers); + if (preprocessResult.errors.length) { + throw preprocessResult.errors[0]; + } + code = preprocessResult.code; + map = preprocessResult.map; + if (preprocessResult.deps) { + preprocessResult.deps.forEach((dep) => { + // sometimes sass registers the file itself as a dep + if (utils_1.normalizePath(dep) !== utils_1.normalizePath(opts.filename)) { + deps.add(dep); + } + }); + } + } + // 3. postcss + const postcssOptions = (postcssConfig && postcssConfig.options) || {}; + const postcssPlugins = postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : []; + if (needInlineImport) { + postcssPlugins.unshift((yield Promise.resolve().then(() => __importStar(require('postcss-import')))).default({ + resolve(id, basedir) { + return __awaiter(this, void 0, void 0, function* () { + const resolved = yield atImportResolvers.css(id, path_1.default.join(basedir, '*')); + if (resolved) { + return path_1.default.resolve(resolved); + } + return id; + }); + }, + })); + } + postcssPlugins.push(UrlRewritePostcssPlugin({ + replacer: urlReplacer, + })); + if (isModule) { + postcssPlugins.unshift((yield Promise.resolve().then(() => __importStar(require('postcss-modules')))).default(Object.assign(Object.assign({}, modulesOptions), { getJSON(cssFileName, _modules, outputFileName) { + modules = _modules; + if (modulesOptions && typeof modulesOptions.getJSON === 'function') { + modulesOptions.getJSON(cssFileName, _modules, outputFileName); + } + } }))); + } + if (!postcssPlugins.length) { + return { + code, + map, + }; + } + // postcss is an unbundled dep and should be lazy imported + const postcssResult = yield (yield Promise.resolve().then(() => __importStar(require('postcss')))) + .default(postcssPlugins) + .process(code, Object.assign(Object.assign({}, postcssOptions), { to: id, from: id, map: { + inline: false, + annotation: false, + prev: map, + } })); + // record CSS dependencies from @imports + for (const message of postcssResult.messages) { + if (message.type === 'dependency') { + deps.add(message.file); + } + else if (message.type === 'dir-dependency') { + // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies + const { dir, glob: globPattern = '**' } = message; + const pattern = utils_1.normalizePath(path_1.default.resolve(path_1.default.dirname(id), dir)) + `/` + globPattern; + const files = fast_glob_1.default.sync(pattern, { + ignore: ['**/node_modules/**'], + }); + for (let i = 0; i < files.length; i++) { + deps.add(files[i]); + } + if (server) { + // register glob importers so we can trigger updates on file add/remove + if (!(id in server._globImporters)) { + ; + server._globImporters[id] = { + module: server.moduleGraph.getModuleById(id), + importGlobs: [], + }; + } + ; + server._globImporters[id].importGlobs.push({ + base: config.root, + pattern, + }); + } + } + else if (message.type === 'warning') { + let msg = `[vite:css] ${message.text}`; + if (message.line && message.column) { + msg += `\n${utils_1.generateCodeFrame(code, { + line: message.line, + column: message.column, + })}`; + } + config.logger.warn(chalk_1.default.yellow(msg)); + } + } + return { + ast: postcssResult, + code: postcssResult.css, + map: postcssResult.map, + modules, + deps, + }; + }); +} +let cachedPostcssConfig; +function resolvePostcssConfig(config) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + if (cachedPostcssConfig !== undefined) { + return cachedPostcssConfig; + } + // inline postcss config via vite config + const inlineOptions = (_a = config.css) === null || _a === void 0 ? void 0 : _a.postcss; + if (utils_1.isObject(inlineOptions)) { + const result = { + options: Object.assign({}, inlineOptions), + plugins: inlineOptions.plugins || [], + }; + delete result.options.plugins; + return (cachedPostcssConfig = result); + } + try { + const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root; + // @ts-ignore + return (cachedPostcssConfig = yield postcss_load_config_1.default({}, searchPath)); + } + catch (e) { + if (!/No PostCSS Config found/.test(e.message)) { + throw e; + } + return (cachedPostcssConfig = null); + } + }); +} +// https://drafts.csswg.org/css-syntax-3/#identifier-code-point +exports.cssUrlRE = /(?<=^|[^\w\-\u0080-\uffff])url\(\s*('[^']+'|"[^"]+"|[^'")]+)\s*\)/; +const cssImageSetRE = /image-set\(([^)]+)\)/; +const UrlRewritePostcssPlugin = (opts) => { + if (!opts) { + throw new Error('base or replace is required'); + } + return { + postcssPlugin: 'vite-url-rewrite', + Once(root) { + const promises = []; + root.walkDecls((declaration) => { + const isCssUrl = exports.cssUrlRE.test(declaration.value); + const isCssImageSet = cssImageSetRE.test(declaration.value); + if (isCssUrl || isCssImageSet) { + const replacerForDeclaration = (rawUrl) => { + var _a; + const importer = (_a = declaration.source) === null || _a === void 0 ? void 0 : _a.input.file; + return opts.replacer(rawUrl, importer); + }; + const rewriterToUse = isCssUrl ? rewriteCssUrls : rewriteCssImageSet; + promises.push(rewriterToUse(declaration.value, replacerForDeclaration).then((url) => { + declaration.value = url; + })); + } + }); + if (promises.length) { + return Promise.all(promises); + } + }, + }; +}; +UrlRewritePostcssPlugin.postcss = true; +function rewriteCssUrls(css, replacer) { + return utils_1.asyncReplace(css, exports.cssUrlRE, (match) => __awaiter(this, void 0, void 0, function* () { + const [matched, rawUrl] = match; + return yield doUrlReplace(rawUrl, matched, replacer); + })); +} +function rewriteCssImageSet(css, replacer) { + return utils_1.asyncReplace(css, cssImageSetRE, (match) => __awaiter(this, void 0, void 0, function* () { + const [matched, rawUrl] = match; + const url = yield utils_1.processSrcSet(rawUrl, ({ url }) => doUrlReplace(url, matched, replacer)); + return `image-set(${url})`; + })); +} +function doUrlReplace(rawUrl, matched, replacer) { + return __awaiter(this, void 0, void 0, function* () { + let wrap = ''; + const first = rawUrl[0]; + if (first === `"` || first === `'`) { + wrap = first; + rawUrl = rawUrl.slice(1, -1); + } + if (utils_1.isExternalUrl(rawUrl) || utils_1.isDataUrl(rawUrl) || rawUrl.startsWith('#')) { + return matched; + } + return `url(${wrap}${yield replacer(rawUrl)}${wrap})`; + }); +} +let CleanCSS; +function minifyCSS(css, config) { + return __awaiter(this, void 0, void 0, function* () { + CleanCSS = CleanCSS || (yield Promise.resolve().then(() => __importStar(require('clean-css')))).default; + const res = new CleanCSS(Object.assign({ rebase: false }, config.build.cleanCssOptions)).minify(css); + if (res.errors && res.errors.length) { + config.logger.error(chalk_1.default.red(`error when minifying css:\n${res.errors}`)); + throw res.errors[0]; + } + // do not warn on remote @imports + const warnings = res.warnings && + res.warnings.filter((m) => !m.includes('remote @import')); + if (warnings && warnings.length) { + config.logger.warn(chalk_1.default.yellow(`warnings when minifying css:\n${warnings.join('\n')}`)); + } + return res.styles; + }); +} +// #1845 +// CSS @import can only appear at top of the file. We need to hoist all @import +// to top when multiple files are concatenated. +function hoistAtImports(css) { + return __awaiter(this, void 0, void 0, function* () { + const postcss = yield Promise.resolve().then(() => __importStar(require('postcss'))); + return (yield postcss.default([AtImportHoistPlugin]).process(css)).css; + }); +} +const AtImportHoistPlugin = () => { + return { + postcssPlugin: 'vite-hoist-at-imports', + Once(root) { + const imports = []; + root.walkAtRules((rule) => { + if (rule.name === 'import') { + // record in reverse so that can simply prepend to preserve order + imports.unshift(rule); + } + }); + imports.forEach((i) => root.prepend(i)); + }, + }; +}; +AtImportHoistPlugin.postcss = true; +const loadedPreprocessors = {}; +function loadPreprocessor(lang, root) { + if (lang in loadedPreprocessors) { + return loadedPreprocessors[lang]; + } + try { + // Search for the preprocessor in the root directory first, and fall back + // to the default require paths. + const fallbackPaths = require.resolve.paths(lang) || []; + const resolved = require.resolve(lang, { paths: [root, ...fallbackPaths] }); + return (loadedPreprocessors[lang] = require(resolved)); + } + catch (e) { + throw new Error(`Preprocessor dependency "${lang}" not found. Did you install it?`); + } +} +// .scss/.sass processor +const scss = (source, root, options, resolvers) => __awaiter(void 0, void 0, void 0, function* () { + const render = loadPreprocessor("sass" /* sass */, root).render; + const internalImporter = (url, importer, done) => { + resolvers.sass(url, importer).then((resolved) => { + if (resolved) { + rebaseUrls(resolved, options.filename, options.alias).then(done); + } + else { + done(null); + } + }); + }; + const importer = [internalImporter]; + if (options.importer) { + Array.isArray(options.importer) + ? importer.push(...options.importer) + : importer.push(options.importer); + } + const finalOptions = Object.assign(Object.assign({}, options), { data: yield getSource(source, options.filename, options.additionalData), file: options.filename, outFile: options.filename, importer }); + try { + const result = yield new Promise((resolve, reject) => { + render(finalOptions, (err, res) => { + if (err) { + reject(err); + } + else { + resolve(res); + } + }); + }); + const deps = result.stats.includedFiles; + return { + code: result.css.toString(), + errors: [], + deps, + }; + } + catch (e) { + // normalize SASS error + e.id = e.file; + e.frame = e.formatted; + return { code: '', errors: [e], deps: [] }; + } +}); +const sass = (source, root, options, aliasResolver) => scss(source, root, Object.assign(Object.assign({}, options), { indentedSyntax: true }), aliasResolver); +/** + * relative url() inside \@imported sass and less files must be rebased to use + * root file as base. + */ +function rebaseUrls(file, rootFile, alias) { + return __awaiter(this, void 0, void 0, function* () { + file = path_1.default.resolve(file); // ensure os-specific flashes + // in the same dir, no need to rebase + const fileDir = path_1.default.dirname(file); + const rootDir = path_1.default.dirname(rootFile); + if (fileDir === rootDir) { + return { file }; + } + // no url() + const content = fs_1.default.readFileSync(file, 'utf-8'); + if (!exports.cssUrlRE.test(content)) { + return { file }; + } + const rebased = yield rewriteCssUrls(content, (url) => { + if (url.startsWith('/')) + return url; + // match alias, no need to rewrite + for (const { find } of alias) { + const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url); + if (matches) { + return url; + } + } + const absolute = path_1.default.resolve(fileDir, url); + const relative = path_1.default.relative(rootDir, absolute); + return utils_1.normalizePath(relative); + }); + return { + file, + contents: rebased, + }; + }); +} +// .less +const less = (source, root, options, resolvers) => __awaiter(void 0, void 0, void 0, function* () { + const nodeLess = loadPreprocessor("less" /* less */, root); + const viteResolverPlugin = createViteLessPlugin(nodeLess, options.filename, options.alias, resolvers); + source = yield getSource(source, options.filename, options.additionalData); + let result; + try { + result = yield nodeLess.render(source, Object.assign(Object.assign({}, options), { plugins: [viteResolverPlugin, ...(options.plugins || [])] })); + } + catch (e) { + const error = e; + // normalize error info + const normalizedError = new Error(error.message || error.type); + normalizedError.loc = { + file: error.filename || options.filename, + line: error.line, + column: error.column, + }; + return { code: '', errors: [normalizedError], deps: [] }; + } + return { + code: result.css.toString(), + deps: result.imports, + errors: [], + }; +}); +/** + * Less manager, lazy initialized + */ +let ViteLessManager; +function createViteLessPlugin(less, rootFile, alias, resolvers) { + if (!ViteLessManager) { + ViteLessManager = class ViteManager extends less.FileManager { + constructor(rootFile, resolvers, alias) { + super(); + this.rootFile = rootFile; + this.resolvers = resolvers; + this.alias = alias; + } + supports() { + return true; + } + supportsSync() { + return false; + } + loadFile(filename, dir, opts, env) { + const _super = Object.create(null, { + loadFile: { get: () => super.loadFile } + }); + return __awaiter(this, void 0, void 0, function* () { + const resolved = yield this.resolvers.less(filename, path_1.default.join(dir, '*')); + if (resolved) { + const result = yield rebaseUrls(resolved, this.rootFile, this.alias); + let contents; + if (result && 'contents' in result) { + contents = result.contents; + } + else { + contents = fs_1.default.readFileSync(resolved, 'utf-8'); + } + return { + filename: path_1.default.resolve(resolved), + contents, + }; + } + else { + return _super.loadFile.call(this, filename, dir, opts, env); + } + }); + } + }; + } + return { + install(_, pluginManager) { + pluginManager.addFileManager(new ViteLessManager(rootFile, resolvers, alias)); + }, + minVersion: [3, 0, 0], + }; +} +// .styl +const styl = (source, root, options) => __awaiter(void 0, void 0, void 0, function* () { + var _a; + const nodeStylus = loadPreprocessor("stylus" /* stylus */, root); + // Get source with preprocessor options.additionalData. Make sure a new line separator + // is added to avoid any render error, as added stylus content may not have semi-colon separators + source = yield getSource(source, options.filename, options.additionalData, '\n'); + // Get preprocessor options.imports dependencies as stylus + // does not return them with its builtin `.deps()` method + const importsDeps = ((_a = options.imports) !== null && _a !== void 0 ? _a : []).map((dep) => path_1.default.resolve(dep)); + try { + const ref = nodeStylus(source, options); + // if (map) ref.set('sourcemap', { inline: false, comment: false }) + const result = ref.render(); + // Concat imports deps with computed deps + const deps = [...ref.deps(), ...importsDeps]; + return { code: result, errors: [], deps }; + } + catch (e) { + return { code: '', errors: [e], deps: [] }; + } +}); +function getSource(source, filename, additionalData, sep = '') { + if (!additionalData) + return source; + if (typeof additionalData === 'function') { + return additionalData(source, filename); + } + return additionalData + sep + source; +} +const preProcessors = Object.freeze({ + ["less" /* less */]: less, + ["sass" /* sass */]: sass, + ["scss" /* scss */]: scss, + ["styl" /* styl */]: styl, + ["stylus" /* stylus */]: styl, +}); +function isPreProcessor(lang) { + return lang && lang in preProcessors; +} diff --git a/packages/uni-app-vite/dist/plugins/vitejs/utils.js b/packages/uni-app-vite/dist/plugins/vitejs/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..e34b9f0cb6e8aeeae4e6011fc13be19567eddea6 --- /dev/null +++ b/packages/uni-app-vite/dist/plugins/vitejs/utils.js @@ -0,0 +1,142 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.processSrcSet = exports.generateCodeFrame = exports.posToNumber = exports.pad = exports.isObject = exports.asyncReplace = exports.isDataUrl = exports.dataUrlRE = exports.isExternalUrl = exports.externalRE = exports.cleanUrl = exports.hashRE = exports.queryRE = exports.normalizePath = exports.isWindows = exports.deepImportRE = exports.bareImportRE = exports.slash = void 0; +/** + * https://github.com/vitejs/vite/blob/main/packages/vite/src/node/utils.ts + */ +const os_1 = __importDefault(require("os")); +const path_1 = __importDefault(require("path")); +function slash(p) { + return p.replace(/\\/g, '/'); +} +exports.slash = slash; +exports.bareImportRE = /^[\w@](?!.*:\/\/)/; +exports.deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//; +exports.isWindows = os_1.default.platform() === 'win32'; +function normalizePath(id) { + return path_1.default.posix.normalize(exports.isWindows ? slash(id) : id); +} +exports.normalizePath = normalizePath; +exports.queryRE = /\?.*$/s; +exports.hashRE = /#.*$/s; +const cleanUrl = (url) => url.replace(exports.hashRE, '').replace(exports.queryRE, ''); +exports.cleanUrl = cleanUrl; +exports.externalRE = /^(https?:)?\/\//; +const isExternalUrl = (url) => exports.externalRE.test(url); +exports.isExternalUrl = isExternalUrl; +exports.dataUrlRE = /^\s*data:/i; +const isDataUrl = (url) => exports.dataUrlRE.test(url); +exports.isDataUrl = isDataUrl; +function asyncReplace(input, re, replacer) { + return __awaiter(this, void 0, void 0, function* () { + let match; + let remaining = input; + let rewritten = ''; + while ((match = re.exec(remaining))) { + rewritten += remaining.slice(0, match.index); + rewritten += yield replacer(match); + remaining = remaining.slice(match.index + match[0].length); + } + rewritten += remaining; + return rewritten; + }); +} +exports.asyncReplace = asyncReplace; +function isObject(value) { + return Object.prototype.toString.call(value) === '[object Object]'; +} +exports.isObject = isObject; +const splitRE = /\r?\n/; +const range = 2; +function pad(source, n = 2) { + const lines = source.split(splitRE); + return lines.map((l) => ` `.repeat(n) + l).join(`\n`); +} +exports.pad = pad; +function posToNumber(source, pos) { + if (typeof pos === 'number') + return pos; + const lines = source.split(splitRE); + const { line, column } = pos; + let start = 0; + for (let i = 0; i < line - 1; i++) { + start += lines[i].length + 1; + } + return start + column; +} +exports.posToNumber = posToNumber; +function generateCodeFrame(source, start = 0, end) { + start = posToNumber(source, start); + end = end || start; + const lines = source.split(splitRE); + let count = 0; + const res = []; + for (let i = 0; i < lines.length; i++) { + count += lines[i].length + 1; + if (count >= start) { + for (let j = i - range; j <= i + range || end > count; j++) { + if (j < 0 || j >= lines.length) + continue; + const line = j + 1; + res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`); + const lineLength = lines[j].length; + if (j === i) { + // push underline + const pad = start - (count - lineLength) + 1; + const length = Math.max(1, end > count ? lineLength - pad : end - start); + res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)); + } + else if (j > i) { + if (end > count) { + const length = Math.max(Math.min(end - count, lineLength), 1); + res.push(` | ` + '^'.repeat(length)); + } + count += lineLength + 1; + } + } + break; + } + } + return res.join('\n'); +} +exports.generateCodeFrame = generateCodeFrame; +const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g; +function processSrcSet(srcs, replacer) { + return __awaiter(this, void 0, void 0, function* () { + const imageCandidates = srcs + .split(',') + .map((s) => { + const [url, descriptor] = s + .replace(escapedSpaceCharacters, ' ') + .trim() + .split(' ', 2); + return { url, descriptor }; + }) + .filter(({ url }) => !!url); + const ret = yield Promise.all(imageCandidates.map(({ url, descriptor }) => __awaiter(this, void 0, void 0, function* () { + return { + url: yield replacer({ url, descriptor }), + descriptor, + }; + }))); + const url = ret.reduce((prev, { url, descriptor }, index) => { + descriptor = descriptor || ''; + return (prev += + url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`); + }, ''); + return url; + }); +} +exports.processSrcSet = processSrcSet; diff --git a/packages/uni-app-vite/lib/require.js b/packages/uni-app-vite/lib/require.js new file mode 100644 index 0000000000000000000000000000000000000000..3458a83e3a348a28da9f1ab485ba82a4a258c601 --- /dev/null +++ b/packages/uni-app-vite/lib/require.js @@ -0,0 +1,1751 @@ +var require, define; +(function (global) { + var req, + interactiveScript, currentlyAddingScript, + version = '2.3.6', + commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/mg, + cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, + jsSuffixRegExp = /\.js$/, + currDirRegExp = /^\.\//, + op = Object.prototype, + ostring = op.toString, + hasOwn = op.hasOwnProperty, + //PS3 indicates loaded and complete, but need to wait for complete + //specifically. Sequence is 'loading', 'loaded', execution, + // then 'complete'. The UA check is unfortunate, but not sure how + //to feature test w/o causing perf issues. + defContextName = '_', + //Oh the tragedy, detecting opera. See the usage of isOpera for reason. + isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', + contexts = {}, + cfg = {}, + globalDefQueue = [], + useInteractive = false; + + //Could match something like ')//comment', do not lose the prefix to comment. + function commentReplace(match, singlePrefix) { + return singlePrefix || ''; + } + + function isFunction(it) { + return ostring.call(it) === '[object Function]'; + } + + function isArray(it) { + return ostring.call(it) === '[object Array]'; + } + + /** + * Helper function for iterating over an array. If the func returns + * a true value, it will break out of the loop. + */ + function each(ary, func) { + if (ary) { + var i; + for (i = 0; i < ary.length; i += 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } + } + } + } + + /** + * Helper function for iterating over an array backwards. If the func + * returns a true value, it will break out of the loop. + */ + function eachReverse(ary, func) { + if (ary) { + var i; + for (i = ary.length - 1; i > -1; i -= 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } + } + } + } + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + function getOwn(obj, prop) { + return hasProp(obj, prop) && obj[prop]; + } + + /** + * Cycles over properties in an object and calls a function for each + * property value. If the function returns a truthy value, then the + * iteration is stopped. + */ + function eachProp(obj, func) { + var prop; + for (prop in obj) { + if (hasProp(obj, prop)) { + if (func(obj[prop], prop)) { + break; + } + } + } + } + + /** + * Simple function to mix in properties from source into target, + * but only if target does not already have a property of the same name. + */ + function mixin(target, source, force, deepStringMixin) { + if (source) { + eachProp(source, function (value, prop) { + if (force || !hasProp(target, prop)) { + if (deepStringMixin && typeof value === 'object' && value && + !isArray(value) && !isFunction(value) && + !(value instanceof RegExp)) { + + if (!target[prop]) { + target[prop] = {}; + } + mixin(target[prop], value, force, deepStringMixin); + } else { + target[prop] = value; + } + } + }); + } + return target; + } + + //Similar to Function.prototype.bind, but the 'this' object is specified + //first, since it is easier to read/figure out what 'this' will be. + function bind(obj, fn) { + return function () { + return fn.apply(obj, arguments); + }; + } + + function defaultOnError(err) { + throw err; + } + + //Allow getting a global that is expressed in + //dot notation, like 'a.b.c'. + function getGlobal(value) { + if (!value) { + return value; + } + var g = global; + each(value.split('.'), function (part) { + g = g[part]; + }); + return g; + } + + /** + * Constructs an error with a pointer to an URL with more information. + * @param {String} id the error ID that maps to an ID on a web page. + * @param {String} message human readable error. + * @param {Error} [err] the original error, if there is one. + * + * @returns {Error} + */ + function makeError(id, msg, err, requireModules) { + var e = new Error(msg + '\nhttps://requirejs.org/docs/errors.html#' + id); + e.requireType = id; + e.requireModules = requireModules; + if (err) { + e.originalError = err; + } + return e; + } + + function newContext(contextName) { + var inCheckLoaded, Module, context, handlers, + checkLoadedTimeoutId, + config = { + //Defaults. Do not set a default for map + //config to speed up normalize(), which + //will run faster if there is no default. + waitSeconds: 7, + baseUrl: './', + paths: {}, + bundles: {}, + pkgs: {}, + shim: {}, + config: {} + }, + registry = {}, + //registry of just enabled modules, to speed + //cycle breaking code when lots of modules + //are registered, but not activated. + enabledRegistry = {}, + undefEvents = {}, + defQueue = [], + defined = {}, + urlFetched = {}, + bundlesMap = {}, + requireCounter = 1, + unnormalizedCounter = 1; + + /** + * Trims the . and .. from an array of path segments. + * It will keep a leading path segment if a .. will become + * the first path segment, to help with module name lookups, + * which act like paths, but can be remapped. But the end result, + * all paths that use this function should look normalized. + * NOTE: this method MODIFIES the input array. + * @param {Array} ary the array of path segments. + */ + function trimDots(ary) { + var i, part; + for (i = 0; i < ary.length; i++) { + part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + // If at the start, or previous value is still .., + // keep them so that when converted to a path it may + // still work when converted to a path, even though + // as an ID it is less than ideal. In larger point + // releases, may be better to just kick out an error. + if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') { + continue; + } else if (i > 0) { + ary.splice(i - 1, 2); + i -= 2; + } + } + } + } + + /** + * Given a relative module name, like ./something, normalize it to + * a real name that can be mapped to a path. + * @param {String} name the relative name + * @param {String} baseName a real name that the name arg is relative + * to. + * @param {Boolean} applyMap apply the map config to the value. Should + * only be done if this normalization is for a dependency ID. + * @returns {String} normalized name + */ + function normalize(name, baseName, applyMap) { + var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, + foundMap, foundI, foundStarMap, starI, normalizedBaseParts, + baseParts = (baseName && baseName.split('/')), + map = config.map, + starMap = map && map['*']; + + //Adjust any relative paths. + if (name) { + name = name.split('/'); + lastIndex = name.length - 1; + + // If wanting node ID compatibility, strip .js from end + // of IDs. Have to do this here, and not in nameToUrl + // because node allows either .js or non .js to map + // to same file. + if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { + name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); + } + + // Starts with a '.' so need the baseName + if (name[0].charAt(0) === '.' && baseParts) { + //Convert baseName to array, and lop off the last part, + //so that . matches that 'directory' and not name of the baseName's + //module. For instance, baseName of 'one/two/three', maps to + //'one/two/three.js', but we want the directory, 'one/two' for + //this normalization. + normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); + name = normalizedBaseParts.concat(name); + } + + trimDots(name); + name = name.join('/'); + } + + //Apply map config if available. + if (applyMap && map && (baseParts || starMap)) { + nameParts = name.split('/'); + + outerLoop: for (i = nameParts.length; i > 0; i -= 1) { + nameSegment = nameParts.slice(0, i).join('/'); + + if (baseParts) { + //Find the longest baseName segment match in the config. + //So, do joins on the biggest to smallest lengths of baseParts. + for (j = baseParts.length; j > 0; j -= 1) { + mapValue = getOwn(map, baseParts.slice(0, j).join('/')); + + //baseName segment has config, find if it has one for + //this name. + if (mapValue) { + mapValue = getOwn(mapValue, nameSegment); + if (mapValue) { + //Match, update name to the new value. + foundMap = mapValue; + foundI = i; + break outerLoop; + } + } + } + } + + //Check for a star map match, but just hold on to it, + //if there is a shorter segment match later in a matching + //config, then favor over this star map. + if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { + foundStarMap = getOwn(starMap, nameSegment); + starI = i; + } + } + + if (!foundMap && foundStarMap) { + foundMap = foundStarMap; + foundI = starI; + } + + if (foundMap) { + nameParts.splice(0, foundI, foundMap); + name = nameParts.join('/'); + } + } + + // If the name points to a package's name, use + // the package main instead. + pkgMain = getOwn(config.pkgs, name); + + return pkgMain ? pkgMain : name; + } + + function removeScript(name) { + + } + + function hasPathFallback(id) { + var pathConfig = getOwn(config.paths, id); + if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { + //Pop off the first array value, since it failed, and + //retry + pathConfig.shift(); + context.require.undef(id); + + //Custom require that does not do map translation, since + //ID is "absolute", already mapped/resolved. + context.makeRequire(null, { + skipMap: true + })([id]); + + return true; + } + } + + //Turns a plugin!resource to [plugin, resource] + //with the plugin being undefined if the name + //did not have a plugin prefix. + function splitPrefix(name) { + var prefix, + index = name ? name.indexOf('!') : -1; + if (index > -1) { + prefix = name.substring(0, index); + name = name.substring(index + 1, name.length); + } + return [prefix, name]; + } + + /** + * Creates a module mapping that includes plugin prefix, module + * name, and path. If parentModuleMap is provided it will + * also normalize the name via require.normalize() + * + * @param {String} name the module name + * @param {String} [parentModuleMap] parent module map + * for the module name, used to resolve relative names. + * @param {Boolean} isNormalized: is the ID already normalized. + * This is true if this call is done for a define() module ID. + * @param {Boolean} applyMap: apply the map config to the ID. + * Should only be true if this map is for a dependency. + * + * @returns {Object} + */ + function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { + var url, pluginModule, suffix, nameParts, + prefix = null, + parentName = parentModuleMap ? parentModuleMap.name : null, + originalName = name, + isDefine = true, + normalizedName = ''; + + //If no name, then it means it is a require call, generate an + //internal name. + if (!name) { + isDefine = false; + name = '_@r' + (requireCounter += 1); + } + + nameParts = splitPrefix(name); + prefix = nameParts[0]; + name = nameParts[1]; + + if (prefix) { + prefix = normalize(prefix, parentName, applyMap); + pluginModule = getOwn(defined, prefix); + } + + //Account for relative paths if there is a base name. + if (name) { + if (prefix) { + if (isNormalized) { + normalizedName = name; + } else if (pluginModule && pluginModule.normalize) { + //Plugin is loaded, use its normalize method. + normalizedName = pluginModule.normalize(name, function (name) { + return normalize(name, parentName, applyMap); + }); + } else { + // If nested plugin references, then do not try to + // normalize, as it will not normalize correctly. This + // places a restriction on resourceIds, and the longer + // term solution is not to normalize until plugins are + // loaded and all normalizations to allow for async + // loading of a loader plugin. But for now, fixes the + // common uses. Details in #1131 + normalizedName = name.indexOf('!') === -1 ? + normalize(name, parentName, applyMap) : + name; + } + } else { + //A regular module. + normalizedName = normalize(name, parentName, applyMap); + + //Normalized name may be a plugin ID due to map config + //application in normalize. The map config values must + //already be normalized, so do not need to redo that part. + nameParts = splitPrefix(normalizedName); + prefix = nameParts[0]; + normalizedName = nameParts[1]; + isNormalized = true; + + url = context.nameToUrl(normalizedName); + } + } + + //If the id is a plugin id that cannot be determined if it needs + //normalization, stamp it with a unique ID so two matching relative + //ids that may conflict can be separate. + suffix = prefix && !pluginModule && !isNormalized ? + '_unnormalized' + (unnormalizedCounter += 1) : + ''; + + return { + prefix: prefix, + name: normalizedName, + parentMap: parentModuleMap, + unnormalized: !!suffix, + url: url, + originalName: originalName, + isDefine: isDefine, + id: (prefix ? + prefix + '!' + normalizedName : + normalizedName) + suffix + }; + } + + function getModule(depMap) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (!mod) { + mod = registry[id] = new context.Module(depMap); + } + + return mod; + } + + function on(depMap, name, fn) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (hasProp(defined, id) && + (!mod || mod.defineEmitComplete)) { + if (name === 'defined') { + fn(defined[id]); + } + } else { + mod = getModule(depMap); + if (mod.error && name === 'error') { + fn(mod.error); + } else { + mod.on(name, fn); + } + } + } + + function onError(err, errback) { + var ids = err.requireModules, + notified = false; + + if (errback) { + errback(err); + } else { + each(ids, function (id) { + var mod = getOwn(registry, id); + if (mod) { + //Set error on module, so it skips timeout checks. + mod.error = err; + if (mod.events.error) { + notified = true; + mod.emit('error', err); + } + } + }); + + if (!notified) { + req.onError(err); + } + } + } + + /** + * Internal method to transfer globalQueue items to this context's + * defQueue. + */ + function takeGlobalQueue() { + //Push all the globalDefQueue items into the context's defQueue + if (globalDefQueue.length) { + each(globalDefQueue, function(queueItem) { + var id = queueItem[0]; + if (typeof id === 'string') { + context.defQueueMap[id] = true; + } + defQueue.push(queueItem); + }); + globalDefQueue = []; + } + } + + handlers = { + 'require': function (mod) { + if (mod.require) { + return mod.require; + } else { + return (mod.require = context.makeRequire(mod.map)); + } + }, + 'exports': function (mod) { + mod.usingExports = true; + if (mod.map.isDefine) { + if (mod.exports) { + return (defined[mod.map.id] = mod.exports); + } else { + return (mod.exports = defined[mod.map.id] = {}); + } + } + }, + 'module': function (mod) { + if (mod.module) { + return mod.module; + } else { + return (mod.module = { + id: mod.map.id, + uri: mod.map.url, + config: function () { + return getOwn(config.config, mod.map.id) || {}; + }, + exports: mod.exports || (mod.exports = {}) + }); + } + } + }; + + function cleanRegistry(id) { + //Clean up machinery used for waiting modules. + delete registry[id]; + delete enabledRegistry[id]; + } + + function breakCycle(mod, traced, processed) { + var id = mod.map.id; + + if (mod.error) { + mod.emit('error', mod.error); + } else { + traced[id] = true; + each(mod.depMaps, function (depMap, i) { + var depId = depMap.id, + dep = getOwn(registry, depId); + + //Only force things that have not completed + //being defined, so still in the registry, + //and only if it has not been matched up + //in the module already. + if (dep && !mod.depMatched[i] && !processed[depId]) { + if (getOwn(traced, depId)) { + mod.defineDep(i, defined[depId]); + mod.check(); //pass false? + } else { + breakCycle(dep, traced, processed); + } + } + }); + processed[id] = true; + } + } + + function checkLoaded() { + var err, usingPathFallback, + waitInterval = config.waitSeconds * 1000, + //It is possible to disable the wait interval by using waitSeconds of 0. + expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), + noLoads = [], + reqCalls = [], + stillLoading = false, + needCycleCheck = true; + + //Do not bother if this call was a result of a cycle break. + if (inCheckLoaded) { + return; + } + + inCheckLoaded = true; + + //Figure out the state of all the modules. + eachProp(enabledRegistry, function (mod) { + var map = mod.map, + modId = map.id; + + //Skip things that are not enabled or in error state. + if (!mod.enabled) { + return; + } + + if (!map.isDefine) { + reqCalls.push(mod); + } + + if (!mod.error) { + //If the module should be executed, and it has not + //been inited and time is up, remember it. + if (!mod.inited && expired) { + if (hasPathFallback(modId)) { + usingPathFallback = true; + stillLoading = true; + } else { + noLoads.push(modId); + removeScript(modId); + } + } else if (!mod.inited && mod.fetched && map.isDefine) { + stillLoading = true; + if (!map.prefix) { + //No reason to keep looking for unfinished + //loading. If the only stillLoading is a + //plugin resource though, keep going, + //because it may be that a plugin resource + //is waiting on a non-plugin cycle. + return (needCycleCheck = false); + } + } + } + }); + + if (expired && noLoads.length) { + //If wait time expired, throw error of unloaded modules. + err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); + err.contextName = context.contextName; + return onError(err); + } + + //Not expired, check for a cycle. + if (needCycleCheck) { + each(reqCalls, function (mod) { + breakCycle(mod, {}, {}); + }); + } + + //If still waiting on loads, and the waiting load is something + //other than a plugin resource, or there are still outstanding + //scripts, then just try back later. + if ((!expired || usingPathFallback) && stillLoading) { + //Something is still waiting to load. Wait for it, but only + //if a timeout is not already in effect. + if (!checkLoadedTimeoutId) { + checkLoadedTimeoutId = setTimeout(function () { + checkLoadedTimeoutId = 0; + checkLoaded(); + }, 50); + } + } + + inCheckLoaded = false; + } + + Module = function (map) { + this.events = getOwn(undefEvents, map.id) || {}; + this.map = map; + this.shim = getOwn(config.shim, map.id); + this.depExports = []; + this.depMaps = []; + this.depMatched = []; + this.pluginMaps = {}; + this.depCount = 0; + + /* this.exports this.factory + this.depMaps = [], + this.enabled, this.fetched + */ + }; + + Module.prototype = { + init: function (depMaps, factory, errback, options) { + options = options || {}; + + //Do not do more inits if already done. Can happen if there + //are multiple define calls for the same module. That is not + //a normal, common case, but it is also not unexpected. + if (this.inited) { + return; + } + + this.factory = factory; + + if (errback) { + //Register for errors on this module. + this.on('error', errback); + } else if (this.events.error) { + //If no errback already, but there are error listeners + //on this module, set up an errback to pass to the deps. + errback = bind(this, function (err) { + this.emit('error', err); + }); + } + + //Do a copy of the dependency array, so that + //source inputs are not modified. For example + //"shim" deps are passed in here directly, and + //doing a direct modification of the depMaps array + //would affect that config. + this.depMaps = depMaps && depMaps.slice(0); + + this.errback = errback; + + //Indicate this module has be initialized + this.inited = true; + + this.ignore = options.ignore; + + //Could have option to init this module in enabled mode, + //or could have been previously marked as enabled. However, + //the dependencies are not known until init is called. So + //if enabled previously, now trigger dependencies as enabled. + if (options.enabled || this.enabled) { + //Enable this module and dependencies. + //Will call this.check() + this.enable(); + } else { + this.check(); + } + }, + + defineDep: function (i, depExports) { + //Because of cycles, defined callback for a given + //export can be called more than once. + if (!this.depMatched[i]) { + this.depMatched[i] = true; + this.depCount -= 1; + this.depExports[i] = depExports; + } + }, + + fetch: function () { + if (this.fetched) { + return; + } + this.fetched = true; + + context.startTime = (new Date()).getTime(); + + var map = this.map; + + return map.prefix ? this.callPlugin() : this.load(); + }, + + load: function () { + var url = this.map.url; + + //Regular dependency. + if (!urlFetched[url]) { + urlFetched[url] = true; + context.load(this.map.id, url); + } + }, + + /** + * Checks if the module is ready to define itself, and if so, + * define it. + */ + check: function () { + if (!this.enabled || this.enabling) { + return; + } + + var err, cjsModule, + id = this.map.id, + depExports = this.depExports, + exports = this.exports, + factory = this.factory; + + if (!this.inited) { + // Only fetch if not already in the defQueue. + if (!hasProp(context.defQueueMap, id)) { + this.fetch(); + } + } else if (this.error) { + this.emit('error', this.error); + } else if (!this.defining) { + //The factory could trigger another require call + //that would result in checking this module to + //define itself again. If already in the process + //of doing that, skip this work. + this.defining = true; + + if (this.depCount < 1 && !this.defined) { + if (isFunction(factory)) { + //If there is an error listener, favor passing + //to that instead of throwing an error. However, + //only do it for define()'d modules. require + //errbacks should not be called for failures in + //their callbacks (#699). However if a global + //onError is set, use that. + if ((this.events.error && this.map.isDefine) || + req.onError !== defaultOnError) { + try { + exports = context.execCb(id, factory, depExports, exports); + } catch (e) { + err = e; + } + } else { + exports = context.execCb(id, factory, depExports, exports); + } + + // Favor return value over exports. If node/cjs in play, + // then will not have a return value anyway. Favor + // module.exports assignment over exports object. + if (this.map.isDefine && exports === undefined) { + cjsModule = this.module; + if (cjsModule) { + exports = cjsModule.exports; + } else if (this.usingExports) { + //exports already set the defined value. + exports = this.exports; + } + } + + if (err) { + err.requireMap = this.map; + err.requireModules = this.map.isDefine ? [this.map.id] : null; + err.requireType = this.map.isDefine ? 'define' : 'require'; + return onError((this.error = err)); + } + + } else { + //Just a literal value + exports = factory; + } + + this.exports = exports; + + if (this.map.isDefine && !this.ignore) { + defined[id] = exports; + + if (req.onResourceLoad) { + var resLoadMaps = []; + each(this.depMaps, function (depMap) { + resLoadMaps.push(depMap.normalizedMap || depMap); + }); + req.onResourceLoad(context, this.map, resLoadMaps); + } + } + + //Clean up + cleanRegistry(id); + + this.defined = true; + } + + //Finished the define stage. Allow calling check again + //to allow define notifications below in the case of a + //cycle. + this.defining = false; + + if (this.defined && !this.defineEmitted) { + this.defineEmitted = true; + this.emit('defined', this.exports); + this.defineEmitComplete = true; + } + + } + }, + + callPlugin: function () { + var map = this.map, + id = map.id, + //Map already normalized the prefix. + pluginMap = makeModuleMap(map.prefix); + + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(pluginMap); + + on(pluginMap, 'defined', bind(this, function (plugin) { + var load, normalizedMap, normalizedMod, + bundleId = getOwn(bundlesMap, this.map.id), + name = this.map.name, + parentName = this.map.parentMap ? this.map.parentMap.name : null, + localRequire = context.makeRequire(map.parentMap, { + enableBuildCallback: true + }); + + //If current map is not normalized, wait for that + //normalized name to load instead of continuing. + if (this.map.unnormalized) { + //Normalize the ID if the plugin allows it. + if (plugin.normalize) { + name = plugin.normalize(name, function (name) { + return normalize(name, parentName, true); + }) || ''; + } + + //prefix and name should already be normalized, no need + //for applying map config again either. + normalizedMap = makeModuleMap(map.prefix + '!' + name, + this.map.parentMap, + true); + on(normalizedMap, + 'defined', bind(this, function (value) { + this.map.normalizedMap = normalizedMap; + this.init([], function () { return value; }, null, { + enabled: true, + ignore: true + }); + })); + + normalizedMod = getOwn(registry, normalizedMap.id); + if (normalizedMod) { + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(normalizedMap); + + if (this.events.error) { + normalizedMod.on('error', bind(this, function (err) { + this.emit('error', err); + })); + } + normalizedMod.enable(); + } + + return; + } + + //If a paths config, then just load that file instead to + //resolve the plugin, as it is built into that paths layer. + if (bundleId) { + this.map.url = context.nameToUrl(bundleId); + this.load(); + return; + } + + load = bind(this, function (value) { + this.init([], function () { return value; }, null, { + enabled: true + }); + }); + + load.error = bind(this, function (err) { + this.inited = true; + this.error = err; + err.requireModules = [id]; + + //Remove temp unnormalized modules for this module, + //since they will never be resolved otherwise now. + eachProp(registry, function (mod) { + if (mod.map.id.indexOf(id + '_unnormalized') === 0) { + cleanRegistry(mod.map.id); + } + }); + + onError(err); + }); + + //Use parentName here since the plugin's name is not reliable, + //could be some weird string with no path that actually wants to + //reference the parentName's path. + plugin.load(map.name, localRequire, load, config); + })); + + context.enable(pluginMap, this); + this.pluginMaps[pluginMap.id] = pluginMap; + }, + + enable: function () { + enabledRegistry[this.map.id] = this; + this.enabled = true; + + //Set flag mentioning that the module is enabling, + //so that immediate calls to the defined callbacks + //for dependencies do not trigger inadvertent load + //with the depCount still being zero. + this.enabling = true; + + //Enable each dependency + each(this.depMaps, bind(this, function (depMap, i) { + var id, mod, handler; + + if (typeof depMap === 'string') { + //Dependency needs to be converted to a depMap + //and wired up to this module. + depMap = makeModuleMap(depMap, + (this.map.isDefine ? this.map : this.map.parentMap), + false, + !this.skipMap); + this.depMaps[i] = depMap; + + handler = getOwn(handlers, depMap.id); + + if (handler) { + this.depExports[i] = handler(this); + return; + } + + this.depCount += 1; + + on(depMap, 'defined', bind(this, function (depExports) { + if (this.undefed) { + return; + } + this.defineDep(i, depExports); + this.check(); + })); + + if (this.errback) { + on(depMap, 'error', bind(this, this.errback)); + } else if (this.events.error) { + // No direct errback on this module, but something + // else is listening for errors, so be sure to + // propagate the error correctly. + on(depMap, 'error', bind(this, function(err) { + this.emit('error', err); + })); + } + } + + id = depMap.id; + mod = registry[id]; + + //Skip special modules like 'require', 'exports', 'module' + //Also, don't call enable if it is already enabled, + //important in circular dependency cases. + if (!hasProp(handlers, id) && mod && !mod.enabled) { + context.enable(depMap, this); + } + })); + + //Enable each plugin that is used in + //a dependency + eachProp(this.pluginMaps, bind(this, function (pluginMap) { + var mod = getOwn(registry, pluginMap.id); + if (mod && !mod.enabled) { + context.enable(pluginMap, this); + } + })); + + this.enabling = false; + + this.check(); + }, + + on: function (name, cb) { + var cbs = this.events[name]; + if (!cbs) { + cbs = this.events[name] = []; + } + cbs.push(cb); + }, + + emit: function (name, evt) { + each(this.events[name], function (cb) { + cb(evt); + }); + if (name === 'error') { + //Now that the error handler was triggered, remove + //the listeners, since this broken Module instance + //can stay around for a while in the registry. + delete this.events[name]; + } + } + }; + + function callGetModule(args) { + //Skip modules already defined. + if (!hasProp(defined, args[0])) { + getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); + } + } + + function removeListener(node, func, name, ieName) { + //Favor detachEvent because of IE9 + //issue, see attachEvent/addEventListener comment elsewhere + //in this file. + if (node.detachEvent && !isOpera) { + //Probably IE. If not it will throw an error, which will be + //useful to know. + if (ieName) { + node.detachEvent(ieName, func); + } + } else { + node.removeEventListener(name, func, false); + } + } + + function intakeDefines() { + var args; + + //Any defined modules in the global queue, intake them now. + takeGlobalQueue(); + + //Make sure any remaining defQueue items get properly processed. + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + + args[args.length - 1])); + } else { + //args are id, deps, factory. Should be normalized by the + //define() function. + callGetModule(args); + } + } + context.defQueueMap = {}; + } + + context = { + config: config, + contextName: contextName, + registry: registry, + defined: defined, + urlFetched: urlFetched, + defQueue: defQueue, + defQueueMap: {}, + Module: Module, + makeModuleMap: makeModuleMap, + nextTick: req.nextTick, + onError: onError, + + /** + * Set a configuration for the context. + * @param {Object} cfg config object to integrate. + */ + configure: function (cfg) { + //Make sure the baseUrl ends in a slash. + if (cfg.baseUrl) { + if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { + cfg.baseUrl += '/'; + } + } + + // Convert old style urlArgs string to a function. + if (typeof cfg.urlArgs === 'string') { + var urlArgs = cfg.urlArgs; + cfg.urlArgs = function(id, url) { + return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs; + }; + } + + //Save off the paths since they require special processing, + //they are additive. + var shim = config.shim, + objs = { + paths: true, + bundles: true, + config: true, + map: true + }; + + eachProp(cfg, function (value, prop) { + if (objs[prop]) { + if (!config[prop]) { + config[prop] = {}; + } + mixin(config[prop], value, true, true); + } else { + config[prop] = value; + } + }); + + //Reverse map the bundles + if (cfg.bundles) { + eachProp(cfg.bundles, function (value, prop) { + each(value, function (v) { + if (v !== prop) { + bundlesMap[v] = prop; + } + }); + }); + } + + //Merge shim + if (cfg.shim) { + eachProp(cfg.shim, function (value, id) { + //Normalize the structure + if (isArray(value)) { + value = { + deps: value + }; + } + if ((value.exports || value.init) && !value.exportsFn) { + value.exportsFn = context.makeShimExports(value); + } + shim[id] = value; + }); + config.shim = shim; + } + + //Adjust packages if necessary. + if (cfg.packages) { + each(cfg.packages, function (pkgObj) { + var location, name; + + pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj; + + name = pkgObj.name; + location = pkgObj.location; + if (location) { + config.paths[name] = pkgObj.location; + } + + //Save pointer to main module ID for pkg name. + //Remove leading dot in main, so main paths are normalized, + //and remove any trailing .js, since different package + //envs have different conventions: some use a module name, + //some use a file name. + config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') + .replace(currDirRegExp, '') + .replace(jsSuffixRegExp, ''); + }); + } + + //If there are any "waiting to execute" modules in the registry, + //update the maps for them, since their info, like URLs to load, + //may have changed. + eachProp(registry, function (mod, id) { + //If module already has init called, since it is too + //late to modify them, and ignore unnormalized ones + //since they are transient. + if (!mod.inited && !mod.map.unnormalized) { + mod.map = makeModuleMap(id, null, true); + } + }); + + //If a deps array or a config callback is specified, then call + //require with those args. This is useful when require is defined as a + //config object before require.js is loaded. + if (cfg.deps || cfg.callback) { + context.require(cfg.deps || [], cfg.callback); + } + }, + + makeShimExports: function (value) { + function fn() { + var ret; + if (value.init) { + ret = value.init.apply(global, arguments); + } + return ret || (value.exports && getGlobal(value.exports)); + } + return fn; + }, + + makeRequire: function (relMap, options) { + options = options || {}; + + function localRequire(deps, callback, errback) { + var id, map, requireMod; + + if (options.enableBuildCallback && callback && isFunction(callback)) { + callback.__requireJsBuild = true; + } + + if (typeof deps === 'string') { + if (isFunction(callback)) { + //Invalid call + return onError(makeError('requireargs', 'Invalid require call'), errback); + } + + //If require|exports|module are requested, get the + //value for them from the special handlers. Caveat: + //this only works while module is being defined. + if (relMap && hasProp(handlers, deps)) { + return handlers[deps](registry[relMap.id]); + } + + //Synchronous access to one module. If require.get is + //available (as in the Node adapter), prefer that. + if (req.get) { + return req.get(context, deps, relMap, localRequire); + } + + //Normalize module name, if it contains . or .. + map = makeModuleMap(deps, relMap, false, true); + id = map.id; + + if (!hasProp(defined, id)) { + return onError(makeError('notloaded', 'Module name "' + + id + + '" has not been loaded yet for context: ' + + contextName + + (relMap ? '' : '. Use require([])'))); + } + return defined[id]; + } + + //Grab defines waiting in the global queue. + intakeDefines(); + + //Mark all the dependencies as needing to be loaded. + context.nextTick(function () { + //Some defines could have been added since the + //require call, collect them. + intakeDefines(); + + requireMod = getModule(makeModuleMap(null, relMap)); + + //Store if map config should be applied to this require + //call for dependencies. + requireMod.skipMap = options.skipMap; + + requireMod.init(deps, callback, errback, { + enabled: true + }); + + checkLoaded(); + }); + + return localRequire; + } + + mixin(localRequire, { + + /** + * Converts a module name + .extension into an URL path. + * *Requires* the use of a module name. It does not support using + * plain URLs like nameToUrl. + */ + toUrl: function (moduleNamePlusExt) { + var ext, + index = moduleNamePlusExt.lastIndexOf('.'), + segment = moduleNamePlusExt.split('/')[0], + isRelative = segment === '.' || segment === '..'; + + //Have a file extension alias, and it is not the + //dots from a relative path. + if (index !== -1 && (!isRelative || index > 1)) { + ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); + moduleNamePlusExt = moduleNamePlusExt.substring(0, index); + } + + return context.nameToUrl(normalize(moduleNamePlusExt, + relMap && relMap.id, true), ext, true); + }, + + defined: function (id) { + return hasProp(defined, makeModuleMap(id, relMap, false, true).id); + }, + + specified: function (id) { + id = makeModuleMap(id, relMap, false, true).id; + return hasProp(defined, id) || hasProp(registry, id); + } + }); + + //Only allow undef on top level require calls + if (!relMap) { + localRequire.undef = function (id) { + //Bind any waiting define() calls to this context, + //fix for #408 + takeGlobalQueue(); + + var map = makeModuleMap(id, relMap, true), + mod = getOwn(registry, id); + + mod.undefed = true; + removeScript(id); + + delete defined[id]; + delete urlFetched[map.url]; + delete undefEvents[id]; + + //Clean queued defines too. Go backwards + //in array so that the splices do not + //mess up the iteration. + eachReverse(defQueue, function(args, i) { + if (args[0] === id) { + defQueue.splice(i, 1); + } + }); + delete context.defQueueMap[id]; + + if (mod) { + //Hold on to listeners in case the + //module will be attempted to be reloaded + //using a different config. + if (mod.events.defined) { + undefEvents[id] = mod.events; + } + + cleanRegistry(id); + } + }; + } + + return localRequire; + }, + + /** + * Called to enable a module if it is still in the registry + * awaiting enablement. A second arg, parent, the parent module, + * is passed in for context, when this method is overridden by + * the optimizer. Not shown here to keep code compact. + */ + enable: function (depMap) { + var mod = getOwn(registry, depMap.id); + if (mod) { + getModule(depMap).enable(); + } + }, + + /** + * Internal method used by environment adapters to complete a load event. + * A load event could be a script load or just a load pass from a synchronous + * load call. + * @param {String} moduleName the name of the module to potentially complete. + */ + completeLoad: function (moduleName) { + var found, args, mod, + shim = getOwn(config.shim, moduleName) || {}, + shExports = shim.exports; + + takeGlobalQueue(); + + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + args[0] = moduleName; + //If already found an anonymous module and bound it + //to this name, then this is some other anon module + //waiting for its completeLoad to fire. + if (found) { + break; + } + found = true; + } else if (args[0] === moduleName) { + //Found matching define call for this script! + found = true; + } + + callGetModule(args); + } + context.defQueueMap = {}; + + //Do this after the cycle of callGetModule in case the result + //of those calls/init calls changes the registry. + mod = getOwn(registry, moduleName); + + if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { + if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { + if (hasPathFallback(moduleName)) { + return; + } else { + return onError(makeError('nodefine', + 'No define call for ' + moduleName, + null, + [moduleName])); + } + } else { + //A script that does not call define(), so just simulate + //the call for it. + callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); + } + } + + checkLoaded(); + }, + + /** + * Converts a module name to a file path. Supports cases where + * moduleName may actually be just an URL. + * Note that it **does not** call normalize on the moduleName, + * it is assumed to have already been normalized. This is an + * internal API, not a public one. Use toUrl for the public API. + */ + nameToUrl: function (moduleName, ext, skipExt) { + var paths, syms, i, parentModule, url, + parentPath, bundleId, + pkgMain = getOwn(config.pkgs, moduleName); + + if (pkgMain) { + moduleName = pkgMain; + } + + bundleId = getOwn(bundlesMap, moduleName); + + if (bundleId) { + return context.nameToUrl(bundleId, ext, skipExt); + } + + //If a colon is in the URL, it indicates a protocol is used and it is just + //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) + //or ends with .js, then assume the user meant to use an url and not a module id. + //The slash is important for protocol-less URLs as well as full paths. + if (req.jsExtRegExp.test(moduleName)) { + //Just a plain path, not module name lookup, so just return it. + //Add extension if it is included. This is a bit wonky, only non-.js things pass + //an extension, this method probably needs to be reworked. + url = moduleName + (ext || ''); + } else { + //A module that needs to be converted to a path. + paths = config.paths; + + syms = moduleName.split('/'); + //For each module name segment, see if there is a path + //registered for it. Start with most specific name + //and work up from it. + for (i = syms.length; i > 0; i -= 1) { + parentModule = syms.slice(0, i).join('/'); + + parentPath = getOwn(paths, parentModule); + if (parentPath) { + //If an array, it means there are a few choices, + //Choose the one that is desired + if (isArray(parentPath)) { + parentPath = parentPath[0]; + } + syms.splice(0, i, parentPath); + break; + } + } + + //Join the path parts together, then figure out if baseUrl is needed. + url = syms.join('/'); + url += (ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js')); + url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; + } + + return config.urlArgs && !/^blob\:/.test(url) ? + url + config.urlArgs(moduleName, url) : url; + }, + + //Delegates to req.load. Broken out as a separate function to + //allow overriding in the optimizer. + load: function (id, url) { + req.load(context, id, url); + }, + + /** + * Executes a module callback function. Broken out as a separate function + * solely to allow the build system to sequence the files in the built + * layer in the right sequence. + * + * @private + */ + execCb: function (name, callback, args, exports) { + return callback.apply(exports, args); + } + }; + + context.require = context.makeRequire(); + return context; + } + + /** + * Main entry point. + * + * If the only argument to require is a string, then the module that + * is represented by that string is fetched for the appropriate context. + * + * If the first argument is an array, then it will be treated as an array + * of dependency string names to fetch. An optional function callback can + * be specified to execute when all of those dependencies are available. + * + * Make a local req variable to help Caja compliance (it assumes things + * on a require that are not standardized), and to give a short + * name for minification/local scope use. + */ + req = function (deps, callback, errback, optional) { + + //Find the right context, use default + var context, config, + contextName = defContextName; + + // Determine if have config object in the call. + if (!isArray(deps) && typeof deps !== 'string') { + // deps is a config object + config = deps; + if (isArray(callback)) { + // Adjust args if there are dependencies + deps = callback; + callback = errback; + errback = optional; + } else { + deps = []; + } + } + + if (config && config.context) { + contextName = config.context; + } + + context = getOwn(contexts, contextName); + if (!context) { + context = contexts[contextName] = req.s.newContext(contextName); + } + + if (config) { + context.configure(config); + } + + return context.require(deps, callback, errback); + }; + + /** + * Execute something after the current tick + * of the event loop. Override for other envs + * that have a better solution than setTimeout. + * @param {Function} fn function to execute later. + */ + req.nextTick = function (fn) { + setTimeout(fn, 4); + } + + /** + * Export require as a global, but only if it does not already exist. + */ + if (!require) { + require = req; + } + + req.version = version; + + //Used to filter out dependencies that are already paths. + req.jsExtRegExp = /^\/|:|\?|\.js$/; + s = req.s = { + contexts: contexts, + newContext: newContext + }; + + //Create default context. + req({}); + + //Exports some context-sensitive methods on global require. + each([ + 'toUrl', + 'undef', + 'defined', + 'specified' + ], function (prop) { + //Reference from contexts instead of early binding to default context, + //so that during builds, the latest instance of the default context + //with its config gets used. + req[prop] = function () { + var ctx = contexts[defContextName]; + return ctx.require[prop].apply(ctx, arguments); + }; + }); + + /** + * Any errors that require explicitly generates will be passed to this + * function. Intercept/override it if you want custom error handling. + * @param {Error} err the error object. + */ + req.onError = defaultOnError; + + /** + * Does the request to load a module for the browser case. + * Make this a separate function to allow other environments + * to override it. + * + * @param {Object} context the require context to find state. + * @param {String} moduleName the name of the module. + * @param {Object} url the URL to the module. + */ + req.load = function (context, moduleName, url) { + console.log('req.load::::'+url); + context.completeLoad(moduleName) + }; + + function getInteractiveScript() { + if (interactiveScript && interactiveScript.readyState === 'interactive') { + return interactiveScript; + } + + eachReverse(scripts(), function (script) { + if (script.readyState === 'interactive') { + return (interactiveScript = script); + } + }); + return interactiveScript; + } + + /** + * The function that handles definitions of modules. Differs from + * require() in that a string for the module should be the first argument, + * and the function to execute after dependencies are loaded should + * return a value to define the module corresponding to the first argument's + * name. + */ + define = function (name, deps, callback) { + var node, context; + + //Allow for anonymous modules + if (typeof name !== 'string') { + //Adjust args appropriately + callback = deps; + deps = name; + name = null; + } + + //This module may not have dependencies + if (!isArray(deps)) { + callback = deps; + deps = null; + } + + //If in IE 6-8 and hit an anonymous define() call, do the interactive + //work. + if (useInteractive) { + node = currentlyAddingScript || getInteractiveScript(); + if (node) { + if (!name) { + name = node.getAttribute('data-requiremodule'); + } + context = contexts[node.getAttribute('data-requirecontext')]; + } + } + + //Always save off evaluating the def call until the script onload handler. + //This allows multiple modules to be in a file without prematurely + //tracing dependencies, and allows for anonymous module support, + //where the module name is not known until the script onload event + //occurs. If no context, use the global queue, and get it processed + //in the onscript load callback. + if (context) { + context.defQueue.push([name, deps, callback]); + context.defQueueMap[name] = true; + } else { + globalDefQueue.push([name, deps, callback]); + } + }; + + //Set up with config info. + req(cfg); +}(this)); +define('vue', ['exports'], function(exports) { + Object.assign(exports,Vue) +}) +// require(['app']) \ No newline at end of file diff --git a/packages/uni-app-vite/package.json b/packages/uni-app-vite/package.json index 87ace64b3be94c9db964c5792624d9e6916ebeb8..0aaee284e66ab7be3b83be0b0d10a8458685db24 100644 --- a/packages/uni-app-vite/package.json +++ b/packages/uni-app-vite/package.json @@ -23,5 +23,11 @@ "main": "dist/index.js" }, "license": "Apache-2.0", - "gitHead": "56deaeb47d42e924d10282d7af418ccee6b139bf" + "gitHead": "56deaeb47d42e924d10282d7af418ccee6b139bf", + "dependencies": { + "clean-css": "^5.1.3", + "postcss-import": "^14.0.2", + "postcss-load-config": "^3.1.0", + "postcss-modules": "^4.1.3" + } } diff --git a/packages/uni-app-vite/src/index.ts b/packages/uni-app-vite/src/index.ts index 49c591f0a2545b79455b157416b8d69d4e6ccf18..220b3cec832a9367e51202cf49ddec6a25dd7a84 100644 --- a/packages/uni-app-vite/src/index.ts +++ b/packages/uni-app-vite/src/index.ts @@ -7,17 +7,22 @@ import { uniManifestJsonPlugin } from './plugins/manifestJson' import { uniPagesJsonPlugin } from './plugins/pagesJson' import { uniResolveIdPlugin } from './plugins/resolveId' -export default [ +const plugins = [ uniResolveIdPlugin(), uniCopyPlugin(), uniMainJsPlugin(), uniManifestJsonPlugin(), uniPagesJsonPlugin(), UniAppPlugin, - uniCssPlugin({ - app: fs.readFileSync( - require.resolve('@dcloudio/uni-app-plus/dist/style.css'), - 'utf8' - ), - }), ] +if (!process.env.UNI_APP_CODE_SPLITING) { + plugins.push( + uniCssPlugin({ + app: fs.readFileSync( + require.resolve('@dcloudio/uni-app-plus/dist/style.css'), + 'utf8' + ), + }) + ) +} +export default plugins diff --git a/packages/uni-app-vite/src/plugin.ts b/packages/uni-app-vite/src/plugin.ts deleted file mode 100644 index 877f85e9f4583713b422faff8a36257e5e1d099a..0000000000000000000000000000000000000000 --- a/packages/uni-app-vite/src/plugin.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { - isServiceNativeTag, - isServiceCustomElement, -} from '@dcloudio/uni-shared' -import { - parseManifestJsonOnce, - resolveMainPathOnce, - UniVitePlugin, - getNVueCompiler, - getNVueStyleCompiler, - resolveBuiltIn, -} from '@dcloudio/uni-cli-shared' - -export const UniAppPlugin: UniVitePlugin = { - name: 'vite:uni-app', - uni: { - compilerOptions: { - isNativeTag: isServiceNativeTag, - isCustomElement: isServiceCustomElement, - }, - transformEvent: { - tap: 'click', - }, - }, - config() { - return { - build: { - rollupOptions: { - input: resolveMainPathOnce(process.env.UNI_INPUT_DIR), - external: ['vue'], - output: { - name: 'AppService', - format: 'iife', - entryFileNames: 'app-service.js', - manualChunks: undefined, - globals: { - vue: 'Vue', - }, - }, - }, - }, - } - }, - configResolved(config) { - const manifestJson = parseManifestJsonOnce(process.env.UNI_INPUT_DIR) - if (getNVueCompiler(manifestJson) === 'uni-app') { - process.env.UNI_USING_NVUE_COMPILER = 'uni-app' - } - if (getNVueStyleCompiler(manifestJson) === 'uni-app') { - process.env.UNI_USING_NVUE_STYLE_COMPILER = 'uni-app' - } - // 移除 vite 内置的 css post 处理 - const index = config.plugins.findIndex((p) => p.name === 'vite:css-post') - if (index > -1) { - ;(config.plugins as Plugin[]).splice(index, 1) - } - }, - resolveId(id) { - if (id === 'vue') { - return resolveBuiltIn('@dcloudio/uni-app-vue') - } - }, -} diff --git a/packages/uni-app-vite/src/plugin/build.ts b/packages/uni-app-vite/src/plugin/build.ts new file mode 100644 index 0000000000000000000000000000000000000000..9a6e878d2ccfdfe501311b1a39595132448b8167 --- /dev/null +++ b/packages/uni-app-vite/src/plugin/build.ts @@ -0,0 +1,32 @@ +import path from 'path' +import slash from 'slash' +import { UserConfig } from 'vite' + +import { resolveMainPathOnce } from '@dcloudio/uni-cli-shared' + +export const buildOptions: UserConfig['build'] = { + rollupOptions: { + input: resolveMainPathOnce(process.env.UNI_INPUT_DIR), + external: ['vue'], + output: { + name: 'AppService', + format: process.env.UNI_APP_CODE_SPLITING ? 'amd' : 'iife', + entryFileNames: 'app-service.js', + manualChunks: {}, + chunkFileNames(chunk) { + if (chunk.isDynamicEntry && chunk.facadeModuleId) { + const filepath = path.relative( + process.env.UNI_INPUT_DIR, + chunk.facadeModuleId + ) + return slash(filepath.replace(path.extname(filepath), '.js')) + } + return '[name].js' + }, + assetFileNames: '[name][extname]', + globals: { + vue: 'Vue', + }, + }, + }, +} diff --git a/packages/uni-app-vite/src/plugin/configResolved.ts b/packages/uni-app-vite/src/plugin/configResolved.ts new file mode 100644 index 0000000000000000000000000000000000000000..53e202e5869d68369d6bf4c63ef2f63c53b2e369 --- /dev/null +++ b/packages/uni-app-vite/src/plugin/configResolved.ts @@ -0,0 +1,52 @@ +import { Plugin, ResolvedConfig } from 'vite' +import { + parseManifestJsonOnce, + getNVueCompiler, + getNVueStyleCompiler, +} from '@dcloudio/uni-cli-shared' + +import { assetPlugin } from '../plugins/vitejs/plugins/asset' +import { cssPlugin, cssPostPlugin } from '../plugins/vitejs/plugins/css' + +export const configResolved: Plugin['configResolved'] = (config) => { + const manifestJson = parseManifestJsonOnce(process.env.UNI_INPUT_DIR) + if (getNVueCompiler(manifestJson) === 'uni-app') { + process.env.UNI_USING_NVUE_COMPILER = 'uni-app' + } + if (getNVueStyleCompiler(manifestJson) === 'uni-app') { + process.env.UNI_USING_NVUE_STYLE_COMPILER = 'uni-app' + } + if (process.env.UNI_APP_CODE_SPLITING) { + initCodeSpliting(config as ResolvedConfig) + } else { + // 移除 vite 内置的 css post 处理,交由 @dcloudio/uni-cli-shared 的 uniCssPlugin 实现 + const index = config.plugins.findIndex((p) => p.name === 'vite:css-post') + if (index > -1) { + ;(config.plugins as Plugin[]).splice(index, 1) + } + } +} + +function initCodeSpliting(config: ResolvedConfig) { + // 替换内置插件 + const replacedPlugins = [ + assetPlugin(config), + cssPlugin(config), + cssPostPlugin(config), + ] + replacedPlugins.forEach((plugin) => { + const index = (config.plugins as Plugin[]).findIndex( + (p) => p.name === plugin.name + ) + if (index > -1) { + ;(config.plugins as Plugin[]).splice(index, 1, plugin) + } + }) + const removedPlugins = ['vite:import-analysis'] + removedPlugins.forEach((name) => { + const index = config.plugins.findIndex((p) => p.name === name) + if (index > -1) { + ;(config.plugins as Plugin[]).splice(index, 1) + } + }) +} diff --git a/packages/uni-app-vite/src/plugin/index.ts b/packages/uni-app-vite/src/plugin/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..9a7d7d3b7ae142b347407af98a150cff64f028fb --- /dev/null +++ b/packages/uni-app-vite/src/plugin/index.ts @@ -0,0 +1,21 @@ +import { UniVitePlugin, resolveBuiltIn } from '@dcloudio/uni-cli-shared' + +import { uniOptions } from './uni' +import { buildOptions } from './build' +import { configResolved } from './configResolved' + +export const UniAppPlugin: UniVitePlugin = { + name: 'vite:uni-app', + uni: uniOptions, + config() { + return { + build: buildOptions, + } + }, + configResolved, + resolveId(id) { + if (id === 'vue') { + return resolveBuiltIn('@dcloudio/uni-app-vue') + } + }, +} diff --git a/packages/uni-app-vite/src/plugin/uni.ts b/packages/uni-app-vite/src/plugin/uni.ts new file mode 100644 index 0000000000000000000000000000000000000000..8410c759882f859a75f808e33e7cc83d5e6c96a8 --- /dev/null +++ b/packages/uni-app-vite/src/plugin/uni.ts @@ -0,0 +1,15 @@ +import { + isServiceNativeTag, + isServiceCustomElement, +} from '@dcloudio/uni-shared' +import { UniVitePlugin } from '@dcloudio/uni-cli-shared' + +export const uniOptions: UniVitePlugin['uni'] = { + compilerOptions: { + isNativeTag: isServiceNativeTag, + isCustomElement: isServiceCustomElement, + }, + transformEvent: { + tap: 'click', + }, +} diff --git a/packages/uni-app-vite/src/plugins/vitejs/constants.ts b/packages/uni-app-vite/src/plugins/vitejs/constants.ts new file mode 100644 index 0000000000000000000000000000000000000000..a54a52f510ea0d3ae8705407da2306a524eaa7e5 --- /dev/null +++ b/packages/uni-app-vite/src/plugins/vitejs/constants.ts @@ -0,0 +1,9 @@ +/** + * https://github.com/vitejs/vite/blob/main/packages/vite/src/node/constants.ts + */ +/** + * Prefix for resolved fs paths, since windows paths may not be valid as URLs. + */ +export const FS_PREFIX = `/@fs/` + +export const CLIENT_PUBLIC_PATH = `/@vite/client` diff --git a/packages/uni-app-vite/src/plugins/vitejs/plugins/asset.ts b/packages/uni-app-vite/src/plugins/vitejs/plugins/asset.ts new file mode 100644 index 0000000000000000000000000000000000000000..97dbbc81d19480ad1ae98edeaa067ee66ec3a2db --- /dev/null +++ b/packages/uni-app-vite/src/plugins/vitejs/plugins/asset.ts @@ -0,0 +1,283 @@ +/** + * https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/asset.ts + */ +import path from 'path' +import { parse as parseUrl } from 'url' +import fs, { promises as fsp } from 'fs' +import mime from 'mime/lite' +import { Plugin } from 'vite' +import { ResolvedConfig } from 'vite' +import { cleanUrl } from '../utils' +import { FS_PREFIX } from '../constants' +import { PluginContext, RenderedChunk } from 'rollup' +import MagicString from 'magic-string' +import { createHash } from 'crypto' + +export const assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g + +// urls in JS must be quoted as strings, so when replacing them we need +// a different regex +const assetUrlQuotedRE = /"__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?"/g + +const rawRE = /(\?|&)raw(?:&|$)/ +const urlRE = /(\?|&)url(?:&|$)/ + +export const chunkToEmittedAssetsMap = new WeakMap>() + +const assetCache = new WeakMap>() + +const assetHashToFilenameMap = new WeakMap< + ResolvedConfig, + Map +>() +// save hashes of the files that has been emitted in build watch +const emittedHashMap = new WeakMap>() + +/** + * Also supports loading plain strings with import text from './foo.txt?raw' + */ +export function assetPlugin(config: ResolvedConfig): Plugin { + // assetHashToFilenameMap initialization in buildStart causes getAssetFilename to return undefined + assetHashToFilenameMap.set(config, new Map()) + return { + name: 'vite:asset', + + buildStart() { + assetCache.set(config, new Map()) + emittedHashMap.set(config, new Set()) + }, + + resolveId(id) { + if (!config.assetsInclude(cleanUrl(id))) { + return + } + // imports to absolute urls pointing to files in /public + // will fail to resolve in the main resolver. handle them here. + const publicFile = checkPublicFile(id, config) + if (publicFile) { + return id + } + }, + + async load(id) { + if (id.startsWith('\0')) { + // Rollup convention, this id should be handled by the + // plugin that marked it with \0 + return + } + + // raw requests, read from disk + if (rawRE.test(id)) { + const file = checkPublicFile(id, config) || cleanUrl(id) + // raw query, read file and return as string + return `export default ${JSON.stringify( + await fsp.readFile(file, 'utf-8') + )}` + } + + if (!config.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) { + return + } + + id = id.replace(urlRE, '$1').replace(/[\?&]$/, '') + const url = await fileToUrl(id, config, this) + return `export default ${JSON.stringify(url)}` + }, + + renderChunk(code, chunk) { + let match: RegExpExecArray | null + let s: MagicString | undefined + while ((match = assetUrlQuotedRE.exec(code))) { + s = s || (s = new MagicString(code)) + const [full, hash, postfix = ''] = match + // some internal plugins may still need to emit chunks (e.g. worker) so + // fallback to this.getFileName for that. + const file = getAssetFilename(hash, config) || this.getFileName(hash) + registerAssetToChunk(chunk, file) + const outputFilepath = config.base + file + postfix + s.overwrite( + match.index, + match.index + full.length, + JSON.stringify(outputFilepath) + ) + } + if (s) { + return { + code: s.toString(), + map: config.build.sourcemap ? s.generateMap({ hires: true }) : null, + } + } else { + return null + } + }, + + generateBundle(_, bundle) { + // do not emit assets for SSR build + if (config.command === 'build' && config.build.ssr) { + for (const file in bundle) { + if ( + bundle[file].type === 'asset' && + !file.includes('ssr-manifest.json') + ) { + delete bundle[file] + } + } + } + }, + } +} + +export function registerAssetToChunk(chunk: RenderedChunk, file: string): void { + let emitted = chunkToEmittedAssetsMap.get(chunk) + if (!emitted) { + emitted = new Set() + chunkToEmittedAssetsMap.set(chunk, emitted) + } + emitted.add(cleanUrl(file)) +} + +export function checkPublicFile( + url: string, + { publicDir }: ResolvedConfig +): string | undefined { + // note if the file is in /public, the resolver would have returned it + // as-is so it's not going to be a fully resolved path. + if (!publicDir || !url.startsWith('/')) { + return + } + const publicFile = path.join(publicDir, cleanUrl(url)) + if (fs.existsSync(publicFile)) { + return publicFile + } else { + return + } +} + +export function fileToUrl( + id: string, + config: ResolvedConfig, + ctx: PluginContext +): string | Promise { + if (config.command === 'serve') { + return fileToDevUrl(id, config) + } else { + return fileToBuiltUrl(id, config, ctx) + } +} + +function fileToDevUrl(id: string, config: ResolvedConfig) { + let rtn: string + if (checkPublicFile(id, config)) { + // in public dir, keep the url as-is + rtn = id + } else if (id.startsWith(config.root)) { + // in project root, infer short public path + rtn = '/' + path.posix.relative(config.root, id) + } else { + // outside of project root, use absolute fs path + // (this is special handled by the serve static middleware + rtn = path.posix.join(FS_PREFIX + id) + } + return config.base + rtn.replace(/^\//, '') +} + +export function getAssetFilename( + hash: string, + config: ResolvedConfig +): string | undefined { + return assetHashToFilenameMap.get(config)?.get(hash) +} + +/** + * Register an asset to be emitted as part of the bundle (if necessary) + * and returns the resolved public URL + */ +async function fileToBuiltUrl( + id: string, + config: ResolvedConfig, + pluginContext: PluginContext, + skipPublicCheck = false +): Promise { + if (!skipPublicCheck && checkPublicFile(id, config)) { + return config.base + id.slice(1) + } + + const cache = assetCache.get(config)! + const cached = cache.get(id) + if (cached) { + return cached + } + + const file = cleanUrl(id) + const content = await fsp.readFile(file) + + let url: string + if ( + config.build.lib || + (!file.endsWith('.svg') && + content.length < Number(config.build.assetsInlineLimit)) + ) { + // base64 inlined as a string + url = `data:${mime.getType(file)};base64,${content.toString('base64')}` + } else { + // emit as asset + // rollup supports `import.meta.ROLLUP_FILE_URL_*`, but it generates code + // that uses runtime url sniffing and it can be verbose when targeting + // non-module format. It also fails to cascade the asset content change + // into the chunk's hash, so we have to do our own content hashing here. + // https://bundlers.tooling.report/hashing/asset-cascade/ + // https://github.com/rollup/rollup/issues/3415 + const map = assetHashToFilenameMap.get(config)! + const contentHash = getAssetHash(content) + const { search, hash } = parseUrl(id) + const postfix = (search || '') + (hash || '') + const basename = path.basename(file) + const ext = path.extname(basename) + const fileName = path.posix.join( + config.build.assetsDir, + `${basename.slice(0, -ext.length)}.${contentHash}${ext}` + ) + if (!map.has(contentHash)) { + map.set(contentHash, fileName) + } + const emittedSet = emittedHashMap.get(config)! + if (!emittedSet.has(contentHash)) { + pluginContext.emitFile({ + fileName, + type: 'asset', + source: content, + }) + emittedSet.add(contentHash) + } + + url = `__VITE_ASSET__${contentHash}__${postfix ? `$_${postfix}__` : ``}` + } + + cache.set(id, url) + return url +} + +export function getAssetHash(content: Buffer): string { + return createHash('sha256').update(content).digest('hex').slice(0, 8) +} + +export async function urlToBuiltUrl( + url: string, + importer: string, + config: ResolvedConfig, + pluginContext: PluginContext +): Promise { + if (checkPublicFile(url, config)) { + return config.base + url.slice(1) + } + const file = url.startsWith('/') + ? path.join(config.root, url) + : path.join(path.dirname(importer), url) + return fileToBuiltUrl( + file, + config, + pluginContext, + // skip public check since we just did it above + true + ) +} diff --git a/packages/uni-app-vite/src/plugins/vitejs/plugins/css.ts b/packages/uni-app-vite/src/plugins/vitejs/plugins/css.ts new file mode 100644 index 0000000000000000000000000000000000000000..34c991884df8c750c5ebc1ce9893c072ba4c11a3 --- /dev/null +++ b/packages/uni-app-vite/src/plugins/vitejs/plugins/css.ts @@ -0,0 +1,1239 @@ +/** + * https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/css.ts + */ +import fs from 'fs' +import path from 'path' +import glob from 'fast-glob' +import { + // createDebugger, + isExternalUrl, + asyncReplace, + cleanUrl, + generateCodeFrame, + isDataUrl, + isObject, + normalizePath, + processSrcSet, +} from '../utils' +import { Plugin } from 'vite' +import { ResolvedConfig } from 'vite' +import postcssrc from 'postcss-load-config' +import { + NormalizedOutputOptions, + OutputChunk, + RenderedChunk, + RollupError, + SourceMap, +} from 'rollup' +import { dataToEsm } from '@rollup/pluginutils' +import chalk from 'chalk' +import { CLIENT_PUBLIC_PATH } from '../constants' +import { ResolveFn, ViteDevServer } from 'vite' +import { + getAssetFilename, + assetUrlRE, + registerAssetToChunk, + fileToUrl, + checkPublicFile, +} from './asset' +import MagicString from 'magic-string' +import * as Postcss from 'postcss' +import type Sass from 'sass' +// We need to disable check of extraneous import which is buggy for stylus, +// and causes the CI tests fail, see: https://github.com/vitejs/vite/pull/2860 +import type Stylus from 'stylus' +import type Less from 'less' +import { Alias } from '../../../../types/alias' + +// const debug = createDebugger('vite:css') + +export interface CSSOptions { + /** + * https://github.com/css-modules/postcss-modules + */ + modules?: CSSModulesOptions | false + preprocessorOptions?: Record + postcss?: + | string + | (Postcss.ProcessOptions & { + plugins?: Postcss.Plugin[] + }) +} + +export interface CSSModulesOptions { + getJSON?: ( + cssFileName: string, + json: Record, + outputFileName: string + ) => void + scopeBehaviour?: 'global' | 'local' + globalModulePaths?: RegExp[] + generateScopedName?: + | string + | ((name: string, filename: string, css: string) => string) + hashPrefix?: string + /** + * default: null + */ + localsConvention?: + | 'camelCase' + | 'camelCaseOnly' + | 'dashes' + | 'dashesOnly' + | null +} + +const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)` +export const cssLangRE = new RegExp(cssLangs) +const cssModuleRE = new RegExp(`\\.module${cssLangs}`) +const directRequestRE = /(\?|&)direct\b/ +const commonjsProxyRE = /\?commonjs-proxy/ + +const enum PreprocessLang { + less = 'less', + sass = 'sass', + scss = 'scss', + styl = 'styl', + stylus = 'stylus', +} +const enum PureCssLang { + css = 'css', +} +type CssLang = keyof typeof PureCssLang | keyof typeof PreprocessLang + +export const isCSSRequest = (request: string): boolean => + cssLangRE.test(request) && !directRequestRE.test(request) + +export const isDirectCSSRequest = (request: string): boolean => + cssLangRE.test(request) && directRequestRE.test(request) + +const cssModulesCache = new WeakMap< + ResolvedConfig, + Map> +>() + +export const chunkToEmittedCssFileMap = new WeakMap< + RenderedChunk, + Set +>() + +/** + * Plugin applied before user plugins + */ +export function cssPlugin(config: ResolvedConfig): Plugin { + let server: ViteDevServer + let moduleCache: Map> + + const resolveUrl = config.createResolver({ + preferRelative: true, + tryIndex: false, + extensions: [], + }) + const atImportResolvers = createCSSResolvers(config) + + return { + name: 'vite:css', + + configureServer(_server) { + server = _server + }, + + buildStart() { + // Ensure a new cache for every build (i.e. rebuilding in watch mode) + moduleCache = new Map>() + cssModulesCache.set(config, moduleCache) + }, + + async transform(raw, id) { + if (!cssLangRE.test(id) || commonjsProxyRE.test(id)) { + return + } + + const urlReplacer: CssUrlReplacer = async (url, importer) => { + if (checkPublicFile(url, config)) { + return config.base + url.slice(1) + } + const resolved = await resolveUrl(url, importer) + if (resolved) { + return fileToUrl(resolved, config, this) + } + return url + } + + const { + code: css, + modules, + deps, + } = await compileCSS( + id, + raw, + config, + urlReplacer, + atImportResolvers, + server + ) + if (modules) { + moduleCache.set(id, modules) + } + + // track deps for build watch mode + if (config.command === 'build' && config.build.watch && deps) { + for (const file of deps) { + this.addWatchFile(file) + } + } + + // dev + if (server) { + // server only logic for handling CSS @import dependency hmr + const { moduleGraph } = server + const thisModule = moduleGraph.getModuleById(id)! + + // CSS modules cannot self-accept since it exports values + const isSelfAccepting = !modules + if (deps) { + // record deps in the module graph so edits to @import css can trigger + // main import to hot update + const depModules = new Set( + [...deps].map((file) => moduleGraph.createFileOnlyEntry(file)) + ) + moduleGraph.updateModuleInfo( + thisModule, + depModules, + // The root CSS proxy module is self-accepting and should not + // have an explicit accept list + new Set(), + isSelfAccepting + ) + for (const file of deps) { + this.addWatchFile(file) + } + } else { + thisModule.isSelfAccepting = isSelfAccepting + } + } + + return { + code: css, + // TODO CSS source map + map: { mappings: '' }, + } + }, + } +} + +/** + * Plugin applied after user plugins + */ +export function cssPostPlugin(config: ResolvedConfig): Plugin { + // styles initialization in buildStart causes a styling loss in watch + const styles: Map = new Map() + let pureCssChunks: Set + + // when there are multiple rollup outputs and extracting CSS, only emit once, + // since output formats have no effect on the generated CSS. + let outputToExtractedCSSMap: Map + let hasEmitted = false + + return { + name: 'vite:css-post', + + buildStart() { + // Ensure new caches for every build (i.e. rebuilding in watch mode) + pureCssChunks = new Set() + outputToExtractedCSSMap = new Map() + hasEmitted = false + }, + + transform(css, id, ssr) { + if (!cssLangRE.test(id) || commonjsProxyRE.test(id)) { + return + } + + const modules = cssModulesCache.get(config)!.get(id) + const modulesCode = + modules && dataToEsm(modules, { namedExports: true, preferConst: true }) + + if (config.command === 'serve') { + if (isDirectCSSRequest(id)) { + return css + } else { + // server only + if (ssr) { + return modulesCode || `export default ${JSON.stringify(css)}` + } + return [ + `import { updateStyle, removeStyle } from ${JSON.stringify( + path.posix.join(config.base, CLIENT_PUBLIC_PATH) + )}`, + `const id = ${JSON.stringify(id)}`, + `const css = ${JSON.stringify(css)}`, + `updateStyle(id, css)`, + // css modules exports change on edit so it can't self accept + `${modulesCode || `import.meta.hot.accept()\nexport default css`}`, + `import.meta.hot.prune(() => removeStyle(id))`, + ].join('\n') + } + } + + // build CSS handling ---------------------------------------------------- + + // record css + styles.set(id, css) + + return { + code: '', //modulesCode || `export default ${JSON.stringify(css)}`, + map: { mappings: '' }, + // avoid the css module from being tree-shaken so that we can retrieve + // it in renderChunk() + moduleSideEffects: 'no-treeshake', + } + }, + + async renderChunk(code, chunk, opts) { + let chunkCSS = '' + let isPureCssChunk = true + const ids = Object.keys(chunk.modules) + for (const id of ids) { + if ( + !isCSSRequest(id) || + cssModuleRE.test(id) || + commonjsProxyRE.test(id) + ) { + isPureCssChunk = false + } + if (styles.has(id)) { + chunkCSS += styles.get(id) + } + } + + if (!chunkCSS) { + return null + } + + // resolve asset URL placeholders to their built file URLs and perform + // minification if necessary + const processChunkCSS = async ( + css: string, + { + inlined, + minify, + }: { + inlined: boolean + minify: boolean + } + ) => { + // replace asset url references with resolved url. + const isRelativeBase = config.base === '' || config.base.startsWith('.') + css = css.replace(assetUrlRE, (_, fileHash, postfix = '') => { + const filename = getAssetFilename(fileHash, config) + postfix + registerAssetToChunk(chunk, filename) + if (!isRelativeBase || inlined) { + // absolute base or relative base but inlined (injected as style tag into + // index.html) use the base as-is + return config.base + filename + } else { + // relative base + extracted CSS - asset file will be in the same dir + return `./${path.posix.basename(filename)}` + } + }) + // only external @imports should exist at this point - and they need to + // be hoisted to the top of the CSS chunk per spec (#1845) + if (css.includes('@import')) { + css = await hoistAtImports(css) + } + if (minify && config.build.minify) { + css = await minifyCSS(css, config) + } + return css + } + + if (config.build.cssCodeSplit) { + if (isPureCssChunk) { + // this is a shared CSS-only chunk that is empty. + pureCssChunks.add(chunk.fileName) + } + if ( + // fixed by xxxxxx support amd + opts.format === 'es' || + opts.format === 'cjs' || + opts.format === 'amd' + ) { + chunkCSS = await processChunkCSS(chunkCSS, { + inlined: false, + minify: true, + }) + const name = + chunk.isDynamicEntry && chunk.fileName + ? chunk.fileName.replace('.js', '') + : chunk.name + // emit corresponding css file + const fileHandle = this.emitFile({ + name: name + '.css', + type: 'asset', + source: chunkCSS, + }) + chunkToEmittedCssFileMap.set( + chunk, + new Set([this.getFileName(fileHandle)]) + ) + } else if (!config.build.ssr) { + // legacy build, inline css + chunkCSS = await processChunkCSS(chunkCSS, { + inlined: true, + minify: true, + }) + const style = `__vite_style__` + const injectCode = + `var ${style} = document.createElement('style');` + + `${style}.innerHTML = ${JSON.stringify(chunkCSS)};` + + `document.head.appendChild(${style});` + if (config.build.sourcemap) { + const s = new MagicString(code) + s.prepend(injectCode) + return { + code: s.toString(), + map: s.generateMap({ hires: true }), + } + } else { + return { code: injectCode + code } + } + } + } else { + // non-split extracted CSS will be minified together + chunkCSS = await processChunkCSS(chunkCSS, { + inlined: false, + minify: false, + }) + outputToExtractedCSSMap.set( + opts, + (outputToExtractedCSSMap.get(opts) || '') + chunkCSS + ) + } + return null + }, + + async generateBundle(opts, bundle) { + // remove empty css chunks and their imports + if (pureCssChunks.size) { + const emptyChunkFiles = [...pureCssChunks] + .map((file) => path.basename(file)) + .join('|') + .replace(/\./g, '\\.') + const emptyChunkRE = new RegExp( + opts.format === 'es' + ? `\\bimport\\s*"[^"]*(?:${emptyChunkFiles})";\n?` + : `\\brequire\\(\\s*"[^"]*(?:${emptyChunkFiles})"\\);\n?`, + 'g' + ) + for (const file in bundle) { + const chunk = bundle[file] + if (chunk.type === 'chunk') { + // remove pure css chunk from other chunk's imports, + // and also register the emitted CSS files under the importer + // chunks instead. + chunk.imports = chunk.imports.filter((file) => { + if (pureCssChunks.has(file)) { + const css = chunkToEmittedCssFileMap.get( + bundle[file] as OutputChunk + ) + if (css) { + let existing = chunkToEmittedCssFileMap.get(chunk) + if (!existing) { + existing = new Set() + } + css.forEach((file) => existing!.add(file)) + chunkToEmittedCssFileMap.set(chunk, existing) + } + return false + } + return true + }) + chunk.code = chunk.code.replace( + emptyChunkRE, + // remove css import while preserving source map location + (m) => `/* empty css ${''.padEnd(m.length - 15)}*/` + ) + } + } + pureCssChunks.forEach((fileName) => { + delete bundle[fileName] + }) + } + + let extractedCss = outputToExtractedCSSMap.get(opts) + if (extractedCss && !hasEmitted) { + hasEmitted = true + // minify css + if (config.build.minify) { + extractedCss = await minifyCSS(extractedCss, config) + } + this.emitFile({ + name: 'style.css', + type: 'asset', + source: extractedCss, + }) + } + }, + } +} + +interface CSSAtImportResolvers { + css: ResolveFn + sass: ResolveFn + less: ResolveFn +} + +function createCSSResolvers(config: ResolvedConfig): CSSAtImportResolvers { + let cssResolve: ResolveFn | undefined + let sassResolve: ResolveFn | undefined + let lessResolve: ResolveFn | undefined + return { + get css() { + return ( + cssResolve || + (cssResolve = config.createResolver({ + extensions: ['.css'], + mainFields: ['style'], + tryIndex: false, + preferRelative: true, + })) + ) + }, + + get sass() { + return ( + sassResolve || + (sassResolve = config.createResolver({ + extensions: ['.scss', '.sass', '.css'], + mainFields: ['sass', 'style'], + tryIndex: true, + tryPrefix: '_', + preferRelative: true, + })) + ) + }, + + get less() { + return ( + lessResolve || + (lessResolve = config.createResolver({ + extensions: ['.less', '.css'], + mainFields: ['less', 'style'], + tryIndex: false, + preferRelative: true, + })) + ) + }, + } +} + +async function compileCSS( + id: string, + code: string, + config: ResolvedConfig, + urlReplacer: CssUrlReplacer, + atImportResolvers: CSSAtImportResolvers, + server?: ViteDevServer +): Promise<{ + code: string + map?: SourceMap + ast?: Postcss.Result + modules?: Record + deps?: Set +}> { + const { modules: modulesOptions, preprocessorOptions } = config.css || {} + const isModule = modulesOptions !== false && cssModuleRE.test(id) + // although at serve time it can work without processing, we do need to + // crawl them in order to register watch dependencies. + const needInlineImport = code.includes('@import') + const hasUrl = cssUrlRE.test(code) || cssImageSetRE.test(code) + const postcssConfig = await resolvePostcssConfig(config) + const lang = id.match(cssLangRE)?.[1] as CssLang | undefined + + // 1. plain css that needs no processing + if ( + lang === 'css' && + !postcssConfig && + !isModule && + !needInlineImport && + !hasUrl + ) { + return { code } + } + + let map: SourceMap | undefined + let modules: Record | undefined + const deps = new Set() + + // 2. pre-processors: sass etc. + if (isPreProcessor(lang)) { + const preProcessor = preProcessors[lang] + let opts = (preprocessorOptions && preprocessorOptions[lang]) || {} + // support @import from node dependencies by default + switch (lang) { + case PreprocessLang.scss: + case PreprocessLang.sass: + opts = { + includePaths: ['node_modules'], + alias: config.resolve.alias, + ...opts, + } + break + case PreprocessLang.less: + case PreprocessLang.styl: + case PreprocessLang.stylus: + opts = { + paths: ['node_modules'], + alias: config.resolve.alias, + ...opts, + } + } + // important: set this for relative import resolving + opts.filename = cleanUrl(id) + const preprocessResult = await preProcessor( + code, + config.root, + opts, + atImportResolvers + ) + if (preprocessResult.errors.length) { + throw preprocessResult.errors[0] + } + + code = preprocessResult.code + map = preprocessResult.map as SourceMap + if (preprocessResult.deps) { + preprocessResult.deps.forEach((dep) => { + // sometimes sass registers the file itself as a dep + if (normalizePath(dep) !== normalizePath(opts.filename)) { + deps.add(dep) + } + }) + } + } + + // 3. postcss + const postcssOptions = (postcssConfig && postcssConfig.options) || {} + const postcssPlugins = + postcssConfig && postcssConfig.plugins ? postcssConfig.plugins.slice() : [] + + if (needInlineImport) { + postcssPlugins.unshift( + (await import('postcss-import')).default({ + async resolve(id, basedir) { + const resolved = await atImportResolvers.css( + id, + path.join(basedir, '*') + ) + if (resolved) { + return path.resolve(resolved) + } + return id + }, + }) + ) + } + postcssPlugins.push( + UrlRewritePostcssPlugin({ + replacer: urlReplacer, + }) as Postcss.Plugin + ) + + if (isModule) { + postcssPlugins.unshift( + (await import('postcss-modules')).default({ + ...modulesOptions, + getJSON( + cssFileName: string, + _modules: Record, + outputFileName: string + ) { + modules = _modules + if (modulesOptions && typeof modulesOptions.getJSON === 'function') { + modulesOptions.getJSON(cssFileName, _modules, outputFileName) + } + }, + }) + ) + } + + if (!postcssPlugins.length) { + return { + code, + map, + } + } + + // postcss is an unbundled dep and should be lazy imported + const postcssResult = await (await import('postcss')) + .default(postcssPlugins) + .process(code, { + ...postcssOptions, + to: id, + from: id, + map: { + inline: false, + annotation: false, + prev: map, + }, + }) + + // record CSS dependencies from @imports + for (const message of postcssResult.messages) { + if (message.type === 'dependency') { + deps.add(message.file as string) + } else if (message.type === 'dir-dependency') { + // https://github.com/postcss/postcss/blob/main/docs/guidelines/plugin.md#3-dependencies + const { dir, glob: globPattern = '**' } = message + const pattern = + normalizePath(path.resolve(path.dirname(id), dir)) + `/` + globPattern + const files = glob.sync(pattern, { + ignore: ['**/node_modules/**'], + }) + for (let i = 0; i < files.length; i++) { + deps.add(files[i]) + } + if (server) { + // register glob importers so we can trigger updates on file add/remove + if (!(id in (server as any)._globImporters)) { + ;(server as any)._globImporters[id] = { + module: server.moduleGraph.getModuleById(id)!, + importGlobs: [], + } + } + ;(server as any)._globImporters[id].importGlobs.push({ + base: config.root, + pattern, + }) + } + } else if (message.type === 'warning') { + let msg = `[vite:css] ${message.text}` + if (message.line && message.column) { + msg += `\n${generateCodeFrame(code, { + line: message.line, + column: message.column, + })}` + } + config.logger.warn(chalk.yellow(msg)) + } + } + + return { + ast: postcssResult, + code: postcssResult.css, + map: postcssResult.map as any, + modules, + deps, + } +} + +interface PostCSSConfigResult { + options: Postcss.ProcessOptions + plugins: Postcss.Plugin[] +} + +let cachedPostcssConfig: PostCSSConfigResult | null | undefined + +async function resolvePostcssConfig( + config: ResolvedConfig +): Promise { + if (cachedPostcssConfig !== undefined) { + return cachedPostcssConfig + } + + // inline postcss config via vite config + const inlineOptions = config.css?.postcss + if (isObject(inlineOptions)) { + const result = { + options: { ...inlineOptions }, + plugins: inlineOptions.plugins || [], + } + delete result.options.plugins + return (cachedPostcssConfig = result) + } + + try { + const searchPath = + typeof inlineOptions === 'string' ? inlineOptions : config.root + // @ts-ignore + return (cachedPostcssConfig = await postcssrc({}, searchPath)) + } catch (e) { + if (!/No PostCSS Config found/.test(e.message)) { + throw e + } + return (cachedPostcssConfig = null) + } +} + +type CssUrlReplacer = ( + url: string, + importer?: string +) => string | Promise +// https://drafts.csswg.org/css-syntax-3/#identifier-code-point +export const cssUrlRE = + /(?<=^|[^\w\-\u0080-\uffff])url\(\s*('[^']+'|"[^"]+"|[^'")]+)\s*\)/ +const cssImageSetRE = /image-set\(([^)]+)\)/ + +const UrlRewritePostcssPlugin: Postcss.PluginCreator<{ + replacer: CssUrlReplacer +}> = (opts) => { + if (!opts) { + throw new Error('base or replace is required') + } + + return { + postcssPlugin: 'vite-url-rewrite', + Once(root) { + const promises: Promise[] = [] + root.walkDecls((declaration) => { + const isCssUrl = cssUrlRE.test(declaration.value) + const isCssImageSet = cssImageSetRE.test(declaration.value) + if (isCssUrl || isCssImageSet) { + const replacerForDeclaration = (rawUrl: string) => { + const importer = declaration.source?.input.file + return opts.replacer(rawUrl, importer) + } + const rewriterToUse = isCssUrl ? rewriteCssUrls : rewriteCssImageSet + promises.push( + rewriterToUse(declaration.value, replacerForDeclaration).then( + (url) => { + declaration.value = url + } + ) + ) + } + }) + if (promises.length) { + return Promise.all(promises) as any + } + }, + } +} +UrlRewritePostcssPlugin.postcss = true + +function rewriteCssUrls( + css: string, + replacer: CssUrlReplacer +): Promise { + return asyncReplace(css, cssUrlRE, async (match) => { + const [matched, rawUrl] = match + return await doUrlReplace(rawUrl, matched, replacer) + }) +} + +function rewriteCssImageSet( + css: string, + replacer: CssUrlReplacer +): Promise { + return asyncReplace(css, cssImageSetRE, async (match) => { + const [matched, rawUrl] = match + const url = await processSrcSet(rawUrl, ({ url }) => + doUrlReplace(url, matched, replacer) + ) + return `image-set(${url})` + }) +} +async function doUrlReplace( + rawUrl: string, + matched: string, + replacer: CssUrlReplacer +) { + let wrap = '' + const first = rawUrl[0] + if (first === `"` || first === `'`) { + wrap = first + rawUrl = rawUrl.slice(1, -1) + } + if (isExternalUrl(rawUrl) || isDataUrl(rawUrl) || rawUrl.startsWith('#')) { + return matched + } + + return `url(${wrap}${await replacer(rawUrl)}${wrap})` +} + +let CleanCSS: any + +async function minifyCSS(css: string, config: ResolvedConfig) { + CleanCSS = CleanCSS || (await import('clean-css')).default + const res = new CleanCSS({ + rebase: false, + ...config.build.cleanCssOptions, + }).minify(css) + + if (res.errors && res.errors.length) { + config.logger.error(chalk.red(`error when minifying css:\n${res.errors}`)) + throw res.errors[0] + } + + // do not warn on remote @imports + const warnings = + res.warnings && + res.warnings.filter((m: string) => !m.includes('remote @import')) + if (warnings && warnings.length) { + config.logger.warn( + chalk.yellow(`warnings when minifying css:\n${warnings.join('\n')}`) + ) + } + + return res.styles +} + +// #1845 +// CSS @import can only appear at top of the file. We need to hoist all @import +// to top when multiple files are concatenated. +async function hoistAtImports(css: string) { + const postcss = await import('postcss') + return (await postcss.default([AtImportHoistPlugin]).process(css)).css +} + +const AtImportHoistPlugin: Postcss.PluginCreator = () => { + return { + postcssPlugin: 'vite-hoist-at-imports', + Once(root) { + const imports: Postcss.AtRule[] = [] + root.walkAtRules((rule) => { + if (rule.name === 'import') { + // record in reverse so that can simply prepend to preserve order + imports.unshift(rule) + } + }) + imports.forEach((i) => root.prepend(i)) + }, + } +} +AtImportHoistPlugin.postcss = true + +// Preprocessor support. This logic is largely replicated from @vue/compiler-sfc + +type PreprocessorAdditionalData = + | string + | ((source: string, filename: string) => string | Promise) + +type StylePreprocessorOptions = { + [key: string]: any + additionalData?: PreprocessorAdditionalData + filename: string + alias: Alias[] +} + +type SassStylePreprocessorOptions = StylePreprocessorOptions & Sass.Options + +type StylePreprocessor = ( + source: string, + root: string, + options: StylePreprocessorOptions, + resolvers: CSSAtImportResolvers +) => StylePreprocessorResults | Promise + +type SassStylePreprocessor = ( + source: string, + root: string, + options: SassStylePreprocessorOptions, + resolvers: CSSAtImportResolvers +) => StylePreprocessorResults | Promise + +export interface StylePreprocessorResults { + code: string + map?: object + errors: RollupError[] + deps: string[] +} + +const loadedPreprocessors: Partial> = {} + +function loadPreprocessor(lang: PreprocessLang.scss, root: string): typeof Sass +function loadPreprocessor(lang: PreprocessLang.sass, root: string): typeof Sass +function loadPreprocessor(lang: PreprocessLang.less, root: string): typeof Less +function loadPreprocessor( + lang: PreprocessLang.stylus, + root: string +): typeof Stylus +function loadPreprocessor(lang: PreprocessLang, root: string): any { + if (lang in loadedPreprocessors) { + return loadedPreprocessors[lang] + } + try { + // Search for the preprocessor in the root directory first, and fall back + // to the default require paths. + const fallbackPaths = require.resolve.paths(lang) || [] + const resolved = require.resolve(lang, { paths: [root, ...fallbackPaths] }) + return (loadedPreprocessors[lang] = require(resolved)) + } catch (e) { + throw new Error( + `Preprocessor dependency "${lang}" not found. Did you install it?` + ) + } +} + +// .scss/.sass processor +const scss: SassStylePreprocessor = async ( + source, + root, + options, + resolvers +) => { + const render = loadPreprocessor(PreprocessLang.sass, root).render + const internalImporter: Sass.Importer = (url, importer, done) => { + resolvers.sass(url, importer).then((resolved) => { + if (resolved) { + rebaseUrls(resolved, options.filename, options.alias).then(done) + } else { + done(null) + } + }) + } + const importer = [internalImporter] + if (options.importer) { + Array.isArray(options.importer) + ? importer.push(...options.importer) + : importer.push(options.importer) + } + + const finalOptions: Sass.Options = { + ...options, + data: await getSource(source, options.filename, options.additionalData), + file: options.filename, + outFile: options.filename, + importer, + } + + try { + const result = await new Promise((resolve, reject) => { + render(finalOptions, (err, res) => { + if (err) { + reject(err) + } else { + resolve(res) + } + }) + }) + const deps = result.stats.includedFiles + + return { + code: result.css.toString(), + errors: [], + deps, + } + } catch (e) { + // normalize SASS error + e.id = e.file + e.frame = e.formatted + return { code: '', errors: [e], deps: [] } + } +} + +const sass: SassStylePreprocessor = (source, root, options, aliasResolver) => + scss( + source, + root, + { + ...options, + indentedSyntax: true, + }, + aliasResolver + ) + +/** + * relative url() inside \@imported sass and less files must be rebased to use + * root file as base. + */ +async function rebaseUrls( + file: string, + rootFile: string, + alias: Alias[] +): Promise { + file = path.resolve(file) // ensure os-specific flashes + // in the same dir, no need to rebase + const fileDir = path.dirname(file) + const rootDir = path.dirname(rootFile) + if (fileDir === rootDir) { + return { file } + } + // no url() + const content = fs.readFileSync(file, 'utf-8') + if (!cssUrlRE.test(content)) { + return { file } + } + const rebased = await rewriteCssUrls(content, (url) => { + if (url.startsWith('/')) return url + // match alias, no need to rewrite + for (const { find } of alias) { + const matches = + typeof find === 'string' ? url.startsWith(find) : find.test(url) + if (matches) { + return url + } + } + const absolute = path.resolve(fileDir, url) + const relative = path.relative(rootDir, absolute) + return normalizePath(relative) + }) + return { + file, + contents: rebased, + } +} + +// .less +const less: StylePreprocessor = async (source, root, options, resolvers) => { + const nodeLess = loadPreprocessor(PreprocessLang.less, root) + const viteResolverPlugin = createViteLessPlugin( + nodeLess, + options.filename, + options.alias, + resolvers + ) + source = await getSource(source, options.filename, options.additionalData) + + let result: Less.RenderOutput | undefined + try { + result = await nodeLess.render(source, { + ...options, + plugins: [viteResolverPlugin, ...(options.plugins || [])], + }) + } catch (e) { + const error = e as Less.RenderError + // normalize error info + const normalizedError: RollupError = new Error(error.message || error.type) + normalizedError.loc = { + file: error.filename || options.filename, + line: error.line, + column: error.column, + } + return { code: '', errors: [normalizedError], deps: [] } + } + return { + code: result.css.toString(), + deps: result.imports, + errors: [], + } +} + +/** + * Less manager, lazy initialized + */ +let ViteLessManager: any + +function createViteLessPlugin( + less: typeof Less, + rootFile: string, + alias: Alias[], + resolvers: CSSAtImportResolvers +): Less.Plugin { + if (!ViteLessManager) { + ViteLessManager = class ViteManager extends less.FileManager { + resolvers + rootFile + alias + constructor( + rootFile: string, + resolvers: CSSAtImportResolvers, + alias: Alias[] + ) { + super() + this.rootFile = rootFile + this.resolvers = resolvers + this.alias = alias + } + override supports() { + return true + } + override supportsSync() { + return false + } + override async loadFile( + filename: string, + dir: string, + opts: any, + env: any + ): Promise { + const resolved = await this.resolvers.less( + filename, + path.join(dir, '*') + ) + if (resolved) { + const result = await rebaseUrls(resolved, this.rootFile, this.alias) + let contents: string + if (result && 'contents' in result) { + contents = result.contents + } else { + contents = fs.readFileSync(resolved, 'utf-8') + } + return { + filename: path.resolve(resolved), + contents, + } + } else { + return super.loadFile(filename, dir, opts, env) + } + } + } + } + + return { + install(_, pluginManager) { + pluginManager.addFileManager( + new ViteLessManager(rootFile, resolvers, alias) + ) + }, + minVersion: [3, 0, 0], + } +} + +// .styl +const styl: StylePreprocessor = async (source, root, options) => { + const nodeStylus = loadPreprocessor(PreprocessLang.stylus, root) + // Get source with preprocessor options.additionalData. Make sure a new line separator + // is added to avoid any render error, as added stylus content may not have semi-colon separators + source = await getSource( + source, + options.filename, + options.additionalData, + '\n' + ) + // Get preprocessor options.imports dependencies as stylus + // does not return them with its builtin `.deps()` method + const importsDeps = (options.imports ?? []).map((dep: string) => + path.resolve(dep) + ) + try { + const ref = nodeStylus(source, options) + + // if (map) ref.set('sourcemap', { inline: false, comment: false }) + + const result = ref.render() + + // Concat imports deps with computed deps + const deps = [...ref.deps(), ...importsDeps] + + return { code: result, errors: [], deps } + } catch (e) { + return { code: '', errors: [e], deps: [] } + } +} + +function getSource( + source: string, + filename: string, + additionalData?: PreprocessorAdditionalData, + sep: string = '' +): string | Promise { + if (!additionalData) return source + if (typeof additionalData === 'function') { + return additionalData(source, filename) + } + return additionalData + sep + source +} + +const preProcessors = Object.freeze({ + [PreprocessLang.less]: less, + [PreprocessLang.sass]: sass, + [PreprocessLang.scss]: scss, + [PreprocessLang.styl]: styl, + [PreprocessLang.stylus]: styl, +}) + +function isPreProcessor(lang: any): lang is PreprocessLang { + return lang && lang in preProcessors +} diff --git a/packages/uni-app-vite/src/plugins/vitejs/utils.ts b/packages/uni-app-vite/src/plugins/vitejs/utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0b99046bff0b603689e49ad657253a1053921ff --- /dev/null +++ b/packages/uni-app-vite/src/plugins/vitejs/utils.ts @@ -0,0 +1,155 @@ +/** + * https://github.com/vitejs/vite/blob/main/packages/vite/src/node/utils.ts + */ +import os from 'os' +import path from 'path' +export function slash(p: string): string { + return p.replace(/\\/g, '/') +} + +export const bareImportRE = /^[\w@](?!.*:\/\/)/ +export const deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\// + +export const isWindows = os.platform() === 'win32' + +export function normalizePath(id: string): string { + return path.posix.normalize(isWindows ? slash(id) : id) +} + +export const queryRE = /\?.*$/s +export const hashRE = /#.*$/s + +export const cleanUrl = (url: string): string => + url.replace(hashRE, '').replace(queryRE, '') + +export const externalRE = /^(https?:)?\/\// +export const isExternalUrl = (url: string): boolean => externalRE.test(url) + +export const dataUrlRE = /^\s*data:/i +export const isDataUrl = (url: string): boolean => dataUrlRE.test(url) + +export async function asyncReplace( + input: string, + re: RegExp, + replacer: (match: RegExpExecArray) => string | Promise +): Promise { + let match: RegExpExecArray | null + let remaining = input + let rewritten = '' + while ((match = re.exec(remaining))) { + rewritten += remaining.slice(0, match.index) + rewritten += await replacer(match) + remaining = remaining.slice(match.index + match[0].length) + } + rewritten += remaining + return rewritten +} + +export function isObject(value: unknown): value is Record { + return Object.prototype.toString.call(value) === '[object Object]' +} + +const splitRE = /\r?\n/ + +const range: number = 2 + +export function pad(source: string, n = 2): string { + const lines = source.split(splitRE) + return lines.map((l) => ` `.repeat(n) + l).join(`\n`) +} + +export function posToNumber( + source: string, + pos: number | { line: number; column: number } +): number { + if (typeof pos === 'number') return pos + const lines = source.split(splitRE) + const { line, column } = pos + let start = 0 + for (let i = 0; i < line - 1; i++) { + start += lines[i].length + 1 + } + return start + column +} + +export function generateCodeFrame( + source: string, + start: number | { line: number; column: number } = 0, + end?: number +): string { + start = posToNumber(source, start) + end = end || start + const lines = source.split(splitRE) + let count = 0 + const res: string[] = [] + for (let i = 0; i < lines.length; i++) { + count += lines[i].length + 1 + if (count >= start) { + for (let j = i - range; j <= i + range || end > count; j++) { + if (j < 0 || j >= lines.length) continue + const line = j + 1 + res.push( + `${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${ + lines[j] + }` + ) + const lineLength = lines[j].length + if (j === i) { + // push underline + const pad = start - (count - lineLength) + 1 + const length = Math.max( + 1, + end > count ? lineLength - pad : end - start + ) + res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)) + } else if (j > i) { + if (end > count) { + const length = Math.max(Math.min(end - count, lineLength), 1) + res.push(` | ` + '^'.repeat(length)) + } + count += lineLength + 1 + } + } + break + } + } + return res.join('\n') +} + +interface ImageCandidate { + url: string + descriptor: string +} +const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g +export async function processSrcSet( + srcs: string, + replacer: (arg: ImageCandidate) => Promise +): Promise { + const imageCandidates: ImageCandidate[] = srcs + .split(',') + .map((s) => { + const [url, descriptor] = s + .replace(escapedSpaceCharacters, ' ') + .trim() + .split(' ', 2) + return { url, descriptor } + }) + .filter(({ url }) => !!url) + + const ret = await Promise.all( + imageCandidates.map(async ({ url, descriptor }) => { + return { + url: await replacer({ url, descriptor }), + descriptor, + } + }) + ) + + const url = ret.reduce((prev, { url, descriptor }, index) => { + descriptor = descriptor || '' + return (prev += + url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`) + }, '') + + return url +} diff --git a/packages/uni-app-vite/tsconfig.json b/packages/uni-app-vite/tsconfig.json index 7de50e34ab83adea59378cbeb54e3751aa236822..98dd51629984c0a0040e34967c911f65a62bdf12 100644 --- a/packages/uni-app-vite/tsconfig.json +++ b/packages/uni-app-vite/tsconfig.json @@ -3,5 +3,10 @@ "compilerOptions": { "outDir": "dist" }, - "include": ["src", "../shims-node.d.ts", "../shims-uni-app.d.ts"] + "include": [ + "src", + "types/shims.d.ts", + "../shims-node.d.ts", + "../shims-uni-app.d.ts" + ] } diff --git a/packages/uni-app-vite/types/alias.d.ts b/packages/uni-app-vite/types/alias.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa70ec5bb59eb2ea71fb92b25458eb9461632488 --- /dev/null +++ b/packages/uni-app-vite/types/alias.d.ts @@ -0,0 +1,59 @@ +/** +Types from https://github.com/rollup/plugins/blob/master/packages/alias/types/index.d.ts +Inlined because the plugin is bundled. + +https://github.com/rollup/plugins/blob/master/LICENSE + +The MIT License (MIT) + +Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +import { PluginHooks } from 'rollup' + +export interface Alias { + find: string | RegExp + replacement: string + /** + * Instructs the plugin to use an alternative resolving algorithm, + * rather than the Rollup's resolver. + * @default null + */ + customResolver?: ResolverFunction | ResolverObject | null +} + +export type ResolverFunction = PluginHooks['resolveId'] + +export interface ResolverObject { + buildStart?: PluginHooks['buildStart'] + resolveId: ResolverFunction +} + +/** + * Specifies an `Object`, or an `Array` of `Object`, + * which defines aliases used to replace values in `import` or `require` statements. + * With either format, the order of the entries is important, + * in that the first defined rules are applied first. + * + * This is passed to \@rollup/plugin-alias as the "entries" field + * https://github.com/rollup/plugins/tree/master/packages/alias#entries + */ +export type AliasOptions = readonly Alias[] | { [find: string]: string } diff --git a/packages/uni-app-vite/types/shims.d.ts b/packages/uni-app-vite/types/shims.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7928c91a948f0467f39f6990645ad72c2b992836 --- /dev/null +++ b/packages/uni-app-vite/types/shims.d.ts @@ -0,0 +1,29 @@ +declare module 'postcss-load-config' { + import { ProcessOptions, Plugin } from 'postcss' + function load( + inline: any, + root: string + ): Promise<{ + options: ProcessOptions + plugins: Plugin[] + }> + export = load +} + +declare module 'postcss-import' { + import { Plugin } from 'postcss' + const plugin: (options: { + resolve: ( + id: string, + basedir: string, + importOptions: any + ) => string | string[] | Promise + }) => Plugin + export = plugin +} + +declare module 'postcss-modules' { + import { Plugin } from 'postcss' + const plugin: (options: any) => Plugin + export = plugin +} diff --git a/packages/uni-app-vue/dist/service.runtime.esm.js b/packages/uni-app-vue/dist/service.runtime.esm.js index 80034b24f6bd029b61f75db1edab9cdfc7c72aea..bca749baccf2c5b07eb193cf9c8d3ba043245b95 100644 --- a/packages/uni-app-vue/dist/service.runtime.esm.js +++ b/packages/uni-app-vue/dist/service.runtime.esm.js @@ -1,52 +1,4 @@ -function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } - -function _nonIterableSpread() { 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } - -function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } - -function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } - -function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } - -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } - -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } - -function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - -function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } export default function vueFactory(exports) { /** @@ -60,9 +12,9 @@ export default function vueFactory(exports) { process.env.NODE_ENV !== 'production' ? Object.freeze([]) : []; var extend$1 = Object.assign; - var cacheStringFunction$1 = function cacheStringFunction$1(fn) { + var cacheStringFunction$1 = fn => { var cache = Object.create(null); - return function (str) { + return str => { var hit = cache[str]; return hit || (cache[str] = fn(str)); }; @@ -73,54 +25,32 @@ export default function vueFactory(exports) { * @private */ - var camelize$1 = cacheStringFunction$1(function (str) { - return str.replace(camelizeRE$1, function (_, c) { - return c ? c.toUpperCase() : ''; - }); + var camelize$1 = cacheStringFunction$1(str => { + return str.replace(camelizeRE$1, (_, c) => c ? c.toUpperCase() : ''); }); var hyphenateRE$1 = /\B([A-Z])/g; /** * @private */ - var hyphenate$1 = cacheStringFunction$1(function (str) { - return str.replace(hyphenateRE$1, '-$1').toLowerCase(); - }); + var hyphenate$1 = cacheStringFunction$1(str => str.replace(hyphenateRE$1, '-$1').toLowerCase()); /** * @private */ - var capitalize$1 = cacheStringFunction$1(function (str) { - return str.charAt(0).toUpperCase() + str.slice(1); - }); + var capitalize$1 = cacheStringFunction$1(str => str.charAt(0).toUpperCase() + str.slice(1)); - function formatLog(module) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key2 = 1; _key2 < _len; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - - return "[".concat(Date.now(), "][").concat(module, "]\uFF1A").concat(args.map(function (arg) { - return JSON.stringify(arg); - }).join(' ')); + function formatLog(module, ...args) { + return "[".concat(Date.now(), "][").concat(module, "]\uFF1A").concat(args.map(arg => JSON.stringify(arg)).join(' ')); } - var DOMException = /*#__PURE__*/function (_Error) { - _inherits(DOMException, _Error); - - var _super = _createSuper(DOMException); - - function DOMException(message) { - var _this; - - _classCallCheck(this, DOMException); - - _this = _super.call(this, message); - _this.name = 'DOMException'; - return _this; + class DOMException extends Error { + constructor(message) { + super(message); + this.name = 'DOMException'; } - return DOMException; - }( /*#__PURE__*/_wrapNativeSuper(Error)); + } function normalizeEventType(type, options) { if (options) { @@ -140,48 +70,47 @@ export default function vueFactory(exports) { return "on".concat(capitalize$1(camelize$1(type))); } - var UniEvent = /*#__PURE__*/function () { - function UniEvent(type, opts) { - _classCallCheck(this, UniEvent); + class UniEvent { + constructor(type, opts) { + _defineProperty(this, "type", void 0); + + _defineProperty(this, "bubbles", void 0); + + _defineProperty(this, "cancelable", void 0); + + _defineProperty(this, "defaultPrevented", false); + + _defineProperty(this, "timeStamp", Date.now()); + + _defineProperty(this, "_stop", false); + + _defineProperty(this, "_end", false); - this.defaultPrevented = false; - this.timeStamp = Date.now(); - this._stop = false; - this._end = false; this.type = type; this.bubbles = !!opts.bubbles; this.cancelable = !!opts.cancelable; } - _createClass(UniEvent, [{ - key: "preventDefault", - value: function preventDefault() { - this.defaultPrevented = true; - } - }, { - key: "stopImmediatePropagation", - value: function stopImmediatePropagation() { - this._end = this._stop = true; - } - }, { - key: "stopPropagation", - value: function stopPropagation() { - this._stop = true; - } - }]); + preventDefault() { + this.defaultPrevented = true; + } - return UniEvent; - }(); + stopImmediatePropagation() { + this._end = this._stop = true; + } + + stopPropagation() { + this._stop = true; + } + + } function createUniEvent(evt) { if (evt instanceof UniEvent) { return evt; } - var _parseEventName = parseEventName(evt.type), - _parseEventName2 = _slicedToArray(_parseEventName, 1), - type = _parseEventName2[0]; - + var [type] = parseEventName(evt.type); var uniEvent = new UniEvent(type, { bubbles: false, cancelable: false @@ -190,66 +119,58 @@ export default function vueFactory(exports) { return uniEvent; } - var UniEventTarget = /*#__PURE__*/function () { - function UniEventTarget() { - _classCallCheck(this, UniEventTarget); - - this.listeners = Object.create(null); + class UniEventTarget { + constructor() { + _defineProperty(this, "listeners", Object.create(null)); } - _createClass(UniEventTarget, [{ - key: "dispatchEvent", - value: function dispatchEvent(evt) { - var listeners = this.listeners[evt.type]; + dispatchEvent(evt) { + var listeners = this.listeners[evt.type]; - if (!listeners) { - if (process.env.NODE_ENV !== 'production') { - console.error(formatLog('dispatchEvent', this.nodeId), evt.type, 'not found'); - } + if (!listeners) { + if (process.env.NODE_ENV !== 'production') { + console.error(formatLog('dispatchEvent', this.nodeId), evt.type, 'not found'); + } - return false; - } // 格式化事件类型 + return false; + } // 格式化事件类型 - var event = createUniEvent(evt); - var len = listeners.length; + var event = createUniEvent(evt); + var len = listeners.length; - for (var i = 0; i < len; i++) { - listeners[i].call(this, event); + for (var i = 0; i < len; i++) { + listeners[i].call(this, event); - if (event._end) { - break; - } + if (event._end) { + break; } - - return event.cancelable && event.defaultPrevented; - } - }, { - key: "addEventListener", - value: function addEventListener(type, listener, options) { - type = normalizeEventType(type, options); - (this.listeners[type] || (this.listeners[type] = [])).push(listener); } - }, { - key: "removeEventListener", - value: function removeEventListener(type, callback, options) { - type = normalizeEventType(type, options); - var listeners = this.listeners[type]; - if (!listeners) { - return; - } + return event.cancelable && event.defaultPrevented; + } + + addEventListener(type, listener, options) { + type = normalizeEventType(type, options); + (this.listeners[type] || (this.listeners[type] = [])).push(listener); + } - var index = listeners.indexOf(callback); + removeEventListener(type, callback, options) { + type = normalizeEventType(type, options); + var listeners = this.listeners[type]; - if (index > -1) { - listeners.splice(index, 1); - } + if (!listeners) { + return; } - }]); - return UniEventTarget; - }(); + var index = listeners.indexOf(callback); + + if (index > -1) { + listeners.splice(index, 1); + } + } + + } var optionsModifierRE$1 = /(?:Once|Passive|Capture)$/; @@ -298,18 +219,24 @@ export default function vueFactory(exports) { var NODE_TYPE_COMMENT = 8; function sibling(node, type) { - var parentNode = node.parentNode; + var { + parentNode + } = node; if (!parentNode) { return null; } - var childNodes = parentNode.childNodes; + var { + childNodes + } = parentNode; return childNodes[childNodes.indexOf(node) + (type === 'n' ? 1 : -1)] || null; } function removeNode(node) { - var parentNode = node.parentNode; + var { + parentNode + } = node; if (parentNode) { parentNode.removeChild(node); @@ -323,416 +250,343 @@ export default function vueFactory(exports) { } // 为优化性能,各平台不使用proxy来实现node的操作拦截,而是直接通过pageNode定制 - var UniNode = /*#__PURE__*/function (_UniEventTarget) { - _inherits(UniNode, _UniEventTarget); + class UniNode extends UniEventTarget { + constructor(nodeType, nodeName, container) { + super(); + + _defineProperty(this, "nodeId", void 0); - var _super2 = _createSuper(UniNode); + _defineProperty(this, "nodeType", void 0); - function UniNode(nodeType, nodeName, container) { - var _this2; + _defineProperty(this, "nodeName", void 0); - _classCallCheck(this, UniNode); + _defineProperty(this, "childNodes", void 0); - _this2 = _super2.call(this); - _this2.pageNode = null; - _this2.parentNode = null; - _this2._text = null; + _defineProperty(this, "pageNode", null); + + _defineProperty(this, "parentNode", null); + + _defineProperty(this, "_text", null); if (container) { - var pageNode = container.pageNode; + var { + pageNode + } = container; if (pageNode) { - _this2.pageNode = pageNode; - _this2.nodeId = pageNode.genId(); - !pageNode.isUnmounted && pageNode.onCreate(_assertThisInitialized(_this2), nodeName); + this.pageNode = pageNode; + this.nodeId = pageNode.genId(); + !pageNode.isUnmounted && pageNode.onCreate(this, nodeName); } } - _this2.nodeType = nodeType; - _this2.nodeName = nodeName; - _this2.childNodes = []; - return _this2; + this.nodeType = nodeType; + this.nodeName = nodeName; + this.childNodes = []; } - _createClass(UniNode, [{ - key: "firstChild", - get: function get() { - return this.childNodes[0] || null; - } - }, { - key: "lastChild", - get: function get() { - var childNodes = this.childNodes; - var length = childNodes.length; - return length ? childNodes[length - 1] : null; - } - }, { - key: "nextSibling", - get: function get() { - return sibling(this, 'n'); - } - }, { - key: "nodeValue", - get: function get() { - return null; - }, - set: function set(_val) {} - }, { - key: "textContent", - get: function get() { - return this._text || ''; - }, - set: function set(text) { - this._text = text; + get firstChild() { + return this.childNodes[0] || null; + } - if (this.pageNode && !this.pageNode.isUnmounted) { - this.pageNode.onTextContent(this, text); - } - } - }, { - key: "parentElement", - get: function get() { - var parentNode = this.parentNode; + get lastChild() { + var { + childNodes + } = this; + var length = childNodes.length; + return length ? childNodes[length - 1] : null; + } - if (parentNode && parentNode.nodeType === NODE_TYPE_ELEMENT) { - return parentNode; - } + get nextSibling() { + return sibling(this, 'n'); + } - return null; - } - }, { - key: "previousSibling", - get: function get() { - return sibling(this, 'p'); - } - }, { - key: "appendChild", - value: function appendChild(newChild) { - return this.insertBefore(newChild, null); - } - }, { - key: "cloneNode", - value: function cloneNode(deep) { - var cloned = extend$1(Object.create(Object.getPrototypeOf(this)), this); - var attributes = cloned.attributes; + get nodeValue() { + return null; + } - if (attributes) { - cloned.attributes = extend$1({}, attributes); - } + set nodeValue(_val) {} - if (deep) { - cloned.childNodes = cloned.childNodes.map(function (childNode) { - return childNode.cloneNode(true); - }); - } + get textContent() { + return this._text || ''; + } + + set textContent(text) { + this._text = text; - return cloned; + if (this.pageNode && !this.pageNode.isUnmounted) { + this.pageNode.onTextContent(this, text); } - }, { - key: "insertBefore", - value: function insertBefore(newChild, refChild) { - removeNode(newChild); - newChild.pageNode = this.pageNode; - newChild.parentNode = this; - checkNodeId(newChild); - var childNodes = this.childNodes; + } - if (refChild) { - var index = childNodes.indexOf(refChild); + get parentElement() { + var { + parentNode + } = this; - if (index === -1) { - throw new DOMException("Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node."); - } + if (parentNode && parentNode.nodeType === NODE_TYPE_ELEMENT) { + return parentNode; + } - childNodes.splice(index, 0, newChild); - } else { - childNodes.push(newChild); - } + return null; + } - return this.pageNode && !this.pageNode.isUnmounted ? this.pageNode.onInsertBefore(this, newChild, refChild) : newChild; - } - }, { - key: "removeChild", - value: function removeChild(oldChild) { - var childNodes = this.childNodes; - var index = childNodes.indexOf(oldChild); + get previousSibling() { + return sibling(this, 'p'); + } - if (index === -1) { - throw new DOMException("Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node."); - } + appendChild(newChild) { + return this.insertBefore(newChild, null); + } - oldChild.parentNode = null; - childNodes.splice(index, 1); - return this.pageNode && !this.pageNode.isUnmounted ? this.pageNode.onRemoveChild(oldChild) : oldChild; - } - }]); + cloneNode(deep) { + var cloned = extend$1(Object.create(Object.getPrototypeOf(this)), this); + var { + attributes + } = cloned; - return UniNode; - }(UniEventTarget); + if (attributes) { + cloned.attributes = extend$1({}, attributes); + } - var ATTR_CLASS = 'class'; - var ATTR_STYLE = 'style'; + if (deep) { + cloned.childNodes = cloned.childNodes.map(childNode => childNode.cloneNode(true)); + } - var UniBaseNode = /*#__PURE__*/function (_UniNode) { - _inherits(UniBaseNode, _UniNode); + return cloned; + } - var _super3 = _createSuper(UniBaseNode); + insertBefore(newChild, refChild) { + removeNode(newChild); + newChild.pageNode = this.pageNode; + newChild.parentNode = this; + checkNodeId(newChild); + var { + childNodes + } = this; - function UniBaseNode(nodeType, nodeName, container) { - var _this3; + if (refChild) { + var index = childNodes.indexOf(refChild); - _classCallCheck(this, UniBaseNode); + if (index === -1) { + throw new DOMException("Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node."); + } - _this3 = _super3.call(this, nodeType, nodeName, container); - _this3.attributes = Object.create(null); - _this3.style = null; - _this3._html = null; // this.style = proxyStyle(new UniCSSStyleDeclaration()) + childNodes.splice(index, 0, newChild); + } else { + childNodes.push(newChild); + } - return _this3; + return this.pageNode && !this.pageNode.isUnmounted ? this.pageNode.onInsertBefore(this, newChild, refChild) : newChild; } - _createClass(UniBaseNode, [{ - key: "className", - get: function get() { - return this.attributes[ATTR_CLASS] || ''; - }, - set: function set(val) { - this.setAttribute(ATTR_CLASS, val); - } - }, { - key: "innerHTML", - get: function get() { - return ''; - }, - set: function set(html) { - this._html = html; - } - }, { - key: "addEventListener", - value: function addEventListener(type, listener, options) { - _get(_getPrototypeOf(UniBaseNode.prototype), "addEventListener", this).call(this, type, listener, options); + removeChild(oldChild) { + var { + childNodes + } = this; + var index = childNodes.indexOf(oldChild); - if (this.pageNode && !this.pageNode.isUnmounted) { - this.pageNode.onAddEvent(this, normalizeEventType(type, options), encodeModifier(listener.modifiers || [])); - } + if (index === -1) { + throw new DOMException("Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node."); } - }, { - key: "removeEventListener", - value: function removeEventListener(type, callback, options) { - _get(_getPrototypeOf(UniBaseNode.prototype), "removeEventListener", this).call(this, type, callback, options); - if (this.pageNode && !this.pageNode.isUnmounted) { - this.pageNode.onRemoveEvent(this, normalizeEventType(type, options)); - } - } - }, { - key: "getAttribute", - value: function getAttribute(qualifiedName) { - if (qualifiedName === ATTR_STYLE) { - return this.style; - } + oldChild.parentNode = null; + childNodes.splice(index, 1); + return this.pageNode && !this.pageNode.isUnmounted ? this.pageNode.onRemoveChild(oldChild) : oldChild; + } - return this.attributes[qualifiedName]; - } - }, { - key: "removeAttribute", - value: function removeAttribute(qualifiedName) { - if (qualifiedName == ATTR_STYLE) { - this.style = null; - } else { - delete this.attributes[qualifiedName]; - } + } - if (this.pageNode && !this.pageNode.isUnmounted) { - this.pageNode.onRemoveAttribute(this, qualifiedName); - } - } - }, { - key: "setAttribute", - value: function setAttribute(qualifiedName, value) { - if (qualifiedName === ATTR_STYLE) { - this.style = value; - } else { - this.attributes[qualifiedName] = value; - } + var ATTR_CLASS = 'class'; + var ATTR_STYLE = 'style'; - if (this.pageNode && !this.pageNode.isUnmounted) { - this.pageNode.onSetAttribute(this, qualifiedName, value); - } - } - }, { - key: "toJSON", - value: function toJSON() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - attr = _ref.attr, - normalize = _ref.normalize; + class UniBaseNode extends UniNode { + constructor(nodeType, nodeName, container) { + super(nodeType, nodeName, container); // this.style = proxyStyle(new UniCSSStyleDeclaration()) - var attributes = this.attributes, - style = this.style, - listeners = this.listeners, - _text = this._text; - var res = {}; + _defineProperty(this, "attributes", Object.create(null)); - if (Object.keys(attributes).length) { - res.a = normalize ? normalize(attributes) : attributes; - } + _defineProperty(this, "style", null); - var events = Object.keys(listeners); + _defineProperty(this, "_html", null); + } - if (events.length) { - var e = {}; - events.forEach(function (name) { - var handlers = listeners[name]; + get className() { + return this.attributes[ATTR_CLASS] || ''; + } - if (handlers.length) { - // 可能存在多个 handler 且不同 modifiers 吗? - e[name] = encodeModifier(handlers[0].modifiers || []); - } - }); - res.e = normalize ? normalize(e, false) : e; - } + set className(val) { + this.setAttribute(ATTR_CLASS, val); + } - if (style !== null) { - res.s = normalize ? normalize(style) : style; - } + get innerHTML() { + return ''; + } - if (!attr) { - res.i = this.nodeId; - res.n = this.nodeName; - } + set innerHTML(html) { + this._html = html; + } - if (_text !== null) { - res.t = normalize ? normalize(_text) : _text; - } + addEventListener(type, listener, options) { + super.addEventListener(type, listener, options); - return res; + if (this.pageNode && !this.pageNode.isUnmounted) { + this.pageNode.onAddEvent(this, normalizeEventType(type, options), encodeModifier(listener.modifiers || [])); } - }]); + } - return UniBaseNode; - }(UniNode); + removeEventListener(type, callback, options) { + super.removeEventListener(type, callback, options); - var UniCommentNode = /*#__PURE__*/function (_UniNode2) { - _inherits(UniCommentNode, _UniNode2); + if (this.pageNode && !this.pageNode.isUnmounted) { + this.pageNode.onRemoveEvent(this, normalizeEventType(type, options)); + } + } - var _super4 = _createSuper(UniCommentNode); + getAttribute(qualifiedName) { + if (qualifiedName === ATTR_STYLE) { + return this.style; + } - function UniCommentNode(text, container) { - var _this4; + return this.attributes[qualifiedName]; + } - _classCallCheck(this, UniCommentNode); + removeAttribute(qualifiedName) { + if (qualifiedName == ATTR_STYLE) { + this.style = null; + } else { + delete this.attributes[qualifiedName]; + } - _this4 = _super4.call(this, NODE_TYPE_COMMENT, '#comment', container); - _this4._text = text; - return _this4; + if (this.pageNode && !this.pageNode.isUnmounted) { + this.pageNode.onRemoveAttribute(this, qualifiedName); + } } - _createClass(UniCommentNode, [{ - key: "toJSON", - value: function toJSON() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - // 暂时不传递 text 到 view 层,没啥意义,节省点数据量 - return opts.attr ? {} : { - i: this.nodeId - }; // return opts.attr - // ? { t: this._text as string } - // : { - // i: this.nodeId!, - // t: this._text as string, - // } + setAttribute(qualifiedName, value) { + if (qualifiedName === ATTR_STYLE) { + this.style = value; + } else { + this.attributes[qualifiedName] = value; } - }]); - - return UniCommentNode; - }(UniNode); - var UniElement = /*#__PURE__*/function (_UniBaseNode) { - _inherits(UniElement, _UniBaseNode); + if (this.pageNode && !this.pageNode.isUnmounted) { + this.pageNode.onSetAttribute(this, qualifiedName, value); + } + } - var _super5 = _createSuper(UniElement); + toJSON({ + attr, + normalize + } = {}) { + var { + attributes, + style, + listeners, + _text + } = this; + var res = {}; - function UniElement(nodeName, container) { - var _this5; + if (Object.keys(attributes).length) { + res.a = normalize ? normalize(attributes) : attributes; + } - _classCallCheck(this, UniElement); + var events = Object.keys(listeners); - _this5 = _super5.call(this, NODE_TYPE_ELEMENT, nodeName.toUpperCase(), container); - _this5.tagName = _this5.nodeName; - return _this5; - } + if (events.length) { + var e = {}; + events.forEach(name => { + var handlers = listeners[name]; - return UniElement; - }(UniBaseNode); + if (handlers.length) { + // 可能存在多个 handler 且不同 modifiers 吗? + e[name] = encodeModifier(handlers[0].modifiers || []); + } + }); + res.e = normalize ? normalize(e, false) : e; + } - var UniInputElement = /*#__PURE__*/function (_UniElement) { - _inherits(UniInputElement, _UniElement); + if (style !== null) { + res.s = normalize ? normalize(style) : style; + } - var _super6 = _createSuper(UniInputElement); + if (!attr) { + res.i = this.nodeId; + res.n = this.nodeName; + } - function UniInputElement() { - _classCallCheck(this, UniInputElement); + if (_text !== null) { + res.t = normalize ? normalize(_text) : _text; + } - return _super6.apply(this, arguments); + return res; } - _createClass(UniInputElement, [{ - key: "value", - get: function get() { - return this.getAttribute('value'); - }, - set: function set(val) { - this.setAttribute('value', val); - } - }]); + } - return UniInputElement; - }(UniElement); + class UniCommentNode extends UniNode { + constructor(text, container) { + super(NODE_TYPE_COMMENT, '#comment', container); + this._text = text; + } + + toJSON(opts = {}) { + // 暂时不传递 text 到 view 层,没啥意义,节省点数据量 + return opts.attr ? {} : { + i: this.nodeId + }; // return opts.attr + // ? { t: this._text as string } + // : { + // i: this.nodeId!, + // t: this._text as string, + // } + } - var UniTextAreaElement = /*#__PURE__*/function (_UniInputElement) { - _inherits(UniTextAreaElement, _UniInputElement); + } - var _super7 = _createSuper(UniTextAreaElement); + class UniElement extends UniBaseNode { + constructor(nodeName, container) { + super(NODE_TYPE_ELEMENT, nodeName.toUpperCase(), container); - function UniTextAreaElement() { - _classCallCheck(this, UniTextAreaElement); + _defineProperty(this, "tagName", void 0); - return _super7.apply(this, arguments); + this.tagName = this.nodeName; } - return UniTextAreaElement; - }(UniInputElement); + } + + class UniInputElement extends UniElement { + get value() { + return this.getAttribute('value'); + } - var UniTextNode = /*#__PURE__*/function (_UniBaseNode2) { - _inherits(UniTextNode, _UniBaseNode2); + set value(val) { + this.setAttribute('value', val); + } - var _super8 = _createSuper(UniTextNode); + } - function UniTextNode(text, container) { - var _this6; + class UniTextAreaElement extends UniInputElement {} - _classCallCheck(this, UniTextNode); + class UniTextNode extends UniBaseNode { + constructor(text, container) { + super(NODE_TYPE_TEXT, '#text', container); + this._text = text; + } - _this6 = _super8.call(this, NODE_TYPE_TEXT, '#text', container); - _this6._text = text; - return _this6; + get nodeValue() { + return this._text || ''; } - _createClass(UniTextNode, [{ - key: "nodeValue", - get: function get() { - return this._text || ''; - }, - set: function set(text) { - this._text = text; + set nodeValue(text) { + this._text = text; - if (this.pageNode && !this.pageNode.isUnmounted) { - this.pageNode.onNodeValue(this, text); - } + if (this.pageNode && !this.pageNode.isUnmounted) { + this.pageNode.onNodeValue(this, text); } - }]); + } - return UniTextNode; - }(UniBaseNode); + } /** * Make a map and return a function for checking if a key * is in that map. @@ -750,11 +604,7 @@ export default function vueFactory(exports) { map[list[i]] = true; } - return expectsLowerCase ? function (val) { - return !!map[val.toLowerCase()]; - } : function (val) { - return !!map[val]; - }; + return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val]; } var GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' + 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' + 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt'; @@ -786,7 +636,7 @@ export default function vueFactory(exports) { function parseStringStyle(cssText) { var ret = {}; - cssText.split(listDelimiterRE).forEach(function (item) { + cssText.split(listDelimiterRE).forEach(item => { if (item) { var tmp = item.split(propertyDelimiterRE); tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); @@ -831,25 +681,21 @@ export default function vueFactory(exports) { * @private */ - var toDisplayString = function toDisplayString(val) { + var toDisplayString = val => { return val == null ? '' : isObject(val) ? JSON.stringify(val, replacer, 2) : String(val); }; - var replacer = function replacer(_key, val) { + var replacer = (_key, val) => { if (isMap(val)) { return { - ["Map(".concat(val.size, ")")]: _toConsumableArray(val.entries()).reduce(function (entries, _ref2) { - var _ref3 = _slicedToArray(_ref2, 2), - key = _ref3[0], - val = _ref3[1]; - + ["Map(".concat(val.size, ")")]: [...val.entries()].reduce((entries, [key, val]) => { entries["".concat(key, " =>")] = val; return entries; }, {}) }; } else if (isSet(val)) { return { - ["Set(".concat(val.size, ")")]: _toConsumableArray(val.values()) + ["Set(".concat(val.size, ")")]: [...val.values()] }; } else if (isObject(val) && !isArray(val) && !isPlainObject(val)) { return String(val); @@ -861,29 +707,23 @@ export default function vueFactory(exports) { var EMPTY_OBJ = process.env.NODE_ENV !== 'production' ? Object.freeze({}) : {}; var EMPTY_ARR = process.env.NODE_ENV !== 'production' ? Object.freeze([]) : []; - var NOOP = function NOOP() {}; + var NOOP = () => {}; /** * Always return false. */ - var NO = function NO() { - return false; - }; + var NO = () => false; var onRE = /^on[^a-z]/; - var isOn = function isOn(key) { - return onRE.test(key); - }; + var isOn = key => onRE.test(key); - var isModelListener = function isModelListener(key) { - return key.startsWith('onUpdate:'); - }; + var isModelListener = key => key.startsWith('onUpdate:'); var extend = Object.assign; - var remove = function remove(arr, el) { + var remove = (arr, el) => { var i = arr.indexOf(el); if (i > -1) { @@ -893,65 +733,45 @@ export default function vueFactory(exports) { var hasOwnProperty = Object.prototype.hasOwnProperty; - var hasOwn = function hasOwn(val, key) { - return hasOwnProperty.call(val, key); - }; + var hasOwn = (val, key) => hasOwnProperty.call(val, key); var isArray = Array.isArray; - var isMap = function isMap(val) { - return toTypeString(val) === '[object Map]'; - }; + var isMap = val => toTypeString(val) === '[object Map]'; - var isSet = function isSet(val) { - return toTypeString(val) === '[object Set]'; - }; + var isSet = val => toTypeString(val) === '[object Set]'; - var isFunction = function isFunction(val) { - return typeof val === 'function'; - }; + var isFunction = val => typeof val === 'function'; - var isString = function isString(val) { - return typeof val === 'string'; - }; + var isString = val => typeof val === 'string'; - var isSymbol = function isSymbol(val) { - return typeof val === 'symbol'; - }; + var isSymbol = val => typeof val === 'symbol'; - var isObject = function isObject(val) { - return val !== null && typeof val === 'object'; - }; + var isObject = val => val !== null && typeof val === 'object'; - var isPromise = function isPromise(val) { + var isPromise = val => { return isObject(val) && isFunction(val.then) && isFunction(val.catch); }; var objectToString = Object.prototype.toString; - var toTypeString = function toTypeString(value) { - return objectToString.call(value); - }; + var toTypeString = value => objectToString.call(value); - var toRawType = function toRawType(value) { + var toRawType = value => { // extract "RawType" from strings like "[object RawType]" return toTypeString(value).slice(8, -1); }; - var isPlainObject = function isPlainObject(val) { - return toTypeString(val) === '[object Object]'; - }; + var isPlainObject = val => toTypeString(val) === '[object Object]'; - var isIntegerKey = function isIntegerKey(key) { - return isString(key) && key !== 'NaN' && key[0] !== '-' && '' + parseInt(key, 10) === key; - }; + var isIntegerKey = key => isString(key) && key !== 'NaN' && key[0] !== '-' && '' + parseInt(key, 10) === key; var isReservedProp = /*#__PURE__*/makeMap( // the leading comma is intentional so empty string "" is also included ',key,ref,' + 'onVnodeBeforeMount,onVnodeMounted,' + 'onVnodeBeforeUpdate,onVnodeUpdated,' + 'onVnodeBeforeUnmount,onVnodeUnmounted'); - var cacheStringFunction = function cacheStringFunction(fn) { + var cacheStringFunction = fn => { var cache = Object.create(null); - return function (str) { + return str => { var hit = cache[str]; return hit || (cache[str] = fn(str)); }; @@ -962,45 +782,35 @@ export default function vueFactory(exports) { * @private */ - var camelize = cacheStringFunction(function (str) { - return str.replace(camelizeRE, function (_, c) { - return c ? c.toUpperCase() : ''; - }); + var camelize = cacheStringFunction(str => { + return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ''); }); var hyphenateRE = /\B([A-Z])/g; /** * @private */ - var hyphenate = cacheStringFunction(function (str) { - return str.replace(hyphenateRE, '-$1').toLowerCase(); - }); + var hyphenate = cacheStringFunction(str => str.replace(hyphenateRE, '-$1').toLowerCase()); /** * @private */ - var capitalize = cacheStringFunction(function (str) { - return str.charAt(0).toUpperCase() + str.slice(1); - }); + var capitalize = cacheStringFunction(str => str.charAt(0).toUpperCase() + str.slice(1)); /** * @private */ - var toHandlerKey = cacheStringFunction(function (str) { - return str ? "on".concat(capitalize(str)) : ""; - }); // compare whether a value has changed, accounting for NaN. + var toHandlerKey = cacheStringFunction(str => str ? "on".concat(capitalize(str)) : ""); // compare whether a value has changed, accounting for NaN. - var hasChanged = function hasChanged(value, oldValue) { - return value !== oldValue && (value === value || oldValue === oldValue); - }; + var hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue); - var invokeArrayFns = function invokeArrayFns(fns, arg) { + var invokeArrayFns = (fns, arg) => { for (var i = 0; i < fns.length; i++) { fns[i](arg); } }; - var def = function def(obj, key, value) { + var def = (obj, key, value) => { Object.defineProperty(obj, key, { configurable: true, enumerable: false, @@ -1008,14 +818,14 @@ export default function vueFactory(exports) { }); }; - var toNumber = function toNumber(val) { + var toNumber = val => { var n = parseFloat(val); return isNaN(n) ? val : n; }; var _globalThis; - var getGlobalThis = function getGlobalThis() { + var getGlobalThis = () => { return _globalThis || (_globalThis = typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof window !== 'undefined' ? window : {}); }; @@ -1029,9 +839,7 @@ export default function vueFactory(exports) { return fn && fn._isEffect === true; } - function effect(fn) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : EMPTY_OBJ; - + function effect(fn, options = EMPTY_OBJ) { if (isEffect(fn)) { fn = fn.raw; } @@ -1092,7 +900,9 @@ export default function vueFactory(exports) { } function cleanup(effect) { - var deps = effect.deps; + var { + deps + } = effect; if (deps.length) { for (var i = 0; i < deps.length; i++) { @@ -1163,9 +973,9 @@ export default function vueFactory(exports) { var effects = new Set(); - var add = function add(effectsToAdd) { + var add = effectsToAdd => { if (effectsToAdd) { - effectsToAdd.forEach(function (effect) { + effectsToAdd.forEach(effect => { if (effect !== activeEffect || effect.allowRecurse) { effects.add(effect); } @@ -1180,7 +990,7 @@ export default function vueFactory(exports) { // trigger all effects for target depsMap.forEach(add); } else if (key === 'length' && isArray(target)) { - depsMap.forEach(function (dep, key) { + depsMap.forEach((dep, key) => { if (key === 'length' || key >= newValue) { add(dep); } @@ -1233,7 +1043,7 @@ export default function vueFactory(exports) { } } - var run = function run(effect) { + var run = effect => { if (process.env.NODE_ENV !== 'production' && effect.options.onTrigger) { effect.options.onTrigger({ effect, @@ -1257,9 +1067,7 @@ export default function vueFactory(exports) { } var isNonTrackableKeys = /*#__PURE__*/makeMap("__proto__,__v_isRef,__isVue"); - var builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol).map(function (key) { - return Symbol[key]; - }).filter(isSymbol)); + var builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol).map(key => Symbol[key]).filter(isSymbol)); var get = /*#__PURE__*/createGetter(); var shallowGet = /*#__PURE__*/createGetter(false, true); var readonlyGet = /*#__PURE__*/createGetter(true); @@ -1268,10 +1076,10 @@ export default function vueFactory(exports) { function createArrayInstrumentations() { var instrumentations = {}; - ['includes', 'indexOf', 'lastIndexOf'].forEach(function (key) { + ['includes', 'indexOf', 'lastIndexOf'].forEach(key => { var method = Array.prototype[key]; - instrumentations[key] = function () { + instrumentations[key] = function (...args) { var arr = toRaw(this); for (var i = 0, l = this.length; i < l; i++) { @@ -1281,10 +1089,6 @@ export default function vueFactory(exports) { } // we run the method using the original args first (which may be reactive) - for (var _len2 = arguments.length, args = new Array(_len2), _key3 = 0; _key3 < _len2; _key3++) { - args[_key3] = arguments[_key3]; - } - var res = method.apply(arr, args); if (res === -1 || res === false) { @@ -1295,16 +1099,11 @@ export default function vueFactory(exports) { } }; }); - ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(function (key) { + ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => { var method = Array.prototype[key]; - instrumentations[key] = function () { + instrumentations[key] = function (...args) { pauseTracking(); - - for (var _len3 = arguments.length, args = new Array(_len3), _key4 = 0; _key4 < _len3; _key4++) { - args[_key4] = arguments[_key4]; - } - var res = method.apply(this, args); resetTracking(); return res; @@ -1313,9 +1112,7 @@ export default function vueFactory(exports) { return instrumentations; } - function createGetter() { - var isReadonly = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - var shallow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + function createGetter(isReadonly = false, shallow = false) { return function get(target, key, receiver) { if (key === "__v_isReactive" /* IS_REACTIVE */ @@ -1373,8 +1170,7 @@ export default function vueFactory(exports) { var set = /*#__PURE__*/createSetter(); var shallowSet = /*#__PURE__*/createSetter(true); - function createSetter() { - var shallow = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + function createSetter(shallow = false) { return function set(target, key, value, receiver) { var oldValue = target[key]; @@ -1478,25 +1274,15 @@ export default function vueFactory(exports) { get: shallowReadonlyGet }); - var toReactive = function toReactive(value) { - return isObject(value) ? reactive(value) : value; - }; + var toReactive = value => isObject(value) ? reactive(value) : value; - var toReadonly = function toReadonly(value) { - return isObject(value) ? readonly(value) : value; - }; + var toReadonly = value => isObject(value) ? readonly(value) : value; - var toShallow = function toShallow(value) { - return value; - }; + var toShallow = value => value; - var getProto = function getProto(v) { - return Reflect.getPrototypeOf(v); - }; + var getProto = v => Reflect.getPrototypeOf(v); - function get$1(target, key) { - var isReadonly = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - var isShallow = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + function get$1(target, key, isReadonly = false, isShallow = false) { // #1772: readonly(reactive(Map)) should return readonly + reactive version // of the value target = target["__v_raw" @@ -1514,10 +1300,9 @@ export default function vueFactory(exports) { !isReadonly && track(rawTarget, "get" /* GET */ , rawKey); - - var _getProto = getProto(rawTarget), - has = _getProto.has; - + var { + has + } = getProto(rawTarget); var wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive; if (has.call(rawTarget, key)) { @@ -1531,8 +1316,7 @@ export default function vueFactory(exports) { } } - function has$1(key) { - var isReadonly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + function has$1(key, isReadonly = false) { var target = this["__v_raw" /* RAW */ ]; @@ -1551,8 +1335,7 @@ export default function vueFactory(exports) { return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); } - function size(target) { - var isReadonly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + function size(target, isReadonly = false) { target = target["__v_raw" /* RAW */ ]; @@ -1581,11 +1364,10 @@ export default function vueFactory(exports) { function set$1(key, value) { value = toRaw(value); var target = toRaw(this); - - var _getProto2 = getProto(target), - has = _getProto2.has, - get = _getProto2.get; - + var { + has, + get + } = getProto(target); var hadKey = has.call(target, key); if (!hadKey) { @@ -1613,11 +1395,10 @@ export default function vueFactory(exports) { function deleteEntry(key) { var target = toRaw(this); - - var _getProto3 = getProto(target), - has = _getProto3.has, - get = _getProto3.get; - + var { + has, + get + } = getProto(target); var hadKey = has.call(target, key); if (!hadKey) { @@ -1667,7 +1448,7 @@ export default function vueFactory(exports) { !isReadonly && track(rawTarget, "iterate" /* ITERATE */ , ITERATE_KEY); - return target.forEach(function (value, key) { + return target.forEach((value, key) => { // important: make sure the callback is // 1. invoked with the reactive map as `this` and 3rd arg // 2. the value received should be a corresponding reactive/readonly. @@ -1677,7 +1458,7 @@ export default function vueFactory(exports) { } function createIterableMethod(method, isReadonly, isShallow) { - return function () { + return function (...args) { var target = this["__v_raw" /* RAW */ ]; @@ -1685,7 +1466,7 @@ export default function vueFactory(exports) { var targetIsMap = isMap(rawTarget); var isPair = method === 'entries' || method === Symbol.iterator && targetIsMap; var isKeyOnly = method === 'keys' && targetIsMap; - var innerIterator = target[method].apply(target, arguments); + var innerIterator = target[method](...args); var wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive; !isReadonly && track(rawTarget, "iterate" /* ITERATE */ @@ -1695,10 +1476,10 @@ export default function vueFactory(exports) { return { // iterator protocol next() { - var _innerIterator$next = innerIterator.next(), - value = _innerIterator$next.value, - done = _innerIterator$next.done; - + var { + value, + done + } = innerIterator.next(); return done ? { value, done @@ -1718,9 +1499,9 @@ export default function vueFactory(exports) { } function createReadonlyMethod(type) { - return function () { + return function (...args) { if (process.env.NODE_ENV !== 'production') { - var key = (arguments.length <= 0 ? undefined : arguments[0]) ? "on key \"".concat(arguments.length <= 0 ? undefined : arguments[0], "\" ") : ""; + var key = args[0] ? "on key \"".concat(args[0], "\" ") : ""; console.warn("".concat(capitalize(type), " operation ").concat(key, "failed: target is readonly."), toRaw(this)); } @@ -1818,7 +1599,7 @@ export default function vueFactory(exports) { forEach: createForEach(true, true) }; var iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator]; - iteratorMethods.forEach(function (method) { + iteratorMethods.forEach(method => { mutableInstrumentations[method] = createIterableMethod(method, false, false); readonlyInstrumentations[method] = createIterableMethod(method, true, false); shallowInstrumentations[method] = createIterableMethod(method, false, true); @@ -1827,16 +1608,11 @@ export default function vueFactory(exports) { return [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations]; } - var _createInstrumentatio = /* #__PURE__*/createInstrumentations(), - _createInstrumentatio2 = _slicedToArray(_createInstrumentatio, 4), - mutableInstrumentations = _createInstrumentatio2[0], - readonlyInstrumentations = _createInstrumentatio2[1], - shallowInstrumentations = _createInstrumentatio2[2], - shallowReadonlyInstrumentations = _createInstrumentatio2[3]; + var [mutableInstrumentations, readonlyInstrumentations, shallowInstrumentations, shallowReadonlyInstrumentations] = /* #__PURE__*/createInstrumentations(); function createInstrumentationGetter(isReadonly, shallow) { var instrumentations = shallow ? isReadonly ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly ? readonlyInstrumentations : mutableInstrumentations; - return function (target, key, receiver) { + return (target, key, receiver) => { if (key === "__v_isReactive" /* IS_REACTIVE */ ) { @@ -2031,9 +1807,7 @@ export default function vueFactory(exports) { return value; } - var convert = function convert(val) { - return isObject(val) ? reactive(val) : val; - }; + var convert = val => isObject(val) ? reactive(val) : val; function isRef(r) { return Boolean(r && r.__v_isRef === true); @@ -2047,41 +1821,34 @@ export default function vueFactory(exports) { return createRef(value, true); } - var RefImpl = /*#__PURE__*/function () { - function RefImpl(_rawValue, _shallow) { - _classCallCheck(this, RefImpl); - + class RefImpl { + constructor(_rawValue, _shallow) { this._rawValue = _rawValue; this._shallow = _shallow; this.__v_isRef = true; this._value = _shallow ? _rawValue : convert(_rawValue); } - _createClass(RefImpl, [{ - key: "value", - get: function get() { - track(toRaw(this), "get" - /* GET */ - , 'value'); - return this._value; - }, - set: function set(newVal) { - if (hasChanged(toRaw(newVal), this._rawValue)) { - this._rawValue = newVal; - this._value = this._shallow ? newVal : convert(newVal); - trigger(toRaw(this), "set" - /* SET */ - , 'value', newVal); - } - } - }]); + get value() { + track(toRaw(this), "get" + /* GET */ + , 'value'); + return this._value; + } - return RefImpl; - }(); + set value(newVal) { + if (hasChanged(toRaw(newVal), this._rawValue)) { + this._rawValue = newVal; + this._value = this._shallow ? newVal : convert(newVal); + trigger(toRaw(this), "set" + /* SET */ + , 'value', newVal); + } + } - function createRef(rawValue) { - var shallow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + } + function createRef(rawValue, shallow = false) { if (isRef(rawValue)) { return rawValue; } @@ -2100,10 +1867,8 @@ export default function vueFactory(exports) { } var shallowUnwrapHandlers = { - get: function get(target, key, receiver) { - return unref(Reflect.get(target, key, receiver)); - }, - set: function set(target, key, value, receiver) { + get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)), + set: (target, key, value, receiver) => { var oldValue = target[key]; if (isRef(oldValue) && !isRef(value)) { @@ -2119,46 +1884,30 @@ export default function vueFactory(exports) { return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); } - var CustomRefImpl = /*#__PURE__*/function () { - function CustomRefImpl(factory) { - var _this7 = this; - - _classCallCheck(this, CustomRefImpl); - + class CustomRefImpl { + constructor(factory) { this.__v_isRef = true; - - var _factory = factory(function () { - return track(_this7, "get" - /* GET */ - , - /* GET */ - 'value'); - }, function () { - return trigger(_this7, "set" - /* SET */ - , - /* SET */ - 'value'); - }), - get = _factory.get, - set = _factory.set; - + var { + get, + set + } = factory(() => track(this, "get" + /* GET */ + , 'value'), () => trigger(this, "set" + /* SET */ + , 'value')); this._get = get; this._set = set; } - _createClass(CustomRefImpl, [{ - key: "value", - get: function get() { - return this._get(); - }, - set: function set(newVal) { - this._set(newVal); - } - }]); + get value() { + return this._get(); + } - return CustomRefImpl; - }(); + set value(newVal) { + this._set(newVal); + } + + } function customRef(factory) { return new CustomRefImpl(factory); @@ -2178,47 +1927,38 @@ export default function vueFactory(exports) { return ret; } - var ObjectRefImpl = /*#__PURE__*/function () { - function ObjectRefImpl(_object, _key) { - _classCallCheck(this, ObjectRefImpl); - + class ObjectRefImpl { + constructor(_object, _key) { this._object = _object; this._key = _key; this.__v_isRef = true; } - _createClass(ObjectRefImpl, [{ - key: "value", - get: function get() { - return this._object[this._key]; - }, - set: function set(newVal) { - this._object[this._key] = newVal; - } - }]); + get value() { + return this._object[this._key]; + } + + set value(newVal) { + this._object[this._key] = newVal; + } - return ObjectRefImpl; - }(); + } function toRef(object, key) { return isRef(object[key]) ? object[key] : new ObjectRefImpl(object, key); } - var ComputedRefImpl = /*#__PURE__*/function () { - function ComputedRefImpl(getter, _setter, isReadonly) { - var _this8 = this; - - _classCallCheck(this, ComputedRefImpl); - + class ComputedRefImpl { + constructor(getter, _setter, isReadonly) { this._setter = _setter; this._dirty = true; this.__v_isRef = true; this.effect = effect(getter, { lazy: true, - scheduler: function scheduler() { - if (!_this8._dirty) { - _this8._dirty = true; - trigger(toRaw(_this8), "set" + scheduler: () => { + if (!this._dirty) { + this._dirty = true; + trigger(toRaw(this), "set" /* SET */ , 'value'); } @@ -2229,29 +1969,26 @@ export default function vueFactory(exports) { ] = isReadonly; } - _createClass(ComputedRefImpl, [{ - key: "value", - get: function get() { - // the computed ref may get wrapped by other proxies e.g. readonly() #3376 - var self = toRaw(this); + get value() { + // the computed ref may get wrapped by other proxies e.g. readonly() #3376 + var self = toRaw(this); - if (self._dirty) { - self._value = this.effect(); - self._dirty = false; - } - - track(self, "get" - /* GET */ - , 'value'); - return self._value; - }, - set: function set(newValue) { - this._setter(newValue); + if (self._dirty) { + self._value = this.effect(); + self._dirty = false; } - }]); - return ComputedRefImpl; - }(); + track(self, "get" + /* GET */ + , 'value'); + return self._value; + } + + set value(newValue) { + this._setter(newValue); + } + + } function computed(getterOrOptions) { var getter; @@ -2259,7 +1996,7 @@ export default function vueFactory(exports) { if (isFunction(getterOrOptions)) { getter = getterOrOptions; - setter = process.env.NODE_ENV !== 'production' ? function () { + setter = process.env.NODE_ENV !== 'production' ? () => { console.warn('Write operation failed: computed value is readonly'); } : NOOP; } else { @@ -2280,7 +2017,7 @@ export default function vueFactory(exports) { stack.pop(); } - function warn(msg) { + function warn(msg, ...args) { // avoid props formatting or warn handler tracking deps that might be mutated // during patch, leading to infinite recursion. pauseTracking(); @@ -2288,29 +2025,22 @@ export default function vueFactory(exports) { var appWarnHandler = instance && instance.appContext.config.warnHandler; var trace = getComponentTrace(); - for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key5 = 1; _key5 < _len4; _key5++) { - args[_key5 - 1] = arguments[_key5]; - } - if (appWarnHandler) { callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */ - , [msg + args.join(''), instance && instance.proxy, trace.map(function (_ref4) { - var vnode = _ref4.vnode; - return "at <".concat(formatComponentName(instance, vnode.type), ">"); - }).join('\n'), trace]); + , [msg + args.join(''), instance && instance.proxy, trace.map(({ + vnode + }) => "at <".concat(formatComponentName(instance, vnode.type), ">")).join('\n'), trace]); } else { - var _console; - - var warnArgs = ["[Vue warn]: ".concat(msg)].concat(args); + var warnArgs = ["[Vue warn]: ".concat(msg), ...args]; /* istanbul ignore if */ if (trace.length && // avoid spamming console during tests !false) { - warnArgs.push.apply(warnArgs, ["\n"].concat(_toConsumableArray(formatTrace(trace)))); + warnArgs.push("\n", ...formatTrace(trace)); } - (_console = console).warn.apply(_console, _toConsumableArray(warnArgs)); + console.warn(...warnArgs); } resetTracking(); @@ -2351,20 +2081,21 @@ export default function vueFactory(exports) { function formatTrace(trace) { var logs = []; - trace.forEach(function (entry, i) { - logs.push.apply(logs, _toConsumableArray(i === 0 ? [] : ["\n"]).concat(_toConsumableArray(formatTraceEntry(entry)))); + trace.forEach((entry, i) => { + logs.push(...(i === 0 ? [] : ["\n"]), ...formatTraceEntry(entry)); }); return logs; } - function formatTraceEntry(_ref5) { - var vnode = _ref5.vnode, - recurseCount = _ref5.recurseCount; + function formatTraceEntry({ + vnode, + recurseCount + }) { var postfix = recurseCount > 0 ? "... (".concat(recurseCount, " recursive calls)") : ""; var isRoot = vnode.component ? vnode.component.parent == null : false; var open = " at <".concat(formatComponentName(vnode.component, vnode.type, isRoot)); var close = ">" + postfix; - return vnode.props ? [open].concat(_toConsumableArray(formatProps(vnode.props)), [close]) : [open + close]; + return vnode.props ? [open, ...formatProps(vnode.props), close] : [open + close]; } /* istanbul ignore next */ @@ -2372,8 +2103,8 @@ export default function vueFactory(exports) { function formatProps(props) { var res = []; var keys = Object.keys(props); - keys.slice(0, 3).forEach(function (key) { - res.push.apply(res, _toConsumableArray(formatProp(key, props[key]))); + keys.slice(0, 3).forEach(key => { + res.push(...formatProp(key, props[key])); }); if (keys.length > 3) { @@ -2496,7 +2227,7 @@ export default function vueFactory(exports) { var res; try { - res = args ? fn.apply(void 0, _toConsumableArray(args)) : fn(); + res = args ? fn(...args) : fn(); } catch (err) { handleError(err, instance, type); } @@ -2509,7 +2240,7 @@ export default function vueFactory(exports) { var res = callWithErrorHandling(fn, instance, type, args); if (res && isPromise(res)) { - res.catch(function (err) { + res.catch(err => { handleError(err, instance, type); }); } @@ -2526,8 +2257,7 @@ export default function vueFactory(exports) { return values; } - function handleError(err, instance, type) { - var throwInDev = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; + function handleError(err, instance, type, throwInDev = true) { var contextVNode = instance ? instance.vnode : null; if (instance) { @@ -2565,9 +2295,7 @@ export default function vueFactory(exports) { logError(err, type, contextVNode, throwInDev); } - function logError(err, type, contextVNode) { - var throwInDev = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; - + function logError(err, type, contextVNode, throwInDev = true) { if (process.env.NODE_ENV !== 'production') { var info = ErrorTypeStrings[type]; @@ -2676,7 +2404,7 @@ export default function vueFactory(exports) { // if cb is an array, it is a component lifecycle hook which can only be // triggered by a job, which is already deduped in the main queue, so // we can skip duplicate check here to improve perf - pendingQueue.push.apply(pendingQueue, _toConsumableArray(cb)); + pendingQueue.push(...cb); } queueFlush(); @@ -2690,12 +2418,10 @@ export default function vueFactory(exports) { queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex); } - function flushPreFlushCbs(seen) { - var parentJob = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; - + function flushPreFlushCbs(seen, parentJob = null) { if (pendingPreFlushCbs.length) { currentPreFlushParentJob = parentJob; - activePreFlushCbs = _toConsumableArray(new Set(pendingPreFlushCbs)); + activePreFlushCbs = [...new Set(pendingPreFlushCbs)]; pendingPreFlushCbs.length = 0; if (process.env.NODE_ENV !== 'production') { @@ -2720,15 +2446,11 @@ export default function vueFactory(exports) { function flushPostFlushCbs(seen) { if (pendingPostFlushCbs.length) { - var deduped = _toConsumableArray(new Set(pendingPostFlushCbs)); - + var deduped = [...new Set(pendingPostFlushCbs)]; pendingPostFlushCbs.length = 0; // #1947 already has active queue, nested flushPostFlushCbs call if (activePostFlushCbs) { - var _activePostFlushCbs; - - (_activePostFlushCbs = activePostFlushCbs).push.apply(_activePostFlushCbs, _toConsumableArray(deduped)); - + activePostFlushCbs.push(...deduped); return; } @@ -2738,9 +2460,7 @@ export default function vueFactory(exports) { seen = seen || new Map(); } - activePostFlushCbs.sort(function (a, b) { - return getId(a) - getId(b); - }); + activePostFlushCbs.sort((a, b) => getId(a) - getId(b)); for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) { if (process.env.NODE_ENV !== 'production' && checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) { @@ -2755,9 +2475,7 @@ export default function vueFactory(exports) { } } - var getId = function getId(job) { - return job.id == null ? Infinity : job.id; - }; + var getId = job => job.id == null ? Infinity : job.id; function flushJobs(seen) { isFlushPending = false; @@ -2775,9 +2493,7 @@ export default function vueFactory(exports) { // 2. If a component is unmounted during a parent component's update, // its update can be skipped. - queue.sort(function (a, b) { - return getId(a) - getId(b); - }); + queue.sort((a, b) => getId(a) - getId(b)); try { for (flushIndex = 0; flushIndex < queue.length; flushIndex++) { @@ -2883,7 +2599,7 @@ export default function vueFactory(exports) { if (newRender) record.component.render = newRender; // Array.from creates a snapshot which avoids the set being mutated during // updates - Array.from(record.instances).forEach(function (instance) { + Array.from(record.instances).forEach(instance => { if (newRender) { instance.render = newRender; } @@ -2901,8 +2617,10 @@ export default function vueFactory(exports) { if (!record) return; // Array.from creates a snapshot which avoids the set being mutated during // updates - var component = record.component, - instances = record.instances; + var { + component, + instances + } = record; if (!hmrDirtyComponents.has(component)) { // 1. Update existing comp definition to match new one @@ -2919,12 +2637,12 @@ export default function vueFactory(exports) { hmrDirtyComponents.add(component); // 3. Make sure to unmark the component after the reload. - queuePostFlushCb(function () { + queuePostFlushCb(() => { hmrDirtyComponents.delete(component); }); } - Array.from(instances).forEach(function (instance) { + Array.from(instances).forEach(instance => { if (instance.parent) { // 4. Force the parent instance to re-render. This will cause all updated // components to be unmounted and re-mounted. Queue the update so that we @@ -2943,7 +2661,7 @@ export default function vueFactory(exports) { } function tryWrap(fn) { - return function (id, arg) { + return (id, arg) => { try { return fn(id, arg); } catch (e) { @@ -2990,7 +2708,7 @@ export default function vueFactory(exports) { ); function createDevtoolsComponentHook(hook) { - return function (component) { + return component => { if (!devtools) return; devtools.emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component); }; @@ -3004,7 +2722,7 @@ export default function vueFactory(exports) { ); function createDevtoolsPerformanceHook(hook) { - return function (component, type, time) { + return (component, type, time) => { if (!devtools) return; devtools.emit(hook, component.appContext.app, component.uid, component, type, time); }; @@ -3031,9 +2749,7 @@ export default function vueFactory(exports) { return globalCompatConfig[key]; } - function isCompatEnabled(key, instance) { - var enableForBuiltIn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - + function isCompatEnabled(key, instance, enableForBuiltIn = false) { // skip compat for built-in components if (!enableForBuiltIn && instance && instance.type.__isBuiltIn) { return false; @@ -3050,17 +2766,14 @@ export default function vueFactory(exports) { } } - function emit(instance, event) { + function emit(instance, event, ...rawArgs) { var props = instance.vnode.props || EMPTY_OBJ; - for (var _len5 = arguments.length, rawArgs = new Array(_len5 > 2 ? _len5 - 2 : 0), _key6 = 2; _key6 < _len5; _key6++) { - rawArgs[_key6 - 2] = arguments[_key6]; - } - if (process.env.NODE_ENV !== 'production') { - var emitsOptions = instance.emitsOptions, - _instance$propsOption = _slicedToArray(instance.propsOptions, 1), - propsOptions = _instance$propsOption[0]; + var { + emitsOptions, + propsOptions: [propsOptions] + } = instance; if (emitsOptions) { if (!(event in emitsOptions) && !false) { @@ -3071,7 +2784,7 @@ export default function vueFactory(exports) { var validator = emitsOptions[event]; if (isFunction(validator)) { - var isValid = validator.apply(void 0, rawArgs); + var isValid = validator(...rawArgs); if (!isValid) { warn("Invalid event arguments: event validation failed for event \"".concat(event, "\".")); @@ -3088,15 +2801,13 @@ export default function vueFactory(exports) { if (modelArg && modelArg in props) { var modifiersKey = "".concat(modelArg === 'modelValue' ? 'model' : modelArg, "Modifiers"); - - var _ref6 = props[modifiersKey] || EMPTY_OBJ, - number = _ref6.number, - trim = _ref6.trim; + var { + number, + trim + } = props[modifiersKey] || EMPTY_OBJ; if (trim) { - args = rawArgs.map(function (a) { - return a.trim(); - }); + args = rawArgs.map(a => a.trim()); } else if (number) { args = rawArgs.map(toNumber); } @@ -3145,8 +2856,7 @@ export default function vueFactory(exports) { } } - function normalizeEmitsOptions(comp, appContext) { - var asMixin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + function normalizeEmitsOptions(comp, appContext, asMixin = false) { var cache = appContext.emitsCache; var cached = cache.get(comp); @@ -3160,7 +2870,7 @@ export default function vueFactory(exports) { var hasExtends = false; if (!isFunction(comp)) { - var extendEmits = function extendEmits(raw) { + var extendEmits = raw => { var normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true); if (normalizedFromExtend) { @@ -3188,9 +2898,7 @@ export default function vueFactory(exports) { } if (isArray(raw)) { - raw.forEach(function (key) { - return normalized[key] = null; - }); + raw.forEach(key => normalized[key] = null); } else { extend(normalized, raw); } @@ -3260,26 +2968,22 @@ export default function vueFactory(exports) { */ - var withScopeId = function withScopeId(_id) { - return withCtx; - }; + var withScopeId = _id => withCtx; /** * Wrap a slot function to memoize current rendering instance * @private compiler helper */ - function withCtx(fn) // false only - { - var ctx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : currentRenderingInstance; - var isNonScopedSlot = arguments.length > 2 ? arguments[2] : undefined; + function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only + ) { if (!ctx) return fn; // already normalized if (fn._n) { return fn; } - var renderFnWithContext = function renderFnWithContext() { + var renderFnWithContext = (...args) => { // If a user calls a compiled slot inside a template expression (#1745), it // can mess up block tracking, so by default we disable block tracking and // force bail out when invoking a compiled slot (indicated by the ._d flag). @@ -3290,7 +2994,7 @@ export default function vueFactory(exports) { } var prevInstance = setCurrentRenderingInstance(ctx); - var res = fn.apply(void 0, arguments); + var res = fn(...args); setCurrentRenderingInstance(prevInstance); if (renderFnWithContext._d) { @@ -3328,23 +3032,23 @@ export default function vueFactory(exports) { } function renderComponentRoot(instance) { - var Component = instance.type, - vnode = instance.vnode, - proxy = instance.proxy, - withProxy = instance.withProxy, - props = instance.props, - _instance$propsOption2 = _slicedToArray(instance.propsOptions, 1), - propsOptions = _instance$propsOption2[0], - slots = instance.slots, - attrs = instance.attrs, - emit = instance.emit, - render = instance.render, - renderCache = instance.renderCache, - data = instance.data, - setupState = instance.setupState, - ctx = instance.ctx, - inheritAttrs = instance.inheritAttrs; - + var { + type: Component, + vnode, + proxy, + withProxy, + props, + propsOptions: [propsOptions], + slots, + attrs, + emit, + render, + renderCache, + data, + setupState, + ctx, + inheritAttrs + } = instance; var result; var prev = setCurrentRenderingInstance(instance); @@ -3399,19 +3103,14 @@ export default function vueFactory(exports) { /* DEV_ROOT_FRAGMENT */ ) { ; - - var _getChildRoot = getChildRoot(result); - - var _getChildRoot2 = _slicedToArray(_getChildRoot, 2); - - root = _getChildRoot2[0]; - setRoot = _getChildRoot2[1]; + [root, setRoot] = getChildRoot(result); } if (fallthroughAttrs && inheritAttrs !== false) { var keys = Object.keys(fallthroughAttrs); - var _root = root, - shapeFlag = _root.shapeFlag; + var { + shapeFlag + } = root; if (keys.length) { if (shapeFlag & 1 @@ -3510,7 +3209,7 @@ export default function vueFactory(exports) { */ - var getChildRoot = function getChildRoot(vnode) { + var getChildRoot = vnode => { var rawChildren = vnode.children; var dynamicChildren = vnode.dynamicChildren; var childRoot = filterSingleRoot(rawChildren); @@ -3522,14 +3221,14 @@ export default function vueFactory(exports) { var index = rawChildren.indexOf(childRoot); var dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1; - var setRoot = function setRoot(updatedRoot) { + var setRoot = updatedRoot => { rawChildren[index] = updatedRoot; if (dynamicChildren) { if (dynamicIndex > -1) { dynamicChildren[dynamicIndex] = updatedRoot; } else if (updatedRoot.patchFlag > 0) { - vnode.dynamicChildren = [].concat(_toConsumableArray(dynamicChildren), [updatedRoot]); + vnode.dynamicChildren = [...dynamicChildren, updatedRoot]; } } }; @@ -3561,7 +3260,7 @@ export default function vueFactory(exports) { return singleRoot; } - var getFunctionalFallthrough = function getFunctionalFallthrough(attrs) { + var getFunctionalFallthrough = attrs => { var res; for (var key in attrs) { @@ -3573,7 +3272,7 @@ export default function vueFactory(exports) { return res; }; - var filterModelListeners = function filterModelListeners(attrs, props) { + var filterModelListeners = (attrs, props) => { var res = {}; for (var key in attrs) { @@ -3585,7 +3284,7 @@ export default function vueFactory(exports) { return res; }; - var isElementRoot = function isElementRoot(vnode) { + var isElementRoot = vnode => { return vnode.shapeFlag & 6 /* COMPONENT */ || vnode.shapeFlag & 1 @@ -3595,12 +3294,16 @@ export default function vueFactory(exports) { }; function shouldUpdateComponent(prevVNode, nextVNode, optimized) { - var prevProps = prevVNode.props, - prevChildren = prevVNode.children, - component = prevVNode.component; - var nextProps = nextVNode.props, - nextChildren = nextVNode.children, - patchFlag = nextVNode.patchFlag; + var { + props: prevProps, + children: prevChildren, + component + } = prevVNode; + var { + props: nextProps, + children: nextChildren, + patchFlag + } = nextVNode; var emits = component.emitsOptions; // Parent component's render function was hot-updated. Since this may have // caused the child component's slots content to have changed, we need to // force the child to update as well. @@ -3690,20 +3393,18 @@ export default function vueFactory(exports) { return false; } - function updateHOCHostEl(_ref7, el // HostNode + function updateHOCHostEl({ + vnode, + parent + }, el // HostNode ) { - var vnode = _ref7.vnode, - parent = _ref7.parent; - while (parent && parent.subTree === vnode) { (vnode = parent.vnode).el = el; parent = parent.parent; } } - var isSuspense = function isSuspense(type) { - return type.__isSuspense; - }; // Suspense exposes a component-like API, and is treated like a component + var isSuspense = type => type.__isSuspense; // Suspense exposes a component-like API, and is treated like a component // in the compiler, but internally it's a special built-in type that hooks // directly into the renderer. @@ -3741,8 +3442,12 @@ export default function vueFactory(exports) { } function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) { - var patch = rendererInternals.p, - createElement = rendererInternals.o.createElement; + var { + p: patch, + o: { + createElement + } + } = rendererInternals; var hiddenContainer = createElement('div', container); // fixed by xxxxxx var suspense = vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals); // start mounting the content subtree in an off-dom container @@ -3764,19 +3469,24 @@ export default function vueFactory(exports) { } } - function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, _ref8) { - var patch = _ref8.p, - unmount = _ref8.um, - createElement = _ref8.o.createElement; + function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { + p: patch, + um: unmount, + o: { + createElement + } + }) { var suspense = n2.suspense = n1.suspense; suspense.vnode = n2; n2.el = n1.el; var newBranch = n2.ssContent; var newFallback = n2.ssFallback; - var activeBranch = suspense.activeBranch, - pendingBranch = suspense.pendingBranch, - isInFallback = suspense.isInFallback, - isHydrating = suspense.isHydrating; + var { + activeBranch, + pendingBranch, + isInFallback, + isHydrating + } = suspense; if (pendingBranch) { suspense.pendingBranch = newBranch; @@ -3857,11 +3567,13 @@ export default function vueFactory(exports) { // incoming branch has no async deps, resolve now. suspense.resolve(); } else { - var timeout = suspense.timeout, - pendingId = suspense.pendingId; + var { + timeout, + pendingId + } = suspense; if (timeout > 0) { - setTimeout(function () { + setTimeout(() => { if (suspense.pendingId === pendingId) { suspense.fallback(newFallback); } @@ -3876,9 +3588,7 @@ export default function vueFactory(exports) { var hasWarned = false; - function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals) { - var isHydrating = arguments.length > 10 && arguments[10] !== undefined ? arguments[10] : false; - + function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !false && !hasWarned) { hasWarned = true; // @ts-ignore `console.info` cannot be null error @@ -3886,13 +3596,16 @@ export default function vueFactory(exports) { console[console.info ? 'info' : 'log'](" is an experimental feature and its API will likely change."); } - var patch = rendererInternals.p, - move = rendererInternals.m, - unmount = rendererInternals.um, - next = rendererInternals.n, - _rendererInternals$o = rendererInternals.o, - parentNode = _rendererInternals$o.parentNode, - remove = _rendererInternals$o.remove; + var { + p: patch, + m: move, + um: unmount, + n: next, + o: { + parentNode, + remove + } + } = rendererInternals; var timeout = toNumber(vnode.props && vnode.props.timeout); var suspense = { vnode, @@ -3912,9 +3625,7 @@ export default function vueFactory(exports) { isUnmounted: false, effects: [], - resolve() { - var resume = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - + resolve(resume = false) { if (process.env.NODE_ENV !== 'production') { if (!resume && !suspense.pendingBranch) { throw new Error("suspense.resolve() is called without a pending branch."); @@ -3925,13 +3636,15 @@ export default function vueFactory(exports) { } } - var vnode = suspense.vnode, - activeBranch = suspense.activeBranch, - pendingBranch = suspense.pendingBranch, - pendingId = suspense.pendingId, - effects = suspense.effects, - parentComponent = suspense.parentComponent, - container = suspense.container; + var { + vnode, + activeBranch, + pendingBranch, + pendingId, + effects, + parentComponent, + container + } = suspense; if (suspense.isHydrating) { suspense.isHydrating = false; @@ -3939,7 +3652,7 @@ export default function vueFactory(exports) { var delayEnter = activeBranch && pendingBranch.transition && pendingBranch.transition.mode === 'out-in'; if (delayEnter) { - activeBranch.transition.afterLeave = function () { + activeBranch.transition.afterLeave = () => { if (pendingId === suspense.pendingId) { move(pendingBranch, container, _anchor, 0 /* ENTER */ @@ -3949,7 +3662,9 @@ export default function vueFactory(exports) { } // this is initial anchor on mount - var _anchor = suspense.anchor; // unmount current active tree + var { + anchor: _anchor + } = suspense; // unmount current active tree if (activeBranch) { // if the fallback tree was mounted, it may have been moved @@ -3976,12 +3691,9 @@ export default function vueFactory(exports) { while (parent) { if (parent.pendingBranch) { - var _parent$effects; - // found a pending parent suspense, merge buffered post jobs // into that parent - (_parent$effects = parent.effects).push.apply(_parent$effects, _toConsumableArray(effects)); - + parent.effects.push(...effects); hasUnresolvedAncestor = true; break; } @@ -4004,16 +3716,18 @@ export default function vueFactory(exports) { return; } - var vnode = suspense.vnode, - activeBranch = suspense.activeBranch, - parentComponent = suspense.parentComponent, - container = suspense.container, - isSVG = suspense.isSVG; // invoke @fallback event + var { + vnode, + activeBranch, + parentComponent, + container, + isSVG + } = suspense; // invoke @fallback event triggerEvent(vnode, 'onFallback'); var anchor = next(activeBranch); - var mountFallback = function mountFallback() { + var mountFallback = () => { if (!suspense.isInFallback) { return; } // mount the fallback tree @@ -4058,11 +3772,11 @@ export default function vueFactory(exports) { } var hydratedEl = instance.vnode.el; - instance.asyncDep.catch(function (err) { + instance.asyncDep.catch(err => { handleError(err, instance, 0 /* SETUP_FUNCTION */ ); - }).then(function (asyncSetupResult) { + }).then(asyncSetupResult => { // retry when the setup() promise resolves. // component may have been unmounted before resolve. if (instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId) { @@ -4071,7 +3785,9 @@ export default function vueFactory(exports) { instance.asyncResolved = true; - var vnode = instance.vnode; + var { + vnode + } = instance; if (process.env.NODE_ENV !== 'production') { pushWarningContext(vnode); @@ -4148,8 +3864,10 @@ export default function vueFactory(exports) { } function normalizeSuspenseChildren(vnode) { - var shapeFlag = vnode.shapeFlag, - children = vnode.children; + var { + shapeFlag, + children + } = vnode; var isSlotChildren = shapeFlag & 32 /* SLOTS_CHILDREN */ ; @@ -4193,9 +3911,7 @@ export default function vueFactory(exports) { s = normalizeVNode(s); if (block) { - s.dynamicChildren = block.filter(function (c) { - return c !== s; - }); + s.dynamicChildren = block.filter(c => c !== s); } return s; @@ -4204,9 +3920,7 @@ export default function vueFactory(exports) { function queueEffectWithSuspense(fn, suspense) { if (suspense && suspense.pendingBranch) { if (isArray(fn)) { - var _suspense$effects; - - (_suspense$effects = suspense.effects).push.apply(_suspense$effects, _toConsumableArray(fn)); + suspense.effects.push(...fn); } else { suspense.effects.push(fn); } @@ -4217,8 +3931,10 @@ export default function vueFactory(exports) { function setActiveBranch(suspense, branch) { suspense.activeBranch = branch; - var vnode = suspense.vnode, - parentComponent = suspense.parentComponent; + var { + vnode, + parentComponent + } = suspense; var el = vnode.el = branch.el; // in case suspense is the root node of a component, // recursively update the HOC el @@ -4251,8 +3967,7 @@ export default function vueFactory(exports) { } } - function inject(key, defaultValue) { - var treatDefaultAsFactory = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + function inject(key, defaultValue, treatDefaultAsFactory = false) { // fallback to `currentRenderingInstance` so that this can be called in // a functional component var instance = currentInstance || currentRenderingInstance; @@ -4292,16 +4007,13 @@ export default function vueFactory(exports) { return doWatch(source, cb, options); } - function doWatch(source, cb) { - var _ref9 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJ, - immediate = _ref9.immediate, - deep = _ref9.deep, - flush = _ref9.flush, - onTrack = _ref9.onTrack, - onTrigger = _ref9.onTrigger; - - var instance = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : currentInstance; - + function doWatch(source, cb, { + immediate, + deep, + flush, + onTrack, + onTrigger + } = EMPTY_OBJ, instance = currentInstance) { if (process.env.NODE_ENV !== 'production' && !cb) { if (immediate !== undefined) { warn("watch() \"immediate\" option is only respected when using the " + "watch(source, callback, options?) signature."); @@ -4312,7 +4024,7 @@ export default function vueFactory(exports) { } } - var warnInvalidSource = function warnInvalidSource(s) { + var warnInvalidSource = s => { warn("Invalid watch source: ", s, "A watch source can only be a getter/effect function, a ref, " + "a reactive object, or an array of these types."); }; @@ -4321,47 +4033,39 @@ export default function vueFactory(exports) { var isMultiSource = false; if (isRef(source)) { - getter = function getter() { - return source.value; - }; + getter = () => source.value; forceTrigger = !!source._shallow; } else if (isReactive(source)) { - getter = function getter() { - return source; - }; + getter = () => source; deep = true; } else if (isArray(source)) { isMultiSource = true; forceTrigger = source.some(isReactive); - getter = function getter() { - return source.map(function (s) { - if (isRef(s)) { - return s.value; - } else if (isReactive(s)) { - return traverse(s); - } else if (isFunction(s)) { - return callWithErrorHandling(s, instance, 2 - /* WATCH_GETTER */ - ); - } else { - process.env.NODE_ENV !== 'production' && warnInvalidSource(s); - } - }); - }; + getter = () => source.map(s => { + if (isRef(s)) { + return s.value; + } else if (isReactive(s)) { + return traverse(s); + } else if (isFunction(s)) { + return callWithErrorHandling(s, instance, 2 + /* WATCH_GETTER */ + ); + } else { + process.env.NODE_ENV !== 'production' && warnInvalidSource(s); + } + }); } else if (isFunction(source)) { if (cb) { // getter with cb - getter = function getter() { - return callWithErrorHandling(source, instance, 2 - /* WATCH_GETTER */ - ); - }; + getter = () => callWithErrorHandling(source, instance, 2 + /* WATCH_GETTER */ + ); } else { // no cb -> simple effect - getter = function getter() { + getter = () => { if (instance && instance.isUnmounted) { return; } @@ -4383,15 +4087,13 @@ export default function vueFactory(exports) { if (cb && deep) { var baseGetter = getter; - getter = function getter() { - return traverse(baseGetter()); - }; + getter = () => traverse(baseGetter()); } var cleanup; - var onInvalidate = function onInvalidate(fn) { - cleanup = runner.options.onStop = function () { + var onInvalidate = fn => { + cleanup = runner.options.onStop = () => { callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */ ); @@ -4400,7 +4102,7 @@ export default function vueFactory(exports) { var oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE; - var job = function job() { + var job = () => { if (!runner.active) { return; } @@ -4409,9 +4111,7 @@ export default function vueFactory(exports) { // watch(source, cb) var newValue = runner(); - if (deep || forceTrigger || (isMultiSource ? newValue.some(function (v, i) { - return hasChanged(v, oldValue[i]); - }) : hasChanged(newValue, oldValue)) || false) { + if (deep || forceTrigger || (isMultiSource ? newValue.some((v, i) => hasChanged(v, oldValue[i])) : hasChanged(newValue, oldValue)) || false) { // cleanup before running cb again if (cleanup) { cleanup(); @@ -4437,12 +4137,10 @@ export default function vueFactory(exports) { if (flush === 'sync') { scheduler = job; // the scheduler function gets called directly } else if (flush === 'post') { - scheduler = function scheduler() { - return queuePostRenderEffect(job, instance && instance.suspense); - }; + scheduler = () => queuePostRenderEffect(job, instance && instance.suspense); } else { // default: 'pre' - scheduler = function scheduler() { + scheduler = () => { if (!instance || instance.isMounted) { queuePreFlushCb(job); } else { @@ -4473,7 +4171,7 @@ export default function vueFactory(exports) { runner(); } - return function () { + return () => { stop(runner); if (instance) { @@ -4485,9 +4183,7 @@ export default function vueFactory(exports) { function instanceWatch(source, value, options) { var publicThis = this.proxy; - var getter = isString(source) ? source.includes('.') ? createPathGetter(publicThis, source) : function () { - return publicThis[source]; - } : source.bind(publicThis, publicThis); + var getter = isString(source) ? source.includes('.') ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis); var cb; if (isFunction(value)) { @@ -4502,7 +4198,7 @@ export default function vueFactory(exports) { function createPathGetter(ctx, path) { var segments = path.split('.'); - return function () { + return () => { var cur = ctx; for (var i = 0; i < segments.length && cur; i++) { @@ -4513,9 +4209,7 @@ export default function vueFactory(exports) { }; } - function traverse(value) { - var seen = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Set(); - + function traverse(value, seen = new Set()) { if (!isObject(value) || seen.has(value) || value["__v_skip" /* SKIP */ ]) { @@ -4531,7 +4225,7 @@ export default function vueFactory(exports) { traverse(value[i], seen); } } else if (isSet(value) || isMap(value)) { - value.forEach(function (v) { + value.forEach(v => { traverse(v, seen); }); } else if (isPlainObject(value)) { @@ -4550,10 +4244,10 @@ export default function vueFactory(exports) { isUnmounting: false, leavingVNodes: new Map() }; - onMounted(function () { + onMounted(() => { state.isMounted = true; }); - onBeforeUnmount(function () { + onBeforeUnmount(() => { state.isUnmounting = true; }); return state; @@ -4583,12 +4277,13 @@ export default function vueFactory(exports) { onAppearCancelled: TransitionHookValidator }, - setup(props, _ref10) { - var slots = _ref10.slots; + setup(props, { + slots + }) { var instance = getCurrentInstance(); var state = useTransitionState(); var prevTransitionKey; - return function () { + return () => { var children = slots.default && getTransitionRawChildren(slots.default(), true); if (!children || !children.length) { @@ -4603,7 +4298,9 @@ export default function vueFactory(exports) { var rawProps = toRaw(props); - var mode = rawProps.mode; // check mode + var { + mode + } = rawProps; // check mode if (process.env.NODE_ENV !== 'production' && mode && !['in-out', 'out-in', 'default'].includes(mode)) { warn("invalid mode: ".concat(mode)); @@ -4629,7 +4326,9 @@ export default function vueFactory(exports) { var oldChild = instance.subTree; var oldInnerChild = oldChild && getKeepAliveChild(oldChild); var transitionKeyChanged = false; - var getTransitionKey = innerChild.type.getTransitionKey; + var { + getTransitionKey + } = innerChild.type; if (getTransitionKey) { var key = getTransitionKey(); @@ -4651,18 +4350,18 @@ export default function vueFactory(exports) { if (mode === 'out-in') { state.isLeaving = true; // return placeholder node and queue update when leave finishes - leavingHooks.afterLeave = function () { + leavingHooks.afterLeave = () => { state.isLeaving = false; instance.update(); }; return emptyPlaceholder(child); } else if (mode === 'in-out' && innerChild.type !== Comment$1) { - leavingHooks.delayLeave = function (el, earlyRemove, delayedLeave) { + leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => { var leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild); leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild; // early removal callback - el._leaveCb = function () { + el._leaveCb = () => { earlyRemove(); el._leaveCb = undefined; delete enterHooks.delayedLeave; @@ -4683,7 +4382,9 @@ export default function vueFactory(exports) { var BaseTransition = BaseTransitionImpl; function getLeavingNodesForType(state, vnode) { - var leavingVNodes = state.leavingVNodes; + var { + leavingVNodes + } = state; var leavingVNodesCache = leavingVNodes.get(vnode.type); if (!leavingVNodesCache) { @@ -4697,26 +4398,27 @@ export default function vueFactory(exports) { function resolveTransitionHooks(vnode, props, state, instance) { - var appear = props.appear, - mode = props.mode, - _props$persisted = props.persisted, - persisted = _props$persisted === void 0 ? false : _props$persisted, - onBeforeEnter = props.onBeforeEnter, - onEnter = props.onEnter, - onAfterEnter = props.onAfterEnter, - onEnterCancelled = props.onEnterCancelled, - onBeforeLeave = props.onBeforeLeave, - onLeave = props.onLeave, - onAfterLeave = props.onAfterLeave, - onLeaveCancelled = props.onLeaveCancelled, - onBeforeAppear = props.onBeforeAppear, - onAppear = props.onAppear, - onAfterAppear = props.onAfterAppear, - onAppearCancelled = props.onAppearCancelled; + var { + appear, + mode, + persisted = false, + onBeforeEnter, + onEnter, + onAfterEnter, + onEnterCancelled, + onBeforeLeave, + onLeave, + onAfterLeave, + onLeaveCancelled, + onBeforeAppear, + onAppear, + onAfterAppear, + onAppearCancelled + } = props; var key = String(vnode.key); var leavingVNodesCache = getLeavingNodesForType(state, vnode); - var callHook = function callHook(hook, args) { + var callHook = (hook, args) => { hook && callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */ , args); @@ -4772,7 +4474,7 @@ export default function vueFactory(exports) { var called = false; - var done = el._enterCb = function (cancelled) { + var done = el._enterCb = cancelled => { if (called) return; called = true; @@ -4816,7 +4518,7 @@ export default function vueFactory(exports) { callHook(onBeforeLeave, [el]); var called = false; - var done = el._leaveCb = function (cancelled) { + var done = el._leaveCb = cancelled => { if (called) return; called = true; remove(); @@ -4886,8 +4588,7 @@ export default function vueFactory(exports) { } } - function getTransitionRawChildren(children) { - var keepComment = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + function getTransitionRawChildren(children, keepComment = false) { var ret = []; var keyedFragmentCount = 0; @@ -4910,8 +4611,8 @@ export default function vueFactory(exports) { if (keyedFragmentCount > 1) { - for (var _i2 = 0; _i2 < ret.length; _i2++) { - ret[_i2].patchFlag = -2 + for (var _i = 0; _i < ret.length; _i++) { + ret[_i].patchFlag = -2 /* BAIL */ ; } @@ -4928,9 +4629,7 @@ export default function vueFactory(exports) { } : options; } - var isAsyncWrapper = function isAsyncWrapper(i) { - return !!i.type.__asyncLoader; - }; + var isAsyncWrapper = i => !!i.type.__asyncLoader; function defineAsyncComponent(source) { if (isFunction(source)) { @@ -4939,47 +4638,43 @@ export default function vueFactory(exports) { }; } - var _source = source, - loader = _source.loader, - loadingComponent = _source.loadingComponent, - errorComponent = _source.errorComponent, - _source$delay = _source.delay, - delay = _source$delay === void 0 ? 200 : _source$delay, - timeout = _source.timeout, - _source$suspensible = _source.suspensible, - suspensible = _source$suspensible === void 0 ? true : _source$suspensible, - userOnError = _source.onError; + var { + loader, + loadingComponent, + errorComponent, + delay = 200, + timeout, + // undefined = never times out + suspensible = true, + onError: userOnError + } = source; var pendingRequest = null; var resolvedComp; var retries = 0; - var retry = function retry() { + var retry = () => { retries++; pendingRequest = null; return load(); }; - var load = function load() { + var load = () => { var thisRequest; - return pendingRequest || (thisRequest = pendingRequest = loader().catch(function (err) { + return pendingRequest || (thisRequest = pendingRequest = loader().catch(err => { err = err instanceof Error ? err : new Error(String(err)); if (userOnError) { - return new Promise(function (resolve, reject) { - var userRetry = function userRetry() { - return resolve(retry()); - }; + return new Promise((resolve, reject) => { + var userRetry = () => resolve(retry()); - var userFail = function userFail() { - return reject(err); - }; + var userFail = () => reject(err); userOnError(err, userRetry, userFail, retries + 1); }); } else { throw err; } - }).then(function (comp) { + }).then(comp => { if (thisRequest !== pendingRequest && pendingRequest) { return pendingRequest; } @@ -5014,12 +4709,10 @@ export default function vueFactory(exports) { var instance = currentInstance; // already resolved if (resolvedComp) { - return function () { - return createInnerComp(resolvedComp, instance); - }; + return () => createInnerComp(resolvedComp, instance); } - var onError = function onError(err) { + var onError = err => { pendingRequest = null; handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */ @@ -5030,17 +4723,13 @@ export default function vueFactory(exports) { if (suspensible && instance.suspense || false) { - return load().then(function (comp) { - return function () { - return createInnerComp(comp, instance); - }; - }).catch(function (err) { + return load().then(comp => { + return () => createInnerComp(comp, instance); + }).catch(err => { onError(err); - return function () { - return errorComponent ? createVNode(errorComponent, { - error: err - }) : null; - }; + return () => errorComponent ? createVNode(errorComponent, { + error: err + }) : null; }); } @@ -5049,13 +4738,13 @@ export default function vueFactory(exports) { var delayed = ref(!!delay); if (delay) { - setTimeout(function () { + setTimeout(() => { delayed.value = false; }, delay); } if (timeout != null) { - setTimeout(function () { + setTimeout(() => { if (!loaded.value && !error.value) { var err = new Error("Async component timed out after ".concat(timeout, "ms.")); onError(err); @@ -5064,7 +4753,7 @@ export default function vueFactory(exports) { }, timeout); } - load().then(function () { + load().then(() => { loaded.value = true; if (instance.parent && isKeepAlive(instance.parent.vnode)) { @@ -5072,11 +4761,11 @@ export default function vueFactory(exports) { // name is taken into account queueJob(instance.parent.update); } - }).catch(function (err) { + }).catch(err => { onError(err); error.value = err; }); - return function () { + return () => { if (loaded.value && resolvedComp) { return createInnerComp(resolvedComp, instance); } else if (error.value && errorComponent) { @@ -5092,20 +4781,20 @@ export default function vueFactory(exports) { }); } - function createInnerComp(comp, _ref11) { - var _ref11$vnode = _ref11.vnode, - ref = _ref11$vnode.ref, - props = _ref11$vnode.props, - children = _ref11$vnode.children; + function createInnerComp(comp, { + vnode: { + ref, + props, + children + } + }) { var vnode = createVNode(comp, props, children); // ensure inner component inherits the async wrapper's ref owner vnode.ref = ref; return vnode; } - var isKeepAlive = function isKeepAlive(vnode) { - return vnode.type.__isKeepAlive; - }; + var isKeepAlive = vnode => vnode.type.__isKeepAlive; var KeepAliveImpl = { name: "KeepAlive", @@ -5119,8 +4808,9 @@ export default function vueFactory(exports) { max: [String, Number] }, - setup(props, _ref12) { - var slots = _ref12.slots; + setup(props, { + slots + }) { var instance = getCurrentInstance(); // KeepAlive communicates with the instantiated renderer via the // ctx where the renderer passes in its internals, // and the KeepAlive instance exposes activate/deactivate implementations. @@ -5143,21 +4833,26 @@ export default function vueFactory(exports) { } var parentSuspense = instance.suspense; - var _sharedContext$render = sharedContext.renderer, - patch = _sharedContext$render.p, - move = _sharedContext$render.m, - _unmount = _sharedContext$render.um, - createElement = _sharedContext$render.o.createElement; + var { + renderer: { + p: patch, + m: move, + um: _unmount, + o: { + createElement + } + } + } = sharedContext; var storageContainer = createElement('div', null); // fixed by xxxxx - sharedContext.activate = function (vnode, container, anchor, isSVG, optimized) { + sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => { var instance = vnode.component; move(vnode, container, anchor, 0 /* ENTER */ , parentSuspense); // in case props have changed patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized); - queuePostRenderEffect(function () { + queuePostRenderEffect(() => { instance.isDeactivated = false; if (instance.a) { @@ -5177,12 +4872,12 @@ export default function vueFactory(exports) { } }; - sharedContext.deactivate = function (vnode) { + sharedContext.deactivate = vnode => { var instance = vnode.component; move(vnode, storageContainer, null, 1 /* LEAVE */ , parentSuspense); - queuePostRenderEffect(function () { + queuePostRenderEffect(() => { if (instance.da) { invokeArrayFns(instance.da); } @@ -5210,7 +4905,7 @@ export default function vueFactory(exports) { } function pruneCache(filter) { - cache.forEach(function (vnode, key) { + cache.forEach((vnode, key) => { var name = getComponentName(vnode.type); if (name && (!filter || !filter(name))) { @@ -5235,19 +4930,9 @@ export default function vueFactory(exports) { } // prune cache on include/exclude prop change - watch(function () { - return [props.include, props.exclude]; - }, function (_ref13) { - var _ref14 = _slicedToArray(_ref13, 2), - include = _ref14[0], - exclude = _ref14[1]; - - include && pruneCache(function (name) { - return matches(include, name); - }); - exclude && pruneCache(function (name) { - return !matches(exclude, name); - }); + watch(() => [props.include, props.exclude], ([include, exclude]) => { + include && pruneCache(name => matches(include, name)); + exclude && pruneCache(name => !matches(exclude, name)); }, // prune post-render after `current` has been updated { flush: 'post', @@ -5256,7 +4941,7 @@ export default function vueFactory(exports) { var pendingCacheKey = null; - var cacheSubtree = function cacheSubtree() { + var cacheSubtree = () => { // fix #1621, the pendingCacheKey could be 0 if (pendingCacheKey != null) { cache.set(pendingCacheKey, getInnerChild(instance.subTree)); @@ -5265,10 +4950,12 @@ export default function vueFactory(exports) { onMounted(cacheSubtree); onUpdated(cacheSubtree); - onBeforeUnmount(function () { - cache.forEach(function (cached) { - var subTree = instance.subTree, - suspense = instance.suspense; + onBeforeUnmount(() => { + cache.forEach(cached => { + var { + subTree, + suspense + } = instance; var vnode = getInnerChild(subTree); if (cached.type === vnode.type) { @@ -5283,7 +4970,7 @@ export default function vueFactory(exports) { unmount(cached); }); }); - return function () { + return () => { pendingCacheKey = null; if (!slots.default) { @@ -5314,9 +5001,11 @@ export default function vueFactory(exports) { // inner component if available var name = getComponentName(isAsyncWrapper(vnode) ? vnode.type.__asyncResolved || {} : comp); - var include = props.include, - exclude = props.exclude, - max = props.max; + var { + include, + exclude, + max + } = props; if (include && (!name || !matches(include, name)) || exclude && name && matches(exclude, name)) { current = vnode; @@ -5384,9 +5073,7 @@ export default function vueFactory(exports) { function matches(pattern, name) { if (isArray(pattern)) { - return pattern.some(function (p) { - return matches(p, name); - }); + return pattern.some(p => matches(p, name)); } else if (isString(pattern)) { return pattern.split(',').indexOf(name) > -1; } else if (pattern.test) { @@ -5410,13 +5097,11 @@ export default function vueFactory(exports) { , target); } - function registerKeepAliveHook(hook, type) { - var target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : currentInstance; - + function registerKeepAliveHook(hook, type, target = currentInstance) { // cache the deactivate branch check wrapper for injected hooks so the same // hook can be properly deduped by the scheduler. "__wdc" stands for "with // deactivation check". - var wrappedHook = hook.__wdc || (hook.__wdc = function () { + var wrappedHook = hook.__wdc || (hook.__wdc = () => { // only fire the hook if the target instance is NOT in a deactivated branch. var current = target; @@ -5456,7 +5141,7 @@ export default function vueFactory(exports) { var injected = injectHook(type, hook, keepAliveRoot, true /* prepend */ ); - onUnmounted(function () { + onUnmounted(() => { remove(keepAliveRoot[type], injected); }, target); } @@ -5489,16 +5174,13 @@ export default function vueFactory(exports) { ? vnode.ssContent : vnode; } - function injectHook(type, hook) { - var target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : currentInstance; - var prepend = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - + function injectHook(type, hook, target = currentInstance, prepend = false) { if (target) { var hooks = target[type] || (target[type] = []); // cache the error handling wrapper for injected hooks so the same hook // can be properly deduped by the scheduler. "__weh" stands for "with error // handling". - var wrappedHook = hook.__weh || (hook.__weh = function () { + var wrappedHook = hook.__weh || (hook.__weh = (...args) => { if (target.isUnmounted) { return; } // disable tracking inside all lifecycle hooks @@ -5510,11 +5192,6 @@ export default function vueFactory(exports) { // can only be false when the user does something really funky. setCurrentInstance(target); - - for (var _len6 = arguments.length, args = new Array(_len6), _key7 = 0; _key7 < _len6; _key7++) { - args[_key7] = arguments[_key7]; - } - var res = callWithAsyncErrorHandling(hook, target, type, args); setCurrentInstance(null); resetTracking(); @@ -5534,16 +5211,10 @@ export default function vueFactory(exports) { } } - var createHook = function createHook(lifecycle) { - return function (hook) { - var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : currentInstance; - return (// post-create lifecycle registrations are noops during SSR (except for serverPrefetch) - (!isInSSRComponentSetup || lifecycle === "sp" - /* SERVER_PREFETCH */ - ) && injectHook(lifecycle, hook, target) - ); - }; - }; + var createHook = lifecycle => (hook, target = currentInstance) => // post-create lifecycle registrations are noops during SSR (except for serverPrefetch) + (!isInSSRComponentSetup || lifecycle === "sp" + /* SERVER_PREFETCH */ + ) && injectHook(lifecycle, hook, target); var onBeforeMount = createHook("bm" /* BEFORE_MOUNT */ @@ -5573,8 +5244,7 @@ export default function vueFactory(exports) { /* RENDER_TRACKED */ ); - function onErrorCaptured(hook) { - var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : currentInstance; + function onErrorCaptured(hook, target = currentInstance) { injectHook("ec" /* ERROR_CAPTURED */ , hook, target); @@ -5582,7 +5252,7 @@ export default function vueFactory(exports) { function createDuplicateChecker() { var cache = Object.create(null); - return function (type, key) { + return (type, key) => { if (cache[key]) { warn("".concat(type, " property \"").concat(key, "\" is already defined in ").concat(cache[key], ".")); } else { @@ -5607,38 +5277,43 @@ export default function vueFactory(exports) { ); } - var dataOptions = options.data, - computedOptions = options.computed, - methods = options.methods, - watchOptions = options.watch, - provideOptions = options.provide, - injectOptions = options.inject, - created = options.created, - beforeMount = options.beforeMount, - mounted = options.mounted, - beforeUpdate = options.beforeUpdate, - updated = options.updated, - activated = options.activated, - deactivated = options.deactivated, - beforeDestroy = options.beforeDestroy, - beforeUnmount = options.beforeUnmount, - destroyed = options.destroyed, - unmounted = options.unmounted, - render = options.render, - renderTracked = options.renderTracked, - renderTriggered = options.renderTriggered, - errorCaptured = options.errorCaptured, - serverPrefetch = options.serverPrefetch, - expose = options.expose, - inheritAttrs = options.inheritAttrs, - components = options.components, - directives = options.directives, - filters = options.filters; + var { + // state + data: dataOptions, + computed: computedOptions, + methods, + watch: watchOptions, + provide: provideOptions, + inject: injectOptions, + // lifecycle + created, + beforeMount, + mounted, + beforeUpdate, + updated, + activated, + deactivated, + beforeDestroy, + beforeUnmount, + destroyed, + unmounted, + render, + renderTracked, + renderTriggered, + errorCaptured, + serverPrefetch, + // public API + expose, + inheritAttrs, + // assets + components, + directives, + filters + } = options; var checkDuplicateProperties = process.env.NODE_ENV !== 'production' ? createDuplicateChecker() : null; if (process.env.NODE_ENV !== 'production') { - var _instance$propsOption3 = _slicedToArray(instance.propsOptions, 1), - propsOptions = _instance$propsOption3[0]; + var [propsOptions] = instance.propsOptions; if (propsOptions) { for (var key in propsOptions) { @@ -5661,30 +5336,30 @@ export default function vueFactory(exports) { } if (methods) { - for (var _key8 in methods) { - var methodHandler = methods[_key8]; + for (var _key2 in methods) { + var methodHandler = methods[_key2]; if (isFunction(methodHandler)) { // In dev mode, we use the `createRenderContext` function to define methods to the proxy target, // and those are read-only but reconfigurable, so it needs to be redefined here if (process.env.NODE_ENV !== 'production') { - Object.defineProperty(ctx, _key8, { + Object.defineProperty(ctx, _key2, { value: methodHandler.bind(publicThis), configurable: true, enumerable: true, writable: true }); } else { - ctx[_key8] = methodHandler.bind(publicThis); + ctx[_key2] = methodHandler.bind(publicThis); } if (process.env.NODE_ENV !== 'production') { checkDuplicateProperties("Methods" /* METHODS */ - , _key8); + , _key2); } } else if (process.env.NODE_ENV !== 'production') { - warn("Method \"".concat(_key8, "\" has type \"").concat(typeof methodHandler, "\" in the component definition. ") + "Did you reference the function correctly?"); + warn("Method \"".concat(_key2, "\" has type \"").concat(typeof methodHandler, "\" in the component definition. ") + "Did you reference the function correctly?"); } } } @@ -5707,25 +5382,23 @@ export default function vueFactory(exports) { instance.data = reactive(data); if (process.env.NODE_ENV !== 'production') { - var _loop = function _loop(_key9) { + var _loop = function (_key3) { checkDuplicateProperties("Data" /* DATA */ - , _key9); // expose data on ctx during dev + , _key3); // expose data on ctx during dev - if (_key9[0] !== '$' && _key9[0] !== '_') { - Object.defineProperty(ctx, _key9, { + if (_key3[0] !== '$' && _key3[0] !== '_') { + Object.defineProperty(ctx, _key3, { configurable: true, enumerable: true, - get: function get() { - return data[_key9]; - }, + get: () => data[_key3], set: NOOP }); } }; - for (var _key9 in data) { - _loop(_key9); + for (var _key3 in data) { + _loop(_key3); } } } @@ -5736,53 +5409,49 @@ export default function vueFactory(exports) { shouldCacheAccess = true; if (computedOptions) { - var _loop2 = function _loop2(_key10) { - var opt = computedOptions[_key10]; + var _loop2 = function (_key4) { + var opt = computedOptions[_key4]; var get = isFunction(opt) ? opt.bind(publicThis, publicThis) : isFunction(opt.get) ? opt.get.bind(publicThis, publicThis) : NOOP; if (process.env.NODE_ENV !== 'production' && get === NOOP) { - warn("Computed property \"".concat(_key10, "\" has no getter.")); + warn("Computed property \"".concat(_key4, "\" has no getter.")); } - var set = !isFunction(opt) && isFunction(opt.set) ? opt.set.bind(publicThis) : process.env.NODE_ENV !== 'production' ? function () { - warn("Write operation failed: computed property \"".concat(_key10, "\" is readonly.")); + var set = !isFunction(opt) && isFunction(opt.set) ? opt.set.bind(publicThis) : process.env.NODE_ENV !== 'production' ? () => { + warn("Write operation failed: computed property \"".concat(_key4, "\" is readonly.")); } : NOOP; var c = computed$1({ get, set }); - Object.defineProperty(ctx, _key10, { + Object.defineProperty(ctx, _key4, { enumerable: true, configurable: true, - get: function get() { - return c.value; - }, - set: function set(v) { - return c.value = v; - } + get: () => c.value, + set: v => c.value = v }); if (process.env.NODE_ENV !== 'production') { checkDuplicateProperties("Computed" /* COMPUTED */ - , _key10); + , _key4); } }; - for (var _key10 in computedOptions) { - _loop2(_key10); + for (var _key4 in computedOptions) { + _loop2(_key4); } } if (watchOptions) { - for (var _key11 in watchOptions) { - createWatcher(watchOptions[_key11], ctx, publicThis, _key11); + for (var _key5 in watchOptions) { + createWatcher(watchOptions[_key5], ctx, publicThis, _key5); } } if (provideOptions) { var provides = isFunction(provideOptions) ? provideOptions.call(publicThis) : provideOptions; - Reflect.ownKeys(provides).forEach(function (key) { + Reflect.ownKeys(provides).forEach(key => { provide(key, provides[key]); }); } @@ -5795,9 +5464,7 @@ export default function vueFactory(exports) { function registerLifecycleHook(register, hook) { if (isArray(hook)) { - hook.forEach(function (_hook) { - return register(_hook.bind(publicThis)); - }); + hook.forEach(_hook => register(_hook.bind(publicThis))); } else if (hook) { register(hook.bind(publicThis)); } @@ -5819,14 +5486,10 @@ export default function vueFactory(exports) { if (isArray(expose)) { if (expose.length) { var exposed = instance.exposed || (instance.exposed = {}); - expose.forEach(function (key) { + expose.forEach(key => { Object.defineProperty(exposed, key, { - get: function get() { - return publicThis[key]; - }, - set: function set(val) { - return publicThis[key] = val; - } + get: () => publicThis[key], + set: val => publicThis[key] = val }); }); } else if (!instance.exposed) { @@ -5855,9 +5518,7 @@ export default function vueFactory(exports) { } } - function resolveInjections(injectOptions, ctx) { - var checkDuplicateProperties = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : NOOP; - + function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP) { if (isArray(injectOptions)) { injectOptions = normalizeInject(injectOptions); } @@ -5886,15 +5547,11 @@ export default function vueFactory(exports) { } function callHook(hook, instance, type) { - callWithAsyncErrorHandling(isArray(hook) ? hook.map(function (h) { - return h.bind(instance.proxy); - }) : hook.bind(instance.proxy), instance, type); + callWithAsyncErrorHandling(isArray(hook) ? hook.map(h => h.bind(instance.proxy)) : hook.bind(instance.proxy), instance, type); } function createWatcher(raw, ctx, publicThis, key) { - var getter = key.includes('.') ? createPathGetter(publicThis, key) : function () { - return publicThis[key]; - }; + var getter = key.includes('.') ? createPathGetter(publicThis, key) : () => publicThis[key]; if (isString(raw)) { var handler = ctx[raw]; @@ -5908,9 +5565,7 @@ export default function vueFactory(exports) { watch(getter, raw.bind(publicThis)); } else if (isObject(raw)) { if (isArray(raw)) { - raw.forEach(function (r) { - return createWatcher(r, ctx, publicThis, key); - }); + raw.forEach(r => createWatcher(r, ctx, publicThis, key)); } else { var _handler = isFunction(raw.handler) ? raw.handler.bind(publicThis) : ctx[raw.handler]; @@ -5933,12 +5588,17 @@ export default function vueFactory(exports) { function resolveMergedOptions(instance) { var base = instance.type; - var mixins = base.mixins, - extendsOptions = base.extends; - var _instance$appContext = instance.appContext, - globalMixins = _instance$appContext.mixins, - cache = _instance$appContext.optionsCache, - optionMergeStrategies = _instance$appContext.config.optionMergeStrategies; + var { + mixins, + extends: extendsOptions + } = base; + var { + mixins: globalMixins, + optionsCache: cache, + config: { + optionMergeStrategies + } + } = instance.appContext; var cached = cache.get(base); var resolved; @@ -5952,9 +5612,7 @@ export default function vueFactory(exports) { resolved = {}; if (globalMixins.length) { - globalMixins.forEach(function (m) { - return mergeOptions(resolved, m, optionMergeStrategies, true); - }); + globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true)); } mergeOptions(resolved, base, optionMergeStrategies); @@ -5964,19 +5622,18 @@ export default function vueFactory(exports) { return resolved; } - function mergeOptions(to, from, strats) { - var asMixin = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - var mixins = from.mixins, - extendsOptions = from.extends; + function mergeOptions(to, from, strats, asMixin = false) { + var { + mixins, + extends: extendsOptions + } = from; if (extendsOptions) { mergeOptions(to, extendsOptions, strats, true); } if (mixins) { - mixins.forEach(function (m) { - return mergeOptions(to, m, strats, true); - }); + mixins.forEach(m => mergeOptions(to, m, strats, true)); } for (var key in from) { @@ -6054,7 +5711,7 @@ export default function vueFactory(exports) { } function mergeAsArray(to, from) { - return to ? _toConsumableArray(new Set([].concat(to, from))) : from; + return to ? [...new Set([].concat(to, from))] : from; } function mergeObjectOptions(to, from) { @@ -6073,8 +5730,8 @@ export default function vueFactory(exports) { return merged; } - function initProps(instance, rawProps, isStateful) { - var isSSR = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison + isSSR = false) { var props = {}; var attrs = {}; def(attrs, InternalObjectKey, 1); @@ -6109,14 +5766,15 @@ export default function vueFactory(exports) { } function updateProps(instance, rawProps, rawPrevProps, optimized) { - var props = instance.props, - attrs = instance.attrs, - patchFlag = instance.vnode.patchFlag; + var { + props, + attrs, + vnode: { + patchFlag + } + } = instance; var rawCurrentProps = toRaw(props); - - var _instance$propsOption4 = _slicedToArray(instance.propsOptions, 1), - options = _instance$propsOption4[0]; - + var [options] = instance.propsOptions; var hasAttrsChanged = false; if ( // always force full diff in dev @@ -6169,21 +5827,21 @@ export default function vueFactory(exports) { var kebabKey; - for (var _key12 in rawCurrentProps) { + for (var _key6 in rawCurrentProps) { if (!rawProps || // for camelCase - !hasOwn(rawProps, _key12) && ( // it's possible the original props was passed in as kebab-case + !hasOwn(rawProps, _key6) && ( // it's possible the original props was passed in as kebab-case // and converted to camelCase (#955) - (kebabKey = hyphenate(_key12)) === _key12 || !hasOwn(rawProps, kebabKey))) { + (kebabKey = hyphenate(_key6)) === _key6 || !hasOwn(rawProps, kebabKey))) { if (options) { if (rawPrevProps && ( // for camelCase - rawPrevProps[_key12] !== undefined || // for kebab-case + rawPrevProps[_key6] !== undefined || // for kebab-case rawPrevProps[kebabKey] !== undefined)) { - props[_key12] = resolvePropValue(options, rawCurrentProps, _key12, undefined, instance, true + props[_key6] = resolvePropValue(options, rawCurrentProps, _key6, undefined, instance, true /* isAbsent */ ); } } else { - delete props[_key12]; + delete props[_key6]; } } } // in the case of functional component w/o props declaration, props and @@ -6191,9 +5849,9 @@ export default function vueFactory(exports) { if (attrs !== rawCurrentProps) { - for (var _key13 in attrs) { - if (!rawProps || !hasOwn(rawProps, _key13)) { - delete attrs[_key13]; + for (var _key7 in attrs) { + if (!rawProps || !hasOwn(rawProps, _key7)) { + delete attrs[_key7]; hasAttrsChanged = true; } } @@ -6213,10 +5871,7 @@ export default function vueFactory(exports) { } function setFullProps(instance, rawProps, props, attrs) { - var _instance$propsOption5 = _slicedToArray(instance.propsOptions, 2), - options = _instance$propsOption5[0], - needCastKeys = _instance$propsOption5[1]; - + var [options, needCastKeys] = instance.propsOptions; var hasAttrsChanged = false; var rawCastValues; @@ -6252,8 +5907,8 @@ export default function vueFactory(exports) { var castValues = rawCastValues || EMPTY_OBJ; for (var i = 0; i < needCastKeys.length; i++) { - var _key14 = needCastKeys[i]; - props[_key14] = resolvePropValue(options, rawCurrentProps, _key14, castValues[_key14], instance, !hasOwn(castValues, _key14)); + var _key8 = needCastKeys[i]; + props[_key8] = resolvePropValue(options, rawCurrentProps, _key8, castValues[_key8], instance, !hasOwn(castValues, _key8)); } } @@ -6270,7 +5925,9 @@ export default function vueFactory(exports) { var defaultValue = opt.default; if (opt.type !== Function && isFunction(defaultValue)) { - var propsDefaults = instance.propsDefaults; + var { + propsDefaults + } = instance; if (key in propsDefaults) { value = propsDefaults[key]; @@ -6301,8 +5958,7 @@ export default function vueFactory(exports) { return value; } - function normalizePropsOptions(comp, appContext) { - var asMixin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + function normalizePropsOptions(comp, appContext, asMixin = false) { var cache = appContext.propsCache; var cached = cache.get(comp); @@ -6317,16 +5973,11 @@ export default function vueFactory(exports) { var hasExtends = false; if (!isFunction(comp)) { - var extendProps = function extendProps(raw) { + var extendProps = raw => { hasExtends = true; - - var _normalizePropsOption = normalizePropsOptions(raw, appContext, true), - _normalizePropsOption2 = _slicedToArray(_normalizePropsOption, 2), - props = _normalizePropsOption2[0], - keys = _normalizePropsOption2[1]; - + var [props, keys] = normalizePropsOptions(raw, appContext, true); extend(normalized, props); - if (keys) needCastKeys.push.apply(needCastKeys, _toConsumableArray(keys)); + if (keys) needCastKeys.push(...keys); }; if (!asMixin && appContext.mixins.length) { @@ -6419,9 +6070,7 @@ export default function vueFactory(exports) { function getTypeIndex(type, expectedTypes) { if (isArray(expectedTypes)) { - return expectedTypes.findIndex(function (t) { - return isSameType(t, type); - }); + return expectedTypes.findIndex(t => isSameType(t, type)); } else if (isFunction(expectedTypes)) { return isSameType(expectedTypes, type) ? 0 : -1; } @@ -6449,9 +6098,11 @@ export default function vueFactory(exports) { function validateProp(name, value, prop, isAbsent) { - var type = prop.type, - required = prop.required, - validator = prop.validator; // required! + var { + type, + required, + validator + } = prop; // required! if (required && isAbsent) { warn('Missing required prop: "' + name + '"'); @@ -6470,10 +6121,10 @@ export default function vueFactory(exports) { var expectedTypes = []; // value is valid as long as one of the specified types match for (var i = 0; i < types.length && !isValid; i++) { - var _assertType = assertType(value, types[i]), - valid = _assertType.valid, - expectedType = _assertType.expectedType; - + var { + valid, + expectedType + } = assertType(value, types[i]); expectedTypes.push(expectedType || ''); isValid = valid; } @@ -6564,35 +6215,23 @@ export default function vueFactory(exports) { function isExplicable(type) { var explicitTypes = ['string', 'number', 'boolean']; - return explicitTypes.some(function (elem) { - return type.toLowerCase() === elem; - }); + return explicitTypes.some(elem => type.toLowerCase() === elem); } /** * dev only */ - function isBoolean() { - for (var _len7 = arguments.length, args = new Array(_len7), _key15 = 0; _key15 < _len7; _key15++) { - args[_key15] = arguments[_key15]; - } - - return args.some(function (elem) { - return elem.toLowerCase() === 'boolean'; - }); + function isBoolean(...args) { + return args.some(elem => elem.toLowerCase() === 'boolean'); } - var isInternalKey = function isInternalKey(key) { - return key[0] === '_' || key === '$stable'; - }; + var isInternalKey = key => key[0] === '_' || key === '$stable'; - var normalizeSlotValue = function normalizeSlotValue(value) { - return isArray(value) ? value.map(normalizeVNode) : [normalizeVNode(value)]; - }; + var normalizeSlotValue = value => isArray(value) ? value.map(normalizeVNode) : [normalizeVNode(value)]; - var normalizeSlot = function normalizeSlot(key, rawSlot, ctx) { - var normalized = withCtx(function (props) { + var normalizeSlot = (key, rawSlot, ctx) => { + var normalized = withCtx(props => { if (process.env.NODE_ENV !== 'production' && currentInstance) { warn("Slot \"".concat(key, "\" invoked outside of the render function: ") + "this will not track dependencies used in the slot. " + "Invoke the slot function inside the render function instead."); } @@ -6603,7 +6242,7 @@ export default function vueFactory(exports) { return normalized; }; - var normalizeObjectSlots = function normalizeObjectSlots(rawSlots, slots, instance) { + var normalizeObjectSlots = (rawSlots, slots, instance) => { var ctx = rawSlots._ctx; for (var key in rawSlots) { @@ -6620,27 +6259,23 @@ export default function vueFactory(exports) { var normalized = normalizeSlotValue(value); - slots[key] = function () { - return normalized; - }; + slots[key] = () => normalized; })(); } } }; - var normalizeVNodeSlots = function normalizeVNodeSlots(instance, children) { + var normalizeVNodeSlots = (instance, children) => { if (process.env.NODE_ENV !== 'production' && !isKeepAlive(instance.vnode) && !false) { warn("Non-function value encountered for default slot. " + "Prefer function slots for better performance."); } var normalized = normalizeSlotValue(children); - instance.slots.default = function () { - return normalized; - }; + instance.slots.default = () => normalized; }; - var initSlots = function initSlots(instance, children) { + var initSlots = (instance, children) => { if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */ ) { @@ -6666,9 +6301,11 @@ export default function vueFactory(exports) { def(instance.slots, InternalObjectKey, 1); }; - var updateSlots = function updateSlots(instance, children, optimized) { - var vnode = instance.vnode, - slots = instance.slots; + var updateSlots = (instance, children, optimized) => { + var { + vnode, + slots + } = instance; var needDeletionCheck = true; var deletionComparisonTarget = EMPTY_OBJ; @@ -6764,12 +6401,7 @@ export default function vueFactory(exports) { var bindings = vnode.dirs || (vnode.dirs = []); for (var i = 0; i < directives.length; i++) { - var _directives$i = _slicedToArray(directives[i], 4), - dir = _directives$i[0], - value = _directives$i[1], - arg = _directives$i[2], - _directives$i$ = _directives$i[3], - modifiers = _directives$i$ === void 0 ? EMPTY_OBJ : _directives$i$; + var [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i]; if (isFunction(dir)) { dir = { @@ -6841,9 +6473,7 @@ export default function vueFactory(exports) { var uid$1 = 0; function createAppAPI(render, hydrate) { - return function createApp(rootComponent) { - var rootProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; - + return function createApp(rootComponent, rootProps = null) { if (rootProps != null && !isObject(rootProps)) { process.env.NODE_ENV !== 'production' && warn("root props passed to app.mount() must be an object."); rootProps = null; @@ -6871,19 +6501,15 @@ export default function vueFactory(exports) { } }, - use(plugin) { - for (var _len8 = arguments.length, options = new Array(_len8 > 1 ? _len8 - 1 : 0), _key16 = 1; _key16 < _len8; _key16++) { - options[_key16 - 1] = arguments[_key16]; - } - + use(plugin, ...options) { if (installedPlugins.has(plugin)) { process.env.NODE_ENV !== 'production' && warn("Plugin has already been applied to target app."); } else if (plugin && isFunction(plugin.install)) { installedPlugins.add(plugin); - plugin.install.apply(plugin, [app].concat(options)); + plugin.install(app, ...options); } else if (isFunction(plugin)) { installedPlugins.add(plugin); - plugin.apply(void 0, [app].concat(options)); + plugin(app, ...options); } else if (process.env.NODE_ENV !== 'production') { warn("A plugin must either be a function or an object with an \"install\" " + "function."); } @@ -6944,7 +6570,7 @@ export default function vueFactory(exports) { vnode.appContext = context; // HMR root reload if (process.env.NODE_ENV !== 'production') { - context.reload = function () { + context.reload = () => { render(cloneVNode(vnode), rootContainer, isSVG); }; } @@ -7003,13 +6629,9 @@ export default function vueFactory(exports) { var hasMismatch = false; - var isSVGContainer = function isSVGContainer(container) { - return /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject'; - }; + var isSVGContainer = container => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject'; - var isComment = function isComment(node) { - return node.nodeType === 8; - } + var isComment = node => node.nodeType === 8 /* COMMENT */ ; // Note: hydration is DOM-specific // But we have to place it in core due to tight coupling with core - splitting @@ -7019,17 +6641,20 @@ export default function vueFactory(exports) { function createHydrationFunctions(rendererInternals) { - var mountComponent = rendererInternals.mt, - patch = rendererInternals.p, - _rendererInternals$o2 = rendererInternals.o, - patchProp = _rendererInternals$o2.patchProp, - nextSibling = _rendererInternals$o2.nextSibling, - parentNode = _rendererInternals$o2.parentNode, - remove = _rendererInternals$o2.remove, - insert = _rendererInternals$o2.insert, - createComment = _rendererInternals$o2.createComment; - - var hydrate = function hydrate(vnode, container) { + var { + mt: mountComponent, + p: patch, + o: { + patchProp, + nextSibling, + parentNode, + remove, + insert, + createComment + } + } = rendererInternals; + + var hydrate = (vnode, container) => { if (!container.hasChildNodes()) { process.env.NODE_ENV !== 'production' && warn("Attempting to hydrate existing markup but container is empty. " + "Performing full mount instead."); patch(null, vnode, container); @@ -7047,17 +6672,16 @@ export default function vueFactory(exports) { } }; - var hydrateNode = function hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds) { - var optimized = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + var hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => { var isFragmentStart = isComment(node) && node.data === '['; - var onMismatch = function onMismatch() { - return handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart); - }; + var onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart); - var type = vnode.type, - ref = vnode.ref, - shapeFlag = vnode.shapeFlag; + var { + type, + ref, + shapeFlag + } = vnode; var domType = node.nodeType; vnode.el = node; var nextNode = null; @@ -7195,13 +6819,15 @@ export default function vueFactory(exports) { return nextNode; }; - var hydrateElement = function hydrateElement(el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) { + var hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => { optimized = optimized || !!vnode.dynamicChildren; - var type = vnode.type, - props = vnode.props, - patchFlag = vnode.patchFlag, - shapeFlag = vnode.shapeFlag, - dirs = vnode.dirs; // #4006 for form elements with non-string v-model value bindings + var { + type, + props, + patchFlag, + shapeFlag, + dirs + } = vnode; // #4006 for form elements with non-string v-model value bindings // e.g.