diff --git a/packages/uni-core/src/helpers/index.ts b/packages/uni-core/src/helpers/index.ts index 44af56a36823079db8c8a15866f2c6f5aeb5ac07..31ce17a81faf245d93a9e74b34403e1157076369 100644 --- a/packages/uni-core/src/helpers/index.ts +++ b/packages/uni-core/src/helpers/index.ts @@ -1,4 +1,5 @@ export * from './util' export * from './icon' export * from './getRealRoute' +export * from './updateCssVar' export * from './getWindowOffset' diff --git a/packages/uni-core/src/helpers/updateCssVar.ts b/packages/uni-core/src/helpers/updateCssVar.ts new file mode 100644 index 0000000000000000000000000000000000000000..8c8bb7520f498810d53fbd0ec1cf939a676db3b1 --- /dev/null +++ b/packages/uni-core/src/helpers/updateCssVar.ts @@ -0,0 +1,28 @@ +interface PageCssVars { + '--window-top'?: string + '--window-bottom'?: string + '--window-left'?: string + '--window-right'?: string + '--window-margin'?: string + '--top-window-height'?: string +} +const style = document.documentElement.style + +function updateCssVar(cssVars: Record) { + Object.keys(cssVars).forEach((name) => { + style.setProperty(name, cssVars[name]) + }) +} + +export function updatePageCssVar(cssVars: PageCssVars) { + return updateCssVar(cssVars) +} + +interface AppCssVar { + '--status-bar-height'?: string + '--tab-bar-height'?: string +} + +export function updateAppCssVar(cssVars: AppCssVar) { + return updateCssVar(cssVars) +} diff --git a/packages/uni-core/src/service/plugin/index.ts b/packages/uni-core/src/service/plugin/index.ts index 14d11c1704789c83329e08befc6f7998e7b66464..2df1a57fcfdf1186a9ac52d3e3538c822de3cb83 100644 --- a/packages/uni-core/src/service/plugin/index.ts +++ b/packages/uni-core/src/service/plugin/index.ts @@ -1,69 +1,8 @@ -import { App, ComponentPublicInstance } from 'vue' -import { isString } from '@vue/shared' -import { invokeArrayFns } from '@dcloudio/uni-shared' +import { App } from 'vue' import { initAppConfig } from './appConfig' - +import { initSubscribe } from './subscribe' +export * from './page' export function initService(app: App) { initAppConfig(app._context.config) -} - -export function getCurrentPage() { - const pages = getCurrentPages() - const len = pages.length - if (len) { - return pages[len - 1] - } -} - -export function getCurrentPageMeta() { - const page = getCurrentPage() - if (page) { - return page.$page.meta - } -} - -export function getCurrentPageId() { - const meta = getCurrentPageMeta() - if (meta) { - return meta.id - } - return -1 -} - -export function getCurrentPageVm() { - const page = getCurrentPage() - if (page) { - return (page as any).$vm as ComponentPublicInstance - } -} - -export function invokeHook(name: string, args?: unknown): unknown -export function invokeHook(id: number, name: string, args?: unknown): unknown -export function invokeHook( - vm: ComponentPublicInstance, - name: string, - args?: unknown -): unknown -export function invokeHook( - vm: ComponentPublicInstance | string | number, - name?: string | unknown, - args?: unknown -) { - if (isString(vm)) { - args = name - name = vm - vm = getCurrentPageVm()! - } else if (typeof vm === 'number') { - const page = getCurrentPages().find((page) => page.$page.id === vm) - if (page) { - vm = (page as any).$vm as ComponentPublicInstance - } else { - vm = getCurrentPageVm() as ComponentPublicInstance - } - } - if (!vm) { - return - } - const hooks = vm.$[name as string] - return hooks && invokeArrayFns(hooks, args) + initSubscribe() } diff --git a/packages/uni-core/src/service/plugin/page.ts b/packages/uni-core/src/service/plugin/page.ts new file mode 100644 index 0000000000000000000000000000000000000000..785544d8ec928a9688bfb53c57f9cdedd1a86f77 --- /dev/null +++ b/packages/uni-core/src/service/plugin/page.ts @@ -0,0 +1,64 @@ +import { isString } from '@vue/shared' +import { ComponentPublicInstance } from 'vue' +import { invokeArrayFns } from '@dcloudio/uni-shared' + +export function getCurrentPage() { + const pages = getCurrentPages() + const len = pages.length + if (len) { + return pages[len - 1] + } +} + +export function getCurrentPageMeta() { + const page = getCurrentPage() + if (page) { + return page.$page.meta + } +} + +export function getCurrentPageId() { + const meta = getCurrentPageMeta() + if (meta) { + return meta.id + } + return -1 +} + +export function getCurrentPageVm() { + const page = getCurrentPage() + if (page) { + return (page as any).$vm as ComponentPublicInstance + } +} + +export function invokeHook(name: string, args?: unknown): unknown +export function invokeHook(id: number, name: string, args?: unknown): unknown +export function invokeHook( + vm: ComponentPublicInstance, + name: string, + args?: unknown +): unknown +export function invokeHook( + vm: ComponentPublicInstance | string | number, + name?: string | unknown, + args?: unknown +) { + if (isString(vm)) { + args = name + name = vm + vm = getCurrentPageVm()! + } else if (typeof vm === 'number') { + const page = getCurrentPages().find((page) => page.$page.id === vm) + if (page) { + vm = (page as any).$vm as ComponentPublicInstance + } else { + vm = getCurrentPageVm() as ComponentPublicInstance + } + } + if (!vm) { + return + } + const hooks = vm.$[name as string] + return hooks && invokeArrayFns(hooks, args) +} diff --git a/packages/uni-core/src/service/plugin/subscribe.ts b/packages/uni-core/src/service/plugin/subscribe.ts index 5ce3bb81eb338b09faa4a0a5671f222c510bf4c6..0e3710f1b1fce864390f2b22c9838576eb11dd8e 100644 --- a/packages/uni-core/src/service/plugin/subscribe.ts +++ b/packages/uni-core/src/service/plugin/subscribe.ts @@ -1,4 +1,22 @@ +import { ComponentPublicInstance } from '@vue/runtime-core' +import { getCurrentPage, invokeHook } from './page' + export function initSubscribe() { - UniServiceJSBridge.on('onAppEnterForeground', () => {}) - UniServiceJSBridge.on('onAppEnterBackground', () => {}) + UniServiceJSBridge.on('onAppEnterForeground', () => { + const page = getCurrentPage() + const showOptions = { + path: '', + query: {}, + } + if (page) { + showOptions.path = page.$page.route + showOptions.query = page.$page.options + } + invokeHook(getApp() as ComponentPublicInstance, 'onShow', showOptions) + invokeHook(page as ComponentPublicInstance, 'onShow') + }) + UniServiceJSBridge.on('onAppEnterBackground', () => { + invokeHook(getApp() as ComponentPublicInstance, 'onHide') + invokeHook(getCurrentPage() as ComponentPublicInstance, 'onHide') + }) } diff --git a/packages/uni-h5/dist/uni-h5.esm.js b/packages/uni-h5/dist/uni-h5.esm.js index 708e90bdc3c2e137c93384f9eea1b867b29177aa..98ee542108b60286d6a0f3dcf4e0bb02d16ae1c8 100644 --- a/packages/uni-h5/dist/uni-h5.esm.js +++ b/packages/uni-h5/dist/uni-h5.esm.js @@ -1,7 +1,7 @@ -import {isFunction, extend, isPlainObject, isString, invokeArrayFns as invokeArrayFns$1, hyphenate, isArray, hasOwn as hasOwn$1, isObject as isObject$1, capitalize, toRawType, makeMap as makeMap$1, isPromise} from "@vue/shared"; +import {isFunction, extend, isPlainObject, isString, isArray, hasOwn as hasOwn$1, isObject as isObject$1, capitalize, toRawType, makeMap as makeMap$1, isPromise, invokeArrayFns as invokeArrayFns$1, hyphenate} from "@vue/shared"; import {injectHook, createVNode, inject, provide, reactive, computed, nextTick, getCurrentInstance, onBeforeMount, onMounted, onBeforeActivate, onBeforeDeactivate, openBlock, createBlock, mergeProps, toDisplayString, ref, defineComponent, resolveComponent, toHandlers, renderSlot, watch, onActivated, onBeforeUnmount, withModifiers, withDirectives, vShow, vModelDynamic, createTextVNode, createCommentVNode, Fragment, renderList, vModelText, watchEffect, withCtx, KeepAlive, resolveDynamicComponent} from "vue"; -import {once, passive, normalizeTarget, invokeArrayFns, NAVBAR_HEIGHT, parseQuery, decodedQuery, plusReady, debounce, PRIMARY_COLOR as PRIMARY_COLOR$1, removeLeadingSlash, getLen, updateElementStyle, addFont, scrollTo} from "@dcloudio/uni-shared"; -import {useRoute, createRouter, createWebHistory, createWebHashHistory, isNavigationFailure, RouterView} from "vue-router"; +import {once, passive, normalizeTarget, invokeArrayFns, NAVBAR_HEIGHT, removeLeadingSlash, getLen, parseQuery, decodedQuery, plusReady, debounce, PRIMARY_COLOR as PRIMARY_COLOR$1, updateElementStyle, addFont, scrollTo} from "@dcloudio/uni-shared"; +import {useRoute, createRouter, createWebHistory, createWebHashHistory, useRouter, isNavigationFailure, RouterView} from "vue-router"; function applyOptions(options, instance2, publicThis) { Object.keys(options).forEach((name) => { if (name.indexOf("on") === 0) { @@ -443,10 +443,10 @@ function init() { }); return; } - function setStyle(el, style) { + function setStyle(el, style2) { var elStyle = el.style; - Object.keys(style).forEach(function(key) { - var val = style[key]; + Object.keys(style2).forEach(function(key) { + var val = style2[key]; elStyle[key] = val; }); } @@ -555,13 +555,13 @@ var changeAttrs = []; function attrChange(attr2) { if (!changeAttrs.length) { setTimeout(function() { - var style = {}; + var style2 = {}; changeAttrs.forEach(function(attr3) { - style[attr3] = elementComputedStyle[attr3]; + style2[attr3] = elementComputedStyle[attr3]; }); changeAttrs.length = 0; callbacks$1.forEach(function(callback) { - callback(style); + callback(style2); }); }, 0); } @@ -606,11 +606,11 @@ var safeAreaInsets = { }; var out = safeAreaInsets; function getWindowOffset() { - const style = document.documentElement.style; - const top = parseInt(style.getPropertyValue("--window-top")); - const bottom = parseInt(style.getPropertyValue("--window-bottom")); - const left = parseInt(style.getPropertyValue("--window-left")); - const right = parseInt(style.getPropertyValue("--window-right")); + const style2 = document.documentElement.style; + const top = parseInt(style2.getPropertyValue("--window-top")); + const bottom = parseInt(style2.getPropertyValue("--window-bottom")); + const left = parseInt(style2.getPropertyValue("--window-left")); + const right = parseInt(style2.getPropertyValue("--window-right")); return { top: top ? top + out.top : 0, bottom: bottom ? bottom + out.bottom : 0, @@ -765,15 +765,15 @@ class ComponentDescriptor { } return descriptors; } - setStyle(style) { - if (!this.$el || !style) { + setStyle(style2) { + if (!this.$el || !style2) { return this; } - if (typeof style === "string") { - style = parseStyleText(style); + if (typeof style2 === "string") { + style2 = parseStyleText(style2); } - if (isPlainObject(style)) { - this.$el.__wxsStyle = style; + if (isPlainObject(style2)) { + this.$el.__wxsStyle = style2; this.$vm.$forceUpdate(); } return this; @@ -920,9 +920,6 @@ function initAppConfig(appConfig) { extend(globalProperties, wxInstance); } } -function initService(app) { - initAppConfig(app._context.config); -} function getCurrentPage() { const pages = getCurrentPages(); const len = pages.length; @@ -968,6 +965,29 @@ function invokeHook(vm, name, args) { const hooks = vm.$[name]; return hooks && invokeArrayFns(hooks, args); } +function initSubscribe() { + UniServiceJSBridge.on("onAppEnterForeground", () => { + const page = getCurrentPage(); + const showOptions = { + path: "", + query: {} + }; + if (page) { + showOptions.path = page.$page.route; + showOptions.query = page.$page.options; + } + invokeHook(getApp(), "onShow", showOptions); + invokeHook(page, "onShow"); + }); + UniServiceJSBridge.on("onAppEnterBackground", () => { + invokeHook(getApp(), "onHide"); + invokeHook(getCurrentPage(), "onHide"); + }); +} +function initService(app) { + initAppConfig(app._context.config); + initSubscribe(); +} function PolySymbol(name) { return Symbol(process.env.NODE_ENV !== "production" ? "[uni-app]: " + name : name); } @@ -1033,6 +1053,15 @@ function getRealRoute(fromRoute, toRoute) { fromRouteArray.splice(fromRouteArray.length - i2 - 1, i2 + 1); return "/" + fromRouteArray.concat(toRouteArray).join("/"); } +const style = document.documentElement.style; +function updateCssVar$1(cssVars) { + Object.keys(cssVars).forEach((name) => { + style.setProperty(name, cssVars[name]); + }); +} +function updatePageCssVar(cssVars) { + return updateCssVar$1(cssVars); +} function errorHandler(err, instance2, info) { if (!instance2) { throw err; @@ -1122,29 +1151,29 @@ function normalizePageMeta(pageMeta) { } const sheetsMap = new Map(); function updateStyle(id2, content) { - let style = sheetsMap.get(id2); - if (style && !(style instanceof HTMLStyleElement)) { + let style2 = sheetsMap.get(id2); + if (style2 && !(style2 instanceof HTMLStyleElement)) { removeStyle(id2); - style = void 0; + style2 = void 0; } - if (!style) { - style = document.createElement("style"); - style.setAttribute("type", "text/css"); - style.innerHTML = content; - document.head.appendChild(style); + if (!style2) { + style2 = document.createElement("style"); + style2.setAttribute("type", "text/css"); + style2.innerHTML = content; + document.head.appendChild(style2); } else { - style.innerHTML = content; + style2.innerHTML = content; } - sheetsMap.set(id2, style); + sheetsMap.set(id2, style2); } function removeStyle(id2) { - let style = sheetsMap.get(id2); - if (style) { - if (style instanceof CSSStyleSheet) { - document.adoptedStyleSheets.indexOf(style); - document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== style); + let style2 = sheetsMap.get(id2); + if (style2) { + if (style2 instanceof CSSStyleSheet) { + document.adoptedStyleSheets.indexOf(style2); + document.adoptedStyleSheets = document.adoptedStyleSheets.filter((s) => s !== style2); } else { - document.head.removeChild(style); + document.head.removeChild(style2); } sheetsMap.delete(id2); } @@ -1342,4461 +1371,4522 @@ function initApp(vm) { appVm.$vm = vm; appVm.globalData = appVm.$options.globalData || {}; } -function usePageRoute() { - if (__UNI_FEATURE_PAGES__) { - return useRoute(); +let tabBar; +function useTabBar() { + if (!tabBar) { + tabBar = __uniConfig.tabBar && reactive(__uniConfig.tabBar); } - const url = location.href; - const searchPos = url.indexOf("?"); - const hashPos = url.indexOf("#", searchPos > -1 ? searchPos : 0); - let query = {}; - if (searchPos > -1) { - query = parseQuery(url.slice(searchPos + 1, hashPos > -1 ? hashPos : url.length)); + return tabBar; +} +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var lookup = /* @__PURE__ */ function() { + const lookup2 = new Uint8Array(256); + for (var i2 = 0; i2 < chars.length; i2++) { + lookup2[chars.charCodeAt(i2)] = i2; } - return { - meta: __uniRoutes[0].meta, - query - }; + return lookup2; +}(); +function encode$1(arraybuffer) { + var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = ""; + for (i2 = 0; i2 < len; i2 += 3) { + base64 += chars[bytes[i2] >> 2]; + base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4]; + base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6]; + base64 += chars[bytes[i2 + 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 wrapperComponentSetup(comp, {init: init2, setup, after}) { - const oldSetup = comp.setup; - comp.setup = (props2, ctx) => { - const instance2 = getCurrentInstance(); - init2(instance2.proxy); - const query = setup(instance2); - if (oldSetup) { - return oldSetup(query, ctx); +function decode(base64) { + var bufferLength = base64.length * 0.75, len = base64.length, i2, p2 = 0, encoded1, encoded2, encoded3, encoded4; + if (base64[base64.length - 1] === "=") { + bufferLength--; + if (base64[base64.length - 2] === "=") { + bufferLength--; } - }; - after && after(comp); + } + var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); + for (i2 = 0; i2 < len; i2 += 4) { + encoded1 = lookup[base64.charCodeAt(i2)]; + encoded2 = lookup[base64.charCodeAt(i2 + 1)]; + encoded3 = lookup[base64.charCodeAt(i2 + 2)]; + encoded4 = lookup[base64.charCodeAt(i2 + 3)]; + bytes[p2++] = encoded1 << 2 | encoded2 >> 4; + bytes[p2++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p2++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + return arraybuffer; } -function setupComponent(comp, options) { - if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) { - wrapperComponentSetup(comp.default, options); - } else { - wrapperComponentSetup(comp, options); +const CHOOSE_SIZE_TYPES = ["original", "compressed"]; +const CHOOSE_SOURCE_TYPES = ["album", "camera"]; +const HTTP_METHODS = [ + "GET", + "OPTIONS", + "HEAD", + "POST", + "PUT", + "DELETE", + "TRACE", + "CONNECT" +]; +function elemInArray(str, arr) { + if (!str || arr.indexOf(str) === -1) { + return arr[0]; } - return comp; + return str; } -function setupPage(comp) { - return setupComponent(comp, { - init: initPage, - setup(instance2) { - instance2.root = instance2; - const route = usePageRoute(); - if (route.meta.isTabBar) { - instance2.__isActive = true; - } - onBeforeMount(() => { - const {onLoad, onShow} = instance2; - onLoad && invokeArrayFns$1(onLoad, decodedQuery(route.query)); - instance2.__isVisible = true; - onShow && invokeArrayFns$1(onShow); - }); - onMounted(() => { - const {onReady} = instance2; - onReady && invokeArrayFns$1(onReady); - }); - onBeforeActivate(() => { - if (!instance2.__isVisible) { - instance2.__isVisible = true; - const {onShow} = instance2; - onShow && invokeArrayFns$1(onShow); - } - }); - onBeforeDeactivate(() => { - if (instance2.__isVisible && !instance2.__isUnload) { - instance2.__isVisible = false; - const {onHide} = instance2; - onHide && invokeArrayFns$1(onHide); - } - }); - return route.query; - } - }); +function elemsInArray(strArr, optionalVal) { + if (!isArray(strArr) || strArr.length === 0 || strArr.find((val) => optionalVal.indexOf(val) === -1)) { + return optionalVal; + } + return strArr; } -function setupApp(comp) { - return setupComponent(comp, { - init: initApp, - setup(instance2) { - const route = usePageRoute(); - onBeforeMount(() => { - const {onLaunch, onShow} = instance2; - onLaunch && invokeArrayFns$1(onLaunch, { - path: route.meta.route, - query: decodedQuery(route.query), - scene: 1001 - }); - onShow && invokeArrayFns$1(onShow); - }); - onMounted(() => { - document.addEventListener("visibilitychange", function() { - if (document.visibilityState === "visible") { - UniServiceJSBridge.emit("onAppEnterForeground"); - } else { - UniServiceJSBridge.emit("onAppEnterBackground"); - } - }); - }); - return route.query; - }, - after(comp2) { - comp2.mpType = "app"; - comp2.render = () => (openBlock(), createBlock(LayoutComponent)); +function validateProtocolFail(name, msg) { + console.warn(`${name}: ${msg}`); +} +function validateProtocol(name, data, protocol) { + for (const key in protocol) { + const errMsg = validateProp(key, data[key], protocol[key], !hasOwn$1(data, key)); + if (isString(errMsg)) { + validateProtocolFail(name, errMsg); } - }); + } } -function broadcast(componentName, eventName, ...params) { - const children = this.$children; - const len = children.length; +function validateProtocols(name, args, protocol) { + if (!protocol) { + return; + } + if (!isArray(protocol)) { + return validateProtocol(name, args[0] || Object.create(null), protocol); + } + const len = protocol.length; + const argsLen = args.length; for (let i2 = 0; i2 < len; i2++) { - const child = children[i2]; - const name = child.$options.name && child.$options.name.substr(4); - if (~componentName.indexOf(name)) { - child.$emit.apply(child, [eventName].concat(params)); - return false; - } else { - if (broadcast.apply(child, [componentName, eventName].concat([params])) === false) { - return false; - } + const opts = protocol[i2]; + const data = Object.create(null); + if (argsLen > i2) { + data[opts.name] = args[i2]; } + validateProtocol(name, data, {[opts.name]: opts}); } } -var emitter = { - methods: { - $dispatch(componentName, eventName, ...params) { - console.log("$dispatch", componentName, eventName, params); - }, - $broadcast(componentName, eventName, ...params) { - if (typeof componentName === "string") { - componentName = [componentName]; - } - broadcast.apply(this, [componentName, eventName].concat(params)); +function validateProp(name, value, prop, isAbsent) { + if (!isPlainObject(prop)) { + prop = {type: prop}; + } + const {type, required, validator} = prop; + if (required && isAbsent) { + return 'Missing required args: "' + name + '"'; + } + if (value == null && !required) { + return; + } + if (type != null) { + let isValid = false; + const types = isArray(type) ? type : [type]; + const expectedTypes = []; + for (let i2 = 0; i2 < types.length && !isValid; i2++) { + const {valid, expectedType} = assertType(value, types[i2]); + expectedTypes.push(expectedType || ""); + isValid = valid; + } + if (!isValid) { + return getInvalidTypeMessage(name, value, expectedTypes); } } -}; -var listeners = { - props: { - id: { - type: String, - default: "" + if (validator) { + return validator(value); + } +} +const isSimpleType = /* @__PURE__ */ makeMap$1("String,Number,Boolean,Function,Symbol"); +function assertType(value, type) { + let valid; + const expectedType = getType(type); + if (isSimpleType(expectedType)) { + const t2 = typeof value; + valid = t2 === expectedType.toLowerCase(); + if (!valid && t2 === "object") { + valid = value instanceof type; } - }, - created() { - this._addListeners(this.id); - this.$watch("id", (newId, oldId) => { - this._removeListeners(oldId, true); - this._addListeners(newId, true); - }); - }, - beforeDestroy() { - this._removeListeners(this.id); - }, - methods: { - _addListeners(id2, watch2) { - if (watch2 && !id2) { - return; - } - const {listeners: listeners2} = this.$options; - if (!isPlainObject(listeners2)) { - return; - } - Object.keys(listeners2).forEach((name) => { - if (watch2) { - if (name.indexOf("@") !== 0 && name.indexOf("uni-") !== 0) { - UniViewJSBridge.on(`uni-${name}-${this.$page.id}-${id2}`, this[listeners2[name]]); - } - } else { - if (name.indexOf("@") === 0) { - this.$on(`uni-${name.substr(1)}`, this[listeners2[name]]); - } else if (name.indexOf("uni-") === 0) { - UniViewJSBridge.on(name, this[listeners2[name]]); - } else if (id2) { - UniViewJSBridge.on(`uni-${name}-${this.$page.id}-${id2}`, this[listeners2[name]]); - } - } - }); - }, - _removeListeners(id2, watch2) { - if (watch2 && !id2) { - return; - } - const {listeners: listeners2} = this.$options; - if (!isPlainObject(listeners2)) { - return; - } - Object.keys(listeners2).forEach((name) => { - if (watch2) { - if (name.indexOf("@") !== 0 && name.indexOf("uni-") !== 0) { - UniViewJSBridge.off(`uni-${name}-${this.$page.id}-${id2}`, this[listeners2[name]]); - } - } else { - if (name.indexOf("@") === 0) { - this.$off(`uni-${name.substr(1)}`, this[listeners2[name]]); - } else if (name.indexOf("uni-") === 0) { - UniViewJSBridge.off(name, this[listeners2[name]]); - } else if (id2) { - UniViewJSBridge.off(`uni-${name}-${this.$page.id}-${id2}`, this[listeners2[name]]); - } - } - }); + } else if (expectedType === "Object") { + valid = isObject$1(value); + } else if (expectedType === "Array") { + valid = isArray(value); + } else { + { + valid = value instanceof type; } } -}; -var hover = { - data() { - return { - hovering: false - }; - }, - props: { - hoverClass: { - type: String, - default: "none" - }, - hoverStopPropagation: { - type: Boolean, - default: false - }, - hoverStartTime: { - type: [Number, String], - default: 50 - }, - hoverStayTime: { - type: [Number, String], - default: 400 + return { + valid, + expectedType + }; +} +function getInvalidTypeMessage(name, value, expectedTypes) { + let message = `Invalid args: type check failed for args "${name}". Expected ${expectedTypes.map(capitalize).join(", ")}`; + const expectedType = expectedTypes[0]; + const receivedType = toRawType(value); + const expectedValue = styleValue(value, expectedType); + const receivedValue = styleValue(value, receivedType); + if (expectedTypes.length === 1 && isExplicable(expectedType) && !isBoolean(expectedType, receivedType)) { + message += ` with value ${expectedValue}`; + } + message += `, got ${receivedType} `; + if (isExplicable(receivedType)) { + message += `with value ${receivedValue}.`; + } + return message; +} +function getType(ctor) { + const match = ctor && ctor.toString().match(/^\s*function (\w+)/); + return match ? match[1] : ""; +} +function styleValue(value, type) { + if (type === "String") { + return `"${value}"`; + } else if (type === "Number") { + return `${Number(value)}`; + } else { + return `${value}`; + } +} +function isExplicable(type) { + const explicitTypes = ["string", "number", "boolean"]; + return explicitTypes.some((elem) => type.toLowerCase() === elem); +} +function isBoolean(...args) { + return args.some((elem) => elem.toLowerCase() === "boolean"); +} +function tryCatch(fn) { + return function() { + try { + return fn.apply(fn, arguments); + } catch (e2) { + console.error(e2); } - }, - methods: { - _hoverTouchStart(evt) { - if (evt._hoverPropagationStopped) { - return; - } - if (!this.hoverClass || this.hoverClass === "none" || this.disabled) { - return; - } - if (evt.touches.length > 1) { - return; - } - if (this.hoverStopPropagation) { - evt._hoverPropagationStopped = true; - } - this._hoverTouch = true; - this._hoverStartTimer = setTimeout(() => { - this.hovering = true; - if (!this._hoverTouch) { - this._hoverReset(); - } - }, this.hoverStartTime); - }, - _hoverTouchEnd(evt) { - this._hoverTouch = false; - if (this.hovering) { - this._hoverReset(); + }; +} +let invokeCallbackId = 1; +const invokeCallbacks = {}; +function addInvokeCallback(id2, name, callback, keepAlive = false) { + invokeCallbacks[id2] = { + name, + keepAlive, + callback + }; + return id2; +} +function invokeCallback(id2, res, extras) { + if (typeof id2 === "number") { + const opts = invokeCallbacks[id2]; + if (opts) { + if (!opts.keepAlive) { + delete invokeCallbacks[id2]; } - }, - _hoverReset() { - requestAnimationFrame(() => { - clearTimeout(this._hoverStayTimer); - this._hoverStayTimer = setTimeout(() => { - this.hovering = false; - }, this.hoverStayTime); - }); - }, - _hoverTouchCancel(evt) { - this._hoverTouch = false; - this.hovering = false; - clearTimeout(this._hoverStartTimer); + return opts.callback(res, extras); } } -}; -var subscriber = { - mounted() { - this._toggleListeners("subscribe", this.id); - this.$watch("id", (newId, oldId) => { - this._toggleListeners("unsubscribe", oldId, true); - this._toggleListeners("subscribe", newId, true); - }); - }, - beforeDestroy() { - this._toggleListeners("unsubscribe", this.id); - if (this._contextId) { - this._toggleListeners("unsubscribe", this._contextId); + return res; +} +function findInvokeCallbackByName(name) { + for (const key in invokeCallbacks) { + if (invokeCallbacks[key].name === name) { + return true; } - }, - methods: { - _toggleListeners(type, id2, watch2) { - if (watch2 && !id2) { - return; - } - if (!isFunction(this._handleSubscribe)) { - return; - } - UniViewJSBridge[type](this.$page.id + "-" + this.$options.name.replace(/VUni([A-Z])/, "$1").toLowerCase() + "-" + id2, this._handleSubscribe); - }, - _getContextInfo() { - const id2 = `context-${this._uid}`; - if (!this._contextId) { - this._toggleListeners("subscribe", id2); - this._contextId = id2; - } - return { - name: this.$options.name.replace(/VUni([A-Z])/, "$1").toLowerCase(), - id: id2, - page: this.$page.id - }; + } + return false; +} +function removeKeepAliveApiCallback(name, callback) { + for (const key in invokeCallbacks) { + const item = invokeCallbacks[key]; + if (item.callback === callback && item.name === name) { + delete invokeCallbacks[key]; } } -}; -function hideKeyboard$1() { - document.activeElement.blur(); } -function iosHideKeyboard() { +function offKeepAliveApiCallback(name) { + UniServiceJSBridge.off("api." + name); } -var keyboard = { - name: "Keyboard", - props: { - cursorSpacing: { - type: [Number, String], - default: 0 - }, - showConfirmBar: { - type: [Boolean, String], - default: "auto" - }, - adjustPosition: { - type: Boolean, - default: true - } - }, - watch: { - focus(val) { - if (val && false) { - this.showSoftKeybord(); +function onKeepAliveApiCallback(name) { + UniServiceJSBridge.on("api." + name, (res) => { + for (const key in invokeCallbacks) { + const opts = invokeCallbacks[key]; + if (opts.name === name) { + opts.callback(res); } } - }, - mounted() { - if (this.autoFocus || this.focus) { - this.showSoftKeybord(); + }); +} +function createKeepAliveApiCallback(name, callback) { + return addInvokeCallback(invokeCallbackId++, name, callback, true); +} +const API_SUCCESS = "success"; +const API_FAIL = "fail"; +const API_COMPLETE = "complete"; +function getApiCallbacks(args) { + const apiCallbacks = {}; + for (const name in args) { + const fn = args[name]; + if (isFunction(fn)) { + apiCallbacks[name] = tryCatch(fn); + delete args[name]; } - }, - beforeDestroy() { - this.onKeyboardHide(); - }, - methods: { - initKeyboard(el) { - el.addEventListener("focus", () => { - this.hideKeyboardTemp = function() { - hideKeyboard$1(); - }; - UniViewJSBridge.subscribe("hideKeyboard", this.hideKeyboardTemp); - document.addEventListener("click", iosHideKeyboard, false); - }); - el.addEventListener("blur", this.onKeyboardHide.bind(this)); - }, - showSoftKeybord() { - plusReady(() => { - plus.key.showSoftKeybord(); - }); - }, - setSoftinputTemporary() { - plusReady(() => { - const currentWebview = plus.webview.currentWebview(); - const style = currentWebview.getStyle() || {}; - const rect = this.$el.getBoundingClientRect(); - currentWebview.setSoftinputTemporary && currentWebview.setSoftinputTemporary({ - mode: style.softinputMode === "adjustResize" ? "adjustResize" : this.adjustPosition ? "adjustPan" : "nothing", - position: { - top: rect.top, - height: rect.height + (Number(this.cursorSpacing) || 0) - } - }); - }); - }, - setSoftinputNavBar() { - if (this.showConfirmBar === "auto") { - delete this.__softinputNavBar; - return; - } - plusReady(() => { - const currentWebview = plus.webview.currentWebview(); - const {softinputNavBar} = currentWebview.getStyle() || {}; - const showConfirmBar = softinputNavBar !== "none"; - if (showConfirmBar !== this.showConfirmBar) { - this.__softinputNavBar = softinputNavBar || "auto"; - currentWebview.setStyle({ - softinputNavBar: this.showConfirmBar ? "auto" : "none" - }); - } else { - delete this.__softinputNavBar; - } - }); - }, - resetSoftinputNavBar() { - const softinputNavBar = this.__softinputNavBar; - if (softinputNavBar) { - plusReady(() => { - const currentWebview = plus.webview.currentWebview(); - currentWebview.setStyle({ - softinputNavBar - }); - }); - } - }, - onKeyboardHide() { - UniViewJSBridge.unsubscribe("hideKeyboard", this.hideKeyboardTemp); - document.removeEventListener("click", iosHideKeyboard, false); - if (String(navigator.vendor).indexOf("Apple") === 0) { - document.documentElement.scrollTo(document.documentElement.scrollLeft, document.documentElement.scrollTop); - } + } + return apiCallbacks; +} +function normalizeErrMsg(errMsg, name) { + if (!errMsg || errMsg.indexOf(":fail") === -1) { + return name + ":ok"; + } + return name + errMsg.substring(errMsg.indexOf(":fail")); +} +function createAsyncApiCallback(name, args = {}, {beforeAll, beforeSuccess} = {}) { + if (!isPlainObject(args)) { + args = {}; + } + const {success, fail, complete} = getApiCallbacks(args); + const hasSuccess = isFunction(success); + const hasFail = isFunction(fail); + const hasComplete = isFunction(complete); + const callbackId = invokeCallbackId++; + addInvokeCallback(callbackId, name, (res) => { + res = res || {}; + res.errMsg = normalizeErrMsg(res.errMsg, name); + isFunction(beforeAll) && beforeAll(res); + if (res.errMsg === name + ":ok") { + isFunction(beforeSuccess) && beforeSuccess(res); + hasSuccess && success(res); + } else { + hasFail && fail(res); } + hasComplete && complete(res); + }); + return callbackId; +} +const callbacks = [API_SUCCESS, API_FAIL, API_COMPLETE]; +function hasCallback(args) { + if (isPlainObject(args) && callbacks.find((cb) => isFunction(args[cb]))) { + return true; } -}; -function throttle(fn, wait) { - let last = 0; - let timeout; - const newFn = function(...arg) { - const now = Date.now(); - clearTimeout(timeout); - const waitCallback = () => { - last = now; - fn.apply(this, arg); - }; - if (now - last < wait) { - timeout = setTimeout(waitCallback, wait - (now - last)); - return; + return false; +} +function handlePromise(promise) { + if (__UNI_FEATURE_PROMISE__) { + return promise.then((data) => { + return [null, data]; + }).catch((err) => [err]); + } + return promise; +} +function promisify(fn) { + return (args = {}) => { + if (hasCallback(args)) { + return fn(args); } - waitCallback(); - }; - newFn.cancel = function() { - clearTimeout(timeout); + return handlePromise(new Promise((resolve, reject) => { + fn(Object.assign(args, {success: resolve, fail: reject})); + })); }; - return newFn; } -var baseInput = { - name: "BaseInput", - mixins: [emitter, keyboard], - model: { - prop: "value", - event: "update:value" - }, - props: { - value: { - type: [String, Number], - default: "" +function formatApiArgs(args, options) { + const params = args[0]; + if (!options || !isPlainObject(options.formatArgs) && isPlainObject(params)) { + return; + } + const formatArgs = options.formatArgs; + const keys = Object.keys(formatArgs); + for (let i2 = 0; i2 < keys.length; i2++) { + const name = keys[i2]; + const formatterOrDefaultValue = formatArgs[name]; + if (isFunction(formatterOrDefaultValue)) { + const errMsg = formatterOrDefaultValue(args[0][name], params); + if (isString(errMsg)) { + return errMsg; + } + } else { + if (!hasOwn$1(params, name)) { + params[name] = formatterOrDefaultValue; + } } - }, - data() { - return { - valueSync: this._getValueString(this.value) - }; - }, - created() { - const valueChange = this.__valueChange = debounce((val) => { - this.valueSync = this._getValueString(val); - }, 100); - this.$watch("value", valueChange); - this.__triggerInput = throttle(($event, detail) => { - this.$emit("update:value", detail.value); - this.$trigger("input", $event, detail); - }, 100); - this.$triggerInput = ($event, detail) => { - this.__valueChange.cancel(); - this.__triggerInput($event, detail); - }; - }, - beforeDestroy() { - this.__valueChange.cancel(); - this.__triggerInput.cancel(); - }, - methods: { - _getValueString(value) { - return value === null ? "" : String(value); + } +} +function invokeSuccess(id2, name, res) { + return invokeCallback(id2, extend(res || {}, {errMsg: name + ":ok"})); +} +function invokeFail(id2, name, err) { + return invokeCallback(id2, {errMsg: name + ":fail" + (err ? " " + err : "")}); +} +function beforeInvokeApi(name, args, protocol, options) { + if (process.env.NODE_ENV !== "production") { + validateProtocols(name, args, protocol); + } + if (options && options.beforeInvoke) { + const errMsg2 = options.beforeInvoke(args); + if (isString(errMsg2)) { + return errMsg2; } } -}; -const _sfc_main$k = { - name: "Audio", - mixins: [subscriber], - props: { - id: { - type: String, - default: "" - }, - src: { - type: String, - default: "" - }, - loop: { - type: [Boolean, String], - default: false - }, - controls: { - type: [Boolean, String], - default: false - }, - poster: { - type: String, - default: "" - }, - name: { - type: String, - default: "" - }, - author: { - type: String, - default: "" - } - }, - data() { - return { - playing: false, - currentTime: this.getTime(0) - }; - }, - watch: { - src(val) { - if (this.$refs.audio) { - this.$refs.audio.src = this.$getRealPath(val); - } - } - }, - mounted() { - const audio = this.$refs.audio; - audio.addEventListener("error", ($event) => { - this.playing = false; - this.$trigger("error", $event, {}); - }); - audio.addEventListener("play", ($event) => { - this.playing = true; - this.$trigger("play", $event, {}); - }); - audio.addEventListener("pause", ($event) => { - this.playing = false; - this.$trigger("pause", $event, {}); - }); - audio.addEventListener("ended", ($event) => { - this.playing = false; - this.$trigger("ended", $event, {}); - }); - audio.addEventListener("timeupdate", ($event) => { - var currentTime = audio.currentTime; - this.currentTime = this.getTime(currentTime); - var duration = audio.duration; - this.$trigger("timeupdate", $event, { - currentTime, - duration - }); - }); - audio.src = this.$getRealPath(this.src); - }, - methods: { - _handleSubscribe({ - type, - data = {} - }) { - var audio = this.$refs.audio; - switch (type) { - case "setSrc": - audio.src = this.$getRealPath(data.src); - this.$emit("update:src", data.src); - break; - case "play": - audio.play(); - break; - case "pause": - audio.pause(); - break; - case "seek": - audio.currentTime = data.position; - break; - } - }, - trigger() { - if (this.playing) { - this.$refs.audio.pause(); - } else { - this.$refs.audio.play(); - } - }, - getTime(time) { - var h = Math.floor(time / 3600); - var m = Math.floor(time % 3600 / 60); - var s = Math.floor(time % 3600 % 60); - h = (h < 10 ? "0" : "") + h; - m = (m < 10 ? "0" : "") + m; - s = (s < 10 ? "0" : "") + s; - var str = m + ":" + s; - if (h !== "00") { - str = h + ":" + str; - } - return str; - } + const errMsg = formatApiArgs(args, options); + if (errMsg) { + return errMsg; } -}; -const _hoisted_1$c = {class: "uni-audio-default"}; -const _hoisted_2$7 = {class: "uni-audio-right"}; -const _hoisted_3$3 = {class: "uni-audio-time"}; -const _hoisted_4$3 = {class: "uni-audio-info"}; -const _hoisted_5$2 = {class: "uni-audio-name"}; -const _hoisted_6$2 = {class: "uni-audio-author"}; -function _sfc_render$k(_ctx, _cache, $props, $setup, $data, $options) { - return openBlock(), createBlock("uni-audio", mergeProps({ - id: $props.id, - controls: !!$props.controls - }, _ctx.$attrs), [ - createVNode("audio", { - ref: "audio", - loop: $props.loop, - style: {display: "none"} - }, null, 8, ["loop"]), - createVNode("div", _hoisted_1$c, [ - createVNode("div", { - style: "background-image: url(" + _ctx.$getRealPath($props.poster) + ");", - class: "uni-audio-left" - }, [ - createVNode("div", { - class: [{play: !$data.playing, pause: $data.playing}, "uni-audio-button"], - onClick: _cache[1] || (_cache[1] = (...args) => $options.trigger && $options.trigger(...args)) - }, null, 2) - ], 4), - createVNode("div", _hoisted_2$7, [ - createVNode("div", _hoisted_3$3, toDisplayString($data.currentTime), 1), - createVNode("div", _hoisted_4$3, [ - createVNode("div", _hoisted_5$2, toDisplayString($props.name), 1), - createVNode("div", _hoisted_6$2, toDisplayString($props.author), 1) - ]) - ]) - ]) - ], 16, ["id", "controls"]); } -_sfc_main$k.render = _sfc_render$k; -const hoverProps = { - hoverClass: { - type: String, - default: "none" - }, - hoverStopPropagation: { - type: Boolean, - default: false - }, - hoverStartTime: { - type: [Number, String], - default: 50 - }, - hoverStayTime: { - type: [Number, String], - default: 400 - } -}; -function useHover(props2) { - const hovering = ref(false); - let hoverTouch = false; - let hoverStartTimer; - let hoverStayTimer; - function hoverReset() { - requestAnimationFrame(() => { - clearTimeout(hoverStayTimer); - hoverStayTimer = setTimeout(() => { - hovering.value = false; - }, parseInt(props2.hoverStayTime)); - }); +function checkCallback(callback) { + if (!isFunction(callback)) { + throw new Error('Invalid args: type check failed for args "callback". Expected Function'); } - function onTouchstartPassive(evt) { - if (evt._hoverPropagationStopped) { - return; - } - if (!props2.hoverClass || props2.hoverClass === "none" || props2.disabled) { - return; - } - if (evt.touches.length > 1) { - return; +} +function wrapperOnApi(name, fn, options) { + return (callback) => { + checkCallback(callback); + const errMsg = beforeInvokeApi(name, [callback], void 0, options); + if (errMsg) { + throw new Error(errMsg); } - if (props2.hoverStopPropagation) { - evt._hoverPropagationStopped = true; + const isFirstInvokeOnApi = !findInvokeCallbackByName(name); + createKeepAliveApiCallback(name, callback); + if (isFirstInvokeOnApi) { + onKeepAliveApiCallback(name); + fn(); } - hoverTouch = true; - hoverStartTimer = setTimeout(() => { - hovering.value = true; - if (!hoverTouch) { - hoverReset(); - } - }, parseInt(props2.hoverStartTime)); - } - function onTouchend() { - hoverTouch = false; - if (hovering.value) { - hoverReset(); + }; +} +function wrapperOffApi(name, fn, options) { + return (callback) => { + checkCallback(callback); + const errMsg = beforeInvokeApi(name, [callback], void 0, options); + if (errMsg) { + throw new Error(errMsg); } - } - function onTouchcancel() { - hoverTouch = false; - hovering.value = false; - clearTimeout(hoverStartTimer); - } - return { - hovering, - binding: { - onTouchstartPassive, - onTouchend, - onTouchcancel + name = name.replace("off", "on"); + removeKeepAliveApiCallback(name, callback); + const hasInvokeOnApi = findInvokeCallbackByName(name); + if (!hasInvokeOnApi) { + offKeepAliveApiCallback(name); + fn(); } }; } -function useBooleanAttr(props2, keys) { - if (isString(keys)) { - keys = [keys]; - } - return keys.reduce((res, key) => { - if (props2[key]) { - res[key] = true; - } - return res; - }, Object.create(null)); +function wrapperTaskApi(name, fn, protocol, options) { + return (args) => { + const id2 = createAsyncApiCallback(name, args, options); + const errMsg = beforeInvokeApi(name, [args], protocol, options); + if (errMsg) { + return invokeFail(id2, name, errMsg); + } + return fn(args, { + resolve: (res) => invokeSuccess(id2, name, res), + reject: (err) => invokeFail(id2, name, err) + }); + }; } -const uniFormKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniForm" : "uf"); -var index$7 = /* @__PURE__ */ defineComponent({ - name: "Form", - setup(_props, { - slots, - emit - }) { - provideForm(emit); - return () => createVNode("uni-form", null, [createVNode("span", null, [slots.default && slots.default()])]); - } -}); -function provideForm(emit) { - const fields = []; - provide(uniFormKey, { - addField(field) { - fields.push(field); - }, - removeField(field) { - fields.splice(fields.indexOf(field), 1); - }, - submit() { - emit("submit", { - detail: { - value: fields.reduce((res, field) => { - const [name, value] = field.submit(); - name && (res[name] = value); - return res; - }, Object.create(null)) - } - }); - }, - reset() { - fields.forEach((field) => field.reset()); - emit("reset"); +function wrapperSyncApi(name, fn, protocol, options) { + return (...args) => { + const errMsg = beforeInvokeApi(name, args, protocol, options); + if (errMsg) { + throw new Error(errMsg); } - }); - return fields; + return fn.apply(null, args); + }; } -var index$6 = /* @__PURE__ */ defineComponent({ - name: "Button", - props: { - id: { - type: String, - default: "" - }, - hoverClass: { - type: String, - default: "button-hover" - }, - hoverStartTime: { - type: [Number, String], - default: 20 - }, - hoverStayTime: { - type: [Number, String], - default: 70 - }, - hoverStopPropagation: { - type: Boolean, - default: false - }, - disabled: { - type: [Boolean, String], - default: false - }, - formType: { - type: String, - default: "" - }, - openType: { - type: String, - default: "" +function wrapperAsyncApi(name, fn, protocol, options) { + return wrapperTaskApi(name, fn, protocol, options); +} +function defineOnApi(name, fn, options) { + return wrapperOnApi(name, fn, options); +} +function defineOffApi(name, fn, options) { + return wrapperOffApi(name, fn, options); +} +function defineTaskApi(name, fn, protocol, options) { + return promisify(wrapperTaskApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options)); +} +function defineSyncApi(name, fn, protocol, options) { + return wrapperSyncApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options); +} +function defineAsyncApi(name, fn, protocol, options) { + return promisify(wrapperAsyncApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options)); +} +const API_BASE64_TO_ARRAY_BUFFER = "base64ToArrayBuffer"; +const Base64ToArrayBufferProtocol = [ + { + name: "base64", + type: String, + required: true + } +]; +const API_ARRAY_BUFFER_TO_BASE64 = "arrayBufferToBase64"; +const ArrayBufferToBase64Protocol = [ + { + name: "arrayBuffer", + type: [ArrayBuffer, Uint8Array], + required: true + } +]; +const base64ToArrayBuffer = defineSyncApi(API_BASE64_TO_ARRAY_BUFFER, (base64) => { + return decode(base64); +}, Base64ToArrayBufferProtocol); +const arrayBufferToBase64 = defineSyncApi(API_ARRAY_BUFFER_TO_BASE64, (arrayBuffer) => { + return encode$1(arrayBuffer); +}, ArrayBufferToBase64Protocol); +function findElem(vm) { + return vm.$el; +} +const SCHEME_RE = /^([a-z-]+:)?\/\//i; +const DATA_RE = /^data:.*,.*/; +function addBase(filePath) { + const base = __uniConfig.router.base; + if (!base) { + return filePath; + } + if (base !== "/") { + if (("/" + filePath).indexOf(base) === 0) { + return "/" + filePath; } - }, - setup(props2, { - slots - }) { - const uniForm = inject(uniFormKey, false); - const { - hovering, - binding - } = useHover(props2); - useI18n(); - function onClick() { - if (props2.disabled) { - return; - } - const formType = props2.formType; - if (formType) { - if (!uniForm) { - return; - } - if (formType === "submit") { - uniForm.submit(); - } else if (formType === "reset") { - uniForm.reset(); - } - return; - } + } + return base + filePath; +} +function getRealPath(filePath) { + if (__uniConfig.router.base === "./") { + filePath = filePath.replace(/^\.\/static\//, "/static/"); + } + if (filePath.indexOf("/") === 0) { + if (filePath.indexOf("//") === 0) { + filePath = "https:" + filePath; + } else { + return addBase(filePath.substr(1)); } - return () => { - const hoverClass = props2.hoverClass; - const booleanAttrs = useBooleanAttr(props2, "disabled"); - if (hoverClass && hoverClass !== "none") { - return createVNode("uni-button", mergeProps({ - onClick, - class: hovering.value ? hoverClass : "" - }, binding, booleanAttrs), [slots.default && slots.default()], 16, ["onClick"]); - } - return createVNode("uni-button", mergeProps({ - onClick - }, booleanAttrs), [slots.default && slots.default()], 16, ["onClick"]); - }; } -}); -const pixelRatio = /* @__PURE__ */ function() { - const canvas = document.createElement("canvas"); - canvas.height = canvas.width = 0; - const context = canvas.getContext("2d"); - const backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; - return (window.devicePixelRatio || 1) / backingStore; -}(); -function wrapper(canvas) { - canvas.width = canvas.offsetWidth * pixelRatio; - canvas.height = canvas.offsetHeight * pixelRatio; - canvas.getContext("2d").__hidpi__ = true; + if (SCHEME_RE.test(filePath) || DATA_RE.test(filePath) || filePath.indexOf("blob:") === 0) { + return filePath; + } + const pages = getCurrentPages(); + if (pages.length) { + return addBase(getRealRoute(pages[pages.length - 1].$page.route, filePath).substr(1)); + } + return filePath; } -function resolveColor(color) { - color = color.slice(0); - color[3] = color[3] / 255; - return "rgba(" + color.join(",") + ")"; +const ua = navigator.userAgent; +const isAndroid = /* @__PURE__ */ /android/i.test(ua); +const isIOS$1 = /* @__PURE__ */ /iphone|ipad|ipod/i.test(ua); +const isWindows = /* @__PURE__ */ ua.match(/Windows NT ([\d|\d.\d]*)/i); +const isMac = /* @__PURE__ */ /Macintosh|Mac/i.test(ua); +const isLinux = /* @__PURE__ */ /Linux|X11/i.test(ua); +const isIPadOS = isMac && navigator.maxTouchPoints > 0; +function getScreenFix() { + return /^Apple/.test(navigator.vendor) && typeof window.orientation === "number"; } -function processTouches(target, touches) { - return [].map.call(touches, (touch) => { - var boundingClientRect = target.getBoundingClientRect(); - return { - identifier: touch.identifier, - x: touch.clientX - boundingClientRect.left, - y: touch.clientY - boundingClientRect.top - }; - }); +function isLandscape(screenFix) { + return screenFix && Math.abs(window.orientation) === 90; } -var tempCanvas; -function getTempCanvas(width = 0, height = 0) { - if (!tempCanvas) { - tempCanvas = document.createElement("canvas"); - } - tempCanvas.width = width; - tempCanvas.height = height; - return tempCanvas; +function getScreenWidth(screenFix, landscape) { + return screenFix ? Math[landscape ? "max" : "min"](screen.width, screen.height) : screen.width; } -const _sfc_main$j = { - name: "Canvas", - mixins: [subscriber], - props: { - canvasId: { - type: String, - default: "" - }, - disableScroll: { - type: [Boolean, String], - default: false - } - }, - data() { - return { - actionsWaiting: false - }; - }, - computed: { - id() { - return this.canvasId; - }, - _listeners() { - var $listeners = Object.assign({}, this.$listeners); - var events = ["touchstart", "touchmove", "touchend"]; - events.forEach((event2) => { - var existing = $listeners[event2]; - var eventHandler = []; - if (existing) { - eventHandler.push(($event) => { - this.$trigger(event2, Object.assign({}, $event, { - touches: processTouches($event.currentTarget, $event.touches), - changedTouches: processTouches($event.currentTarget, $event.changedTouches) - })); - }); - } - if (this.disableScroll && event2 === "touchmove") { - eventHandler.push(this._touchmove); - } - $listeners[event2] = eventHandler; - }); - return $listeners; - } - }, - created() { - this._actionsDefer = []; - this._images = {}; - }, - mounted() { - this._resize({ - width: this.$refs.sensor.$el.offsetWidth, - height: this.$refs.sensor.$el.offsetHeight - }); - }, - beforeDestroy() { - const canvas = this.$refs.canvas; - canvas.height = canvas.width = 0; - }, - methods: { - _handleSubscribe({ - type, - data = {} - }) { - var method = this[type]; - if (type.indexOf("_") !== 0 && typeof method === "function") { - method(data); - } - }, - _resize() { - var canvas = this.$refs.canvas; - if (canvas.width > 0 && canvas.height > 0) { - var context = canvas.getContext("2d"); - var imageData = context.getImageData(0, 0, canvas.width, canvas.height); - wrapper(this.$refs.canvas); - context.putImageData(imageData, 0, 0); - } else { - wrapper(this.$refs.canvas); - } - }, - _touchmove(event2) { - event2.preventDefault(); - }, - actionsChanged({ - actions, - reserve, - callbackId - }) { - var self = this; - if (!actions) { - return; - } - if (this.actionsWaiting) { - this._actionsDefer.push([actions, reserve, callbackId]); - return; - } - var canvas = this.$refs.canvas; - var c2d = canvas.getContext("2d"); - if (!reserve) { - c2d.fillStyle = "#000000"; - c2d.strokeStyle = "#000000"; - c2d.shadowColor = "#000000"; - c2d.shadowBlur = 0; - c2d.shadowOffsetX = 0; - c2d.shadowOffsetY = 0; - c2d.setTransform(1, 0, 0, 1, 0, 0); - c2d.clearRect(0, 0, canvas.width, canvas.height); - } - this.preloadImage(actions); - for (let index2 = 0; index2 < actions.length; index2++) { - const action = actions[index2]; - let method = action.method; - const data = action.data; - if (/^set/.test(method) && method !== "setTransform") { - const method1 = method[3].toLowerCase() + method.slice(4); - let color; - if (method1 === "fillStyle" || method1 === "strokeStyle") { - if (data[0] === "normal") { - color = resolveColor(data[1]); - } else if (data[0] === "linear") { - const LinearGradient = c2d.createLinearGradient(...data[1]); - data[2].forEach(function(data2) { - const offset = data2[0]; - const color2 = resolveColor(data2[1]); - LinearGradient.addColorStop(offset, color2); - }); - color = LinearGradient; - } else if (data[0] === "radial") { - const x = data[1][0]; - const y = data[1][1]; - const r = data[1][2]; - const LinearGradient = c2d.createRadialGradient(x, y, 0, x, y, r); - data[2].forEach(function(data2) { - const offset = data2[0]; - const color2 = resolveColor(data2[1]); - LinearGradient.addColorStop(offset, color2); - }); - color = LinearGradient; - } else if (data[0] === "pattern") { - const loaded = this.checkImageLoaded(data[1], actions.slice(index2 + 1), callbackId, function(image2) { - if (image2) { - c2d[method1] = c2d.createPattern(image2, data[2]); - } - }); - if (!loaded) { - break; - } - continue; - } - c2d[method1] = color; - } else if (method1 === "globalAlpha") { - c2d[method1] = data[0] / 255; - } else if (method1 === "shadow") { - var _ = ["shadowOffsetX", "shadowOffsetY", "shadowBlur", "shadowColor"]; - data.forEach(function(color_, method_) { - c2d[_[method_]] = _[method_] === "shadowColor" ? resolveColor(color_) : color_; - }); - } else { - if (method1 === "fontSize") { - c2d.font = c2d.font.replace(/\d+\.?\d*px/, data[0] + "px"); - } else { - if (method1 === "lineDash") { - c2d.setLineDash(data[0]); - c2d.lineDashOffset = data[1] || 0; - } else { - if (method1 === "textBaseline") { - if (data[0] === "normal") { - data[0] = "alphabetic"; - } - c2d[method1] = data[0]; - } else { - c2d[method1] = data[0]; - } - } - } - } - } else if (method === "fillPath" || method === "strokePath") { - method = method.replace(/Path/, ""); - c2d.beginPath(); - data.forEach(function(data_) { - c2d[data_.method].apply(c2d, data_.data); - }); - c2d[method](); - } else if (method === "fillText") { - c2d.fillText.apply(c2d, data); - } else if (method === "drawImage") { - var A = function() { - var dataArray = [...data]; - var url = dataArray[0]; - var otherData = dataArray.slice(1); - self._images = self._images || {}; - if (!self.checkImageLoaded(url, actions.slice(index2 + 1), callbackId, function(image2) { - if (image2) { - c2d.drawImage.apply(c2d, [image2].concat([...otherData.slice(4, 8)], [...otherData.slice(0, 4)])); - } - })) - return "break"; - }(); - if (A === "break") { - break; - } - } else { - if (method === "clip") { - data.forEach(function(data_) { - c2d[data_.method].apply(c2d, data_.data); - }); - c2d.clip(); - } else { - c2d[method].apply(c2d, data); - } - } - } - if (!this.actionsWaiting && callbackId) { - UniViewJSBridge.publishHandler("onDrawCanvas", { - callbackId, - data: { - errMsg: "drawCanvas:ok" - } - }, this.$page.id); - } - }, - preloadImage: function(actions) { - var self = this; - actions.forEach(function(action) { - var method = action.method; - var data = action.data; - var src = ""; - if (method === "drawImage") { - src = data[0]; - src = self.$getRealPath(src); - data[0] = src; - } else if (method === "setFillStyle" && data[0] === "pattern") { - src = data[1]; - src = self.$getRealPath(src); - data[1] = src; - } - if (src && !self._images[src]) { - loadImage(); - } - function loadImage() { - self._images[src] = new Image(); - self._images[src].onload = function() { - self._images[src].ready = true; - }; - function loadBlob(blob) { - self._images[src].src = (window.URL || window.webkitURL).createObjectURL(blob); - } - function loadFile(path) { - var bitmap = new plus.nativeObj.Bitmap("bitmap" + Date.now()); - bitmap.load(path, function() { - self._images[src].src = bitmap.toBase64Data(); - bitmap.clear(); - }, function() { - bitmap.clear(); - console.error("preloadImage error"); - }); - } - function loadUrl(url) { - function plusDownload() { - plus.downloader.createDownload(url, { - filename: "_doc/uniapp_temp/download/" - }, function(d, status) { - if (status === 200) { - loadFile(d.filename); - } else { - self._images[src].src = src; - } - }).start(); - } - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, true); - xhr.responseType = "blob"; - xhr.onload = function() { - if (this.status === 200) { - loadBlob(this.response); - } - }; - xhr.onerror = window.plus ? plusDownload : function() { - self._images[src].src = src; - }; - xhr.send(); - } - if (window.plus && (!window.webkit || !window.webkit.messageHandlers)) { - self._images[src].src = src; - } else { - if (window.plus && src.indexOf("http://") !== 0 && src.indexOf("https://") !== 0 && !/^data:.*,.*/.test(src)) { - loadFile(src); - } else if (/^data:.*,.*/.test(src)) { - self._images[src].src = src; - } else { - loadUrl(src); - } - } - } - }); - }, - checkImageLoaded: function(src, actions, callbackId, fn) { - var self = this; - var image2 = this._images[src]; - if (image2.ready) { - fn(image2); - return true; - } else { - this._actionsDefer.unshift([actions, true]); - this.actionsWaiting = true; - image2.onload = function() { - image2.ready = true; - fn(image2); - self.actionsWaiting = false; - var actions2 = self._actionsDefer.slice(0); - self._actionsDefer = []; - for (var action = actions2.shift(); action; ) { - self.actionsChanged({ - actions: action[0], - reserve: action[1], - callbackId - }); - action = actions2.shift(); - } - }; - return false; - } - }, - getImageData({ - x = 0, - y = 0, - width, - height, - destWidth, - destHeight, - hidpi = true, - callbackId - }) { - var imgData; - var canvas = this.$refs.canvas; - if (!width) { - width = canvas.offsetWidth - x; - } - if (!height) { - height = canvas.offsetHeight - y; - } - try { - if (!hidpi) { - if (!destWidth && !destHeight) { - destWidth = Math.round(width * pixelRatio); - destHeight = Math.round(height * pixelRatio); - } else if (!destWidth) { - destWidth = Math.round(width / height * destHeight); - } else if (!destHeight) { - destHeight = Math.round(height / width * destWidth); - } - } else { - destWidth = width; - destHeight = height; - } - const newCanvas = getTempCanvas(destWidth, destHeight); - const context = newCanvas.getContext("2d"); - context.__hidpi__ = true; - context.drawImageByCanvas(canvas, x, y, width, height, 0, 0, destWidth, destHeight, false); - imgData = context.getImageData(0, 0, destWidth, destHeight); - newCanvas.height = newCanvas.width = 0; - context.__hidpi__ = false; - } catch (error) { - if (!callbackId) { - return; - } - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: "canvasGetImageData:fail" - } - }, this.$page.id); - return; - } - if (!callbackId) { - return { - data: Array.prototype.slice.call(imgData.data), - width: destWidth, - height: destHeight - }; - } else { - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: "canvasGetImageData:ok", - data: [...imgData.data], - width: destWidth, - height: destHeight - } - }, this.$page.id); - } - }, - putImageData({ - data, - x, - y, - width, - height, - callbackId - }) { - try { - if (!height) { - height = Math.round(data.length / 4 / width); - } - const canvas = getTempCanvas(width, height); - const context = canvas.getContext("2d"); - context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0); - this.$refs.canvas.getContext("2d").drawImage(canvas, x, y, width, height); - canvas.height = canvas.width = 0; - } catch (error) { - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: "canvasPutImageData:fail" - } - }, this.$page.id); - return; - } - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: "canvasPutImageData:ok" - } - }, this.$page.id); - }, - getDataUrl({ - x = 0, - y = 0, - width, - height, - destWidth, - destHeight, - hidpi = true, - fileType, - qualit, - callbackId - }) { - const res = this.getImageData({ - x, - y, - width, - height, - destWidth, - destHeight, - hidpi - }); - if (!res.data || !res.data.length) { - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: "canvasGetDataUrl:fail" - } - }, this.$page.id); - return; - } - let imgData; - try { - imgData = new ImageData(new Uint8ClampedArray(res.data), res.width, res.height); - } catch (error) { - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: "canvasGetDataUrl:fail" - } - }, this.$page.id); - return; - } - destWidth = res.width; - destHeight = res.height; - const canvas = getTempCanvas(destWidth, destHeight); - const c2d = canvas.getContext("2d"); - c2d.putImageData(imgData, 0, 0); - let base64 = canvas.toDataURL("image/png"); - canvas.height = canvas.width = 0; - const img = new Image(); - img.onload = () => { - const canvas2 = getTempCanvas(destWidth, destHeight); - if (fileType === "jpeg" || fileType === "jpg") { - fileType = "jpeg"; - c2d.fillStyle = "#fff"; - c2d.fillRect(0, 0, destWidth, destHeight); - } - c2d.drawImage(img, 0, 0); - base64 = canvas2.toDataURL(`image/${fileType}`, qualit); - canvas2.height = canvas2.width = 0; - UniViewJSBridge.publishHandler("onCanvasMethodCallback", { - callbackId, - data: { - errMsg: "canvasGetDataUrl:ok", - base64 - } - }, this.$page.id); - }; - img.src = base64; - } - } -}; -const _hoisted_1$b = { - ref: "canvas", - width: "300", - height: "150" -}; -const _hoisted_2$6 = {style: {position: "absolute", top: "0", left: "0", width: "100%", height: "100%", overflow: "hidden"}}; -function _sfc_render$j(_ctx, _cache, $props, $setup, $data, $options) { - const _component_v_uni_resize_sensor = resolveComponent("v-uni-resize-sensor"); - return openBlock(), createBlock("uni-canvas", mergeProps({ - "canvas-id": $props.canvasId, - "disable-scroll": $props.disableScroll - }, toHandlers($options._listeners)), [ - createVNode("canvas", _hoisted_1$b, null, 512), - createVNode("div", _hoisted_2$6, [ - renderSlot(_ctx.$slots, "default") - ]), - createVNode(_component_v_uni_resize_sensor, { - ref: "sensor", - onResize: $options._resize - }, null, 8, ["onResize"]) - ], 16, ["canvas-id", "disable-scroll"]); -} -_sfc_main$j.render = _sfc_render$j; -const _sfc_main$i = { - name: "Checkbox", - mixins: [emitter, listeners], - props: { - checked: { - type: [Boolean, String], - default: false - }, - id: { - type: String, - default: "" - }, - disabled: { - type: [Boolean, String], - default: false - }, - color: { - type: String, - default: "#007aff" - }, - value: { - type: String, - default: "" - } - }, - data() { - return { - checkboxChecked: this.checked, - checkboxValue: this.value - }; - }, - watch: { - checked(val) { - this.checkboxChecked = val; - }, - value(val) { - this.checkboxValue = val; - } - }, - listeners: { - "label-click": "_onClick", - "@label-click": "_onClick" - }, - created() { - this.$dispatch("CheckboxGroup", "uni-checkbox-group-update", { - type: "add", - vm: this - }); - this.$dispatch("Form", "uni-form-group-update", { - type: "add", - vm: this - }); - }, - beforeDestroy() { - this.$dispatch("CheckboxGroup", "uni-checkbox-group-update", { - type: "remove", - vm: this - }); - this.$dispatch("Form", "uni-form-group-update", { - type: "remove", - vm: this - }); - }, - methods: { - _onClick($event) { - if (this.disabled) { - return; - } - this.checkboxChecked = !this.checkboxChecked; - this.$dispatch("CheckboxGroup", "uni-checkbox-change", $event); - }, - _resetFormData() { - this.checkboxChecked = false; - } - } -}; -const _hoisted_1$a = {class: "uni-checkbox-wrapper"}; -function _sfc_render$i(_ctx, _cache, $props, $setup, $data, $options) { - return openBlock(), createBlock("uni-checkbox", mergeProps({disabled: $props.disabled}, _ctx.$attrs, { - onClick: _cache[1] || (_cache[1] = (...args) => $options._onClick && $options._onClick(...args)) - }), [ - createVNode("div", _hoisted_1$a, [ - createVNode("div", { - class: [[$data.checkboxChecked ? "uni-checkbox-input-checked" : ""], "uni-checkbox-input"], - style: {color: $props.color} - }, null, 6), - renderSlot(_ctx.$slots, "default") - ]) - ], 16, ["disabled"]); -} -_sfc_main$i.render = _sfc_render$i; -const _sfc_main$h = { - name: "CheckboxGroup", - mixins: [emitter, listeners], - props: { - name: { - type: String, - default: "" - } - }, - data() { - return { - checkboxList: [] - }; - }, - listeners: { - "@checkbox-change": "_changeHandler", - "@checkbox-group-update": "_checkboxGroupUpdateHandler" - }, - created() { - this.$dispatch("Form", "uni-form-group-update", { - type: "add", - vm: this - }); - }, - beforeDestroy() { - this.$dispatch("Form", "uni-form-group-update", { - type: "remove", - vm: this - }); - }, - methods: { - _changeHandler($event) { - const value = []; - this.checkboxList.forEach((vm) => { - if (vm.checkboxChecked) { - value.push(vm.value); - } - }); - this.$trigger("change", $event, { - value - }); - }, - _checkboxGroupUpdateHandler($event) { - if ($event.type === "add") { - this.checkboxList.push($event.vm); - } else { - const index2 = this.checkboxList.indexOf($event.vm); - this.checkboxList.splice(index2, 1); - } - }, - _getFormData() { - const data = {}; - if (this.name !== "") { - const value = []; - this.checkboxList.forEach((vm) => { - if (vm.checkboxChecked) { - value.push(vm.value); - } - }); - data.value = value; - data.key = this.name; - } - return data; - } - } -}; -function _sfc_render$h(_ctx, _cache, $props, $setup, $data, $options) { - return openBlock(), createBlock("uni-checkbox-group", _ctx.$attrs, [ - renderSlot(_ctx.$slots, "default") - ], 16); +function getScreenHeight(screenFix, landscape) { + return screenFix ? Math[landscape ? "min" : "max"](screen.height, screen.width) : screen.height; } -_sfc_main$h.render = _sfc_render$h; -var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/; -var endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/; -var attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; -var empty = /* @__PURE__ */ makeMap("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr"); -var block = /* @__PURE__ */ makeMap("a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video"); -var inline = /* @__PURE__ */ makeMap("abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var"); -var closeSelf = /* @__PURE__ */ makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr"); -var fillAttrs = /* @__PURE__ */ makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected"); -var special = /* @__PURE__ */ makeMap("script,style"); -function HTMLParser(html, handler) { - var index2; - var chars2; - var match; - var stack = []; - var last = html; - stack.last = function() { - return this[this.length - 1]; +function getWindowWidth(screenWidth) { + return Math.min(window.innerWidth, document.documentElement.clientWidth, screenWidth) || screenWidth; +} +function getBaseSystemInfo() { + const screenFix = getScreenFix(); + const windowWidth = getWindowWidth(getScreenWidth(screenFix, isLandscape(screenFix))); + return { + platform: isIOS$1 ? "ios" : "other", + pixelRatio: window.devicePixelRatio, + windowWidth }; - while (html) { - chars2 = true; - if (!stack.last() || !special[stack.last()]) { - if (html.indexOf(""); - if (index2 >= 0) { - if (handler.comment) { - handler.comment(html.substring(4, index2)); - } - html = html.substring(index2 + 3); - chars2 = false; - } - } else if (html.indexOf(" { + if (deviceWidth === 0) { + checkDeviceWidth(); + } + number = Number(number); + if (number === 0) { + return 0; + } + let result = number / BASE_DEVICE_WIDTH * (newDeviceWidth || deviceWidth); + if (result < 0) { + result = -result; + } + result = Math.floor(result + EPS); + if (result === 0) { + if (deviceDPR === 1 || !isIOS) { + result = 1; } else { - html = html.replace(new RegExp("([\\s\\S]*?)]*>"), function(all, text3) { - text3 = text3.replace(/|/g, "$1$2"); - if (handler.chars) { - handler.chars(text3); - } - return ""; - }); - parseEndTag("", stack.last()); + result = 0.5; } - if (html == last) { - throw "Parse Error: " + html; + } + return number < 0 ? -result : result; +}, Upx2pxProtocol); +const globalInterceptors = {}; +const scopedInterceptors = {}; +const API_ADD_INTERCEPTOR = "addInterceptor"; +const API_REMOVE_INTERCEPTOR = "removeInterceptor"; +const AddInterceptorProtocol = [ + { + name: "method", + type: [String, Object], + required: true + } +]; +const RemoveInterceptorProtocol = AddInterceptorProtocol; +function mergeInterceptorHook(interceptors, interceptor) { + Object.keys(interceptor).forEach((hook) => { + if (isFunction(interceptor[hook])) { + interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]); } - last = html; + }); +} +function removeInterceptorHook(interceptors, interceptor) { + if (!interceptors || !interceptor) { + return; } - parseEndTag(); - function parseStartTag(tag, tagName, rest, unary) { - tagName = tagName.toLowerCase(); - if (block[tagName]) { - while (stack.last() && inline[stack.last()]) { - parseEndTag("", stack.last()); - } + Object.keys(interceptor).forEach((hook) => { + if (isFunction(interceptor[hook])) { + removeHook(interceptors[hook], interceptor[hook]); } - if (closeSelf[tagName] && stack.last() == tagName) { - parseEndTag("", tagName); + }); +} +function mergeHook(parentVal, childVal) { + const res = childVal ? parentVal ? parentVal.concat(childVal) : isArray(childVal) ? childVal : [childVal] : parentVal; + return res ? dedupeHooks(res) : res; +} +function dedupeHooks(hooks) { + const res = []; + for (let i2 = 0; i2 < hooks.length; i2++) { + if (res.indexOf(hooks[i2]) === -1) { + res.push(hooks[i2]); } - unary = empty[tagName] || !!unary; - if (!unary) { - stack.push(tagName); + } + return res; +} +function removeHook(hooks, hook) { + if (!hooks) { + return; + } + const index2 = hooks.indexOf(hook); + if (index2 !== -1) { + hooks.splice(index2, 1); + } +} +const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => { + if (typeof method === "string" && isPlainObject(interceptor)) { + mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); + } else if (isPlainObject(method)) { + mergeInterceptorHook(globalInterceptors, method); + } +}, AddInterceptorProtocol); +const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => { + if (typeof method === "string") { + if (isPlainObject(interceptor)) { + removeInterceptorHook(scopedInterceptors[method], interceptor); + } else { + delete scopedInterceptors[method]; } - if (handler.start) { - var attrs2 = []; - rest.replace(attr, function(match2, name) { - var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : ""; - attrs2.push({ - name, - value, - escaped: value.replace(/(^|[^\\])"/g, '$1\\"') - }); - }); - if (handler.start) { - handler.start(tagName, attrs2, unary); - } + } else if (isPlainObject(method)) { + removeInterceptorHook(globalInterceptors, method); + } +}, RemoveInterceptorProtocol); +const promiseInterceptor = { + returnValue(res) { + if (!isPromise(res)) { + return res; } + return res.then((res2) => { + return res2[1]; + }).catch((res2) => { + return res2[0]; + }); + } +}; +const API_CREATE_VIDEO_CONTEXT = "createVideoContext"; +const API_CREATE_INNER_AUDIO_CONTEXT = "createInnerAudioContext"; +const RATES = [0.5, 0.8, 1, 1.25, 1.5, 2]; +class VideoContext { + constructor(id2, vm) { + this.id = id2; + this.vm = vm; + } + play() { + operateVideoPlayer(this.id, this.vm, "play"); + } + pause() { + operateVideoPlayer(this.id, this.vm, "pause"); } - function parseEndTag(tag, tagName) { - if (!tagName) { - var pos = 0; - } else { - for (var pos = stack.length - 1; pos >= 0; pos--) { - if (stack[pos] == tagName) { - break; - } - } - } - if (pos >= 0) { - for (var i2 = stack.length - 1; i2 >= pos; i2--) { - if (handler.end) { - handler.end(stack[i2]); - } - } - stack.length = pos; + stop() { + operateVideoPlayer(this.id, this.vm, "stop"); + } + seek(position) { + operateVideoPlayer(this.id, this.vm, "seek", { + position + }); + } + sendDanmu(args) { + operateVideoPlayer(this.id, this.vm, "sendDanmu", args); + } + playbackRate(rate) { + if (!~RATES.indexOf(rate)) { + rate = 1; } + operateVideoPlayer(this.id, this.vm, "playbackRate", { + rate + }); } -} -function makeMap(str) { - var obj = {}; - var items = str.split(","); - for (var i2 = 0; i2 < items.length; i2++) { - obj[items[i2]] = true; + requestFullScreen(args = {}) { + operateVideoPlayer(this.id, this.vm, "requestFullScreen", args); } - return obj; -} -function divider(Quill) { - const BlockEmbed = Quill.import("blots/block/embed"); - class Divider extends BlockEmbed { + exitFullScreen() { + operateVideoPlayer(this.id, this.vm, "exitFullScreen"); } - Divider.blotName = "divider"; - Divider.tagName = "HR"; - return { - "formats/divider": Divider - }; -} -function ins(Quill) { - const Inline = Quill.import("blots/inline"); - class Ins extends Inline { + showStatusBar() { + operateVideoPlayer(this.id, this.vm, "showStatusBar"); + } + hideStatusBar() { + operateVideoPlayer(this.id, this.vm, "hideStatusBar"); } - Ins.blotName = "ins"; - Ins.tagName = "INS"; - return { - "formats/ins": Ins - }; -} -function align(Quill) { - const {Scope, Attributor} = Quill.import("parchment"); - const config = { - scope: Scope.BLOCK, - whitelist: ["left", "right", "center", "justify"] - }; - const AlignStyle = new Attributor.Style("align", "text-align", config); - return { - "formats/align": AlignStyle - }; } -function direction(Quill) { - const {Scope, Attributor} = Quill.import("parchment"); - const config = { - scope: Scope.BLOCK, - whitelist: ["rtl"] - }; - const DirectionStyle = new Attributor.Style("direction", "direction", config); - return { - "formats/direction": DirectionStyle - }; +const createVideoContext = defineSyncApi(API_CREATE_VIDEO_CONTEXT, (id2, context) => { + if (context) { + return new VideoContext(id2, context); + } + return new VideoContext(id2, getCurrentPageVm()); +}); +const defaultOptions = { + thresholds: [0], + initialRatio: 0, + observeAll: false +}; +const MARGINS = ["top", "right", "bottom", "left"]; +let reqComponentObserverId = 1; +function normalizeRootMargin(margins = {}) { + return MARGINS.map((name) => `${Number(margins[name]) || 0}px`).join(" "); } -function list(Quill) { - const Parchment = Quill.import("parchment"); - const Container = Quill.import("blots/container"); - const ListItem = Quill.import("formats/list/item"); - class List extends Container { - static create(value) { - const tagName = value === "ordered" ? "OL" : "UL"; - const node = super.create(tagName); - if (value === "checked" || value === "unchecked") { - node.setAttribute("data-checked", value === "checked"); - } - return node; - } - static formats(domNode) { - if (domNode.tagName === "OL") - return "ordered"; - if (domNode.tagName === "UL") { - if (domNode.hasAttribute("data-checked")) { - return domNode.getAttribute("data-checked") === "true" ? "checked" : "unchecked"; - } else { - return "bullet"; - } - } - return void 0; - } - constructor(domNode) { - super(domNode); - const listEventHandler = (e2) => { - if (e2.target.parentNode !== domNode) - return; - const format = this.statics.formats(domNode); - const blot = Parchment.find(e2.target); - if (format === "checked") { - blot.format("list", "unchecked"); - } else if (format === "unchecked") { - blot.format("list", "checked"); - } - }; - domNode.addEventListener("click", listEventHandler); +class ServiceIntersectionObserver { + constructor(component, options) { + this._pageId = component.$page && component.$page.id; + this._component = component; + this._options = extend({}, defaultOptions, options); + } + relativeTo(selector, margins) { + this._options.relativeToSelector = selector; + this._options.rootMargin = normalizeRootMargin(margins); + return this; + } + relativeToViewport(margins) { + this._options.relativeToSelector = void 0; + this._options.rootMargin = normalizeRootMargin(margins); + return this; + } + observe(selector, callback) { + if (!isFunction(callback)) { + return; } - format(name, value) { - if (this.children.length > 0) { - this.children.tail.format(name, value); - } + this._options.selector = selector; + this._reqId = reqComponentObserverId++; + addIntersectionObserver({ + reqId: this._reqId, + component: this._component, + options: this._options, + callback + }, this._pageId); + } + disconnect() { + this._reqId && removeIntersectionObserver({reqId: this._reqId, component: this._component}, this._pageId); + } +} +const createIntersectionObserver = defineSyncApi("createIntersectionObserver", (context, options) => { + if (context && !context.$page) { + options = context; + context = null; + } + if (context) { + return new ServiceIntersectionObserver(context, options); + } + return new ServiceIntersectionObserver(getCurrentPageVm(), options); +}); +const createSelectorQuery = () => { +}; +const API_ON_TAB_BAR_MID_BUTTON_TAP = "onTabBarMidButtonTap"; +const onTabBarMidButtonTap = defineOnApi(API_ON_TAB_BAR_MID_BUTTON_TAP, () => { +}); +const API_CAN_I_USE = "canIUse"; +const CanIUseProtocol = [ + { + name: "schema", + type: String, + required: true + } +]; +const API_MAKE_PHONE_CALL = "makePhoneCall"; +const MakePhoneCallProtocol = { + phoneNumber: String +}; +const API_ON_ACCELEROMETER = "onAccelerometer"; +const API_OFF_ACCELEROMETER = "offAccelerometer"; +const API_START_ACCELEROMETER = "startAccelerometer"; +const API_STOP_ACCELEROMETER = "stopAccelerometer"; +const API_ON_COMPASS = "onCompass"; +const API_OFF_COMPASS = "offCompass"; +const API_START_COMPASS = "startCompass"; +const API_STOP_COMPASS = "stopCompass"; +const API_VIBRATE_SHORT = "vibrateShort"; +const API_VIBRATE_LONG = "vibrateLong"; +const API_GET_STORAGE = "getStorage"; +const GetStorageProtocol = { + key: { + type: String, + required: true + } +}; +const API_GET_STORAGE_SYNC = "getStorageSync"; +const GetStorageSyncProtocol = [ + { + name: "key", + type: String, + required: true + } +]; +const API_SET_STORAGE = "setStorage"; +const SetStorageProtocol = { + key: { + type: String, + required: true + }, + data: { + required: true + } +}; +const API_SET_STORAGE_SYNC = "setStorageSync"; +const SetStorageSyncProtocol = [ + { + name: "key", + type: String, + required: true + }, + { + name: "data", + required: true + } +]; +const API_REMOVE_STORAGE = "removeStorage"; +const RemoveStorageProtocol = GetStorageProtocol; +const RemoveStorageSyncProtocol = GetStorageSyncProtocol; +const API_GET_FILE_INFO = "getFileInfo"; +const GetFileInfoOptions = { + formatArgs: { + filePath(filePath, params) { + params.filePath = getRealPath(filePath); } - formats() { - return {[this.statics.blotName]: this.statics.formats(this.domNode)}; + } +}; +const GetFileInfoProtocol = { + filePath: { + type: String, + required: true + } +}; +const API_OPEN_DOCUMENT = "openDocument"; +const OpenDocumentOptions = { + formatArgs: { + filePath(filePath, params) { + params.filePath = getRealPath(filePath); } - insertBefore(blot, ref2) { - if (blot instanceof ListItem) { - super.insertBefore(blot, ref2); + } +}; +const OpenDocumentProtocol = { + filePath: { + type: String, + required: true + }, + fileType: String +}; +const API_HIDE_KEYBOARD = "hideKeyboard"; +const API_GET_LOCATION = "getLocation"; +const coordTypes = ["WGS84", "GCJ02"]; +const GetLocationOptions = { + formatArgs: { + type(value, params) { + value = (value || "").toUpperCase(); + if (coordTypes.indexOf(value) === -1) { + params.type = coordTypes[0]; } else { - const index2 = ref2 == null ? this.length() : ref2.offset(this); - const after = this.split(index2); - after.parent.insertBefore(blot, after); - } - } - optimize(context) { - super.optimize(context); - const next = this.next; - if (next != null && next.prev === this && next.statics.blotName === this.statics.blotName && next.domNode.tagName === this.domNode.tagName && next.domNode.getAttribute("data-checked") === this.domNode.getAttribute("data-checked")) { - next.moveChildren(this); - next.remove(); - } - } - replace(target) { - if (target.statics.blotName !== this.statics.blotName) { - const item = Parchment.create(this.statics.defaultChild); - target.moveChildren(item); - this.appendChild(item); + params.type = value; } - super.replace(target); + }, + altitude(value, params) { + params.altitude = value ? value : false; } } - List.blotName = "list"; - List.scope = Parchment.Scope.BLOCK_BLOT; - List.tagName = ["OL", "UL"]; - List.defaultChild = "list-item"; - List.allowedChildren = [ListItem]; - return { - "formats/list": List - }; -} -function background(Quill) { - const {Scope} = Quill.import("parchment"); - const BackgroundStyle = Quill.import("formats/background"); - const BackgroundColorStyle = new BackgroundStyle.constructor("backgroundColor", "background-color", { - scope: Scope.INLINE - }); - return { - "formats/backgroundColor": BackgroundColorStyle - }; -} -function box(Quill) { - const {Scope, Attributor} = Quill.import("parchment"); - const config = { - scope: Scope.BLOCK - }; - const margin = [ - "margin", - "marginTop", - "marginBottom", - "marginLeft", - "marginRight" - ]; - const padding = [ - "padding", - "paddingTop", - "paddingBottom", - "paddingLeft", - "paddingRight" - ]; - const result = {}; - margin.concat(padding).forEach((name) => { - result[`formats/${name}`] = new Attributor.Style(name, hyphenate(name), config); - }); - return result; -} -function font(Quill) { - const {Scope, Attributor} = Quill.import("parchment"); - const config = { - scope: Scope.INLINE - }; - const font2 = [ - "font", - "fontSize", - "fontStyle", - "fontVariant", - "fontWeight", - "fontFamily" - ]; - const result = {}; - font2.forEach((name) => { - result[`formats/${name}`] = new Attributor.Style(name, hyphenate(name), config); - }); - return result; -} -function text(Quill) { - const {Scope, Attributor} = Quill.import("parchment"); - const text2 = [ - { - name: "lineHeight", - scope: Scope.BLOCK +}; +const GetLocationProtocol = { + type: String, + altitude: Boolean +}; +const API_CHOOSE_IMAGE = "chooseImage"; +const ChooseImageOptions = { + formatArgs: { + count(value, params) { + if (!value || value <= 0) { + params.count = 9; + } }, - { - name: "letterSpacing", - scope: Scope.INLINE + sizeType(sizeType, params) { + params.sizeType = elemsInArray(sizeType, CHOOSE_SIZE_TYPES); }, - { - name: "textDecoration", - scope: Scope.INLINE + sourceType(sourceType, params) { + params.sourceType = elemsInArray(sourceType, CHOOSE_SOURCE_TYPES); }, - { - name: "textIndent", - scope: Scope.BLOCK - } - ]; - const result = {}; - text2.forEach(({name, scope}) => { - result[`formats/${name}`] = new Attributor.Style(name, hyphenate(name), { - scope - }); - }); - return result; -} -function image(Quill) { - const Image2 = Quill.import("formats/image"); - const ATTRIBUTES = [ - "alt", - "height", - "width", - "data-custom", - "class", - "data-local" - ]; - Image2.sanitize = (url) => url; - Image2.formats = function formats(domNode) { - return ATTRIBUTES.reduce(function(formats2, attribute) { - if (domNode.hasAttribute(attribute)) { - formats2[attribute] = domNode.getAttribute(attribute); - } - return formats2; - }, {}); - }; - const format = Image2.prototype.format; - Image2.prototype.format = function(name, value) { - if (ATTRIBUTES.indexOf(name) > -1) { - if (value) { - this.domNode.setAttribute(name, value); - } else { - this.domNode.removeAttribute(name); + extension(extension, params) { + if (extension instanceof Array && extension.length === 0) { + return "param extension should not be empty."; } - } else { - format.call(this, name, value); + if (!extension) + params.extension = [""]; } - }; -} -function register(Quill) { - const formats = { - divider, - ins, - align, - direction, - list, - background, - box, - font, - text, - image - }; - const options = {}; - Object.values(formats).forEach((value) => Object.assign(options, value(Quill))); - Quill.register(options, true); -} -const _sfc_main$g = { - name: "Editor", - mixins: [subscriber, emitter, keyboard], - props: { - id: { - type: String, - default: "" - }, - readOnly: { - type: [Boolean, String], - default: false - }, - placeholder: { - type: String, - default: "" - }, - showImgSize: { - type: [Boolean, String], - default: false - }, - showImgToolbar: { - type: [Boolean, String], - default: false + } +}; +const ChooseImageProtocol = { + count: Number, + sizeType: [Array, String], + sourceType: Array, + extension: Array +}; +const API_CHOOSE_VIDEO = "chooseVideo"; +const ChooseVideoOptions = { + formatArgs: { + sourceType(sourceType, params) { + params.sourceType = elemsInArray(sourceType, CHOOSE_SOURCE_TYPES); }, - showImgResize: { - type: [Boolean, String], - default: false + compressed: true, + maxDuration: 60, + camera: "back", + extension(extension, params) { + if (extension instanceof Array && extension.length === 0) { + return "param extension should not be empty."; + } + if (!extension) + params.extension = [""]; } - }, - data() { - return { - quillReady: false - }; - }, - computed: {}, - watch: { - readOnly(value) { - if (this.quillReady) { - const quill = this.quill; - quill.enable(!value); - if (!value) { - quill.blur(); - } + } +}; +const ChooseVideoProtocol = { + sourceType: Array, + compressed: Boolean, + maxDuration: Number, + camera: String, + extension: Array +}; +const API_CHOOSE_FILE = "chooseFile"; +const CHOOSE_MEDIA_TYPE = [ + "all", + "image", + "video" +]; +const ChooseFileOptions = { + formatArgs: { + count(count, params) { + if (!count || count <= 0) { + params.count = 100; } }, - placeholder(value) { - if (this.quillReady) { - this.quill.root.setAttribute("data-placeholder", value); + sourceType(sourceType, params) { + params.sourceType = elemsInArray(sourceType, CHOOSE_SOURCE_TYPES); + }, + type(type, params) { + params.type = elemInArray(type, CHOOSE_MEDIA_TYPE); + }, + extension(extension, params) { + if (extension instanceof Array && extension.length === 0) { + return "param extension should not be empty."; } + if (!extension) + params.extension = [""]; } - }, - mounted() { - const imageResizeModules = []; - if (this.showImgSize) { - imageResizeModules.push("DisplaySize"); - } - if (this.showImgToolbar) { - imageResizeModules.push("Toolbar"); + } +}; +const ChooseFileProtocol = { + count: Number, + sourceType: Array, + type: String, + extension: Array +}; +const API_GET_IMAGE_INFO = "getImageInfo"; +const GetImageInfoOptions = { + formatArgs: { + src(src, params) { + params.src = getRealPath(src); } - if (this.showImgResize) { - imageResizeModules.push("Resize"); + } +}; +const GetImageInfoProtocol = { + src: { + type: String, + required: true + } +}; +const API_GET_VIDEO_INFO = "getVideoInfo"; +const GetVideoInfoOptions = { + formatArgs: { + src(src, params) { + params.src = getRealPath(src); } - this.loadQuill(() => { - if (imageResizeModules.length) { - this.loadImageResizeModule(() => { - this.initQuill(imageResizeModules); - }); - } else { - this.initQuill(imageResizeModules); - } - }); - }, - methods: { - _handleSubscribe({ - type, - data - }) { - const {options, callbackId} = data; - const quill = this.quill; - const Quill = window.Quill; - let res; - let range; - let errMsg; - if (this.quillReady) { - switch (type) { - case "format": - { - let {name = "", value = false} = options; - range = quill.getSelection(true); - let format = quill.getFormat(range)[name] || false; - if (["bold", "italic", "underline", "strike", "ins"].includes(name)) { - value = !format; - } else if (name === "direction") { - value = value === "rtl" && format ? false : value; - const align2 = quill.getFormat(range).align; - if (value === "rtl" && !align2) { - quill.format("align", "right", Quill.sources.USER); - } else if (!value && align2 === "right") { - quill.format("align", false, Quill.sources.USER); - } - } else if (name === "indent") { - const rtl = quill.getFormat(range).direction === "rtl"; - value = value === "+1"; - if (rtl) { - value = !value; - } - value = value ? "+1" : "-1"; - } else { - if (name === "list") { - value = value === "check" ? "unchecked" : value; - format = format === "checked" ? "unchecked" : format; - } - value = format && format !== (value || false) || !format && value ? value : !format; - } - quill.format(name, value, Quill.sources.USER); - } - break; - case "insertDivider": - range = quill.getSelection(true); - quill.insertText(range.index, "\n", Quill.sources.USER); - quill.insertEmbed(range.index + 1, "divider", true, Quill.sources.USER); - quill.setSelection(range.index + 2, Quill.sources.SILENT); - break; - case "insertImage": - { - range = quill.getSelection(true); - const {src = "", alt = "", width = "", height = "", extClass = "", data: data2 = {}} = options; - const path = this.$getRealPath(src); - quill.insertEmbed(range.index, "image", path, Quill.sources.USER); - const local = /^(file|blob):/.test(path) ? path : false; - quill.formatText(range.index, 1, "data-local", local); - quill.formatText(range.index, 1, "alt", alt); - quill.formatText(range.index, 1, "width", width); - quill.formatText(range.index, 1, "height", height); - quill.formatText(range.index, 1, "class", extClass); - quill.formatText(range.index, 1, "data-custom", Object.keys(data2).map((key) => `${key}=${data2[key]}`).join("&")); - quill.setSelection(range.index + 1, Quill.sources.SILENT); - } - break; - case "insertText": - { - range = quill.getSelection(true); - const {text: text2 = ""} = options; - quill.insertText(range.index, text2, Quill.sources.USER); - quill.setSelection(range.index + text2.length, 0, Quill.sources.SILENT); - } - break; - case "setContents": - { - const {delta, html} = options; - if (typeof delta === "object") { - quill.setContents(delta, Quill.sources.SILENT); - } else if (typeof html === "string") { - quill.setContents(this.html2delta(html), Quill.sources.SILENT); - } else { - errMsg = "contents is missing"; - } - } - break; - case "getContents": - res = this.getContents(); - break; - case "clear": - quill.setContents([]); - break; - case "removeFormat": - { - range = quill.getSelection(true); - const parchment = Quill.import("parchment"); - if (range.length) { - quill.removeFormat(range, Quill.sources.USER); - } else { - Object.keys(quill.getFormat(range)).forEach((key) => { - if (parchment.query(key, parchment.Scope.INLINE)) { - quill.format(key, false); - } - }); - } - } - break; - case "undo": - quill.history.undo(); - break; - case "redo": - quill.history.redo(); - break; - } - this.updateStatus(range); - } else { - errMsg = "not ready"; + } +}; +const GetVideoInfoProtocol = { + src: { + type: String, + required: true + } +}; +const API_REQUEST = "request"; +const dataType = { + JSON: "json" +}; +const RESPONSE_TYPE = ["text", "arraybuffer"]; +const DEFAULT_RESPONSE_TYPE = "text"; +const encode = encodeURIComponent; +function stringifyQuery(url, data) { + let str = url.split("#"); + const hash = str[1] || ""; + str = str[0].split("?"); + let query = str[1] || ""; + url = str[0]; + const search = query.split("&").filter((item) => item); + const params = {}; + search.forEach((item) => { + const part = item.split("="); + params[part[0]] = part[1]; + }); + for (const key in data) { + if (hasOwn$1(data, key)) { + let v2 = data[key]; + if (typeof v2 === "undefined" || v2 === null) { + v2 = ""; + } else if (isPlainObject(v2)) { + v2 = JSON.stringify(v2); } - if (callbackId) { - UniViewJSBridge.publishHandler("onEditorMethodCallback", { - callbackId, - data: Object.assign({}, res, { - errMsg: `${type}:${errMsg ? "fail " + errMsg : "ok"}` - }) - }, this.$page.id); + params[encode(key)] = encode(v2); + } + } + query = Object.keys(params).map((item) => `${item}=${params[item]}`).join("&"); + return url + (query ? "?" + query : "") + (hash ? "#" + hash : ""); +} +const RequestProtocol = { + method: String, + data: [Object, String, Array, ArrayBuffer], + url: { + type: String, + required: true + }, + header: Object, + dataType: String, + responseType: String, + withCredentials: Boolean +}; +const RequestOptions = { + formatArgs: { + method(value, params) { + params.method = elemInArray((value || "").toUpperCase(), HTTP_METHODS); + }, + data(value, params) { + params.data = value || ""; + }, + url(value, params) { + if (params.method === HTTP_METHODS[0] && isPlainObject(params.data) && Object.keys(params.data).length) { + params.url = stringifyQuery(value, params.data); } }, - loadQuill(callback) { - if (typeof window.Quill === "function") { - if (typeof callback === "function") { - callback(); + header(value, params) { + const header = params.header = value || {}; + if (params.method !== HTTP_METHODS[0]) { + if (!Object.keys(header).find((key) => key.toLowerCase() === "content-type")) { + header["Content-Type"] = "application/json"; } - return; } - const script = document.createElement("script"); - script.src = window.plus ? "./__uniappquill.js" : "https://unpkg.com/quill@1.3.7/dist/quill.min.js"; - document.body.appendChild(script); - script.onload = callback; }, - loadImageResizeModule(callback) { - if (typeof window.ImageResize === "function") { - if (typeof callback === "function") { - callback(); - } - return; + dataType(value, params) { + params.dataType = (value || dataType.JSON).toLowerCase(); + }, + responseType(value, params) { + params.responseType = (value || "").toLowerCase(); + if (RESPONSE_TYPE.indexOf(params.responseType) === -1) { + params.responseType = DEFAULT_RESPONSE_TYPE; + } + } + } +}; +const API_DOWNLOAD_FILE = "downloadFile"; +const DownloadFileOptions = { + formatArgs: { + header(value, params) { + params.header = value || {}; + } + } +}; +const DownloadFileProtocol = { + url: { + type: String, + required: true + }, + header: Object, + timeout: Number +}; +const API_UPLOAD_FILE = "uploadFile"; +const UploadFileOptions = { + formatArgs: { + filePath(filePath, params) { + if (filePath) { + params.filePath = getRealPath(filePath); } - const script = document.createElement("script"); - script.src = window.plus ? "./__uniappquillimageresize.js" : "https://unpkg.com/quill-image-resize-mp@3.0.1/image-resize.min.js"; - document.body.appendChild(script); - script.onload = callback; }, - initQuill(imageResizeModules) { - const Quill = window.Quill; - register(Quill); - const options = { - toolbar: false, - readOnly: this.readOnly, - placeholder: this.placeholder, - modules: {} - }; - if (imageResizeModules.length) { - Quill.register("modules/ImageResize", window.ImageResize.default); - options.modules.ImageResize = { - modules: imageResizeModules - }; + header(value, params) { + params.header = value || {}; + }, + formData(value, params) { + params.formData = value || {}; + } + } +}; +const UploadFileProtocol = { + url: { + type: String, + required: true + }, + files: Array, + filePath: String, + name: String, + header: Object, + formData: Object, + timeout: Number +}; +const API_CONNECT_SOCKET = "connectSocket"; +const ConnectSocketOptions = { + formatArgs: { + header(value, params) { + params.header = value || {}; + }, + method(value, params) { + params.method = elemInArray((value || "").toUpperCase(), HTTP_METHODS); + }, + protocols(protocols, params) { + if (typeof protocols === "string") { + params.protocols = [protocols]; } - const quill = this.quill = new Quill(this.$el, options); - const $el = quill.root; - const events = ["focus", "blur", "input"]; - events.forEach((name) => { - $el.addEventListener(name, ($event) => { - if (name === "input") { - $event.stopPropagation(); - } else { - this.$trigger(name, $event, this.getContents()); - } - }); - }); - quill.on(Quill.events.TEXT_CHANGE, () => { - this.$trigger("input", {}, this.getContents()); - }); - quill.on(Quill.events.SELECTION_CHANGE, this.updateStatus.bind(this)); - quill.on(Quill.events.SCROLL_OPTIMIZE, () => { - const range = quill.selection.getRange()[0]; - this.updateStatus(range); - }); - quill.clipboard.addMatcher(Node.ELEMENT_NODE, (node, delta) => { - if (this.skipMatcher) { - return delta; + } + } +}; +const ConnectSocketProtocol = { + url: { + type: String, + required: true + }, + header: { + type: Object + }, + method: String, + protocols: [Array, String] +}; +const API_SEND_SOCKET_MESSAGE = "sendSocketMessage"; +const SendSocketMessageProtocol = { + data: [String, ArrayBuffer] +}; +const API_CLOSE_SOCKET = "closeSocket"; +const CloseSocketProtocol = { + code: Number, + reason: String +}; +function encodeQueryString(url) { + if (typeof url !== "string") { + return url; + } + const index2 = url.indexOf("?"); + if (index2 === -1) { + return url; + } + const query = url.substr(index2 + 1).trim().replace(/^(\?|#|&)/, ""); + if (!query) { + return url; + } + url = url.substr(0, index2); + const params = []; + query.split("&").forEach((param) => { + const parts = param.replace(/\+/g, " ").split("="); + const key = parts.shift(); + const val = parts.length > 0 ? parts.join("=") : ""; + params.push(key + "=" + encodeURIComponent(val)); + }); + return params.length ? url + "?" + params.join("&") : url; +} +const ANIMATION_IN = [ + "slide-in-right", + "slide-in-left", + "slide-in-top", + "slide-in-bottom", + "fade-in", + "zoom-out", + "zoom-fade-out", + "pop-in", + "none" +]; +const ANIMATION_OUT = [ + "slide-out-right", + "slide-out-left", + "slide-out-top", + "slide-out-bottom", + "fade-out", + "zoom-in", + "zoom-fade-in", + "pop-out", + "none" +]; +const BaseRouteProtocol = { + url: { + type: String, + required: true + } +}; +const API_NAVIGATE_TO = "navigateTo"; +const API_REDIRECT_TO = "redirectTo"; +const API_RE_LAUNCH = "reLaunch"; +const API_SWITCH_TAB = "switchTab"; +const API_NAVIGATE_BACK = "navigateBack"; +const API_PRELOAD_PAGE = "preloadPage"; +const API_UN_PRELOAD_PAGE = "unPreloadPage"; +const NavigateToProtocol = /* @__PURE__ */ extend({}, BaseRouteProtocol, createAnimationProtocol(ANIMATION_IN)); +const NavigateBackProtocol = /* @__PURE__ */ extend({ + delta: { + type: Number + } +}, createAnimationProtocol(ANIMATION_OUT)); +const RedirectToProtocol = BaseRouteProtocol; +const ReLaunchProtocol = BaseRouteProtocol; +const SwitchTabProtocol = BaseRouteProtocol; +const NavigateToOptions = /* @__PURE__ */ createRouteOptions(API_NAVIGATE_TO); +const RedirectToOptions = /* @__PURE__ */ createRouteOptions(API_REDIRECT_TO); +const ReLaunchOptions = /* @__PURE__ */ createRouteOptions(API_RE_LAUNCH); +const SwitchTabOptions = /* @__PURE__ */ createRouteOptions(API_SWITCH_TAB); +const NavigateBackOptions = { + formatArgs: { + delta(value, params) { + value = parseInt(value + "") || 1; + params.delta = Math.min(getCurrentPages().length - 1, value); + } + } +}; +function createAnimationProtocol(animationTypes) { + return { + animationType: { + type: String, + validator(type) { + if (type && animationTypes.indexOf(type) === -1) { + return "`" + type + "` is not supported for `animationType` (supported values are: `" + animationTypes.join("`|`") + "`)"; } - delta.ops = delta.ops.filter(({insert}) => typeof insert === "string").map(({insert}) => ({insert})); - return delta; - }); - this.initKeyboard($el); - this.quillReady = true; - this.$trigger("ready", event, {}); + } }, - getContents() { - const quill = this.quill; - const html = quill.root.innerHTML; - const text2 = quill.getText(); - const delta = quill.getContents(); - return { - html, - text: text2, - delta - }; + animationDuration: { + type: Number + } + }; +} +let navigatorLock; +function beforeRoute() { + navigatorLock = ""; +} +function createRouteOptions(type) { + return { + formatArgs: { + url: createNormalizeUrl(type) }, - html2delta(html) { - const tags = ["span", "strong", "b", "ins", "em", "i", "u", "a", "del", "s", "sub", "sup", "img", "div", "p", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "ol", "ul", "li", "br"]; - let content = ""; - let disable; - HTMLParser(html, { - start: function(tag, attrs2, unary) { - if (!tags.includes(tag)) { - disable = !unary; - return; - } - disable = false; - const arrts = attrs2.map(({name, value}) => `${name}="${value}"`).join(" "); - const start = `<${tag} ${arrts} ${unary ? "/" : ""}>`; - content += start; - }, - end: function(tag) { - if (!disable) { - content += ``; - } - }, - chars: function(text2) { - if (!disable) { - content += text2; - } + beforeAll: beforeRoute + }; +} +function createNormalizeUrl(type) { + return function normalizeUrl(url, params) { + if (!url) { + return `Missing required args: "url"`; + } + url = getRealRoute(url); + const pagePath = url.split("?")[0]; + const routeOptions = __uniRoutes.find(({path, alias}) => path === pagePath || alias === pagePath); + if (!routeOptions) { + return "page `" + url + "` is not found"; + } + if (type === API_NAVIGATE_TO || type === API_REDIRECT_TO) { + if (routeOptions.meta.isTabBar) { + return `can not ${type} a tabbar page`; + } + } else if (type === API_SWITCH_TAB) { + if (!routeOptions.meta.isTabBar) { + return "can not switch to no-tabBar page"; + } + } + if ((type === API_SWITCH_TAB || type === API_PRELOAD_PAGE) && routeOptions.meta.isTabBar && params.openType !== "appLaunch") { + url = pagePath; + } + if (routeOptions.meta.isEntry) { + url = url.replace(routeOptions.alias, "/"); + } + params.url = encodeQueryString(url); + if (type === API_UN_PRELOAD_PAGE) { + return; + } else if (type === API_PRELOAD_PAGE) { + if (routeOptions.meta.isTabBar) { + const pages = getCurrentPages(true); + const tabBarPagePath = routeOptions.path.substr(1); + if (pages.find((page) => page.route === tabBarPagePath)) { + return "tabBar page `" + tabBarPagePath + "` already exists"; } - }); - this.skipMatcher = true; - const delta = this.quill.clipboard.convert(content); - this.skipMatcher = false; - return delta; - }, - updateStatus(range) { - const status = range ? this.quill.getFormat(range) : {}; - const keys = Object.keys(status); - if (keys.length !== Object.keys(this.__status || {}).length || keys.find((key) => status[key] !== this.__status[key])) { - this.__status = status; - this.$trigger("statuschange", {}, status); } + return; } - } -}; -function _sfc_render$g(_ctx, _cache, $props, $setup, $data, $options) { - return openBlock(), createBlock("uni-editor", mergeProps({ - id: $props.id, - class: "ql-container" - }, _ctx.$attrs), null, 16, ["id"]); + if (navigatorLock === url && params.openType !== "appLaunch") { + return `${navigatorLock} locked`; + } + if (__uniConfig.ready) { + navigatorLock = url; + } + }; } -_sfc_main$g.render = _sfc_render$g; -const INFO_COLOR = "#10aeff"; -const WARN_COLOR = "#f76260"; -const GREY_COLOR = "#b2b2b2"; -const CANCEL_COLOR = "#f43530"; -const ICONS = { - success: { - d: ICON_PATH_SUCCESS, - c: PRIMARY_COLOR$1 - }, - success_no_circle: { - d: ICON_PATH_SUCCESS_NO_CIRCLE, - c: PRIMARY_COLOR$1 - }, - info: { - d: ICON_PATH_INFO, - c: INFO_COLOR - }, - warn: { - d: ICON_PATH_WARN, - c: WARN_COLOR +const API_LOAD_FONT_FACE = "loadFontFace"; +const LoadFontFaceProtocol = { + family: { + type: String, + required: true }, - waiting: { - d: ICON_PATH_WAITING, - c: INFO_COLOR + source: { + type: String, + required: true }, - cancel: { - d: ICON_PATH_CANCEL, - c: CANCEL_COLOR + desc: Object +}; +const API_PAGE_SCROLL_TO = "pageScrollTo"; +const PageScrollToProtocol = { + scrollTop: Number, + selector: String, + duration: Number +}; +const DEFAULT_DURATION = 300; +const PageScrollToOptions = { + formatArgs: { + duration(value, params) { + params.duration = Math.max(0, parseInt(value + "") || DEFAULT_DURATION); + } + } +}; +const FRONT_COLORS = ["#ffffff", "#000000"]; +const API_SET_NAVIGATION_BAR_COLOR = "setNavigationBarColor"; +const SetNavigationBarColorOptions = { + formatArgs: { + animation(animation, params) { + if (!animation) { + animation = {duration: 0, timingFunc: "linear"}; + } + params.animation = { + duration: animation.duration || 0, + timingFunc: animation.timingFunc || "linear" + }; + } + } +}; +const SetNavigationBarColorProtocol = { + frontColor: { + type: String, + required: true, + validator(frontColor) { + if (FRONT_COLORS.indexOf(frontColor) === -1) { + return `invalid frontColor "${frontColor}"`; + } + } }, - download: { - d: ICON_PATH_DOWNLOAD, - c: PRIMARY_COLOR$1 + backgroundColor: { + type: String, + required: true }, - search: { - d: ICON_PATH_SEARCH, - c: GREY_COLOR + animation: Object +}; +const API_SET_NAVIGATION_BAR_TITLE = "setNavigationBarTitle"; +const SetNavigationBarTitleProtocol = { + title: { + type: String, + required: true + } +}; +const API_SHOW_NAVIGATION_BAR_LOADING = "showNavigationBarLoading"; +const API_HIDE_NAVIGATION_BAR_LOADING = "hideNavigationBarLoading"; +const PRIMARY_COLOR = "#007aff"; +const API_SHOW_MODAL = "showModal"; +const ShowModalProtocol = { + title: String, + content: String, + showCancel: Boolean, + cancelText: String, + cancelColor: String, + confirmText: String, + confirmColor: String +}; +const ShowModalOptions = { + beforeInvoke() { + initI18nShowModalMsgsOnce(); }, - clear: { - d: ICON_PATH_CLEAR, - c: GREY_COLOR + 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 } }; -var index$5 = /* @__PURE__ */ defineComponent({ - name: "Icon", - props: { - type: { - type: String, - required: true, - default: "" +const API_SHOW_TOAST = "showToast"; +const ShowToastProtocol = { + title: String, + icon: String, + image: String, + duration: Number, + mask: Boolean +}; +const ShowToastOptions = { + formatArgs: { + title: "", + icon(value, params) { + if (["success", "loading", "none"].indexOf(value) === -1) { + params.icon = "success"; + } }, - size: { - type: [String, Number], - default: 23 + image(value, params) { + if (value) { + params.image = getRealPath(value); + } }, - color: { - type: String, - default: "" - } - }, - setup(props2) { - const path = computed(() => ICONS[props2.type]); - return () => createVNode("uni-icon", null, [path.value.d && createSvgIconVNode(path.value.d, props2.color || path.value.c, rpx2px(props2.size))]); + duration: 1500, + mask: false } -}); -function findElem(vm) { - return vm.$el; -} -const SCHEME_RE = /^([a-z-]+:)?\/\//i; -const DATA_RE = /^data:.*,.*/; -function addBase(filePath) { - const base = __uniConfig.router.base; - if (!base) { - return filePath; +}; +const API_SHOW_LOADING = "showLoading"; +const ShowLoadingProtocol = { + title: String, + mask: Boolean +}; +const ShowLoadingOptions = { + formatArgs: { + title: "", + mask: false } - if (base !== "/") { - if (("/" + filePath).indexOf(base) === 0) { - return "/" + filePath; - } +}; +const API_SHOW_ACTION_SHEET = "showActionSheet"; +const ShowActionSheetProtocol = { + itemList: { + type: Array, + required: true + }, + itemColor: String +}; +const ShowActionSheetOptions = { + formatArgs: { + itemColor: "#000" } - return base + filePath; -} -function getRealPath(filePath) { - if (__uniConfig.router.base === "./") { - filePath = filePath.replace(/^\.\/static\//, "/static/"); +}; +const API_HIDE_TOAST = "hideToast"; +const API_HIDE_LOADING = "hideLoading"; +const API_START_PULL_DOWN_REFRESH = "startPullDownRefresh"; +const API_STOP_PULL_DOWN_REFRESH = "stopPullDownRefresh"; +const IndexProtocol = { + index: { + type: Number, + required: true } - if (filePath.indexOf("/") === 0) { - if (filePath.indexOf("//") === 0) { - filePath = "https:" + filePath; - } else { - return addBase(filePath.substr(1)); +}; +const IndexOptions = { + beforeInvoke() { + const pageMeta = getCurrentPageMeta(); + if (pageMeta && !pageMeta.isTabBar) { + return "not TabBar page"; + } + }, + formatArgs: { + index(value) { + if (!__uniConfig.tabBar.list[value]) { + return "tabbar item not found"; + } } } - if (SCHEME_RE.test(filePath) || DATA_RE.test(filePath) || filePath.indexOf("blob:") === 0) { - return filePath; - } - const pages = getCurrentPages(); - if (pages.length) { - return addBase(getRealRoute(pages[pages.length - 1].$page.route, filePath).substr(1)); - } - return filePath; -} -const ua = navigator.userAgent; -const isAndroid = /* @__PURE__ */ /android/i.test(ua); -const isIOS$1 = /* @__PURE__ */ /iphone|ipad|ipod/i.test(ua); -const isWindows = /* @__PURE__ */ ua.match(/Windows NT ([\d|\d.\d]*)/i); -const isMac = /* @__PURE__ */ /Macintosh|Mac/i.test(ua); -const isLinux = /* @__PURE__ */ /Linux|X11/i.test(ua); -const isIPadOS = isMac && navigator.maxTouchPoints > 0; -function getScreenFix() { - return /^Apple/.test(navigator.vendor) && typeof window.orientation === "number"; -} -function isLandscape(screenFix) { - return screenFix && Math.abs(window.orientation) === 90; -} -function getScreenWidth(screenFix, landscape) { - return screenFix ? Math[landscape ? "max" : "min"](screen.width, screen.height) : screen.width; -} -function getScreenHeight(screenFix, landscape) { - return screenFix ? Math[landscape ? "min" : "max"](screen.height, screen.width) : screen.height; -} -function getWindowWidth(screenWidth) { - return Math.min(window.innerWidth, document.documentElement.clientWidth, screenWidth) || screenWidth; -} -function getBaseSystemInfo() { - const screenFix = getScreenFix(); - const windowWidth = getWindowWidth(getScreenWidth(screenFix, isLandscape(screenFix))); - return { - platform: isIOS$1 ? "ios" : "other", - pixelRatio: window.devicePixelRatio, - windowWidth - }; -} -function operateVideoPlayer(videoId, vm, type, data) { - const pageId = vm.$root.$page.id; - UniServiceJSBridge.publishHandler("video." + videoId, { - videoId, - type, - data - }, pageId); -} -var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -var lookup = /* @__PURE__ */ function() { - const lookup2 = new Uint8Array(256); - for (var i2 = 0; i2 < chars.length; i2++) { - lookup2[chars.charCodeAt(i2)] = i2; +}; +const API_SET_TAB_BAR_ITEM = "setTabBarItem"; +const SetTabBarItemProtocol = /* @__PURE__ */ extend({ + text: String, + iconPath: String, + selectedIconPath: String, + pagePath: String +}, IndexProtocol); +const SetTabBarItemOptions = { + beforeInvoke: IndexOptions.beforeInvoke, + formatArgs: /* @__PURE__ */ extend({ + pagePath(value, params) { + if (value) { + params.pagePath = removeLeadingSlash(value); + } + } + }, IndexOptions.formatArgs) +}; +const API_SET_TAB_BAR_STYLE = "setTabBarStyle"; +const SetTabBarStyleProtocol = { + color: String, + selectedColor: String, + backgroundColor: String, + backgroundImage: String, + backgroundRepeat: String, + borderStyle: String +}; +const GRADIENT_RE = /^(linear|radial)-gradient\(.+?\);?$/; +const SetTabBarStyleOptions = { + beforeInvoke: IndexOptions.beforeInvoke, + formatArgs: { + backgroundImage(value, params) { + if (value && !GRADIENT_RE.test(value)) { + params.backgroundImage = getRealPath(value); + } + }, + borderStyle(value, params) { + if (value) { + params.borderStyle = value === "white" ? "white" : "black"; + } + } } - return lookup2; -}(); -function encode$1(arraybuffer) { - var bytes = new Uint8Array(arraybuffer), i2, len = bytes.length, base64 = ""; - for (i2 = 0; i2 < len; i2 += 3) { - base64 += chars[bytes[i2] >> 2]; - base64 += chars[(bytes[i2] & 3) << 4 | bytes[i2 + 1] >> 4]; - base64 += chars[(bytes[i2 + 1] & 15) << 2 | bytes[i2 + 2] >> 6]; - base64 += chars[bytes[i2 + 2] & 63]; +}; +const API_HIDE_TAB_BAR = "hideTabBar"; +const HideTabBarProtocol = { + animation: Boolean +}; +const API_SHOW_TAB_BAR = "showTabBar"; +const ShowTabBarProtocol = HideTabBarProtocol; +const API_HIDE_TAB_BAR_RED_DOT = "hideTabBarRedDot"; +const HideTabBarRedDotProtocol = IndexProtocol; +const HideTabBarRedDotOptions = IndexOptions; +const API_SHOW_TAB_BAR_RED_DOT = "showTabBarRedDot"; +const ShowTabBarRedDotProtocol = IndexProtocol; +const ShowTabBarRedDotOptions = IndexOptions; +const API_REMOVE_TAB_BAR_BADGE = "removeTabBarBadge"; +const RemoveTabBarBadgeProtocol = IndexProtocol; +const RemoveTabBarBadgeOptions = IndexOptions; +const API_SET_TAB_BAR_BADGE = "setTabBarBadge"; +const SetTabBarBadgeProtocol = /* @__PURE__ */ extend({ + text: { + type: String, + required: true } - if (len % 3 === 2) { - base64 = base64.substring(0, base64.length - 1) + "="; - } else if (len % 3 === 1) { - base64 = base64.substring(0, base64.length - 2) + "=="; +}, IndexProtocol); +const SetTabBarBadgeOptions = { + beforeInvoke: IndexOptions.beforeInvoke, + formatArgs: /* @__PURE__ */ extend({ + text(value, params) { + if (getLen(value) >= 4) { + params.text = "..."; + } + } + }, IndexOptions.formatArgs) +}; +const initIntersectionObserverPolyfill = function() { + if (typeof window !== "object") { + return; } - return base64; -} -function decode(base64) { - var bufferLength = base64.length * 0.75, len = base64.length, i2, p2 = 0, encoded1, encoded2, encoded3, encoded4; - if (base64[base64.length - 1] === "=") { - bufferLength--; - if (base64[base64.length - 2] === "=") { - bufferLength--; + if ("IntersectionObserver" in window && "IntersectionObserverEntry" in window && "intersectionRatio" in window.IntersectionObserverEntry.prototype) { + if (!("isIntersecting" in window.IntersectionObserverEntry.prototype)) { + Object.defineProperty(window.IntersectionObserverEntry.prototype, "isIntersecting", { + get: function() { + return this.intersectionRatio > 0; + } + }); } + return; } - var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); - for (i2 = 0; i2 < len; i2 += 4) { - encoded1 = lookup[base64.charCodeAt(i2)]; - encoded2 = lookup[base64.charCodeAt(i2 + 1)]; - encoded3 = lookup[base64.charCodeAt(i2 + 2)]; - encoded4 = lookup[base64.charCodeAt(i2 + 3)]; - bytes[p2++] = encoded1 << 2 | encoded2 >> 4; - bytes[p2++] = (encoded2 & 15) << 4 | encoded3 >> 2; - bytes[p2++] = (encoded3 & 3) << 6 | encoded4 & 63; + function getFrameElement(doc) { + try { + return doc.defaultView && doc.defaultView.frameElement || null; + } catch (e2) { + return null; + } } - return arraybuffer; -} -const CHOOSE_SIZE_TYPES = ["original", "compressed"]; -const CHOOSE_SOURCE_TYPES = ["album", "camera"]; -const HTTP_METHODS = [ - "GET", - "OPTIONS", - "HEAD", - "POST", - "PUT", - "DELETE", - "TRACE", - "CONNECT" -]; -function elemInArray(str, arr) { - if (!str || arr.indexOf(str) === -1) { - return arr[0]; + var document2 = function(startDoc) { + var doc = startDoc; + var frame = getFrameElement(doc); + while (frame) { + doc = frame.ownerDocument; + frame = getFrameElement(doc); + } + return doc; + }(window.document); + var registry = []; + var crossOriginUpdater = null; + var crossOriginRect = null; + function IntersectionObserverEntry(entry) { + this.time = entry.time; + this.target = entry.target; + this.rootBounds = ensureDOMRect(entry.rootBounds); + this.boundingClientRect = ensureDOMRect(entry.boundingClientRect); + this.intersectionRect = ensureDOMRect(entry.intersectionRect || getEmptyRect()); + this.isIntersecting = !!entry.intersectionRect; + var targetRect = this.boundingClientRect; + var targetArea = targetRect.width * targetRect.height; + var intersectionRect = this.intersectionRect; + var intersectionArea = intersectionRect.width * intersectionRect.height; + if (targetArea) { + this.intersectionRatio = Number((intersectionArea / targetArea).toFixed(4)); + } else { + this.intersectionRatio = this.isIntersecting ? 1 : 0; + } } - return str; -} -function elemsInArray(strArr, optionalVal) { - if (!isArray(strArr) || strArr.length === 0 || strArr.find((val) => optionalVal.indexOf(val) === -1)) { - return optionalVal; + function IntersectionObserver2(callback, opt_options) { + var options = opt_options || {}; + if (typeof callback != "function") { + throw new Error("callback must be a function"); + } + if (options.root && options.root.nodeType != 1 && options.root.nodeType != 9) { + throw new Error("root must be a Document or Element"); + } + this._checkForIntersections = throttle2(this._checkForIntersections.bind(this), this.THROTTLE_TIMEOUT); + this._callback = callback; + this._observationTargets = []; + this._queuedEntries = []; + this._rootMarginValues = this._parseRootMargin(options.rootMargin); + this.thresholds = this._initThresholds(options.threshold); + this.root = options.root || null; + this.rootMargin = this._rootMarginValues.map(function(margin) { + return margin.value + margin.unit; + }).join(" "); + this._monitoringDocuments = []; + this._monitoringUnsubscribes = []; } - return strArr; -} -function validateProtocolFail(name, msg) { - console.warn(`${name}: ${msg}`); -} -function validateProtocol(name, data, protocol) { - for (const key in protocol) { - const errMsg = validateProp(key, data[key], protocol[key], !hasOwn$1(data, key)); - if (isString(errMsg)) { - validateProtocolFail(name, errMsg); + IntersectionObserver2.prototype.THROTTLE_TIMEOUT = 100; + IntersectionObserver2.prototype.POLL_INTERVAL = null; + IntersectionObserver2.prototype.USE_MUTATION_OBSERVER = true; + IntersectionObserver2._setupCrossOriginUpdater = function() { + if (!crossOriginUpdater) { + crossOriginUpdater = function(boundingClientRect, intersectionRect) { + if (!boundingClientRect || !intersectionRect) { + crossOriginRect = getEmptyRect(); + } else { + crossOriginRect = convertFromParentRect(boundingClientRect, intersectionRect); + } + registry.forEach(function(observer) { + observer._checkForIntersections(); + }); + }; + } + return crossOriginUpdater; + }; + IntersectionObserver2._resetCrossOriginUpdater = function() { + crossOriginUpdater = null; + crossOriginRect = null; + }; + IntersectionObserver2.prototype.observe = function(target) { + var isTargetAlreadyObserved = this._observationTargets.some(function(item) { + return item.element == target; + }); + if (isTargetAlreadyObserved) { + return; + } + if (!(target && target.nodeType == 1)) { + throw new Error("target must be an Element"); + } + this._registerInstance(); + this._observationTargets.push({element: target, entry: null}); + this._monitorIntersections(target.ownerDocument); + this._checkForIntersections(); + }; + IntersectionObserver2.prototype.unobserve = function(target) { + this._observationTargets = this._observationTargets.filter(function(item) { + return item.element != target; + }); + this._unmonitorIntersections(target.ownerDocument); + if (this._observationTargets.length == 0) { + this._unregisterInstance(); + } + }; + IntersectionObserver2.prototype.disconnect = function() { + this._observationTargets = []; + this._unmonitorAllIntersections(); + this._unregisterInstance(); + }; + IntersectionObserver2.prototype.takeRecords = function() { + var records = this._queuedEntries.slice(); + this._queuedEntries = []; + return records; + }; + IntersectionObserver2.prototype._initThresholds = function(opt_threshold) { + var threshold = opt_threshold || [0]; + if (!Array.isArray(threshold)) + threshold = [threshold]; + return threshold.sort().filter(function(t2, i2, a2) { + if (typeof t2 != "number" || isNaN(t2) || t2 < 0 || t2 > 1) { + throw new Error("threshold must be a number between 0 and 1 inclusively"); + } + return t2 !== a2[i2 - 1]; + }); + }; + IntersectionObserver2.prototype._parseRootMargin = function(opt_rootMargin) { + var marginString = opt_rootMargin || "0px"; + var margins = marginString.split(/\s+/).map(function(margin) { + var parts = /^(-?\d*\.?\d+)(px|%)$/.exec(margin); + if (!parts) { + throw new Error("rootMargin must be specified in pixels or percent"); + } + return {value: parseFloat(parts[1]), unit: parts[2]}; + }); + margins[1] = margins[1] || margins[0]; + margins[2] = margins[2] || margins[0]; + margins[3] = margins[3] || margins[1]; + return margins; + }; + IntersectionObserver2.prototype._monitorIntersections = function(doc) { + var win = doc.defaultView; + if (!win) { + return; + } + if (this._monitoringDocuments.indexOf(doc) != -1) { + return; + } + var callback = this._checkForIntersections; + var monitoringInterval = null; + var domObserver = null; + if (this.POLL_INTERVAL) { + monitoringInterval = win.setInterval(callback, this.POLL_INTERVAL); + } else { + addEvent(win, "resize", callback, true); + addEvent(doc, "scroll", callback, true); + if (this.USE_MUTATION_OBSERVER && "MutationObserver" in win) { + domObserver = new win.MutationObserver(callback); + domObserver.observe(doc, { + attributes: true, + childList: true, + characterData: true, + subtree: true + }); + } + } + this._monitoringDocuments.push(doc); + this._monitoringUnsubscribes.push(function() { + var win2 = doc.defaultView; + if (win2) { + if (monitoringInterval) { + win2.clearInterval(monitoringInterval); + } + removeEvent(win2, "resize", callback, true); + } + removeEvent(doc, "scroll", callback, true); + if (domObserver) { + domObserver.disconnect(); + } + }); + var rootDoc = this.root && (this.root.ownerDocument || this.root) || document2; + if (doc != rootDoc) { + var frame = getFrameElement(doc); + if (frame) { + this._monitorIntersections(frame.ownerDocument); + } + } + }; + IntersectionObserver2.prototype._unmonitorIntersections = function(doc) { + var index2 = this._monitoringDocuments.indexOf(doc); + if (index2 == -1) { + return; + } + var rootDoc = this.root && (this.root.ownerDocument || this.root) || document2; + var hasDependentTargets = this._observationTargets.some(function(item) { + var itemDoc = item.element.ownerDocument; + if (itemDoc == doc) { + return true; + } + while (itemDoc && itemDoc != rootDoc) { + var frame2 = getFrameElement(itemDoc); + itemDoc = frame2 && frame2.ownerDocument; + if (itemDoc == doc) { + return true; + } + } + return false; + }); + if (hasDependentTargets) { + return; } - } -} -function validateProtocols(name, args, protocol) { - if (!protocol) { - return; - } - if (!isArray(protocol)) { - return validateProtocol(name, args[0] || Object.create(null), protocol); - } - const len = protocol.length; - const argsLen = args.length; - for (let i2 = 0; i2 < len; i2++) { - const opts = protocol[i2]; - const data = Object.create(null); - if (argsLen > i2) { - data[opts.name] = args[i2]; + var unsubscribe = this._monitoringUnsubscribes[index2]; + this._monitoringDocuments.splice(index2, 1); + this._monitoringUnsubscribes.splice(index2, 1); + unsubscribe(); + if (doc != rootDoc) { + var frame = getFrameElement(doc); + if (frame) { + this._unmonitorIntersections(frame.ownerDocument); + } } - validateProtocol(name, data, {[opts.name]: opts}); - } -} -function validateProp(name, value, prop, isAbsent) { - if (!isPlainObject(prop)) { - prop = {type: prop}; - } - const {type, required, validator} = prop; - if (required && isAbsent) { - return 'Missing required args: "' + name + '"'; - } - if (value == null && !required) { - return; - } - if (type != null) { - let isValid = false; - const types = isArray(type) ? type : [type]; - const expectedTypes = []; - for (let i2 = 0; i2 < types.length && !isValid; i2++) { - const {valid, expectedType} = assertType(value, types[i2]); - expectedTypes.push(expectedType || ""); - isValid = valid; + }; + IntersectionObserver2.prototype._unmonitorAllIntersections = function() { + var unsubscribes = this._monitoringUnsubscribes.slice(0); + this._monitoringDocuments.length = 0; + this._monitoringUnsubscribes.length = 0; + for (var i2 = 0; i2 < unsubscribes.length; i2++) { + unsubscribes[i2](); } - if (!isValid) { - return getInvalidTypeMessage(name, value, expectedTypes); + }; + IntersectionObserver2.prototype._checkForIntersections = function() { + if (!this.root && crossOriginUpdater && !crossOriginRect) { + return; } - } - if (validator) { - return validator(value); - } -} -const isSimpleType = /* @__PURE__ */ makeMap$1("String,Number,Boolean,Function,Symbol"); -function assertType(value, type) { - let valid; - const expectedType = getType(type); - if (isSimpleType(expectedType)) { - const t2 = typeof value; - valid = t2 === expectedType.toLowerCase(); - if (!valid && t2 === "object") { - valid = value instanceof type; + var rootIsInDom = this._rootIsInDom(); + var rootRect = rootIsInDom ? this._getRootRect() : getEmptyRect(); + this._observationTargets.forEach(function(item) { + var target = item.element; + var targetRect = getBoundingClientRect(target); + var rootContainsTarget = this._rootContainsTarget(target); + var oldEntry = item.entry; + var intersectionRect = rootIsInDom && rootContainsTarget && this._computeTargetAndRootIntersection(target, targetRect, rootRect); + var rootBounds = null; + if (!this._rootContainsTarget(target)) { + rootBounds = getEmptyRect(); + } else if (!crossOriginUpdater || this.root) { + rootBounds = rootRect; + } + var newEntry = item.entry = new IntersectionObserverEntry({ + time: now(), + target, + boundingClientRect: targetRect, + rootBounds, + intersectionRect + }); + if (!oldEntry) { + this._queuedEntries.push(newEntry); + } else if (rootIsInDom && rootContainsTarget) { + if (this._hasCrossedThreshold(oldEntry, newEntry)) { + this._queuedEntries.push(newEntry); + } + } else { + if (oldEntry && oldEntry.isIntersecting) { + this._queuedEntries.push(newEntry); + } + } + }, this); + if (this._queuedEntries.length) { + this._callback(this.takeRecords(), this); } - } else if (expectedType === "Object") { - valid = isObject$1(value); - } else if (expectedType === "Array") { - valid = isArray(value); - } else { - { - valid = value instanceof type; + }; + IntersectionObserver2.prototype._computeTargetAndRootIntersection = function(target, targetRect, rootRect) { + if (window.getComputedStyle(target).display == "none") + return; + var intersectionRect = targetRect; + var parent = getParentNode(target); + var atRoot = false; + while (!atRoot && parent) { + var parentRect = null; + var parentComputedStyle = parent.nodeType == 1 ? window.getComputedStyle(parent) : {}; + if (parentComputedStyle.display == "none") + return null; + if (parent == this.root || parent.nodeType == 9) { + atRoot = true; + if (parent == this.root || parent == document2) { + if (crossOriginUpdater && !this.root) { + if (!crossOriginRect || crossOriginRect.width == 0 && crossOriginRect.height == 0) { + parent = null; + parentRect = null; + intersectionRect = null; + } else { + parentRect = crossOriginRect; + } + } else { + parentRect = rootRect; + } + } else { + var frame = getParentNode(parent); + var frameRect = frame && getBoundingClientRect(frame); + var frameIntersect = frame && this._computeTargetAndRootIntersection(frame, frameRect, rootRect); + if (frameRect && frameIntersect) { + parent = frame; + parentRect = convertFromParentRect(frameRect, frameIntersect); + } else { + parent = null; + intersectionRect = null; + } + } + } else { + var doc = parent.ownerDocument; + if (parent != doc.body && parent != doc.documentElement && parentComputedStyle.overflow != "visible") { + parentRect = getBoundingClientRect(parent); + } + } + if (parentRect) { + intersectionRect = computeRectIntersection(parentRect, intersectionRect); + } + if (!intersectionRect) + break; + parent = parent && getParentNode(parent); } - } - return { - valid, - expectedType + return intersectionRect; }; -} -function getInvalidTypeMessage(name, value, expectedTypes) { - let message = `Invalid args: type check failed for args "${name}". Expected ${expectedTypes.map(capitalize).join(", ")}`; - const expectedType = expectedTypes[0]; - const receivedType = toRawType(value); - const expectedValue = styleValue(value, expectedType); - const receivedValue = styleValue(value, receivedType); - if (expectedTypes.length === 1 && isExplicable(expectedType) && !isBoolean(expectedType, receivedType)) { - message += ` with value ${expectedValue}`; - } - message += `, got ${receivedType} `; - if (isExplicable(receivedType)) { - message += `with value ${receivedValue}.`; - } - return message; -} -function getType(ctor) { - const match = ctor && ctor.toString().match(/^\s*function (\w+)/); - return match ? match[1] : ""; -} -function styleValue(value, type) { - if (type === "String") { - return `"${value}"`; - } else if (type === "Number") { - return `${Number(value)}`; - } else { - return `${value}`; - } -} -function isExplicable(type) { - const explicitTypes = ["string", "number", "boolean"]; - return explicitTypes.some((elem) => type.toLowerCase() === elem); -} -function isBoolean(...args) { - return args.some((elem) => elem.toLowerCase() === "boolean"); -} -function tryCatch(fn) { - return function() { - try { - return fn.apply(fn, arguments); - } catch (e2) { - console.error(e2); + IntersectionObserver2.prototype._getRootRect = function() { + var rootRect; + if (this.root && !isDoc(this.root)) { + rootRect = getBoundingClientRect(this.root); + } else { + var doc = isDoc(this.root) ? this.root : document2; + var html = doc.documentElement; + var body = doc.body; + rootRect = { + top: 0, + left: 0, + right: html.clientWidth || body.clientWidth, + width: html.clientWidth || body.clientWidth, + bottom: html.clientHeight || body.clientHeight, + height: html.clientHeight || body.clientHeight + }; } + return this._expandRectByRootMargin(rootRect); }; -} -let invokeCallbackId = 1; -const invokeCallbacks = {}; -function addInvokeCallback(id2, name, callback, keepAlive = false) { - invokeCallbacks[id2] = { - name, - keepAlive, - callback + IntersectionObserver2.prototype._expandRectByRootMargin = function(rect) { + var margins = this._rootMarginValues.map(function(margin, i2) { + return margin.unit == "px" ? margin.value : margin.value * (i2 % 2 ? rect.width : rect.height) / 100; + }); + var newRect = { + top: rect.top - margins[0], + right: rect.right + margins[1], + bottom: rect.bottom + margins[2], + left: rect.left - margins[3] + }; + newRect.width = newRect.right - newRect.left; + newRect.height = newRect.bottom - newRect.top; + return newRect; }; - return id2; -} -function invokeCallback(id2, res, extras) { - if (typeof id2 === "number") { - const opts = invokeCallbacks[id2]; - if (opts) { - if (!opts.keepAlive) { - delete invokeCallbacks[id2]; + IntersectionObserver2.prototype._hasCrossedThreshold = function(oldEntry, newEntry) { + var oldRatio = oldEntry && oldEntry.isIntersecting ? oldEntry.intersectionRatio || 0 : -1; + var newRatio = newEntry.isIntersecting ? newEntry.intersectionRatio || 0 : -1; + if (oldRatio === newRatio) + return; + for (var i2 = 0; i2 < this.thresholds.length; i2++) { + var threshold = this.thresholds[i2]; + if (threshold == oldRatio || threshold == newRatio || threshold < oldRatio !== threshold < newRatio) { + return true; } - return opts.callback(res, extras); - } - } - return res; -} -function findInvokeCallbackByName(name) { - for (const key in invokeCallbacks) { - if (invokeCallbacks[key].name === name) { - return true; } - } - return false; -} -function removeKeepAliveApiCallback(name, callback) { - for (const key in invokeCallbacks) { - const item = invokeCallbacks[key]; - if (item.callback === callback && item.name === name) { - delete invokeCallbacks[key]; + }; + IntersectionObserver2.prototype._rootIsInDom = function() { + return !this.root || containsDeep(document2, this.root); + }; + IntersectionObserver2.prototype._rootContainsTarget = function(target) { + var rootDoc = this.root && (this.root.ownerDocument || this.root) || document2; + return containsDeep(rootDoc, target) && (!this.root || rootDoc == target.ownerDocument); + }; + IntersectionObserver2.prototype._registerInstance = function() { + if (registry.indexOf(this) < 0) { + registry.push(this); } + }; + IntersectionObserver2.prototype._unregisterInstance = function() { + var index2 = registry.indexOf(this); + if (index2 != -1) + registry.splice(index2, 1); + }; + function now() { + return window.performance && performance.now && performance.now(); } -} -function offKeepAliveApiCallback(name) { - UniServiceJSBridge.off("api." + name); -} -function onKeepAliveApiCallback(name) { - UniServiceJSBridge.on("api." + name, (res) => { - for (const key in invokeCallbacks) { - const opts = invokeCallbacks[key]; - if (opts.name === name) { - opts.callback(res); + function throttle2(fn, timeout) { + var timer = null; + return function() { + if (!timer) { + timer = setTimeout(function() { + fn(); + timer = null; + }, timeout); } - } - }); -} -function createKeepAliveApiCallback(name, callback) { - return addInvokeCallback(invokeCallbackId++, name, callback, true); -} -const API_SUCCESS = "success"; -const API_FAIL = "fail"; -const API_COMPLETE = "complete"; -function getApiCallbacks(args) { - const apiCallbacks = {}; - for (const name in args) { - const fn = args[name]; - if (isFunction(fn)) { - apiCallbacks[name] = tryCatch(fn); - delete args[name]; - } - } - return apiCallbacks; -} -function normalizeErrMsg(errMsg, name) { - if (!errMsg || errMsg.indexOf(":fail") === -1) { - return name + ":ok"; + }; } - return name + errMsg.substring(errMsg.indexOf(":fail")); -} -function createAsyncApiCallback(name, args = {}, {beforeAll, beforeSuccess} = {}) { - if (!isPlainObject(args)) { - args = {}; + function addEvent(node, event2, fn, opt_useCapture) { + if (typeof node.addEventListener == "function") { + node.addEventListener(event2, fn, opt_useCapture || false); + } else if (typeof node.attachEvent == "function") { + node.attachEvent("on" + event2, fn); + } } - const {success, fail, complete} = getApiCallbacks(args); - const hasSuccess = isFunction(success); - const hasFail = isFunction(fail); - const hasComplete = isFunction(complete); - const callbackId = invokeCallbackId++; - addInvokeCallback(callbackId, name, (res) => { - res = res || {}; - res.errMsg = normalizeErrMsg(res.errMsg, name); - isFunction(beforeAll) && beforeAll(res); - if (res.errMsg === name + ":ok") { - isFunction(beforeSuccess) && beforeSuccess(res); - hasSuccess && success(res); - } else { - hasFail && fail(res); + function removeEvent(node, event2, fn, opt_useCapture) { + if (typeof node.removeEventListener == "function") { + node.removeEventListener(event2, fn, opt_useCapture || false); + } else if (typeof node.detatchEvent == "function") { + node.detatchEvent("on" + event2, fn); } - hasComplete && complete(res); - }); - return callbackId; -} -const callbacks = [API_SUCCESS, API_FAIL, API_COMPLETE]; -function hasCallback(args) { - if (isPlainObject(args) && callbacks.find((cb) => isFunction(args[cb]))) { - return true; } - return false; -} -function handlePromise(promise) { - if (__UNI_FEATURE_PROMISE__) { - return promise.then((data) => { - return [null, data]; - }).catch((err) => [err]); + function computeRectIntersection(rect1, rect2) { + var top = Math.max(rect1.top, rect2.top); + var bottom = Math.min(rect1.bottom, rect2.bottom); + var left = Math.max(rect1.left, rect2.left); + var right = Math.min(rect1.right, rect2.right); + var width = right - left; + var height = bottom - top; + return width >= 0 && height >= 0 && { + top, + bottom, + left, + right, + width, + height + } || null; } - return promise; -} -function promisify(fn) { - return (args = {}) => { - if (hasCallback(args)) { - return fn(args); + function getBoundingClientRect(el) { + var rect; + try { + rect = el.getBoundingClientRect(); + } catch (err) { } - return handlePromise(new Promise((resolve, reject) => { - fn(Object.assign(args, {success: resolve, fail: reject})); - })); - }; -} -function formatApiArgs(args, options) { - const params = args[0]; - if (!options || !isPlainObject(options.formatArgs) && isPlainObject(params)) { - return; - } - const formatArgs = options.formatArgs; - const keys = Object.keys(formatArgs); - for (let i2 = 0; i2 < keys.length; i2++) { - const name = keys[i2]; - const formatterOrDefaultValue = formatArgs[name]; - if (isFunction(formatterOrDefaultValue)) { - const errMsg = formatterOrDefaultValue(args[0][name], params); - if (isString(errMsg)) { - return errMsg; - } - } else { - if (!hasOwn$1(params, name)) { - params[name] = formatterOrDefaultValue; - } + if (!rect) + return getEmptyRect(); + if (!(rect.width && rect.height)) { + rect = { + top: rect.top, + right: rect.right, + bottom: rect.bottom, + left: rect.left, + width: rect.right - rect.left, + height: rect.bottom - rect.top + }; } + return rect; } -} -function invokeSuccess(id2, name, res) { - return invokeCallback(id2, extend(res || {}, {errMsg: name + ":ok"})); -} -function invokeFail(id2, name, err) { - return invokeCallback(id2, {errMsg: name + ":fail" + (err ? " " + err : "")}); -} -function beforeInvokeApi(name, args, protocol, options) { - if (process.env.NODE_ENV !== "production") { - validateProtocols(name, args, protocol); + function getEmptyRect() { + return { + top: 0, + bottom: 0, + left: 0, + right: 0, + width: 0, + height: 0 + }; } - if (options && options.beforeInvoke) { - const errMsg2 = options.beforeInvoke(args); - if (isString(errMsg2)) { - return errMsg2; + function ensureDOMRect(rect) { + if (!rect || "x" in rect) { + return rect; } + return { + top: rect.top, + y: rect.top, + bottom: rect.bottom, + left: rect.left, + x: rect.left, + right: rect.right, + width: rect.width, + height: rect.height + }; } - const errMsg = formatApiArgs(args, options); - if (errMsg) { - return errMsg; - } -} -function checkCallback(callback) { - if (!isFunction(callback)) { - throw new Error('Invalid args: type check failed for args "callback". Expected Function'); + function convertFromParentRect(parentBoundingRect, parentIntersectionRect) { + var top = parentIntersectionRect.top - parentBoundingRect.top; + var left = parentIntersectionRect.left - parentBoundingRect.left; + return { + top, + left, + height: parentIntersectionRect.height, + width: parentIntersectionRect.width, + bottom: top + parentIntersectionRect.height, + right: left + parentIntersectionRect.width + }; } -} -function wrapperOnApi(name, fn, options) { - return (callback) => { - checkCallback(callback); - const errMsg = beforeInvokeApi(name, [callback], void 0, options); - if (errMsg) { - throw new Error(errMsg); + function containsDeep(parent, child) { + var node = child; + while (node) { + if (node == parent) + return true; + node = getParentNode(node); } - const isFirstInvokeOnApi = !findInvokeCallbackByName(name); - createKeepAliveApiCallback(name, callback); - if (isFirstInvokeOnApi) { - onKeepAliveApiCallback(name); - fn(); + return false; + } + function getParentNode(node) { + var parent = node.parentNode; + if (node.nodeType == 9 && node != document2) { + return getFrameElement(node); } - }; -} -function wrapperOffApi(name, fn, options) { - return (callback) => { - checkCallback(callback); - const errMsg = beforeInvokeApi(name, [callback], void 0, options); - if (errMsg) { - throw new Error(errMsg); + if (parent && parent.assignedSlot) { + parent = parent.assignedSlot.parentNode; } - name = name.replace("off", "on"); - removeKeepAliveApiCallback(name, callback); - const hasInvokeOnApi = findInvokeCallbackByName(name); - if (!hasInvokeOnApi) { - offKeepAliveApiCallback(name); - fn(); + if (parent && parent.nodeType == 11 && parent.host) { + return parent.host; } + return parent; + } + function isDoc(node) { + return node && node.nodeType === 9; + } + window.IntersectionObserver = IntersectionObserver2; + window.IntersectionObserverEntry = IntersectionObserverEntry; +}; +function normalizeRect(rect) { + const {bottom, height, left, right, top, width} = rect || {}; + return { + bottom, + height, + left, + right, + top, + width }; } -function wrapperTaskApi(name, fn, protocol, options) { - return (args) => { - const id2 = createAsyncApiCallback(name, args, options); - const errMsg = beforeInvokeApi(name, [args], protocol, options); - if (errMsg) { - return invokeFail(id2, name, errMsg); - } - return fn(args, { - resolve: (res) => invokeSuccess(id2, name, res), - reject: (err) => invokeFail(id2, name, err) +function requestComponentObserver($el, options, callback) { + initIntersectionObserverPolyfill(); + const root = options.relativeToSelector ? $el.querySelector(options.relativeToSelector) : null; + const intersectionObserver = new IntersectionObserver((entries) => { + entries.forEach((entrie) => { + callback({ + intersectionRatio: entrie.intersectionRatio, + intersectionRect: normalizeRect(entrie.intersectionRect), + boundingClientRect: normalizeRect(entrie.boundingClientRect), + relativeRect: normalizeRect(entrie.rootBounds), + time: Date.now() + }); }); - }; -} -function wrapperSyncApi(name, fn, protocol, options) { - return (...args) => { - const errMsg = beforeInvokeApi(name, args, protocol, options); - if (errMsg) { - throw new Error(errMsg); + }, { + root, + rootMargin: options.rootMargin, + threshold: options.thresholds + }); + if (options.observeAll) { + intersectionObserver.USE_MUTATION_OBSERVER = true; + const nodeList = $el.querySelectorAll(options.selector); + for (let i2 = 0; i2 < nodeList.length; i2++) { + intersectionObserver.observe(nodeList[i2]); } - return fn.apply(null, args); - }; -} -function wrapperAsyncApi(name, fn, protocol, options) { - return wrapperTaskApi(name, fn, protocol, options); -} -function defineOnApi(name, fn, options) { - return wrapperOnApi(name, fn, options); -} -function defineOffApi(name, fn, options) { - return wrapperOffApi(name, fn, options); -} -function defineTaskApi(name, fn, protocol, options) { - return promisify(wrapperTaskApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options)); -} -function defineSyncApi(name, fn, protocol, options) { - return wrapperSyncApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options); + } else { + intersectionObserver.USE_MUTATION_OBSERVER = false; + const el = $el.querySelector(options.selector); + if (!el) { + console.warn(`Node ${options.selector} is not found. Intersection observer will not trigger.`); + } else { + intersectionObserver.observe(el); + } + } + return intersectionObserver; } -function defineAsyncApi(name, fn, protocol, options) { - return promisify(wrapperAsyncApi(name, fn, process.env.NODE_ENV !== "production" ? protocol : void 0, options)); +const supports = window.CSS && window.CSS.supports; +function cssSupports(css) { + return supports && (supports(css) || supports.apply(window.CSS, css.split(":"))); } -const API_BASE64_TO_ARRAY_BUFFER = "base64ToArrayBuffer"; -const Base64ToArrayBufferProtocol = [ - { - name: "base64", - type: String, - required: true - } -]; -const API_ARRAY_BUFFER_TO_BASE64 = "arrayBufferToBase64"; -const ArrayBufferToBase64Protocol = [ - { - name: "arrayBuffer", - type: [ArrayBuffer, Uint8Array], - required: true +const cssVar = /* @__PURE__ */ cssSupports("--a:0"); +const cssEnv = /* @__PURE__ */ cssSupports("top:env(a)"); +const cssConstant = /* @__PURE__ */ cssSupports("top:constant(a)"); +const cssBackdropFilter = /* @__PURE__ */ cssSupports("backdrop-filter:blur(10px)"); +const SCHEMA_CSS = { + "css.var": cssVar, + "css.env": cssEnv, + "css.constant": cssConstant, + "css.backdrop-filter": cssBackdropFilter +}; +const canIUse = defineSyncApi(API_CAN_I_USE, (schema) => { + if (hasOwn$1(SCHEMA_CSS, schema)) { + return SCHEMA_CSS[schema]; } -]; -const base64ToArrayBuffer = defineSyncApi(API_BASE64_TO_ARRAY_BUFFER, (base64) => { - return decode(base64); -}, Base64ToArrayBufferProtocol); -const arrayBufferToBase64 = defineSyncApi(API_ARRAY_BUFFER_TO_BASE64, (arrayBuffer) => { - return encode$1(arrayBuffer); -}, ArrayBufferToBase64Protocol); -const API_UPX2PX = "upx2px"; -const Upx2pxProtocol = [ - { - name: "upx", - type: [Number, String], - required: true + return true; +}, CanIUseProtocol); +const envMethod = /* @__PURE__ */ (() => cssEnv ? "env" : cssConstant ? "constant" : "")(); +function updateCurPageCssVar(pageMeta) { + let windowTopValue = 0; + let windowBottomValue = 0; + if (__UNI_FEATURE_NAVIGATIONBAR__ && ["default", "float"].indexOf(pageMeta.navigationBar.type) > -1) { + windowTopValue = NAVBAR_HEIGHT; + } + if (__UNI_FEATURE_TABBAR__ && pageMeta.isTabBar) { + const tabBar2 = useTabBar(); + tabBar2.shown && (windowBottomValue = parseInt(tabBar2.height)); } -]; -const EPS = 1e-4; -const BASE_DEVICE_WIDTH = 750; -let isIOS = false; -let deviceWidth = 0; -let deviceDPR = 0; -function checkDeviceWidth() { - const {platform, pixelRatio: pixelRatio2, windowWidth} = getBaseSystemInfo(); - deviceWidth = windowWidth; - deviceDPR = pixelRatio2; - isIOS = platform === "ios"; + updatePageCssVar({ + "--window-top": normalizeWindowBottom(windowTopValue), + "--window-bottom": normalizeWindowBottom(windowBottomValue) + }); } -const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => { - if (deviceWidth === 0) { - checkDeviceWidth(); - } - number = Number(number); - if (number === 0) { - return 0; +function normalizeWindowBottom(windowBottom) { + return envMethod ? `calc(${windowBottom}px + ${envMethod}(safe-area-inset-bottom))` : `${windowBottom}px`; +} +function usePageRoute() { + if (__UNI_FEATURE_PAGES__) { + return useRoute(); } - let result = number / BASE_DEVICE_WIDTH * (newDeviceWidth || deviceWidth); - if (result < 0) { - result = -result; + const url = location.href; + const searchPos = url.indexOf("?"); + const hashPos = url.indexOf("#", searchPos > -1 ? searchPos : 0); + let query = {}; + if (searchPos > -1) { + query = parseQuery(url.slice(searchPos + 1, hashPos > -1 ? hashPos : url.length)); } - result = Math.floor(result + EPS); - if (result === 0) { - if (deviceDPR === 1 || !isIOS) { - result = 1; - } else { - result = 0.5; + const {meta} = __uniRoutes[0]; + return { + meta, + query, + path: "/" + meta.route + }; +} +function wrapperComponentSetup(comp, {init: init2, setup, after}) { + const oldSetup = comp.setup; + comp.setup = (props2, ctx) => { + const instance2 = getCurrentInstance(); + init2(instance2.proxy); + const query = setup(instance2); + if (oldSetup) { + return oldSetup(query, ctx); } - } - return number < 0 ? -result : result; -}, Upx2pxProtocol); -const globalInterceptors = {}; -const scopedInterceptors = {}; -const API_ADD_INTERCEPTOR = "addInterceptor"; -const API_REMOVE_INTERCEPTOR = "removeInterceptor"; -const AddInterceptorProtocol = [ - { - name: "method", - type: [String, Object], - required: true - } -]; -const RemoveInterceptorProtocol = AddInterceptorProtocol; -function mergeInterceptorHook(interceptors, interceptor) { - Object.keys(interceptor).forEach((hook) => { - if (isFunction(interceptor[hook])) { - interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]); + }; + after && after(comp); +} +function setupComponent(comp, options) { + if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) { + wrapperComponentSetup(comp.default, options); + } else { + wrapperComponentSetup(comp, options); + } + return comp; +} +function onPageShow(pageMeta) { + updateCurPageCssVar(pageMeta); +} +function setupPage(comp) { + return setupComponent(comp, { + init: initPage, + setup(instance2) { + instance2.root = instance2; + const route = usePageRoute(); + if (route.meta.isTabBar) { + instance2.__isActive = true; + } + const pageMeta = usePageMeta(); + onBeforeMount(() => { + const {onLoad, onShow} = instance2; + onPageShow(pageMeta); + onLoad && invokeArrayFns$1(onLoad, decodedQuery(route.query)); + instance2.__isVisible = true; + onShow && invokeArrayFns$1(onShow); + }); + onMounted(() => { + const {onReady} = instance2; + onReady && invokeArrayFns$1(onReady); + }); + onBeforeActivate(() => { + if (!instance2.__isVisible) { + onPageShow(pageMeta); + instance2.__isVisible = true; + const {onShow} = instance2; + onShow && invokeArrayFns$1(onShow); + } + }); + onBeforeDeactivate(() => { + if (instance2.__isVisible && !instance2.__isUnload) { + instance2.__isVisible = false; + const {onHide} = instance2; + onHide && invokeArrayFns$1(onHide); + } + }); + return route.query; } }); } -function removeInterceptorHook(interceptors, interceptor) { - if (!interceptors || !interceptor) { - return; - } - Object.keys(interceptor).forEach((hook) => { - if (isFunction(interceptor[hook])) { - removeHook(interceptors[hook], interceptor[hook]); +function setupApp(comp) { + return setupComponent(comp, { + init: initApp, + setup(instance2) { + const route = usePageRoute(); + const onLaunch = () => { + const {onLaunch: onLaunch2, onShow} = instance2; + const path = route.path.substr(1); + const launchOptions = { + path: path || __uniRoutes[0].meta.route, + query: decodedQuery(route.query), + scene: 1001 + }; + onLaunch2 && invokeArrayFns$1(onLaunch2, launchOptions); + onShow && invokeArrayFns$1(onShow, launchOptions); + }; + if (__UNI_FEATURE_PAGES__) { + useRouter().isReady().then(onLaunch); + } else { + onBeforeMount(onLaunch); + } + onMounted(() => { + document.addEventListener("visibilitychange", function() { + if (document.visibilityState === "visible") { + UniServiceJSBridge.emit("onAppEnterForeground"); + } else { + UniServiceJSBridge.emit("onAppEnterBackground"); + } + }); + }); + return route.query; + }, + after(comp2) { + comp2.mpType = "app"; + comp2.render = () => (openBlock(), createBlock(LayoutComponent)); } }); } -function mergeHook(parentVal, childVal) { - const res = childVal ? parentVal ? parentVal.concat(childVal) : isArray(childVal) ? childVal : [childVal] : parentVal; - return res ? dedupeHooks(res) : res; -} -function dedupeHooks(hooks) { - const res = []; - for (let i2 = 0; i2 < hooks.length; i2++) { - if (res.indexOf(hooks[i2]) === -1) { - res.push(hooks[i2]); +function broadcast(componentName, eventName, ...params) { + const children = this.$children; + const len = children.length; + for (let i2 = 0; i2 < len; i2++) { + const child = children[i2]; + const name = child.$options.name && child.$options.name.substr(4); + if (~componentName.indexOf(name)) { + child.$emit.apply(child, [eventName].concat(params)); + return false; + } else { + if (broadcast.apply(child, [componentName, eventName].concat([params])) === false) { + return false; + } } } - return res; -} -function removeHook(hooks, hook) { - if (!hooks) { - return; - } - const index2 = hooks.indexOf(hook); - if (index2 !== -1) { - hooks.splice(index2, 1); - } } -const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => { - if (typeof method === "string" && isPlainObject(interceptor)) { - mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); - } else if (isPlainObject(method)) { - mergeInterceptorHook(globalInterceptors, method); +var emitter = { + methods: { + $dispatch(componentName, eventName, ...params) { + console.log("$dispatch", componentName, eventName, params); + }, + $broadcast(componentName, eventName, ...params) { + if (typeof componentName === "string") { + componentName = [componentName]; + } + broadcast.apply(this, [componentName, eventName].concat(params)); + } } -}, AddInterceptorProtocol); -const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => { - if (typeof method === "string") { - if (isPlainObject(interceptor)) { - removeInterceptorHook(scopedInterceptors[method], interceptor); - } else { - delete scopedInterceptors[method]; +}; +var listeners = { + props: { + id: { + type: String, + default: "" + } + }, + created() { + this._addListeners(this.id); + this.$watch("id", (newId, oldId) => { + this._removeListeners(oldId, true); + this._addListeners(newId, true); + }); + }, + beforeDestroy() { + this._removeListeners(this.id); + }, + methods: { + _addListeners(id2, watch2) { + if (watch2 && !id2) { + return; + } + const {listeners: listeners2} = this.$options; + if (!isPlainObject(listeners2)) { + return; + } + Object.keys(listeners2).forEach((name) => { + if (watch2) { + if (name.indexOf("@") !== 0 && name.indexOf("uni-") !== 0) { + UniViewJSBridge.on(`uni-${name}-${this.$page.id}-${id2}`, this[listeners2[name]]); + } + } else { + if (name.indexOf("@") === 0) { + this.$on(`uni-${name.substr(1)}`, this[listeners2[name]]); + } else if (name.indexOf("uni-") === 0) { + UniViewJSBridge.on(name, this[listeners2[name]]); + } else if (id2) { + UniViewJSBridge.on(`uni-${name}-${this.$page.id}-${id2}`, this[listeners2[name]]); + } + } + }); + }, + _removeListeners(id2, watch2) { + if (watch2 && !id2) { + return; + } + const {listeners: listeners2} = this.$options; + if (!isPlainObject(listeners2)) { + return; + } + Object.keys(listeners2).forEach((name) => { + if (watch2) { + if (name.indexOf("@") !== 0 && name.indexOf("uni-") !== 0) { + UniViewJSBridge.off(`uni-${name}-${this.$page.id}-${id2}`, this[listeners2[name]]); + } + } else { + if (name.indexOf("@") === 0) { + this.$off(`uni-${name.substr(1)}`, this[listeners2[name]]); + } else if (name.indexOf("uni-") === 0) { + UniViewJSBridge.off(name, this[listeners2[name]]); + } else if (id2) { + UniViewJSBridge.off(`uni-${name}-${this.$page.id}-${id2}`, this[listeners2[name]]); + } + } + }); } - } else if (isPlainObject(method)) { - removeInterceptorHook(globalInterceptors, method); } -}, RemoveInterceptorProtocol); -const promiseInterceptor = { - returnValue(res) { - if (!isPromise(res)) { - return res; +}; +var hover = { + data() { + return { + hovering: false + }; + }, + props: { + hoverClass: { + type: String, + default: "none" + }, + hoverStopPropagation: { + type: Boolean, + default: false + }, + hoverStartTime: { + type: [Number, String], + default: 50 + }, + hoverStayTime: { + type: [Number, String], + default: 400 + } + }, + methods: { + _hoverTouchStart(evt) { + if (evt._hoverPropagationStopped) { + return; + } + if (!this.hoverClass || this.hoverClass === "none" || this.disabled) { + return; + } + if (evt.touches.length > 1) { + return; + } + if (this.hoverStopPropagation) { + evt._hoverPropagationStopped = true; + } + this._hoverTouch = true; + this._hoverStartTimer = setTimeout(() => { + this.hovering = true; + if (!this._hoverTouch) { + this._hoverReset(); + } + }, this.hoverStartTime); + }, + _hoverTouchEnd(evt) { + this._hoverTouch = false; + if (this.hovering) { + this._hoverReset(); + } + }, + _hoverReset() { + requestAnimationFrame(() => { + clearTimeout(this._hoverStayTimer); + this._hoverStayTimer = setTimeout(() => { + this.hovering = false; + }, this.hoverStayTime); + }); + }, + _hoverTouchCancel(evt) { + this._hoverTouch = false; + this.hovering = false; + clearTimeout(this._hoverStartTimer); } - return res.then((res2) => { - return res2[1]; - }).catch((res2) => { - return res2[0]; - }); } }; -const API_CREATE_VIDEO_CONTEXT = "createVideoContext"; -const API_CREATE_INNER_AUDIO_CONTEXT = "createInnerAudioContext"; -const RATES = [0.5, 0.8, 1, 1.25, 1.5, 2]; -class VideoContext { - constructor(id2, vm) { - this.id = id2; - this.vm = vm; - } - play() { - operateVideoPlayer(this.id, this.vm, "play"); - } - pause() { - operateVideoPlayer(this.id, this.vm, "pause"); - } - stop() { - operateVideoPlayer(this.id, this.vm, "stop"); - } - seek(position) { - operateVideoPlayer(this.id, this.vm, "seek", { - position +var subscriber = { + mounted() { + this._toggleListeners("subscribe", this.id); + this.$watch("id", (newId, oldId) => { + this._toggleListeners("unsubscribe", oldId, true); + this._toggleListeners("subscribe", newId, true); }); - } - sendDanmu(args) { - operateVideoPlayer(this.id, this.vm, "sendDanmu", args); - } - playbackRate(rate) { - if (!~RATES.indexOf(rate)) { - rate = 1; + }, + beforeDestroy() { + this._toggleListeners("unsubscribe", this.id); + if (this._contextId) { + this._toggleListeners("unsubscribe", this._contextId); + } + }, + methods: { + _toggleListeners(type, id2, watch2) { + if (watch2 && !id2) { + return; + } + if (!isFunction(this._handleSubscribe)) { + return; + } + UniViewJSBridge[type](this.$page.id + "-" + this.$options.name.replace(/VUni([A-Z])/, "$1").toLowerCase() + "-" + id2, this._handleSubscribe); + }, + _getContextInfo() { + const id2 = `context-${this._uid}`; + if (!this._contextId) { + this._toggleListeners("subscribe", id2); + this._contextId = id2; + } + return { + name: this.$options.name.replace(/VUni([A-Z])/, "$1").toLowerCase(), + id: id2, + page: this.$page.id + }; } - operateVideoPlayer(this.id, this.vm, "playbackRate", { - rate - }); - } - requestFullScreen(args = {}) { - operateVideoPlayer(this.id, this.vm, "requestFullScreen", args); - } - exitFullScreen() { - operateVideoPlayer(this.id, this.vm, "exitFullScreen"); - } - showStatusBar() { - operateVideoPlayer(this.id, this.vm, "showStatusBar"); - } - hideStatusBar() { - operateVideoPlayer(this.id, this.vm, "hideStatusBar"); - } -} -const createVideoContext = defineSyncApi(API_CREATE_VIDEO_CONTEXT, (id2, context) => { - if (context) { - return new VideoContext(id2, context); } - return new VideoContext(id2, getCurrentPageVm()); -}); -const defaultOptions = { - thresholds: [0], - initialRatio: 0, - observeAll: false }; -const MARGINS = ["top", "right", "bottom", "left"]; -let reqComponentObserverId = 1; -function normalizeRootMargin(margins = {}) { - return MARGINS.map((name) => `${Number(margins[name]) || 0}px`).join(" "); +function hideKeyboard$1() { + document.activeElement.blur(); } -class ServiceIntersectionObserver { - constructor(component, options) { - this._pageId = component.$page && component.$page.id; - this._component = component; - this._options = extend({}, defaultOptions, options); - } - relativeTo(selector, margins) { - this._options.relativeToSelector = selector; - this._options.rootMargin = normalizeRootMargin(margins); - return this; - } - relativeToViewport(margins) { - this._options.relativeToSelector = void 0; - this._options.rootMargin = normalizeRootMargin(margins); - return this; - } - observe(selector, callback) { - if (!isFunction(callback)) { - return; - } - this._options.selector = selector; - this._reqId = reqComponentObserverId++; - addIntersectionObserver({ - reqId: this._reqId, - component: this._component, - options: this._options, - callback - }, this._pageId); - } - disconnect() { - this._reqId && removeIntersectionObserver({reqId: this._reqId, component: this._component}, this._pageId); - } +function iosHideKeyboard() { } -const createIntersectionObserver = defineSyncApi("createIntersectionObserver", (context, options) => { - if (context && !context.$page) { - options = context; - context = null; - } - if (context) { - return new ServiceIntersectionObserver(context, options); - } - return new ServiceIntersectionObserver(getCurrentPageVm(), options); -}); -const createSelectorQuery = () => { -}; -const API_ON_TAB_BAR_MID_BUTTON_TAP = "onTabBarMidButtonTap"; -const onTabBarMidButtonTap = defineOnApi(API_ON_TAB_BAR_MID_BUTTON_TAP, () => { -}); -const API_CAN_I_USE = "canIUse"; -const CanIUseProtocol = [ - { - name: "schema", - type: String, - required: true - } -]; -const API_MAKE_PHONE_CALL = "makePhoneCall"; -const MakePhoneCallProtocol = { - phoneNumber: String -}; -const API_ON_ACCELEROMETER = "onAccelerometer"; -const API_OFF_ACCELEROMETER = "offAccelerometer"; -const API_START_ACCELEROMETER = "startAccelerometer"; -const API_STOP_ACCELEROMETER = "stopAccelerometer"; -const API_ON_COMPASS = "onCompass"; -const API_OFF_COMPASS = "offCompass"; -const API_START_COMPASS = "startCompass"; -const API_STOP_COMPASS = "stopCompass"; -const API_VIBRATE_SHORT = "vibrateShort"; -const API_VIBRATE_LONG = "vibrateLong"; -const API_GET_STORAGE = "getStorage"; -const GetStorageProtocol = { - key: { - type: String, - required: true +var keyboard = { + name: "Keyboard", + props: { + cursorSpacing: { + type: [Number, String], + default: 0 + }, + showConfirmBar: { + type: [Boolean, String], + default: "auto" + }, + adjustPosition: { + type: Boolean, + default: true + } + }, + watch: { + focus(val) { + if (val && false) { + this.showSoftKeybord(); + } + } + }, + mounted() { + if (this.autoFocus || this.focus) { + this.showSoftKeybord(); + } + }, + beforeDestroy() { + this.onKeyboardHide(); + }, + methods: { + initKeyboard(el) { + el.addEventListener("focus", () => { + this.hideKeyboardTemp = function() { + hideKeyboard$1(); + }; + UniViewJSBridge.subscribe("hideKeyboard", this.hideKeyboardTemp); + document.addEventListener("click", iosHideKeyboard, false); + }); + el.addEventListener("blur", this.onKeyboardHide.bind(this)); + }, + showSoftKeybord() { + plusReady(() => { + plus.key.showSoftKeybord(); + }); + }, + setSoftinputTemporary() { + plusReady(() => { + const currentWebview = plus.webview.currentWebview(); + const style2 = currentWebview.getStyle() || {}; + const rect = this.$el.getBoundingClientRect(); + currentWebview.setSoftinputTemporary && currentWebview.setSoftinputTemporary({ + mode: style2.softinputMode === "adjustResize" ? "adjustResize" : this.adjustPosition ? "adjustPan" : "nothing", + position: { + top: rect.top, + height: rect.height + (Number(this.cursorSpacing) || 0) + } + }); + }); + }, + setSoftinputNavBar() { + if (this.showConfirmBar === "auto") { + delete this.__softinputNavBar; + return; + } + plusReady(() => { + const currentWebview = plus.webview.currentWebview(); + const {softinputNavBar} = currentWebview.getStyle() || {}; + const showConfirmBar = softinputNavBar !== "none"; + if (showConfirmBar !== this.showConfirmBar) { + this.__softinputNavBar = softinputNavBar || "auto"; + currentWebview.setStyle({ + softinputNavBar: this.showConfirmBar ? "auto" : "none" + }); + } else { + delete this.__softinputNavBar; + } + }); + }, + resetSoftinputNavBar() { + const softinputNavBar = this.__softinputNavBar; + if (softinputNavBar) { + plusReady(() => { + const currentWebview = plus.webview.currentWebview(); + currentWebview.setStyle({ + softinputNavBar + }); + }); + } + }, + onKeyboardHide() { + UniViewJSBridge.unsubscribe("hideKeyboard", this.hideKeyboardTemp); + document.removeEventListener("click", iosHideKeyboard, false); + if (String(navigator.vendor).indexOf("Apple") === 0) { + document.documentElement.scrollTo(document.documentElement.scrollLeft, document.documentElement.scrollTop); + } + } } }; -const API_GET_STORAGE_SYNC = "getStorageSync"; -const GetStorageSyncProtocol = [ - { - name: "key", - type: String, - required: true - } -]; -const API_SET_STORAGE = "setStorage"; -const SetStorageProtocol = { - key: { - type: String, - required: true +function throttle(fn, wait) { + let last = 0; + let timeout; + const newFn = function(...arg) { + const now = Date.now(); + clearTimeout(timeout); + const waitCallback = () => { + last = now; + fn.apply(this, arg); + }; + if (now - last < wait) { + timeout = setTimeout(waitCallback, wait - (now - last)); + return; + } + waitCallback(); + }; + newFn.cancel = function() { + clearTimeout(timeout); + }; + return newFn; +} +var baseInput = { + name: "BaseInput", + mixins: [emitter, keyboard], + model: { + prop: "value", + event: "update:value" }, - data: { - required: true - } -}; -const API_SET_STORAGE_SYNC = "setStorageSync"; -const SetStorageSyncProtocol = [ - { - name: "key", - type: String, - required: true + props: { + value: { + type: [String, Number], + default: "" + } }, - { - name: "data", - required: true - } -]; -const API_REMOVE_STORAGE = "removeStorage"; -const RemoveStorageProtocol = GetStorageProtocol; -const RemoveStorageSyncProtocol = GetStorageSyncProtocol; -const API_GET_FILE_INFO = "getFileInfo"; -const GetFileInfoOptions = { - formatArgs: { - filePath(filePath, params) { - params.filePath = getRealPath(filePath); + data() { + return { + valueSync: this._getValueString(this.value) + }; + }, + created() { + const valueChange = this.__valueChange = debounce((val) => { + this.valueSync = this._getValueString(val); + }, 100); + this.$watch("value", valueChange); + this.__triggerInput = throttle(($event, detail) => { + this.$emit("update:value", detail.value); + this.$trigger("input", $event, detail); + }, 100); + this.$triggerInput = ($event, detail) => { + this.__valueChange.cancel(); + this.__triggerInput($event, detail); + }; + }, + beforeDestroy() { + this.__valueChange.cancel(); + this.__triggerInput.cancel(); + }, + methods: { + _getValueString(value) { + return value === null ? "" : String(value); } } }; -const GetFileInfoProtocol = { - filePath: { - type: String, - required: true - } -}; -const API_OPEN_DOCUMENT = "openDocument"; -const OpenDocumentOptions = { - formatArgs: { - filePath(filePath, params) { - params.filePath = getRealPath(filePath); +const _sfc_main$k = { + name: "Audio", + mixins: [subscriber], + props: { + id: { + type: String, + default: "" + }, + src: { + type: String, + default: "" + }, + loop: { + type: [Boolean, String], + default: false + }, + controls: { + type: [Boolean, String], + default: false + }, + poster: { + type: String, + default: "" + }, + name: { + type: String, + default: "" + }, + author: { + type: String, + default: "" } - } -}; -const OpenDocumentProtocol = { - filePath: { - type: String, - required: true }, - fileType: String -}; -const API_HIDE_KEYBOARD = "hideKeyboard"; -const API_GET_LOCATION = "getLocation"; -const coordTypes = ["WGS84", "GCJ02"]; -const GetLocationOptions = { - formatArgs: { - type(value, params) { - value = (value || "").toUpperCase(); - if (coordTypes.indexOf(value) === -1) { - params.type = coordTypes[0]; - } else { - params.type = value; + data() { + return { + playing: false, + currentTime: this.getTime(0) + }; + }, + watch: { + src(val) { + if (this.$refs.audio) { + this.$refs.audio.src = this.$getRealPath(val); } - }, - altitude(value, params) { - params.altitude = value ? value : false; } - } -}; -const GetLocationProtocol = { - type: String, - altitude: Boolean -}; -const API_CHOOSE_IMAGE = "chooseImage"; -const ChooseImageOptions = { - formatArgs: { - count(value, params) { - if (!value || value <= 0) { - params.count = 9; + }, + mounted() { + const audio = this.$refs.audio; + audio.addEventListener("error", ($event) => { + this.playing = false; + this.$trigger("error", $event, {}); + }); + audio.addEventListener("play", ($event) => { + this.playing = true; + this.$trigger("play", $event, {}); + }); + audio.addEventListener("pause", ($event) => { + this.playing = false; + this.$trigger("pause", $event, {}); + }); + audio.addEventListener("ended", ($event) => { + this.playing = false; + this.$trigger("ended", $event, {}); + }); + audio.addEventListener("timeupdate", ($event) => { + var currentTime = audio.currentTime; + this.currentTime = this.getTime(currentTime); + var duration = audio.duration; + this.$trigger("timeupdate", $event, { + currentTime, + duration + }); + }); + audio.src = this.$getRealPath(this.src); + }, + methods: { + _handleSubscribe({ + type, + data = {} + }) { + var audio = this.$refs.audio; + switch (type) { + case "setSrc": + audio.src = this.$getRealPath(data.src); + this.$emit("update:src", data.src); + break; + case "play": + audio.play(); + break; + case "pause": + audio.pause(); + break; + case "seek": + audio.currentTime = data.position; + break; } }, - sizeType(sizeType, params) { - params.sizeType = elemsInArray(sizeType, CHOOSE_SIZE_TYPES); - }, - sourceType(sourceType, params) { - params.sourceType = elemsInArray(sourceType, CHOOSE_SOURCE_TYPES); - }, - extension(extension, params) { - if (extension instanceof Array && extension.length === 0) { - return "param extension should not be empty."; + trigger() { + if (this.playing) { + this.$refs.audio.pause(); + } else { + this.$refs.audio.play(); } - if (!extension) - params.extension = [""]; - } - } -}; -const ChooseImageProtocol = { - count: Number, - sizeType: [Array, String], - sourceType: Array, - extension: Array -}; -const API_CHOOSE_VIDEO = "chooseVideo"; -const ChooseVideoOptions = { - formatArgs: { - sourceType(sourceType, params) { - params.sourceType = elemsInArray(sourceType, CHOOSE_SOURCE_TYPES); }, - compressed: true, - maxDuration: 60, - camera: "back", - extension(extension, params) { - if (extension instanceof Array && extension.length === 0) { - return "param extension should not be empty."; + getTime(time) { + var h = Math.floor(time / 3600); + var m = Math.floor(time % 3600 / 60); + var s = Math.floor(time % 3600 % 60); + h = (h < 10 ? "0" : "") + h; + m = (m < 10 ? "0" : "") + m; + s = (s < 10 ? "0" : "") + s; + var str = m + ":" + s; + if (h !== "00") { + str = h + ":" + str; } - if (!extension) - params.extension = [""]; + return str; } } }; -const ChooseVideoProtocol = { - sourceType: Array, - compressed: Boolean, - maxDuration: Number, - camera: String, - extension: Array +const _hoisted_1$c = {class: "uni-audio-default"}; +const _hoisted_2$7 = {class: "uni-audio-right"}; +const _hoisted_3$3 = {class: "uni-audio-time"}; +const _hoisted_4$3 = {class: "uni-audio-info"}; +const _hoisted_5$2 = {class: "uni-audio-name"}; +const _hoisted_6$2 = {class: "uni-audio-author"}; +function _sfc_render$k(_ctx, _cache, $props, $setup, $data, $options) { + return openBlock(), createBlock("uni-audio", mergeProps({ + id: $props.id, + controls: !!$props.controls + }, _ctx.$attrs), [ + createVNode("audio", { + ref: "audio", + loop: $props.loop, + style: {display: "none"} + }, null, 8, ["loop"]), + createVNode("div", _hoisted_1$c, [ + createVNode("div", { + style: "background-image: url(" + _ctx.$getRealPath($props.poster) + ");", + class: "uni-audio-left" + }, [ + createVNode("div", { + class: [{play: !$data.playing, pause: $data.playing}, "uni-audio-button"], + onClick: _cache[1] || (_cache[1] = (...args) => $options.trigger && $options.trigger(...args)) + }, null, 2) + ], 4), + createVNode("div", _hoisted_2$7, [ + createVNode("div", _hoisted_3$3, toDisplayString($data.currentTime), 1), + createVNode("div", _hoisted_4$3, [ + createVNode("div", _hoisted_5$2, toDisplayString($props.name), 1), + createVNode("div", _hoisted_6$2, toDisplayString($props.author), 1) + ]) + ]) + ]) + ], 16, ["id", "controls"]); +} +_sfc_main$k.render = _sfc_render$k; +const hoverProps = { + hoverClass: { + type: String, + default: "none" + }, + hoverStopPropagation: { + type: Boolean, + default: false + }, + hoverStartTime: { + type: [Number, String], + default: 50 + }, + hoverStayTime: { + type: [Number, String], + default: 400 + } }; -const API_CHOOSE_FILE = "chooseFile"; -const CHOOSE_MEDIA_TYPE = [ - "all", - "image", - "video" -]; -const ChooseFileOptions = { - formatArgs: { - count(count, params) { - if (!count || count <= 0) { - params.count = 100; - } - }, - sourceType(sourceType, params) { - params.sourceType = elemsInArray(sourceType, CHOOSE_SOURCE_TYPES); - }, - type(type, params) { - params.type = elemInArray(type, CHOOSE_MEDIA_TYPE); - }, - extension(extension, params) { - if (extension instanceof Array && extension.length === 0) { - return "param extension should not be empty."; - } - if (!extension) - params.extension = [""]; +function useHover(props2) { + const hovering = ref(false); + let hoverTouch = false; + let hoverStartTimer; + let hoverStayTimer; + function hoverReset() { + requestAnimationFrame(() => { + clearTimeout(hoverStayTimer); + hoverStayTimer = setTimeout(() => { + hovering.value = false; + }, parseInt(props2.hoverStayTime)); + }); + } + function onTouchstartPassive(evt) { + if (evt._hoverPropagationStopped) { + return; } + if (!props2.hoverClass || props2.hoverClass === "none" || props2.disabled) { + return; + } + if (evt.touches.length > 1) { + return; + } + if (props2.hoverStopPropagation) { + evt._hoverPropagationStopped = true; + } + hoverTouch = true; + hoverStartTimer = setTimeout(() => { + hovering.value = true; + if (!hoverTouch) { + hoverReset(); + } + }, parseInt(props2.hoverStartTime)); } -}; -const ChooseFileProtocol = { - count: Number, - sourceType: Array, - type: String, - extension: Array -}; -const API_GET_IMAGE_INFO = "getImageInfo"; -const GetImageInfoOptions = { - formatArgs: { - src(src, params) { - params.src = getRealPath(src); + function onTouchend() { + hoverTouch = false; + if (hovering.value) { + hoverReset(); } } -}; -const GetImageInfoProtocol = { - src: { - type: String, - required: true + function onTouchcancel() { + hoverTouch = false; + hovering.value = false; + clearTimeout(hoverStartTimer); } -}; -const API_GET_VIDEO_INFO = "getVideoInfo"; -const GetVideoInfoOptions = { - formatArgs: { - src(src, params) { - params.src = getRealPath(src); + return { + hovering, + binding: { + onTouchstartPassive, + onTouchend, + onTouchcancel } + }; +} +function useBooleanAttr(props2, keys) { + if (isString(keys)) { + keys = [keys]; } -}; -const GetVideoInfoProtocol = { - src: { - type: String, - required: true + return keys.reduce((res, key) => { + if (props2[key]) { + res[key] = true; + } + return res; + }, Object.create(null)); +} +const uniFormKey = PolySymbol(process.env.NODE_ENV !== "production" ? "uniForm" : "uf"); +var index$7 = /* @__PURE__ */ defineComponent({ + name: "Form", + setup(_props, { + slots, + emit + }) { + provideForm(emit); + return () => createVNode("uni-form", null, [createVNode("span", null, [slots.default && slots.default()])]); } -}; -const API_REQUEST = "request"; -const dataType = { - JSON: "json" -}; -const RESPONSE_TYPE = ["text", "arraybuffer"]; -const DEFAULT_RESPONSE_TYPE = "text"; -const encode = encodeURIComponent; -function stringifyQuery(url, data) { - let str = url.split("#"); - const hash = str[1] || ""; - str = str[0].split("?"); - let query = str[1] || ""; - url = str[0]; - const search = query.split("&").filter((item) => item); - const params = {}; - search.forEach((item) => { - const part = item.split("="); - params[part[0]] = part[1]; - }); - for (const key in data) { - if (hasOwn$1(data, key)) { - let v2 = data[key]; - if (typeof v2 === "undefined" || v2 === null) { - v2 = ""; - } else if (isPlainObject(v2)) { - v2 = JSON.stringify(v2); - } - params[encode(key)] = encode(v2); +}); +function provideForm(emit) { + const fields = []; + provide(uniFormKey, { + addField(field) { + fields.push(field); + }, + removeField(field) { + fields.splice(fields.indexOf(field), 1); + }, + submit() { + emit("submit", { + detail: { + value: fields.reduce((res, field) => { + const [name, value] = field.submit(); + name && (res[name] = value); + return res; + }, Object.create(null)) + } + }); + }, + reset() { + fields.forEach((field) => field.reset()); + emit("reset"); } - } - query = Object.keys(params).map((item) => `${item}=${params[item]}`).join("&"); - return url + (query ? "?" + query : "") + (hash ? "#" + hash : ""); + }); + return fields; } -const RequestProtocol = { - method: String, - data: [Object, String, Array, ArrayBuffer], - url: { - type: String, - required: true - }, - header: Object, - dataType: String, - responseType: String, - withCredentials: Boolean -}; -const RequestOptions = { - formatArgs: { - method(value, params) { - params.method = elemInArray((value || "").toUpperCase(), HTTP_METHODS); +var index$6 = /* @__PURE__ */ defineComponent({ + name: "Button", + props: { + id: { + type: String, + default: "" }, - data(value, params) { - params.data = value || ""; + hoverClass: { + type: String, + default: "button-hover" }, - url(value, params) { - if (params.method === HTTP_METHODS[0] && isPlainObject(params.data) && Object.keys(params.data).length) { - params.url = stringifyQuery(value, params.data); - } + hoverStartTime: { + type: [Number, String], + default: 20 }, - header(value, params) { - const header = params.header = value || {}; - if (params.method !== HTTP_METHODS[0]) { - if (!Object.keys(header).find((key) => key.toLowerCase() === "content-type")) { - header["Content-Type"] = "application/json"; - } - } + hoverStayTime: { + type: [Number, String], + default: 70 }, - dataType(value, params) { - params.dataType = (value || dataType.JSON).toLowerCase(); + hoverStopPropagation: { + type: Boolean, + default: false }, - responseType(value, params) { - params.responseType = (value || "").toLowerCase(); - if (RESPONSE_TYPE.indexOf(params.responseType) === -1) { - params.responseType = DEFAULT_RESPONSE_TYPE; + disabled: { + type: [Boolean, String], + default: false + }, + formType: { + type: String, + default: "" + }, + openType: { + type: String, + default: "" + } + }, + setup(props2, { + slots + }) { + const uniForm = inject(uniFormKey, false); + const { + hovering, + binding + } = useHover(props2); + useI18n(); + function onClick() { + if (props2.disabled) { + return; + } + const formType = props2.formType; + if (formType) { + if (!uniForm) { + return; + } + if (formType === "submit") { + uniForm.submit(); + } else if (formType === "reset") { + uniForm.reset(); + } + return; } } + return () => { + const hoverClass = props2.hoverClass; + const booleanAttrs = useBooleanAttr(props2, "disabled"); + if (hoverClass && hoverClass !== "none") { + return createVNode("uni-button", mergeProps({ + onClick, + class: hovering.value ? hoverClass : "" + }, binding, booleanAttrs), [slots.default && slots.default()], 16, ["onClick"]); + } + return createVNode("uni-button", mergeProps({ + onClick + }, booleanAttrs), [slots.default && slots.default()], 16, ["onClick"]); + }; } -}; -const API_DOWNLOAD_FILE = "downloadFile"; -const DownloadFileOptions = { - formatArgs: { - header(value, params) { - params.header = value || {}; - } +}); +const pixelRatio = /* @__PURE__ */ function() { + const canvas = document.createElement("canvas"); + canvas.height = canvas.width = 0; + const context = canvas.getContext("2d"); + const backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; + return (window.devicePixelRatio || 1) / backingStore; +}(); +function wrapper(canvas) { + canvas.width = canvas.offsetWidth * pixelRatio; + canvas.height = canvas.offsetHeight * pixelRatio; + canvas.getContext("2d").__hidpi__ = true; +} +function resolveColor(color) { + color = color.slice(0); + color[3] = color[3] / 255; + return "rgba(" + color.join(",") + ")"; +} +function processTouches(target, touches) { + return [].map.call(touches, (touch) => { + var boundingClientRect = target.getBoundingClientRect(); + return { + identifier: touch.identifier, + x: touch.clientX - boundingClientRect.left, + y: touch.clientY - boundingClientRect.top + }; + }); +} +var tempCanvas; +function getTempCanvas(width = 0, height = 0) { + if (!tempCanvas) { + tempCanvas = document.createElement("canvas"); } -}; -const DownloadFileProtocol = { - url: { - type: String, - required: true + tempCanvas.width = width; + tempCanvas.height = height; + return tempCanvas; +} +const _sfc_main$j = { + name: "Canvas", + mixins: [subscriber], + props: { + canvasId: { + type: String, + default: "" + }, + disableScroll: { + type: [Boolean, String], + default: false + } }, - header: Object, - timeout: Number -}; -const API_UPLOAD_FILE = "uploadFile"; -const UploadFileOptions = { - formatArgs: { - filePath(filePath, params) { - if (filePath) { - params.filePath = getRealPath(filePath); + data() { + return { + actionsWaiting: false + }; + }, + computed: { + id() { + return this.canvasId; + }, + _listeners() { + var $listeners = Object.assign({}, this.$listeners); + var events = ["touchstart", "touchmove", "touchend"]; + events.forEach((event2) => { + var existing = $listeners[event2]; + var eventHandler = []; + if (existing) { + eventHandler.push(($event) => { + this.$trigger(event2, Object.assign({}, $event, { + touches: processTouches($event.currentTarget, $event.touches), + changedTouches: processTouches($event.currentTarget, $event.changedTouches) + })); + }); + } + if (this.disableScroll && event2 === "touchmove") { + eventHandler.push(this._touchmove); + } + $listeners[event2] = eventHandler; + }); + return $listeners; + } + }, + created() { + this._actionsDefer = []; + this._images = {}; + }, + mounted() { + this._resize({ + width: this.$refs.sensor.$el.offsetWidth, + height: this.$refs.sensor.$el.offsetHeight + }); + }, + beforeDestroy() { + const canvas = this.$refs.canvas; + canvas.height = canvas.width = 0; + }, + methods: { + _handleSubscribe({ + type, + data = {} + }) { + var method = this[type]; + if (type.indexOf("_") !== 0 && typeof method === "function") { + method(data); + } + }, + _resize() { + var canvas = this.$refs.canvas; + if (canvas.width > 0 && canvas.height > 0) { + var context = canvas.getContext("2d"); + var imageData = context.getImageData(0, 0, canvas.width, canvas.height); + wrapper(this.$refs.canvas); + context.putImageData(imageData, 0, 0); + } else { + wrapper(this.$refs.canvas); } }, - header(value, params) { - params.header = value || {}; - }, - formData(value, params) { - params.formData = value || {}; - } - } -}; -const UploadFileProtocol = { - url: { - type: String, - required: true - }, - files: Array, - filePath: String, - name: String, - header: Object, - formData: Object, - timeout: Number -}; -const API_CONNECT_SOCKET = "connectSocket"; -const ConnectSocketOptions = { - formatArgs: { - header(value, params) { - params.header = value || {}; - }, - method(value, params) { - params.method = elemInArray((value || "").toUpperCase(), HTTP_METHODS); + _touchmove(event2) { + event2.preventDefault(); }, - protocols(protocols, params) { - if (typeof protocols === "string") { - params.protocols = [protocols]; + actionsChanged({ + actions, + reserve, + callbackId + }) { + var self = this; + if (!actions) { + return; } - } - } -}; -const ConnectSocketProtocol = { - url: { - type: String, - required: true - }, - header: { - type: Object - }, - method: String, - protocols: [Array, String] -}; -const API_SEND_SOCKET_MESSAGE = "sendSocketMessage"; -const SendSocketMessageProtocol = { - data: [String, ArrayBuffer] -}; -const API_CLOSE_SOCKET = "closeSocket"; -const CloseSocketProtocol = { - code: Number, - reason: String -}; -function encodeQueryString(url) { - if (typeof url !== "string") { - return url; - } - const index2 = url.indexOf("?"); - if (index2 === -1) { - return url; - } - const query = url.substr(index2 + 1).trim().replace(/^(\?|#|&)/, ""); - if (!query) { - return url; - } - url = url.substr(0, index2); - const params = []; - query.split("&").forEach((param) => { - const parts = param.replace(/\+/g, " ").split("="); - const key = parts.shift(); - const val = parts.length > 0 ? parts.join("=") : ""; - params.push(key + "=" + encodeURIComponent(val)); - }); - return params.length ? url + "?" + params.join("&") : url; -} -const ANIMATION_IN = [ - "slide-in-right", - "slide-in-left", - "slide-in-top", - "slide-in-bottom", - "fade-in", - "zoom-out", - "zoom-fade-out", - "pop-in", - "none" -]; -const ANIMATION_OUT = [ - "slide-out-right", - "slide-out-left", - "slide-out-top", - "slide-out-bottom", - "fade-out", - "zoom-in", - "zoom-fade-in", - "pop-out", - "none" -]; -const BaseRouteProtocol = { - url: { - type: String, - required: true - } -}; -const API_NAVIGATE_TO = "navigateTo"; -const API_REDIRECT_TO = "redirectTo"; -const API_RE_LAUNCH = "reLaunch"; -const API_SWITCH_TAB = "switchTab"; -const API_NAVIGATE_BACK = "navigateBack"; -const API_PRELOAD_PAGE = "preloadPage"; -const API_UN_PRELOAD_PAGE = "unPreloadPage"; -const NavigateToProtocol = /* @__PURE__ */ extend({}, BaseRouteProtocol, createAnimationProtocol(ANIMATION_IN)); -const NavigateBackProtocol = /* @__PURE__ */ extend({ - delta: { - type: Number - } -}, createAnimationProtocol(ANIMATION_OUT)); -const RedirectToProtocol = BaseRouteProtocol; -const ReLaunchProtocol = BaseRouteProtocol; -const SwitchTabProtocol = BaseRouteProtocol; -const NavigateToOptions = /* @__PURE__ */ createRouteOptions(API_NAVIGATE_TO); -const RedirectToOptions = /* @__PURE__ */ createRouteOptions(API_REDIRECT_TO); -const ReLaunchOptions = /* @__PURE__ */ createRouteOptions(API_RE_LAUNCH); -const SwitchTabOptions = /* @__PURE__ */ createRouteOptions(API_SWITCH_TAB); -const NavigateBackOptions = { - formatArgs: { - delta(value, params) { - value = parseInt(value + "") || 1; - params.delta = Math.min(getCurrentPages().length - 1, value); - } - } -}; -function createAnimationProtocol(animationTypes) { - return { - animationType: { - type: String, - validator(type) { - if (type && animationTypes.indexOf(type) === -1) { - return "`" + type + "` is not supported for `animationType` (supported values are: `" + animationTypes.join("`|`") + "`)"; + if (this.actionsWaiting) { + this._actionsDefer.push([actions, reserve, callbackId]); + return; + } + var canvas = this.$refs.canvas; + var c2d = canvas.getContext("2d"); + if (!reserve) { + c2d.fillStyle = "#000000"; + c2d.strokeStyle = "#000000"; + c2d.shadowColor = "#000000"; + c2d.shadowBlur = 0; + c2d.shadowOffsetX = 0; + c2d.shadowOffsetY = 0; + c2d.setTransform(1, 0, 0, 1, 0, 0); + c2d.clearRect(0, 0, canvas.width, canvas.height); + } + this.preloadImage(actions); + for (let index2 = 0; index2 < actions.length; index2++) { + const action = actions[index2]; + let method = action.method; + const data = action.data; + if (/^set/.test(method) && method !== "setTransform") { + const method1 = method[3].toLowerCase() + method.slice(4); + let color; + if (method1 === "fillStyle" || method1 === "strokeStyle") { + if (data[0] === "normal") { + color = resolveColor(data[1]); + } else if (data[0] === "linear") { + const LinearGradient = c2d.createLinearGradient(...data[1]); + data[2].forEach(function(data2) { + const offset = data2[0]; + const color2 = resolveColor(data2[1]); + LinearGradient.addColorStop(offset, color2); + }); + color = LinearGradient; + } else if (data[0] === "radial") { + const x = data[1][0]; + const y = data[1][1]; + const r = data[1][2]; + const LinearGradient = c2d.createRadialGradient(x, y, 0, x, y, r); + data[2].forEach(function(data2) { + const offset = data2[0]; + const color2 = resolveColor(data2[1]); + LinearGradient.addColorStop(offset, color2); + }); + color = LinearGradient; + } else if (data[0] === "pattern") { + const loaded = this.checkImageLoaded(data[1], actions.slice(index2 + 1), callbackId, function(image2) { + if (image2) { + c2d[method1] = c2d.createPattern(image2, data[2]); + } + }); + if (!loaded) { + break; + } + continue; + } + c2d[method1] = color; + } else if (method1 === "globalAlpha") { + c2d[method1] = data[0] / 255; + } else if (method1 === "shadow") { + var _ = ["shadowOffsetX", "shadowOffsetY", "shadowBlur", "shadowColor"]; + data.forEach(function(color_, method_) { + c2d[_[method_]] = _[method_] === "shadowColor" ? resolveColor(color_) : color_; + }); + } else { + if (method1 === "fontSize") { + c2d.font = c2d.font.replace(/\d+\.?\d*px/, data[0] + "px"); + } else { + if (method1 === "lineDash") { + c2d.setLineDash(data[0]); + c2d.lineDashOffset = data[1] || 0; + } else { + if (method1 === "textBaseline") { + if (data[0] === "normal") { + data[0] = "alphabetic"; + } + c2d[method1] = data[0]; + } else { + c2d[method1] = data[0]; + } + } + } + } + } else if (method === "fillPath" || method === "strokePath") { + method = method.replace(/Path/, ""); + c2d.beginPath(); + data.forEach(function(data_) { + c2d[data_.method].apply(c2d, data_.data); + }); + c2d[method](); + } else if (method === "fillText") { + c2d.fillText.apply(c2d, data); + } else if (method === "drawImage") { + var A = function() { + var dataArray = [...data]; + var url = dataArray[0]; + var otherData = dataArray.slice(1); + self._images = self._images || {}; + if (!self.checkImageLoaded(url, actions.slice(index2 + 1), callbackId, function(image2) { + if (image2) { + c2d.drawImage.apply(c2d, [image2].concat([...otherData.slice(4, 8)], [...otherData.slice(0, 4)])); + } + })) + return "break"; + }(); + if (A === "break") { + break; + } + } else { + if (method === "clip") { + data.forEach(function(data_) { + c2d[data_.method].apply(c2d, data_.data); + }); + c2d.clip(); + } else { + c2d[method].apply(c2d, data); + } } } - }, - animationDuration: { - type: Number - } - }; -} -let navigatorLock; -function beforeRoute() { - navigatorLock = ""; -} -function createRouteOptions(type) { - return { - formatArgs: { - url: createNormalizeUrl(type) - }, - beforeAll: beforeRoute - }; -} -function createNormalizeUrl(type) { - return function normalizeUrl(url, params) { - if (!url) { - return `Missing required args: "url"`; - } - url = getRealRoute(url); - const pagePath = url.split("?")[0]; - const routeOptions = __uniRoutes.find(({path, alias}) => path === pagePath || alias === pagePath); - if (!routeOptions) { - return "page `" + url + "` is not found"; - } - if (type === API_NAVIGATE_TO || type === API_REDIRECT_TO) { - if (routeOptions.meta.isTabBar) { - return `can not ${type} a tabbar page`; - } - } else if (type === API_SWITCH_TAB) { - if (!routeOptions.meta.isTabBar) { - return "can not switch to no-tabBar page"; + if (!this.actionsWaiting && callbackId) { + UniViewJSBridge.publishHandler("onDrawCanvas", { + callbackId, + data: { + errMsg: "drawCanvas:ok" + } + }, this.$page.id); } - } - if ((type === API_SWITCH_TAB || type === API_PRELOAD_PAGE) && routeOptions.meta.isTabBar && params.openType !== "appLaunch") { - url = pagePath; - } - if (routeOptions.meta.isEntry) { - url = url.replace(routeOptions.alias, "/"); - } - params.url = encodeQueryString(url); - if (type === API_UN_PRELOAD_PAGE) { - return; - } else if (type === API_PRELOAD_PAGE) { - if (routeOptions.meta.isTabBar) { - const pages = getCurrentPages(true); - const tabBarPagePath = routeOptions.path.substr(1); - if (pages.find((page) => page.route === tabBarPagePath)) { - return "tabBar page `" + tabBarPagePath + "` already exists"; + }, + preloadImage: function(actions) { + var self = this; + actions.forEach(function(action) { + var method = action.method; + var data = action.data; + var src = ""; + if (method === "drawImage") { + src = data[0]; + src = self.$getRealPath(src); + data[0] = src; + } else if (method === "setFillStyle" && data[0] === "pattern") { + src = data[1]; + src = self.$getRealPath(src); + data[1] = src; } - } - return; - } - if (navigatorLock === url && params.openType !== "appLaunch") { - return `${navigatorLock} locked`; - } - if (__uniConfig.ready) { - navigatorLock = url; - } - }; -} -const API_LOAD_FONT_FACE = "loadFontFace"; -const LoadFontFaceProtocol = { - family: { - type: String, - required: true - }, - source: { - type: String, - required: true - }, - desc: Object -}; -const API_PAGE_SCROLL_TO = "pageScrollTo"; -const PageScrollToProtocol = { - scrollTop: Number, - selector: String, - duration: Number -}; -const DEFAULT_DURATION = 300; -const PageScrollToOptions = { - formatArgs: { - duration(value, params) { - params.duration = Math.max(0, parseInt(value + "") || DEFAULT_DURATION); - } - } -}; -const FRONT_COLORS = ["#ffffff", "#000000"]; -const API_SET_NAVIGATION_BAR_COLOR = "setNavigationBarColor"; -const SetNavigationBarColorOptions = { - formatArgs: { - animation(animation, params) { - if (!animation) { - animation = {duration: 0, timingFunc: "linear"}; - } - params.animation = { - duration: animation.duration || 0, - timingFunc: animation.timingFunc || "linear" - }; - } - } -}; -const SetNavigationBarColorProtocol = { - frontColor: { - type: String, - required: true, - validator(frontColor) { - if (FRONT_COLORS.indexOf(frontColor) === -1) { - return `invalid frontColor "${frontColor}"`; - } - } - }, - backgroundColor: { - type: String, - required: true - }, - animation: Object -}; -const API_SET_NAVIGATION_BAR_TITLE = "setNavigationBarTitle"; -const SetNavigationBarTitleProtocol = { - title: { - type: String, - required: true - } -}; -const API_SHOW_NAVIGATION_BAR_LOADING = "showNavigationBarLoading"; -const API_HIDE_NAVIGATION_BAR_LOADING = "hideNavigationBarLoading"; -const PRIMARY_COLOR = "#007aff"; -const API_SHOW_MODAL = "showModal"; -const ShowModalProtocol = { - title: String, - content: String, - showCancel: Boolean, - cancelText: String, - cancelColor: String, - confirmText: String, - confirmColor: String -}; -const ShowModalOptions = { - 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"); - } + if (src && !self._images[src]) { + loadImage(); + } + function loadImage() { + self._images[src] = new Image(); + self._images[src].onload = function() { + self._images[src].ready = true; + }; + function loadBlob(blob) { + self._images[src].src = (window.URL || window.webkitURL).createObjectURL(blob); + } + function loadFile(path) { + var bitmap = new plus.nativeObj.Bitmap("bitmap" + Date.now()); + bitmap.load(path, function() { + self._images[src].src = bitmap.toBase64Data(); + bitmap.clear(); + }, function() { + bitmap.clear(); + console.error("preloadImage error"); + }); + } + function loadUrl(url) { + function plusDownload() { + plus.downloader.createDownload(url, { + filename: "_doc/uniapp_temp/download/" + }, function(d, status) { + if (status === 200) { + loadFile(d.filename); + } else { + self._images[src].src = src; + } + }).start(); + } + var xhr = new XMLHttpRequest(); + xhr.open("GET", url, true); + xhr.responseType = "blob"; + xhr.onload = function() { + if (this.status === 200) { + loadBlob(this.response); + } + }; + xhr.onerror = window.plus ? plusDownload : function() { + self._images[src].src = src; + }; + xhr.send(); + } + if (window.plus && (!window.webkit || !window.webkit.messageHandlers)) { + self._images[src].src = src; + } else { + if (window.plus && src.indexOf("http://") !== 0 && src.indexOf("https://") !== 0 && !/^data:.*,.*/.test(src)) { + loadFile(src); + } else if (/^data:.*,.*/.test(src)) { + self._images[src].src = src; + } else { + loadUrl(src); + } + } + } + }); }, - cancelColor: "#000", - confirmText(_value, params) { - if (!hasOwn$1(params, "confirmText")) { - const {t: t2} = useI18n(); - params.confirmText = t2("uni.showModal.confirm"); + checkImageLoaded: function(src, actions, callbackId, fn) { + var self = this; + var image2 = this._images[src]; + if (image2.ready) { + fn(image2); + return true; + } else { + this._actionsDefer.unshift([actions, true]); + this.actionsWaiting = true; + image2.onload = function() { + image2.ready = true; + fn(image2); + self.actionsWaiting = false; + var actions2 = self._actionsDefer.slice(0); + self._actionsDefer = []; + for (var action = actions2.shift(); action; ) { + self.actionsChanged({ + actions: action[0], + reserve: action[1], + callbackId + }); + action = actions2.shift(); + } + }; + return false; } }, - confirmColor: PRIMARY_COLOR - } -}; -const API_SHOW_TOAST = "showToast"; -const ShowToastProtocol = { - title: String, - icon: String, - image: String, - duration: Number, - mask: Boolean -}; -const ShowToastOptions = { - formatArgs: { - title: "", - icon(value, params) { - if (["success", "loading", "none"].indexOf(value) === -1) { - params.icon = "success"; + getImageData({ + x = 0, + y = 0, + width, + height, + destWidth, + destHeight, + hidpi = true, + callbackId + }) { + var imgData; + var canvas = this.$refs.canvas; + if (!width) { + width = canvas.offsetWidth - x; } - }, - image(value, params) { - if (value) { - params.image = getRealPath(value); + if (!height) { + height = canvas.offsetHeight - y; } - }, - duration: 1500, - mask: false - } -}; -const API_SHOW_LOADING = "showLoading"; -const ShowLoadingProtocol = { - title: String, - mask: Boolean -}; -const ShowLoadingOptions = { - formatArgs: { - title: "", - mask: false - } -}; -const API_SHOW_ACTION_SHEET = "showActionSheet"; -const ShowActionSheetProtocol = { - itemList: { - type: Array, - required: true - }, - itemColor: String -}; -const ShowActionSheetOptions = { - formatArgs: { - itemColor: "#000" - } -}; -const API_HIDE_TOAST = "hideToast"; -const API_HIDE_LOADING = "hideLoading"; -const API_START_PULL_DOWN_REFRESH = "startPullDownRefresh"; -const API_STOP_PULL_DOWN_REFRESH = "stopPullDownRefresh"; -const IndexProtocol = { - index: { - type: Number, - required: true - } -}; -const IndexOptions = { - beforeInvoke() { - const pageMeta = getCurrentPageMeta(); - if (pageMeta && !pageMeta.isTabBar) { - return "not TabBar page"; - } - }, - formatArgs: { - index(value) { - if (!__uniConfig.tabBar.list[value]) { - return "tabbar item not found"; + try { + if (!hidpi) { + if (!destWidth && !destHeight) { + destWidth = Math.round(width * pixelRatio); + destHeight = Math.round(height * pixelRatio); + } else if (!destWidth) { + destWidth = Math.round(width / height * destHeight); + } else if (!destHeight) { + destHeight = Math.round(height / width * destWidth); + } + } else { + destWidth = width; + destHeight = height; + } + const newCanvas = getTempCanvas(destWidth, destHeight); + const context = newCanvas.getContext("2d"); + context.__hidpi__ = true; + context.drawImageByCanvas(canvas, x, y, width, height, 0, 0, destWidth, destHeight, false); + imgData = context.getImageData(0, 0, destWidth, destHeight); + newCanvas.height = newCanvas.width = 0; + context.__hidpi__ = false; + } catch (error) { + if (!callbackId) { + return; + } + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: "canvasGetImageData:fail" + } + }, this.$page.id); + return; } - } - } -}; -const API_SET_TAB_BAR_ITEM = "setTabBarItem"; -const SetTabBarItemProtocol = /* @__PURE__ */ extend({ - text: String, - iconPath: String, - selectedIconPath: String, - pagePath: String -}, IndexProtocol); -const SetTabBarItemOptions = { - beforeInvoke: IndexOptions.beforeInvoke, - formatArgs: /* @__PURE__ */ extend({ - pagePath(value, params) { - if (value) { - params.pagePath = removeLeadingSlash(value); + if (!callbackId) { + return { + data: Array.prototype.slice.call(imgData.data), + width: destWidth, + height: destHeight + }; + } else { + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: "canvasGetImageData:ok", + data: [...imgData.data], + width: destWidth, + height: destHeight + } + }, this.$page.id); } - } - }, IndexOptions.formatArgs) -}; -const API_SET_TAB_BAR_STYLE = "setTabBarStyle"; -const SetTabBarStyleProtocol = { - color: String, - selectedColor: String, - backgroundColor: String, - backgroundImage: String, - backgroundRepeat: String, - borderStyle: String -}; -const GRADIENT_RE = /^(linear|radial)-gradient\(.+?\);?$/; -const SetTabBarStyleOptions = { - beforeInvoke: IndexOptions.beforeInvoke, - formatArgs: { - backgroundImage(value, params) { - if (value && !GRADIENT_RE.test(value)) { - params.backgroundImage = getRealPath(value); + }, + putImageData({ + data, + x, + y, + width, + height, + callbackId + }) { + try { + if (!height) { + height = Math.round(data.length / 4 / width); + } + const canvas = getTempCanvas(width, height); + const context = canvas.getContext("2d"); + context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0); + this.$refs.canvas.getContext("2d").drawImage(canvas, x, y, width, height); + canvas.height = canvas.width = 0; + } catch (error) { + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: "canvasPutImageData:fail" + } + }, this.$page.id); + return; } + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: "canvasPutImageData:ok" + } + }, this.$page.id); }, - borderStyle(value, params) { - if (value) { - params.borderStyle = value === "white" ? "white" : "black"; + getDataUrl({ + x = 0, + y = 0, + width, + height, + destWidth, + destHeight, + hidpi = true, + fileType, + qualit, + callbackId + }) { + const res = this.getImageData({ + x, + y, + width, + height, + destWidth, + destHeight, + hidpi + }); + if (!res.data || !res.data.length) { + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: "canvasGetDataUrl:fail" + } + }, this.$page.id); + return; } - } - } -}; -const API_HIDE_TAB_BAR = "hideTabBar"; -const HideTabBarProtocol = { - animation: Boolean -}; -const API_SHOW_TAB_BAR = "showTabBar"; -const ShowTabBarProtocol = HideTabBarProtocol; -const API_HIDE_TAB_BAR_RED_DOT = "hideTabBarRedDot"; -const HideTabBarRedDotProtocol = IndexProtocol; -const HideTabBarRedDotOptions = IndexOptions; -const API_SHOW_TAB_BAR_RED_DOT = "showTabBarRedDot"; -const ShowTabBarRedDotProtocol = IndexProtocol; -const ShowTabBarRedDotOptions = IndexOptions; -const API_REMOVE_TAB_BAR_BADGE = "removeTabBarBadge"; -const RemoveTabBarBadgeProtocol = IndexProtocol; -const RemoveTabBarBadgeOptions = IndexOptions; -const API_SET_TAB_BAR_BADGE = "setTabBarBadge"; -const SetTabBarBadgeProtocol = /* @__PURE__ */ extend({ - text: { - type: String, - required: true - } -}, IndexProtocol); -const SetTabBarBadgeOptions = { - beforeInvoke: IndexOptions.beforeInvoke, - formatArgs: /* @__PURE__ */ extend({ - text(value, params) { - if (getLen(value) >= 4) { - params.text = "..."; + let imgData; + try { + imgData = new ImageData(new Uint8ClampedArray(res.data), res.width, res.height); + } catch (error) { + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: "canvasGetDataUrl:fail" + } + }, this.$page.id); + return; } - } - }, IndexOptions.formatArgs) -}; -const initIntersectionObserverPolyfill = function() { - if (typeof window !== "object") { - return; - } - if ("IntersectionObserver" in window && "IntersectionObserverEntry" in window && "intersectionRatio" in window.IntersectionObserverEntry.prototype) { - if (!("isIntersecting" in window.IntersectionObserverEntry.prototype)) { - Object.defineProperty(window.IntersectionObserverEntry.prototype, "isIntersecting", { - get: function() { - return this.intersectionRatio > 0; + destWidth = res.width; + destHeight = res.height; + const canvas = getTempCanvas(destWidth, destHeight); + const c2d = canvas.getContext("2d"); + c2d.putImageData(imgData, 0, 0); + let base64 = canvas.toDataURL("image/png"); + canvas.height = canvas.width = 0; + const img = new Image(); + img.onload = () => { + const canvas2 = getTempCanvas(destWidth, destHeight); + if (fileType === "jpeg" || fileType === "jpg") { + fileType = "jpeg"; + c2d.fillStyle = "#fff"; + c2d.fillRect(0, 0, destWidth, destHeight); } - }); - } - return; - } - function getFrameElement(doc) { - try { - return doc.defaultView && doc.defaultView.frameElement || null; - } catch (e2) { - return null; - } - } - var document2 = function(startDoc) { - var doc = startDoc; - var frame = getFrameElement(doc); - while (frame) { - doc = frame.ownerDocument; - frame = getFrameElement(doc); - } - return doc; - }(window.document); - var registry = []; - var crossOriginUpdater = null; - var crossOriginRect = null; - function IntersectionObserverEntry(entry) { - this.time = entry.time; - this.target = entry.target; - this.rootBounds = ensureDOMRect(entry.rootBounds); - this.boundingClientRect = ensureDOMRect(entry.boundingClientRect); - this.intersectionRect = ensureDOMRect(entry.intersectionRect || getEmptyRect()); - this.isIntersecting = !!entry.intersectionRect; - var targetRect = this.boundingClientRect; - var targetArea = targetRect.width * targetRect.height; - var intersectionRect = this.intersectionRect; - var intersectionArea = intersectionRect.width * intersectionRect.height; - if (targetArea) { - this.intersectionRatio = Number((intersectionArea / targetArea).toFixed(4)); - } else { - this.intersectionRatio = this.isIntersecting ? 1 : 0; + c2d.drawImage(img, 0, 0); + base64 = canvas2.toDataURL(`image/${fileType}`, qualit); + canvas2.height = canvas2.width = 0; + UniViewJSBridge.publishHandler("onCanvasMethodCallback", { + callbackId, + data: { + errMsg: "canvasGetDataUrl:ok", + base64 + } + }, this.$page.id); + }; + img.src = base64; } } - function IntersectionObserver2(callback, opt_options) { - var options = opt_options || {}; - if (typeof callback != "function") { - throw new Error("callback must be a function"); - } - if (options.root && options.root.nodeType != 1 && options.root.nodeType != 9) { - throw new Error("root must be a Document or Element"); +}; +const _hoisted_1$b = { + ref: "canvas", + width: "300", + height: "150" +}; +const _hoisted_2$6 = {style: {position: "absolute", top: "0", left: "0", width: "100%", height: "100%", overflow: "hidden"}}; +function _sfc_render$j(_ctx, _cache, $props, $setup, $data, $options) { + const _component_v_uni_resize_sensor = resolveComponent("v-uni-resize-sensor"); + return openBlock(), createBlock("uni-canvas", mergeProps({ + "canvas-id": $props.canvasId, + "disable-scroll": $props.disableScroll + }, toHandlers($options._listeners)), [ + createVNode("canvas", _hoisted_1$b, null, 512), + createVNode("div", _hoisted_2$6, [ + renderSlot(_ctx.$slots, "default") + ]), + createVNode(_component_v_uni_resize_sensor, { + ref: "sensor", + onResize: $options._resize + }, null, 8, ["onResize"]) + ], 16, ["canvas-id", "disable-scroll"]); +} +_sfc_main$j.render = _sfc_render$j; +const _sfc_main$i = { + name: "Checkbox", + mixins: [emitter, listeners], + props: { + checked: { + type: [Boolean, String], + default: false + }, + id: { + type: String, + default: "" + }, + disabled: { + type: [Boolean, String], + default: false + }, + color: { + type: String, + default: "#007aff" + }, + value: { + type: String, + default: "" } - this._checkForIntersections = throttle2(this._checkForIntersections.bind(this), this.THROTTLE_TIMEOUT); - this._callback = callback; - this._observationTargets = []; - this._queuedEntries = []; - this._rootMarginValues = this._parseRootMargin(options.rootMargin); - this.thresholds = this._initThresholds(options.threshold); - this.root = options.root || null; - this.rootMargin = this._rootMarginValues.map(function(margin) { - return margin.value + margin.unit; - }).join(" "); - this._monitoringDocuments = []; - this._monitoringUnsubscribes = []; - } - IntersectionObserver2.prototype.THROTTLE_TIMEOUT = 100; - IntersectionObserver2.prototype.POLL_INTERVAL = null; - IntersectionObserver2.prototype.USE_MUTATION_OBSERVER = true; - IntersectionObserver2._setupCrossOriginUpdater = function() { - if (!crossOriginUpdater) { - crossOriginUpdater = function(boundingClientRect, intersectionRect) { - if (!boundingClientRect || !intersectionRect) { - crossOriginRect = getEmptyRect(); - } else { - crossOriginRect = convertFromParentRect(boundingClientRect, intersectionRect); - } - registry.forEach(function(observer) { - observer._checkForIntersections(); - }); - }; + }, + data() { + return { + checkboxChecked: this.checked, + checkboxValue: this.value + }; + }, + watch: { + checked(val) { + this.checkboxChecked = val; + }, + value(val) { + this.checkboxValue = val; } - return crossOriginUpdater; - }; - IntersectionObserver2._resetCrossOriginUpdater = function() { - crossOriginUpdater = null; - crossOriginRect = null; - }; - IntersectionObserver2.prototype.observe = function(target) { - var isTargetAlreadyObserved = this._observationTargets.some(function(item) { - return item.element == target; + }, + listeners: { + "label-click": "_onClick", + "@label-click": "_onClick" + }, + created() { + this.$dispatch("CheckboxGroup", "uni-checkbox-group-update", { + type: "add", + vm: this }); - if (isTargetAlreadyObserved) { - return; - } - if (!(target && target.nodeType == 1)) { - throw new Error("target must be an Element"); - } - this._registerInstance(); - this._observationTargets.push({element: target, entry: null}); - this._monitorIntersections(target.ownerDocument); - this._checkForIntersections(); - }; - IntersectionObserver2.prototype.unobserve = function(target) { - this._observationTargets = this._observationTargets.filter(function(item) { - return item.element != target; + this.$dispatch("Form", "uni-form-group-update", { + type: "add", + vm: this + }); + }, + beforeDestroy() { + this.$dispatch("CheckboxGroup", "uni-checkbox-group-update", { + type: "remove", + vm: this }); - this._unmonitorIntersections(target.ownerDocument); - if (this._observationTargets.length == 0) { - this._unregisterInstance(); - } - }; - IntersectionObserver2.prototype.disconnect = function() { - this._observationTargets = []; - this._unmonitorAllIntersections(); - this._unregisterInstance(); - }; - IntersectionObserver2.prototype.takeRecords = function() { - var records = this._queuedEntries.slice(); - this._queuedEntries = []; - return records; - }; - IntersectionObserver2.prototype._initThresholds = function(opt_threshold) { - var threshold = opt_threshold || [0]; - if (!Array.isArray(threshold)) - threshold = [threshold]; - return threshold.sort().filter(function(t2, i2, a2) { - if (typeof t2 != "number" || isNaN(t2) || t2 < 0 || t2 > 1) { - throw new Error("threshold must be a number between 0 and 1 inclusively"); - } - return t2 !== a2[i2 - 1]; + this.$dispatch("Form", "uni-form-group-update", { + type: "remove", + vm: this }); - }; - IntersectionObserver2.prototype._parseRootMargin = function(opt_rootMargin) { - var marginString = opt_rootMargin || "0px"; - var margins = marginString.split(/\s+/).map(function(margin) { - var parts = /^(-?\d*\.?\d+)(px|%)$/.exec(margin); - if (!parts) { - throw new Error("rootMargin must be specified in pixels or percent"); + }, + methods: { + _onClick($event) { + if (this.disabled) { + return; } - return {value: parseFloat(parts[1]), unit: parts[2]}; - }); - margins[1] = margins[1] || margins[0]; - margins[2] = margins[2] || margins[0]; - margins[3] = margins[3] || margins[1]; - return margins; - }; - IntersectionObserver2.prototype._monitorIntersections = function(doc) { - var win = doc.defaultView; - if (!win) { - return; - } - if (this._monitoringDocuments.indexOf(doc) != -1) { - return; + this.checkboxChecked = !this.checkboxChecked; + this.$dispatch("CheckboxGroup", "uni-checkbox-change", $event); + }, + _resetFormData() { + this.checkboxChecked = false; } - var callback = this._checkForIntersections; - var monitoringInterval = null; - var domObserver = null; - if (this.POLL_INTERVAL) { - monitoringInterval = win.setInterval(callback, this.POLL_INTERVAL); - } else { - addEvent(win, "resize", callback, true); - addEvent(doc, "scroll", callback, true); - if (this.USE_MUTATION_OBSERVER && "MutationObserver" in win) { - domObserver = new win.MutationObserver(callback); - domObserver.observe(doc, { - attributes: true, - childList: true, - characterData: true, - subtree: true - }); - } + } +}; +const _hoisted_1$a = {class: "uni-checkbox-wrapper"}; +function _sfc_render$i(_ctx, _cache, $props, $setup, $data, $options) { + return openBlock(), createBlock("uni-checkbox", mergeProps({disabled: $props.disabled}, _ctx.$attrs, { + onClick: _cache[1] || (_cache[1] = (...args) => $options._onClick && $options._onClick(...args)) + }), [ + createVNode("div", _hoisted_1$a, [ + createVNode("div", { + class: [[$data.checkboxChecked ? "uni-checkbox-input-checked" : ""], "uni-checkbox-input"], + style: {color: $props.color} + }, null, 6), + renderSlot(_ctx.$slots, "default") + ]) + ], 16, ["disabled"]); +} +_sfc_main$i.render = _sfc_render$i; +const _sfc_main$h = { + name: "CheckboxGroup", + mixins: [emitter, listeners], + props: { + name: { + type: String, + default: "" } - this._monitoringDocuments.push(doc); - this._monitoringUnsubscribes.push(function() { - var win2 = doc.defaultView; - if (win2) { - if (monitoringInterval) { - win2.clearInterval(monitoringInterval); + }, + data() { + return { + checkboxList: [] + }; + }, + listeners: { + "@checkbox-change": "_changeHandler", + "@checkbox-group-update": "_checkboxGroupUpdateHandler" + }, + created() { + this.$dispatch("Form", "uni-form-group-update", { + type: "add", + vm: this + }); + }, + beforeDestroy() { + this.$dispatch("Form", "uni-form-group-update", { + type: "remove", + vm: this + }); + }, + methods: { + _changeHandler($event) { + const value = []; + this.checkboxList.forEach((vm) => { + if (vm.checkboxChecked) { + value.push(vm.value); } - removeEvent(win2, "resize", callback, true); - } - removeEvent(doc, "scroll", callback, true); - if (domObserver) { - domObserver.disconnect(); + }); + this.$trigger("change", $event, { + value + }); + }, + _checkboxGroupUpdateHandler($event) { + if ($event.type === "add") { + this.checkboxList.push($event.vm); + } else { + const index2 = this.checkboxList.indexOf($event.vm); + this.checkboxList.splice(index2, 1); } - }); - var rootDoc = this.root && (this.root.ownerDocument || this.root) || document2; - if (doc != rootDoc) { - var frame = getFrameElement(doc); - if (frame) { - this._monitorIntersections(frame.ownerDocument); + }, + _getFormData() { + const data = {}; + if (this.name !== "") { + const value = []; + this.checkboxList.forEach((vm) => { + if (vm.checkboxChecked) { + value.push(vm.value); + } + }); + data.value = value; + data.key = this.name; } + return data; } + } +}; +function _sfc_render$h(_ctx, _cache, $props, $setup, $data, $options) { + return openBlock(), createBlock("uni-checkbox-group", _ctx.$attrs, [ + renderSlot(_ctx.$slots, "default") + ], 16); +} +_sfc_main$h.render = _sfc_render$h; +var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/; +var endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/; +var attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; +var empty = /* @__PURE__ */ makeMap("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr"); +var block = /* @__PURE__ */ makeMap("a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video"); +var inline = /* @__PURE__ */ makeMap("abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var"); +var closeSelf = /* @__PURE__ */ makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr"); +var fillAttrs = /* @__PURE__ */ makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected"); +var special = /* @__PURE__ */ makeMap("script,style"); +function HTMLParser(html, handler) { + var index2; + var chars2; + var match; + var stack = []; + var last = html; + stack.last = function() { + return this[this.length - 1]; }; - IntersectionObserver2.prototype._unmonitorIntersections = function(doc) { - var index2 = this._monitoringDocuments.indexOf(doc); - if (index2 == -1) { - return; - } - var rootDoc = this.root && (this.root.ownerDocument || this.root) || document2; - var hasDependentTargets = this._observationTargets.some(function(item) { - var itemDoc = item.element.ownerDocument; - if (itemDoc == doc) { - return true; + while (html) { + chars2 = true; + if (!stack.last() || !special[stack.last()]) { + if (html.indexOf(""); + if (index2 >= 0) { + if (handler.comment) { + handler.comment(html.substring(4, index2)); + } + html = html.substring(index2 + 3); + chars2 = false; + } + } else if (html.indexOf("]*>"), function(all, text3) { + text3 = text3.replace(/|/g, "$1$2"); + if (handler.chars) { + handler.chars(text3); + } + return ""; + }); + parseEndTag("", stack.last()); + } + if (html == last) { + throw "Parse Error: " + html; } - var unsubscribe = this._monitoringUnsubscribes[index2]; - this._monitoringDocuments.splice(index2, 1); - this._monitoringUnsubscribes.splice(index2, 1); - unsubscribe(); - if (doc != rootDoc) { - var frame = getFrameElement(doc); - if (frame) { - this._unmonitorIntersections(frame.ownerDocument); + last = html; + } + parseEndTag(); + function parseStartTag(tag, tagName, rest, unary) { + tagName = tagName.toLowerCase(); + if (block[tagName]) { + while (stack.last() && inline[stack.last()]) { + parseEndTag("", stack.last()); } } - }; - IntersectionObserver2.prototype._unmonitorAllIntersections = function() { - var unsubscribes = this._monitoringUnsubscribes.slice(0); - this._monitoringDocuments.length = 0; - this._monitoringUnsubscribes.length = 0; - for (var i2 = 0; i2 < unsubscribes.length; i2++) { - unsubscribes[i2](); + if (closeSelf[tagName] && stack.last() == tagName) { + parseEndTag("", tagName); } - }; - IntersectionObserver2.prototype._checkForIntersections = function() { - if (!this.root && crossOriginUpdater && !crossOriginRect) { - return; + unary = empty[tagName] || !!unary; + if (!unary) { + stack.push(tagName); } - var rootIsInDom = this._rootIsInDom(); - var rootRect = rootIsInDom ? this._getRootRect() : getEmptyRect(); - this._observationTargets.forEach(function(item) { - var target = item.element; - var targetRect = getBoundingClientRect(target); - var rootContainsTarget = this._rootContainsTarget(target); - var oldEntry = item.entry; - var intersectionRect = rootIsInDom && rootContainsTarget && this._computeTargetAndRootIntersection(target, targetRect, rootRect); - var rootBounds = null; - if (!this._rootContainsTarget(target)) { - rootBounds = getEmptyRect(); - } else if (!crossOriginUpdater || this.root) { - rootBounds = rootRect; - } - var newEntry = item.entry = new IntersectionObserverEntry({ - time: now(), - target, - boundingClientRect: targetRect, - rootBounds, - intersectionRect + if (handler.start) { + var attrs2 = []; + rest.replace(attr, function(match2, name) { + var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : ""; + attrs2.push({ + name, + value, + escaped: value.replace(/(^|[^\\])"/g, '$1\\"') + }); }); - if (!oldEntry) { - this._queuedEntries.push(newEntry); - } else if (rootIsInDom && rootContainsTarget) { - if (this._hasCrossedThreshold(oldEntry, newEntry)) { - this._queuedEntries.push(newEntry); + if (handler.start) { + handler.start(tagName, attrs2, unary); + } + } + } + function parseEndTag(tag, tagName) { + if (!tagName) { + var pos = 0; + } else { + for (var pos = stack.length - 1; pos >= 0; pos--) { + if (stack[pos] == tagName) { + break; } - } else { - if (oldEntry && oldEntry.isIntersecting) { - this._queuedEntries.push(newEntry); + } + } + if (pos >= 0) { + for (var i2 = stack.length - 1; i2 >= pos; i2--) { + if (handler.end) { + handler.end(stack[i2]); } } - }, this); - if (this._queuedEntries.length) { - this._callback(this.takeRecords(), this); + stack.length = pos; } + } +} +function makeMap(str) { + var obj = {}; + var items = str.split(","); + for (var i2 = 0; i2 < items.length; i2++) { + obj[items[i2]] = true; + } + return obj; +} +function divider(Quill) { + const BlockEmbed = Quill.import("blots/block/embed"); + class Divider extends BlockEmbed { + } + Divider.blotName = "divider"; + Divider.tagName = "HR"; + return { + "formats/divider": Divider }; - IntersectionObserver2.prototype._computeTargetAndRootIntersection = function(target, targetRect, rootRect) { - if (window.getComputedStyle(target).display == "none") - return; - var intersectionRect = targetRect; - var parent = getParentNode(target); - var atRoot = false; - while (!atRoot && parent) { - var parentRect = null; - var parentComputedStyle = parent.nodeType == 1 ? window.getComputedStyle(parent) : {}; - if (parentComputedStyle.display == "none") - return null; - if (parent == this.root || parent.nodeType == 9) { - atRoot = true; - if (parent == this.root || parent == document2) { - if (crossOriginUpdater && !this.root) { - if (!crossOriginRect || crossOriginRect.width == 0 && crossOriginRect.height == 0) { - parent = null; - parentRect = null; - intersectionRect = null; - } else { - parentRect = crossOriginRect; - } - } else { - parentRect = rootRect; - } +} +function ins(Quill) { + const Inline = Quill.import("blots/inline"); + class Ins extends Inline { + } + Ins.blotName = "ins"; + Ins.tagName = "INS"; + return { + "formats/ins": Ins + }; +} +function align(Quill) { + const {Scope, Attributor} = Quill.import("parchment"); + const config = { + scope: Scope.BLOCK, + whitelist: ["left", "right", "center", "justify"] + }; + const AlignStyle = new Attributor.Style("align", "text-align", config); + return { + "formats/align": AlignStyle + }; +} +function direction(Quill) { + const {Scope, Attributor} = Quill.import("parchment"); + const config = { + scope: Scope.BLOCK, + whitelist: ["rtl"] + }; + const DirectionStyle = new Attributor.Style("direction", "direction", config); + return { + "formats/direction": DirectionStyle + }; +} +function list(Quill) { + const Parchment = Quill.import("parchment"); + const Container = Quill.import("blots/container"); + const ListItem = Quill.import("formats/list/item"); + class List extends Container { + static create(value) { + const tagName = value === "ordered" ? "OL" : "UL"; + const node = super.create(tagName); + if (value === "checked" || value === "unchecked") { + node.setAttribute("data-checked", value === "checked"); + } + return node; + } + static formats(domNode) { + if (domNode.tagName === "OL") + return "ordered"; + if (domNode.tagName === "UL") { + if (domNode.hasAttribute("data-checked")) { + return domNode.getAttribute("data-checked") === "true" ? "checked" : "unchecked"; } else { - var frame = getParentNode(parent); - var frameRect = frame && getBoundingClientRect(frame); - var frameIntersect = frame && this._computeTargetAndRootIntersection(frame, frameRect, rootRect); - if (frameRect && frameIntersect) { - parent = frame; - parentRect = convertFromParentRect(frameRect, frameIntersect); - } else { - parent = null; - intersectionRect = null; - } - } - } else { - var doc = parent.ownerDocument; - if (parent != doc.body && parent != doc.documentElement && parentComputedStyle.overflow != "visible") { - parentRect = getBoundingClientRect(parent); + return "bullet"; } } - if (parentRect) { - intersectionRect = computeRectIntersection(parentRect, intersectionRect); - } - if (!intersectionRect) - break; - parent = parent && getParentNode(parent); + return void 0; } - return intersectionRect; - }; - IntersectionObserver2.prototype._getRootRect = function() { - var rootRect; - if (this.root && !isDoc(this.root)) { - rootRect = getBoundingClientRect(this.root); - } else { - var doc = isDoc(this.root) ? this.root : document2; - var html = doc.documentElement; - var body = doc.body; - rootRect = { - top: 0, - left: 0, - right: html.clientWidth || body.clientWidth, - width: html.clientWidth || body.clientWidth, - bottom: html.clientHeight || body.clientHeight, - height: html.clientHeight || body.clientHeight + constructor(domNode) { + super(domNode); + const listEventHandler = (e2) => { + if (e2.target.parentNode !== domNode) + return; + const format = this.statics.formats(domNode); + const blot = Parchment.find(e2.target); + if (format === "checked") { + blot.format("list", "unchecked"); + } else if (format === "unchecked") { + blot.format("list", "checked"); + } }; + domNode.addEventListener("click", listEventHandler); + } + format(name, value) { + if (this.children.length > 0) { + this.children.tail.format(name, value); + } + } + formats() { + return {[this.statics.blotName]: this.statics.formats(this.domNode)}; + } + insertBefore(blot, ref2) { + if (blot instanceof ListItem) { + super.insertBefore(blot, ref2); + } else { + const index2 = ref2 == null ? this.length() : ref2.offset(this); + const after = this.split(index2); + after.parent.insertBefore(blot, after); + } } - return this._expandRectByRootMargin(rootRect); - }; - IntersectionObserver2.prototype._expandRectByRootMargin = function(rect) { - var margins = this._rootMarginValues.map(function(margin, i2) { - return margin.unit == "px" ? margin.value : margin.value * (i2 % 2 ? rect.width : rect.height) / 100; - }); - var newRect = { - top: rect.top - margins[0], - right: rect.right + margins[1], - bottom: rect.bottom + margins[2], - left: rect.left - margins[3] - }; - newRect.width = newRect.right - newRect.left; - newRect.height = newRect.bottom - newRect.top; - return newRect; - }; - IntersectionObserver2.prototype._hasCrossedThreshold = function(oldEntry, newEntry) { - var oldRatio = oldEntry && oldEntry.isIntersecting ? oldEntry.intersectionRatio || 0 : -1; - var newRatio = newEntry.isIntersecting ? newEntry.intersectionRatio || 0 : -1; - if (oldRatio === newRatio) - return; - for (var i2 = 0; i2 < this.thresholds.length; i2++) { - var threshold = this.thresholds[i2]; - if (threshold == oldRatio || threshold == newRatio || threshold < oldRatio !== threshold < newRatio) { - return true; + optimize(context) { + super.optimize(context); + const next = this.next; + if (next != null && next.prev === this && next.statics.blotName === this.statics.blotName && next.domNode.tagName === this.domNode.tagName && next.domNode.getAttribute("data-checked") === this.domNode.getAttribute("data-checked")) { + next.moveChildren(this); + next.remove(); + } + } + replace(target) { + if (target.statics.blotName !== this.statics.blotName) { + const item = Parchment.create(this.statics.defaultChild); + target.moveChildren(item); + this.appendChild(item); } + super.replace(target); } + } + List.blotName = "list"; + List.scope = Parchment.Scope.BLOCK_BLOT; + List.tagName = ["OL", "UL"]; + List.defaultChild = "list-item"; + List.allowedChildren = [ListItem]; + return { + "formats/list": List }; - IntersectionObserver2.prototype._rootIsInDom = function() { - return !this.root || containsDeep(document2, this.root); +} +function background(Quill) { + const {Scope} = Quill.import("parchment"); + const BackgroundStyle = Quill.import("formats/background"); + const BackgroundColorStyle = new BackgroundStyle.constructor("backgroundColor", "background-color", { + scope: Scope.INLINE + }); + return { + "formats/backgroundColor": BackgroundColorStyle }; - IntersectionObserver2.prototype._rootContainsTarget = function(target) { - var rootDoc = this.root && (this.root.ownerDocument || this.root) || document2; - return containsDeep(rootDoc, target) && (!this.root || rootDoc == target.ownerDocument); +} +function box(Quill) { + const {Scope, Attributor} = Quill.import("parchment"); + const config = { + scope: Scope.BLOCK }; - IntersectionObserver2.prototype._registerInstance = function() { - if (registry.indexOf(this) < 0) { - registry.push(this); - } + const margin = [ + "margin", + "marginTop", + "marginBottom", + "marginLeft", + "marginRight" + ]; + const padding = [ + "padding", + "paddingTop", + "paddingBottom", + "paddingLeft", + "paddingRight" + ]; + const result = {}; + margin.concat(padding).forEach((name) => { + result[`formats/${name}`] = new Attributor.Style(name, hyphenate(name), config); + }); + return result; +} +function font(Quill) { + const {Scope, Attributor} = Quill.import("parchment"); + const config = { + scope: Scope.INLINE }; - IntersectionObserver2.prototype._unregisterInstance = function() { - var index2 = registry.indexOf(this); - if (index2 != -1) - registry.splice(index2, 1); + const font2 = [ + "font", + "fontSize", + "fontStyle", + "fontVariant", + "fontWeight", + "fontFamily" + ]; + const result = {}; + font2.forEach((name) => { + result[`formats/${name}`] = new Attributor.Style(name, hyphenate(name), config); + }); + return result; +} +function text(Quill) { + const {Scope, Attributor} = Quill.import("parchment"); + const text2 = [ + { + name: "lineHeight", + scope: Scope.BLOCK + }, + { + name: "letterSpacing", + scope: Scope.INLINE + }, + { + name: "textDecoration", + scope: Scope.INLINE + }, + { + name: "textIndent", + scope: Scope.BLOCK + } + ]; + const result = {}; + text2.forEach(({name, scope}) => { + result[`formats/${name}`] = new Attributor.Style(name, hyphenate(name), { + scope + }); + }); + return result; +} +function image(Quill) { + const Image2 = Quill.import("formats/image"); + const ATTRIBUTES = [ + "alt", + "height", + "width", + "data-custom", + "class", + "data-local" + ]; + Image2.sanitize = (url) => url; + Image2.formats = function formats(domNode) { + return ATTRIBUTES.reduce(function(formats2, attribute) { + if (domNode.hasAttribute(attribute)) { + formats2[attribute] = domNode.getAttribute(attribute); + } + return formats2; + }, {}); }; - function now() { - return window.performance && performance.now && performance.now(); - } - function throttle2(fn, timeout) { - var timer = null; - return function() { - if (!timer) { - timer = setTimeout(function() { - fn(); - timer = null; - }, timeout); + const format = Image2.prototype.format; + Image2.prototype.format = function(name, value) { + if (ATTRIBUTES.indexOf(name) > -1) { + if (value) { + this.domNode.setAttribute(name, value); + } else { + this.domNode.removeAttribute(name); } - }; - } - function addEvent(node, event2, fn, opt_useCapture) { - if (typeof node.addEventListener == "function") { - node.addEventListener(event2, fn, opt_useCapture || false); - } else if (typeof node.attachEvent == "function") { - node.attachEvent("on" + event2, fn); - } - } - function removeEvent(node, event2, fn, opt_useCapture) { - if (typeof node.removeEventListener == "function") { - node.removeEventListener(event2, fn, opt_useCapture || false); - } else if (typeof node.detatchEvent == "function") { - node.detatchEvent("on" + event2, fn); - } - } - function computeRectIntersection(rect1, rect2) { - var top = Math.max(rect1.top, rect2.top); - var bottom = Math.min(rect1.bottom, rect2.bottom); - var left = Math.max(rect1.left, rect2.left); - var right = Math.min(rect1.right, rect2.right); - var width = right - left; - var height = bottom - top; - return width >= 0 && height >= 0 && { - top, - bottom, - left, - right, - width, - height - } || null; - } - function getBoundingClientRect(el) { - var rect; - try { - rect = el.getBoundingClientRect(); - } catch (err) { + } else { + format.call(this, name, value); } - if (!rect) - return getEmptyRect(); - if (!(rect.width && rect.height)) { - rect = { - top: rect.top, - right: rect.right, - bottom: rect.bottom, - left: rect.left, - width: rect.right - rect.left, - height: rect.bottom - rect.top - }; + }; +} +function register(Quill) { + const formats = { + divider, + ins, + align, + direction, + list, + background, + box, + font, + text, + image + }; + const options = {}; + Object.values(formats).forEach((value) => Object.assign(options, value(Quill))); + Quill.register(options, true); +} +const _sfc_main$g = { + name: "Editor", + mixins: [subscriber, emitter, keyboard], + props: { + id: { + type: String, + default: "" + }, + readOnly: { + type: [Boolean, String], + default: false + }, + placeholder: { + type: String, + default: "" + }, + showImgSize: { + type: [Boolean, String], + default: false + }, + showImgToolbar: { + type: [Boolean, String], + default: false + }, + showImgResize: { + type: [Boolean, String], + default: false } - return rect; - } - function getEmptyRect() { + }, + data() { return { - top: 0, - bottom: 0, - left: 0, - right: 0, - width: 0, - height: 0 + quillReady: false }; - } - function ensureDOMRect(rect) { - if (!rect || "x" in rect) { - return rect; + }, + computed: {}, + watch: { + readOnly(value) { + if (this.quillReady) { + const quill = this.quill; + quill.enable(!value); + if (!value) { + quill.blur(); + } + } + }, + placeholder(value) { + if (this.quillReady) { + this.quill.root.setAttribute("data-placeholder", value); + } } - return { - top: rect.top, - y: rect.top, - bottom: rect.bottom, - left: rect.left, - x: rect.left, - right: rect.right, - width: rect.width, - height: rect.height - }; - } - function convertFromParentRect(parentBoundingRect, parentIntersectionRect) { - var top = parentIntersectionRect.top - parentBoundingRect.top; - var left = parentIntersectionRect.left - parentBoundingRect.left; - return { - top, - left, - height: parentIntersectionRect.height, - width: parentIntersectionRect.width, - bottom: top + parentIntersectionRect.height, - right: left + parentIntersectionRect.width - }; - } - function containsDeep(parent, child) { - var node = child; - while (node) { - if (node == parent) - return true; - node = getParentNode(node); + }, + mounted() { + const imageResizeModules = []; + if (this.showImgSize) { + imageResizeModules.push("DisplaySize"); } - return false; - } - function getParentNode(node) { - var parent = node.parentNode; - if (node.nodeType == 9 && node != document2) { - return getFrameElement(node); + if (this.showImgToolbar) { + imageResizeModules.push("Toolbar"); } - if (parent && parent.assignedSlot) { - parent = parent.assignedSlot.parentNode; + if (this.showImgResize) { + imageResizeModules.push("Resize"); } - if (parent && parent.nodeType == 11 && parent.host) { - return parent.host; + this.loadQuill(() => { + if (imageResizeModules.length) { + this.loadImageResizeModule(() => { + this.initQuill(imageResizeModules); + }); + } else { + this.initQuill(imageResizeModules); + } + }); + }, + methods: { + _handleSubscribe({ + type, + data + }) { + const {options, callbackId} = data; + const quill = this.quill; + const Quill = window.Quill; + let res; + let range; + let errMsg; + if (this.quillReady) { + switch (type) { + case "format": + { + let {name = "", value = false} = options; + range = quill.getSelection(true); + let format = quill.getFormat(range)[name] || false; + if (["bold", "italic", "underline", "strike", "ins"].includes(name)) { + value = !format; + } else if (name === "direction") { + value = value === "rtl" && format ? false : value; + const align2 = quill.getFormat(range).align; + if (value === "rtl" && !align2) { + quill.format("align", "right", Quill.sources.USER); + } else if (!value && align2 === "right") { + quill.format("align", false, Quill.sources.USER); + } + } else if (name === "indent") { + const rtl = quill.getFormat(range).direction === "rtl"; + value = value === "+1"; + if (rtl) { + value = !value; + } + value = value ? "+1" : "-1"; + } else { + if (name === "list") { + value = value === "check" ? "unchecked" : value; + format = format === "checked" ? "unchecked" : format; + } + value = format && format !== (value || false) || !format && value ? value : !format; + } + quill.format(name, value, Quill.sources.USER); + } + break; + case "insertDivider": + range = quill.getSelection(true); + quill.insertText(range.index, "\n", Quill.sources.USER); + quill.insertEmbed(range.index + 1, "divider", true, Quill.sources.USER); + quill.setSelection(range.index + 2, Quill.sources.SILENT); + break; + case "insertImage": + { + range = quill.getSelection(true); + const {src = "", alt = "", width = "", height = "", extClass = "", data: data2 = {}} = options; + const path = this.$getRealPath(src); + quill.insertEmbed(range.index, "image", path, Quill.sources.USER); + const local = /^(file|blob):/.test(path) ? path : false; + quill.formatText(range.index, 1, "data-local", local); + quill.formatText(range.index, 1, "alt", alt); + quill.formatText(range.index, 1, "width", width); + quill.formatText(range.index, 1, "height", height); + quill.formatText(range.index, 1, "class", extClass); + quill.formatText(range.index, 1, "data-custom", Object.keys(data2).map((key) => `${key}=${data2[key]}`).join("&")); + quill.setSelection(range.index + 1, Quill.sources.SILENT); + } + break; + case "insertText": + { + range = quill.getSelection(true); + const {text: text2 = ""} = options; + quill.insertText(range.index, text2, Quill.sources.USER); + quill.setSelection(range.index + text2.length, 0, Quill.sources.SILENT); + } + break; + case "setContents": + { + const {delta, html} = options; + if (typeof delta === "object") { + quill.setContents(delta, Quill.sources.SILENT); + } else if (typeof html === "string") { + quill.setContents(this.html2delta(html), Quill.sources.SILENT); + } else { + errMsg = "contents is missing"; + } + } + break; + case "getContents": + res = this.getContents(); + break; + case "clear": + quill.setContents([]); + break; + case "removeFormat": + { + range = quill.getSelection(true); + const parchment = Quill.import("parchment"); + if (range.length) { + quill.removeFormat(range, Quill.sources.USER); + } else { + Object.keys(quill.getFormat(range)).forEach((key) => { + if (parchment.query(key, parchment.Scope.INLINE)) { + quill.format(key, false); + } + }); + } + } + break; + case "undo": + quill.history.undo(); + break; + case "redo": + quill.history.redo(); + break; + } + this.updateStatus(range); + } else { + errMsg = "not ready"; + } + if (callbackId) { + UniViewJSBridge.publishHandler("onEditorMethodCallback", { + callbackId, + data: Object.assign({}, res, { + errMsg: `${type}:${errMsg ? "fail " + errMsg : "ok"}` + }) + }, this.$page.id); + } + }, + loadQuill(callback) { + if (typeof window.Quill === "function") { + if (typeof callback === "function") { + callback(); + } + return; + } + const script = document.createElement("script"); + script.src = window.plus ? "./__uniappquill.js" : "https://unpkg.com/quill@1.3.7/dist/quill.min.js"; + document.body.appendChild(script); + script.onload = callback; + }, + loadImageResizeModule(callback) { + if (typeof window.ImageResize === "function") { + if (typeof callback === "function") { + callback(); + } + return; + } + const script = document.createElement("script"); + script.src = window.plus ? "./__uniappquillimageresize.js" : "https://unpkg.com/quill-image-resize-mp@3.0.1/image-resize.min.js"; + document.body.appendChild(script); + script.onload = callback; + }, + initQuill(imageResizeModules) { + const Quill = window.Quill; + register(Quill); + const options = { + toolbar: false, + readOnly: this.readOnly, + placeholder: this.placeholder, + modules: {} + }; + if (imageResizeModules.length) { + Quill.register("modules/ImageResize", window.ImageResize.default); + options.modules.ImageResize = { + modules: imageResizeModules + }; + } + const quill = this.quill = new Quill(this.$el, options); + const $el = quill.root; + const events = ["focus", "blur", "input"]; + events.forEach((name) => { + $el.addEventListener(name, ($event) => { + if (name === "input") { + $event.stopPropagation(); + } else { + this.$trigger(name, $event, this.getContents()); + } + }); + }); + quill.on(Quill.events.TEXT_CHANGE, () => { + this.$trigger("input", {}, this.getContents()); + }); + quill.on(Quill.events.SELECTION_CHANGE, this.updateStatus.bind(this)); + quill.on(Quill.events.SCROLL_OPTIMIZE, () => { + const range = quill.selection.getRange()[0]; + this.updateStatus(range); + }); + quill.clipboard.addMatcher(Node.ELEMENT_NODE, (node, delta) => { + if (this.skipMatcher) { + return delta; + } + delta.ops = delta.ops.filter(({insert}) => typeof insert === "string").map(({insert}) => ({insert})); + return delta; + }); + this.initKeyboard($el); + this.quillReady = true; + this.$trigger("ready", event, {}); + }, + getContents() { + const quill = this.quill; + const html = quill.root.innerHTML; + const text2 = quill.getText(); + const delta = quill.getContents(); + return { + html, + text: text2, + delta + }; + }, + html2delta(html) { + const tags = ["span", "strong", "b", "ins", "em", "i", "u", "a", "del", "s", "sub", "sup", "img", "div", "p", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "ol", "ul", "li", "br"]; + let content = ""; + let disable; + HTMLParser(html, { + start: function(tag, attrs2, unary) { + if (!tags.includes(tag)) { + disable = !unary; + return; + } + disable = false; + const arrts = attrs2.map(({name, value}) => `${name}="${value}"`).join(" "); + const start = `<${tag} ${arrts} ${unary ? "/" : ""}>`; + content += start; + }, + end: function(tag) { + if (!disable) { + content += ``; + } + }, + chars: function(text2) { + if (!disable) { + content += text2; + } + } + }); + this.skipMatcher = true; + const delta = this.quill.clipboard.convert(content); + this.skipMatcher = false; + return delta; + }, + updateStatus(range) { + const status = range ? this.quill.getFormat(range) : {}; + const keys = Object.keys(status); + if (keys.length !== Object.keys(this.__status || {}).length || keys.find((key) => status[key] !== this.__status[key])) { + this.__status = status; + this.$trigger("statuschange", {}, status); + } } - return parent; - } - function isDoc(node) { - return node && node.nodeType === 9; } - window.IntersectionObserver = IntersectionObserver2; - window.IntersectionObserverEntry = IntersectionObserverEntry; }; -function normalizeRect(rect) { - const {bottom, height, left, right, top, width} = rect || {}; - return { - bottom, - height, - left, - right, - top, - width - }; +function _sfc_render$g(_ctx, _cache, $props, $setup, $data, $options) { + return openBlock(), createBlock("uni-editor", mergeProps({ + id: $props.id, + class: "ql-container" + }, _ctx.$attrs), null, 16, ["id"]); } -function requestComponentObserver($el, options, callback) { - initIntersectionObserverPolyfill(); - const root = options.relativeToSelector ? $el.querySelector(options.relativeToSelector) : null; - const intersectionObserver = new IntersectionObserver((entries) => { - entries.forEach((entrie) => { - callback({ - intersectionRatio: entrie.intersectionRatio, - intersectionRect: normalizeRect(entrie.intersectionRect), - boundingClientRect: normalizeRect(entrie.boundingClientRect), - relativeRect: normalizeRect(entrie.rootBounds), - time: Date.now() - }); - }); - }, { - root, - rootMargin: options.rootMargin, - threshold: options.thresholds - }); - if (options.observeAll) { - intersectionObserver.USE_MUTATION_OBSERVER = true; - const nodeList = $el.querySelectorAll(options.selector); - for (let i2 = 0; i2 < nodeList.length; i2++) { - intersectionObserver.observe(nodeList[i2]); - } - } else { - intersectionObserver.USE_MUTATION_OBSERVER = false; - const el = $el.querySelector(options.selector); - if (!el) { - console.warn(`Node ${options.selector} is not found. Intersection observer will not trigger.`); - } else { - intersectionObserver.observe(el); - } +_sfc_main$g.render = _sfc_render$g; +const INFO_COLOR = "#10aeff"; +const WARN_COLOR = "#f76260"; +const GREY_COLOR = "#b2b2b2"; +const CANCEL_COLOR = "#f43530"; +const ICONS = { + success: { + d: ICON_PATH_SUCCESS, + c: PRIMARY_COLOR$1 + }, + success_no_circle: { + d: ICON_PATH_SUCCESS_NO_CIRCLE, + c: PRIMARY_COLOR$1 + }, + info: { + d: ICON_PATH_INFO, + c: INFO_COLOR + }, + warn: { + d: ICON_PATH_WARN, + c: WARN_COLOR + }, + waiting: { + d: ICON_PATH_WAITING, + c: INFO_COLOR + }, + cancel: { + d: ICON_PATH_CANCEL, + c: CANCEL_COLOR + }, + download: { + d: ICON_PATH_DOWNLOAD, + c: PRIMARY_COLOR$1 + }, + search: { + d: ICON_PATH_SEARCH, + c: GREY_COLOR + }, + clear: { + d: ICON_PATH_CLEAR, + c: GREY_COLOR } - return intersectionObserver; -} -function addIntersectionObserver({reqId, component, options, callback}, _pageId) { - const $el = findElem(component); - ($el.__io || ($el.__io = {}))[reqId] = requestComponentObserver($el, options, callback); -} -function removeIntersectionObserver({reqId, component}, _pageId) { - const $el = findElem(component); - const intersectionObserver = $el.__io && $el.__io[reqId]; - if (intersectionObserver) { - intersectionObserver.disconnect(); - delete $el.__io[reqId]; +}; +var index$5 = /* @__PURE__ */ defineComponent({ + name: "Icon", + props: { + type: { + type: String, + required: true, + default: "" + }, + size: { + type: [String, Number], + default: 23 + }, + color: { + type: String, + default: "" + } + }, + setup(props2) { + const path = computed(() => ICONS[props2.type]); + return () => createVNode("uni-icon", null, [path.value.d && createSvgIconVNode(path.value.d, props2.color || path.value.c, rpx2px(props2.size))]); } -} +}); function useCustomEvent(ref2, emit) { return (name, evt, detail) => { emit(name, normalizeCustomEvent(name, evt, ref2.value, detail || {})); @@ -5985,9 +6075,9 @@ function useImageState(rootRef, props2) { }); onMounted(() => { const rootEl = rootRef.value; - const style = rootEl.style; - state.origWidth = Number(style.width) || 0; - state.origHeight = Number(style.height) || 0; + const style2 = rootEl.style; + state.origWidth = Number(style2.width) || 0; + state.origHeight = Number(style2.height) || 0; }); return state; } @@ -6076,7 +6166,7 @@ function useImageSize(rootRef, props2, state) { }; const resetSize = () => { const { - style + style: style2 } = rootRef.value; const { origStyle: { @@ -6084,8 +6174,8 @@ function useImageSize(rootRef, props2, state) { height } } = state; - style.width = width; - style.height = height; + style2.width = width; + style2.height = height; }; watch(() => props2.mode, (value, oldValue) => { if (FIX_MODES[oldValue]) { @@ -10252,12 +10342,12 @@ const _sfc_main$3 = { const p2 = document.createElement("p"); p2.className = "uni-video-danmu-item"; p2.innerText = danmu.text; - let style = `bottom: ${Math.random() * 100}%;color: ${danmu.color};`; - p2.setAttribute("style", style); + let style2 = `bottom: ${Math.random() * 100}%;color: ${danmu.color};`; + p2.setAttribute("style", style2); this.$refs.danmu.appendChild(p2); setTimeout(function() { - style += "left: 0;-webkit-transform: translateX(-100%);transform: translateX(-100%);"; - p2.setAttribute("style", style); + style2 += "left: 0;-webkit-transform: translateX(-100%);transform: translateX(-100%);"; + p2.setAttribute("style", style2); setTimeout(function() { p2.remove(); }, 4e3); @@ -10686,26 +10776,6 @@ const UniViewJSBridge$1 = /* @__PURE__ */ extend(ViewJSBridge, { window.UniServiceJSBridge.subscribeHandler(event2, args, pageId); } }); -const supports = window.CSS && window.CSS.supports; -function cssSupports(css) { - return supports && (supports(css) || supports.apply(window.CSS, css.split(":"))); -} -const cssVar = /* @__PURE__ */ cssSupports("--a:0"); -const cssEnv = /* @__PURE__ */ cssSupports("top:env(a)"); -const cssConstant = /* @__PURE__ */ cssSupports("top:constant(a)"); -const cssBackdropFilter = /* @__PURE__ */ cssSupports("backdrop-filter:blur(10px)"); -const SCHEMA_CSS = { - "css.var": cssVar, - "css.env": cssEnv, - "css.constant": cssConstant, - "css.backdrop-filter": cssBackdropFilter -}; -const canIUse = defineSyncApi(API_CAN_I_USE, (schema) => { - if (hasOwn$1(SCHEMA_CSS, schema)) { - return SCHEMA_CSS[schema]; - } - return true; -}, CanIUseProtocol); const innerAudioContextEventNames = [ "onCanplay", "onPlay", @@ -12403,13 +12473,6 @@ const stopPullDownRefresh = defineAsyncApi(API_STOP_PULL_DOWN_REFRESH, (_args, { UniServiceJSBridge.publishHandler(API_STOP_PULL_DOWN_REFRESH, {}, getCurrentPageId()); resolve(); }); -let tabBar; -function useTabBar() { - if (!tabBar) { - tabBar = __uniConfig.tabBar && reactive(__uniConfig.tabBar); - } - return tabBar; -} const setTabBarItemProps = ["text", "iconPath", "selectedIconPath"]; const setTabBarStyleProps = [ "color", @@ -12609,9 +12672,10 @@ var TabBar = /* @__PURE__ */ defineComponent({ name: "TabBar", setup() { const tabBar2 = useTabBar(); + useTabBarCssVar(tabBar2); const onSwitchTab = useSwitchTab(useRoute(), tabBar2); const { - style, + style: style2, borderStyle, placeholderStyle } = useTabBarStyle(tabBar2); @@ -12621,7 +12685,7 @@ var TabBar = /* @__PURE__ */ defineComponent({ class: "uni-tabbar-" + tabBar2.position }, [createVNode("div", { class: "uni-tabbar", - style: style.value + style: style2.value }, [createVNode("div", { class: "uni-tabbar-border", style: borderStyle.value @@ -12632,6 +12696,13 @@ var TabBar = /* @__PURE__ */ defineComponent({ }; } }); +function useTabBarCssVar(tabBar2) { + watch(() => tabBar2.shown, (value) => { + updatePageCssVar({ + "--window-bottom": normalizeWindowBottom(value ? parseInt(tabBar2.height) : 0) + }); + }); +} function useSwitchTab(route, tabBar2) { watchEffect(() => { const meta = route.meta; @@ -12688,7 +12759,7 @@ const BORDER_COLORS = { black: "rgba(0, 0, 0, 0.33)" }; function useTabBarStyle(tabBar2) { - const style = computed(() => { + const style2 = computed(() => { let backgroundColor = tabBar2.backgroundColor; const blurEffect = tabBar2.blurEffect; if (!backgroundColor) { @@ -12715,7 +12786,7 @@ function useTabBarStyle(tabBar2) { }; }); return { - style, + style: style2, borderStyle, placeholderStyle }; @@ -12768,13 +12839,13 @@ function createTabBarItemIconTsx(iconPath, tabBarItem, tabBar2) { iconWidth } = tabBar2; const clazz = "uni-tabbar__icon" + (text2 ? " uni-tabbar__icon__diff" : ""); - const style = { + const style2 = { width: iconWidth, height: iconWidth }; return createVNode("div", { class: clazz, - style + style: style2 }, [type !== "midButton" && createVNode("img", { src: getRealPath(iconPath) }, null, 8, ["src"]), redDot && createTabBarItemRedDotTsx(tabBarItem.badge)], 6); @@ -12789,7 +12860,7 @@ function createTabBarItemTextTsx(color, tabBarItem, tabBar2) { fontSize, spacing } = tabBar2; - const style = { + const style2 = { color, fontSize, lineHeight: !iconPath ? 1.8 : "normal", @@ -12797,7 +12868,7 @@ function createTabBarItemTextTsx(color, tabBarItem, tabBar2) { }; return createVNode("div", { class: "uni-tabbar__label", - style + style: style2 }, [text2, redDot && !iconPath && createTabBarItemRedDotTsx(tabBarItem.badge)], 4); } function createTabBarItemRedDotTsx(badge) { @@ -13049,7 +13120,7 @@ var PageHead = /* @__PURE__ */ defineComponent({ const navigationBar = pageMeta.navigationBar; const { clazz, - style + style: style2 } = usePageHead(navigationBar); const buttons = __UNI_FEATURE_NAVIGATIONBAR_BUTTONS__ && usePageHeadButtons(navigationBar); const searchInput = __UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__ && navigationBar.searchInput && usePageHeadSearchInput(pageMeta); @@ -13070,7 +13141,7 @@ var PageHead = /* @__PURE__ */ defineComponent({ }, [createVNode("div", { ref: headRef, class: clazz.value, - style: style.value + style: style2.value }, [createVNode("div", { class: "uni-page-head-hd" }, [backButtonTsx, ...leftButtonsTsx]), createPageHeadBdTsx(navigationBar, searchInput), createVNode("div", { @@ -13226,7 +13297,7 @@ function usePageHead(navigationBar) { } return clazz2; }); - const style = computed(() => { + const style2 = computed(() => { const backgroundColor = __UNI_FEATURE_NAVIGATIONBAR_TRANSPARENT__ && navigationBar.type === "transparent" ? usePageHeadTransparentBackgroundColor(navigationBar.backgroundColor) : navigationBar.backgroundColor; return { backgroundColor, @@ -13237,7 +13308,7 @@ function usePageHead(navigationBar) { }); return { clazz, - style + style: style2 }; } function usePageHeadButtons(navigationBar) { diff --git a/packages/uni-h5/src/framework/components/layout/tabBar.tsx b/packages/uni-h5/src/framework/components/layout/tabBar.tsx index e78067c8865eda1ac8409854c5067bc043dbb95f..f90d1998d84a969d2e3601e7a2186de9fe8e8283 100644 --- a/packages/uni-h5/src/framework/components/layout/tabBar.tsx +++ b/packages/uni-h5/src/framework/components/layout/tabBar.tsx @@ -1,6 +1,6 @@ -import { watchEffect, computed, defineComponent } from 'vue' +import { watch, watchEffect, computed, defineComponent } from 'vue' import { RouteLocationNormalizedLoaded, useRoute } from 'vue-router' -import { invokeHook } from '@dcloudio/uni-core' +import { invokeHook, updatePageCssVar } from '@dcloudio/uni-core' import { API_ON_TAB_BAR_MID_BUTTON_TAP, OnTabBarMidButtonTap, @@ -8,11 +8,13 @@ import { import { getRealPath } from '../../../platform' import { useTabBar } from '../../plugin/state' import { cssBackdropFilter } from '../../../service/api/base/canIUse' +import { normalizeWindowBottom } from '../../../helpers/cssVar' export default /*#__PURE__*/ defineComponent({ name: 'TabBar', setup() { const tabBar = useTabBar()! + useTabBarCssVar(tabBar) const onSwitchTab = useSwitchTab(useRoute(), tabBar) const { style, borderStyle, placeholderStyle } = useTabBarStyle(tabBar) return () => { @@ -30,6 +32,19 @@ export default /*#__PURE__*/ defineComponent({ }, }) +function useTabBarCssVar(tabBar: UniApp.TabBarOptions) { + watch( + () => tabBar.shown, + (value) => { + updatePageCssVar({ + '--window-bottom': normalizeWindowBottom( + value ? parseInt(tabBar.height!) : 0 + ), + }) + } + ) +} + function useSwitchTab( route: RouteLocationNormalizedLoaded, tabBar: UniApp.TabBarOptions diff --git a/packages/uni-h5/src/framework/components/page/pageHead.tsx b/packages/uni-h5/src/framework/components/page/pageHead.tsx index 36c5aad80e712e3274111670c44beadd7059570b..2ff6c0d4e2c9a5cdc9ab7f487e54bf551c4ef3cb 100644 --- a/packages/uni-h5/src/framework/components/page/pageHead.tsx +++ b/packages/uni-h5/src/framework/components/page/pageHead.tsx @@ -1,4 +1,4 @@ -import { computed, defineComponent, Ref, ref } from 'vue' +import { computed, defineComponent, ref } from 'vue' import { isArray } from '@vue/shared' import { Input } from '@dcloudio/uni-components' import { getRealPath } from '@dcloudio/uni-platform' diff --git a/packages/uni-h5/src/framework/plugin/setup.ts b/packages/uni-h5/src/framework/plugin/setup.ts index 2fedbe7a240228ca6f298f9e8e64e67edf3f63bd..0c51969aee85b874d19a61775a33b8fb7790e801 100644 --- a/packages/uni-h5/src/framework/plugin/setup.ts +++ b/packages/uni-h5/src/framework/plugin/setup.ts @@ -1,4 +1,4 @@ -import { extend, invokeArrayFns } from '@vue/shared' +import { invokeArrayFns } from '@vue/shared' import { ComponentInternalInstance, ComponentPublicInstance, @@ -11,11 +11,13 @@ import { onBeforeDeactivate, onBeforeMount, } from 'vue' -import { useRoute } from 'vue-router' +import { useRoute, useRouter } from 'vue-router' import { parseQuery, decodedQuery } from '@dcloudio/uni-shared' import { LayoutComponent } from '../..' import { initApp } from './app' import { initPage } from './page' +import { usePageMeta } from './provide' +import { updateCurPageCssVar } from '../../helpers/cssVar' interface SetupComponentOptions { init: (vm: ComponentPublicInstance) => void @@ -36,9 +38,11 @@ export function usePageRoute() { url.slice(searchPos + 1, hashPos > -1 ? hashPos : url.length) ) } + const { meta } = __uniRoutes[0] return { - meta: __uniRoutes[0].meta, + meta, query: query, + path: '/' + meta.route, } } @@ -67,6 +71,10 @@ function setupComponent(comp: any, options: SetupComponentOptions) { return comp } +function onPageShow(pageMeta: UniApp.PageRouteMeta) { + updateCurPageCssVar(pageMeta) +} + export function setupPage(comp: any) { return setupComponent(comp, { init: initPage, @@ -77,8 +85,10 @@ export function setupPage(comp: any) { //初始化时,状态肯定是激活 instance.__isActive = true } + const pageMeta = usePageMeta() onBeforeMount(() => { const { onLoad, onShow } = instance + onPageShow(pageMeta) onLoad && invokeArrayFns(onLoad, decodedQuery(route.query)) instance.__isVisible = true onShow && invokeArrayFns(onShow) @@ -89,6 +99,7 @@ export function setupPage(comp: any) { }) onBeforeActivate(() => { if (!instance.__isVisible) { + onPageShow(pageMeta) instance.__isVisible = true const { onShow } = instance onShow && invokeArrayFns(onShow) @@ -111,16 +122,23 @@ export function setupApp(comp: any) { init: initApp, setup(instance) { const route = usePageRoute() - onBeforeMount(() => { + const onLaunch = () => { const { onLaunch, onShow } = instance - onLaunch && - invokeArrayFns(onLaunch, { - path: route.meta.route, - query: decodedQuery(route.query), - scene: 1001, - }) - onShow && invokeArrayFns(onShow) - }) + const path = route.path.substr(1) + const launchOptions = { + path: path || __uniRoutes[0].meta.route, + query: decodedQuery(route.query), + scene: 1001, + } + onLaunch && invokeArrayFns(onLaunch, launchOptions) + onShow && invokeArrayFns(onShow, launchOptions) + } + if (__UNI_FEATURE_PAGES__) { + // 等待ready后,再onLaunch,可以顺利获取到正确的path和query + useRouter().isReady().then(onLaunch) + } else { + onBeforeMount(onLaunch) + } onMounted(() => { document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'visible') { diff --git a/packages/uni-h5/src/helpers/cssVar.ts b/packages/uni-h5/src/helpers/cssVar.ts new file mode 100644 index 0000000000000000000000000000000000000000..c7dc284773fd7a6b269bc9293e9426a3af5674a1 --- /dev/null +++ b/packages/uni-h5/src/helpers/cssVar.ts @@ -0,0 +1,38 @@ +import { NAVBAR_HEIGHT } from '@dcloudio/uni-shared' +import { updatePageCssVar } from '@dcloudio/uni-core' +import { useTabBar } from '../framework/plugin/state' +import { cssEnv, cssConstant } from '../service/api/base/canIUse' + +const envMethod = /*#__PURE__*/ (() => + cssEnv ? 'env' : cssConstant ? 'constant' : '')() + +export function updateCurPageCssVar(pageMeta: UniApp.PageRouteMeta) { + let windowTopValue = 0 + let windowBottomValue = 0 + if ( + __UNI_FEATURE_NAVIGATIONBAR__ && + ['default', 'float'].indexOf(pageMeta.navigationBar.type!) > -1 + ) { + windowTopValue = NAVBAR_HEIGHT + } + if (__UNI_FEATURE_TABBAR__ && pageMeta.isTabBar) { + const tabBar = useTabBar()! + tabBar.shown && (windowBottomValue = parseInt(tabBar.height!)) + } + updatePageCssVar({ + '--window-top': normalizeWindowBottom(windowTopValue), + '--window-bottom': normalizeWindowBottom(windowBottomValue), + }) +} + +export function normalizeWindowTop(windowTop: number) { + return envMethod + ? `calc(${windowTop}px + ${envMethod}(safe-area-inset-top))` + : `${windowTop}px` +} + +export function normalizeWindowBottom(windowBottom: number) { + return envMethod + ? `calc(${windowBottom}px + ${envMethod}(safe-area-inset-bottom))` + : `${windowBottom}px` +}